diff --git a/README.md b/README.md index aa9a016bb352eb3a0f93152bf57c8d2af4b8588d..e295b4da2902ba866f37493bc9ad595af2217a7f 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,10 @@ sdk: static pinned: false models: - Xenova/nllb-200-distilled-600M +custom_headers: + cross-origin-embedder-policy: require-corp + cross-origin-opener-policy: same-origin + cross-origin-resource-policy: cross-origin --- A simple React application that performs multilingual translation using Transformers.js! diff --git a/assets/index-138f5db2.js b/assets/index-138f5db2.js deleted file mode 100644 index 5eee70594bb46ea8a00d0fdeb482af31f9c1d6dd..0000000000000000000000000000000000000000 --- a/assets/index-138f5db2.js +++ /dev/null @@ -1,40 +0,0 @@ -(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const i of l)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function t(l){const i={};return l.integrity&&(i.integrity=l.integrity),l.referrerPolicy&&(i.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?i.credentials="include":l.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(l){if(l.ep)return;l.ep=!0;const i=t(l);fetch(l.href,i)}})();function lc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Wu={exports:{}},el={},Qu={exports:{}},T={};/** - * @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 Yt=Symbol.for("react.element"),ic=Symbol.for("react.portal"),oc=Symbol.for("react.fragment"),uc=Symbol.for("react.strict_mode"),ac=Symbol.for("react.profiler"),sc=Symbol.for("react.provider"),cc=Symbol.for("react.context"),fc=Symbol.for("react.forward_ref"),dc=Symbol.for("react.suspense"),pc=Symbol.for("react.memo"),mc=Symbol.for("react.lazy"),Oo=Symbol.iterator;function hc(e){return e===null||typeof e!="object"?null:(e=Oo&&e[Oo]||e["@@iterator"],typeof e=="function"?e:null)}var Ku={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Gu=Object.assign,Yu={};function it(e,n,t){this.props=e,this.context=n,this.refs=Yu,this.updater=t||Ku}it.prototype.isReactComponent={};it.prototype.setState=function(e,n){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,n,"setState")};it.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Xu(){}Xu.prototype=it.prototype;function Ai(e,n,t){this.props=e,this.context=n,this.refs=Yu,this.updater=t||Ku}var Ui=Ai.prototype=new Xu;Ui.constructor=Ai;Gu(Ui,it.prototype);Ui.isPureReactComponent=!0;var Do=Array.isArray,Zu=Object.prototype.hasOwnProperty,$i={current:null},Ju={key:!0,ref:!0,__self:!0,__source:!0};function qu(e,n,t){var r,l={},i=null,o=null;if(n!=null)for(r in n.ref!==void 0&&(o=n.ref),n.key!==void 0&&(i=""+n.key),n)Zu.call(n,r)&&!Ju.hasOwnProperty(r)&&(l[r]=n[r]);var u=arguments.length-2;if(u===1)l.children=t;else if(1>>1,X=E[W];if(0>>1;Wl(gl,P))gnl(er,gl)?(E[W]=er,E[gn]=P,W=gn):(E[W]=gl,E[yn]=P,W=yn);else if(gnl(er,P))E[W]=er,E[gn]=P,W=gn;else break e}}return N}function l(E,N){var P=E.sortIndex-N.sortIndex;return P!==0?P:E.id-N.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var o=Date,u=o.now();e.unstable_now=function(){return o.now()-u}}var a=[],f=[],h=1,m=null,p=3,w=!1,g=!1,k=!1,z=typeof setTimeout=="function"?setTimeout:null,c=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 d(E){for(var N=t(f);N!==null;){if(N.callback===null)r(f);else if(N.startTime<=E)r(f),N.sortIndex=N.expirationTime,n(a,N);else break;N=t(f)}}function v(E){if(k=!1,d(E),!g)if(t(a)!==null)g=!0,vl(_);else{var N=t(f);N!==null&&yl(v,N.startTime-E)}}function _(E,N){g=!1,k&&(k=!1,c(x),x=-1),w=!0;var P=p;try{for(d(N),m=t(a);m!==null&&(!(m.expirationTime>N)||E&&!Ne());){var W=m.callback;if(typeof W=="function"){m.callback=null,p=m.priorityLevel;var X=W(m.expirationTime<=N);N=e.unstable_now(),typeof X=="function"?m.callback=X:m===t(a)&&r(a),d(N)}else r(a);m=t(a)}if(m!==null)var bt=!0;else{var yn=t(f);yn!==null&&yl(v,yn.startTime-N),bt=!1}return bt}finally{m=null,p=P,w=!1}}var L=!1,C=null,x=-1,H=5,R=-1;function Ne(){return!(e.unstable_now()-RE||125W?(E.sortIndex=P,n(f,E),t(a)===null&&E===t(f)&&(k?(c(x),x=-1):k=!0,yl(v,P-W))):(E.sortIndex=X,n(a,E),g||w||(g=!0,vl(_))),E},e.unstable_shouldYield=Ne,e.unstable_wrapCallback=function(E){var N=p;return function(){var P=p;p=N;try{return E.apply(this,arguments)}finally{p=P}}}})(ta);na.exports=ta;var Nc=na.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 ra=ke,ye=Nc;function y(e){for(var n="https://reactjs.org/docs/error-decoder.html?invariant="+e,t=1;t"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Kl=Object.prototype.hasOwnProperty,Pc=/^[: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]*$/,Fo={},Ao={};function zc(e){return Kl.call(Ao,e)?!0:Kl.call(Fo,e)?!1:Pc.test(e)?Ao[e]=!0:(Fo[e]=!0,!1)}function Tc(e,n,t,r){if(t!==null&&t.type===0)return!1;switch(typeof n){case"function":case"symbol":return!0;case"boolean":return r?!1:t!==null?!t.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Rc(e,n,t,r){if(n===null||typeof n>"u"||Tc(e,n,t,r))return!0;if(r)return!1;if(t!==null)switch(t.type){case 3:return!n;case 4:return n===!1;case 5:return isNaN(n);case 6:return isNaN(n)||1>n}return!1}function ae(e,n,t,r,l,i,o){this.acceptsBooleans=n===2||n===3||n===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=t,this.propertyName=e,this.type=n,this.sanitizeURL=i,this.removeEmptyString=o}var ee={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){ee[e]=new ae(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var n=e[0];ee[n]=new ae(n,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){ee[e]=new ae(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){ee[e]=new ae(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){ee[e]=new ae(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){ee[e]=new ae(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){ee[e]=new ae(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){ee[e]=new ae(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){ee[e]=new ae(e,5,!1,e.toLowerCase(),null,!1,!1)});var Vi=/[\-:]([a-z])/g;function Hi(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 n=e.replace(Vi,Hi);ee[n]=new ae(n,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var n=e.replace(Vi,Hi);ee[n]=new ae(n,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var n=e.replace(Vi,Hi);ee[n]=new ae(n,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){ee[e]=new ae(e,1,!1,e.toLowerCase(),null,!1,!1)});ee.xlinkHref=new ae("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){ee[e]=new ae(e,1,!1,e.toLowerCase(),null,!0,!0)});function Wi(e,n,t,r){var l=ee.hasOwnProperty(n)?ee[n]:null;(l!==null?l.type!==0:r||!(2u||l[o]!==i[u]){var a=` -`+l[o].replace(" at new "," at ");return e.displayName&&a.includes("")&&(a=a.replace("",e.displayName)),a}while(1<=o&&0<=u);break}}}finally{Sl=!1,Error.prepareStackTrace=t}return(e=e?e.displayName||e.name:"")?gt(e):""}function Mc(e){switch(e.tag){case 5:return gt(e.type);case 16:return gt("Lazy");case 13:return gt("Suspense");case 19:return gt("SuspenseList");case 0:case 2:case 15:return e=_l(e.type,!1),e;case 11:return e=_l(e.type.render,!1),e;case 1:return e=_l(e.type,!0),e;default:return""}}function Zl(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 Dn:return"Fragment";case On:return"Portal";case Gl:return"Profiler";case Qi:return"StrictMode";case Yl:return"Suspense";case Xl:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case oa:return(e.displayName||"Context")+".Consumer";case ia:return(e._context.displayName||"Context")+".Provider";case Ki:var n=e.render;return e=e.displayName,e||(e=n.displayName||n.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case Gi:return n=e.displayName||null,n!==null?n:Zl(e.type)||"Memo";case Je:n=e._payload,e=e._init;try{return Zl(e(n))}catch{}}return null}function jc(e){var n=e.type;switch(e.tag){case 24:return"Cache";case 9:return(n.displayName||"Context")+".Consumer";case 10:return(n._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=n.render,e=e.displayName||e.name||"",n.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return n;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Zl(n);case 8:return n===Qi?"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 n=="function")return n.displayName||n.name||null;if(typeof n=="string")return n}return null}function dn(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function aa(e){var n=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(n==="checkbox"||n==="radio")}function Oc(e){var n=aa(e)?"checked":"value",t=Object.getOwnPropertyDescriptor(e.constructor.prototype,n),r=""+e[n];if(!e.hasOwnProperty(n)&&typeof t<"u"&&typeof t.get=="function"&&typeof t.set=="function"){var l=t.get,i=t.set;return Object.defineProperty(e,n,{configurable:!0,get:function(){return l.call(this)},set:function(o){r=""+o,i.call(this,o)}}),Object.defineProperty(e,n,{enumerable:t.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[n]}}}}function rr(e){e._valueTracker||(e._valueTracker=Oc(e))}function sa(e){if(!e)return!1;var n=e._valueTracker;if(!n)return!0;var t=n.getValue(),r="";return e&&(r=aa(e)?e.checked?"true":"false":e.value),e=r,e!==t?(n.setValue(e),!0):!1}function Tr(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 Jl(e,n){var t=n.checked;return B({},n,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:t??e._wrapperState.initialChecked})}function $o(e,n){var t=n.defaultValue==null?"":n.defaultValue,r=n.checked!=null?n.checked:n.defaultChecked;t=dn(n.value!=null?n.value:t),e._wrapperState={initialChecked:r,initialValue:t,controlled:n.type==="checkbox"||n.type==="radio"?n.checked!=null:n.value!=null}}function ca(e,n){n=n.checked,n!=null&&Wi(e,"checked",n,!1)}function ql(e,n){ca(e,n);var t=dn(n.value),r=n.type;if(t!=null)r==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+t):e.value!==""+t&&(e.value=""+t);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}n.hasOwnProperty("value")?bl(e,n.type,t):n.hasOwnProperty("defaultValue")&&bl(e,n.type,dn(n.defaultValue)),n.checked==null&&n.defaultChecked!=null&&(e.defaultChecked=!!n.defaultChecked)}function Bo(e,n,t){if(n.hasOwnProperty("value")||n.hasOwnProperty("defaultValue")){var r=n.type;if(!(r!=="submit"&&r!=="reset"||n.value!==void 0&&n.value!==null))return;n=""+e._wrapperState.initialValue,t||n===e.value||(e.value=n),e.defaultValue=n}t=e.name,t!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,t!==""&&(e.name=t)}function bl(e,n,t){(n!=="number"||Tr(e.ownerDocument)!==e)&&(t==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+t&&(e.defaultValue=""+t))}var wt=Array.isArray;function Kn(e,n,t,r){if(e=e.options,n){n={};for(var l=0;l"+n.valueOf().toString()+"",n=lr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;n.firstChild;)e.appendChild(n.firstChild)}});function Mt(e,n){if(n){var t=e.firstChild;if(t&&t===e.lastChild&&t.nodeType===3){t.nodeValue=n;return}}e.textContent=n}var _t={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},Dc=["Webkit","ms","Moz","O"];Object.keys(_t).forEach(function(e){Dc.forEach(function(n){n=n+e.charAt(0).toUpperCase()+e.substring(1),_t[n]=_t[e]})});function ma(e,n,t){return n==null||typeof n=="boolean"||n===""?"":t||typeof n!="number"||n===0||_t.hasOwnProperty(e)&&_t[e]?(""+n).trim():n+"px"}function ha(e,n){e=e.style;for(var t in n)if(n.hasOwnProperty(t)){var r=t.indexOf("--")===0,l=ma(t,n[t],r);t==="float"&&(t="cssFloat"),r?e.setProperty(t,l):e[t]=l}}var Ic=B({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 ti(e,n){if(n){if(Ic[e]&&(n.children!=null||n.dangerouslySetInnerHTML!=null))throw Error(y(137,e));if(n.dangerouslySetInnerHTML!=null){if(n.children!=null)throw Error(y(60));if(typeof n.dangerouslySetInnerHTML!="object"||!("__html"in n.dangerouslySetInnerHTML))throw Error(y(61))}if(n.style!=null&&typeof n.style!="object")throw Error(y(62))}}function ri(e,n){if(e.indexOf("-")===-1)return typeof n.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 li=null;function Yi(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ii=null,Gn=null,Yn=null;function Wo(e){if(e=Jt(e)){if(typeof ii!="function")throw Error(y(280));var n=e.stateNode;n&&(n=il(n),ii(e.stateNode,e.type,n))}}function va(e){Gn?Yn?Yn.push(e):Yn=[e]:Gn=e}function ya(){if(Gn){var e=Gn,n=Yn;if(Yn=Gn=null,Wo(e),n)for(e=0;e>>=0,e===0?32:31-(Gc(e)/Yc|0)|0}var ir=64,or=4194304;function kt(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 Or(e,n){var t=e.pendingLanes;if(t===0)return 0;var r=0,l=e.suspendedLanes,i=e.pingedLanes,o=t&268435455;if(o!==0){var u=o&~l;u!==0?r=kt(u):(i&=o,i!==0&&(r=kt(i)))}else o=t&~l,o!==0?r=kt(o):i!==0&&(r=kt(i));if(r===0)return 0;if(n!==0&&n!==r&&!(n&l)&&(l=r&-r,i=n&-n,l>=i||l===16&&(i&4194240)!==0))return n;if(r&4&&(r|=t&16),n=e.entangledLanes,n!==0)for(e=e.entanglements,n&=r;0t;t++)n.push(e);return n}function Xt(e,n,t){e.pendingLanes|=n,n!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,n=31-Me(n),e[n]=t}function qc(e,n){var t=e.pendingLanes&~n;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=n,e.mutableReadLanes&=n,e.entangledLanes&=n,n=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Lt),bo=String.fromCharCode(32),eu=!1;function Fa(e,n){switch(e){case"keyup":return Nf.indexOf(n.keyCode)!==-1;case"keydown":return n.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Aa(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var In=!1;function zf(e,n){switch(e){case"compositionend":return Aa(n);case"keypress":return n.which!==32?null:(eu=!0,bo);case"textInput":return e=n.data,e===bo&&eu?null:e;default:return null}}function Tf(e,n){if(In)return e==="compositionend"||!to&&Fa(e,n)?(e=Da(),Sr=bi=nn=null,In=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(n.ctrlKey||n.altKey||n.metaKey)||n.ctrlKey&&n.altKey){if(n.char&&1=n)return{node:t,offset:n-e};e=r}e:{for(;t;){if(t.nextSibling){t=t.nextSibling;break e}t=t.parentNode}t=void 0}t=lu(t)}}function Va(e,n){return e&&n?e===n?!0:e&&e.nodeType===3?!1:n&&n.nodeType===3?Va(e,n.parentNode):"contains"in e?e.contains(n):e.compareDocumentPosition?!!(e.compareDocumentPosition(n)&16):!1:!1}function Ha(){for(var e=window,n=Tr();n instanceof e.HTMLIFrameElement;){try{var t=typeof n.contentWindow.location.href=="string"}catch{t=!1}if(t)e=n.contentWindow;else break;n=Tr(e.document)}return n}function ro(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return n&&(n==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||n==="textarea"||e.contentEditable==="true")}function Uf(e){var n=Ha(),t=e.focusedElem,r=e.selectionRange;if(n!==t&&t&&t.ownerDocument&&Va(t.ownerDocument.documentElement,t)){if(r!==null&&ro(t)){if(n=r.start,e=r.end,e===void 0&&(e=n),"selectionStart"in t)t.selectionStart=n,t.selectionEnd=Math.min(e,t.value.length);else if(e=(n=t.ownerDocument||document)&&n.defaultView||window,e.getSelection){e=e.getSelection();var l=t.textContent.length,i=Math.min(r.start,l);r=r.end===void 0?i:Math.min(r.end,l),!e.extend&&i>r&&(l=r,r=i,i=l),l=iu(t,i);var o=iu(t,r);l&&o&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(n=n.createRange(),n.setStart(l.node,l.offset),e.removeAllRanges(),i>r?(e.addRange(n),e.extend(o.node,o.offset)):(n.setEnd(o.node,o.offset),e.addRange(n)))}}for(n=[],e=t;e=e.parentNode;)e.nodeType===1&&n.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof t.focus=="function"&&t.focus(),t=0;t=document.documentMode,Fn=null,fi=null,xt=null,di=!1;function ou(e,n,t){var r=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;di||Fn==null||Fn!==Tr(r)||(r=Fn,"selectionStart"in r&&ro(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),xt&&At(xt,r)||(xt=r,r=Fr(fi,"onSelect"),0$n||(e.current=gi[$n],gi[$n]=null,$n--)}function O(e,n){$n++,gi[$n]=e.current,e.current=n}var pn={},le=hn(pn),fe=hn(!1),xn=pn;function bn(e,n){var t=e.type.contextTypes;if(!t)return pn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===n)return r.__reactInternalMemoizedMaskedChildContext;var l={},i;for(i in t)l[i]=n[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=l),l}function de(e){return e=e.childContextTypes,e!=null}function Ur(){I(fe),I(le)}function pu(e,n,t){if(le.current!==pn)throw Error(y(168));O(le,n),O(fe,t)}function qa(e,n,t){var r=e.stateNode;if(n=n.childContextTypes,typeof r.getChildContext!="function")return t;r=r.getChildContext();for(var l in r)if(!(l in n))throw Error(y(108,jc(e)||"Unknown",l));return B({},t,r)}function $r(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||pn,xn=le.current,O(le,e),O(fe,fe.current),!0}function mu(e,n,t){var r=e.stateNode;if(!r)throw Error(y(169));t?(e=qa(e,n,xn),r.__reactInternalMemoizedMergedChildContext=e,I(fe),I(le),O(le,e)):I(fe),O(fe,t)}var Be=null,ol=!1,Il=!1;function ba(e){Be===null?Be=[e]:Be.push(e)}function Jf(e){ol=!0,ba(e)}function vn(){if(!Il&&Be!==null){Il=!0;var e=0,n=j;try{var t=Be;for(j=1;e>=o,l-=o,Ve=1<<32-Me(n)+l|t<x?(H=C,C=null):H=C.sibling;var R=p(c,C,d[x],v);if(R===null){C===null&&(C=H);break}e&&C&&R.alternate===null&&n(c,C),s=i(R,s,x),L===null?_=R:L.sibling=R,L=R,C=H}if(x===d.length)return t(c,C),A&&wn(c,x),_;if(C===null){for(;xx?(H=C,C=null):H=C.sibling;var Ne=p(c,C,R.value,v);if(Ne===null){C===null&&(C=H);break}e&&C&&Ne.alternate===null&&n(c,C),s=i(Ne,s,x),L===null?_=Ne:L.sibling=Ne,L=Ne,C=H}if(R.done)return t(c,C),A&&wn(c,x),_;if(C===null){for(;!R.done;x++,R=d.next())R=m(c,R.value,v),R!==null&&(s=i(R,s,x),L===null?_=R:L.sibling=R,L=R);return A&&wn(c,x),_}for(C=r(c,C);!R.done;x++,R=d.next())R=w(C,c,x,R.value,v),R!==null&&(e&&R.alternate!==null&&C.delete(R.key===null?x:R.key),s=i(R,s,x),L===null?_=R:L.sibling=R,L=R);return e&&C.forEach(function(at){return n(c,at)}),A&&wn(c,x),_}function z(c,s,d,v){if(typeof d=="object"&&d!==null&&d.type===Dn&&d.key===null&&(d=d.props.children),typeof d=="object"&&d!==null){switch(d.$$typeof){case tr:e:{for(var _=d.key,L=s;L!==null;){if(L.key===_){if(_=d.type,_===Dn){if(L.tag===7){t(c,L.sibling),s=l(L,d.props.children),s.return=c,c=s;break e}}else if(L.elementType===_||typeof _=="object"&&_!==null&&_.$$typeof===Je&&Su(_)===L.type){t(c,L.sibling),s=l(L,d.props),s.ref=ht(c,L,d),s.return=c,c=s;break e}t(c,L);break}else n(c,L);L=L.sibling}d.type===Dn?(s=Cn(d.props.children,c.mode,v,d.key),s.return=c,c=s):(v=zr(d.type,d.key,d.props,null,c.mode,v),v.ref=ht(c,s,d),v.return=c,c=v)}return o(c);case On:e:{for(L=d.key;s!==null;){if(s.key===L)if(s.tag===4&&s.stateNode.containerInfo===d.containerInfo&&s.stateNode.implementation===d.implementation){t(c,s.sibling),s=l(s,d.children||[]),s.return=c,c=s;break e}else{t(c,s);break}else n(c,s);s=s.sibling}s=Wl(d,c.mode,v),s.return=c,c=s}return o(c);case Je:return L=d._init,z(c,s,L(d._payload),v)}if(wt(d))return g(c,s,d,v);if(ct(d))return k(c,s,d,v);pr(c,d)}return typeof d=="string"&&d!==""||typeof d=="number"?(d=""+d,s!==null&&s.tag===6?(t(c,s.sibling),s=l(s,d),s.return=c,c=s):(t(c,s),s=Hl(d,c.mode,v),s.return=c,c=s),o(c)):t(c,s)}return z}var nt=us(!0),as=us(!1),qt={},Ue=hn(qt),Vt=hn(qt),Ht=hn(qt);function En(e){if(e===qt)throw Error(y(174));return e}function po(e,n){switch(O(Ht,n),O(Vt,e),O(Ue,qt),e=n.nodeType,e){case 9:case 11:n=(n=n.documentElement)?n.namespaceURI:ni(null,"");break;default:e=e===8?n.parentNode:n,n=e.namespaceURI||null,e=e.tagName,n=ni(n,e)}I(Ue),O(Ue,n)}function tt(){I(Ue),I(Vt),I(Ht)}function ss(e){En(Ht.current);var n=En(Ue.current),t=ni(n,e.type);n!==t&&(O(Vt,e),O(Ue,t))}function mo(e){Vt.current===e&&(I(Ue),I(Vt))}var U=hn(0);function Kr(e){for(var n=e;n!==null;){if(n.tag===13){var t=n.memoizedState;if(t!==null&&(t=t.dehydrated,t===null||t.data==="$?"||t.data==="$!"))return n}else if(n.tag===19&&n.memoizedProps.revealOrder!==void 0){if(n.flags&128)return n}else if(n.child!==null){n.child.return=n,n=n.child;continue}if(n===e)break;for(;n.sibling===null;){if(n.return===null||n.return===e)return null;n=n.return}n.sibling.return=n.return,n=n.sibling}return null}var Fl=[];function ho(){for(var e=0;et?t:4,e(!0);var r=Al.transition;Al.transition={};try{e(!1),n()}finally{j=t,Al.transition=r}}function Cs(){return xe().memoizedState}function nd(e,n,t){var r=cn(e);if(t={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null},xs(e))Ns(n,t);else if(t=rs(e,n,t,r),t!==null){var l=oe();je(t,e,r,l),Ps(t,n,r)}}function td(e,n,t){var r=cn(e),l={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null};if(xs(e))Ns(n,l);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=n.lastRenderedReducer,i!==null))try{var o=n.lastRenderedState,u=i(o,t);if(l.hasEagerState=!0,l.eagerState=u,Oe(u,o)){var a=n.interleaved;a===null?(l.next=l,co(n)):(l.next=a.next,a.next=l),n.interleaved=l;return}}catch{}finally{}t=rs(e,n,l,r),t!==null&&(l=oe(),je(t,e,r,l),Ps(t,n,r))}}function xs(e){var n=e.alternate;return e===$||n!==null&&n===$}function Ns(e,n){Nt=Gr=!0;var t=e.pending;t===null?n.next=n:(n.next=t.next,t.next=n),e.pending=n}function Ps(e,n,t){if(t&4194240){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,Zi(e,t)}}var Yr={readContext:Ce,useCallback:ne,useContext:ne,useEffect:ne,useImperativeHandle:ne,useInsertionEffect:ne,useLayoutEffect:ne,useMemo:ne,useReducer:ne,useRef:ne,useState:ne,useDebugValue:ne,useDeferredValue:ne,useTransition:ne,useMutableSource:ne,useSyncExternalStore:ne,useId:ne,unstable_isNewReconciler:!1},rd={readContext:Ce,useCallback:function(e,n){return Ie().memoizedState=[e,n===void 0?null:n],e},useContext:Ce,useEffect:Eu,useImperativeHandle:function(e,n,t){return t=t!=null?t.concat([e]):null,Cr(4194308,4,ks.bind(null,n,e),t)},useLayoutEffect:function(e,n){return Cr(4194308,4,e,n)},useInsertionEffect:function(e,n){return Cr(4,2,e,n)},useMemo:function(e,n){var t=Ie();return n=n===void 0?null:n,e=e(),t.memoizedState=[e,n],e},useReducer:function(e,n,t){var r=Ie();return n=t!==void 0?t(n):n,r.memoizedState=r.baseState=n,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},r.queue=e,e=e.dispatch=nd.bind(null,$,e),[r.memoizedState,e]},useRef:function(e){var n=Ie();return e={current:e},n.memoizedState=e},useState:_u,useDebugValue:ko,useDeferredValue:function(e){return Ie().memoizedState=e},useTransition:function(){var e=_u(!1),n=e[0];return e=ed.bind(null,e[1]),Ie().memoizedState=e,[n,e]},useMutableSource:function(){},useSyncExternalStore:function(e,n,t){var r=$,l=Ie();if(A){if(t===void 0)throw Error(y(407));t=t()}else{if(t=n(),J===null)throw Error(y(349));Pn&30||ds(r,n,t)}l.memoizedState=t;var i={value:t,getSnapshot:n};return l.queue=i,Eu(ms.bind(null,r,i,e),[e]),r.flags|=2048,Kt(9,ps.bind(null,r,i,t,n),void 0,null),t},useId:function(){var e=Ie(),n=J.identifierPrefix;if(A){var t=He,r=Ve;t=(r&~(1<<32-Me(r)-1)).toString(32)+t,n=":"+n+"R"+t,t=Wt++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(t,{is:r.is}):(e=o.createElement(t),t==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,t),e[Fe]=n,e[Bt]=r,Fs(e,n,!1,!1),n.stateNode=e;e:{switch(o=ri(t,r),t){case"dialog":D("cancel",e),D("close",e),l=r;break;case"iframe":case"object":case"embed":D("load",e),l=r;break;case"video":case"audio":for(l=0;llt&&(n.flags|=128,r=!0,vt(i,!1),n.lanes=4194304)}else{if(!r)if(e=Kr(o),e!==null){if(n.flags|=128,r=!0,t=e.updateQueue,t!==null&&(n.updateQueue=t,n.flags|=4),vt(i,!0),i.tail===null&&i.tailMode==="hidden"&&!o.alternate&&!A)return te(n),null}else 2*Q()-i.renderingStartTime>lt&&t!==1073741824&&(n.flags|=128,r=!0,vt(i,!1),n.lanes=4194304);i.isBackwards?(o.sibling=n.child,n.child=o):(t=i.last,t!==null?t.sibling=o:n.child=o,i.last=o)}return i.tail!==null?(n=i.tail,i.rendering=n,i.tail=n.sibling,i.renderingStartTime=Q(),n.sibling=null,t=U.current,O(U,r?t&1|2:t&1),n):(te(n),null);case 22:case 23:return xo(),r=n.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(n.flags|=8192),r&&n.mode&1?me&1073741824&&(te(n),n.subtreeFlags&6&&(n.flags|=8192)):te(n),null;case 24:return null;case 25:return null}throw Error(y(156,n.tag))}function fd(e,n){switch(io(n),n.tag){case 1:return de(n.type)&&Ur(),e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 3:return tt(),I(fe),I(le),ho(),e=n.flags,e&65536&&!(e&128)?(n.flags=e&-65537|128,n):null;case 5:return mo(n),null;case 13:if(I(U),e=n.memoizedState,e!==null&&e.dehydrated!==null){if(n.alternate===null)throw Error(y(340));et()}return e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 19:return I(U),null;case 4:return tt(),null;case 10:return so(n.type._context),null;case 22:case 23:return xo(),null;case 24:return null;default:return null}}var hr=!1,re=!1,dd=typeof WeakSet=="function"?WeakSet:Set,S=null;function Wn(e,n){var t=e.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(r){V(e,n,r)}else t.current=null}function Ti(e,n,t){try{t()}catch(r){V(e,n,r)}}var Mu=!1;function pd(e,n){if(pi=Dr,e=Ha(),ro(e)){if("selectionStart"in e)var t={start:e.selectionStart,end:e.selectionEnd};else e:{t=(t=e.ownerDocument)&&t.defaultView||window;var r=t.getSelection&&t.getSelection();if(r&&r.rangeCount!==0){t=r.anchorNode;var l=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{t.nodeType,i.nodeType}catch{t=null;break e}var o=0,u=-1,a=-1,f=0,h=0,m=e,p=null;n:for(;;){for(var w;m!==t||l!==0&&m.nodeType!==3||(u=o+l),m!==i||r!==0&&m.nodeType!==3||(a=o+r),m.nodeType===3&&(o+=m.nodeValue.length),(w=m.firstChild)!==null;)p=m,m=w;for(;;){if(m===e)break n;if(p===t&&++f===l&&(u=o),p===i&&++h===r&&(a=o),(w=m.nextSibling)!==null)break;m=p,p=m.parentNode}m=w}t=u===-1||a===-1?null:{start:u,end:a}}else t=null}t=t||{start:0,end:0}}else t=null;for(mi={focusedElem:e,selectionRange:t},Dr=!1,S=n;S!==null;)if(n=S,e=n.child,(n.subtreeFlags&1028)!==0&&e!==null)e.return=n,S=e;else for(;S!==null;){n=S;try{var g=n.alternate;if(n.flags&1024)switch(n.tag){case 0:case 11:case 15:break;case 1:if(g!==null){var k=g.memoizedProps,z=g.memoizedState,c=n.stateNode,s=c.getSnapshotBeforeUpdate(n.elementType===n.type?k:ze(n.type,k),z);c.__reactInternalSnapshotBeforeUpdate=s}break;case 3:var d=n.stateNode.containerInfo;d.nodeType===1?d.textContent="":d.nodeType===9&&d.documentElement&&d.removeChild(d.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(y(163))}}catch(v){V(n,n.return,v)}if(e=n.sibling,e!==null){e.return=n.return,S=e;break}S=n.return}return g=Mu,Mu=!1,g}function Pt(e,n,t){var r=n.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var i=l.destroy;l.destroy=void 0,i!==void 0&&Ti(n,t,i)}l=l.next}while(l!==r)}}function sl(e,n){if(n=n.updateQueue,n=n!==null?n.lastEffect:null,n!==null){var t=n=n.next;do{if((t.tag&e)===e){var r=t.create;t.destroy=r()}t=t.next}while(t!==n)}}function Ri(e){var n=e.ref;if(n!==null){var t=e.stateNode;switch(e.tag){case 5:e=t;break;default:e=t}typeof n=="function"?n(e):n.current=e}}function $s(e){var n=e.alternate;n!==null&&(e.alternate=null,$s(n)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(n=e.stateNode,n!==null&&(delete n[Fe],delete n[Bt],delete n[yi],delete n[Xf],delete n[Zf])),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 Bs(e){return e.tag===5||e.tag===3||e.tag===4}function ju(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Bs(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 Mi(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?t.nodeType===8?t.parentNode.insertBefore(e,n):t.insertBefore(e,n):(t.nodeType===8?(n=t.parentNode,n.insertBefore(e,t)):(n=t,n.appendChild(e)),t=t._reactRootContainer,t!=null||n.onclick!==null||(n.onclick=Ar));else if(r!==4&&(e=e.child,e!==null))for(Mi(e,n,t),e=e.sibling;e!==null;)Mi(e,n,t),e=e.sibling}function ji(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?t.insertBefore(e,n):t.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(ji(e,n,t),e=e.sibling;e!==null;)ji(e,n,t),e=e.sibling}var q=null,Te=!1;function Ze(e,n,t){for(t=t.child;t!==null;)Vs(e,n,t),t=t.sibling}function Vs(e,n,t){if(Ae&&typeof Ae.onCommitFiberUnmount=="function")try{Ae.onCommitFiberUnmount(nl,t)}catch{}switch(t.tag){case 5:re||Wn(t,n);case 6:var r=q,l=Te;q=null,Ze(e,n,t),q=r,Te=l,q!==null&&(Te?(e=q,t=t.stateNode,e.nodeType===8?e.parentNode.removeChild(t):e.removeChild(t)):q.removeChild(t.stateNode));break;case 18:q!==null&&(Te?(e=q,t=t.stateNode,e.nodeType===8?Dl(e.parentNode,t):e.nodeType===1&&Dl(e,t),It(e)):Dl(q,t.stateNode));break;case 4:r=q,l=Te,q=t.stateNode.containerInfo,Te=!0,Ze(e,n,t),q=r,Te=l;break;case 0:case 11:case 14:case 15:if(!re&&(r=t.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var i=l,o=i.destroy;i=i.tag,o!==void 0&&(i&2||i&4)&&Ti(t,n,o),l=l.next}while(l!==r)}Ze(e,n,t);break;case 1:if(!re&&(Wn(t,n),r=t.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(u){V(t,n,u)}Ze(e,n,t);break;case 21:Ze(e,n,t);break;case 22:t.mode&1?(re=(r=re)||t.memoizedState!==null,Ze(e,n,t),re=r):Ze(e,n,t);break;default:Ze(e,n,t)}}function Ou(e){var n=e.updateQueue;if(n!==null){e.updateQueue=null;var t=e.stateNode;t===null&&(t=e.stateNode=new dd),n.forEach(function(r){var l=_d.bind(null,e,r);t.has(r)||(t.add(r),r.then(l,l))})}}function Pe(e,n){var t=n.deletions;if(t!==null)for(var r=0;rl&&(l=o),r&=~i}if(r=l,r=Q()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*hd(r/1960))-r,10e?16:e,tn===null)var r=!1;else{if(e=tn,tn=null,Jr=0,M&6)throw Error(y(331));var l=M;for(M|=4,S=e.current;S!==null;){var i=S,o=i.child;if(S.flags&16){var u=i.deletions;if(u!==null){for(var a=0;aQ()-Lo?Ln(e,0):Eo|=t),pe(e,n)}function Zs(e,n){n===0&&(e.mode&1?(n=or,or<<=1,!(or&130023424)&&(or=4194304)):n=1);var t=oe();e=Ge(e,n),e!==null&&(Xt(e,n,t),pe(e,t))}function Sd(e){var n=e.memoizedState,t=0;n!==null&&(t=n.retryLane),Zs(e,t)}function _d(e,n){var t=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(t=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(y(314))}r!==null&&r.delete(n),Zs(e,t)}var Js;Js=function(e,n,t){if(e!==null)if(e.memoizedProps!==n.pendingProps||fe.current)ce=!0;else{if(!(e.lanes&t)&&!(n.flags&128))return ce=!1,sd(e,n,t);ce=!!(e.flags&131072)}else ce=!1,A&&n.flags&1048576&&es(n,Vr,n.index);switch(n.lanes=0,n.tag){case 2:var r=n.type;xr(e,n),e=n.pendingProps;var l=bn(n,le.current);Zn(n,t),l=yo(null,n,r,e,l,t);var i=go();return n.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(n.tag=1,n.memoizedState=null,n.updateQueue=null,de(r)?(i=!0,$r(n)):i=!1,n.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,fo(n),l.updater=ul,n.stateNode=l,l._reactInternals=n,Ei(n,r,e,t),n=xi(null,n,r,!0,i,t)):(n.tag=0,A&&i&&lo(n),ie(null,n,l,t),n=n.child),n;case 16:r=n.elementType;e:{switch(xr(e,n),e=n.pendingProps,l=r._init,r=l(r._payload),n.type=r,l=n.tag=Ld(r),e=ze(r,e),l){case 0:n=Ci(null,n,r,e,t);break e;case 1:n=zu(null,n,r,e,t);break e;case 11:n=Nu(null,n,r,e,t);break e;case 14:n=Pu(null,n,r,ze(r.type,e),t);break e}throw Error(y(306,r,""))}return n;case 0:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:ze(r,l),Ci(e,n,r,l,t);case 1:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:ze(r,l),zu(e,n,r,l,t);case 3:e:{if(Os(n),e===null)throw Error(y(387));r=n.pendingProps,i=n.memoizedState,l=i.element,ls(e,n),Qr(n,r,null,t);var o=n.memoizedState;if(r=o.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},n.updateQueue.baseState=i,n.memoizedState=i,n.flags&256){l=rt(Error(y(423)),n),n=Tu(e,n,r,t,l);break e}else if(r!==l){l=rt(Error(y(424)),n),n=Tu(e,n,r,t,l);break e}else for(he=un(n.stateNode.containerInfo.firstChild),ve=n,A=!0,Re=null,t=as(n,null,r,t),n.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(et(),r===l){n=Ye(e,n,t);break e}ie(e,n,r,t)}n=n.child}return n;case 5:return ss(n),e===null&&ki(n),r=n.type,l=n.pendingProps,i=e!==null?e.memoizedProps:null,o=l.children,hi(r,l)?o=null:i!==null&&hi(r,i)&&(n.flags|=32),js(e,n),ie(e,n,o,t),n.child;case 6:return e===null&&ki(n),null;case 13:return Ds(e,n,t);case 4:return po(n,n.stateNode.containerInfo),r=n.pendingProps,e===null?n.child=nt(n,null,r,t):ie(e,n,r,t),n.child;case 11:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:ze(r,l),Nu(e,n,r,l,t);case 7:return ie(e,n,n.pendingProps,t),n.child;case 8:return ie(e,n,n.pendingProps.children,t),n.child;case 12:return ie(e,n,n.pendingProps.children,t),n.child;case 10:e:{if(r=n.type._context,l=n.pendingProps,i=n.memoizedProps,o=l.value,O(Hr,r._currentValue),r._currentValue=o,i!==null)if(Oe(i.value,o)){if(i.children===l.children&&!fe.current){n=Ye(e,n,t);break e}}else for(i=n.child,i!==null&&(i.return=n);i!==null;){var u=i.dependencies;if(u!==null){o=i.child;for(var a=u.firstContext;a!==null;){if(a.context===r){if(i.tag===1){a=We(-1,t&-t),a.tag=2;var f=i.updateQueue;if(f!==null){f=f.shared;var h=f.pending;h===null?a.next=a:(a.next=h.next,h.next=a),f.pending=a}}i.lanes|=t,a=i.alternate,a!==null&&(a.lanes|=t),Si(i.return,t,n),u.lanes|=t;break}a=a.next}}else if(i.tag===10)o=i.type===n.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(y(341));o.lanes|=t,u=o.alternate,u!==null&&(u.lanes|=t),Si(o,t,n),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===n){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}ie(e,n,l.children,t),n=n.child}return n;case 9:return l=n.type,r=n.pendingProps.children,Zn(n,t),l=Ce(l),r=r(l),n.flags|=1,ie(e,n,r,t),n.child;case 14:return r=n.type,l=ze(r,n.pendingProps),l=ze(r.type,l),Pu(e,n,r,l,t);case 15:return Rs(e,n,n.type,n.pendingProps,t);case 17:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:ze(r,l),xr(e,n),n.tag=1,de(r)?(e=!0,$r(n)):e=!1,Zn(n,t),os(n,r,l),Ei(n,r,l,t),xi(null,n,r,!0,e,t);case 19:return Is(e,n,t);case 22:return Ms(e,n,t)}throw Error(y(156,n.tag))};function qs(e,n){return La(e,n)}function Ed(e,n,t,r){this.tag=e,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ee(e,n,t,r){return new Ed(e,n,t,r)}function Po(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Ld(e){if(typeof e=="function")return Po(e)?1:0;if(e!=null){if(e=e.$$typeof,e===Ki)return 11;if(e===Gi)return 14}return 2}function fn(e,n){var t=e.alternate;return t===null?(t=Ee(e.tag,n,e.key,e.mode),t.elementType=e.elementType,t.type=e.type,t.stateNode=e.stateNode,t.alternate=e,e.alternate=t):(t.pendingProps=n,t.type=e.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=e.flags&14680064,t.childLanes=e.childLanes,t.lanes=e.lanes,t.child=e.child,t.memoizedProps=e.memoizedProps,t.memoizedState=e.memoizedState,t.updateQueue=e.updateQueue,n=e.dependencies,t.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext},t.sibling=e.sibling,t.index=e.index,t.ref=e.ref,t}function zr(e,n,t,r,l,i){var o=2;if(r=e,typeof e=="function")Po(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case Dn:return Cn(t.children,l,i,n);case Qi:o=8,l|=8;break;case Gl:return e=Ee(12,t,n,l|2),e.elementType=Gl,e.lanes=i,e;case Yl:return e=Ee(13,t,n,l),e.elementType=Yl,e.lanes=i,e;case Xl:return e=Ee(19,t,n,l),e.elementType=Xl,e.lanes=i,e;case ua:return fl(t,l,i,n);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case ia:o=10;break e;case oa:o=9;break e;case Ki:o=11;break e;case Gi:o=14;break e;case Je:o=16,r=null;break e}throw Error(y(130,e==null?e:typeof e,""))}return n=Ee(o,t,n,l),n.elementType=e,n.type=r,n.lanes=i,n}function Cn(e,n,t,r){return e=Ee(7,e,r,n),e.lanes=t,e}function fl(e,n,t,r){return e=Ee(22,e,r,n),e.elementType=ua,e.lanes=t,e.stateNode={isHidden:!1},e}function Hl(e,n,t){return e=Ee(6,e,null,n),e.lanes=t,e}function Wl(e,n,t){return n=Ee(4,e.children!==null?e.children:[],e.key,n),n.lanes=t,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function Cd(e,n,t,r,l){this.tag=n,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=Ll(0),this.expirationTimes=Ll(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ll(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function zo(e,n,t,r,l,i,o,u,a){return e=new Cd(e,n,t,u,a),n===1?(n=1,i===!0&&(n|=8)):n=0,i=Ee(3,null,null,n),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},fo(i),e}function xd(e,n,t){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(tc)}catch(e){console.error(e)}}tc(),ea.exports=ge;var Rd=ea.exports,Vu=Rd;Ql.createRoot=Vu.createRoot,Ql.hydrateRoot=Vu.hydrateRoot;const Md={"Acehnese (Arabic script)":"ace_Arab","Acehnese (Latin script)":"ace_Latn",Afrikaans:"afr_Latn",Akan:"aka_Latn",Amharic:"amh_Ethi",Armenian:"hye_Armn",Assamese:"asm_Beng",Asturian:"ast_Latn",Awadhi:"awa_Deva","Ayacucho Quechua":"quy_Latn",Balinese:"ban_Latn",Bambara:"bam_Latn","Banjar (Arabic script)":"bjn_Arab","Banjar (Latin script)":"bjn_Latn",Bashkir:"bak_Cyrl",Basque:"eus_Latn",Belarusian:"bel_Cyrl",Bemba:"bem_Latn",Bengali:"ben_Beng",Bhojpuri:"bho_Deva",Bosnian:"bos_Latn",Buginese:"bug_Latn",Bulgarian:"bul_Cyrl",Burmese:"mya_Mymr",Catalan:"cat_Latn",Cebuano:"ceb_Latn","Central Atlas Tamazight":"tzm_Tfng","Central Aymara":"ayr_Latn","Central Kanuri (Arabic script)":"knc_Arab","Central Kanuri (Latin script)":"knc_Latn","Central Kurdish":"ckb_Arab",Chhattisgarhi:"hne_Deva","Chinese (Simplified)":"zho_Hans","Chinese (Traditional)":"zho_Hant",Chokwe:"cjk_Latn","Crimean Tatar":"crh_Latn",Croatian:"hrv_Latn",Czech:"ces_Latn",Danish:"dan_Latn",Dari:"prs_Arab",Dutch:"nld_Latn",Dyula:"dyu_Latn",Dzongkha:"dzo_Tibt","Eastern Panjabi":"pan_Guru","Eastern Yiddish":"ydd_Hebr","Egyptian Arabic":"arz_Arab",English:"eng_Latn",Esperanto:"epo_Latn",Estonian:"est_Latn",Ewe:"ewe_Latn",Faroese:"fao_Latn",Fijian:"fij_Latn",Finnish:"fin_Latn",Fon:"fon_Latn",French:"fra_Latn",Friulian:"fur_Latn",Galician:"glg_Latn",Ganda:"lug_Latn",Georgian:"kat_Geor",German:"deu_Latn",Greek:"ell_Grek",Guarani:"grn_Latn",Gujarati:"guj_Gujr","Haitian Creole":"hat_Latn","Halh Mongolian":"khk_Cyrl",Hausa:"hau_Latn",Hebrew:"heb_Hebr",Hindi:"hin_Deva",Hungarian:"hun_Latn",Icelandic:"isl_Latn",Igbo:"ibo_Latn",Ilocano:"ilo_Latn",Indonesian:"ind_Latn",Irish:"gle_Latn",Italian:"ita_Latn",Japanese:"jpn_Jpan",Javanese:"jav_Latn",Jingpho:"kac_Latn",Kabiyè:"kbp_Latn",Kabuverdianu:"kea_Latn",Kabyle:"kab_Latn",Kamba:"kam_Latn",Kannada:"kan_Knda","Kashmiri (Arabic script)":"kas_Arab","Kashmiri (Devanagari script)":"kas_Deva",Kazakh:"kaz_Cyrl",Khmer:"khm_Khmr",Kikongo:"kon_Latn",Kikuyu:"kik_Latn",Kimbundu:"kmb_Latn",Kinyarwanda:"kin_Latn",Korean:"kor_Hang",Kyrgyz:"kir_Cyrl",Lao:"lao_Laoo",Latgalian:"ltg_Latn",Ligurian:"lij_Latn",Limburgish:"lim_Latn",Lingala:"lin_Latn",Lithuanian:"lit_Latn",Lombard:"lmo_Latn","Luba-Kasai":"lua_Latn",Luo:"luo_Latn",Luxembourgish:"ltz_Latn",Macedonian:"mkd_Cyrl",Magahi:"mag_Deva",Maithili:"mai_Deva",Malayalam:"mal_Mlym",Maltese:"mlt_Latn",Maori:"mri_Latn",Marathi:"mar_Deva","Meitei (Bengali script)":"mni_Beng","Mesopotamian Arabic":"acm_Arab","Minangkabau (Arabic script)":"min_Arab","Minangkabau (Latin script)":"min_Latn",Mizo:"lus_Latn","Modern Standard Arabic (Romanized)":"arb_Latn","Modern Standard Arabic":"arb_Arab","Moroccan Arabic":"ary_Arab",Mossi:"mos_Latn","Najdi Arabic":"ars_Arab",Nepali:"npi_Deva","Nigerian Fulfulde":"fuv_Latn","North Azerbaijani":"azj_Latn","North Levantine Arabic":"apc_Arab","Northern Kurdish":"kmr_Latn","Northern Sotho":"nso_Latn","Northern Uzbek":"uzn_Latn","Norwegian Bokmål":"nob_Latn","Norwegian Nynorsk":"nno_Latn",Nuer:"nus_Latn",Nyanja:"nya_Latn",Occitan:"oci_Latn",Odia:"ory_Orya",Pangasinan:"pag_Latn",Papiamento:"pap_Latn","Plateau Malagasy":"plt_Latn",Polish:"pol_Latn",Portuguese:"por_Latn",Romanian:"ron_Latn",Rundi:"run_Latn",Russian:"rus_Cyrl",Samoan:"smo_Latn",Sango:"sag_Latn",Sanskrit:"san_Deva",Santali:"sat_Olck",Sardinian:"srd_Latn","Scottish Gaelic":"gla_Latn",Serbian:"srp_Cyrl",Shan:"shn_Mymr",Shona:"sna_Latn",Sicilian:"scn_Latn",Silesian:"szl_Latn",Sindhi:"snd_Arab",Sinhala:"sin_Sinh",Slovak:"slk_Latn",Slovenian:"slv_Latn",Somali:"som_Latn","South Azerbaijani":"azb_Arab","South Levantine Arabic":"ajp_Arab","Southern Pashto":"pbt_Arab","Southern Sotho":"sot_Latn","Southwestern Dinka":"dik_Latn",Spanish:"spa_Latn","Standard Latvian":"lvs_Latn","Standard Malay":"zsm_Latn","Standard Tibetan":"bod_Tibt",Sundanese:"sun_Latn",Swahili:"swh_Latn",Swati:"ssw_Latn",Swedish:"swe_Latn",Tagalog:"tgl_Latn",Tajik:"tgk_Cyrl","Tamasheq (Latin script)":"taq_Latn","Tamasheq (Tifinagh script)":"taq_Tfng",Tamil:"tam_Taml",Tatar:"tat_Cyrl","Ta’izzi-Adeni Arabic":"acq_Arab",Telugu:"tel_Telu",Thai:"tha_Thai",Tigrinya:"tir_Ethi","Tok Pisin":"tpi_Latn","Tosk Albanian":"als_Latn",Tsonga:"tso_Latn",Tswana:"tsn_Latn",Tumbuka:"tum_Latn","Tunisian Arabic":"aeb_Arab",Turkish:"tur_Latn",Turkmen:"tuk_Latn",Twi:"twi_Latn",Ukrainian:"ukr_Cyrl",Umbundu:"umb_Latn",Urdu:"urd_Arab",Uyghur:"uig_Arab",Venetian:"vec_Latn",Vietnamese:"vie_Latn",Waray:"war_Latn",Welsh:"cym_Latn","West Central Oromo":"gaz_Latn","Western Persian":"pes_Arab",Wolof:"wol_Latn",Xhosa:"xho_Latn",Yoruba:"yor_Latn","Yue Chinese":"yue_Hant",Zulu:"zul_Latn"};function Hu({type:e,onChange:n,defaultLanguage:t}){return F.jsxs("div",{className:"language-selector",children:[F.jsxs("label",{children:[e,": "]}),F.jsx("select",{onChange:n,defaultValue:t,children:Object.entries(Md).map(([r,l])=>F.jsx("option",{value:l,children:r},r))})]})}function jd({text:e,percentage:n}){return n=n??0,F.jsx("div",{className:"progress-container",children:F.jsxs("div",{className:"progress-bar",style:{width:`${n}%`},children:[e," (",`${n.toFixed(2)}%`,")"]})})}function Od(){const[e,n]=ke.useState(null),[t,r]=ke.useState(!1),[l,i]=ke.useState([]),[o,u]=ke.useState("I love walking my dog."),[a,f]=ke.useState("eng_Latn"),[h,m]=ke.useState("fra_Latn"),[p,w]=ke.useState(""),g=ke.useRef(null);ke.useEffect(()=>{g.current||(g.current=new Worker(new URL("/assets/worker-22715bb5.js",self.location),{type:"module"}));const z=c=>{switch(c.data.status){case"initiate":n(!1),i(s=>[...s,c.data]);break;case"progress":i(s=>s.map(d=>d.file===c.data.file?{...d,progress:c.data.progress}:d));break;case"done":i(s=>s.filter(d=>d.file!==c.data.file));break;case"ready":n(!0);break;case"update":w(c.data.output);break;case"complete":r(!1);break}};return g.current.addEventListener("message",z),()=>g.current.removeEventListener("message",z)});const k=()=>{r(!0),g.current.postMessage({text:o,src_lang:a,tgt_lang:h})};return F.jsxs(F.Fragment,{children:[F.jsx("h1",{children:"Transformers.js"}),F.jsx("h2",{children:"ML-powered multilingual translation in React!"}),F.jsxs("div",{className:"container",children:[F.jsxs("div",{className:"language-container",children:[F.jsx(Hu,{type:"Source",defaultLanguage:"eng_Latn",onChange:z=>f(z.target.value)}),F.jsx(Hu,{type:"Target",defaultLanguage:"fra_Latn",onChange:z=>m(z.target.value)})]}),F.jsxs("div",{className:"textbox-container",children:[F.jsx("textarea",{value:o,rows:3,onChange:z=>u(z.target.value)}),F.jsx("textarea",{value:p,rows:3,readOnly:!0})]})]}),F.jsx("button",{disabled:t,onClick:k,children:"Translate"}),F.jsxs("div",{className:"progress-bars-container",children:[e===!1&&F.jsx("label",{children:"Loading models... (only run once)"}),l.map(z=>F.jsx("div",{children:F.jsx(jd,{text:z.file,percentage:z.progress})},z.file))]})]})}Ql.createRoot(document.getElementById("root")).render(F.jsx(kc.StrictMode,{children:F.jsx(Od,{})})); diff --git a/assets/index-48a6f08c.css b/assets/index-48a6f08c.css deleted file mode 100644 index cc14a4f7bcebf97ddc0ce149e0239044abebc040..0000000000000000000000000000000000000000 --- a/assets/index-48a6f08c.css +++ /dev/null @@ -1 +0,0 @@ -#root{max-width:1280px;margin:0 auto;padding:2rem;text-align:center}.language-container{display:flex;gap:20px}.textbox-container{display:flex;justify-content:center;gap:20px;width:800px}.textbox-container>textarea{width:50%}.language-selector{width:50%}.language-selector>select{width:150px}.progress-container{position:relative;font-size:14px;color:#fff;background-color:#e9ecef;border:solid 1px;border-radius:8px;text-align:left;overflow:hidden}.progress-bar{padding:0 4px;z-index:0;top:0;width:1%;height:100%;overflow:hidden;background-color:#007bff;white-space:nowrap}.progress-text{z-index:2}.selector-container{display:flex;gap:20px}.progress-bars-container{padding:8px;height:140px}.container{margin:25px;display:flex;flex-direction:column;gap:10px}:root{font-family:Inter,system-ui,Avenir,Helvetica,Arial,sans-serif;line-height:1.5;font-weight:400;color:#213547;background-color:#fff;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-text-size-adjust:100%}body{margin:0;display:flex;place-items:center;min-width:320px;min-height:100vh}h1{font-size:3.2em;line-height:1}h1,h2{margin:8px}select{padding:.3em;cursor:pointer}textarea{padding:.6em}button{padding:.6em 1.2em;cursor:pointer;font-weight:500}button[disabled]{cursor:not-allowed}select,textarea,button{border-radius:8px;border:1px solid transparent;font-size:1em;font-family:inherit;background-color:#f9f9f9;transition:border-color .25s}select:hover,textarea:hover,button:not([disabled]):hover{border-color:#646cff}select:focus,select:focus-visible,textarea:focus,textarea:focus-visible,button:focus,button:focus-visible{outline:4px auto -webkit-focus-ring-color} diff --git a/assets/index-COWyLN3d.css b/assets/index-COWyLN3d.css new file mode 100644 index 0000000000000000000000000000000000000000..e4be19293bb0fccccd43134668dd794ad3789878 --- /dev/null +++ b/assets/index-COWyLN3d.css @@ -0,0 +1 @@ +:root{font-family:Inter,system-ui,Avenir,Helvetica,Arial,sans-serif;line-height:1.5;font-weight:400;color:#213547;background-color:#fff;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-text-size-adjust:100%}body{margin:0;display:flex;place-items:center;min-width:320px;min-height:100vh}h1{font-size:3.2em;line-height:1}h1,h2{margin:8px}select{padding:.3em;cursor:pointer}textarea{padding:.6em}button{padding:.6em 1.2em;cursor:pointer;font-weight:500}button[disabled]{cursor:not-allowed}select,textarea,button{border-radius:8px;border:1px solid transparent;font-size:1em;font-family:inherit;background-color:#f9f9f9;transition:border-color .25s}select:hover,textarea:hover,button:not([disabled]):hover{border-color:#646cff}select:focus,select:focus-visible,textarea:focus,textarea:focus-visible,button:focus,button:focus-visible{outline:4px auto -webkit-focus-ring-color}#root{max-width:1280px;margin:0 auto;padding:2rem;text-align:center}.language-container{display:flex;gap:20px}.textbox-container{display:flex;justify-content:center;gap:20px;width:800px}.textbox-container>textarea,.language-selector{width:50%}.language-selector>select{width:150px}.progress-container{position:relative;font-size:14px;color:#fff;background-color:#e9ecef;border:solid 1px;border-radius:8px;text-align:left;overflow:hidden}.progress-bar{padding:0 4px;z-index:0;top:0;width:1%;height:100%;overflow:hidden;background-color:#007bff;white-space:nowrap}.progress-text{z-index:2}.selector-container{display:flex;gap:20px}.progress-bars-container{padding:8px;height:140px}.container{margin:25px;display:flex;flex-direction:column;gap:10px} diff --git a/assets/index-DQkPzh0z.js b/assets/index-DQkPzh0z.js new file mode 100644 index 0000000000000000000000000000000000000000..fe9c8d54c9f926e3b13c492b547bef489aab4f2a --- /dev/null +++ b/assets/index-DQkPzh0z.js @@ -0,0 +1,40 @@ +(function(){const O=document.createElement("link").relList;if(O&&O.supports&&O.supports("modulepreload"))return;for(const F of document.querySelectorAll('link[rel="modulepreload"]'))se(F);new MutationObserver(F=>{for(const H of F)if(H.type==="childList")for(const ie of H.addedNodes)ie.tagName==="LINK"&&ie.rel==="modulepreload"&&se(ie)}).observe(document,{childList:!0,subtree:!0});function m(F){const H={};return F.integrity&&(H.integrity=F.integrity),F.referrerPolicy&&(H.referrerPolicy=F.referrerPolicy),F.crossOrigin==="use-credentials"?H.credentials="include":F.crossOrigin==="anonymous"?H.credentials="omit":H.credentials="same-origin",H}function se(F){if(F.ep)return;F.ep=!0;const H=m(F);fetch(F.href,H)}})();var Ei={exports:{}},gr={},Li={exports:{}},D={};/** + * @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 Ls;function Tc(){if(Ls)return D;Ls=1;var T=Symbol.for("react.element"),O=Symbol.for("react.portal"),m=Symbol.for("react.fragment"),se=Symbol.for("react.strict_mode"),F=Symbol.for("react.profiler"),H=Symbol.for("react.provider"),ie=Symbol.for("react.context"),fe=Symbol.for("react.forward_ref"),W=Symbol.for("react.suspense"),ke=Symbol.for("react.memo"),he=Symbol.for("react.lazy"),Z=Symbol.iterator;function K(f){return f===null||typeof f!="object"?null:(f=Z&&f[Z]||f["@@iterator"],typeof f=="function"?f:null)}var Te={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},de=Object.assign,G={};function M(f,v,j){this.props=f,this.context=v,this.refs=G,this.updater=j||Te}M.prototype.isReactComponent={},M.prototype.setState=function(f,v){if(typeof f!="object"&&typeof f!="function"&&f!=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,f,v,"setState")},M.prototype.forceUpdate=function(f){this.updater.enqueueForceUpdate(this,f,"forceUpdate")};function Le(){}Le.prototype=M.prototype;function ve(f,v,j){this.props=f,this.context=v,this.refs=G,this.updater=j||Te}var _e=ve.prototype=new Le;_e.constructor=ve,de(_e,M.prototype),_e.isPureReactComponent=!0;var Ce=Array.isArray,nn=Object.prototype.hasOwnProperty,Re={current:null},De={key:!0,ref:!0,__self:!0,__source:!0};function Ye(f,v,j){var I,U={},B=null,Y=null;if(v!=null)for(I in v.ref!==void 0&&(Y=v.ref),v.key!==void 0&&(B=""+v.key),v)nn.call(v,I)&&!De.hasOwnProperty(I)&&(U[I]=v[I]);var $=arguments.length-2;if($===1)U.children=j;else if(1<$){for(var b=Array($),We=0;We<$;We++)b[We]=arguments[We+2];U.children=b}if(f&&f.defaultProps)for(I in $=f.defaultProps,$)U[I]===void 0&&(U[I]=$[I]);return{$$typeof:T,type:f,key:B,ref:Y,props:U,_owner:Re.current}}function Pn(f,v){return{$$typeof:T,type:f.type,key:v,ref:f.ref,props:f.props,_owner:f._owner}}function wn(f){return typeof f=="object"&&f!==null&&f.$$typeof===T}function Yn(f){var v={"=":"=0",":":"=2"};return"$"+f.replace(/[=:]/g,function(j){return v[j]})}var cn=/\/+/g;function He(f,v){return typeof f=="object"&&f!==null&&f.key!=null?Yn(""+f.key):v.toString(36)}function tn(f,v,j,I,U){var B=typeof f;(B==="undefined"||B==="boolean")&&(f=null);var Y=!1;if(f===null)Y=!0;else switch(B){case"string":case"number":Y=!0;break;case"object":switch(f.$$typeof){case T:case O:Y=!0}}if(Y)return Y=f,U=U(Y),f=I===""?"."+He(Y,0):I,Ce(U)?(j="",f!=null&&(j=f.replace(cn,"$&/")+"/"),tn(U,v,j,"",function(We){return We})):U!=null&&(wn(U)&&(U=Pn(U,j+(!U.key||Y&&Y.key===U.key?"":(""+U.key).replace(cn,"$&/")+"/")+f)),v.push(U)),1;if(Y=0,I=I===""?".":I+":",Ce(f))for(var $=0;$>>1,v=k[f];if(0>>1;fF(U,E))BF(Y,U)?(k[f]=Y,k[B]=E,f=B):(k[f]=U,k[I]=E,f=I);else if(BF(Y,E))k[f]=Y,k[B]=E,f=B;else break e}}return z}function F(k,z){var E=k.sortIndex-z.sortIndex;return E!==0?E:k.id-z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var H=performance;T.unstable_now=function(){return H.now()}}else{var ie=Date,fe=ie.now();T.unstable_now=function(){return ie.now()-fe}}var W=[],ke=[],he=1,Z=null,K=3,Te=!1,de=!1,G=!1,M=typeof setTimeout=="function"?setTimeout:null,Le=typeof clearTimeout=="function"?clearTimeout:null,ve=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function _e(k){for(var z=m(ke);z!==null;){if(z.callback===null)se(ke);else if(z.startTime<=k)se(ke),z.sortIndex=z.expirationTime,O(W,z);else break;z=m(ke)}}function Ce(k){if(G=!1,_e(k),!de)if(m(W)!==null)de=!0,Oe(nn);else{var z=m(ke);z!==null&&le(Ce,z.startTime-k)}}function nn(k,z){de=!1,G&&(G=!1,Le(Ye),Ye=-1),Te=!0;var E=K;try{for(_e(z),Z=m(W);Z!==null&&(!(Z.expirationTime>z)||k&&!Yn());){var f=Z.callback;if(typeof f=="function"){Z.callback=null,K=Z.priorityLevel;var v=f(Z.expirationTime<=z);z=T.unstable_now(),typeof v=="function"?Z.callback=v:Z===m(W)&&se(W),_e(z)}else se(W);Z=m(W)}if(Z!==null)var j=!0;else{var I=m(ke);I!==null&&le(Ce,I.startTime-z),j=!1}return j}finally{Z=null,K=E,Te=!1}}var Re=!1,De=null,Ye=-1,Pn=5,wn=-1;function Yn(){return!(T.unstable_now()-wnk||125f?(k.sortIndex=E,O(ke,k),m(W)===null&&k===m(ke)&&(G?(Le(Ye),Ye=-1):G=!0,le(Ce,E-f))):(k.sortIndex=v,O(W,k),de||Te||(de=!0,Oe(nn))),k},T.unstable_shouldYield=Yn,T.unstable_wrapCallback=function(k){var z=K;return function(){var E=K;K=z;try{return k.apply(this,arguments)}finally{K=E}}}}(Ni)),Ni}var zs;function Dc(){return zs||(zs=1,xi.exports=jc()),xi.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 Ts;function Oc(){if(Ts)return Ve;Ts=1;var T=Pi(),O=Dc();function m(e){for(var n="https://reactjs.org/docs/error-decoder.html?invariant="+e,t=1;t"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),W=Object.prototype.hasOwnProperty,ke=/^[: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]*$/,he={},Z={};function K(e){return W.call(Z,e)?!0:W.call(he,e)?!1:ke.test(e)?Z[e]=!0:(he[e]=!0,!1)}function Te(e,n,t,r){if(t!==null&&t.type===0)return!1;switch(typeof n){case"function":case"symbol":return!0;case"boolean":return r?!1:t!==null?!t.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function de(e,n,t,r){if(n===null||typeof n>"u"||Te(e,n,t,r))return!0;if(r)return!1;if(t!==null)switch(t.type){case 3:return!n;case 4:return n===!1;case 5:return isNaN(n);case 6:return isNaN(n)||1>n}return!1}function G(e,n,t,r,l,u,i){this.acceptsBooleans=n===2||n===3||n===4,this.attributeName=r,this.attributeNamespace=l,this.mustUseProperty=t,this.propertyName=e,this.type=n,this.sanitizeURL=u,this.removeEmptyString=i}var M={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){M[e]=new G(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var n=e[0];M[n]=new G(n,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){M[e]=new G(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){M[e]=new G(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){M[e]=new G(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){M[e]=new G(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){M[e]=new G(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){M[e]=new G(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){M[e]=new G(e,5,!1,e.toLowerCase(),null,!1,!1)});var Le=/[\-:]([a-z])/g;function ve(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 n=e.replace(Le,ve);M[n]=new G(n,1,!1,e,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var n=e.replace(Le,ve);M[n]=new G(n,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(e){var n=e.replace(Le,ve);M[n]=new G(n,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){M[e]=new G(e,1,!1,e.toLowerCase(),null,!1,!1)}),M.xlinkHref=new G("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){M[e]=new G(e,1,!1,e.toLowerCase(),null,!0,!0)});function _e(e,n,t,r){var l=M.hasOwnProperty(n)?M[n]:null;(l!==null?l.type!==0:r||!(2o||l[i]!==u[o]){var a=` +`+l[i].replace(" at new "," at ");return e.displayName&&a.includes("")&&(a=a.replace("",e.displayName)),a}while(1<=i&&0<=o);break}}}finally{j=!1,Error.prepareStackTrace=t}return(e=e?e.displayName||e.name:"")?v(e):""}function U(e){switch(e.tag){case 5:return v(e.type);case 16:return v("Lazy");case 13:return v("Suspense");case 19:return v("SuspenseList");case 0:case 2:case 15:return e=I(e.type,!1),e;case 11:return e=I(e.type.render,!1),e;case 1:return e=I(e.type,!0),e;default:return""}}function B(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 De:return"Fragment";case Re:return"Portal";case Pn:return"Profiler";case Ye:return"StrictMode";case He:return"Suspense";case tn:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Yn:return(e.displayName||"Context")+".Consumer";case wn:return(e._context.displayName||"Context")+".Provider";case cn:var n=e.render;return e=e.displayName,e||(e=n.displayName||n.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case dn:return n=e.displayName||null,n!==null?n:B(e.type)||"Memo";case Oe:n=e._payload,e=e._init;try{return B(e(n))}catch{}}return null}function Y(e){var n=e.type;switch(e.tag){case 24:return"Cache";case 9:return(n.displayName||"Context")+".Consumer";case 10:return(n._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=n.render,e=e.displayName||e.name||"",n.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return n;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return B(n);case 8:return n===Ye?"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 n=="function")return n.displayName||n.name||null;if(typeof n=="string")return n}return null}function $(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function b(e){var n=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(n==="checkbox"||n==="radio")}function We(e){var n=b(e)?"checked":"value",t=Object.getOwnPropertyDescriptor(e.constructor.prototype,n),r=""+e[n];if(!e.hasOwnProperty(n)&&typeof t<"u"&&typeof t.get=="function"&&typeof t.set=="function"){var l=t.get,u=t.set;return Object.defineProperty(e,n,{configurable:!0,get:function(){return l.call(this)},set:function(i){r=""+i,u.call(this,i)}}),Object.defineProperty(e,n,{enumerable:t.enumerable}),{getValue:function(){return r},setValue:function(i){r=""+i},stopTracking:function(){e._valueTracker=null,delete e[n]}}}}function wr(e){e._valueTracker||(e._valueTracker=We(e))}function zi(e){if(!e)return!1;var n=e._valueTracker;if(!n)return!0;var t=n.getValue(),r="";return e&&(r=b(e)?e.checked?"true":"false":e.value),e=r,e!==t?(n.setValue(e),!0):!1}function kr(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 Tl(e,n){var t=n.checked;return E({},n,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:t??e._wrapperState.initialChecked})}function Ti(e,n){var t=n.defaultValue==null?"":n.defaultValue,r=n.checked!=null?n.checked:n.defaultChecked;t=$(n.value!=null?n.value:t),e._wrapperState={initialChecked:r,initialValue:t,controlled:n.type==="checkbox"||n.type==="radio"?n.checked!=null:n.value!=null}}function Ri(e,n){n=n.checked,n!=null&&_e(e,"checked",n,!1)}function Rl(e,n){Ri(e,n);var t=$(n.value),r=n.type;if(t!=null)r==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+t):e.value!==""+t&&(e.value=""+t);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}n.hasOwnProperty("value")?Ml(e,n.type,t):n.hasOwnProperty("defaultValue")&&Ml(e,n.type,$(n.defaultValue)),n.checked==null&&n.defaultChecked!=null&&(e.defaultChecked=!!n.defaultChecked)}function Mi(e,n,t){if(n.hasOwnProperty("value")||n.hasOwnProperty("defaultValue")){var r=n.type;if(!(r!=="submit"&&r!=="reset"||n.value!==void 0&&n.value!==null))return;n=""+e._wrapperState.initialValue,t||n===e.value||(e.value=n),e.defaultValue=n}t=e.name,t!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,t!==""&&(e.name=t)}function Ml(e,n,t){(n!=="number"||kr(e.ownerDocument)!==e)&&(t==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+t&&(e.defaultValue=""+t))}var jt=Array.isArray;function at(e,n,t,r){if(e=e.options,n){n={};for(var l=0;l"+n.valueOf().toString()+"",n=_r.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;n.firstChild;)e.appendChild(n.firstChild)}});function Dt(e,n){if(n){var t=e.firstChild;if(t&&t===e.lastChild&&t.nodeType===3){t.nodeValue=n;return}}e.textContent=n}var Ot={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},Ds=["Webkit","ms","Moz","O"];Object.keys(Ot).forEach(function(e){Ds.forEach(function(n){n=n+e.charAt(0).toUpperCase()+e.substring(1),Ot[n]=Ot[e]})});function Ai(e,n,t){return n==null||typeof n=="boolean"||n===""?"":t||typeof n!="number"||n===0||Ot.hasOwnProperty(e)&&Ot[e]?(""+n).trim():n+"px"}function Ui(e,n){e=e.style;for(var t in n)if(n.hasOwnProperty(t)){var r=t.indexOf("--")===0,l=Ai(t,n[t],r);t==="float"&&(t="cssFloat"),r?e.setProperty(t,l):e[t]=l}}var Os=E({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 Ol(e,n){if(n){if(Os[e]&&(n.children!=null||n.dangerouslySetInnerHTML!=null))throw Error(m(137,e));if(n.dangerouslySetInnerHTML!=null){if(n.children!=null)throw Error(m(60));if(typeof n.dangerouslySetInnerHTML!="object"||!("__html"in n.dangerouslySetInnerHTML))throw Error(m(61))}if(n.style!=null&&typeof n.style!="object")throw Error(m(62))}}function Il(e,n){if(e.indexOf("-")===-1)return typeof n.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 Fl=null;function Al(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Ul=null,st=null,ft=null;function Bi(e){if(e=rr(e)){if(typeof Ul!="function")throw Error(m(280));var n=e.stateNode;n&&(n=$r(n),Ul(e.stateNode,e.type,n))}}function Vi(e){st?ft?ft.push(e):ft=[e]:st=e}function Hi(){if(st){var e=st,n=ft;if(ft=st=null,Bi(e),n)for(e=0;e>>=0,e===0?32:31-(Ks(e)/Gs|0)|0}var xr=64,Nr=4194304;function Ut(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 Pr(e,n){var t=e.pendingLanes;if(t===0)return 0;var r=0,l=e.suspendedLanes,u=e.pingedLanes,i=t&268435455;if(i!==0){var o=i&~l;o!==0?r=Ut(o):(u&=i,u!==0&&(r=Ut(u)))}else i=t&~l,i!==0?r=Ut(i):u!==0&&(r=Ut(u));if(r===0)return 0;if(n!==0&&n!==r&&!(n&l)&&(l=r&-r,u=n&-n,l>=u||l===16&&(u&4194240)!==0))return n;if(r&4&&(r|=t&16),n=e.entangledLanes,n!==0)for(e=e.entanglements,n&=r;0t;t++)n.push(e);return n}function Bt(e,n,t){e.pendingLanes|=n,n!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,n=31-rn(n),e[n]=t}function Js(e,n){var t=e.pendingLanes&~n;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=n,e.mutableReadLanes&=n,e.entangledLanes&=n,n=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Yt),yo=" ",go=!1;function wo(e,n){switch(e){case"keyup":return xf.indexOf(n.keyCode)!==-1;case"keydown":return n.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function ko(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var pt=!1;function Pf(e,n){switch(e){case"compositionend":return ko(n);case"keypress":return n.which!==32?null:(go=!0,yo);case"textInput":return e=n.data,e===yo&&go?null:e;default:return null}}function zf(e,n){if(pt)return e==="compositionend"||!ru&&wo(e,n)?(e=fo(),jr=Jl=jn=null,pt=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(n.ctrlKey||n.altKey||n.metaKey)||n.ctrlKey&&n.altKey){if(n.char&&1=n)return{node:t,offset:n-e};e=r}e:{for(;t;){if(t.nextSibling){t=t.nextSibling;break e}t=t.parentNode}t=void 0}t=No(t)}}function zo(e,n){return e&&n?e===n?!0:e&&e.nodeType===3?!1:n&&n.nodeType===3?zo(e,n.parentNode):"contains"in e?e.contains(n):e.compareDocumentPosition?!!(e.compareDocumentPosition(n)&16):!1:!1}function To(){for(var e=window,n=kr();n instanceof e.HTMLIFrameElement;){try{var t=typeof n.contentWindow.location.href=="string"}catch{t=!1}if(t)e=n.contentWindow;else break;n=kr(e.document)}return n}function iu(e){var n=e&&e.nodeName&&e.nodeName.toLowerCase();return n&&(n==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||n==="textarea"||e.contentEditable==="true")}function Af(e){var n=To(),t=e.focusedElem,r=e.selectionRange;if(n!==t&&t&&t.ownerDocument&&zo(t.ownerDocument.documentElement,t)){if(r!==null&&iu(t)){if(n=r.start,e=r.end,e===void 0&&(e=n),"selectionStart"in t)t.selectionStart=n,t.selectionEnd=Math.min(e,t.value.length);else if(e=(n=t.ownerDocument||document)&&n.defaultView||window,e.getSelection){e=e.getSelection();var l=t.textContent.length,u=Math.min(r.start,l);r=r.end===void 0?u:Math.min(r.end,l),!e.extend&&u>r&&(l=r,r=u,u=l),l=Po(t,u);var i=Po(t,r);l&&i&&(e.rangeCount!==1||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==i.node||e.focusOffset!==i.offset)&&(n=n.createRange(),n.setStart(l.node,l.offset),e.removeAllRanges(),u>r?(e.addRange(n),e.extend(i.node,i.offset)):(n.setEnd(i.node,i.offset),e.addRange(n)))}}for(n=[],e=t;e=e.parentNode;)e.nodeType===1&&n.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof t.focus=="function"&&t.focus(),t=0;t=document.documentMode,mt=null,ou=null,qt=null,au=!1;function Ro(e,n,t){var r=t.window===t?t.document:t.nodeType===9?t:t.ownerDocument;au||mt==null||mt!==kr(r)||(r=mt,"selectionStart"in r&&iu(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),qt&&Jt(qt,r)||(qt=r,r=Vr(ou,"onSelect"),0wt||(e.current=ku[wt],ku[wt]=null,wt--)}function X(e,n){wt++,ku[wt]=e.current,e.current=n}var Fn={},xe=In(Fn),Ie=In(!1),Jn=Fn;function kt(e,n){var t=e.type.contextTypes;if(!t)return Fn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===n)return r.__reactInternalMemoizedMaskedChildContext;var l={},u;for(u in t)l[u]=n[u];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=n,e.__reactInternalMemoizedMaskedChildContext=l),l}function Fe(e){return e=e.childContextTypes,e!=null}function Qr(){q(Ie),q(xe)}function Ko(e,n,t){if(xe.current!==Fn)throw Error(m(168));X(xe,n),X(Ie,t)}function Go(e,n,t){var r=e.stateNode;if(n=n.childContextTypes,typeof r.getChildContext!="function")return t;r=r.getChildContext();for(var l in r)if(!(l in n))throw Error(m(108,Y(e)||"Unknown",l));return E({},t,r)}function Kr(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Fn,Jn=xe.current,X(xe,e),X(Ie,Ie.current),!0}function Yo(e,n,t){var r=e.stateNode;if(!r)throw Error(m(169));t?(e=Go(e,n,Jn),r.__reactInternalMemoizedMergedChildContext=e,q(Ie),q(xe),X(xe,e)):q(Ie),X(Ie,t)}var _n=null,Gr=!1,_u=!1;function Xo(e){_n===null?_n=[e]:_n.push(e)}function Zf(e){Gr=!0,Xo(e)}function An(){if(!_u&&_n!==null){_u=!0;var e=0,n=Q;try{var t=_n;for(Q=1;e>=i,l-=i,Sn=1<<32-rn(n)+l|t<R?(we=P,P=null):we=P.sibling;var V=h(c,P,d[R],w);if(V===null){P===null&&(P=we);break}e&&P&&V.alternate===null&&n(c,P),s=u(V,s,R),N===null?x=V:N.sibling=V,N=V,P=we}if(R===d.length)return t(c,P),ee&&bn(c,R),x;if(P===null){for(;RR?(we=P,P=null):we=P.sibling;var Gn=h(c,P,V.value,w);if(Gn===null){P===null&&(P=we);break}e&&P&&Gn.alternate===null&&n(c,P),s=u(Gn,s,R),N===null?x=Gn:N.sibling=Gn,N=Gn,P=we}if(V.done)return t(c,P),ee&&bn(c,R),x;if(P===null){for(;!V.done;R++,V=d.next())V=g(c,V.value,w),V!==null&&(s=u(V,s,R),N===null?x=V:N.sibling=V,N=V);return ee&&bn(c,R),x}for(P=r(c,P);!V.done;R++,V=d.next())V=_(P,c,R,V.value,w),V!==null&&(e&&V.alternate!==null&&P.delete(V.key===null?R:V.key),s=u(V,s,R),N===null?x=V:N.sibling=V,N=V);return e&&P.forEach(function(zc){return n(c,zc)}),ee&&bn(c,R),x}function ae(c,s,d,w){if(typeof d=="object"&&d!==null&&d.type===De&&d.key===null&&(d=d.props.children),typeof d=="object"&&d!==null){switch(d.$$typeof){case nn:e:{for(var x=d.key,N=s;N!==null;){if(N.key===x){if(x=d.type,x===De){if(N.tag===7){t(c,N.sibling),s=l(N,d.props.children),s.return=c,c=s;break e}}else if(N.elementType===x||typeof x=="object"&&x!==null&&x.$$typeof===Oe&&na(x)===N.type){t(c,N.sibling),s=l(N,d.props),s.ref=lr(c,N,d),s.return=c,c=s;break e}t(c,N);break}else n(c,N);N=N.sibling}d.type===De?(s=ot(d.props.children,c.mode,w,d.key),s.return=c,c=s):(w=_l(d.type,d.key,d.props,null,c.mode,w),w.ref=lr(c,s,d),w.return=c,c=w)}return i(c);case Re:e:{for(N=d.key;s!==null;){if(s.key===N)if(s.tag===4&&s.stateNode.containerInfo===d.containerInfo&&s.stateNode.implementation===d.implementation){t(c,s.sibling),s=l(s,d.children||[]),s.return=c,c=s;break e}else{t(c,s);break}else n(c,s);s=s.sibling}s=gi(d,c.mode,w),s.return=c,c=s}return i(c);case Oe:return N=d._init,ae(c,s,N(d._payload),w)}if(jt(d))return L(c,s,d,w);if(z(d))return C(c,s,d,w);Jr(c,d)}return typeof d=="string"&&d!==""||typeof d=="number"?(d=""+d,s!==null&&s.tag===6?(t(c,s.sibling),s=l(s,d),s.return=c,c=s):(t(c,s),s=yi(d,c.mode,w),s.return=c,c=s),i(c)):t(c,s)}return ae}var Lt=ta(!0),ra=ta(!1),qr=In(null),br=null,Ct=null,Nu=null;function Pu(){Nu=Ct=br=null}function zu(e){var n=qr.current;q(qr),e._currentValue=n}function Tu(e,n,t){for(;e!==null;){var r=e.alternate;if((e.childLanes&n)!==n?(e.childLanes|=n,r!==null&&(r.childLanes|=n)):r!==null&&(r.childLanes&n)!==n&&(r.childLanes|=n),e===t)break;e=e.return}}function xt(e,n){br=e,Nu=Ct=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&n&&(Ae=!0),e.firstContext=null)}function Je(e){var n=e._currentValue;if(Nu!==e)if(e={context:e,memoizedValue:n,next:null},Ct===null){if(br===null)throw Error(m(308));Ct=e,br.dependencies={lanes:0,firstContext:e}}else Ct=Ct.next=e;return n}var et=null;function Ru(e){et===null?et=[e]:et.push(e)}function la(e,n,t,r){var l=n.interleaved;return l===null?(t.next=t,Ru(n)):(t.next=l.next,l.next=t),n.interleaved=t,Ln(e,r)}function Ln(e,n){e.lanes|=n;var t=e.alternate;for(t!==null&&(t.lanes|=n),t=e,e=e.return;e!==null;)e.childLanes|=n,t=e.alternate,t!==null&&(t.childLanes|=n),t=e,e=e.return;return t.tag===3?t.stateNode:null}var Un=!1;function Mu(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function ua(e,n){e=e.updateQueue,n.updateQueue===e&&(n.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Cn(e,n){return{eventTime:e,lane:n,tag:0,payload:null,callback:null,next:null}}function Bn(e,n,t){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,A&2){var l=r.pending;return l===null?n.next=n:(n.next=l.next,l.next=n),r.pending=n,Ln(e,t)}return l=r.interleaved,l===null?(n.next=n,Ru(r)):(n.next=l.next,l.next=n),r.interleaved=n,Ln(e,t)}function el(e,n,t){if(n=n.updateQueue,n!==null&&(n=n.shared,(t&4194240)!==0)){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,Kl(e,t)}}function ia(e,n){var t=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,t===r)){var l=null,u=null;if(t=t.firstBaseUpdate,t!==null){do{var i={eventTime:t.eventTime,lane:t.lane,tag:t.tag,payload:t.payload,callback:t.callback,next:null};u===null?l=u=i:u=u.next=i,t=t.next}while(t!==null);u===null?l=u=n:u=u.next=n}else l=u=n;t={baseState:r.baseState,firstBaseUpdate:l,lastBaseUpdate:u,shared:r.shared,effects:r.effects},e.updateQueue=t;return}e=t.lastBaseUpdate,e===null?t.firstBaseUpdate=n:e.next=n,t.lastBaseUpdate=n}function nl(e,n,t,r){var l=e.updateQueue;Un=!1;var u=l.firstBaseUpdate,i=l.lastBaseUpdate,o=l.shared.pending;if(o!==null){l.shared.pending=null;var a=o,p=a.next;a.next=null,i===null?u=p:i.next=p,i=a;var y=e.alternate;y!==null&&(y=y.updateQueue,o=y.lastBaseUpdate,o!==i&&(o===null?y.firstBaseUpdate=p:o.next=p,y.lastBaseUpdate=a))}if(u!==null){var g=l.baseState;i=0,y=p=a=null,o=u;do{var h=o.lane,_=o.eventTime;if((r&h)===h){y!==null&&(y=y.next={eventTime:_,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var L=e,C=o;switch(h=n,_=t,C.tag){case 1:if(L=C.payload,typeof L=="function"){g=L.call(_,g,h);break e}g=L;break e;case 3:L.flags=L.flags&-65537|128;case 0:if(L=C.payload,h=typeof L=="function"?L.call(_,g,h):L,h==null)break e;g=E({},g,h);break e;case 2:Un=!0}}o.callback!==null&&o.lane!==0&&(e.flags|=64,h=l.effects,h===null?l.effects=[o]:h.push(o))}else _={eventTime:_,lane:h,tag:o.tag,payload:o.payload,callback:o.callback,next:null},y===null?(p=y=_,a=g):y=y.next=_,i|=h;if(o=o.next,o===null){if(o=l.shared.pending,o===null)break;h=o,o=h.next,h.next=null,l.lastBaseUpdate=h,l.shared.pending=null}}while(!0);if(y===null&&(a=g),l.baseState=a,l.firstBaseUpdate=p,l.lastBaseUpdate=y,n=l.shared.interleaved,n!==null){l=n;do i|=l.lane,l=l.next;while(l!==n)}else u===null&&(l.shared.lanes=0);rt|=i,e.lanes=i,e.memoizedState=g}}function oa(e,n,t){if(e=n.effects,n.effects=null,e!==null)for(n=0;nt?t:4,e(!0);var r=Fu.transition;Fu.transition={};try{e(!1),n()}finally{Q=t,Fu.transition=r}}function xa(){return qe().memoizedState}function ec(e,n,t){var r=$n(e);if(t={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null},Na(e))Pa(n,t);else if(t=la(e,n,t,r),t!==null){var l=je();fn(t,e,r,l),za(t,n,r)}}function nc(e,n,t){var r=$n(e),l={lane:r,action:t,hasEagerState:!1,eagerState:null,next:null};if(Na(e))Pa(n,l);else{var u=e.alternate;if(e.lanes===0&&(u===null||u.lanes===0)&&(u=n.lastRenderedReducer,u!==null))try{var i=n.lastRenderedState,o=u(i,t);if(l.hasEagerState=!0,l.eagerState=o,ln(o,i)){var a=n.interleaved;a===null?(l.next=l,Ru(n)):(l.next=a.next,a.next=l),n.interleaved=l;return}}catch{}finally{}t=la(e,n,l,r),t!==null&&(l=je(),fn(t,e,r,l),za(t,n,r))}}function Na(e){var n=e.alternate;return e===re||n!==null&&n===re}function Pa(e,n){ar=ll=!0;var t=e.pending;t===null?n.next=n:(n.next=t.next,t.next=n),e.pending=n}function za(e,n,t){if(t&4194240){var r=n.lanes;r&=e.pendingLanes,t|=r,n.lanes=t,Kl(e,t)}}var ol={readContext:Je,useCallback:Ne,useContext:Ne,useEffect:Ne,useImperativeHandle:Ne,useInsertionEffect:Ne,useLayoutEffect:Ne,useMemo:Ne,useReducer:Ne,useRef:Ne,useState:Ne,useDebugValue:Ne,useDeferredValue:Ne,useTransition:Ne,useMutableSource:Ne,useSyncExternalStore:Ne,useId:Ne,unstable_isNewReconciler:!1},tc={readContext:Je,useCallback:function(e,n){return vn().memoizedState=[e,n===void 0?null:n],e},useContext:Je,useEffect:ga,useImperativeHandle:function(e,n,t){return t=t!=null?t.concat([e]):null,ul(4194308,4,_a.bind(null,n,e),t)},useLayoutEffect:function(e,n){return ul(4194308,4,e,n)},useInsertionEffect:function(e,n){return ul(4,2,e,n)},useMemo:function(e,n){var t=vn();return n=n===void 0?null:n,e=e(),t.memoizedState=[e,n],e},useReducer:function(e,n,t){var r=vn();return n=t!==void 0?t(n):n,r.memoizedState=r.baseState=n,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:n},r.queue=e,e=e.dispatch=ec.bind(null,re,e),[r.memoizedState,e]},useRef:function(e){var n=vn();return e={current:e},n.memoizedState=e},useState:va,useDebugValue:$u,useDeferredValue:function(e){return vn().memoizedState=e},useTransition:function(){var e=va(!1),n=e[0];return e=bf.bind(null,e[1]),vn().memoizedState=e,[n,e]},useMutableSource:function(){},useSyncExternalStore:function(e,n,t){var r=re,l=vn();if(ee){if(t===void 0)throw Error(m(407));t=t()}else{if(t=n(),ge===null)throw Error(m(349));tt&30||ca(r,n,t)}l.memoizedState=t;var u={value:t,getSnapshot:n};return l.queue=u,ga(pa.bind(null,r,u,e),[e]),r.flags|=2048,cr(9,da.bind(null,r,u,t,n),void 0,null),t},useId:function(){var e=vn(),n=ge.identifierPrefix;if(ee){var t=En,r=Sn;t=(r&~(1<<32-rn(r)-1)).toString(32)+t,n=":"+n+"R"+t,t=sr++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=i.createElement(t,{is:r.is}):(e=i.createElement(t),t==="select"&&(i=e,r.multiple?i.multiple=!0:r.size&&(i.size=r.size))):e=i.createElementNS(e,t),e[mn]=n,e[tr]=r,Xa(e,n,!1,!1),n.stateNode=e;e:{switch(i=Il(t,r),t){case"dialog":J("cancel",e),J("close",e),l=r;break;case"iframe":case"object":case"embed":J("load",e),l=r;break;case"video":case"audio":for(l=0;lRt&&(n.flags|=128,r=!0,dr(u,!1),n.lanes=4194304)}else{if(!r)if(e=tl(i),e!==null){if(n.flags|=128,r=!0,t=e.updateQueue,t!==null&&(n.updateQueue=t,n.flags|=4),dr(u,!0),u.tail===null&&u.tailMode==="hidden"&&!i.alternate&&!ee)return Pe(n),null}else 2*oe()-u.renderingStartTime>Rt&&t!==1073741824&&(n.flags|=128,r=!0,dr(u,!1),n.lanes=4194304);u.isBackwards?(i.sibling=n.child,n.child=i):(t=u.last,t!==null?t.sibling=i:n.child=i,u.last=i)}return u.tail!==null?(n=u.tail,u.rendering=n,u.tail=n.sibling,u.renderingStartTime=oe(),n.sibling=null,t=te.current,X(te,r?t&1|2:t&1),n):(Pe(n),null);case 22:case 23:return mi(),r=n.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(n.flags|=8192),r&&n.mode&1?Ge&1073741824&&(Pe(n),n.subtreeFlags&6&&(n.flags|=8192)):Pe(n),null;case 24:return null;case 25:return null}throw Error(m(156,n.tag))}function fc(e,n){switch(Eu(n),n.tag){case 1:return Fe(n.type)&&Qr(),e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 3:return Nt(),q(Ie),q(xe),Iu(),e=n.flags,e&65536&&!(e&128)?(n.flags=e&-65537|128,n):null;case 5:return Du(n),null;case 13:if(q(te),e=n.memoizedState,e!==null&&e.dehydrated!==null){if(n.alternate===null)throw Error(m(340));Et()}return e=n.flags,e&65536?(n.flags=e&-65537|128,n):null;case 19:return q(te),null;case 4:return Nt(),null;case 10:return zu(n.type._context),null;case 22:case 23:return mi(),null;case 24:return null;default:return null}}var cl=!1,ze=!1,cc=typeof WeakSet=="function"?WeakSet:Set,S=null;function zt(e,n){var t=e.ref;if(t!==null)if(typeof t=="function")try{t(null)}catch(r){ue(e,n,r)}else t.current=null}function ti(e,n,t){try{t()}catch(r){ue(e,n,r)}}var qa=!1;function dc(e,n){if(mu=Rr,e=To(),iu(e)){if("selectionStart"in e)var t={start:e.selectionStart,end:e.selectionEnd};else e:{t=(t=e.ownerDocument)&&t.defaultView||window;var r=t.getSelection&&t.getSelection();if(r&&r.rangeCount!==0){t=r.anchorNode;var l=r.anchorOffset,u=r.focusNode;r=r.focusOffset;try{t.nodeType,u.nodeType}catch{t=null;break e}var i=0,o=-1,a=-1,p=0,y=0,g=e,h=null;n:for(;;){for(var _;g!==t||l!==0&&g.nodeType!==3||(o=i+l),g!==u||r!==0&&g.nodeType!==3||(a=i+r),g.nodeType===3&&(i+=g.nodeValue.length),(_=g.firstChild)!==null;)h=g,g=_;for(;;){if(g===e)break n;if(h===t&&++p===l&&(o=i),h===u&&++y===r&&(a=i),(_=g.nextSibling)!==null)break;g=h,h=g.parentNode}g=_}t=o===-1||a===-1?null:{start:o,end:a}}else t=null}t=t||{start:0,end:0}}else t=null;for(hu={focusedElem:e,selectionRange:t},Rr=!1,S=n;S!==null;)if(n=S,e=n.child,(n.subtreeFlags&1028)!==0&&e!==null)e.return=n,S=e;else for(;S!==null;){n=S;try{var L=n.alternate;if(n.flags&1024)switch(n.tag){case 0:case 11:case 15:break;case 1:if(L!==null){var C=L.memoizedProps,ae=L.memoizedState,c=n.stateNode,s=c.getSnapshotBeforeUpdate(n.elementType===n.type?C:on(n.type,C),ae);c.__reactInternalSnapshotBeforeUpdate=s}break;case 3:var d=n.stateNode.containerInfo;d.nodeType===1?d.textContent="":d.nodeType===9&&d.documentElement&&d.removeChild(d.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(m(163))}}catch(w){ue(n,n.return,w)}if(e=n.sibling,e!==null){e.return=n.return,S=e;break}S=n.return}return L=qa,qa=!1,L}function pr(e,n,t){var r=n.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var l=r=r.next;do{if((l.tag&e)===e){var u=l.destroy;l.destroy=void 0,u!==void 0&&ti(n,t,u)}l=l.next}while(l!==r)}}function dl(e,n){if(n=n.updateQueue,n=n!==null?n.lastEffect:null,n!==null){var t=n=n.next;do{if((t.tag&e)===e){var r=t.create;t.destroy=r()}t=t.next}while(t!==n)}}function ri(e){var n=e.ref;if(n!==null){var t=e.stateNode;switch(e.tag){case 5:e=t;break;default:e=t}typeof n=="function"?n(e):n.current=e}}function ba(e){var n=e.alternate;n!==null&&(e.alternate=null,ba(n)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(n=e.stateNode,n!==null&&(delete n[mn],delete n[tr],delete n[wu],delete n[Yf],delete n[Xf])),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 es(e){return e.tag===5||e.tag===3||e.tag===4}function ns(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||es(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 li(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?t.nodeType===8?t.parentNode.insertBefore(e,n):t.insertBefore(e,n):(t.nodeType===8?(n=t.parentNode,n.insertBefore(e,t)):(n=t,n.appendChild(e)),t=t._reactRootContainer,t!=null||n.onclick!==null||(n.onclick=Wr));else if(r!==4&&(e=e.child,e!==null))for(li(e,n,t),e=e.sibling;e!==null;)li(e,n,t),e=e.sibling}function ui(e,n,t){var r=e.tag;if(r===5||r===6)e=e.stateNode,n?t.insertBefore(e,n):t.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(ui(e,n,t),e=e.sibling;e!==null;)ui(e,n,t),e=e.sibling}var Se=null,an=!1;function Vn(e,n,t){for(t=t.child;t!==null;)ts(e,n,t),t=t.sibling}function ts(e,n,t){if(pn&&typeof pn.onCommitFiberUnmount=="function")try{pn.onCommitFiberUnmount(Cr,t)}catch{}switch(t.tag){case 5:ze||zt(t,n);case 6:var r=Se,l=an;Se=null,Vn(e,n,t),Se=r,an=l,Se!==null&&(an?(e=Se,t=t.stateNode,e.nodeType===8?e.parentNode.removeChild(t):e.removeChild(t)):Se.removeChild(t.stateNode));break;case 18:Se!==null&&(an?(e=Se,t=t.stateNode,e.nodeType===8?gu(e.parentNode,t):e.nodeType===1&&gu(e,t),Qt(e)):gu(Se,t.stateNode));break;case 4:r=Se,l=an,Se=t.stateNode.containerInfo,an=!0,Vn(e,n,t),Se=r,an=l;break;case 0:case 11:case 14:case 15:if(!ze&&(r=t.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){l=r=r.next;do{var u=l,i=u.destroy;u=u.tag,i!==void 0&&(u&2||u&4)&&ti(t,n,i),l=l.next}while(l!==r)}Vn(e,n,t);break;case 1:if(!ze&&(zt(t,n),r=t.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=t.memoizedProps,r.state=t.memoizedState,r.componentWillUnmount()}catch(o){ue(t,n,o)}Vn(e,n,t);break;case 21:Vn(e,n,t);break;case 22:t.mode&1?(ze=(r=ze)||t.memoizedState!==null,Vn(e,n,t),ze=r):Vn(e,n,t);break;default:Vn(e,n,t)}}function rs(e){var n=e.updateQueue;if(n!==null){e.updateQueue=null;var t=e.stateNode;t===null&&(t=e.stateNode=new cc),n.forEach(function(r){var l=_c.bind(null,e,r);t.has(r)||(t.add(r),r.then(l,l))})}}function sn(e,n){var t=n.deletions;if(t!==null)for(var r=0;rl&&(l=i),r&=~u}if(r=l,r=oe()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*mc(r/1960))-r,10e?16:e,Wn===null)var r=!1;else{if(e=Wn,Wn=null,yl=0,A&6)throw Error(m(331));var l=A;for(A|=4,S=e.current;S!==null;){var u=S,i=u.child;if(S.flags&16){var o=u.deletions;if(o!==null){for(var a=0;aoe()-ai?ut(e,0):oi|=t),Be(e,n)}function vs(e,n){n===0&&(e.mode&1?(n=Nr,Nr<<=1,!(Nr&130023424)&&(Nr=4194304)):n=1);var t=je();e=Ln(e,n),e!==null&&(Bt(e,n,t),Be(e,t))}function kc(e){var n=e.memoizedState,t=0;n!==null&&(t=n.retryLane),vs(e,t)}function _c(e,n){var t=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;l!==null&&(t=l.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(m(314))}r!==null&&r.delete(n),vs(e,t)}var ys;ys=function(e,n,t){if(e!==null)if(e.memoizedProps!==n.pendingProps||Ie.current)Ae=!0;else{if(!(e.lanes&t)&&!(n.flags&128))return Ae=!1,ac(e,n,t);Ae=!!(e.flags&131072)}else Ae=!1,ee&&n.flags&1048576&&Zo(n,Xr,n.index);switch(n.lanes=0,n.tag){case 2:var r=n.type;fl(e,n),e=n.pendingProps;var l=kt(n,xe.current);xt(n,t),l=Uu(null,n,r,e,l,t);var u=Bu();return n.flags|=1,typeof l=="object"&&l!==null&&typeof l.render=="function"&&l.$$typeof===void 0?(n.tag=1,n.memoizedState=null,n.updateQueue=null,Fe(r)?(u=!0,Kr(n)):u=!1,n.memoizedState=l.state!==null&&l.state!==void 0?l.state:null,Mu(n),l.updater=al,n.stateNode=l,l._reactInternals=n,Ku(n,r,e,t),n=Zu(null,n,r,!0,u,t)):(n.tag=0,ee&&u&&Su(n),Me(null,n,l,t),n=n.child),n;case 16:r=n.elementType;e:{switch(fl(e,n),e=n.pendingProps,l=r._init,r=l(r._payload),n.type=r,l=n.tag=Ec(r),e=on(r,e),l){case 0:n=Xu(null,n,r,e,t);break e;case 1:n=Wa(null,n,r,e,t);break e;case 11:n=Aa(null,n,r,e,t);break e;case 14:n=Ua(null,n,r,on(r.type,e),t);break e}throw Error(m(306,r,""))}return n;case 0:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:on(r,l),Xu(e,n,r,l,t);case 1:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:on(r,l),Wa(e,n,r,l,t);case 3:e:{if($a(n),e===null)throw Error(m(387));r=n.pendingProps,u=n.memoizedState,l=u.element,ua(e,n),nl(n,r,null,t);var i=n.memoizedState;if(r=i.element,u.isDehydrated)if(u={element:r,isDehydrated:!1,cache:i.cache,pendingSuspenseBoundaries:i.pendingSuspenseBoundaries,transitions:i.transitions},n.updateQueue.baseState=u,n.memoizedState=u,n.flags&256){l=Pt(Error(m(423)),n),n=Qa(e,n,r,t,l);break e}else if(r!==l){l=Pt(Error(m(424)),n),n=Qa(e,n,r,t,l);break e}else for(Ke=On(n.stateNode.containerInfo.firstChild),Qe=n,ee=!0,un=null,t=ra(n,null,r,t),n.child=t;t;)t.flags=t.flags&-3|4096,t=t.sibling;else{if(Et(),r===l){n=xn(e,n,t);break e}Me(e,n,r,t)}n=n.child}return n;case 5:return aa(n),e===null&&Cu(n),r=n.type,l=n.pendingProps,u=e!==null?e.memoizedProps:null,i=l.children,vu(r,l)?i=null:u!==null&&vu(r,u)&&(n.flags|=32),Ha(e,n),Me(e,n,i,t),n.child;case 6:return e===null&&Cu(n),null;case 13:return Ka(e,n,t);case 4:return ju(n,n.stateNode.containerInfo),r=n.pendingProps,e===null?n.child=Lt(n,null,r,t):Me(e,n,r,t),n.child;case 11:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:on(r,l),Aa(e,n,r,l,t);case 7:return Me(e,n,n.pendingProps,t),n.child;case 8:return Me(e,n,n.pendingProps.children,t),n.child;case 12:return Me(e,n,n.pendingProps.children,t),n.child;case 10:e:{if(r=n.type._context,l=n.pendingProps,u=n.memoizedProps,i=l.value,X(qr,r._currentValue),r._currentValue=i,u!==null)if(ln(u.value,i)){if(u.children===l.children&&!Ie.current){n=xn(e,n,t);break e}}else for(u=n.child,u!==null&&(u.return=n);u!==null;){var o=u.dependencies;if(o!==null){i=u.child;for(var a=o.firstContext;a!==null;){if(a.context===r){if(u.tag===1){a=Cn(-1,t&-t),a.tag=2;var p=u.updateQueue;if(p!==null){p=p.shared;var y=p.pending;y===null?a.next=a:(a.next=y.next,y.next=a),p.pending=a}}u.lanes|=t,a=u.alternate,a!==null&&(a.lanes|=t),Tu(u.return,t,n),o.lanes|=t;break}a=a.next}}else if(u.tag===10)i=u.type===n.type?null:u.child;else if(u.tag===18){if(i=u.return,i===null)throw Error(m(341));i.lanes|=t,o=i.alternate,o!==null&&(o.lanes|=t),Tu(i,t,n),i=u.sibling}else i=u.child;if(i!==null)i.return=u;else for(i=u;i!==null;){if(i===n){i=null;break}if(u=i.sibling,u!==null){u.return=i.return,i=u;break}i=i.return}u=i}Me(e,n,l.children,t),n=n.child}return n;case 9:return l=n.type,r=n.pendingProps.children,xt(n,t),l=Je(l),r=r(l),n.flags|=1,Me(e,n,r,t),n.child;case 14:return r=n.type,l=on(r,n.pendingProps),l=on(r.type,l),Ua(e,n,r,l,t);case 15:return Ba(e,n,n.type,n.pendingProps,t);case 17:return r=n.type,l=n.pendingProps,l=n.elementType===r?l:on(r,l),fl(e,n),n.tag=1,Fe(r)?(e=!0,Kr(n)):e=!1,xt(n,t),Ra(n,r,l),Ku(n,r,l,t),Zu(null,n,r,!0,e,t);case 19:return Ya(e,n,t);case 22:return Va(e,n,t)}throw Error(m(156,n.tag))};function gs(e,n){return Zi(e,n)}function Sc(e,n,t,r){this.tag=e,this.key=t,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=n,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function en(e,n,t,r){return new Sc(e,n,t,r)}function vi(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Ec(e){if(typeof e=="function")return vi(e)?1:0;if(e!=null){if(e=e.$$typeof,e===cn)return 11;if(e===dn)return 14}return 2}function Kn(e,n){var t=e.alternate;return t===null?(t=en(e.tag,n,e.key,e.mode),t.elementType=e.elementType,t.type=e.type,t.stateNode=e.stateNode,t.alternate=e,e.alternate=t):(t.pendingProps=n,t.type=e.type,t.flags=0,t.subtreeFlags=0,t.deletions=null),t.flags=e.flags&14680064,t.childLanes=e.childLanes,t.lanes=e.lanes,t.child=e.child,t.memoizedProps=e.memoizedProps,t.memoizedState=e.memoizedState,t.updateQueue=e.updateQueue,n=e.dependencies,t.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext},t.sibling=e.sibling,t.index=e.index,t.ref=e.ref,t}function _l(e,n,t,r,l,u){var i=2;if(r=e,typeof e=="function")vi(e)&&(i=1);else if(typeof e=="string")i=5;else e:switch(e){case De:return ot(t.children,l,u,n);case Ye:i=8,l|=8;break;case Pn:return e=en(12,t,n,l|2),e.elementType=Pn,e.lanes=u,e;case He:return e=en(13,t,n,l),e.elementType=He,e.lanes=u,e;case tn:return e=en(19,t,n,l),e.elementType=tn,e.lanes=u,e;case le:return Sl(t,l,u,n);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case wn:i=10;break e;case Yn:i=9;break e;case cn:i=11;break e;case dn:i=14;break e;case Oe:i=16,r=null;break e}throw Error(m(130,e==null?e:typeof e,""))}return n=en(i,t,n,l),n.elementType=e,n.type=r,n.lanes=u,n}function ot(e,n,t,r){return e=en(7,e,r,n),e.lanes=t,e}function Sl(e,n,t,r){return e=en(22,e,r,n),e.elementType=le,e.lanes=t,e.stateNode={isHidden:!1},e}function yi(e,n,t){return e=en(6,e,null,n),e.lanes=t,e}function gi(e,n,t){return n=en(4,e.children!==null?e.children:[],e.key,n),n.lanes=t,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function Lc(e,n,t,r,l){this.tag=n,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=Ql(0),this.expirationTimes=Ql(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ql(0),this.identifierPrefix=r,this.onRecoverableError=l,this.mutableSourceEagerHydrationData=null}function wi(e,n,t,r,l,u,i,o,a){return e=new Lc(e,n,t,o,a),n===1?(n=1,u===!0&&(n|=8)):n=0,u=en(3,null,null,n),e.current=u,u.stateNode=e,u.memoizedState={element:r,isDehydrated:t,cache:null,transitions:null,pendingSuspenseBoundaries:null},Mu(u),e}function Cc(e,n,t){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(T)}catch(O){console.error(O)}}return T(),Ci.exports=Oc(),Ci.exports}var Ms;function Fc(){if(Ms)return zl;Ms=1;var T=Ic();return zl.createRoot=T.createRoot,zl.hydrateRoot=T.hydrateRoot,zl}var Ac=Fc();const Uc={"Acehnese (Arabic script)":"ace_Arab","Acehnese (Latin script)":"ace_Latn",Afrikaans:"afr_Latn",Akan:"aka_Latn",Amharic:"amh_Ethi",Armenian:"hye_Armn",Assamese:"asm_Beng",Asturian:"ast_Latn",Awadhi:"awa_Deva","Ayacucho Quechua":"quy_Latn",Balinese:"ban_Latn",Bambara:"bam_Latn","Banjar (Arabic script)":"bjn_Arab","Banjar (Latin script)":"bjn_Latn",Bashkir:"bak_Cyrl",Basque:"eus_Latn",Belarusian:"bel_Cyrl",Bemba:"bem_Latn",Bengali:"ben_Beng",Bhojpuri:"bho_Deva",Bosnian:"bos_Latn",Buginese:"bug_Latn",Bulgarian:"bul_Cyrl",Burmese:"mya_Mymr",Catalan:"cat_Latn",Cebuano:"ceb_Latn","Central Atlas Tamazight":"tzm_Tfng","Central Aymara":"ayr_Latn","Central Kanuri (Arabic script)":"knc_Arab","Central Kanuri (Latin script)":"knc_Latn","Central Kurdish":"ckb_Arab",Chhattisgarhi:"hne_Deva","Chinese (Simplified)":"zho_Hans","Chinese (Traditional)":"zho_Hant",Chokwe:"cjk_Latn","Crimean Tatar":"crh_Latn",Croatian:"hrv_Latn",Czech:"ces_Latn",Danish:"dan_Latn",Dari:"prs_Arab",Dutch:"nld_Latn",Dyula:"dyu_Latn",Dzongkha:"dzo_Tibt","Eastern Panjabi":"pan_Guru","Eastern Yiddish":"ydd_Hebr","Egyptian Arabic":"arz_Arab",English:"eng_Latn",Esperanto:"epo_Latn",Estonian:"est_Latn",Ewe:"ewe_Latn",Faroese:"fao_Latn",Fijian:"fij_Latn",Finnish:"fin_Latn",Fon:"fon_Latn",French:"fra_Latn",Friulian:"fur_Latn",Galician:"glg_Latn",Ganda:"lug_Latn",Georgian:"kat_Geor",German:"deu_Latn",Greek:"ell_Grek",Guarani:"grn_Latn",Gujarati:"guj_Gujr","Haitian Creole":"hat_Latn","Halh Mongolian":"khk_Cyrl",Hausa:"hau_Latn",Hebrew:"heb_Hebr",Hindi:"hin_Deva",Hungarian:"hun_Latn",Icelandic:"isl_Latn",Igbo:"ibo_Latn",Ilocano:"ilo_Latn",Indonesian:"ind_Latn",Irish:"gle_Latn",Italian:"ita_Latn",Japanese:"jpn_Jpan",Javanese:"jav_Latn",Jingpho:"kac_Latn",Kabiyè:"kbp_Latn",Kabuverdianu:"kea_Latn",Kabyle:"kab_Latn",Kamba:"kam_Latn",Kannada:"kan_Knda","Kashmiri (Arabic script)":"kas_Arab","Kashmiri (Devanagari script)":"kas_Deva",Kazakh:"kaz_Cyrl",Khmer:"khm_Khmr",Kikongo:"kon_Latn",Kikuyu:"kik_Latn",Kimbundu:"kmb_Latn",Kinyarwanda:"kin_Latn",Korean:"kor_Hang",Kyrgyz:"kir_Cyrl",Lao:"lao_Laoo",Latgalian:"ltg_Latn",Ligurian:"lij_Latn",Limburgish:"lim_Latn",Lingala:"lin_Latn",Lithuanian:"lit_Latn",Lombard:"lmo_Latn","Luba-Kasai":"lua_Latn",Luo:"luo_Latn",Luxembourgish:"ltz_Latn",Macedonian:"mkd_Cyrl",Magahi:"mag_Deva",Maithili:"mai_Deva",Malayalam:"mal_Mlym",Maltese:"mlt_Latn",Maori:"mri_Latn",Marathi:"mar_Deva","Meitei (Bengali script)":"mni_Beng","Mesopotamian Arabic":"acm_Arab","Minangkabau (Arabic script)":"min_Arab","Minangkabau (Latin script)":"min_Latn",Mizo:"lus_Latn","Modern Standard Arabic (Romanized)":"arb_Latn","Modern Standard Arabic":"arb_Arab","Moroccan Arabic":"ary_Arab",Mossi:"mos_Latn","Najdi Arabic":"ars_Arab",Nepali:"npi_Deva","Nigerian Fulfulde":"fuv_Latn","North Azerbaijani":"azj_Latn","North Levantine Arabic":"apc_Arab","Northern Kurdish":"kmr_Latn","Northern Sotho":"nso_Latn","Northern Uzbek":"uzn_Latn","Norwegian Bokmål":"nob_Latn","Norwegian Nynorsk":"nno_Latn",Nuer:"nus_Latn",Nyanja:"nya_Latn",Occitan:"oci_Latn",Odia:"ory_Orya",Pangasinan:"pag_Latn",Papiamento:"pap_Latn","Plateau Malagasy":"plt_Latn",Polish:"pol_Latn",Portuguese:"por_Latn",Romanian:"ron_Latn",Rundi:"run_Latn",Russian:"rus_Cyrl",Samoan:"smo_Latn",Sango:"sag_Latn",Sanskrit:"san_Deva",Santali:"sat_Olck",Sardinian:"srd_Latn","Scottish Gaelic":"gla_Latn",Serbian:"srp_Cyrl",Shan:"shn_Mymr",Shona:"sna_Latn",Sicilian:"scn_Latn",Silesian:"szl_Latn",Sindhi:"snd_Arab",Sinhala:"sin_Sinh",Slovak:"slk_Latn",Slovenian:"slv_Latn",Somali:"som_Latn","South Azerbaijani":"azb_Arab","South Levantine Arabic":"ajp_Arab","Southern Pashto":"pbt_Arab","Southern Sotho":"sot_Latn","Southwestern Dinka":"dik_Latn",Spanish:"spa_Latn","Standard Latvian":"lvs_Latn","Standard Malay":"zsm_Latn","Standard Tibetan":"bod_Tibt",Sundanese:"sun_Latn",Swahili:"swh_Latn",Swati:"ssw_Latn",Swedish:"swe_Latn",Tagalog:"tgl_Latn",Tajik:"tgk_Cyrl","Tamasheq (Latin script)":"taq_Latn","Tamasheq (Tifinagh script)":"taq_Tfng",Tamil:"tam_Taml",Tatar:"tat_Cyrl","Ta’izzi-Adeni Arabic":"acq_Arab",Telugu:"tel_Telu",Thai:"tha_Thai",Tigrinya:"tir_Ethi","Tok Pisin":"tpi_Latn","Tosk Albanian":"als_Latn",Tsonga:"tso_Latn",Tswana:"tsn_Latn",Tumbuka:"tum_Latn","Tunisian Arabic":"aeb_Arab",Turkish:"tur_Latn",Turkmen:"tuk_Latn",Twi:"twi_Latn",Ukrainian:"ukr_Cyrl",Umbundu:"umb_Latn",Urdu:"urd_Arab",Uyghur:"uig_Arab",Venetian:"vec_Latn",Vietnamese:"vie_Latn",Waray:"war_Latn",Welsh:"cym_Latn","West Central Oromo":"gaz_Latn","Western Persian":"pes_Arab",Wolof:"wol_Latn",Xhosa:"xho_Latn",Yoruba:"yor_Latn","Yue Chinese":"yue_Hant",Zulu:"zul_Latn"};function js({type:T,onChange:O,defaultLanguage:m}){return ne.jsxs("div",{className:"language-selector",children:[ne.jsxs("label",{children:[T,": "]}),ne.jsx("select",{onChange:O,defaultValue:m,children:Object.entries(Uc).map(([se,F])=>ne.jsx("option",{value:F,children:se},se))})]})}function Bc({text:T,percentage:O}){return O=O??0,ne.jsx("div",{className:"progress-container",children:ne.jsxs("div",{className:"progress-bar",style:{width:`${O}%`},children:[T," (",`${O.toFixed(2)}%`,")"]})})}function Vc(){const[T,O]=gn.useState(null),[m,se]=gn.useState(!1),[F,H]=gn.useState([]),[ie,fe]=gn.useState("I love walking my dog."),[W,ke]=gn.useState("eng_Latn"),[he,Z]=gn.useState("fra_Latn"),[K,Te]=gn.useState(""),de=gn.useRef(null);gn.useEffect(()=>{de.current??(de.current=new Worker(new URL("/assets/worker-CMOjGuql.js",import.meta.url),{type:"module"}));const M=Le=>{switch(Le.data.status){case"initiate":O(!1),H(ve=>[...ve,Le.data]);break;case"progress":H(ve=>ve.map(_e=>_e.file===Le.data.file?{..._e,progress:Le.data.progress}:_e));break;case"done":H(ve=>ve.filter(_e=>_e.file!==Le.data.file));break;case"ready":O(!0);break;case"update":Te(ve=>ve+Le.data.output);break;case"complete":se(!1);break}};return de.current.addEventListener("message",M),()=>de.current.removeEventListener("message",M)});const G=()=>{se(!0),Te(""),de.current.postMessage({text:ie,src_lang:W,tgt_lang:he})};return ne.jsxs(ne.Fragment,{children:[ne.jsx("h1",{children:"Transformers.js"}),ne.jsx("h2",{children:"ML-powered multilingual translation in React!"}),ne.jsxs("div",{className:"container",children:[ne.jsxs("div",{className:"language-container",children:[ne.jsx(js,{type:"Source",defaultLanguage:"eng_Latn",onChange:M=>ke(M.target.value)}),ne.jsx(js,{type:"Target",defaultLanguage:"fra_Latn",onChange:M=>Z(M.target.value)})]}),ne.jsxs("div",{className:"textbox-container",children:[ne.jsx("textarea",{value:ie,rows:3,onChange:M=>fe(M.target.value)}),ne.jsx("textarea",{value:K,rows:3,readOnly:!0})]})]}),ne.jsx("button",{disabled:m,onClick:G,children:"Translate"}),ne.jsxs("div",{className:"progress-bars-container",children:[T===!1&&ne.jsx("label",{children:"Loading models... (only run once)"}),F.map(M=>ne.jsx("div",{children:ne.jsx(Bc,{text:M.file,percentage:M.progress})},M.file))]})]})}Ac.createRoot(document.getElementById("root")).render(ne.jsx(gn.StrictMode,{children:ne.jsx(Vc,{})})); diff --git a/assets/worker-22715bb5.js b/assets/worker-22715bb5.js deleted file mode 100644 index c8469fbe724c110faacf1a35e0bc6fe8f1aee06a..0000000000000000000000000000000000000000 --- a/assets/worker-22715bb5.js +++ /dev/null @@ -1,1790 +0,0 @@ -var gn=Object.defineProperty;var mn=(rt,Xe,_)=>Xe in rt?gn(rt,Xe,{enumerable:!0,configurable:!0,writable:!0,value:_}):rt[Xe]=_;var fe=(rt,Xe,_)=>(mn(rt,typeof Xe!="symbol"?Xe+"":Xe,_),_);(function(){var rt;"use strict";function _mergeNamespaces(_,n){return n.forEach(function(s){s&&typeof s!="string"&&!Array.isArray(s)&&Object.keys(s).forEach(function(c){if(c!=="default"&&!(c in _)){var l=Object.getOwnPropertyDescriptor(s,c);Object.defineProperty(_,c,l.get?l:{enumerable:!0,get:function(){return s[c]}})}})}),Object.freeze(_)}function dispatchCallback(_,n){_!==null&&_(n)}function reverseDictionary(_){return Object.fromEntries(Object.entries(_).map(([n,s])=>[s,n]))}function escapeRegExp(_){return _.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Callable=class{constructor(){let _=function(...n){return _._call(...n)};return Object.setPrototypeOf(_,new.target.prototype)}_call(..._){throw Error("Must implement _call method in subclass")}};function isString(_){return typeof _=="string"||_ instanceof String}function isTypedArray(_){var n,s,c;return((c=(s=(n=_==null?void 0:_.prototype)==null?void 0:n.__proto__)==null?void 0:s.constructor)==null?void 0:c.name)==="TypedArray"}function isIntegralNumber(_){return Number.isInteger(_)||typeof _=="bigint"}function exists(_){return _!=null}function calculateDimensions(_){const n=[];let s=_;for(;Array.isArray(s);)n.push(s.length),s=s[0];return n}var fs={},ONNX_NODE=Object.freeze({__proto__:null,default:fs});function getDefaultExportFromCjs(_){return _&&_.__esModule&&Object.prototype.hasOwnProperty.call(_,"default")?_.default:_}function getAugmentedNamespace(_){if(_.__esModule)return _;var n=_.default;if(typeof n=="function"){var s=function c(){if(this instanceof c){var l=[null];l.push.apply(l,arguments);var f=Function.bind.apply(n,l);return new f}return n.apply(this,arguments)};s.prototype=n.prototype}else s={};return Object.defineProperty(s,"__esModule",{value:!0}),Object.keys(_).forEach(function(c){var l=Object.getOwnPropertyDescriptor(_,c);Object.defineProperty(s,c,l.get?l:{enumerable:!0,get:function(){return _[c]}})}),s}var ortWeb_min$1={exports:{}};const backends={},backendsSortedByPriority=[],registerBackend=(_,n,s)=>{if(n&&typeof n.init=="function"&&typeof n.createSessionHandler=="function"){const c=backends[_];if(c===void 0)backends[_]={backend:n,priority:s};else{if(c.priority>s)return;if(c.priority===s&&c.backend!==n)throw new Error(`cannot register backend "${_}" using priority ${s}`)}if(s>=0){const l=backendsSortedByPriority.indexOf(_);l!==-1&&backendsSortedByPriority.splice(l,1);for(let f=0;f{const n=_.length===0?backendsSortedByPriority:_,s=[];for(const c of n){const l=backends[c];if(l){if(l.initialized)return l.backend;if(l.aborted)continue;const f=!!l.initPromise;try{return f||(l.initPromise=l.backend.init()),await l.initPromise,l.initialized=!0,l.backend}catch(a){f||s.push({name:c,err:a}),l.aborted=!0}finally{delete l.initPromise}}}throw new Error(`no available backend found. ERR: ${s.map(c=>`[${c.name}] ${c.err}`).join(", ")}`)};class EnvImpl{constructor(){this.wasm={},this.webgl={},this.logLevelInternal="warning"}set logLevel(n){if(n!==void 0){if(typeof n!="string"||["verbose","info","warning","error","fatal"].indexOf(n)===-1)throw new Error(`Unsupported logging level: ${n}`);this.logLevelInternal=n}}get logLevel(){return this.logLevelInternal}}const env$1=new EnvImpl,isBigInt64ArrayAvailable=typeof BigInt64Array<"u"&&typeof BigInt64Array.from=="function",isBigUint64ArrayAvailable=typeof BigUint64Array<"u"&&typeof BigUint64Array.from=="function",NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array]]),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);isBigInt64ArrayAvailable&&(NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("int64",BigInt64Array),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array,"int64")),isBigUint64ArrayAvailable&&(NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("uint64",BigUint64Array),NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array,"uint64"));const calculateSize=_=>{let n=1;for(let s=0;s<_.length;s++){const c=_[s];if(typeof c!="number"||!Number.isSafeInteger(c))throw new TypeError(`dims[${s}] must be an integer, got: ${c}`);if(c<0)throw new RangeError(`dims[${s}] must be a non-negative integer, got: ${c}`);n*=c}return n};let Tensor$2=class lt{constructor(n,s,c){let l,f,a;if(typeof n=="string")if(l=n,a=c,n==="string"){if(!Array.isArray(s))throw new TypeError("A string tensor's data must be a string array.");f=s}else{const p=NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(n);if(p===void 0)throw new TypeError(`Unsupported tensor type: ${n}.`);if(Array.isArray(s))f=p.from(s);else if(s instanceof p)f=s;else throw new TypeError(`A ${l} tensor's data must be type of ${p}`)}else if(a=s,Array.isArray(n)){if(n.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const p=typeof n[0];if(p==="string")l="string",f=n;else if(p==="boolean")l="bool",f=Uint8Array.from(n);else throw new TypeError(`Invalid element type of data array: ${p}.`)}else{const p=NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(n.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${n.constructor}.`);l=p,f=n}if(a===void 0)a=[f.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");const h=calculateSize(a);if(h!==f.length)throw new Error(`Tensor's size(${h}) does not match data length(${f.length}).`);this.dims=a,this.type=l,this.data=f,this.size=h}static bufferToTensor(n,s){if(n===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");const{height:c,width:l}=s,f=s.norm;let a,h;f===void 0||f.mean===void 0?a=255:a=f.mean,f===void 0||f.bias===void 0?h=0:h=f.bias;const p=s.bitmapFormat!==void 0?s.bitmapFormat:"RGBA",u=s.tensorFormat!==void 0&&s.tensorFormat!==void 0?s.tensorFormat:"RGB",o=c*l,t=u==="RGBA"?new Float32Array(o*4):new Float32Array(o*3);let e=4,r=0,i=1,d=2,g=3,m=0,b=o,y=o*2,w=-1;p==="RGB"&&(e=3,r=0,i=1,d=2,g=-1),u==="RGBA"?w=o*3:u==="RBG"?(m=0,y=o,b=o*2):u==="BGR"&&(y=0,b=o,m=o*2);for(let S=0;S{const t=document.createElement("canvas"),e=t.getContext("2d");if(!n||!e)return o();const r=new Image;r.crossOrigin="Anonymous",r.src=n,r.onload=()=>{t.width=r.width,t.height=r.height,e.drawImage(r,0,0,t.width,t.height);const i=e.getImageData(0,0,t.width,t.height);if(s!==void 0){if(s.height!==void 0&&s.height!==t.height)throw new Error("Image input config height doesn't match ImageBitmap height");if(p.height=t.height,s.width!==void 0&&s.width!==t.width)throw new Error("Image input config width doesn't match ImageBitmap width");p.width=t.width}else p.height=t.height,p.width=t.width;u(lt.bufferToTensor(i.data,p))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(h!==void 0)return lt.bufferToTensor(h,p);throw new Error("Input data provided is not supported - aborted tensor creation")}toImageData(n){var s,c;const l=document.createElement("canvas").getContext("2d");let f;if(l!=null){const a=this.dims[3],h=this.dims[2],p=this.dims[1],u=n!==void 0&&n.format!==void 0?n.format:"RGB",o=n!==void 0&&((s=n.norm)===null||s===void 0?void 0:s.mean)!==void 0?n.norm.mean:255,t=n!==void 0&&((c=n.norm)===null||c===void 0?void 0:c.bias)!==void 0?n.norm.bias:0,e=h*a;if(n!==void 0){if(n.height!==void 0&&n.height!==h)throw new Error("Image output config height doesn't match tensor height");if(n.width!==void 0&&n.width!==a)throw new Error("Image output config width doesn't match tensor width");if(n.format!==void 0&&p===4&&n.format!=="RGBA"||p===3&&n.format!=="RGB"&&n.format!=="BGR")throw new Error("Tensor format doesn't match input tensor dims")}const r=4;let i=0,d=1,g=2,m=3,b=0,y=e,w=e*2,v=-1;u==="RGBA"?(b=0,y=e,w=e*2,v=e*3):u==="RGB"?(b=0,y=e,w=e*2):u==="RBG"&&(b=0,w=e,y=e*2),f=l.createImageData(a,h);for(let S=0;S"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(a)for(const u of this.outputNames)l[u]=null;const h=await this.handler.run(n,l,f),p={};for(const u in h)Object.hasOwnProperty.call(h,u)&&(p[u]=new Tensor$1(h[u].type,h[u].data,h[u].dims));return p}static async create(n,s,c,l){let f,a={};if(typeof n=="string"){if(f=n,typeof s=="object"&&s!==null)a=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(n instanceof Uint8Array){if(f=n,typeof s=="object"&&s!==null)a=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer){const t=n;let e=0,r=n.byteLength;if(typeof s=="object"&&s!==null)a=s;else if(typeof s=="number"){if(e=s,!Number.isSafeInteger(e))throw new RangeError("'byteOffset' must be an integer.");if(e<0||e>=t.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${t.byteLength}).`);if(r=n.byteLength-e,typeof c=="number"){if(r=c,!Number.isSafeInteger(r))throw new RangeError("'byteLength' must be an integer.");if(r<=0||e+r>t.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${t.byteLength-e}].`);if(typeof l=="object"&&l!==null)a=l;else if(typeof l<"u")throw new TypeError("'options' must be an object.")}else if(typeof c<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof s<"u")throw new TypeError("'options' must be an object.");f=new Uint8Array(t,e,r)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const p=(a.executionProviders||[]).map(t=>typeof t=="string"?t:t.name),o=await(await resolveBackend(p)).createSessionHandler(f,a);return new hn(o)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}};const InferenceSession$1=InferenceSession$2;var lib=Object.freeze({__proto__:null,InferenceSession:InferenceSession$1,Tensor:Tensor$1,env:env$1,registerBackend}),require$$0=getAugmentedNamespace(lib);/*! -* ONNX Runtime Web v1.14.0 -* Copyright (c) Microsoft Corporation. All rights reserved. -* Licensed under the MIT License. -*/(function(module,exports){(function(_,n){module.exports=n(require$$0)})(self,__WEBPACK_EXTERNAL_MODULE__1670__=>(()=>{var __webpack_modules__={3474:(_,n,s)=>{var c,l=(c=(c=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(f){function a(){return X.buffer!=ee&&Ee(X.buffer),ue}function h(){return X.buffer!=ee&&Ee(X.buffer),Ae}function p(){return X.buffer!=ee&&Ee(X.buffer),xe}function u(){return X.buffer!=ee&&Ee(X.buffer),oe}function o(){return X.buffer!=ee&&Ee(X.buffer),we}var t,e,r;f=f||{},t||(t=f!==void 0?f:{}),t.ready=new Promise(function(T,E){e=T,r=E});var i,d,g,m,b,y,w=Object.assign({},t),v="./this.program",S=(T,E)=>{throw E},A=typeof window=="object",O=typeof importScripts=="function",x=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",I=t.ENVIRONMENT_IS_PTHREAD||!1,$="";function z(T){return t.locateFile?t.locateFile(T,$):$+T}if(x){let T;$=O?s(908).dirname($)+"/":"//",y=()=>{b||(m=s(1384),b=s(908))},i=function(E,k){return y(),E=b.normalize(E),m.readFileSync(E,k?void 0:"utf8")},g=E=>((E=i(E,!0)).buffer||(E=new Uint8Array(E)),E),d=(E,k,C)=>{y(),E=b.normalize(E),m.readFile(E,function(B,V){B?C(B):k(V.buffer)})},1{if(qe())throw process.exitCode=E,k;k instanceof Qe||j("exiting due to exception: "+k),process.exit(E)},t.inspect=function(){return"[Emscripten Module object]"};try{T=s(9925)}catch(E){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),E}s.g.Worker=T.Worker}else(A||O)&&(O?$=self.location.href:typeof document<"u"&&document.currentScript&&($=document.currentScript.src),c&&($=c),$=$.indexOf("blob:")!==0?$.substr(0,$.replace(/[?#].*/,"").lastIndexOf("/")+1):"",x||(i=T=>{var E=new XMLHttpRequest;return E.open("GET",T,!1),E.send(null),E.responseText},O&&(g=T=>{var E=new XMLHttpRequest;return E.open("GET",T,!1),E.responseType="arraybuffer",E.send(null),new Uint8Array(E.response)}),d=(T,E,k)=>{var C=new XMLHttpRequest;C.open("GET",T,!0),C.responseType="arraybuffer",C.onload=()=>{C.status==200||C.status==0&&C.response?E(C.response):k()},C.onerror=k,C.send(null)}));x&&typeof performance>"u"&&(s.g.performance=s(6953).performance);var L=console.log.bind(console),N=console.warn.bind(console);x&&(y(),L=T=>m.writeSync(1,T+` -`),N=T=>m.writeSync(2,T+` -`));var H,M=t.print||L,j=t.printErr||N;Object.assign(t,w),w=null,t.thisProgram&&(v=t.thisProgram),t.quit&&(S=t.quit),t.wasmBinary&&(H=t.wasmBinary);var Z=t.noExitRuntime||!1;typeof WebAssembly!="object"&&ge("no native wasm support detected");var X,Q,ee,ue,Ae,xe,oe,we,ye=!1,ke=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Ne(T,E,k){var C=(E>>>=0)+k;for(k=E;T[k]&&!(k>=C);)++k;if(16(B=(240&B)==224?(15&B)<<12|V<<6|K:(7&B)<<18|V<<12|K<<6|63&T[E++])?C+=String.fromCharCode(B):(B-=65536,C+=String.fromCharCode(55296|B>>10,56320|1023&B))}}else C+=String.fromCharCode(B)}return C}function Te(T,E){return(T>>>=0)?Ne(h(),T,E):""}function $e(T,E,k,C){if(!(0>>=0;C=k+C-1;for(var V=0;V=K&&(K=65536+((1023&K)<<10)|1023&T.charCodeAt(++V)),127>=K){if(k>=C)break;E[k++>>>0]=K}else{if(2047>=K){if(k+1>=C)break;E[k++>>>0]=192|K>>6}else{if(65535>=K){if(k+2>=C)break;E[k++>>>0]=224|K>>12}else{if(k+3>=C)break;E[k++>>>0]=240|K>>18,E[k++>>>0]=128|K>>12&63}E[k++>>>0]=128|K>>6&63}E[k++>>>0]=128|63&K}}return E[k>>>0]=0,k-B}function Ce(T){for(var E=0,k=0;k=C?E++:2047>=C?E+=2:55296<=C&&57343>=C?(E+=4,++k):E+=3}return E}function Ee(T){ee=T,t.HEAP8=ue=new Int8Array(T),t.HEAP16=new Int16Array(T),t.HEAP32=xe=new Int32Array(T),t.HEAPU8=Ae=new Uint8Array(T),t.HEAPU16=new Uint16Array(T),t.HEAPU32=oe=new Uint32Array(T),t.HEAPF32=new Float32Array(T),t.HEAPF64=we=new Float64Array(T)}I&&(ee=t.buffer);var Oe=t.INITIAL_MEMORY||16777216;if(I)X=t.wasmMemory,ee=t.buffer;else if(t.wasmMemory)X=t.wasmMemory;else if(!((X=new WebAssembly.Memory({initial:Oe/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw j("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"),x&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");X&&(ee=X.buffer),Oe=ee.byteLength,Ee(ee);var ze,Ve=[],Ge=[],Ye=[],Je=[];function qe(){return Z||!1}function Ue(){var T=t.preRun.shift();Ve.unshift(T)}var Ie,je=0,Ke=null;function ge(T){throw I?postMessage({cmd:"onAbort",arg:T}):t.onAbort&&t.onAbort(T),j(T="Aborted("+T+")"),ye=!0,T=new WebAssembly.RuntimeError(T+". Build with -sASSERTIONS for more info."),r(T),T}function ft(){return Ie.startsWith("data:application/octet-stream;base64,")}function ct(){var T=Ie;try{if(T==Ie&&H)return new Uint8Array(H);if(g)return g(T);throw"both async and sync fetching of the wasm failed"}catch(E){ge(E)}}Ie="ort-wasm-threaded.wasm",ft()||(Ie=z(Ie));var It={};function Qe(T){this.name="ExitStatus",this.message="Program terminated with exit("+T+")",this.status=T}function dt(T){(T=re.Vb[T])||ge(),re.mc(T)}function ht(T){var E=re.Cc();if(!E)return 6;re.ac.push(E),re.Vb[T.Ub]=E,E.Ub=T.Ub;var k={cmd:"run",start_routine:T.Ic,arg:T.zc,pthread_ptr:T.Ub};return E.$b=()=>{k.time=performance.now(),E.postMessage(k,T.Nc)},E.loaded&&(E.$b(),delete E.$b),0}function Re(T){if(I)return J(1,1,T);qe()||(re.oc(),t.onExit&&t.onExit(T),ye=!0),S(T,new Qe(T))}function ot(T,E){if(!E&&I)throw Dt(T),"unwind";qe()||I||(Ht(),it(Ye),Wt(0),Nt[1].length&&Lt(1,10),Nt[2].length&&Lt(2,10),re.oc()),Re(T)}var re={Yb:[],ac:[],qc:[],Vb:{},fc:function(){I&&re.Ec()},Pc:function(){},Ec:function(){re.receiveObjectTransfer=re.Gc,re.threadInitTLS=re.pc,re.setExitStatus=re.nc,Z=!1},nc:function(){},oc:function(){for(var T of Object.values(re.Vb))re.mc(T);for(T of re.Yb)T.terminate();re.Yb=[]},mc:function(T){var E=T.Ub;delete re.Vb[E],re.Yb.push(T),re.ac.splice(re.ac.indexOf(T),1),T.Ub=0,jt(E)},Gc:function(){},pc:function(){re.qc.forEach(T=>T())},Fc:function(T,E){T.onmessage=k=>{var C=(k=k.data).cmd;if(T.Ub&&(re.Bc=T.Ub),k.targetThread&&k.targetThread!=Ct()){var B=re.Vb[k.Qc];B?B.postMessage(k,k.transferList):j('Internal error! Worker sent a message "'+C+'" to target pthread '+k.targetThread+", but that thread no longer exists!")}else C==="processProxyingQueue"?F(k.queue):C==="spawnThread"?ht(k):C==="cleanupThread"?dt(k.thread):C==="killThread"?(k=k.thread,C=re.Vb[k],delete re.Vb[k],C.terminate(),jt(k),re.ac.splice(re.ac.indexOf(C),1),C.Ub=0):C==="cancelThread"?re.Vb[k.thread].postMessage({cmd:"cancel"}):C==="loaded"?(T.loaded=!0,E&&E(T),T.$b&&(T.$b(),delete T.$b)):C==="print"?M("Thread "+k.threadId+": "+k.text):C==="printErr"?j("Thread "+k.threadId+": "+k.text):C==="alert"?alert("Thread "+k.threadId+": "+k.text):k.target==="setimmediate"?T.postMessage(k):C==="onAbort"?t.onAbort&&t.onAbort(k.arg):C&&j("worker sent an unknown command "+C);re.Bc=void 0},T.onerror=k=>{throw j("worker sent an error! "+k.filename+":"+k.lineno+": "+k.message),k},x&&(T.on("message",function(k){T.onmessage({data:k})}),T.on("error",function(k){T.onerror(k)}),T.on("detachedExit",function(){})),T.postMessage({cmd:"load",urlOrBlob:t.mainScriptUrlOrBlob||c,wasmMemory:X,wasmModule:Q})},yc:function(){var T=z("ort-wasm-threaded.worker.js");re.Yb.push(new Worker(T))},Cc:function(){return re.Yb.length==0&&(re.yc(),re.Fc(re.Yb[0])),re.Yb.pop()}};function it(T){for(;0>2>>>0];T=p()[T+48>>2>>>0],Jt(E,E-T),ce(E)};var et=[];function ve(T){var E=et[T];return E||(T>=et.length&&(et.length=T+1),et[T]=E=ze.get(T)),E}t.invokeEntryPoint=function(T,E){T=ve(T)(E),qe()?re.nc(T):Zt(T)};var st,gt,at=[],ae=0,ie=0;function se(T){this.Zb=T,this.Sb=T-24,this.xc=function(E){u()[this.Sb+4>>2>>>0]=E},this.bc=function(){return u()[this.Sb+4>>2>>>0]},this.wc=function(E){u()[this.Sb+8>>2>>>0]=E},this.Dc=function(){return u()[this.Sb+8>>2>>>0]},this.rc=function(){p()[this.Sb>>2>>>0]=0},this.hc=function(E){E=E?1:0,a()[this.Sb+12>>0>>>0]=E},this.uc=function(){return a()[this.Sb+12>>0>>>0]!=0},this.ic=function(E){E=E?1:0,a()[this.Sb+13>>0>>>0]=E},this.kc=function(){return a()[this.Sb+13>>0>>>0]!=0},this.fc=function(E,k){this.cc(0),this.xc(E),this.wc(k),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(p(),this.Sb>>2,1)},this.Hc=function(){return Atomics.sub(p(),this.Sb>>2,1)===1},this.cc=function(E){u()[this.Sb+16>>2>>>0]=E},this.tc=function(){return u()[this.Sb+16>>2>>>0]},this.vc=function(){if(Qt(this.bc()))return u()[this.Zb>>2>>>0];var E=this.tc();return E!==0?E:this.Zb}}function mt(T){return qt(new se(T).Sb)}function ut(T,E,k,C){return I?J(3,1,T,E,k,C):bt(T,E,k,C)}function bt(T,E,k,C){if(typeof SharedArrayBuffer>"u")return j("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var B=[];return I&&B.length===0?ut(T,E,k,C):(T={Ic:k,Ub:T,zc:C,Nc:B},I?(T.Oc="spawnThread",postMessage(T,B),0):ht(T))}function yt(T,E,k){return I?J(4,1,T,E,k):0}function _t(T,E){if(I)return J(5,1,T,E)}function wt(T,E){if(I)return J(6,1,T,E)}function vt(T,E,k){if(I)return J(7,1,T,E,k)}function xt(T,E,k){return I?J(8,1,T,E,k):0}function Tt(T,E){if(I)return J(9,1,T,E)}function St(T,E,k){if(I)return J(10,1,T,E,k)}function At(T,E,k,C){if(I)return J(11,1,T,E,k,C)}function Ot(T,E,k,C){if(I)return J(12,1,T,E,k,C)}function Et(T,E,k,C){if(I)return J(13,1,T,E,k,C)}function Pt(T){if(I)return J(14,1,T)}function P(T,E){if(I)return J(15,1,T,E)}function D(T,E,k){if(I)return J(16,1,T,E,k)}function F(T){Atomics.store(p(),T>>2,1),Ct()&&Kt(T),Atomics.compareExchange(p(),T>>2,1,0)}function R(T){return u()[T>>>2]+4294967296*p()[T+4>>>2]}function U(T,E,k,C,B,V){return I?J(17,1,T,E,k,C,B,V):-52}function W(T,E,k,C,B,V){if(I)return J(18,1,T,E,k,C,B,V)}function Y(T){var E=Ce(T)+1,k=Rt(E);return k&&$e(T,a(),k,E),k}function te(T,E,k){function C(me){return(me=me.toTimeString().match(/\(([A-Za-z ]+)\)$/))?me[1]:"GMT"}if(I)return J(19,1,T,E,k);var B=new Date().getFullYear(),V=new Date(B,0,1),K=new Date(B,6,1);B=V.getTimezoneOffset();var ne=K.getTimezoneOffset(),pe=Math.max(B,ne);p()[T>>2>>>0]=60*pe,p()[E>>2>>>0]=+(B!=ne),T=C(V),E=C(K),T=Y(T),E=Y(E),ne>2>>>0]=T,u()[k+4>>2>>>0]=E):(u()[k>>2>>>0]=E,u()[k+4>>2>>>0]=T)}function J(T,E){var k=arguments.length-2,C=arguments;return kt(()=>{for(var B=Bt(8*k),V=B>>3,K=0;K>>0]=ne}return Yt(T,k,B,E)})}t.executeNotifiedProxyingQueue=F,gt=x?()=>{var T=process.hrtime();return 1e3*T[0]+T[1]/1e6}:I?()=>performance.now()-t.__performance_now_clock_drift:()=>performance.now();var le,Se=[],Le={};function Fe(){if(!le){var T,E={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",_:v||"./this.program"};for(T in Le)Le[T]===void 0?delete E[T]:E[T]=Le[T];var k=[];for(T in E)k.push(T+"="+E[T]);le=k}return le}function G(T,E){if(I)return J(20,1,T,E);var k=0;return Fe().forEach(function(C,B){var V=E+k;for(B=u()[T+4*B>>2>>>0]=V,V=0;V>0>>>0]=C.charCodeAt(V);a()[B>>0>>>0]=0,k+=C.length+1}),0}function be(T,E){if(I)return J(21,1,T,E);var k=Fe();u()[T>>2>>>0]=k.length;var C=0;return k.forEach(function(B){C+=B.length+1}),u()[E>>2>>>0]=C,0}function Pe(T){return I?J(22,1,T):52}function We(T,E,k,C){return I?J(23,1,T,E,k,C):52}function tt(T,E,k,C,B){return I?J(24,1,T,E,k,C,B):70}var Nt=[null,[],[]];function Lt(T,E){var k=Nt[T];E===0||E===10?((T===1?M:j)(Ne(k,0)),k.length=0):k.push(E)}function zt(T,E,k,C){if(I)return J(25,1,T,E,k,C);for(var B=0,V=0;V>2>>>0],ne=u()[E+4>>2>>>0];E+=8;for(var pe=0;pe>>0]);B+=ne}return u()[C>>2>>>0]=B,0}var Be=0;function Mt(T){return T%4==0&&(T%100!=0||T%400==0)}var Ut=[31,29,31,30,31,30,31,31,30,31,30,31],Vt=[31,28,31,30,31,30,31,31,30,31,30,31];function Gt(T,E,k,C){function B(q,_e,De){for(q=typeof q=="number"?q.toString():q||"";q.length<_e;)q=De[0]+q;return q}function V(q,_e){return B(q,_e,"0")}function K(q,_e){function De(pt){return 0>pt?-1:0nt-q.getDate())){q.setDate(q.getDate()+_e);break}_e-=nt-q.getDate()+1,q.setDate(1),11>De?q.setMonth(De+1):(q.setMonth(0),q.setFullYear(q.getFullYear()+1))}return De=new Date(q.getFullYear()+1,0,4),_e=ne(new Date(q.getFullYear(),0,4)),De=ne(De),0>=K(_e,q)?0>=K(De,q)?q.getFullYear()+1:q.getFullYear():q.getFullYear()-1}var me=p()[C+40>>2>>>0];for(var Me in C={Lc:p()[C>>2>>>0],Kc:p()[C+4>>2>>>0],dc:p()[C+8>>2>>>0],jc:p()[C+12>>2>>>0],ec:p()[C+16>>2>>>0],Xb:p()[C+20>>2>>>0],Tb:p()[C+24>>2>>>0],Wb:p()[C+28>>2>>>0],Rc:p()[C+32>>2>>>0],Jc:p()[C+36>>2>>>0],Mc:me?Te(me):""},k=Te(k),me={"%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"})k=k.replace(new RegExp(Me,"g"),me[Me]);var Ze="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),He="January February March April May June July August September October November December".split(" ");for(Me in me={"%a":function(q){return Ze[q.Tb].substring(0,3)},"%A":function(q){return Ze[q.Tb]},"%b":function(q){return He[q.ec].substring(0,3)},"%B":function(q){return He[q.ec]},"%C":function(q){return V((q.Xb+1900)/100|0,2)},"%d":function(q){return V(q.jc,2)},"%e":function(q){return B(q.jc,2," ")},"%g":function(q){return pe(q).toString().substring(2)},"%G":function(q){return pe(q)},"%H":function(q){return V(q.dc,2)},"%I":function(q){return(q=q.dc)==0?q=12:12q.dc?"AM":"PM"},"%S":function(q){return V(q.Lc,2)},"%t":function(){return" "},"%u":function(q){return q.Tb||7},"%U":function(q){return V(Math.floor((q.Wb+7-q.Tb)/7),2)},"%V":function(q){var _e=Math.floor((q.Wb+7-(q.Tb+6)%7)/7);if(2>=(q.Tb+371-q.Wb-2)%7&&_e++,_e)_e==53&&((De=(q.Tb+371-q.Wb)%7)==4||De==3&&Mt(q.Xb)||(_e=1));else{_e=52;var De=(q.Tb+7-q.Wb-1)%7;(De==4||De==5&&Mt(q.Xb%400-1))&&_e++}return V(_e,2)},"%w":function(q){return q.Tb},"%W":function(q){return V(Math.floor((q.Wb+7-(q.Tb+6)%7)/7),2)},"%y":function(q){return(q.Xb+1900).toString().substring(2)},"%Y":function(q){return q.Xb+1900},"%z":function(q){var _e=0<=(q=q.Jc);return q=Math.abs(q)/60,(_e?"+":"-")+("0000"+(q/60*100+q%60)).slice(-4)},"%Z":function(q){return q.Mc},"%%":function(){return"%"}},k=k.replace(/%%/g,"\0\0"),me)k.includes(Me)&&(k=k.replace(new RegExp(Me,"g"),me[Me](C)));return Me=function(q){var _e=Array(Ce(q)+1);return $e(q,_e,0,_e.length),_e}(k=k.replace(/\0\0/g,"%")),Me.length>E?0:(function(q,_e){a().set(q,_e>>>0)}(Me,T),Me.length-1)}re.fc();var pn=[null,Re,Dt,ut,yt,_t,wt,vt,xt,Tt,St,At,Ot,Et,Pt,P,D,U,W,te,G,be,Pe,We,tt,zt],fn={b:function(T){return Rt(T+24)+24},n:function(T){return(T=new se(T)).uc()||(T.hc(!0),ae--),T.ic(!1),at.push(T),T.sc(),T.vc()},ma:function(T){throw j("Unexpected exception thrown, this is not properly supported - aborting"),ye=!0,T},x:function(){he(0);var T=at.pop();if(T.Hc()&&!T.kc()){var E=T.Dc();E&&ve(E)(T.Zb),mt(T.Zb)}ie=0},e:function(){var T=ie;if(!T)return Be=0;var E=new se(T);E.cc(T);var k=E.bc();if(!k)return Be=0,T;for(var C=Array.prototype.slice.call(arguments),B=0;BF(C));else if(I)postMessage({targetThread:T,cmd:"processProxyingQueue",queue:C});else{if(!(T=re.Vb[T]))return;T.postMessage({cmd:"processProxyingQueue",queue:C})}return 1},Ea:function(){return-1},Pa:function(T,E){T=new Date(1e3*R(T)),p()[E>>2>>>0]=T.getUTCSeconds(),p()[E+4>>2>>>0]=T.getUTCMinutes(),p()[E+8>>2>>>0]=T.getUTCHours(),p()[E+12>>2>>>0]=T.getUTCDate(),p()[E+16>>2>>>0]=T.getUTCMonth(),p()[E+20>>2>>>0]=T.getUTCFullYear()-1900,p()[E+24>>2>>>0]=T.getUTCDay(),T=(T.getTime()-Date.UTC(T.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,p()[E+28>>2>>>0]=T},Qa:function(T,E){T=new Date(1e3*R(T)),p()[E>>2>>>0]=T.getSeconds(),p()[E+4>>2>>>0]=T.getMinutes(),p()[E+8>>2>>>0]=T.getHours(),p()[E+12>>2>>>0]=T.getDate(),p()[E+16>>2>>>0]=T.getMonth(),p()[E+20>>2>>>0]=T.getFullYear()-1900,p()[E+24>>2>>>0]=T.getDay();var k=new Date(T.getFullYear(),0,1),C=(T.getTime()-k.getTime())/864e5|0;p()[E+28>>2>>>0]=C,p()[E+36>>2>>>0]=-60*T.getTimezoneOffset(),C=new Date(T.getFullYear(),6,1).getTimezoneOffset(),T=0|(C!=(k=k.getTimezoneOffset())&&T.getTimezoneOffset()==Math.min(k,C)),p()[E+32>>2>>>0]=T},Ra:function(T){var E=new Date(p()[T+20>>2>>>0]+1900,p()[T+16>>2>>>0],p()[T+12>>2>>>0],p()[T+8>>2>>>0],p()[T+4>>2>>>0],p()[T>>2>>>0],0),k=p()[T+32>>2>>>0],C=E.getTimezoneOffset(),B=new Date(E.getFullYear(),0,1),V=new Date(E.getFullYear(),6,1).getTimezoneOffset(),K=B.getTimezoneOffset(),ne=Math.min(K,V);return 0>k?p()[T+32>>2>>>0]=+(V!=K&&ne==C):0>2>>>0]=E.getDay(),k=(E.getTime()-B.getTime())/864e5|0,p()[T+28>>2>>>0]=k,p()[T>>2>>>0]=E.getSeconds(),p()[T+4>>2>>>0]=E.getMinutes(),p()[T+8>>2>>>0]=E.getHours(),p()[T+12>>2>>>0]=E.getDate(),p()[T+16>>2>>>0]=E.getMonth(),E.getTime()/1e3|0},Aa:U,Ba:W,Sa:function T(E,k,C){T.Ac||(T.Ac=!0,te(E,k,C))},y:function(){ge("")},U:function(){if(!x&&!O){var T="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";st||(st={}),st[T]||(st[T]=1,x&&(T="warning: "+T),j(T))}},ra:function(){return 4294901760},B:gt,Ia:function(T,E,k){h().copyWithin(T>>>0,E>>>0,E+k>>>0)},F:function(){return x?s(3993).cpus().length:navigator.hardwareConcurrency},Da:function(T,E,k){Se.length=E,k>>=3;for(var C=0;C>>0];return(0>T?It[-T-1]:pn[T]).apply(null,Se)},qa:function(T){var E=h().length;if((T>>>=0)<=E||4294901760=k;k*=2){var C=E*(1+.2/k);C=Math.min(C,T+100663296);var B=Math;C=Math.max(T,C),B=B.min.call(B,4294901760,C+(65536-C%65536)%65536);e:{try{X.grow(B-ee.byteLength+65535>>>16),Ee(X.buffer);var V=1;break e}catch{}V=void 0}if(V)return!0}return!1},Na:function(){throw"unwind"},Ga:G,Ha:be,J:ot,I:Pe,S:We,ga:tt,R:zt,d:function(){return Be},na:function T(E,k){T.lc||(T.lc=function(){if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function"){var B=new Uint8Array(1);return()=>(crypto.getRandomValues(B),B[0])}if(x)try{var V=s(Object(function(){var K=new Error("Cannot find module 'crypto'");throw K.code="MODULE_NOT_FOUND",K}()));return()=>V.randomBytes(1)[0]}catch{}return()=>ge("randomDevice")}());for(var C=0;C>0>>>0]=T.lc();return 0},ia:function(T,E,k){var C=de();try{return ve(T)(E,k)}catch(B){if(ce(C),B!==B+0)throw B;he(1,0)}},ja:function(T,E,k){var C=de();try{return ve(T)(E,k)}catch(B){if(ce(C),B!==B+0)throw B;he(1,0)}},K:function(T){var E=de();try{return ve(T)()}catch(k){if(ce(E),k!==k+0)throw k;he(1,0)}},f:function(T,E){var k=de();try{return ve(T)(E)}catch(C){if(ce(k),C!==C+0)throw C;he(1,0)}},P:function(T,E,k){var C=de();try{return ve(T)(E,k)}catch(B){if(ce(C),B!==B+0)throw B;he(1,0)}},Q:function(T,E,k){var C=de();try{return ve(T)(E,k)}catch(B){if(ce(C),B!==B+0)throw B;he(1,0)}},k:function(T,E,k){var C=de();try{return ve(T)(E,k)}catch(B){if(ce(C),B!==B+0)throw B;he(1,0)}},p:function(T,E,k,C){var B=de();try{return ve(T)(E,k,C)}catch(V){if(ce(B),V!==V+0)throw V;he(1,0)}},q:function(T,E,k,C,B){var V=de();try{return ve(T)(E,k,C,B)}catch(K){if(ce(V),K!==K+0)throw K;he(1,0)}},N:function(T,E,k,C,B,V){var K=de();try{return ve(T)(E,k,C,B,V)}catch(ne){if(ce(K),ne!==ne+0)throw ne;he(1,0)}},s:function(T,E,k,C,B,V){var K=de();try{return ve(T)(E,k,C,B,V)}catch(ne){if(ce(K),ne!==ne+0)throw ne;he(1,0)}},w:function(T,E,k,C,B,V,K){var ne=de();try{return ve(T)(E,k,C,B,V,K)}catch(pe){if(ce(ne),pe!==pe+0)throw pe;he(1,0)}},L:function(T,E,k,C,B,V,K,ne){var pe=de();try{return ve(T)(E,k,C,B,V,K,ne)}catch(me){if(ce(pe),me!==me+0)throw me;he(1,0)}},E:function(T,E,k,C,B,V,K,ne,pe,me,Me,Ze){var He=de();try{return ve(T)(E,k,C,B,V,K,ne,pe,me,Me,Ze)}catch(q){if(ce(He),q!==q+0)throw q;he(1,0)}},aa:function(T,E,k,C,B,V,K,ne){var pe=de();try{return ln(T,E,k,C,B,V,K,ne)}catch(me){if(ce(pe),me!==me+0)throw me;he(1,0)}},_:function(T,E,k,C,B,V,K){var ne=de();try{return tn(T,E,k,C,B,V,K)}catch(pe){if(ce(ne),pe!==pe+0)throw pe;he(1,0)}},Z:function(T,E,k,C,B){var V=de();try{return cn(T,E,k,C,B)}catch(K){if(ce(V),K!==K+0)throw K;he(1,0)}},ca:function(T,E,k,C){var B=de();try{return an(T,E,k,C)}catch(V){if(ce(B),V!==V+0)throw V;he(1,0)}},$:function(T){var E=de();try{return en(T)}catch(k){if(ce(E),k!==k+0)throw k;he(1,0)}},ba:function(T,E){var k=de();try{return un(T,E)}catch(C){if(ce(k),C!==C+0)throw C;he(1,0)}},Y:function(T,E,k){var C=de();try{return nn(T,E,k)}catch(B){if(ce(C),B!==B+0)throw B;he(1,0)}},g:function(T){var E=de();try{ve(T)()}catch(k){if(ce(E),k!==k+0)throw k;he(1,0)}},r:function(T,E){var k=de();try{ve(T)(E)}catch(C){if(ce(k),C!==C+0)throw C;he(1,0)}},i:function(T,E,k){var C=de();try{ve(T)(E,k)}catch(B){if(ce(C),B!==B+0)throw B;he(1,0)}},ha:function(T,E,k,C){var B=de();try{ve(T)(E,k,C)}catch(V){if(ce(B),V!==V+0)throw V;he(1,0)}},m:function(T,E,k,C){var B=de();try{ve(T)(E,k,C)}catch(V){if(ce(B),V!==V+0)throw V;he(1,0)}},v:function(T,E,k,C,B){var V=de();try{ve(T)(E,k,C,B)}catch(K){if(ce(V),K!==K+0)throw K;he(1,0)}},u:function(T,E,k,C,B,V){var K=de();try{ve(T)(E,k,C,B,V)}catch(ne){if(ce(K),ne!==ne+0)throw ne;he(1,0)}},O:function(T,E,k,C,B,V,K){var ne=de();try{ve(T)(E,k,C,B,V,K)}catch(pe){if(ce(ne),pe!==pe+0)throw pe;he(1,0)}},A:function(T,E,k,C,B,V,K,ne){var pe=de();try{ve(T)(E,k,C,B,V,K,ne)}catch(me){if(ce(pe),me!==me+0)throw me;he(1,0)}},ka:function(T,E,k,C,B,V,K,ne,pe){var me=de();try{ve(T)(E,k,C,B,V,K,ne,pe)}catch(Me){if(ce(me),Me!==Me+0)throw Me;he(1,0)}},C:function(T,E,k,C,B,V,K,ne,pe,me,Me){var Ze=de();try{ve(T)(E,k,C,B,V,K,ne,pe,me,Me)}catch(He){if(ce(Ze),He!==He+0)throw He;he(1,0)}},D:function(T,E,k,C,B,V,K,ne,pe,me,Me,Ze,He,q,_e,De){var nt=de();try{ve(T)(E,k,C,B,V,K,ne,pe,me,Me,Ze,He,q,_e,De)}catch(pt){if(ce(nt),pt!==pt+0)throw pt;he(1,0)}},fa:function(T,E,k,C,B,V,K,ne){var pe=de();try{rn(T,E,k,C,B,V,K,ne)}catch(me){if(ce(pe),me!==me+0)throw me;he(1,0)}},da:function(T,E,k,C,B,V,K,ne,pe,me,Me,Ze){var He=de();try{sn(T,E,k,C,B,V,K,ne,pe,me,Me,Ze)}catch(q){if(ce(He),q!==q+0)throw q;he(1,0)}},ea:function(T,E,k,C,B,V){var K=de();try{on(T,E,k,C,B,V)}catch(ne){if(ce(K),ne!==ne+0)throw ne;he(1,0)}},o:function(T){return T},a:X||t.wasmMemory,G:function(T){Be=T},la:Gt,z:function(T,E,k,C){return Gt(T,E,k,C)}};(function(){function T(B,V){t.asm=B.exports,re.qc.push(t.asm.sb),ze=t.asm.ub,Ge.unshift(t.asm.Va),Q=V,I||(je--,t.monitorRunDependencies&&t.monitorRunDependencies(je),je==0&&Ke&&(B=Ke,Ke=null,B()))}function E(B){T(B.instance,B.module)}function k(B){return function(){if(!H&&(A||O)){if(typeof fetch=="function"&&!Ie.startsWith("file://"))return fetch(Ie,{credentials:"same-origin"}).then(function(V){if(!V.ok)throw"failed to load wasm binary file at '"+Ie+"'";return V.arrayBuffer()}).catch(function(){return ct()});if(d)return new Promise(function(V,K){d(Ie,function(ne){V(new Uint8Array(ne))},K)})}return Promise.resolve().then(function(){return ct()})}().then(function(V){return WebAssembly.instantiate(V,C)}).then(function(V){return V}).then(B,function(V){j("failed to asynchronously prepare wasm: "+V),ge(V)})}var C={a:fn};if(I||(je++,t.monitorRunDependencies&&t.monitorRunDependencies(je)),t.instantiateWasm)try{return t.instantiateWasm(C,T)}catch(B){return j("Module.instantiateWasm callback failed with error: "+B),!1}(H||typeof WebAssembly.instantiateStreaming!="function"||ft()||Ie.startsWith("file://")||x||typeof fetch!="function"?k(E):fetch(Ie,{credentials:"same-origin"}).then(function(B){return WebAssembly.instantiateStreaming(B,C).then(E,function(V){return j("wasm streaming compile failed: "+V),j("falling back to ArrayBuffer instantiation"),k(E)})})).catch(r)})(),t.___wasm_call_ctors=function(){return(t.___wasm_call_ctors=t.asm.Va).apply(null,arguments)},t._OrtInit=function(){return(t._OrtInit=t.asm.Wa).apply(null,arguments)},t._OrtCreateSessionOptions=function(){return(t._OrtCreateSessionOptions=t.asm.Xa).apply(null,arguments)},t._OrtAppendExecutionProvider=function(){return(t._OrtAppendExecutionProvider=t.asm.Ya).apply(null,arguments)},t._OrtAddSessionConfigEntry=function(){return(t._OrtAddSessionConfigEntry=t.asm.Za).apply(null,arguments)},t._OrtReleaseSessionOptions=function(){return(t._OrtReleaseSessionOptions=t.asm._a).apply(null,arguments)},t._OrtCreateSession=function(){return(t._OrtCreateSession=t.asm.$a).apply(null,arguments)},t._OrtReleaseSession=function(){return(t._OrtReleaseSession=t.asm.ab).apply(null,arguments)},t._OrtGetInputCount=function(){return(t._OrtGetInputCount=t.asm.bb).apply(null,arguments)},t._OrtGetOutputCount=function(){return(t._OrtGetOutputCount=t.asm.cb).apply(null,arguments)},t._OrtGetInputName=function(){return(t._OrtGetInputName=t.asm.db).apply(null,arguments)},t._OrtGetOutputName=function(){return(t._OrtGetOutputName=t.asm.eb).apply(null,arguments)},t._OrtFree=function(){return(t._OrtFree=t.asm.fb).apply(null,arguments)},t._OrtCreateTensor=function(){return(t._OrtCreateTensor=t.asm.gb).apply(null,arguments)},t._OrtGetTensorData=function(){return(t._OrtGetTensorData=t.asm.hb).apply(null,arguments)},t._OrtReleaseTensor=function(){return(t._OrtReleaseTensor=t.asm.ib).apply(null,arguments)},t._OrtCreateRunOptions=function(){return(t._OrtCreateRunOptions=t.asm.jb).apply(null,arguments)},t._OrtAddRunConfigEntry=function(){return(t._OrtAddRunConfigEntry=t.asm.kb).apply(null,arguments)},t._OrtReleaseRunOptions=function(){return(t._OrtReleaseRunOptions=t.asm.lb).apply(null,arguments)},t._OrtRun=function(){return(t._OrtRun=t.asm.mb).apply(null,arguments)},t._OrtEndProfiling=function(){return(t._OrtEndProfiling=t.asm.nb).apply(null,arguments)};var Ct=t._pthread_self=function(){return(Ct=t._pthread_self=t.asm.ob).apply(null,arguments)},Rt=t._malloc=function(){return(Rt=t._malloc=t.asm.pb).apply(null,arguments)},qt=t._free=function(){return(qt=t._free=t.asm.qb).apply(null,arguments)},Wt=t._fflush=function(){return(Wt=t._fflush=t.asm.rb).apply(null,arguments)};t.__emscripten_tls_init=function(){return(t.__emscripten_tls_init=t.asm.sb).apply(null,arguments)};var Ht=t.___funcs_on_exit=function(){return(Ht=t.___funcs_on_exit=t.asm.tb).apply(null,arguments)},Xt=t.__emscripten_thread_init=function(){return(Xt=t.__emscripten_thread_init=t.asm.vb).apply(null,arguments)};t.__emscripten_thread_crashed=function(){return(t.__emscripten_thread_crashed=t.asm.wb).apply(null,arguments)};var $t,Yt=t._emscripten_run_in_main_runtime_thread_js=function(){return(Yt=t._emscripten_run_in_main_runtime_thread_js=t.asm.xb).apply(null,arguments)},Kt=t.__emscripten_proxy_execute_task_queue=function(){return(Kt=t.__emscripten_proxy_execute_task_queue=t.asm.yb).apply(null,arguments)},jt=t.__emscripten_thread_free_data=function(){return(jt=t.__emscripten_thread_free_data=t.asm.zb).apply(null,arguments)},Zt=t.__emscripten_thread_exit=function(){return(Zt=t.__emscripten_thread_exit=t.asm.Ab).apply(null,arguments)},he=t._setThrew=function(){return(he=t._setThrew=t.asm.Bb).apply(null,arguments)},Jt=t._emscripten_stack_set_limits=function(){return(Jt=t._emscripten_stack_set_limits=t.asm.Cb).apply(null,arguments)},de=t.stackSave=function(){return(de=t.stackSave=t.asm.Db).apply(null,arguments)},ce=t.stackRestore=function(){return(ce=t.stackRestore=t.asm.Eb).apply(null,arguments)},Bt=t.stackAlloc=function(){return(Bt=t.stackAlloc=t.asm.Fb).apply(null,arguments)},Ft=t.___cxa_can_catch=function(){return(Ft=t.___cxa_can_catch=t.asm.Gb).apply(null,arguments)},Qt=t.___cxa_is_pointer_type=function(){return(Qt=t.___cxa_is_pointer_type=t.asm.Hb).apply(null,arguments)},en=t.dynCall_j=function(){return(en=t.dynCall_j=t.asm.Ib).apply(null,arguments)},tn=t.dynCall_iiiiij=function(){return(tn=t.dynCall_iiiiij=t.asm.Jb).apply(null,arguments)},nn=t.dynCall_jii=function(){return(nn=t.dynCall_jii=t.asm.Kb).apply(null,arguments)},rn=t.dynCall_viiiiij=function(){return(rn=t.dynCall_viiiiij=t.asm.Lb).apply(null,arguments)},on=t.dynCall_vjji=function(){return(on=t.dynCall_vjji=t.asm.Mb).apply(null,arguments)},sn=t.dynCall_viiijjjii=function(){return(sn=t.dynCall_viiijjjii=t.asm.Nb).apply(null,arguments)},an=t.dynCall_iij=function(){return(an=t.dynCall_iij=t.asm.Ob).apply(null,arguments)},un=t.dynCall_ji=function(){return(un=t.dynCall_ji=t.asm.Pb).apply(null,arguments)},ln=t.dynCall_iiiiiij=function(){return(ln=t.dynCall_iiiiiij=t.asm.Qb).apply(null,arguments)},cn=t.dynCall_iiij=function(){return(cn=t.dynCall_iiij=t.asm.Rb).apply(null,arguments)};function dn(){function T(){if(!$t&&($t=!0,t.calledRun=!0,!ye)&&(I||it(Ge),e(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),!I)){if(t.postRun)for(typeof t.postRun=="function"&&(t.postRun=[t.postRun]);t.postRun.length;){var E=t.postRun.shift();Je.unshift(E)}it(Je)}}if(!(0{var c,l=(c=(c=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(f){var a,h,p;f=f||{},a||(a=f!==void 0?f:{}),a.ready=new Promise(function(P,D){h=P,p=D});var u,o,t,e,r,i,d=Object.assign({},a),g="./this.program",m=(P,D)=>{throw D},b=typeof window=="object",y=typeof importScripts=="function",w=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",v="";w?(v=y?s(908).dirname(v)+"/":"//",i=()=>{r||(e=s(1384),r=s(908))},u=function(P,D){return i(),P=r.normalize(P),e.readFileSync(P,D?void 0:"utf8")},t=P=>((P=u(P,!0)).buffer||(P=new Uint8Array(P)),P),o=(P,D,F)=>{i(),P=r.normalize(P),e.readFile(P,function(R,U){R?F(R):D(U.buffer)})},1{if(x||0{var D=new XMLHttpRequest;return D.open("GET",P,!1),D.send(null),D.responseText},y&&(t=P=>{var D=new XMLHttpRequest;return D.open("GET",P,!1),D.responseType="arraybuffer",D.send(null),new Uint8Array(D.response)}),o=(P,D,F)=>{var R=new XMLHttpRequest;R.open("GET",P,!0),R.responseType="arraybuffer",R.onload=()=>{R.status==200||R.status==0&&R.response?D(R.response):F()},R.onerror=F,R.send(null)});var S,A=a.print||console.log.bind(console),O=a.printErr||console.warn.bind(console);Object.assign(a,d),d=null,a.thisProgram&&(g=a.thisProgram),a.quit&&(m=a.quit),a.wasmBinary&&(S=a.wasmBinary);var x=a.noExitRuntime||!1;typeof WebAssembly!="object"&&Ee("no native wasm support detected");var I,$,z,L,N,H,M=!1,j=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Z(P,D,F){var R=(D>>>=0)+F;for(F=D;P[F]&&!(F>=R);)++F;if(16(U=(240&U)==224?(15&U)<<12|W<<6|Y:(7&U)<<18|W<<12|Y<<6|63&P[D++])?R+=String.fromCharCode(U):(U-=65536,R+=String.fromCharCode(55296|U>>10,56320|1023&U))}}else R+=String.fromCharCode(U)}return R}function X(P,D){return(P>>>=0)?Z(L,P,D):""}function Q(P,D,F,R){if(!(0>>=0;R=F+R-1;for(var W=0;W=Y&&(Y=65536+((1023&Y)<<10)|1023&P.charCodeAt(++W)),127>=Y){if(F>=R)break;D[F++>>>0]=Y}else{if(2047>=Y){if(F+1>=R)break;D[F++>>>0]=192|Y>>6}else{if(65535>=Y){if(F+2>=R)break;D[F++>>>0]=224|Y>>12}else{if(F+3>=R)break;D[F++>>>0]=240|Y>>18,D[F++>>>0]=128|Y>>12&63}D[F++>>>0]=128|Y>>6&63}D[F++>>>0]=128|63&Y}}return D[F>>>0]=0,F-U}function ee(P){for(var D=0,F=0;F=R?D++:2047>=R?D+=2:55296<=R&&57343>=R?(D+=4,++F):D+=3}return D}function ue(){var P=I.buffer;$=P,a.HEAP8=z=new Int8Array(P),a.HEAP16=new Int16Array(P),a.HEAP32=N=new Int32Array(P),a.HEAPU8=L=new Uint8Array(P),a.HEAPU16=new Uint16Array(P),a.HEAPU32=H=new Uint32Array(P),a.HEAPF32=new Float32Array(P),a.HEAPF64=new Float64Array(P)}var Ae,xe=[],oe=[],we=[],ye=[],ke=0;function Ne(){var P=a.preRun.shift();xe.unshift(P)}var Te,$e=0,Ce=null;function Ee(P){throw a.onAbort&&a.onAbort(P),O(P="Aborted("+P+")"),M=!0,P=new WebAssembly.RuntimeError(P+". Build with -sASSERTIONS for more info."),p(P),P}function Oe(){return Te.startsWith("data:application/octet-stream;base64,")}if(Te="ort-wasm.wasm",!Oe()){var ze=Te;Te=a.locateFile?a.locateFile(ze,v):v+ze}function Ve(){var P=Te;try{if(P==Te&&S)return new Uint8Array(S);if(t)return t(P);throw"both async and sync fetching of the wasm failed"}catch(D){Ee(D)}}function Ge(P){this.name="ExitStatus",this.message="Program terminated with exit("+P+")",this.status=P}function Ye(P){for(;0>2>>>0]=D},this.Eb=function(){return H[this.zb+4>>2>>>0]},this.Sb=function(D){H[this.zb+8>>2>>>0]=D},this.Wb=function(){return H[this.zb+8>>2>>>0]},this.Tb=function(){N[this.zb>>2>>>0]=0},this.Ib=function(D){z[this.zb+12>>0>>>0]=D?1:0},this.Pb=function(){return z[this.zb+12>>0>>>0]!=0},this.Jb=function(D){z[this.zb+13>>0>>>0]=D?1:0},this.Lb=function(){return z[this.zb+13>>0>>>0]!=0},this.Rb=function(D,F){this.Fb(0),this.Ub(D),this.Sb(F),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){N[this.zb>>2>>>0]+=1},this.Xb=function(){var D=N[this.zb>>2>>>0];return N[this.zb>>2>>>0]=D-1,D===1},this.Fb=function(D){H[this.zb+16>>2>>>0]=D},this.Ob=function(){return H[this.zb+16>>2>>>0]},this.Qb=function(){if(bt(this.Eb()))return H[this.Db>>2>>>0];var D=this.Ob();return D!==0?D:this.Db}}function je(P){return st(new Ie(P).zb)}var Ke=[];function ge(P){var D=Ke[P];return D||(P>=Ke.length&&(Ke.length=P+1),Ke[P]=D=Ae.get(P)),D}function ft(P){var D=ee(P)+1,F=ve(D);return F&&Q(P,z,F,D),F}var ct={};function It(){if(!Qe){var P,D={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",_:g||"./this.program"};for(P in ct)ct[P]===void 0?delete D[P]:D[P]=ct[P];var F=[];for(P in D)F.push(P+"="+D[P]);Qe=F}return Qe}var Qe,dt=[null,[],[]];function ht(P,D){var F=dt[P];D===0||D===10?((P===1?A:O)(Z(F,0)),F.length=0):F.push(D)}var Re=0;function ot(P){return P%4==0&&(P%100!=0||P%400==0)}var re=[31,29,31,30,31,30,31,31,30,31,30,31],it=[31,28,31,30,31,30,31,31,30,31,30,31];function kt(P,D,F,R){function U(G,be,Pe){for(G=typeof G=="number"?G.toString():G||"";G.lengthtt?-1:0We-G.getDate())){G.setDate(G.getDate()+be);break}be-=We-G.getDate()+1,G.setDate(1),11>Pe?G.setMonth(Pe+1):(G.setMonth(0),G.setFullYear(G.getFullYear()+1))}return Pe=new Date(G.getFullYear()+1,0,4),be=te(new Date(G.getFullYear(),0,4)),Pe=te(Pe),0>=Y(be,G)?0>=Y(Pe,G)?G.getFullYear()+1:G.getFullYear():G.getFullYear()-1}var le=N[R+40>>2>>>0];for(var Se in R={$b:N[R>>2>>>0],Zb:N[R+4>>2>>>0],Gb:N[R+8>>2>>>0],Kb:N[R+12>>2>>>0],Hb:N[R+16>>2>>>0],Cb:N[R+20>>2>>>0],Ab:N[R+24>>2>>>0],Bb:N[R+28>>2>>>0],bc:N[R+32>>2>>>0],Yb:N[R+36>>2>>>0],ac:le?X(le):""},F=X(F),le={"%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"})F=F.replace(new RegExp(Se,"g"),le[Se]);var Le="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),Fe="January February March April May June July August September October November December".split(" ");for(Se in le={"%a":function(G){return Le[G.Ab].substring(0,3)},"%A":function(G){return Le[G.Ab]},"%b":function(G){return Fe[G.Hb].substring(0,3)},"%B":function(G){return Fe[G.Hb]},"%C":function(G){return W((G.Cb+1900)/100|0,2)},"%d":function(G){return W(G.Kb,2)},"%e":function(G){return U(G.Kb,2," ")},"%g":function(G){return J(G).toString().substring(2)},"%G":function(G){return J(G)},"%H":function(G){return W(G.Gb,2)},"%I":function(G){return(G=G.Gb)==0?G=12:12G.Gb?"AM":"PM"},"%S":function(G){return W(G.$b,2)},"%t":function(){return" "},"%u":function(G){return G.Ab||7},"%U":function(G){return W(Math.floor((G.Bb+7-G.Ab)/7),2)},"%V":function(G){var be=Math.floor((G.Bb+7-(G.Ab+6)%7)/7);if(2>=(G.Ab+371-G.Bb-2)%7&&be++,be)be==53&&((Pe=(G.Ab+371-G.Bb)%7)==4||Pe==3&&ot(G.Cb)||(be=1));else{be=52;var Pe=(G.Ab+7-G.Bb-1)%7;(Pe==4||Pe==5&&ot(G.Cb%400-1))&&be++}return W(be,2)},"%w":function(G){return G.Ab},"%W":function(G){return W(Math.floor((G.Bb+7-(G.Ab+6)%7)/7),2)},"%y":function(G){return(G.Cb+1900).toString().substring(2)},"%Y":function(G){return G.Cb+1900},"%z":function(G){var be=0<=(G=G.Yb);return G=Math.abs(G)/60,(be?"+":"-")+("0000"+(G/60*100+G%60)).slice(-4)},"%Z":function(G){return G.ac},"%%":function(){return"%"}},F=F.replace(/%%/g,"\0\0"),le)F.includes(Se)&&(F=F.replace(new RegExp(Se,"g"),le[Se](R)));return Se=function(G){var be=Array(ee(G)+1);return Q(G,be,0,be.length),be}(F=F.replace(/\0\0/g,"%")),Se.length>D?0:(z.set(Se,P>>>0),Se.length-1)}var Dt={a:function(P){return ve(P+24)+24},m:function(P){return(P=new Ie(P)).Pb()||(P.Ib(!0),qe--),P.Jb(!1),Je.push(P),P.Nb(),P.Qb()},ia:function(P){throw O("Unexpected exception thrown, this is not properly supported - aborting"),M=!0,P},w:function(){ae(0);var P=Je.pop();if(P.Xb()&&!P.Lb()){var D=P.Wb();D&&ge(D)(P.Db),je(P.Db)}Ue=0},d:function(){var P=Ue;if(!P)return Re=0;var D=new Ie(P);D.Fb(P);var F=D.Eb();if(!F)return Re=0,P;for(var R=Array.prototype.slice.call(arguments),U=0;U>>2]+4294967296*N[P+4>>>2])),N[D>>2>>>0]=P.getUTCSeconds(),N[D+4>>2>>>0]=P.getUTCMinutes(),N[D+8>>2>>>0]=P.getUTCHours(),N[D+12>>2>>>0]=P.getUTCDate(),N[D+16>>2>>>0]=P.getUTCMonth(),N[D+20>>2>>>0]=P.getUTCFullYear()-1900,N[D+24>>2>>>0]=P.getUTCDay(),N[D+28>>2>>>0]=(P.getTime()-Date.UTC(P.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(P,D){P=new Date(1e3*(H[P>>>2]+4294967296*N[P+4>>>2])),N[D>>2>>>0]=P.getSeconds(),N[D+4>>2>>>0]=P.getMinutes(),N[D+8>>2>>>0]=P.getHours(),N[D+12>>2>>>0]=P.getDate(),N[D+16>>2>>>0]=P.getMonth(),N[D+20>>2>>>0]=P.getFullYear()-1900,N[D+24>>2>>>0]=P.getDay();var F=new Date(P.getFullYear(),0,1);N[D+28>>2>>>0]=(P.getTime()-F.getTime())/864e5|0,N[D+36>>2>>>0]=-60*P.getTimezoneOffset();var R=new Date(P.getFullYear(),6,1).getTimezoneOffset();F=F.getTimezoneOffset(),N[D+32>>2>>>0]=0|(R!=F&&P.getTimezoneOffset()==Math.min(F,R))},Fa:function(P){var D=new Date(N[P+20>>2>>>0]+1900,N[P+16>>2>>>0],N[P+12>>2>>>0],N[P+8>>2>>>0],N[P+4>>2>>>0],N[P>>2>>>0],0),F=N[P+32>>2>>>0],R=D.getTimezoneOffset(),U=new Date(D.getFullYear(),0,1),W=new Date(D.getFullYear(),6,1).getTimezoneOffset(),Y=U.getTimezoneOffset(),te=Math.min(Y,W);return 0>F?N[P+32>>2>>>0]=+(W!=Y&&te==R):0>2>>>0]=D.getDay(),N[P+28>>2>>>0]=(D.getTime()-U.getTime())/864e5|0,N[P>>2>>>0]=D.getSeconds(),N[P+4>>2>>>0]=D.getMinutes(),N[P+8>>2>>>0]=D.getHours(),N[P+12>>2>>>0]=D.getDate(),N[P+16>>2>>>0]=D.getMonth(),D.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function P(D,F,R){P.Vb||(P.Vb=!0,function(U,W,Y){function te(Fe){return(Fe=Fe.toTimeString().match(/\(([A-Za-z ]+)\)$/))?Fe[1]:"GMT"}var J=new Date().getFullYear(),le=new Date(J,0,1),Se=new Date(J,6,1);J=le.getTimezoneOffset();var Le=Se.getTimezoneOffset();N[U>>2>>>0]=60*Math.max(J,Le),N[W>>2>>>0]=+(J!=Le),U=te(le),W=te(Se),U=ft(U),W=ft(W),Le>2>>>0]=U,H[Y+4>>2>>>0]=W):(H[Y>>2>>>0]=W,H[Y+4>>2>>>0]=U)}(D,F,R))},B:function(){Ee("")},ma:function(){return 4294901760},I:w?()=>{var P=process.hrtime();return 1e3*P[0]+P[1]/1e6}:()=>performance.now(),xa:function(P,D,F){L.copyWithin(P>>>0,D>>>0,D+F>>>0)},G:function(P){var D=L.length;if(4294901760<(P>>>=0))return!1;for(var F=1;4>=F;F*=2){var R=D*(1+.2/F);R=Math.min(R,P+100663296);var U=Math;R=Math.max(P,R),U=U.min.call(U,4294901760,R+(65536-R%65536)%65536);e:{try{I.grow(U-$.byteLength+65535>>>16),ue();var W=1;break e}catch{}W=void 0}if(W)return!0}return!1},va:function(P,D){var F=0;return It().forEach(function(R,U){var W=D+F;for(U=H[P+4*U>>2>>>0]=W,W=0;W>0>>>0]=R.charCodeAt(W);z[U>>0>>>0]=0,F+=R.length+1}),0},wa:function(P,D){var F=It();H[P>>2>>>0]=F.length;var R=0;return F.forEach(function(U){R+=U.length+1}),H[D>>2>>>0]=R,0},ba:function(P){x||0>2>>>0],te=H[D+4>>2>>>0];D+=8;for(var J=0;J>>0]);U+=te}return H[R>>2>>>0]=U,0},c:function(){return Re},ja:function P(D,F){P.Mb||(P.Mb=function(){if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function"){var U=new Uint8Array(1);return()=>(crypto.getRandomValues(U),U[0])}if(w)try{var W=s(Object(function(){var Y=new Error("Cannot find module 'crypto'");throw Y.code="MODULE_NOT_FOUND",Y}()));return()=>W.randomBytes(1)[0]}catch{}return()=>Ee("randomDevice")}());for(var R=0;R>0>>>0]=P.Mb();return 0},ea:function(P,D,F){var R=ie();try{return ge(P)(D,F)}catch(U){if(se(R),U!==U+0)throw U;ae(1,0)}},fa:function(P,D,F){var R=ie();try{return ge(P)(D,F)}catch(U){if(se(R),U!==U+0)throw U;ae(1,0)}},J:function(P){var D=ie();try{return ge(P)()}catch(F){if(se(D),F!==F+0)throw F;ae(1,0)}},e:function(P,D){var F=ie();try{return ge(P)(D)}catch(R){if(se(F),R!==R+0)throw R;ae(1,0)}},N:function(P,D,F){var R=ie();try{return ge(P)(D,F)}catch(U){if(se(R),U!==U+0)throw U;ae(1,0)}},O:function(P,D,F){var R=ie();try{return ge(P)(D,F)}catch(U){if(se(R),U!==U+0)throw U;ae(1,0)}},j:function(P,D,F){var R=ie();try{return ge(P)(D,F)}catch(U){if(se(R),U!==U+0)throw U;ae(1,0)}},o:function(P,D,F,R){var U=ie();try{return ge(P)(D,F,R)}catch(W){if(se(U),W!==W+0)throw W;ae(1,0)}},p:function(P,D,F,R,U){var W=ie();try{return ge(P)(D,F,R,U)}catch(Y){if(se(W),Y!==Y+0)throw Y;ae(1,0)}},M:function(P,D,F,R,U,W){var Y=ie();try{return ge(P)(D,F,R,U,W)}catch(te){if(se(Y),te!==te+0)throw te;ae(1,0)}},r:function(P,D,F,R,U,W){var Y=ie();try{return ge(P)(D,F,R,U,W)}catch(te){if(se(Y),te!==te+0)throw te;ae(1,0)}},v:function(P,D,F,R,U,W,Y){var te=ie();try{return ge(P)(D,F,R,U,W,Y)}catch(J){if(se(te),J!==J+0)throw J;ae(1,0)}},K:function(P,D,F,R,U,W,Y,te){var J=ie();try{return ge(P)(D,F,R,U,W,Y,te)}catch(le){if(se(J),le!==le+0)throw le;ae(1,0)}},D:function(P,D,F,R,U,W,Y,te,J,le,Se,Le){var Fe=ie();try{return ge(P)(D,F,R,U,W,Y,te,J,le,Se,Le)}catch(G){if(se(Fe),G!==G+0)throw G;ae(1,0)}},X:function(P,D,F,R,U,W,Y,te){var J=ie();try{return Ot(P,D,F,R,U,W,Y,te)}catch(le){if(se(J),le!==le+0)throw le;ae(1,0)}},V:function(P,D,F,R,U,W,Y){var te=ie();try{return _t(P,D,F,R,U,W,Y)}catch(J){if(se(te),J!==J+0)throw J;ae(1,0)}},U:function(P,D,F,R,U){var W=ie();try{return Et(P,D,F,R,U)}catch(Y){if(se(W),Y!==Y+0)throw Y;ae(1,0)}},Z:function(P,D,F,R){var U=ie();try{return St(P,D,F,R)}catch(W){if(se(U),W!==W+0)throw W;ae(1,0)}},W:function(P){var D=ie();try{return yt(P)}catch(F){if(se(D),F!==F+0)throw F;ae(1,0)}},Y:function(P,D){var F=ie();try{return At(P,D)}catch(R){if(se(F),R!==R+0)throw R;ae(1,0)}},T:function(P,D,F){var R=ie();try{return wt(P,D,F)}catch(U){if(se(R),U!==U+0)throw U;ae(1,0)}},f:function(P){var D=ie();try{ge(P)()}catch(F){if(se(D),F!==F+0)throw F;ae(1,0)}},q:function(P,D){var F=ie();try{ge(P)(D)}catch(R){if(se(F),R!==R+0)throw R;ae(1,0)}},h:function(P,D,F){var R=ie();try{ge(P)(D,F)}catch(U){if(se(R),U!==U+0)throw U;ae(1,0)}},da:function(P,D,F,R){var U=ie();try{ge(P)(D,F,R)}catch(W){if(se(U),W!==W+0)throw W;ae(1,0)}},l:function(P,D,F,R){var U=ie();try{ge(P)(D,F,R)}catch(W){if(se(U),W!==W+0)throw W;ae(1,0)}},t:function(P,D,F,R,U){var W=ie();try{ge(P)(D,F,R,U)}catch(Y){if(se(W),Y!==Y+0)throw Y;ae(1,0)}},u:function(P,D,F,R,U,W){var Y=ie();try{ge(P)(D,F,R,U,W)}catch(te){if(se(Y),te!==te+0)throw te;ae(1,0)}},x:function(P,D,F,R,U,W,Y){var te=ie();try{ge(P)(D,F,R,U,W,Y)}catch(J){if(se(te),J!==J+0)throw J;ae(1,0)}},z:function(P,D,F,R,U,W,Y,te){var J=ie();try{ge(P)(D,F,R,U,W,Y,te)}catch(le){if(se(J),le!==le+0)throw le;ae(1,0)}},ga:function(P,D,F,R,U,W,Y,te,J){var le=ie();try{ge(P)(D,F,R,U,W,Y,te,J)}catch(Se){if(se(le),Se!==Se+0)throw Se;ae(1,0)}},A:function(P,D,F,R,U,W,Y,te,J,le,Se){var Le=ie();try{ge(P)(D,F,R,U,W,Y,te,J,le,Se)}catch(Fe){if(se(Le),Fe!==Fe+0)throw Fe;ae(1,0)}},C:function(P,D,F,R,U,W,Y,te,J,le,Se,Le,Fe,G,be,Pe){var We=ie();try{ge(P)(D,F,R,U,W,Y,te,J,le,Se,Le,Fe,G,be,Pe)}catch(tt){if(se(We),tt!==tt+0)throw tt;ae(1,0)}},aa:function(P,D,F,R,U,W,Y,te){var J=ie();try{vt(P,D,F,R,U,W,Y,te)}catch(le){if(se(J),le!==le+0)throw le;ae(1,0)}},_:function(P,D,F,R,U,W,Y,te,J,le,Se,Le){var Fe=ie();try{Tt(P,D,F,R,U,W,Y,te,J,le,Se,Le)}catch(G){if(se(Fe),G!==G+0)throw G;ae(1,0)}},$:function(P,D,F,R,U,W){var Y=ie();try{xt(P,D,F,R,U,W)}catch(te){if(se(Y),te!==te+0)throw te;ae(1,0)}},n:function(P){return P},F:function(P){Re=P},ha:kt,y:function(P,D,F,R){return kt(P,D,F,R)}};(function(){function P(U){a.asm=U.exports,I=a.asm.Ka,ue(),Ae=a.asm.ib,oe.unshift(a.asm.La),$e--,a.monitorRunDependencies&&a.monitorRunDependencies($e),$e==0&&Ce&&(U=Ce,Ce=null,U())}function D(U){P(U.instance)}function F(U){return function(){if(!S&&(b||y)){if(typeof fetch=="function"&&!Te.startsWith("file://"))return fetch(Te,{credentials:"same-origin"}).then(function(W){if(!W.ok)throw"failed to load wasm binary file at '"+Te+"'";return W.arrayBuffer()}).catch(function(){return Ve()});if(o)return new Promise(function(W,Y){o(Te,function(te){W(new Uint8Array(te))},Y)})}return Promise.resolve().then(function(){return Ve()})}().then(function(W){return WebAssembly.instantiate(W,R)}).then(function(W){return W}).then(U,function(W){O("failed to asynchronously prepare wasm: "+W),Ee(W)})}var R={a:Dt};if($e++,a.monitorRunDependencies&&a.monitorRunDependencies($e),a.instantiateWasm)try{return a.instantiateWasm(R,P)}catch(U){return O("Module.instantiateWasm callback failed with error: "+U),!1}(S||typeof WebAssembly.instantiateStreaming!="function"||Oe()||Te.startsWith("file://")||w||typeof fetch!="function"?F(D):fetch(Te,{credentials:"same-origin"}).then(function(U){return WebAssembly.instantiateStreaming(U,R).then(D,function(W){return O("wasm streaming compile failed: "+W),O("falling back to ArrayBuffer instantiation"),F(D)})})).catch(p)})(),a.___wasm_call_ctors=function(){return(a.___wasm_call_ctors=a.asm.La).apply(null,arguments)},a._OrtInit=function(){return(a._OrtInit=a.asm.Ma).apply(null,arguments)},a._OrtCreateSessionOptions=function(){return(a._OrtCreateSessionOptions=a.asm.Na).apply(null,arguments)},a._OrtAppendExecutionProvider=function(){return(a._OrtAppendExecutionProvider=a.asm.Oa).apply(null,arguments)},a._OrtAddSessionConfigEntry=function(){return(a._OrtAddSessionConfigEntry=a.asm.Pa).apply(null,arguments)},a._OrtReleaseSessionOptions=function(){return(a._OrtReleaseSessionOptions=a.asm.Qa).apply(null,arguments)},a._OrtCreateSession=function(){return(a._OrtCreateSession=a.asm.Ra).apply(null,arguments)},a._OrtReleaseSession=function(){return(a._OrtReleaseSession=a.asm.Sa).apply(null,arguments)},a._OrtGetInputCount=function(){return(a._OrtGetInputCount=a.asm.Ta).apply(null,arguments)},a._OrtGetOutputCount=function(){return(a._OrtGetOutputCount=a.asm.Ua).apply(null,arguments)},a._OrtGetInputName=function(){return(a._OrtGetInputName=a.asm.Va).apply(null,arguments)},a._OrtGetOutputName=function(){return(a._OrtGetOutputName=a.asm.Wa).apply(null,arguments)},a._OrtFree=function(){return(a._OrtFree=a.asm.Xa).apply(null,arguments)},a._OrtCreateTensor=function(){return(a._OrtCreateTensor=a.asm.Ya).apply(null,arguments)},a._OrtGetTensorData=function(){return(a._OrtGetTensorData=a.asm.Za).apply(null,arguments)},a._OrtReleaseTensor=function(){return(a._OrtReleaseTensor=a.asm._a).apply(null,arguments)},a._OrtCreateRunOptions=function(){return(a._OrtCreateRunOptions=a.asm.$a).apply(null,arguments)},a._OrtAddRunConfigEntry=function(){return(a._OrtAddRunConfigEntry=a.asm.ab).apply(null,arguments)},a._OrtReleaseRunOptions=function(){return(a._OrtReleaseRunOptions=a.asm.bb).apply(null,arguments)},a._OrtRun=function(){return(a._OrtRun=a.asm.cb).apply(null,arguments)},a._OrtEndProfiling=function(){return(a._OrtEndProfiling=a.asm.db).apply(null,arguments)};var et,ve=a._malloc=function(){return(ve=a._malloc=a.asm.eb).apply(null,arguments)},st=a._free=function(){return(st=a._free=a.asm.fb).apply(null,arguments)},gt=a._fflush=function(){return(gt=a._fflush=a.asm.gb).apply(null,arguments)},at=a.___funcs_on_exit=function(){return(at=a.___funcs_on_exit=a.asm.hb).apply(null,arguments)},ae=a._setThrew=function(){return(ae=a._setThrew=a.asm.jb).apply(null,arguments)},ie=a.stackSave=function(){return(ie=a.stackSave=a.asm.kb).apply(null,arguments)},se=a.stackRestore=function(){return(se=a.stackRestore=a.asm.lb).apply(null,arguments)},mt=a.stackAlloc=function(){return(mt=a.stackAlloc=a.asm.mb).apply(null,arguments)},ut=a.___cxa_can_catch=function(){return(ut=a.___cxa_can_catch=a.asm.nb).apply(null,arguments)},bt=a.___cxa_is_pointer_type=function(){return(bt=a.___cxa_is_pointer_type=a.asm.ob).apply(null,arguments)},yt=a.dynCall_j=function(){return(yt=a.dynCall_j=a.asm.pb).apply(null,arguments)},_t=a.dynCall_iiiiij=function(){return(_t=a.dynCall_iiiiij=a.asm.qb).apply(null,arguments)},wt=a.dynCall_jii=function(){return(wt=a.dynCall_jii=a.asm.rb).apply(null,arguments)},vt=a.dynCall_viiiiij=function(){return(vt=a.dynCall_viiiiij=a.asm.sb).apply(null,arguments)},xt=a.dynCall_vjji=function(){return(xt=a.dynCall_vjji=a.asm.tb).apply(null,arguments)},Tt=a.dynCall_viiijjjii=function(){return(Tt=a.dynCall_viiijjjii=a.asm.ub).apply(null,arguments)},St=a.dynCall_iij=function(){return(St=a.dynCall_iij=a.asm.vb).apply(null,arguments)},At=a.dynCall_ji=function(){return(At=a.dynCall_ji=a.asm.wb).apply(null,arguments)},Ot=a.dynCall_iiiiiij=function(){return(Ot=a.dynCall_iiiiiij=a.asm.xb).apply(null,arguments)},Et=a.dynCall_iiij=function(){return(Et=a.dynCall_iiij=a.asm.yb).apply(null,arguments)};function Pt(){function P(){if(!et&&(et=!0,a.calledRun=!0,!M)){if(Ye(oe),h(a),a.onRuntimeInitialized&&a.onRuntimeInitialized(),a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;){var D=a.postRun.shift();ye.unshift(D)}Ye(ye)}}if(!(0<$e)){if(a.preRun)for(typeof a.preRun=="function"&&(a.preRun=[a.preRun]);a.preRun.length;)Ne();Ye(xe),0<$e||(a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1),P()},1)):P())}}if(a.UTF8ToString=X,a.stringToUTF8=function(P,D,F){return Q(P,L,D,F)},a.lengthBytesUTF8=ee,a.stackSave=ie,a.stackRestore=se,a.stackAlloc=mt,Ce=function P(){et||Pt(),et||(Ce=P)},a.preInit)for(typeof a.preInit=="function"&&(a.preInit=[a.preInit]);0{_.exports=function(n,s){for(var c=new Array(arguments.length-1),l=0,f=2,a=!0;f{var s=n;s.length=function(h){var p=h.length;if(!p)return 0;for(var u=0;--p%4>1&&h.charAt(p)==="=";)++u;return Math.ceil(3*h.length)/4-u};for(var c=new Array(64),l=new Array(123),f=0;f<64;)l[c[f]=f<26?f+65:f<52?f+71:f<62?f-4:f-59|43]=f++;s.encode=function(h,p,u){for(var o,t=null,e=[],r=0,i=0;p>2],o=(3&d)<<4,i=1;break;case 1:e[r++]=c[o|d>>4],o=(15&d)<<2,i=2;break;case 2:e[r++]=c[o|d>>6],e[r++]=c[63&d],i=0}r>8191&&((t||(t=[])).push(String.fromCharCode.apply(String,e)),r=0)}return i&&(e[r++]=c[o],e[r++]=61,i===1&&(e[r++]=61)),t?(r&&t.push(String.fromCharCode.apply(String,e.slice(0,r))),t.join("")):String.fromCharCode.apply(String,e.slice(0,r))};var a="invalid encoding";s.decode=function(h,p,u){for(var o,t=u,e=0,r=0;r1)break;if((i=l[i])===void 0)throw Error(a);switch(e){case 0:o=i,e=1;break;case 1:p[u++]=o<<2|(48&i)>>4,o=i,e=2;break;case 2:p[u++]=(15&o)<<4|(60&i)>>2,o=i,e=3;break;case 3:p[u++]=(3&o)<<6|i,e=0}}if(e===1)throw Error(a);return u-t},s.test=function(h){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(h)}},9211:_=>{function n(){this._listeners={}}_.exports=n,n.prototype.on=function(s,c,l){return(this._listeners[s]||(this._listeners[s]=[])).push({fn:c,ctx:l||this}),this},n.prototype.off=function(s,c){if(s===void 0)this._listeners={};else if(c===void 0)this._listeners[s]=[];else for(var l=this._listeners[s],f=0;f{function n(a){return typeof Float32Array<"u"?function(){var h=new Float32Array([-0]),p=new Uint8Array(h.buffer),u=p[3]===128;function o(i,d,g){h[0]=i,d[g]=p[0],d[g+1]=p[1],d[g+2]=p[2],d[g+3]=p[3]}function t(i,d,g){h[0]=i,d[g]=p[3],d[g+1]=p[2],d[g+2]=p[1],d[g+3]=p[0]}function e(i,d){return p[0]=i[d],p[1]=i[d+1],p[2]=i[d+2],p[3]=i[d+3],h[0]}function r(i,d){return p[3]=i[d],p[2]=i[d+1],p[1]=i[d+2],p[0]=i[d+3],h[0]}a.writeFloatLE=u?o:t,a.writeFloatBE=u?t:o,a.readFloatLE=u?e:r,a.readFloatBE=u?r:e}():function(){function h(u,o,t,e){var r=o<0?1:0;if(r&&(o=-o),o===0)u(1/o>0?0:2147483648,t,e);else if(isNaN(o))u(2143289344,t,e);else if(o>34028234663852886e22)u((r<<31|2139095040)>>>0,t,e);else if(o<11754943508222875e-54)u((r<<31|Math.round(o/1401298464324817e-60))>>>0,t,e);else{var i=Math.floor(Math.log(o)/Math.LN2);u((r<<31|i+127<<23|8388607&Math.round(o*Math.pow(2,-i)*8388608))>>>0,t,e)}}function p(u,o,t){var e=u(o,t),r=2*(e>>31)+1,i=e>>>23&255,d=8388607&e;return i===255?d?NaN:r*(1/0):i===0?1401298464324817e-60*r*d:r*Math.pow(2,i-150)*(d+8388608)}a.writeFloatLE=h.bind(null,s),a.writeFloatBE=h.bind(null,c),a.readFloatLE=p.bind(null,l),a.readFloatBE=p.bind(null,f)}(),typeof Float64Array<"u"?function(){var h=new Float64Array([-0]),p=new Uint8Array(h.buffer),u=p[7]===128;function o(i,d,g){h[0]=i,d[g]=p[0],d[g+1]=p[1],d[g+2]=p[2],d[g+3]=p[3],d[g+4]=p[4],d[g+5]=p[5],d[g+6]=p[6],d[g+7]=p[7]}function t(i,d,g){h[0]=i,d[g]=p[7],d[g+1]=p[6],d[g+2]=p[5],d[g+3]=p[4],d[g+4]=p[3],d[g+5]=p[2],d[g+6]=p[1],d[g+7]=p[0]}function e(i,d){return p[0]=i[d],p[1]=i[d+1],p[2]=i[d+2],p[3]=i[d+3],p[4]=i[d+4],p[5]=i[d+5],p[6]=i[d+6],p[7]=i[d+7],h[0]}function r(i,d){return p[7]=i[d],p[6]=i[d+1],p[5]=i[d+2],p[4]=i[d+3],p[3]=i[d+4],p[2]=i[d+5],p[1]=i[d+6],p[0]=i[d+7],h[0]}a.writeDoubleLE=u?o:t,a.writeDoubleBE=u?t:o,a.readDoubleLE=u?e:r,a.readDoubleBE=u?r:e}():function(){function h(u,o,t,e,r,i){var d=e<0?1:0;if(d&&(e=-e),e===0)u(0,r,i+o),u(1/e>0?0:2147483648,r,i+t);else if(isNaN(e))u(0,r,i+o),u(2146959360,r,i+t);else if(e>17976931348623157e292)u(0,r,i+o),u((d<<31|2146435072)>>>0,r,i+t);else{var g;if(e<22250738585072014e-324)u((g=e/5e-324)>>>0,r,i+o),u((d<<31|g/4294967296)>>>0,r,i+t);else{var m=Math.floor(Math.log(e)/Math.LN2);m===1024&&(m=1023),u(4503599627370496*(g=e*Math.pow(2,-m))>>>0,r,i+o),u((d<<31|m+1023<<20|1048576*g&1048575)>>>0,r,i+t)}}}function p(u,o,t,e,r){var i=u(e,r+o),d=u(e,r+t),g=2*(d>>31)+1,m=d>>>20&2047,b=4294967296*(1048575&d)+i;return m===2047?b?NaN:g*(1/0):m===0?5e-324*g*b:g*Math.pow(2,m-1075)*(b+4503599627370496)}a.writeDoubleLE=h.bind(null,s,0,4),a.writeDoubleBE=h.bind(null,c,4,0),a.readDoubleLE=p.bind(null,l,0,4),a.readDoubleBE=p.bind(null,f,4,0)}(),a}function s(a,h,p){h[p]=255&a,h[p+1]=a>>>8&255,h[p+2]=a>>>16&255,h[p+3]=a>>>24}function c(a,h,p){h[p]=a>>>24,h[p+1]=a>>>16&255,h[p+2]=a>>>8&255,h[p+3]=255&a}function l(a,h){return(a[h]|a[h+1]<<8|a[h+2]<<16|a[h+3]<<24)>>>0}function f(a,h){return(a[h]<<24|a[h+1]<<16|a[h+2]<<8|a[h+3])>>>0}_.exports=n(n)},7199:module=>{function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(_){}return null}module.exports=inquire},6662:_=>{_.exports=function(n,s,c){var l=c||8192,f=l>>>1,a=null,h=l;return function(p){if(p<1||p>f)return n(p);h+p>l&&(a=n(l),h=0);var u=s.call(a,h,h+=p);return 7&h&&(h=1+(7|h)),u}}},4997:(_,n)=>{var s=n;s.length=function(c){for(var l=0,f=0,a=0;a191&&a<224?p[u++]=(31&a)<<6|63&c[l++]:a>239&&a<365?(a=((7&a)<<18|(63&c[l++])<<12|(63&c[l++])<<6|63&c[l++])-65536,p[u++]=55296+(a>>10),p[u++]=56320+(1023&a)):p[u++]=(15&a)<<12|(63&c[l++])<<6|63&c[l++],u>8191&&((h||(h=[])).push(String.fromCharCode.apply(String,p)),u=0);return h?(u&&h.push(String.fromCharCode.apply(String,p.slice(0,u))),h.join("")):String.fromCharCode.apply(String,p.slice(0,u))},s.write=function(c,l,f){for(var a,h,p=f,u=0;u>6|192,l[f++]=63&a|128):(64512&a)==55296&&(64512&(h=c.charCodeAt(u+1)))==56320?(a=65536+((1023&a)<<10)+(1023&h),++u,l[f++]=a>>18|240,l[f++]=a>>12&63|128,l[f++]=a>>6&63|128,l[f++]=63&a|128):(l[f++]=a>>12|224,l[f++]=a>>6&63|128,l[f++]=63&a|128);return f-p}},3442:(_,n)=>{n.__esModule=!0;var s=function(){function c(l){if(!l)throw new TypeError("Invalid argument; `value` has no value.");this.value=c.EMPTY,l&&c.isGuid(l)&&(this.value=l)}return c.isGuid=function(l){var f=l.toString();return l&&(l instanceof c||c.validator.test(f))},c.create=function(){return new c([c.gen(2),c.gen(1),c.gen(1),c.gen(1),c.gen(3)].join("-"))},c.createEmpty=function(){return new c("emptyguid")},c.parse=function(l){return new c(l)},c.raw=function(){return[c.gen(2),c.gen(1),c.gen(1),c.gen(1),c.gen(3)].join("-")},c.gen=function(l){for(var f="",a=0;a{_.exports=s;var n=null;try{n=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function s(x,I,$){this.low=0|x,this.high=0|I,this.unsigned=!!$}function c(x){return(x&&x.__isLong__)===!0}s.prototype.__isLong__,Object.defineProperty(s.prototype,"__isLong__",{value:!0}),s.isLong=c;var l={},f={};function a(x,I){var $,z,L;return I?(L=0<=(x>>>=0)&&x<256)&&(z=f[x])?z:($=p(x,(0|x)<0?-1:0,!0),L&&(f[x]=$),$):(L=-128<=(x|=0)&&x<128)&&(z=l[x])?z:($=p(x,x<0?-1:0,!1),L&&(l[x]=$),$)}function h(x,I){if(isNaN(x))return I?m:g;if(I){if(x<0)return m;if(x>=r)return S}else{if(x<=-i)return A;if(x+1>=i)return v}return x<0?h(-x,I).neg():p(x%e|0,x/e|0,I)}function p(x,I,$){return new s(x,I,$)}s.fromInt=a,s.fromNumber=h,s.fromBits=p;var u=Math.pow;function o(x,I,$){if(x.length===0)throw Error("empty string");if(x==="NaN"||x==="Infinity"||x==="+Infinity"||x==="-Infinity")return g;if(typeof I=="number"?($=I,I=!1):I=!!I,($=$||10)<2||36<$)throw RangeError("radix");var z;if((z=x.indexOf("-"))>0)throw Error("interior hyphen");if(z===0)return o(x.substring(1),I,$).neg();for(var L=h(u($,8)),N=g,H=0;H>>0:this.low},O.toNumber=function(){return this.unsigned?(this.high>>>0)*e+(this.low>>>0):this.high*e+(this.low>>>0)},O.toString=function(x){if((x=x||10)<2||36>>0).toString(x);if((N=M).isZero())return j+H;for(;j.length<6;)j="0"+j;H=""+j+H}},O.getHighBits=function(){return this.high},O.getHighBitsUnsigned=function(){return this.high>>>0},O.getLowBits=function(){return this.low},O.getLowBitsUnsigned=function(){return this.low>>>0},O.getNumBitsAbs=function(){if(this.isNegative())return this.eq(A)?64:this.neg().getNumBitsAbs();for(var x=this.high!=0?this.high:this.low,I=31;I>0&&!(x&1<=0},O.isOdd=function(){return(1&this.low)==1},O.isEven=function(){return(1&this.low)==0},O.equals=function(x){return c(x)||(x=t(x)),(this.unsigned===x.unsigned||this.high>>>31!=1||x.high>>>31!=1)&&this.high===x.high&&this.low===x.low},O.eq=O.equals,O.notEquals=function(x){return!this.eq(x)},O.neq=O.notEquals,O.ne=O.notEquals,O.lessThan=function(x){return this.comp(x)<0},O.lt=O.lessThan,O.lessThanOrEqual=function(x){return this.comp(x)<=0},O.lte=O.lessThanOrEqual,O.le=O.lessThanOrEqual,O.greaterThan=function(x){return this.comp(x)>0},O.gt=O.greaterThan,O.greaterThanOrEqual=function(x){return this.comp(x)>=0},O.gte=O.greaterThanOrEqual,O.ge=O.greaterThanOrEqual,O.compare=function(x){if(c(x)||(x=t(x)),this.eq(x))return 0;var I=this.isNegative(),$=x.isNegative();return I&&!$?-1:!I&&$?1:this.unsigned?x.high>>>0>this.high>>>0||x.high===this.high&&x.low>>>0>this.low>>>0?-1:1:this.sub(x).isNegative()?-1:1},O.comp=O.compare,O.negate=function(){return!this.unsigned&&this.eq(A)?A:this.not().add(b)},O.neg=O.negate,O.add=function(x){c(x)||(x=t(x));var I=this.high>>>16,$=65535&this.high,z=this.low>>>16,L=65535&this.low,N=x.high>>>16,H=65535&x.high,M=x.low>>>16,j=0,Z=0,X=0,Q=0;return X+=(Q+=L+(65535&x.low))>>>16,Z+=(X+=z+M)>>>16,j+=(Z+=$+H)>>>16,j+=I+N,p((X&=65535)<<16|(Q&=65535),(j&=65535)<<16|(Z&=65535),this.unsigned)},O.subtract=function(x){return c(x)||(x=t(x)),this.add(x.neg())},O.sub=O.subtract,O.multiply=function(x){if(this.isZero())return g;if(c(x)||(x=t(x)),n)return p(n.mul(this.low,this.high,x.low,x.high),n.get_high(),this.unsigned);if(x.isZero())return g;if(this.eq(A))return x.isOdd()?A:g;if(x.eq(A))return this.isOdd()?A:g;if(this.isNegative())return x.isNegative()?this.neg().mul(x.neg()):this.neg().mul(x).neg();if(x.isNegative())return this.mul(x.neg()).neg();if(this.lt(d)&&x.lt(d))return h(this.toNumber()*x.toNumber(),this.unsigned);var I=this.high>>>16,$=65535&this.high,z=this.low>>>16,L=65535&this.low,N=x.high>>>16,H=65535&x.high,M=x.low>>>16,j=65535&x.low,Z=0,X=0,Q=0,ee=0;return Q+=(ee+=L*j)>>>16,X+=(Q+=z*j)>>>16,Q&=65535,X+=(Q+=L*M)>>>16,Z+=(X+=$*j)>>>16,X&=65535,Z+=(X+=z*M)>>>16,X&=65535,Z+=(X+=L*H)>>>16,Z+=I*j+$*M+z*H+L*N,p((Q&=65535)<<16|(ee&=65535),(Z&=65535)<<16|(X&=65535),this.unsigned)},O.mul=O.multiply,O.divide=function(x){if(c(x)||(x=t(x)),x.isZero())throw Error("division by zero");var I,$,z;if(n)return this.unsigned||this.high!==-2147483648||x.low!==-1||x.high!==-1?p((this.unsigned?n.div_u:n.div_s)(this.low,this.high,x.low,x.high),n.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?m:g;if(this.unsigned){if(x.unsigned||(x=x.toUnsigned()),x.gt(this))return m;if(x.gt(this.shru(1)))return y;z=m}else{if(this.eq(A))return x.eq(b)||x.eq(w)?A:x.eq(A)?b:(I=this.shr(1).div(x).shl(1)).eq(g)?x.isNegative()?b:w:($=this.sub(x.mul(I)),z=I.add($.div(x)));if(x.eq(A))return this.unsigned?m:g;if(this.isNegative())return x.isNegative()?this.neg().div(x.neg()):this.neg().div(x).neg();if(x.isNegative())return this.div(x.neg()).neg();z=g}for($=this;$.gte(x);){I=Math.max(1,Math.floor($.toNumber()/x.toNumber()));for(var L=Math.ceil(Math.log(I)/Math.LN2),N=L<=48?1:u(2,L-48),H=h(I),M=H.mul(x);M.isNegative()||M.gt($);)M=(H=h(I-=N,this.unsigned)).mul(x);H.isZero()&&(H=b),z=z.add(H),$=$.sub(M)}return z},O.div=O.divide,O.modulo=function(x){return c(x)||(x=t(x)),n?p((this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,x.low,x.high),n.get_high(),this.unsigned):this.sub(this.div(x).mul(x))},O.mod=O.modulo,O.rem=O.modulo,O.not=function(){return p(~this.low,~this.high,this.unsigned)},O.and=function(x){return c(x)||(x=t(x)),p(this.low&x.low,this.high&x.high,this.unsigned)},O.or=function(x){return c(x)||(x=t(x)),p(this.low|x.low,this.high|x.high,this.unsigned)},O.xor=function(x){return c(x)||(x=t(x)),p(this.low^x.low,this.high^x.high,this.unsigned)},O.shiftLeft=function(x){return c(x)&&(x=x.toInt()),(x&=63)==0?this:x<32?p(this.low<>>32-x,this.unsigned):p(0,this.low<>>x|this.high<<32-x,this.high>>x,this.unsigned):p(this.high>>x-32,this.high>=0?0:-1,this.unsigned)},O.shr=O.shiftRight,O.shiftRightUnsigned=function(x){if(c(x)&&(x=x.toInt()),(x&=63)==0)return this;var I=this.high;return x<32?p(this.low>>>x|I<<32-x,I>>>x,this.unsigned):p(x===32?I:I>>>x-32,0,this.unsigned)},O.shru=O.shiftRightUnsigned,O.shr_u=O.shiftRightUnsigned,O.toSigned=function(){return this.unsigned?p(this.low,this.high,!1):this},O.toUnsigned=function(){return this.unsigned?this:p(this.low,this.high,!0)},O.toBytes=function(x){return x?this.toBytesLE():this.toBytesBE()},O.toBytesLE=function(){var x=this.high,I=this.low;return[255&I,I>>>8&255,I>>>16&255,I>>>24,255&x,x>>>8&255,x>>>16&255,x>>>24]},O.toBytesBE=function(){var x=this.high,I=this.low;return[x>>>24,x>>>16&255,x>>>8&255,255&x,I>>>24,I>>>16&255,I>>>8&255,255&I]},s.fromBytes=function(x,I,$){return $?s.fromBytesLE(x,I):s.fromBytesBE(x,I)},s.fromBytesLE=function(x,I){return new s(x[0]|x[1]<<8|x[2]<<16|x[3]<<24,x[4]|x[5]<<8|x[6]<<16|x[7]<<24,I)},s.fromBytesBE=function(x,I){return new s(x[4]<<24|x[5]<<16|x[6]<<8|x[7],x[0]<<24|x[1]<<16|x[2]<<8|x[3],I)}},1446:(_,n,s)=>{var c,l,f,a=s(2100),h=a.Reader,p=a.Writer,u=a.util,o=a.roots.default||(a.roots.default={});o.onnx=((f={}).Version=(c={},(l=Object.create(c))[c[0]="_START_VERSION"]=0,l[c[1]="IR_VERSION_2017_10_10"]=1,l[c[2]="IR_VERSION_2017_10_30"]=2,l[c[3]="IR_VERSION_2017_11_3"]=3,l[c[4]="IR_VERSION_2019_1_22"]=4,l[c[5]="IR_VERSION"]=5,l),f.AttributeProto=function(){function t(e){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],e)for(var r=Object.keys(e),i=0;i>>3){case 1:d.name=e.string();break;case 21:d.refAttrName=e.string();break;case 13:d.docString=e.string();break;case 20:d.type=e.int32();break;case 2:d.f=e.float();break;case 3:d.i=e.int64();break;case 4:d.s=e.bytes();break;case 5:d.t=o.onnx.TensorProto.decode(e,e.uint32());break;case 6:d.g=o.onnx.GraphProto.decode(e,e.uint32());break;case 7:if(d.floats&&d.floats.length||(d.floats=[]),(7&g)==2)for(var m=e.uint32()+e.pos;e.pos>>0,e.i.high>>>0).toNumber())),e.s!=null&&(typeof e.s=="string"?u.base64.decode(e.s,r.s=u.newBuffer(u.base64.length(e.s)),0):e.s.length&&(r.s=e.s)),e.t!=null){if(typeof e.t!="object")throw TypeError(".onnx.AttributeProto.t: object expected");r.t=o.onnx.TensorProto.fromObject(e.t)}if(e.g!=null){if(typeof e.g!="object")throw TypeError(".onnx.AttributeProto.g: object expected");r.g=o.onnx.GraphProto.fromObject(e.g)}if(e.floats){if(!Array.isArray(e.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");r.floats=[];for(var i=0;i>>0,e.ints[i].high>>>0).toNumber())}if(e.strings){if(!Array.isArray(e.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");for(r.strings=[],i=0;i>>0,e.i.high>>>0).toNumber():e.i),e.s!=null&&e.hasOwnProperty("s")&&(i.s=r.bytes===String?u.base64.encode(e.s,0,e.s.length):r.bytes===Array?Array.prototype.slice.call(e.s):e.s),e.t!=null&&e.hasOwnProperty("t")&&(i.t=o.onnx.TensorProto.toObject(e.t,r)),e.g!=null&&e.hasOwnProperty("g")&&(i.g=o.onnx.GraphProto.toObject(e.g,r)),e.floats&&e.floats.length){i.floats=[];for(var g=0;g>>0,e.ints[g].high>>>0).toNumber():e.ints[g];if(e.strings&&e.strings.length)for(i.strings=[],g=0;g>>3){case 1:d.name=e.string();break;case 2:d.type=o.onnx.TypeProto.decode(e,e.uint32());break;case 3:d.docString=e.string();break;default:e.skipType(7&g)}}return d},t.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.name!=null&&e.hasOwnProperty("name")&&!u.isString(e.name))return"name: string expected";if(e.type!=null&&e.hasOwnProperty("type")){var r=o.onnx.TypeProto.verify(e.type);if(r)return"type."+r}return e.docString!=null&&e.hasOwnProperty("docString")&&!u.isString(e.docString)?"docString: string expected":null},t.fromObject=function(e){if(e instanceof o.onnx.ValueInfoProto)return e;var r=new o.onnx.ValueInfoProto;if(e.name!=null&&(r.name=String(e.name)),e.type!=null){if(typeof e.type!="object")throw TypeError(".onnx.ValueInfoProto.type: object expected");r.type=o.onnx.TypeProto.fromObject(e.type)}return e.docString!=null&&(r.docString=String(e.docString)),r},t.toObject=function(e,r){r||(r={});var i={};return r.defaults&&(i.name="",i.type=null,i.docString=""),e.name!=null&&e.hasOwnProperty("name")&&(i.name=e.name),e.type!=null&&e.hasOwnProperty("type")&&(i.type=o.onnx.TypeProto.toObject(e.type,r)),e.docString!=null&&e.hasOwnProperty("docString")&&(i.docString=e.docString),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),f.NodeProto=function(){function t(e){if(this.input=[],this.output=[],this.attribute=[],e)for(var r=Object.keys(e),i=0;i>>3){case 1:d.input&&d.input.length||(d.input=[]),d.input.push(e.string());break;case 2:d.output&&d.output.length||(d.output=[]),d.output.push(e.string());break;case 3:d.name=e.string();break;case 4:d.opType=e.string();break;case 7:d.domain=e.string();break;case 5:d.attribute&&d.attribute.length||(d.attribute=[]),d.attribute.push(o.onnx.AttributeProto.decode(e,e.uint32()));break;case 6:d.docString=e.string();break;default:e.skipType(7&g)}}return d},t.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.input!=null&&e.hasOwnProperty("input")){if(!Array.isArray(e.input))return"input: array expected";for(var r=0;r>>3){case 1:d.irVersion=e.int64();break;case 8:d.opsetImport&&d.opsetImport.length||(d.opsetImport=[]),d.opsetImport.push(o.onnx.OperatorSetIdProto.decode(e,e.uint32()));break;case 2:d.producerName=e.string();break;case 3:d.producerVersion=e.string();break;case 4:d.domain=e.string();break;case 5:d.modelVersion=e.int64();break;case 6:d.docString=e.string();break;case 7:d.graph=o.onnx.GraphProto.decode(e,e.uint32());break;case 14:d.metadataProps&&d.metadataProps.length||(d.metadataProps=[]),d.metadataProps.push(o.onnx.StringStringEntryProto.decode(e,e.uint32()));break;default:e.skipType(7&g)}}return d},t.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.irVersion!=null&&e.hasOwnProperty("irVersion")&&!(u.isInteger(e.irVersion)||e.irVersion&&u.isInteger(e.irVersion.low)&&u.isInteger(e.irVersion.high)))return"irVersion: integer|Long expected";if(e.opsetImport!=null&&e.hasOwnProperty("opsetImport")){if(!Array.isArray(e.opsetImport))return"opsetImport: array expected";for(var r=0;r>>0,e.irVersion.high>>>0).toNumber())),e.opsetImport){if(!Array.isArray(e.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");r.opsetImport=[];for(var i=0;i>>0,e.modelVersion.high>>>0).toNumber())),e.docString!=null&&(r.docString=String(e.docString)),e.graph!=null){if(typeof e.graph!="object")throw TypeError(".onnx.ModelProto.graph: object expected");r.graph=o.onnx.GraphProto.fromObject(e.graph)}if(e.metadataProps){if(!Array.isArray(e.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");for(r.metadataProps=[],i=0;i>>0,e.irVersion.high>>>0).toNumber():e.irVersion),e.producerName!=null&&e.hasOwnProperty("producerName")&&(i.producerName=e.producerName),e.producerVersion!=null&&e.hasOwnProperty("producerVersion")&&(i.producerVersion=e.producerVersion),e.domain!=null&&e.hasOwnProperty("domain")&&(i.domain=e.domain),e.modelVersion!=null&&e.hasOwnProperty("modelVersion")&&(typeof e.modelVersion=="number"?i.modelVersion=r.longs===String?String(e.modelVersion):e.modelVersion:i.modelVersion=r.longs===String?u.Long.prototype.toString.call(e.modelVersion):r.longs===Number?new u.LongBits(e.modelVersion.low>>>0,e.modelVersion.high>>>0).toNumber():e.modelVersion),e.docString!=null&&e.hasOwnProperty("docString")&&(i.docString=e.docString),e.graph!=null&&e.hasOwnProperty("graph")&&(i.graph=o.onnx.GraphProto.toObject(e.graph,r)),e.opsetImport&&e.opsetImport.length){i.opsetImport=[];for(var g=0;g>>3){case 1:d.key=e.string();break;case 2:d.value=e.string();break;default:e.skipType(7&g)}}return d},t.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},t.verify=function(e){return typeof e!="object"||e===null?"object expected":e.key!=null&&e.hasOwnProperty("key")&&!u.isString(e.key)?"key: string expected":e.value!=null&&e.hasOwnProperty("value")&&!u.isString(e.value)?"value: string expected":null},t.fromObject=function(e){if(e instanceof o.onnx.StringStringEntryProto)return e;var r=new o.onnx.StringStringEntryProto;return e.key!=null&&(r.key=String(e.key)),e.value!=null&&(r.value=String(e.value)),r},t.toObject=function(e,r){r||(r={});var i={};return r.defaults&&(i.key="",i.value=""),e.key!=null&&e.hasOwnProperty("key")&&(i.key=e.key),e.value!=null&&e.hasOwnProperty("value")&&(i.value=e.value),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),f.TensorAnnotation=function(){function t(e){if(this.quantParameterTensorNames=[],e)for(var r=Object.keys(e),i=0;i>>3){case 1:d.tensorName=e.string();break;case 2:d.quantParameterTensorNames&&d.quantParameterTensorNames.length||(d.quantParameterTensorNames=[]),d.quantParameterTensorNames.push(o.onnx.StringStringEntryProto.decode(e,e.uint32()));break;default:e.skipType(7&g)}}return d},t.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.tensorName!=null&&e.hasOwnProperty("tensorName")&&!u.isString(e.tensorName))return"tensorName: string expected";if(e.quantParameterTensorNames!=null&&e.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(e.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var r=0;r>>3){case 1:d.node&&d.node.length||(d.node=[]),d.node.push(o.onnx.NodeProto.decode(e,e.uint32()));break;case 2:d.name=e.string();break;case 5:d.initializer&&d.initializer.length||(d.initializer=[]),d.initializer.push(o.onnx.TensorProto.decode(e,e.uint32()));break;case 10:d.docString=e.string();break;case 11:d.input&&d.input.length||(d.input=[]),d.input.push(o.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 12:d.output&&d.output.length||(d.output=[]),d.output.push(o.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 13:d.valueInfo&&d.valueInfo.length||(d.valueInfo=[]),d.valueInfo.push(o.onnx.ValueInfoProto.decode(e,e.uint32()));break;case 14:d.quantizationAnnotation&&d.quantizationAnnotation.length||(d.quantizationAnnotation=[]),d.quantizationAnnotation.push(o.onnx.TensorAnnotation.decode(e,e.uint32()));break;default:e.skipType(7&g)}}return d},t.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.node!=null&&e.hasOwnProperty("node")){if(!Array.isArray(e.node))return"node: array expected";for(var r=0;r>>3){case 1:if(d.dims&&d.dims.length||(d.dims=[]),(7&g)==2)for(var m=e.uint32()+e.pos;e.pos>>0,e.dims[i].high>>>0).toNumber())}if(e.dataType!=null&&(r.dataType=0|e.dataType),e.segment!=null){if(typeof e.segment!="object")throw TypeError(".onnx.TensorProto.segment: object expected");r.segment=o.onnx.TensorProto.Segment.fromObject(e.segment)}if(e.floatData){if(!Array.isArray(e.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");for(r.floatData=[],i=0;i>>0,e.int64Data[i].high>>>0).toNumber())}if(e.name!=null&&(r.name=String(e.name)),e.docString!=null&&(r.docString=String(e.docString)),e.rawData!=null&&(typeof e.rawData=="string"?u.base64.decode(e.rawData,r.rawData=u.newBuffer(u.base64.length(e.rawData)),0):e.rawData.length&&(r.rawData=e.rawData)),e.externalData){if(!Array.isArray(e.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");for(r.externalData=[],i=0;i>>0,e.uint64Data[i].high>>>0).toNumber(!0))}return r},t.toObject=function(e,r){r||(r={});var i={};if((r.arrays||r.defaults)&&(i.dims=[],i.floatData=[],i.int32Data=[],i.stringData=[],i.int64Data=[],i.doubleData=[],i.uint64Data=[],i.externalData=[]),r.defaults&&(i.dataType=0,i.segment=null,i.name="",r.bytes===String?i.rawData="":(i.rawData=[],r.bytes!==Array&&(i.rawData=u.newBuffer(i.rawData))),i.docString="",i.dataLocation=r.enums===String?"DEFAULT":0),e.dims&&e.dims.length){i.dims=[];for(var d=0;d>>0,e.dims[d].high>>>0).toNumber():e.dims[d]}if(e.dataType!=null&&e.hasOwnProperty("dataType")&&(i.dataType=e.dataType),e.segment!=null&&e.hasOwnProperty("segment")&&(i.segment=o.onnx.TensorProto.Segment.toObject(e.segment,r)),e.floatData&&e.floatData.length)for(i.floatData=[],d=0;d>>0,e.int64Data[d].high>>>0).toNumber():e.int64Data[d];if(e.name!=null&&e.hasOwnProperty("name")&&(i.name=e.name),e.rawData!=null&&e.hasOwnProperty("rawData")&&(i.rawData=r.bytes===String?u.base64.encode(e.rawData,0,e.rawData.length):r.bytes===Array?Array.prototype.slice.call(e.rawData):e.rawData),e.doubleData&&e.doubleData.length)for(i.doubleData=[],d=0;d>>0,e.uint64Data[d].high>>>0).toNumber(!0):e.uint64Data[d];if(e.docString!=null&&e.hasOwnProperty("docString")&&(i.docString=e.docString),e.externalData&&e.externalData.length)for(i.externalData=[],d=0;d>>3){case 1:g.begin=r.int64();break;case 2:g.end=r.int64();break;default:r.skipType(7&m)}}return g},e.decodeDelimited=function(r){return r instanceof h||(r=new h(r)),this.decode(r,r.uint32())},e.verify=function(r){return typeof r!="object"||r===null?"object expected":r.begin!=null&&r.hasOwnProperty("begin")&&!(u.isInteger(r.begin)||r.begin&&u.isInteger(r.begin.low)&&u.isInteger(r.begin.high))?"begin: integer|Long expected":r.end!=null&&r.hasOwnProperty("end")&&!(u.isInteger(r.end)||r.end&&u.isInteger(r.end.low)&&u.isInteger(r.end.high))?"end: integer|Long expected":null},e.fromObject=function(r){if(r instanceof o.onnx.TensorProto.Segment)return r;var i=new o.onnx.TensorProto.Segment;return r.begin!=null&&(u.Long?(i.begin=u.Long.fromValue(r.begin)).unsigned=!1:typeof r.begin=="string"?i.begin=parseInt(r.begin,10):typeof r.begin=="number"?i.begin=r.begin:typeof r.begin=="object"&&(i.begin=new u.LongBits(r.begin.low>>>0,r.begin.high>>>0).toNumber())),r.end!=null&&(u.Long?(i.end=u.Long.fromValue(r.end)).unsigned=!1:typeof r.end=="string"?i.end=parseInt(r.end,10):typeof r.end=="number"?i.end=r.end:typeof r.end=="object"&&(i.end=new u.LongBits(r.end.low>>>0,r.end.high>>>0).toNumber())),i},e.toObject=function(r,i){i||(i={});var d={};if(i.defaults){if(u.Long){var g=new u.Long(0,0,!1);d.begin=i.longs===String?g.toString():i.longs===Number?g.toNumber():g}else d.begin=i.longs===String?"0":0;u.Long?(g=new u.Long(0,0,!1),d.end=i.longs===String?g.toString():i.longs===Number?g.toNumber():g):d.end=i.longs===String?"0":0}return r.begin!=null&&r.hasOwnProperty("begin")&&(typeof r.begin=="number"?d.begin=i.longs===String?String(r.begin):r.begin:d.begin=i.longs===String?u.Long.prototype.toString.call(r.begin):i.longs===Number?new u.LongBits(r.begin.low>>>0,r.begin.high>>>0).toNumber():r.begin),r.end!=null&&r.hasOwnProperty("end")&&(typeof r.end=="number"?d.end=i.longs===String?String(r.end):r.end:d.end=i.longs===String?u.Long.prototype.toString.call(r.end):i.longs===Number?new u.LongBits(r.end.low>>>0,r.end.high>>>0).toNumber():r.end),d},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e}(),t.DataLocation=function(){var e={},r=Object.create(e);return r[e[0]="DEFAULT"]=0,r[e[1]="EXTERNAL"]=1,r}(),t}(),f.TensorShapeProto=function(){function t(e){if(this.dim=[],e)for(var r=Object.keys(e),i=0;i>>3==1?(d.dim&&d.dim.length||(d.dim=[]),d.dim.push(o.onnx.TensorShapeProto.Dimension.decode(e,e.uint32()))):e.skipType(7&g)}return d},t.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},t.verify=function(e){if(typeof e!="object"||e===null)return"object expected";if(e.dim!=null&&e.hasOwnProperty("dim")){if(!Array.isArray(e.dim))return"dim: array expected";for(var r=0;r>>3){case 1:m.dimValue=i.int64();break;case 2:m.dimParam=i.string();break;case 3:m.denotation=i.string();break;default:i.skipType(7&b)}}return m},e.decodeDelimited=function(i){return i instanceof h||(i=new h(i)),this.decode(i,i.uint32())},e.verify=function(i){if(typeof i!="object"||i===null)return"object expected";var d={};if(i.dimValue!=null&&i.hasOwnProperty("dimValue")&&(d.value=1,!(u.isInteger(i.dimValue)||i.dimValue&&u.isInteger(i.dimValue.low)&&u.isInteger(i.dimValue.high))))return"dimValue: integer|Long expected";if(i.dimParam!=null&&i.hasOwnProperty("dimParam")){if(d.value===1)return"value: multiple values";if(d.value=1,!u.isString(i.dimParam))return"dimParam: string expected"}return i.denotation!=null&&i.hasOwnProperty("denotation")&&!u.isString(i.denotation)?"denotation: string expected":null},e.fromObject=function(i){if(i instanceof o.onnx.TensorShapeProto.Dimension)return i;var d=new o.onnx.TensorShapeProto.Dimension;return i.dimValue!=null&&(u.Long?(d.dimValue=u.Long.fromValue(i.dimValue)).unsigned=!1:typeof i.dimValue=="string"?d.dimValue=parseInt(i.dimValue,10):typeof i.dimValue=="number"?d.dimValue=i.dimValue:typeof i.dimValue=="object"&&(d.dimValue=new u.LongBits(i.dimValue.low>>>0,i.dimValue.high>>>0).toNumber())),i.dimParam!=null&&(d.dimParam=String(i.dimParam)),i.denotation!=null&&(d.denotation=String(i.denotation)),d},e.toObject=function(i,d){d||(d={});var g={};return d.defaults&&(g.denotation=""),i.dimValue!=null&&i.hasOwnProperty("dimValue")&&(typeof i.dimValue=="number"?g.dimValue=d.longs===String?String(i.dimValue):i.dimValue:g.dimValue=d.longs===String?u.Long.prototype.toString.call(i.dimValue):d.longs===Number?new u.LongBits(i.dimValue.low>>>0,i.dimValue.high>>>0).toNumber():i.dimValue,d.oneofs&&(g.value="dimValue")),i.dimParam!=null&&i.hasOwnProperty("dimParam")&&(g.dimParam=i.dimParam,d.oneofs&&(g.value="dimParam")),i.denotation!=null&&i.hasOwnProperty("denotation")&&(g.denotation=i.denotation),g},e.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},e}(),t}(),f.TypeProto=function(){function t(r){if(r)for(var i=Object.keys(r),d=0;d>>3){case 1:g.tensorType=o.onnx.TypeProto.Tensor.decode(r,r.uint32());break;case 6:g.denotation=r.string();break;default:r.skipType(7&m)}}return g},t.decodeDelimited=function(r){return r instanceof h||(r=new h(r)),this.decode(r,r.uint32())},t.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.tensorType!=null&&r.hasOwnProperty("tensorType")){var i=o.onnx.TypeProto.Tensor.verify(r.tensorType);if(i)return"tensorType."+i}return r.denotation!=null&&r.hasOwnProperty("denotation")&&!u.isString(r.denotation)?"denotation: string expected":null},t.fromObject=function(r){if(r instanceof o.onnx.TypeProto)return r;var i=new o.onnx.TypeProto;if(r.tensorType!=null){if(typeof r.tensorType!="object")throw TypeError(".onnx.TypeProto.tensorType: object expected");i.tensorType=o.onnx.TypeProto.Tensor.fromObject(r.tensorType)}return r.denotation!=null&&(i.denotation=String(r.denotation)),i},t.toObject=function(r,i){i||(i={});var d={};return i.defaults&&(d.denotation=""),r.tensorType!=null&&r.hasOwnProperty("tensorType")&&(d.tensorType=o.onnx.TypeProto.Tensor.toObject(r.tensorType,i),i.oneofs&&(d.value="tensorType")),r.denotation!=null&&r.hasOwnProperty("denotation")&&(d.denotation=r.denotation),d},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t.Tensor=function(){function r(i){if(i)for(var d=Object.keys(i),g=0;g>>3){case 1:m.elemType=i.int32();break;case 2:m.shape=o.onnx.TensorShapeProto.decode(i,i.uint32());break;default:i.skipType(7&b)}}return m},r.decodeDelimited=function(i){return i instanceof h||(i=new h(i)),this.decode(i,i.uint32())},r.verify=function(i){if(typeof i!="object"||i===null)return"object expected";if(i.elemType!=null&&i.hasOwnProperty("elemType")&&!u.isInteger(i.elemType))return"elemType: integer expected";if(i.shape!=null&&i.hasOwnProperty("shape")){var d=o.onnx.TensorShapeProto.verify(i.shape);if(d)return"shape."+d}return null},r.fromObject=function(i){if(i instanceof o.onnx.TypeProto.Tensor)return i;var d=new o.onnx.TypeProto.Tensor;if(i.elemType!=null&&(d.elemType=0|i.elemType),i.shape!=null){if(typeof i.shape!="object")throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");d.shape=o.onnx.TensorShapeProto.fromObject(i.shape)}return d},r.toObject=function(i,d){d||(d={});var g={};return d.defaults&&(g.elemType=0,g.shape=null),i.elemType!=null&&i.hasOwnProperty("elemType")&&(g.elemType=i.elemType),i.shape!=null&&i.hasOwnProperty("shape")&&(g.shape=o.onnx.TensorShapeProto.toObject(i.shape,d)),g},r.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},r}(),t}(),f.OperatorSetIdProto=function(){function t(e){if(e)for(var r=Object.keys(e),i=0;i>>3){case 1:d.domain=e.string();break;case 2:d.version=e.int64();break;default:e.skipType(7&g)}}return d},t.decodeDelimited=function(e){return e instanceof h||(e=new h(e)),this.decode(e,e.uint32())},t.verify=function(e){return typeof e!="object"||e===null?"object expected":e.domain!=null&&e.hasOwnProperty("domain")&&!u.isString(e.domain)?"domain: string expected":e.version!=null&&e.hasOwnProperty("version")&&!(u.isInteger(e.version)||e.version&&u.isInteger(e.version.low)&&u.isInteger(e.version.high))?"version: integer|Long expected":null},t.fromObject=function(e){if(e instanceof o.onnx.OperatorSetIdProto)return e;var r=new o.onnx.OperatorSetIdProto;return e.domain!=null&&(r.domain=String(e.domain)),e.version!=null&&(u.Long?(r.version=u.Long.fromValue(e.version)).unsigned=!1:typeof e.version=="string"?r.version=parseInt(e.version,10):typeof e.version=="number"?r.version=e.version:typeof e.version=="object"&&(r.version=new u.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber())),r},t.toObject=function(e,r){r||(r={});var i={};if(r.defaults)if(i.domain="",u.Long){var d=new u.Long(0,0,!1);i.version=r.longs===String?d.toString():r.longs===Number?d.toNumber():d}else i.version=r.longs===String?"0":0;return e.domain!=null&&e.hasOwnProperty("domain")&&(i.domain=e.domain),e.version!=null&&e.hasOwnProperty("version")&&(typeof e.version=="number"?i.version=r.longs===String?String(e.version):e.version:i.version=r.longs===String?u.Long.prototype.toString.call(e.version):r.longs===Number?new u.LongBits(e.version.low>>>0,e.version.high>>>0).toNumber():e.version),i},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),f),_.exports=o},2100:(_,n,s)=>{_.exports=s(9482)},9482:(_,n,s)=>{var c=n;function l(){c.util._configure(),c.Writer._configure(c.BufferWriter),c.Reader._configure(c.BufferReader)}c.build="minimal",c.Writer=s(1173),c.BufferWriter=s(3155),c.Reader=s(1408),c.BufferReader=s(593),c.util=s(9693),c.rpc=s(5994),c.roots=s(5054),c.configure=l,l()},1408:(_,n,s)=>{_.exports=p;var c,l=s(9693),f=l.LongBits,a=l.utf8;function h(d,g){return RangeError("index out of range: "+d.pos+" + "+(g||1)+" > "+d.len)}function p(d){this.buf=d,this.pos=0,this.len=d.length}var u,o=typeof Uint8Array<"u"?function(d){if(d instanceof Uint8Array||Array.isArray(d))return new p(d);throw Error("illegal buffer")}:function(d){if(Array.isArray(d))return new p(d);throw Error("illegal buffer")},t=function(){return l.Buffer?function(d){return(p.create=function(g){return l.Buffer.isBuffer(g)?new c(g):o(g)})(d)}:o};function e(){var d=new f(0,0),g=0;if(!(this.len-this.pos>4)){for(;g<3;++g){if(this.pos>=this.len)throw h(this);if(d.lo=(d.lo|(127&this.buf[this.pos])<<7*g)>>>0,this.buf[this.pos++]<128)return d}return d.lo=(d.lo|(127&this.buf[this.pos++])<<7*g)>>>0,d}for(;g<4;++g)if(d.lo=(d.lo|(127&this.buf[this.pos])<<7*g)>>>0,this.buf[this.pos++]<128)return d;if(d.lo=(d.lo|(127&this.buf[this.pos])<<28)>>>0,d.hi=(d.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return d;if(g=0,this.len-this.pos>4){for(;g<5;++g)if(d.hi=(d.hi|(127&this.buf[this.pos])<<7*g+3)>>>0,this.buf[this.pos++]<128)return d}else for(;g<5;++g){if(this.pos>=this.len)throw h(this);if(d.hi=(d.hi|(127&this.buf[this.pos])<<7*g+3)>>>0,this.buf[this.pos++]<128)return d}throw Error("invalid varint encoding")}function r(d,g){return(d[g-4]|d[g-3]<<8|d[g-2]<<16|d[g-1]<<24)>>>0}function i(){if(this.pos+8>this.len)throw h(this,8);return new f(r(this.buf,this.pos+=4),r(this.buf,this.pos+=4))}p.create=t(),p.prototype._slice=l.Array.prototype.subarray||l.Array.prototype.slice,p.prototype.uint32=(u=4294967295,function(){if(u=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(u=(u|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)||(u=(u|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)||(u=(u|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)||(u=(u|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128))return u;if((this.pos+=5)>this.len)throw this.pos=this.len,h(this,10);return u}),p.prototype.int32=function(){return 0|this.uint32()},p.prototype.sint32=function(){var d=this.uint32();return d>>>1^-(1&d)|0},p.prototype.bool=function(){return this.uint32()!==0},p.prototype.fixed32=function(){if(this.pos+4>this.len)throw h(this,4);return r(this.buf,this.pos+=4)},p.prototype.sfixed32=function(){if(this.pos+4>this.len)throw h(this,4);return 0|r(this.buf,this.pos+=4)},p.prototype.float=function(){if(this.pos+4>this.len)throw h(this,4);var d=l.float.readFloatLE(this.buf,this.pos);return this.pos+=4,d},p.prototype.double=function(){if(this.pos+8>this.len)throw h(this,4);var d=l.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,d},p.prototype.bytes=function(){var d=this.uint32(),g=this.pos,m=this.pos+d;if(m>this.len)throw h(this,d);return this.pos+=d,Array.isArray(this.buf)?this.buf.slice(g,m):g===m?new this.buf.constructor(0):this._slice.call(this.buf,g,m)},p.prototype.string=function(){var d=this.bytes();return a.read(d,0,d.length)},p.prototype.skip=function(d){if(typeof d=="number"){if(this.pos+d>this.len)throw h(this,d);this.pos+=d}else do if(this.pos>=this.len)throw h(this);while(128&this.buf[this.pos++]);return this},p.prototype.skipType=function(d){switch(d){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(d=7&this.uint32())!=4;)this.skipType(d);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+d+" at offset "+this.pos)}return this},p._configure=function(d){c=d,p.create=t(),c._configure();var g=l.Long?"toLong":"toNumber";l.merge(p.prototype,{int64:function(){return e.call(this)[g](!1)},uint64:function(){return e.call(this)[g](!0)},sint64:function(){return e.call(this).zzDecode()[g](!1)},fixed64:function(){return i.call(this)[g](!0)},sfixed64:function(){return i.call(this)[g](!1)}})}},593:(_,n,s)=>{_.exports=f;var c=s(1408);(f.prototype=Object.create(c.prototype)).constructor=f;var l=s(9693);function f(a){c.call(this,a)}f._configure=function(){l.Buffer&&(f.prototype._slice=l.Buffer.prototype.slice)},f.prototype.string=function(){var a=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+a,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+a,this.len))},f._configure()},5054:_=>{_.exports={}},5994:(_,n,s)=>{n.Service=s(7948)},7948:(_,n,s)=>{_.exports=l;var c=s(9693);function l(f,a,h){if(typeof f!="function")throw TypeError("rpcImpl must be a function");c.EventEmitter.call(this),this.rpcImpl=f,this.requestDelimited=!!a,this.responseDelimited=!!h}(l.prototype=Object.create(c.EventEmitter.prototype)).constructor=l,l.prototype.rpcCall=function f(a,h,p,u,o){if(!u)throw TypeError("request must be specified");var t=this;if(!o)return c.asPromise(f,t,a,h,p,u);if(t.rpcImpl)try{return t.rpcImpl(a,h[t.requestDelimited?"encodeDelimited":"encode"](u).finish(),function(e,r){if(e)return t.emit("error",e,a),o(e);if(r!==null){if(!(r instanceof p))try{r=p[t.responseDelimited?"decodeDelimited":"decode"](r)}catch(i){return t.emit("error",i,a),o(i)}return t.emit("data",r,a),o(null,r)}t.end(!0)})}catch(e){return t.emit("error",e,a),void setTimeout(function(){o(e)},0)}else setTimeout(function(){o(Error("already ended"))},0)},l.prototype.end=function(f){return this.rpcImpl&&(f||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},1945:(_,n,s)=>{_.exports=l;var c=s(9693);function l(p,u){this.lo=p>>>0,this.hi=u>>>0}var f=l.zero=new l(0,0);f.toNumber=function(){return 0},f.zzEncode=f.zzDecode=function(){return this},f.length=function(){return 1};var a=l.zeroHash="\0\0\0\0\0\0\0\0";l.fromNumber=function(p){if(p===0)return f;var u=p<0;u&&(p=-p);var o=p>>>0,t=(p-o)/4294967296>>>0;return u&&(t=~t>>>0,o=~o>>>0,++o>4294967295&&(o=0,++t>4294967295&&(t=0))),new l(o,t)},l.from=function(p){if(typeof p=="number")return l.fromNumber(p);if(c.isString(p)){if(!c.Long)return l.fromNumber(parseInt(p,10));p=c.Long.fromString(p)}return p.low||p.high?new l(p.low>>>0,p.high>>>0):f},l.prototype.toNumber=function(p){if(!p&&this.hi>>>31){var u=1+~this.lo>>>0,o=~this.hi>>>0;return u||(o=o+1>>>0),-(u+4294967296*o)}return this.lo+4294967296*this.hi},l.prototype.toLong=function(p){return c.Long?new c.Long(0|this.lo,0|this.hi,!!p):{low:0|this.lo,high:0|this.hi,unsigned:!!p}};var h=String.prototype.charCodeAt;l.fromHash=function(p){return p===a?f:new l((h.call(p,0)|h.call(p,1)<<8|h.call(p,2)<<16|h.call(p,3)<<24)>>>0,(h.call(p,4)|h.call(p,5)<<8|h.call(p,6)<<16|h.call(p,7)<<24)>>>0)},l.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},l.prototype.zzEncode=function(){var p=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^p)>>>0,this.lo=(this.lo<<1^p)>>>0,this},l.prototype.zzDecode=function(){var p=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^p)>>>0,this.hi=(this.hi>>>1^p)>>>0,this},l.prototype.length=function(){var p=this.lo,u=(this.lo>>>28|this.hi<<4)>>>0,o=this.hi>>>24;return o===0?u===0?p<16384?p<128?1:2:p<2097152?3:4:u<16384?u<128?5:6:u<2097152?7:8:o<128?9:10}},9693:function(_,n,s){var c=n;function l(a,h,p){for(var u=Object.keys(h),o=0;o0)},c.Buffer=function(){try{var a=c.inquire("buffer").Buffer;return a.prototype.utf8Write?a:null}catch{return null}}(),c._Buffer_from=null,c._Buffer_allocUnsafe=null,c.newBuffer=function(a){return typeof a=="number"?c.Buffer?c._Buffer_allocUnsafe(a):new c.Array(a):c.Buffer?c._Buffer_from(a):typeof Uint8Array>"u"?a:new Uint8Array(a)},c.Array=typeof Uint8Array<"u"?Uint8Array:Array,c.Long=c.global.dcodeIO&&c.global.dcodeIO.Long||c.global.Long||c.inquire("long"),c.key2Re=/^true|false|0|1$/,c.key32Re=/^-?(?:0|[1-9][0-9]*)$/,c.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,c.longToHash=function(a){return a?c.LongBits.from(a).toHash():c.LongBits.zeroHash},c.longFromHash=function(a,h){var p=c.LongBits.fromHash(a);return c.Long?c.Long.fromBits(p.lo,p.hi,h):p.toNumber(!!h)},c.merge=l,c.lcFirst=function(a){return a.charAt(0).toLowerCase()+a.substring(1)},c.newError=f,c.ProtocolError=f("ProtocolError"),c.oneOfGetter=function(a){for(var h={},p=0;p-1;--o)if(h[u[o]]===1&&this[u[o]]!==void 0&&this[u[o]]!==null)return u[o]}},c.oneOfSetter=function(a){return function(h){for(var p=0;p{_.exports=t;var c,l=s(9693),f=l.LongBits,a=l.base64,h=l.utf8;function p(b,y,w){this.fn=b,this.len=y,this.next=void 0,this.val=w}function u(){}function o(b){this.head=b.head,this.tail=b.tail,this.len=b.len,this.next=b.states}function t(){this.len=0,this.head=new p(u,0,0),this.tail=this.head,this.states=null}var e=function(){return l.Buffer?function(){return(t.create=function(){return new c})()}:function(){return new t}};function r(b,y,w){y[w]=255&b}function i(b,y){this.len=b,this.next=void 0,this.val=y}function d(b,y,w){for(;b.hi;)y[w++]=127&b.lo|128,b.lo=(b.lo>>>7|b.hi<<25)>>>0,b.hi>>>=7;for(;b.lo>127;)y[w++]=127&b.lo|128,b.lo=b.lo>>>7;y[w++]=b.lo}function g(b,y,w){y[w]=255&b,y[w+1]=b>>>8&255,y[w+2]=b>>>16&255,y[w+3]=b>>>24}t.create=e(),t.alloc=function(b){return new l.Array(b)},l.Array!==Array&&(t.alloc=l.pool(t.alloc,l.Array.prototype.subarray)),t.prototype._push=function(b,y,w){return this.tail=this.tail.next=new p(b,y,w),this.len+=y,this},i.prototype=Object.create(p.prototype),i.prototype.fn=function(b,y,w){for(;b>127;)y[w++]=127&b|128,b>>>=7;y[w]=b},t.prototype.uint32=function(b){return this.len+=(this.tail=this.tail.next=new i((b>>>=0)<128?1:b<16384?2:b<2097152?3:b<268435456?4:5,b)).len,this},t.prototype.int32=function(b){return b<0?this._push(d,10,f.fromNumber(b)):this.uint32(b)},t.prototype.sint32=function(b){return this.uint32((b<<1^b>>31)>>>0)},t.prototype.uint64=function(b){var y=f.from(b);return this._push(d,y.length(),y)},t.prototype.int64=t.prototype.uint64,t.prototype.sint64=function(b){var y=f.from(b).zzEncode();return this._push(d,y.length(),y)},t.prototype.bool=function(b){return this._push(r,1,b?1:0)},t.prototype.fixed32=function(b){return this._push(g,4,b>>>0)},t.prototype.sfixed32=t.prototype.fixed32,t.prototype.fixed64=function(b){var y=f.from(b);return this._push(g,4,y.lo)._push(g,4,y.hi)},t.prototype.sfixed64=t.prototype.fixed64,t.prototype.float=function(b){return this._push(l.float.writeFloatLE,4,b)},t.prototype.double=function(b){return this._push(l.float.writeDoubleLE,8,b)};var m=l.Array.prototype.set?function(b,y,w){y.set(b,w)}:function(b,y,w){for(var v=0;v>>0;if(!y)return this._push(r,1,0);if(l.isString(b)){var w=t.alloc(y=a.length(b));a.decode(b,w,0),b=w}return this.uint32(y)._push(m,y,b)},t.prototype.string=function(b){var y=h.length(b);return y?this.uint32(y)._push(h.write,y,b):this._push(r,1,0)},t.prototype.fork=function(){return this.states=new o(this),this.head=this.tail=new p(u,0,0),this.len=0,this},t.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new p(u,0,0),this.len=0),this},t.prototype.ldelim=function(){var b=this.head,y=this.tail,w=this.len;return this.reset().uint32(w),w&&(this.tail.next=b.next,this.tail=y,this.len+=w),this},t.prototype.finish=function(){for(var b=this.head.next,y=this.constructor.alloc(this.len),w=0;b;)b.fn(b.val,y,w),w+=b.len,b=b.next;return y},t._configure=function(b){c=b,t.create=e(),c._configure()}},3155:(_,n,s)=>{_.exports=f;var c=s(1173);(f.prototype=Object.create(c.prototype)).constructor=f;var l=s(9693);function f(){c.call(this)}function a(h,p,u){h.length<40?l.utf8.write(h,p,u):p.utf8Write?p.utf8Write(h,u):p.write(h,u)}f._configure=function(){f.alloc=l._Buffer_allocUnsafe,f.writeBytesBuffer=l.Buffer&&l.Buffer.prototype instanceof Uint8Array&&l.Buffer.prototype.set.name==="set"?function(h,p,u){p.set(h,u)}:function(h,p,u){if(h.copy)h.copy(p,u,0,h.length);else for(var o=0;o>>0;return this.uint32(p),p&&this._push(f.writeBytesBuffer,p,h),this},f.prototype.string=function(h){var p=l.Buffer.byteLength(h);return this.uint32(p),p&&this._push(a,p,h),this},f._configure()},7714:(_,n,s)=>{n.R=void 0;const c=s(6919),l=s(7448);n.R=new class{async init(){}async createSessionHandler(f,a){const h=new c.Session(a);return await h.loadModel(f),new l.OnnxjsSessionHandler(h)}}},4200:(_,n,s)=>{n.c8=n.rX=void 0;const c=s(1670),l=s(5381),f=s(2157),a=s(2306);n.rX=()=>{if((typeof c.env.wasm.initTimeout!="number"||c.env.wasm.initTimeout<0)&&(c.env.wasm.initTimeout=0),typeof c.env.wasm.simd!="boolean"&&(c.env.wasm.simd=!0),typeof c.env.wasm.proxy!="boolean"&&(c.env.wasm.proxy=!1),typeof c.env.wasm.numThreads!="number"||!Number.isInteger(c.env.wasm.numThreads)||c.env.wasm.numThreads<=0){const h=typeof navigator>"u"?(0,l.cpus)().length:navigator.hardwareConcurrency;c.env.wasm.numThreads=Math.min(4,Math.ceil((h||1)/2))}},n.c8=new class{async init(){(0,n.rX)(),await(0,f.initWasm)()}async createSessionHandler(h,p){const u=new a.OnnxruntimeWebAssemblySessionHandler;return await u.loadModel(h,p),Promise.resolve(u)}}},6018:function(_,n,s){var c=this&&this.__createBinding||(Object.create?function(a,h,p,u){u===void 0&&(u=p);var o=Object.getOwnPropertyDescriptor(h,p);o&&!("get"in o?!h.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return h[p]}}),Object.defineProperty(a,u,o)}:function(a,h,p,u){u===void 0&&(u=p),a[u]=h[p]}),l=this&&this.__exportStar||function(a,h){for(var p in a)p==="default"||Object.prototype.hasOwnProperty.call(h,p)||c(h,a,p)};Object.defineProperty(n,"__esModule",{value:!0}),l(s(1670),n);const f=s(1670);{const a=s(7714).R;(0,f.registerBackend)("webgl",a,-10)}{const a=s(4200).c8;(0,f.registerBackend)("cpu",a,10),(0,f.registerBackend)("wasm",a,10),(0,f.registerBackend)("xnnpack",a,9)}},246:(_,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createAttributeWithCacheKey=void 0;class s{constructor(l){Object.assign(this,l)}get cacheKey(){return this._cacheKey||(this._cacheKey=Object.getOwnPropertyNames(this).sort().map(l=>`${this[l]}`).join(";")),this._cacheKey}}n.createAttributeWithCacheKey=c=>new s(c)},7778:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Attribute=void 0;const c=s(1446),l=s(9395),f=s(9162),a=s(2517);var h=l.onnxruntime.experimental.fbs;class p{constructor(o){if(this._attributes=new Map,o!=null){for(const t of o)t instanceof c.onnx.AttributeProto?this._attributes.set(t.name,[p.getValue(t),p.getType(t)]):t instanceof h.Attribute&&this._attributes.set(t.name(),[p.getValue(t),p.getType(t)]);if(this._attributes.sizef.Tensor.fromProto(r));if(o instanceof h.Attribute)return e.map(r=>f.Tensor.fromOrtTensor(r))}if(t===c.onnx.AttributeProto.AttributeType.STRING&&o instanceof c.onnx.AttributeProto){const r=e;return(0,a.decodeUtf8String)(r)}return t===c.onnx.AttributeProto.AttributeType.STRINGS&&o instanceof c.onnx.AttributeProto?e.map(a.decodeUtf8String):e}static getValueNoCheck(o){return o instanceof c.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(o):this.getValueNoCheckFromOrtFormat(o)}static getValueNoCheckFromOnnxFormat(o){switch(o.type){case c.onnx.AttributeProto.AttributeType.FLOAT:return o.f;case c.onnx.AttributeProto.AttributeType.INT:return o.i;case c.onnx.AttributeProto.AttributeType.STRING:return o.s;case c.onnx.AttributeProto.AttributeType.TENSOR:return o.t;case c.onnx.AttributeProto.AttributeType.GRAPH:return o.g;case c.onnx.AttributeProto.AttributeType.FLOATS:return o.floats;case c.onnx.AttributeProto.AttributeType.INTS:return o.ints;case c.onnx.AttributeProto.AttributeType.STRINGS:return o.strings;case c.onnx.AttributeProto.AttributeType.TENSORS:return o.tensors;case c.onnx.AttributeProto.AttributeType.GRAPHS:return o.graphs;default:throw new Error(`unsupported attribute type: ${c.onnx.AttributeProto.AttributeType[o.type]}`)}}static getValueNoCheckFromOrtFormat(o){switch(o.type()){case h.AttributeType.FLOAT:return o.f();case h.AttributeType.INT:return o.i();case h.AttributeType.STRING:return o.s();case h.AttributeType.TENSOR:return o.t();case h.AttributeType.GRAPH:return o.g();case h.AttributeType.FLOATS:return o.floatsArray();case h.AttributeType.INTS:{const t=[];for(let e=0;e{Object.defineProperty(n,"__esModule",{value:!0}),n.resolveBackend=n.backend=void 0;const c=s(5038),l=new Map;async function f(a){const h=n.backend;if(h[a]!==void 0&&function(p){const u=p;return"initialize"in u&&typeof u.initialize=="function"&&"createSessionHandler"in u&&typeof u.createSessionHandler=="function"&&"dispose"in u&&typeof u.dispose=="function"}(h[a])){const p=h[a];let u=p.initialize();if(typeof u=="object"&&"then"in u&&(u=await u),u)return l.set(a,p),p}}n.backend={webgl:new c.WebGLBackend},n.resolveBackend=async function a(h){if(!h)return a(["webgl"]);{const p=typeof h=="string"?[h]:h;for(const u of p){const o=l.get(u);if(o)return o;const t=await f(u);if(t)return t}}throw new Error("no available backend to use")}},5038:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.WebGLBackend=void 0;const c=s(1670),l=s(6231),f=s(6416),a=s(7305);n.WebGLBackend=class{get contextId(){return c.env.webgl.contextId}set contextId(h){c.env.webgl.contextId=h}get matmulMaxBatchSize(){return c.env.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(h){c.env.webgl.matmulMaxBatchSize=h}get textureCacheMode(){return c.env.webgl.textureCacheMode}set textureCacheMode(h){c.env.webgl.textureCacheMode=h}get pack(){return c.env.webgl.pack}set pack(h){c.env.webgl.pack=h}get async(){return c.env.webgl.async}set async(h){c.env.webgl.async=h}initialize(){try{return this.glContext=(0,a.createWebGLContext)(this.contextId),typeof this.matmulMaxBatchSize!="number"&&(this.matmulMaxBatchSize=16),typeof this.textureCacheMode!="string"&&(this.textureCacheMode="full"),typeof this.pack!="boolean"&&(this.pack=!1),typeof this.async!="boolean"&&(this.async=!1),l.Logger.setWithEnv(c.env),l.Logger.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(h){return l.Logger.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${h}`),!1}}createSessionHandler(h){return new f.WebGLSessionHandler(this,h)}dispose(){this.glContext.dispose()}}},5107:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CoordsGlslLib=void 0;const c=s(2517),l=s(8520),f=s(5060),a=s(7859),h=s(9390);class p extends l.GlslLib{constructor(o){super(o)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.offsetToCoords()),this.coordsToOffset()),this.toVec()),this.valueFrom()),this.getCommonUtilFuncs()),this.getInputsSamplingSnippets()),this.getOutputSamplingSnippet())}getCustomTypes(){return{}}offsetToCoords(){return{offsetToCoords:new l.GlslLibRoutine(` - vec2 offsetToCoords(int offset, int width, int height) { - int t = offset / width; - int s = offset - t*width; - vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height); - return coords; - } - `)}}coordsToOffset(){return{coordsToOffset:new l.GlslLibRoutine(` - int coordsToOffset(vec2 coords, int width, int height) { - float s = coords.s * float(width); - float t = coords.t * float(height); - int offset = int(t) * width + int(s); - return offset; - } - `)}}getOutputSamplingSnippet(){const o=this.context.outputTextureLayout;return o.isPacked?this.getPackedOutputSamplingSnippet(o):this.getUnpackedOutputSamplingSnippet(o)}getPackedOutputSamplingSnippet(o){const t=o.unpackedShape,e=[o.width,o.height],r={},i="getOutputCoords";switch(t.length){case 0:r[i]=this.getOutputScalarCoords();break;case 1:r[i]=this.getOutputPacked1DCoords(t,e);break;case 2:r[i]=this.getOutputPacked2DCoords(t,e);break;case 3:r[i]=this.getOutputPacked3DCoords(t,e);break;default:r[i]=this.getOutputPackedNDCoords(t,e)}const d=` - void setOutput(vec4 val) { - ${(0,f.getGlsl)(this.context.glContext.version).output} = val; - } - `;return r.floatTextureSetRGBA=new l.GlslLibRoutine(d),r}getUnpackedOutputSamplingSnippet(o){const t=o.unpackedShape,e=[o.width,o.height],r={},i="getOutputCoords";switch(t.length){case 0:r[i]=this.getOutputScalarCoords();break;case 1:r[i]=this.getOutputUnpacked1DCoords(t,e);break;case 2:r[i]=this.getOutputUnpacked2DCoords(t,e);break;case 3:r[i]=this.getOutputUnpacked3DCoords(t,e);break;case 4:r[i]=this.getOutputUnpacked4DCoords(t,e);break;case 5:r[i]=this.getOutputUnpacked5DCoords(t,e);break;case 6:r[i]=this.getOutputUnpacked6DCoords(t,e);break;default:throw new Error(`Unsupported output dimensionality: ${t.length}`)}const d=` - void setOutput(float val) { - ${(0,f.getGlsl)(this.context.glContext.version).output} = vec4(val, 0, 0, 0); - } - `;return r.floatTextureSetR=new l.GlslLibRoutine(d),r}getOutputScalarCoords(){return new l.GlslLibRoutine(` - int getOutputCoords() { - return 0; - } - `)}getOutputPacked1DCoords(o,t){const e=t;let r="";return e[0]===1?(r=` - int getOutputCoords() { - return 2 * int(TexCoords.y * ${e[1]}.0); - } - `,new l.GlslLibRoutine(r)):e[1]===1?(r=` - int getOutputCoords() { - return 2 * int(TexCoords.x * ${e[0]}.0); - } - `,new l.GlslLibRoutine(r)):(r=` - int getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${e[0]}, ${e[1]})); - return 2 * (resTexRC.y * ${e[0]} + resTexRC.x); - } - `,new l.GlslLibRoutine(r))}getOutputPacked2DCoords(o,t){let e="";if(c.ArrayUtil.arraysEqual(o,t))return e=` - ivec2 getOutputCoords() { - return 2 * ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); - } - `,new l.GlslLibRoutine(e);const r=t,i=Math.ceil(o[1]/2);return e=` - ivec2 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${r[0]}, ${r[1]})); - - int index = resTexRC.y * ${r[0]} + resTexRC.x; - - // reverse r and c order for packed texture - int r = imod(index, ${i}) * 2; - int c = 2 * (index / ${i}); - - return ivec2(r, c); - } - `,new l.GlslLibRoutine(e)}getOutputPacked3DCoords(o,t){const e=[t[0],t[1]],r=Math.ceil(o[2]/2),i=r*Math.ceil(o[1]/2),d=` - ivec3 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${e[0]}, ${e[1]})); - int index = resTexRC.y * ${e[0]} + resTexRC.x; - - int b = index / ${i}; - index -= b * ${i}; - - // reverse r and c order for packed texture - int r = imod(index, ${r}) * 2; - int c = 2 * (index / ${r}); - - return ivec3(b, r, c); - } - `;return new l.GlslLibRoutine(d)}getOutputPackedNDCoords(o,t){const e=[t[0],t[1]],r=Math.ceil(o[o.length-1]/2),i=r*Math.ceil(o[o.length-2]/2);let d=i,g="",m="b, r, c";for(let y=2;y=0;--m)i[m]=i[m+1]*o[m+1];const d=["r","c","d"],g=i.map((m,b)=>`int ${d[b]} = index / ${m}; ${b===i.length-1?`int ${d[b+1]} = index - ${d[b]} * ${m}`:`index -= ${d[b]} * ${m}`};`).join("");return e=` - ivec3 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${t[0]}, ${t[1]})); - int index = resTexRC.y * ${t[0]} + resTexRC.x; - ${g} - return ivec3(r, c, d); - } - `,new l.GlslLibRoutine(e)}getOutputUnpacked4DCoords(o,t){let e="";const r=o.length;let i=null;r<2&&(i=[]),i=new Array(r-1),i[r-2]=o[r-1];for(let m=r-3;m>=0;--m)i[m]=i[m+1]*o[m+1];const d=["r","c","d","d2"],g=i.map((m,b)=>`int ${d[b]} = index / ${m}; ${b===i.length-1?`int ${d[b+1]} = index - ${d[b]} * ${m}`:`index -= ${d[b]} * ${m}`};`).join("");return e=` - ivec4 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${t[0]}, ${t[1]})); - int index = resTexRC.y * ${t[0]} + resTexRC.x; - ${g} - return ivec4(r, c, d, d2); - } - `,new l.GlslLibRoutine(e)}getOutputUnpacked5DCoords(o,t){let e="";const r=o.length;let i=null;r<2&&(i=[]),i=new Array(r-1),i[r-2]=o[r-1];for(let m=r-3;m>=0;--m)i[m]=i[m+1]*o[m+1];const d=["r","c","d","d2","d3"],g=i.map((m,b)=>`int ${d[b]} = index / ${m}; ${b===i.length-1?`int ${d[b+1]} = index - ${d[b]} * ${m}`:`index -= ${d[b]} * ${m}`};`).join("");return e=` - ivec5 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${t[0]}, ${t[1]})); - int index = resTexRC.y * ${t[0]} + resTexRC.x; - ${g} - return ivec5(r, c, d, d2, d3); - } - `,new l.GlslLibRoutine(e)}getOutputUnpacked6DCoords(o,t){let e="";const r=o.length;let i=null;r<2&&(i=[]),i=new Array(r-1),i[r-2]=o[r-1];for(let m=r-3;m>=0;--m)i[m]=i[m+1]*o[m+1];const d=["r","c","d","d2","d3","d4"],g=i.map((m,b)=>`int ${d[b]} = index / ${m}; ${b===i.length-1?`int ${d[b+1]} = index - ${d[b]} * ${m}`:`index -= ${d[b]} * ${m}`};`).join("");return e=` - ivec6 getOutputCoords() { - ivec2 resTexRC = ivec2(TexCoords.xy * - vec2(${t[0]}, ${t[1]})); - int index = resTexRC.y * ${t[0]} + resTexRC.x; - ${g} - return ivec6(r, c, d, d2, d3, d4); - } - `,new l.GlslLibRoutine(e)}getCommonUtilFuncs(){const o={};let t="uvFromFlat";o[t]=new l.GlslLibRoutine(` - vec2 uvFromFlat(int texNumR, int texNumC, int index) { - int texC = index / texNumR; - int texR = index - texC * texNumR; - // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to - // v. - return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC); - } - `),t="packedUVfrom1D",o[t]=new l.GlslLibRoutine(` - vec2 packedUVfrom1D(int texNumR, int texNumC, int index) { - int texelIndex = index / 2; - int texR = texelIndex / texNumC; - int texC = texelIndex - texR * texNumC; - return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); - } - `),t="packedUVfrom2D",o[t]=new l.GlslLibRoutine(` - vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) { - int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2); - int texR = texelIndex / texNumC; - int texC = texelIndex - texR * texNumC; - return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); - } - `),t="packedUVfrom3D",o[t]=new l.GlslLibRoutine(` - vec2 packedUVfrom3D(int texNumR, int texNumC, - int texelsInBatch, int texelsInLogicalRow, int b, - int row, int col) { - int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2); - int texR = index / texNumC; - int texC = index - texR * texNumC; - return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); - } - `),t="sampleTexture";const e=(0,f.getGlsl)(this.context.glContext.version);return o[t]=new l.GlslLibRoutine(` - float sampleTexture(sampler2D textureSampler, vec2 uv) { - return ${e.texture2D}(textureSampler, uv).r; - }`),o}getInputsSamplingSnippets(){const o={},t=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach((e,r)=>{const i=this.context.inputTextureLayouts[r],d=(0,h.generateShaderFuncNameFromInputSamplerName)(e);i.isPacked?o[d]=this.getPackedSamplerFromInput(d,e,i):o[d]=this.getUnpackedSamplerFromInput(d,e,i);const g=(0,h.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(e);i.unpackedShape.length<=t.unpackedShape.length&&(i.isPacked?o[g]=this.getPackedSamplerAtOutputCoords(g,i,t,e):o[g]=this.getUnpackedSamplerAtOutputCoords(g,i,t,e))}),o}getPackedSamplerAtOutputCoords(o,t,e,r){const i=t.unpackedShape,d=e.unpackedShape,g=r,m=(0,h.generateShaderFuncNameFromInputSamplerName)(g),b=i.length,y=d.length,w=c.BroadcastUtil.getBroadcastDims(i,d),v=(0,h.getCoordsDataType)(y),S=y-b;let A;const O=(0,h.getGlChannels)();A=b===0?"":y<2&&w.length>=1?"coords = 0;":w.map(N=>`coords.${O[N+S]} = 0;`).join(` -`);let x="";x=y<2&&b>0?"coords":i.map((N,H)=>`coords.${O[H+S]}`).join(", ");let I="return outputValue;";const $=c.ShapeUtil.size(i)===1,z=c.ShapeUtil.size(d)===1;if(b!==1||$||z){if($&&!z)I=y===1?` - return vec4(outputValue.x, outputValue.x, 0., 0.); - `:` - return vec4(outputValue.x); - `;else if(w.length){const N=b-2,H=b-1;w.indexOf(N)>-1&&w.indexOf(H)>-1?I="return vec4(outputValue.x);":w.indexOf(N)>-1?I="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":w.indexOf(H)>-1&&(I="return vec4(outputValue.xx, outputValue.zz);")}}else I=` - return vec4(outputValue.xy, outputValue.xy); - `;const L=` - vec4 ${o}() { - ${v} coords = getOutputCoords(); - - int lastDim = coords.${O[y-1]}; - coords.${O[y-1]} = coords.${O[y-2]}; - coords.${O[y-2]} = lastDim; - - ${A} - vec4 outputValue = ${m}(${x}); - ${I} - } - `;return new l.GlslLibRoutine(L,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(o,t,e,r){const i=[e.width,e.height],d=[t.width,t.height],g=t.unpackedShape.length,m=e.unpackedShape.length,b=t.unpackedShape,y=e.unpackedShape,w=(0,h.generateShaderFuncNameFromInputSamplerName)(r);if(g===m&&c.ArrayUtil.arraysEqual(d,i)){const z=` - float ${o}() { - return sampleTexture(${r}, TexCoords); - } - `;return new l.GlslLibRoutine(z,["coordinates.sampleTexture"])}const v=(0,h.getCoordsDataType)(m),S=c.BroadcastUtil.getBroadcastDims(b,y),A=m-g;let O;const x=(0,h.getGlChannels)();O=g===0?"":m<2&&S.length>=1?"coords = 0;":S.map(z=>`coords.${x[z+A]} = 0;`).join(` -`);let I="";I=m<2&&g>0?"coords":t.unpackedShape.map((z,L)=>`coords.${x[L+A]}`).join(", ");const $=` - float ${o}() { - ${v} coords = getOutputCoords(); - ${O} - return ${w}(${I}); - } - `;return new l.GlslLibRoutine($,["coordinates.getOutputCoords"])}getPackedSamplerFromInput(o,t,e){switch(e.unpackedShape.length){case 0:return this.getPackedSamplerScalar(o,t);case 1:return this.getPackedSampler1D(o,t,e);case 2:return this.getPackedSampler2D(o,t,e);case 3:return this.getPackedSampler3D(o,t,e);default:return this.getPackedSamplerND(o,t,e)}}getUnpackedSamplerFromInput(o,t,e){const r=e.unpackedShape;switch(r.length){case 0:return this.getUnpackedSamplerScalar(o,t,e);case 1:return this.getUnpackedSampler1D(o,t,e);case 2:return this.getUnpackedSampler2D(o,t,e);case 3:return this.getUnpackedSampler3D(o,t,e);case 4:return this.getUnpackedSampler4D(o,t,e);case 5:return this.getUnpackedSampler5D(o,t,e);case 6:return this.getUnpackedSampler6D(o,t,e);default:throw new Error(`Unsupported dimension ${r.length}-D`)}}getPackedSamplerScalar(o,t){const e=` - vec4 ${o}() { - return ${(0,f.getGlsl)(this.context.glContext.version).texture2D}(${t}, halfCR); - } - `;return new l.GlslLibRoutine(e)}getPackedSampler1D(o,t,e){const r=[e.width,e.height],i=[r[1],r[0]],d=(0,f.getGlsl)(this.context.glContext.version),g=`vec4 ${o}(int index) { - vec2 uv = packedUVfrom1D( - ${i[0]}, ${i[1]}, index); - return ${d.texture2D}(${t}, uv); - }`;return new l.GlslLibRoutine(g,["coordinates.packedUVfrom1D"])}getPackedSampler2D(o,t,e){const r=e.unpackedShape,i=[e.width,e.height],d=(0,f.getGlsl)(this.context.glContext.version),g=i[0],m=i[1];if(i!=null&&c.ArrayUtil.arraysEqual(r,i)){const v=`vec4 ${o}(int row, int col) { - vec2 uv = (vec2(col, row) + halfCR) / vec2(${m}.0, ${g}.0); - return ${d.texture2D}(${t}, uv); - }`;return new l.GlslLibRoutine(v)}const b=i,y=Math.ceil(r[1]/2),w=`vec4 ${o}(int row, int col) { - vec2 uv = packedUVfrom2D(${b[1]}, ${b[0]}, ${y}, row, col); - return ${d.texture2D}(${t}, uv); - }`;return new l.GlslLibRoutine(w,["coordinates.packedUVfrom2D"])}getPackedSampler3D(o,t,e){const r=e.unpackedShape,i=[e.width,e.height],d=[i[0],i[1]],g=(0,f.getGlsl)(this.context.glContext.version);if(r[0]===1){const v=r.slice(1),S=[1,2],A=(0,h.squeezeInputShape)(r,v),O=["b","row","col"],x=JSON.parse(JSON.stringify(e));x.unpackedShape=A;const I=this.getPackedSamplerFromInput(o,t,x),$=`${I.routineBody} - vec4 ${o}(int b, int row, int col) { - return ${o}(${(0,h.getSqueezedParams)(O,S)}); - } `;return new l.GlslLibRoutine($,I.dependencies)}const m=d[0],b=d[1],y=Math.ceil(r[2]/2),w=`vec4 ${o}(int b, int row, int col) { - vec2 uv = packedUVfrom3D( - ${b}, ${m}, ${y*Math.ceil(r[1]/2)}, ${y}, b, row, col); - return ${g.texture2D}(${t}, uv);}`;return new l.GlslLibRoutine(w,["coordinates.packedUVfrom3D"])}getPackedSamplerND(o,t,e){const r=e.unpackedShape,i=r.length,d=[e.width,e.height],g=(0,f.getGlsl)(this.context.glContext.version),m=[d[0],d[1]],b=m[1],y=m[0],w=Math.ceil(r[i-1]/2);let v=w*Math.ceil(r[i-2]/2),S="int b, int row, int col",A=`b * ${v} + (row / 2) * ${w} + (col / 2)`;for(let x=2;x{const r=this.context.inputTextureLayouts[e],i=(r.unpackedShape.length>0?r.unpackedShape:r.shape).length;let d=`_${t}`;o[d]=new l.GlslLibRoutine(this.getValueFromSingle(t,i,r.width,r.height,!1),[`shapeUtils.indicesToOffset${d}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"]),d+="_T",o[d]=new l.GlslLibRoutine(this.getValueFromSingle(t,i,r.width,r.height,!0),[`shapeUtils.indicesToOffset${d}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"])}),o}getValueFromSingle(o,t,e,r,i){let d=`_${o}`;return i&&(d+="_T"),` - float ${d}(int m[${t}]) { - int offset = indicesToOffset${d}(m); - vec2 coords = offsetToCoords(offset, ${e}, ${r}); - float value = getColorAsFloat(${(0,f.getGlsl)(this.context.glContext.version).texture2D}(${o}, coords)); - return value; - } - `}getPackedValueFrom(o,t,e,r,i){let d=`_${o}_Pack`;return i&&(d+="_T"),` - vec4 ${d}(int m[${t}]) { - int offset = indicesToOffset_${o}(m); - vec2 coords = offsetToCoords(offset, ${e}, ${r}); - return ${(0,f.getGlsl)(this.context.glContext.version).texture2D}(${o}, coords); - } - `}}n.CoordsGlslLib=p},8520:(_,n)=>{var s;Object.defineProperty(n,"__esModule",{value:!0}),n.TopologicalSortGlslRoutines=n.GlslLibRoutineNode=n.GlslLibRoutine=n.GlslLib=n.GlslContext=n.FunctionType=void 0,(s=n.FunctionType||(n.FunctionType={}))[s.ValueBased=0]="ValueBased",s[s.Positional=1]="Positional",n.GlslContext=class{constructor(c,l,f,a){this.glContext=c,this.programInfo=l,this.inputTextureLayouts=f,this.outputTextureLayout=a}},n.GlslLib=class{constructor(c){this.context=c}},n.GlslLibRoutine=class{constructor(c,l){this.routineBody=c,this.dependencies=l}},n.GlslLibRoutineNode=class{constructor(c,l,f){this.name=c,this.dependencies=f||[],l&&(this.routineBody=l)}addDependency(c){c&&this.dependencies.push(c)}},n.TopologicalSortGlslRoutines=class{static returnOrderedNodes(c){if(!c||c.length===0)return[];if(c.length===1)return c;const l=new Set,f=new Set,a=new Array;return this.createOrderedNodes(c,l,f,a),a}static createOrderedNodes(c,l,f,a){for(let h=0;h0)for(let p=0;p{Object.defineProperty(n,"__esModule",{value:!0}),n.EncodingGlslLib=void 0;const c=s(8520);class l extends c.GlslLib{constructor(a){super(a)}getFunctions(){return Object.assign(Object.assign({},this.encodeFloat32()),this.decodeFloat32())}getCustomTypes(){return{}}encodeFloat32(){return{encode:new c.GlslLibRoutine(`highp vec4 encode(highp float f) { - return vec4(f, 0.0, 0.0, 0.0); - } - `)}}decodeFloat32(){return{decode:new c.GlslLibRoutine(`highp float decode(highp vec4 rgba) { - return rgba.r; - } - `)}}encodeUint8(){const a=l.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{encode:new c.GlslLibRoutine(` - highp vec4 encode(highp float f) { - highp float F = abs(f); - highp float Sign = step(0.0,-f); - highp float Exponent = floor(log2(F)); - highp float Mantissa = (exp2(- Exponent) * F); - Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa)); - highp vec4 rgba; - rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0)); - rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0); - rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0))); - rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0))); - ${a} - rgba = rgba / 255.0; // values need to be normalized to [0,1] - return rgba; - } - `)}}decodeUint8(){const a=l.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{decode:new c.GlslLibRoutine(` - highp float decode(highp vec4 rgba) { - rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255] - ${a} - highp float Sign = 1.0 - step(128.0,rgba[0])*2.0; - highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0; - highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000); - highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 )); - return Result; - } - `)}}static isLittleEndian(){const a=new ArrayBuffer(4),h=new Uint32Array(a),p=new Uint8Array(a);if(h[0]=3735928559,p[0]===239)return!0;if(p[0]===222)return!1;throw new Error("unknown endianness")}}n.EncodingGlslLib=l},9894:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.FragColorGlslLib=void 0;const c=s(8520),l=s(5060);class f extends c.GlslLib{constructor(h){super(h)}getFunctions(){return Object.assign(Object.assign({},this.setFragColor()),this.getColorAsFloat())}getCustomTypes(){return{}}setFragColor(){const h=(0,l.getGlsl)(this.context.glContext.version);return{setFragColor:new c.GlslLibRoutine(` - void setFragColor(float value) { - ${h.output} = encode(value); - } - `,["encoding.encode"])}}getColorAsFloat(){return{getColorAsFloat:new c.GlslLibRoutine(` - float getColorAsFloat(vec4 color) { - return decode(color); - } - `,["encoding.decode"])}}}n.FragColorGlslLib=f},2848:(_,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.replaceInlines=void 0;const s=/@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm;n.replaceInlines=function(c){const l={};let f;for(;(f=s.exec(c))!==null;){const a=f[3].split(",").map(h=>{const p=h.trim().split(" ");return p&&p.length===2?{type:p[0],name:p[1]}:null}).filter(h=>h!==null);l[f[2]]={params:a,body:f[4]}}for(const a in l){const h="(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;".replace("__FUNC__",a),p=new RegExp(h,"gm");for(;(f=p.exec(c))!==null;){const u=f[1],o=f[2],t=f[3].split(","),e=u?`${u} ${o};`:"";let r=l[a].body,i="";l[a].params.forEach((g,m)=>{g&&(i+=`${g.type} ${g.name} = ${t[m]}; -`)}),r=`${i} - ${r}`,r=r.replace("return",`${o} = `);const d=` - ${e} - { - ${r} - } - `;c=c.replace(f[0],d)}}return c.replace(s,"")}},8879:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.GlslPreprocessor=void 0;const c=s(8520),l=s(2848),f=s(5483),a=s(5060);n.GlslPreprocessor=class{constructor(h,p,u,o){this.libs={},this.glslLibRoutineDependencyGraph={},this.context=new c.GlslContext(h,p,u,o),Object.keys(f.glslRegistry).forEach(e=>{const r=new f.glslRegistry[e](this.context);this.libs[e]=r});const t=this.glslLibRoutineDependencyGraph;for(const e in this.libs){const r=this.libs[e].getFunctions();for(const i in r){const d=e+"."+i;let g;t[d]?(g=t[d],g.routineBody=r[i].routineBody):(g=new c.GlslLibRoutineNode(d,r[i].routineBody),t[d]=g);const m=r[i].dependencies;if(m)for(let b=0;b{const o=u.split(".")[1];h.indexOf(o)!==-1&&p.push(this.glslLibRoutineDependencyGraph[u])}),c.TopologicalSortGlslRoutines.returnOrderedNodes(p)}getUniforms(h,p){const u=[];if(h)for(const o of h)u.push(`uniform sampler2D ${o};`);if(p)for(const o of p)u.push(`uniform ${o.type} ${o.name}${o.arrayLength?`[${o.arrayLength}]`:""};`);return u.join(` -`)}}},5483:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.glslRegistry=void 0;const c=s(5107),l=s(7341),f=s(9894),a=s(2655),h=s(3891);n.glslRegistry={encoding:l.EncodingGlslLib,fragcolor:f.FragColorGlslLib,vec:h.VecGlslLib,shapeUtils:a.ShapeUtilsGlslLib,coordinates:c.CoordsGlslLib}},2655:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ShapeUtilsGlslLib=void 0;const c=s(8520);class l extends c.GlslLib{constructor(a){super(a)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.bcastIndex()),this.bcastMatmulIndex()),this.offsetToIndices()),this.indicesToOffset()),this.incrementIndices())}getCustomTypes(){return{}}bcastIndex(){const a=this.context.outputTextureLayout.shape.length,h={};return this.context.programInfo.inputNames.forEach((p,u)=>{const o=this.context.inputTextureLayouts[u].unpackedShape;if(o.length<=a){const t=o.length,e=a-t,r=`bcastIndices_${p}`;let i="";for(let g=0;g{const o=this.context.inputTextureLayouts[u].shape;if(!(o.length<2||o.length>a)){const t=o.length,e=a-t,r=`bcastMatmulIndices_${p}`;let i="";for(let g=0;g{const u=this.context.inputTextureLayouts[p].shape,o=this.context.inputTextureLayouts[p].strides,t=u.length;let e=`indicesToOffset_${h}`;a[e]=new c.GlslLibRoutine(l.indexToOffsetSingle(e,t,o)),e=`indicesToOffset_${h}_T`,a[e]=new c.GlslLibRoutine(l.indexToOffsetSingle(e,t,o.slice().reverse()))}),a}static indexToOffsetSingle(a,h,p){let u="";for(let o=h-1;o>=0;--o)u+=` - offset += indices[${o}] * ${p[o]}; - `;return` - int ${a}(int indices[${h}]) { - int offset = 0; - ${u} - return offset; - } - `}offsetToIndices(){const a={};return this.context.programInfo.inputNames.forEach((h,p)=>{const u=this.context.inputTextureLayouts[p].shape,o=this.context.inputTextureLayouts[p].strides,t=u.length;let e=`offsetToIndices_${h}`;a[e]=new c.GlslLibRoutine(l.offsetToIndicesSingle(e,t,o)),e=`offsetToIndices_${h}_T`,a[e]=new c.GlslLibRoutine(l.offsetToIndicesSingle(e,t,o.slice().reverse()))}),a}static offsetToIndicesSingle(a,h,p){const u=[];for(let o=0;o{const u=this.context.inputTextureLayouts[p].shape,o=u.length,t=`incrementIndices_${h}`;let e="";for(let i=0;i= 0; --i) { - if(i > axis) continue; - indices[i] += 1; - if(indices[i] < shape[i]) { - break; - } - indices[i] = 0; - } - } - `;a[t]=new c.GlslLibRoutine(r)}),a}}n.ShapeUtilsGlslLib=l},5060:(_,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.getDefaultFragShaderMain=n.getFragShaderPreamble=n.getVertexShaderSource=n.getGlsl=void 0;const s={version:"",attribute:"attribute",varyingVertex:"varying",varyingFrag:"varying",texture2D:"texture2D",output:"gl_FragColor",outputDeclaration:""},c={version:"#version 300 es",attribute:"in",varyingVertex:"out",varyingFrag:"in",texture2D:"texture",output:"outputColor",outputDeclaration:"out vec4 outputColor;"};function l(f){return f===1?s:c}n.getGlsl=l,n.getVertexShaderSource=function(f){const a=l(f);return`${a.version} - precision highp float; - ${a.attribute} vec3 position; - ${a.attribute} vec2 textureCoord; - - ${a.varyingVertex} vec2 TexCoords; - - void main() - { - gl_Position = vec4(position, 1.0); - TexCoords = textureCoord; - }`},n.getFragShaderPreamble=function(f){const a=l(f);return`${a.version} - precision highp float; - precision highp int; - precision highp sampler2D; - ${a.varyingFrag} vec2 TexCoords; - ${a.outputDeclaration} - const vec2 halfCR = vec2(0.5, 0.5); - - // Custom vector types to handle higher dimenalities. - struct ivec5 - { - int x; - int y; - int z; - int w; - int u; - }; - - struct ivec6 - { - int x; - int y; - int z; - int w; - int u; - int v; - }; - - int imod(int x, int y) { - return x - y * (x / y); - } - - `},n.getDefaultFragShaderMain=function(f,a){return` - void main() { - int indices[${a}]; - toVec(TexCoords, indices); - vec4 result = vec4(process(indices)); - ${l(f).output} = result; - } - `}},3891:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.VecGlslLib=void 0;const c=s(8520);class l extends c.GlslLib{constructor(a){super(a)}getCustomTypes(){return{}}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign({},this.binaryVecFunctions()),this.copyVec()),this.setVecItem()),this.getVecItem())}binaryVecFunctions(){const a=this.context.outputTextureLayout.shape.length,h={add:"+=",sub:"-=",mul:"*=",div:"/="},p={};for(const u in h){const o=`${u}Vec`;let t="";for(let r=0;r{Object.defineProperty(n,"__esModule",{value:!0}),n.WebGLInferenceHandler=void 0;const c=s(6231),l=s(9162),f=s(2517),a=s(2403),h=s(7019),p=s(8710),u=s(5611),o=s(4057),t=s(2039);n.WebGLInferenceHandler=class{constructor(e){this.session=e,this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(e,r){return(0,o.calculateTextureWidthAndHeight)(this.session.layoutStrategy,e,r)}executeProgram(e,r){if(r.length{const S=v.map(O=>`${O.unpackedShape.join(",")};${O.width}x${O.height}`).join("_");let A=w.name;return w.cacheHint&&(A+="["+w.cacheHint+"]"),A+=":"+S,A})(e,i);let g=this.session.programManager.getArtifact(d);const m=g?g.programInfo:typeof e.get=="function"?e.get():e,b=(0,o.createTextureLayoutFromTextureType)(this.session.layoutStrategy,m.output.dims,m.output.textureType),y=this.createTextureData(b,m.output.type);return g||(g=this.session.programManager.build(m,i,y),this.session.programManager.setArtifact(d,g)),this.runProgram(g,i,y),y}run(e,r){return this.executeProgram(e,r).tensor}runProgram(e,r,i){for(let d=0;dthis.readTexture(m),async b=>this.readTextureAsync(m),void 0,g),texture:i});return this.setTextureData(m.tensor.dataId,m,e.isPacked),m}getTextureData(e,r=!1){return this.session.isInitializer(e)?this.session.getTextureData(e,r):r?this.packedTextureDataCache.get(e):this.unpackedTextureDataCache.get(e)}setTextureData(e,r,i=!1){this.session.isInitializer(e)?this.session.setTextureData(e,r,i):(i?this.packedTextureDataCache:this.unpackedTextureDataCache).set(e,r)}isTextureLayoutCached(e,r=!1){return!!this.getTextureData(e.dataId,r)}dispose(){this.session.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(e=>this.session.textureManager.releaseTexture(e)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(e=>this.session.textureManager.releaseTexture(e)),this.unpackedTextureDataCache=new Map}readTexture(e){return e.isPacked?this.readTexture(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTexture(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat((0,p.encodeAsUint8)(this,e))}async readTextureAsync(e){return e.isPacked?this.readTextureAsync(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTextureAsync(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat((0,p.encodeAsUint8)(this,e))}pack(e){return this.executeProgram((0,a.createPackProgramInfoLoader)(this,e.tensor),[e.tensor])}unpack(e){return this.executeProgram((0,u.createUnpackProgramInfoLoader)(this,e.tensor),[e.tensor])}}},1640:function(_,n,s){var c=this&&this.__createBinding||(Object.create?function(X,Q,ee,ue){ue===void 0&&(ue=ee);var Ae=Object.getOwnPropertyDescriptor(Q,ee);Ae&&!("get"in Ae?!Q.__esModule:Ae.writable||Ae.configurable)||(Ae={enumerable:!0,get:function(){return Q[ee]}}),Object.defineProperty(X,ue,Ae)}:function(X,Q,ee,ue){ue===void 0&&(ue=ee),X[ue]=Q[ee]}),l=this&&this.__setModuleDefault||(Object.create?function(X,Q){Object.defineProperty(X,"default",{enumerable:!0,value:Q})}:function(X,Q){X.default=Q}),f=this&&this.__importStar||function(X){if(X&&X.__esModule)return X;var Q={};if(X!=null)for(var ee in X)ee!=="default"&&Object.prototype.hasOwnProperty.call(X,ee)&&c(Q,X,ee);return l(Q,X),Q};Object.defineProperty(n,"__esModule",{value:!0}),n.WEBGL_OP_RESOLVE_RULES=void 0;const a=s(2898),h=f(s(7839)),p=s(4196),u=s(2069),o=s(8138),t=s(9663),e=s(5193),r=s(7992),i=s(1253),d=s(4776),g=s(6572),m=s(3346),b=s(5623),y=s(2870),w=s(2143),v=s(4939),S=s(718),A=s(2268),O=s(8117),x=s(2278),I=s(5524),$=s(5975),z=s(3933),L=s(6558),N=s(5723),H=s(3738),M=f(s(4909)),j=s(8428),Z=s(9793);n.WEBGL_OP_RESOLVE_RULES=[["Abs","","6+",M.abs],["Acos","","7+",M.acos],["Add","","7+",h.add],["And","","7+",h.and],["Asin","","7+",M.asin],["Atan","","7+",M.atan],["AveragePool","","7+",w.averagePool,w.parseAveragePoolAttributes],["BatchNormalization","","7+",a.batchNormalization,a.parseBatchNormalizationAttributes],["Cast","","6+",p.cast,p.parseCastAttributes],["Ceil","","6+",M.ceil],["Clip","","6-10",M.clip,M.parseClipAttributes],["Clip","","11+",M.clipV11],["Concat","","4+",u.concat,u.parseConcatAttributes],["Conv","","1+",o.conv,o.parseConvAttributes],["ConvTranspose","","1+",t.convTranspose,t.parseConvTransposeAttributes],["Cos","","7+",M.cos],["Div","","7+",h.div],["Dropout","","7+",M.identity],["DepthToSpace","","1+",e.depthToSpace,e.parseDepthToSpaceAttributes],["Equal","","7+",h.equal],["Elu","","6+",M.elu,M.parseEluAttributes],["Exp","","6+",M.exp],["Flatten","","1+",r.flatten,r.parseFlattenAttributes],["Floor","","6+",M.floor],["FusedConv","com.microsoft","1+",o.conv,o.parseConvAttributes],["Gather","","1+",i.gather,i.parseGatherAttributes],["Gemm","","7-10",d.gemm,d.parseGemmAttributesV7],["Gemm","","11+",d.gemm,d.parseGemmAttributesV11],["GlobalAveragePool","","1+",w.globalAveragePool,w.parseGlobalAveragePoolAttributes],["GlobalMaxPool","","1+",w.globalMaxPool],["Greater","","7+",h.greater],["Identity","","1+",M.identity],["ImageScaler","","1+",g.imageScaler,g.parseImageScalerAttributes],["InstanceNormalization","","6+",m.instanceNormalization,m.parseInstanceNormalizationAttributes],["LeakyRelu","","6+",M.leakyRelu,M.parseLeakyReluAttributes],["Less","","7+",h.less],["Log","","6+",M.log],["MatMul","","1+",b.matMul,b.parseMatMulAttributes],["MaxPool","","1+",w.maxPool,w.parseMaxPoolAttributes],["Mul","","7+",h.mul],["Neg","","6+",M.neg],["Not","","1+",M.not],["Or","","7+",h.or],["Pad","","2-10",y.padV2,y.parsePadAttributesV2],["Pad","","11+",y.padV11,y.parsePadAttributesV11],["Pow","","7+",h.pow],["PRelu","","7+",h.pRelu],["ReduceLogSum","","1+",v.reduceLogSum,v.parseReduceAttributes],["ReduceMax","","1+",v.reduceMax,v.parseReduceAttributes],["ReduceMean","","1+",v.reduceMean,v.parseReduceAttributes],["ReduceMin","","1+",v.reduceMin,v.parseReduceAttributes],["ReduceProd","","1+",v.reduceProd,v.parseReduceAttributes],["ReduceSum","","1-12",v.reduceSum,v.parseReduceAttributes],["ReduceSumSquare","","1+",v.reduceLogSumSquare,v.parseReduceAttributes],["Relu","","6+",M.relu],["Reshape","","5+",S.reshape],["Resize","","10",A.resize,A.parseResizeAttributesV10],["Resize","","11+",A.resize,A.parseResizeAttributesV11],["Shape","","1+",O.shape],["Sigmoid","","6+",M.sigmoid],["Sin","","7+",M.sin],["Slice","","10+",x.sliceV10],["Slice","","1-9",x.slice,x.parseSliceAttributes],["Softmax","","1-12",I.softmax,I.parseSoftmaxAttributes],["Softmax","","13+",I.softmaxV13,I.parseSoftmaxAttributesV13],["Split","","2-12",$.split,$.parseSplitAttributes],["Sqrt","","6+",M.sqrt],["Squeeze","","1-12",z.squeeze,z.parseSqueezeAttributes],["Squeeze","","13+",z.squeezeV13],["Sub","","7+",h.sub],["Sum","","6+",L.sum],["Tan","","7+",M.tan],["Tanh","","6+",M.tanh],["Tile","","6+",N.tile],["Transpose","","1+",H.transpose,H.parseTransposeAttributes],["Upsample","","7-8",Z.upsample,Z.parseUpsampleAttributesV7],["Upsample","","9",Z.upsample,Z.parseUpsampleAttributesV9],["Unsqueeze","","1-12",j.unsqueeze,j.parseUnsqueezeAttributes],["Unsqueeze","","13+",j.unsqueezeV13],["Xor","","7+",h.xor]]},2898:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseBatchNormalizationAttributes=n.batchNormalization=void 0;const c=s(246),l=s(5060),f=s(2039),a={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[f.TextureType.unpacked,f.TextureType.unpacked,f.TextureType.unpacked,f.TextureType.unpacked,f.TextureType.unpacked]};n.batchNormalization=(u,o,t)=>(p(o),[u.run(Object.assign(Object.assign({},a),{cacheHint:t.cacheKey,get:()=>h(u,o,t)}),o)]),n.parseBatchNormalizationAttributes=u=>{const o=u.attributes.getFloat("epsilon",1e-5),t=u.attributes.getFloat("momentum",.9),e=u.attributes.getInt("spatial",1);return(0,c.createAttributeWithCacheKey)({epsilon:o,momentum:t,spatial:e})};const h=(u,o,t)=>{const e=(0,l.getGlsl)(u.session.backend.glContext.version),r=o[0].dims.length,[i,d]=u.calculateTextureWidthAndHeight(o[1].dims,f.TextureType.unpacked),g=` - float process(int[${r}] indices) { - vec2 position = offsetToCoords(indices[1], ${i}, ${d}); - float scale = getColorAsFloat(${e.texture2D}(Scale, position)); - float mean = getColorAsFloat(${e.texture2D}(Mean, position)); - float variance = getColorAsFloat(${e.texture2D}(Variance, position)); - float b = getColorAsFloat(${e.texture2D}(B, position)); - - return scale * ( (_A(indices) - mean) / sqrt(variance + float(${t.epsilon})) ) + b; - }`;return Object.assign(Object.assign({},a),{output:{dims:o[0].dims,type:o[0].type,textureType:f.TextureType.unpacked},shaderSource:g})},p=u=>{if(!u||u.length!==5)throw new Error("BatchNormalization requires 5 inputs.");const o=u[0],t=u[1],e=u[2],r=u[3],i=u[4];if(o.dims.length<3||t.dims.length!==1||e.dims.length!==1||r.dims.length!==1||i.dims.length!==1)throw new Error("invalid input shape.");if(t.dims[0]!==o.dims[1]||e.dims[0]!==o.dims[1]||r.dims[0]!==o.dims[1]||i.dims[0]!==o.dims[1])throw new Error("invalid input shape.");if(o.type!=="float32"&&o.type!=="float64"||t.type!=="float32"&&t.type!=="float64"||e.type!=="float32"&&e.type!=="float64"||r.type!=="float32"&&r.type!=="float64"||i.type!=="float32"&&i.type!=="float64")throw new Error("invalid input tensor types.")}},7839:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.xor=n.sub=n.pRelu=n.pow=n.or=n.mul=n.less=n.greater=n.equal=n.div=n.and=n.add=n.glslPRelu=n.glslPow=n.glslXor=n.glslOr=n.glslAnd=n.glslLess=n.glslGreater=n.glslEqual=n.glslSub=n.glslMul=n.glslDiv=n.glslAdd=void 0;const c=s(2517),l=s(8520),f=s(5060),a=s(2039);function h(){const v="add_";return{body:` - float ${v}(float a, float b) { - return a + b; - } - vec4 ${v}(vec4 v1, vec4 v2) { - return v1 + v2; - } - `,name:v,type:l.FunctionType.ValueBased}}function p(){const v="div_";return{body:` - float ${v}(float a, float b) { - return a / b; - } - vec4 ${v}(vec4 v1, vec4 v2) { - return v1 / v2; - } - `,name:v,type:l.FunctionType.ValueBased}}function u(){const v="mul_";return{body:` - float ${v}(float a, float b) { - return a * b; - } - vec4 ${v}(vec4 v1, vec4 v2) { - return v1 * v2; - } - `,name:v,type:l.FunctionType.ValueBased}}function o(){const v="sub_";return{body:` - float ${v}(float a, float b) { - return a - b; - } - vec4 ${v}(vec4 v1, vec4 v2) { - return v1 - v2; - } - `,name:v,type:l.FunctionType.ValueBased}}function t(){const v="equal_";return{body:` - float ${v}(float a, float b) { - return float(a == b); - } - vec4 ${v}(vec4 v1, vec4 v2) { - return vec4(equal(v1, v2)); - } - `,name:v,type:l.FunctionType.ValueBased}}function e(){const v="greater_";return{body:` - float ${v}(float a, float b) { - return float(a > b); - } - vec4 ${v}(vec4 v1, vec4 v2) { - return vec4( v1.r > v2.r , - v1.g > v2.g, - v1.b > v2.b, - v1.a > v2.a ); - } - `,name:v,type:l.FunctionType.ValueBased}}function r(){const v="less_";return{body:` - float ${v}(float a, float b) { - return float(a < b); - } - vec4 ${v}(vec4 v1, vec4 v2) { - return vec4( v1.r < v2.r , - v1.g < v2.g, - v1.b < v2.b, - v1.a < v2.a ); - } - `,name:v,type:l.FunctionType.ValueBased}}function i(){const v="and_";return{body:` - float ${v}(float a, float b) { - return float( bool(a) && bool(b) ); - } - vec4 ${v}(vec4 v1, vec4 v2) { - bvec4 b1 = bvec4(v1); - bvec4 b2 = bvec4(v2); - return vec4( b1.r && b2.r , - b1.g && b2.g, - b1.b && b2.b, - b1.a && b2.a ); - } - `,name:v,type:l.FunctionType.ValueBased}}function d(){const v="or_";return{body:` - float ${v}(float a, float b) { - return float( bool(a) || bool(b) ); - } - vec4 ${v}(vec4 v1, vec4 v2) { - bvec4 b1 = bvec4(v1); - bvec4 b2 = bvec4(v2); - return vec4( b1.r || b2.r , - b1.g || b2.g, - b1.b || b2.b, - b1.a || b2.a ); - } - `,name:v,type:l.FunctionType.ValueBased}}function g(){const v="xor_";return{body:` - float ${v}(float a, float b) { - return float( bool(a) ^^ bool(b) ); - } - vec4 ${v}(vec4 v1, vec4 v2) { - bvec4 b1 = bvec4(v1); - bvec4 b2 = bvec4(v2); - return vec4( b1.r ^^ b2.r , - b1.g ^^ b2.g, - b1.b ^^ b2.b, - b1.a ^^ b2.a ); - } - `,name:v,type:l.FunctionType.ValueBased}}function m(){return function(v){const S=`${v}_`;return{body:` - float ${S}(float a, float b) { - return ${v}(a, b); - } - vec4 ${S}(vec4 v1, vec4 v2) { - return ${v}(v1, v2); - } - `,name:S,type:l.FunctionType.ValueBased}}("pow")}function b(){const v="prelu_";return{body:` - float ${v}(float a, float b) { - return a < 0.0 ? a * b: a; - } - vec4 ${v}(vec4 v1, vec4 v2) { - return vec4( - v1.r < 0.0 ? v1.r * v2.r: v1.r, - v1.g < 0.0 ? v1.g * v2.g: v1.g, - v1.b < 0.0 ? v1.b * v2.b: v1.b, - v1.a < 0.0 ? v1.a * v2.a: v1.a - ); - } - `,name:v,type:l.FunctionType.ValueBased}}n.glslAdd=h,n.glslDiv=p,n.glslMul=u,n.glslSub=o,n.glslEqual=t,n.glslGreater=e,n.glslLess=r,n.glslAnd=i,n.glslOr=d,n.glslXor=g,n.glslPow=m,n.glslPRelu=b;const y=(v,S,A,O=S[0].type,x)=>{const I=v.session.pack?a.TextureType.packed:a.TextureType.unpacked;return{name:A.name,inputNames:["A","B"],inputTypes:[I,I],cacheHint:x,get:()=>w(v,S,A,O)}},w=(v,S,A,O=S[0].type)=>{const x=v.session.pack?a.TextureType.packed:a.TextureType.unpacked,I=!c.ShapeUtil.areEqual(S[0].dims,S[1].dims);let $=S[0].dims;const z=v.session.pack;if(I){const H=c.BroadcastUtil.calcShape(S[0].dims,S[1].dims,!1);if(!H)throw new Error("Can't perform binary op on the given tensors");$=H;const M=$.length,j=S[0].dims.length!==0?S[0].dims.length:1,Z=S[1].dims.length!==0?S[1].dims.length:1,X=S[0].dims.length!==0?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",Q=S[1].dims.length!==0?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",ee=(0,f.getGlsl)(v.session.backend.glContext.version),ue=z?` - ${A.body} - void main() { - vec4 a = getAAtOutCoords(); - vec4 b = getBAtOutCoords(); - vec4 result = ${A.name}(a, b); - ${ee.output} = result; - }`:` - ${A.body} - float process(int indices[${M}]) { - int aindices[${j}]; - int bindices[${Z}]; - ${X} - ${Q} - return ${A.name}(_A(aindices), _B(bindices)); - }`;return{name:A.name,inputNames:["A","B"],inputTypes:[x,x],output:{dims:$,type:O,textureType:x},shaderSource:ue,hasMain:z}}const L=(0,f.getGlsl)(v.session.backend.glContext.version),N=` - ${A.body} - void main() { - vec4 v1 = ${L.texture2D}(A, TexCoords); - vec4 v2 = ${L.texture2D}(B, TexCoords); - vec4 result = ${A.name}(v1, v2); - ${L.output} = result; - } - `;return{name:A.name,inputNames:["A","B"],inputTypes:[x,x],output:{dims:S[0].dims,type:O,textureType:x},shaderSource:N,hasMain:!0}};n.add=(v,S)=>[v.run(y(v,S,h()),S)],n.and=(v,S)=>[v.run(y(v,S,i(),"bool"),S)],n.div=(v,S)=>[v.run(y(v,S,p()),S)],n.equal=(v,S)=>[v.run(y(v,S,t(),"bool"),S)],n.greater=(v,S)=>[v.run(y(v,S,e(),"bool"),S)],n.less=(v,S)=>[v.run(y(v,S,r(),"bool"),S)],n.mul=(v,S)=>[v.run(y(v,S,u()),S)],n.or=(v,S)=>[v.run(y(v,S,d(),"bool"),S)],n.pow=(v,S)=>[v.run(y(v,S,m()),S)],n.pRelu=(v,S)=>[v.run(y(v,S,b()),S)],n.sub=(v,S)=>[v.run(y(v,S,o()),S)],n.xor=(v,S)=>[v.run(y(v,S,g(),"bool"),S)]},4196:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseCastAttributes=n.cast=void 0;const c=s(2517);n.cast=(f,a,h)=>(l(a),[f.cast(a[0],h)]),n.parseCastAttributes=f=>c.ProtoUtil.tensorDataTypeFromProto(f.attributes.getInt("to"));const l=f=>{if(!f||f.length!==1)throw new Error("Cast requires 1 input.");if(f[0].type==="string")throw new Error("Invalid input type.")}},1163:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createPackedConcatProgramInfoLoader=void 0;const c=s(5060),l=s(2039),f=s(9390),a=s(2827);n.createPackedConcatProgramInfoLoader=(p,u,o)=>{const t=(e=u.length,r=o.cacheKey,{name:"Concat (packed)",inputNames:Array.from({length:e},(i,d)=>`X${d}`),inputTypes:Array(e).fill(l.TextureType.packed),cacheHint:r});var e,r;return Object.assign(Object.assign({},t),{get:()=>((i,d,g,m)=>{const b=g[0].dims.slice();if(m>=b.length||m<-1*b.length)throw new Error("axis specified for concat doesn't match input dimensionality");m<0&&(m=b.length+m);const y=b.slice(0);for(let X=1;XX.dims),x=(0,f.getGlChannels)(w),I=new Array(O.length-1);I[0]=O[0][m];for(let X=1;X= ${I[X-1]}) { - return getChannel( - getX${X}(${h(x,$,Q)}), - vec2(${h(z,$,Q)})); - }`}const H=I.length,M=I[I.length-1];N+=` - return getChannel( - getX${H}(${h(x,$,M)}), - vec2(${h(z,$,M)}));`;const j=(0,c.getGlsl)(i.session.backend.glContext.version),Z=` - ${A} - float getValue(${x.map(X=>"int "+X)}) { - ${N} - } - - void main() { - ${S} coords = getOutputCoords(); - int lastDim = coords.${x[w-1]}; - coords.${x[w-1]} = coords.${x[w-2]}; - coords.${x[w-2]} = lastDim; - - vec4 result = vec4(getValue(${v}), 0., 0., 0.); - - ${v[w-1]} = ${v[w-1]} + 1; - if (${v[w-1]} < ${y[w-1]}) { - result.g = getValue(${v}); - } - - ${v[w-2]} = ${v[w-2]} + 1; - if (${v[w-2]} < ${y[w-2]}) { - result.a = getValue(${v}); - } - - ${v[w-1]} = ${v[w-1]} - 1; - if (${v[w-2]} < ${y[w-2]} && - ${v[w-1]} < ${y[w-1]}) { - result.b = getValue(${v}); - } - ${j.output} = result; - } - `;return Object.assign(Object.assign({},d),{output:{dims:y,type:g[0].type,textureType:l.TextureType.packed},shaderSource:Z,hasMain:!0})})(p,t,u,o.axis)})};const h=(p,u,o)=>{const t=p.indexOf(u);return p.map((e,r)=>r===t?`${e} - ${o}`:e).join()}},2069:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseConcatAttributes=n.concat=void 0;const c=s(246),l=s(2039),f=s(1163);n.concat=(e,r,i)=>(t(r),e.session.pack&&r[0].dims.length>1?[e.run((0,f.createPackedConcatProgramInfoLoader)(e,r,i),r)]:[e.run(a(e,r,i),r)]);const a=(e,r,i)=>{const d=(g=r.length,m=i.cacheKey,{name:"Concat",inputNames:Array.from({length:g},(b,y)=>`X${y}`),inputTypes:Array(g).fill(l.TextureType.unpacked),cacheHint:m});var g,m;return Object.assign(Object.assign({},d),{get:()=>((b,y,w,v)=>{const S=w[0].dims.slice();if(v>=S.length||v<-1*S.length)throw new Error("axis specified for concat doesn't match input dimensionality");v<0&&(v=S.length+v);const A=S.slice(0);for(let L=1;L`int getTextureWhereDataResides(int index) { - ${e.map((r,i)=>`if(index<${r}) {return ${i};} -`).join("")} - }`,p=e=>h(e),u=(e,r)=>{const i=[`float fetchDataFromCorrectTexture(int textureIndex, int indices[${r}]) {`];for(let d=0;d{const r=["int getSizeInConcatAxisValueFromIndex(int index) {"];for(let i=0;i(0,c.createAttributeWithCacheKey)({axis:e.attributes.getInt("axis")});const t=e=>{if(!e||e.length<1)throw new Error("too few inputs");const r=e[0].type,i=e[0].dims.length;if(r==="string")throw new Error("string tensor is not supported yet");for(const d of e){if(d.type!==r)throw new Error("input tensors should be one type");if(d.dims.length!==i)throw new Error("input tensors should have the same shape")}}},4770:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createUnpackedGroupedConvProgramInfoLoader=void 0;const c=s(6231),l=s(5060),f=s(2039),a=s(8138),h=s(2823);n.createUnpackedGroupedConvProgramInfoLoader=(p,u,o)=>{const t=(e=u.length>2,r=o.cacheKey,{name:"GroupedConv",inputNames:e?["X","W","Bias"]:["X","W"],inputTypes:e?[f.TextureType.unpacked,f.TextureType.unpacked,f.TextureType.unpacked]:[f.TextureType.unpacked,f.TextureType.unpacked],cacheHint:r});var e,r;return Object.assign(Object.assign({},t),{get:()=>((i,d,g,m)=>{const b=d.length>2?"value += getBias(output_channel);":"",y=d[0].dims.slice(),w=d[1].dims.slice(),v=w[0]/m.group;c.Logger.verbose("GroupedConv",`autpPad:${m.autoPad}, dilations:${m.dilations}, group:${m.group}, kernelShape:${m.kernelShape}, pads:${m.pads}, strides:${m.strides}`);const S=(0,a.calculateOutputShape)(y,w,m.dilations,m.pads,m.strides),A=(0,l.getGlsl)(i.session.backend.glContext.version),{activationFunction:O,applyActivation:x}=(0,h.getActivationSnippet)(m),I=` - const ivec2 strides = ivec2(${m.strides[0]}, ${m.strides[1]}); - const ivec2 pads = ivec2(${m.pads[0]}, ${m.pads[1]}); - ${O} - void main() { - ivec4 coords = getOutputCoords(); - int batch = coords.x; - int output_channel = coords.y; - ivec2 xRCCorner = coords.zw * strides - pads; - int group_id = output_channel / ${v}; - - float value = 0.0; - for (int wInChannel = 0; wInChannel < ${w[1]}; wInChannel++) { - int input_channel = group_id * ${w[1]} + wInChannel; - for (int wHeight = 0; wHeight < ${w[2]}; wHeight++) { - int xHeight = xRCCorner.x + wHeight * ${m.dilations[0]}; - - if (xHeight < 0 || xHeight >= ${y[2]}) { - continue; - } - - for (int wWidth = 0; wWidth < ${w[3]}; wWidth++) { - int xWidth = xRCCorner.y + wWidth * ${m.dilations[1]}; - if (xWidth < 0 || xWidth >= ${y[3]}) { - continue; - } - - float xVal = getX(batch, input_channel, xWidth, xHeight); - float wVal = getW(output_channel, wInChannel, wWidth, wHeight); - value += xVal*wVal; - } - } - } - ${b} - ${x} - ${A.output} = vec4(value, .0, .0, .0); - } -`;return Object.assign(Object.assign({},g),{output:{dims:S,type:d[0].type,textureType:f.TextureType.unpacked},shaderSource:I,hasMain:!0})})(p,u,t,o)})}},1386:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.conv2DPacked=n.conv2DPackedPointwise=void 0;const c=s(8138),l=s(8555),f=s(708);n.conv2DPackedPointwise=(a,h,p)=>{const u=h[0].dims,o=h[1].dims,t=(0,c.calculateOutputShape)(u,o,p.dilations,p.pads,p.strides),e=a.reshapePacked(h[0],[u[1],u[2]*u[3]]),r=a.reshapePacked(h[1],[o[0],o[1]]),i=h.length>2?[r,e,h[2]]:[r,e],d=a.run((0,f.createPackedMatmulProgramInfoLoader)(a,i,p),i);return a.reshapePacked(d,t)},n.conv2DPacked=(a,h,p)=>{const u=h[0].dims,o=h[1].dims,t=(0,c.calculateOutputShape)(u,o,p.dilations,p.pads,p.strides),e=a.run((0,l.createPackedIm2ColProgramInfoLoader)(a,h[0],h[1],t,p),[h[0]]),r=a.reshapePacked(h[1],[o[0],o[1]*o[2]*o[3]]),i=h.length===3?[r,e,h[2]]:[r,e],d=a.run((0,f.createPackedMatmulProgramInfoLoader)(a,i,p),i);return a.reshapePacked(d,t)}},9663:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseConvTransposeAttributes=n.convTranspose=void 0;const c=s(246),l=s(5060),f=s(2039),a=s(2823),h=(r,i,d,g,m,b)=>(r-1)*i+d+(g-1)*m+1-b,p=(r,i,d,g,m)=>{const b=Math.floor(r/2);i==="SAME_UPPER"?(d[g]=b,d[m]=r-b):i==="SAME_LOWER"&&(d[g]=r-b,d[m]=b)};n.convTranspose=(r,i,d)=>(e(i,d),u(r,i,d));const u=(r,i,d)=>{const g=t(d,i);return[o(r,i,g)]},o=(r,i,d)=>r.run(((g,m,b)=>{const y=(w=m.length>2,v=b.cacheKey,{name:"ConvTranspose",inputNames:w?["X","W","B"]:["X","W"],inputTypes:w?[f.TextureType.unpacked,f.TextureType.unpacked,f.TextureType.unpacked]:[f.TextureType.unpacked,f.TextureType.unpacked],cacheHint:v});var w,v;return Object.assign(Object.assign({},y),{get:()=>((S,A,O,x)=>{const I=A.length>2?"getB(output_channel)":"0.0",$=A[0].dims,z=A[1].dims,L=z[1],N=z[0]/x.group,H=[A[0].dims[0],A[1].dims[1]*x.group,...x.outputShape],M=(0,l.getGlsl)(S.session.backend.glContext.version),{activationFunction:j,applyActivation:Z}=(0,a.getActivationSnippet)(x),X=` - const ivec2 strides = ivec2(${x.strides[0]}, ${x.strides[1]}); - const ivec2 pads = ivec2(${x.pads[0]}, ${x.pads[1]}); - ${j} - void main() { - ivec4 coords = getOutputCoords(); - int batch = coords.x; - int output_channel = coords.y; - - ivec2 loc = coords.zw + pads; - - int group_id = output_channel / ${L}; - int wOutChannel = output_channel - group_id * ${L}; - - float value = ${I}; - for (int inChannelOffset = 0; inChannelOffset < ${N}; inChannelOffset++) { - int input_channel = group_id * ${N} + inChannelOffset; - for (int wWOff = 0; wWOff < ${z[2]}; wWOff++) { - for (int wHOff = 0; wHOff < ${z[3]}; wHOff++) { - ivec2 wOff = ivec2(wWOff * ${x.dilations[0]}, wHOff * ${x.dilations[1]}); - ivec2 wLoc = loc - wOff; - ivec2 wLocIn = wLoc / strides; - if ( - wLocIn * strides == wLoc && - wLocIn.x >= 0 && wLocIn.x < ${$[2]} && - wLocIn.y >= 0 && wLocIn.y < ${$[3]} - ) { - float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x); - float wVal = getW(input_channel, wOutChannel, wHOff, wWOff); - value += xVal * wVal; - } - } - } - } - ${Z} - ${M.output} = vec4(value, .0, .0, .0); - } -`;return Object.assign(Object.assign({},O),{output:{dims:H,type:A[0].type,textureType:f.TextureType.unpacked},shaderSource:X,hasMain:!0})})(g,m,y,b)})})(r,i,d),i),t=(r,i)=>{const d=r.kernelShape.slice();if(r.kernelShape.length===0)for(let y=2;y{const $=y.length-2,z=I.length===0;for(let L=0;L<$;++L){const N=z?y[L+2]*O[L]:I[L],H=h(y[L+2],O[L],A[L],w[L],v[L],N);p(H,S,A,L,L+$),z&&I.push(O[L]*(y[L+2]-1)+x[L]+(w[L]-1)*v[L]+1-A[L]-A[L+$])}})(i[0].dims,d,r.dilations,r.autoPad,g,r.strides,r.outputPadding,m);const b=Object.assign({},r);return Object.assign(b,{kernelShape:d,pads:g,outputShape:m,cacheKey:r.cacheKey}),b};n.parseConvTransposeAttributes=r=>{const i=r.attributes,d=(0,a.parseInternalActivationAttributes)(i),g=i.getString("auto_pad","NOTSET"),m=i.getInts("dilations",[1,1]),b=i.getInt("group",1),y=i.getInts("kernel_shape",[]),w=i.getInts("output_padding",[0,0]),v=i.getInts("output_shape",[]),S=i.getInts("pads",[0,0,0,0]),A=i.getInts("strides",[1,1]);return(0,c.createAttributeWithCacheKey)(Object.assign({autoPad:g,dilations:m,group:b,kernelShape:y,outputPadding:w,outputShape:v,pads:S,strides:A},d))};const e=(r,i)=>{if(!r||r.length!==2&&r.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(r[0].dims.length!==4||r[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");if(r[0].dims[1]!==r[1].dims[0])throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");const d=r[1].dims[1]*i.group;if(r.length===3&&(r[2].dims.length!==1||r[2].dims[0]!==d))throw new Error("invalid bias");const g=r[0].dims.length-2;if(i.dilations.length!==g)throw new Error(`dilations should be ${g}D`);if(i.strides.length!==g)throw new Error(`strides should be ${g}D`);if(i.pads.length!==2*g)throw new Error(`pads should be ${2*g}D`);if(i.outputPadding.length!==g)throw new Error(`output_padding should be ${g}D`);if(i.kernelShape.length!==0&&i.kernelShape.length!==r[1].dims.length-2)throw new Error("invalid kernel shape");if(i.outputShape.length!==0&&i.outputShape.length!==r[0].dims.length-2)throw new Error("invalid output shape");if(r[0].type!=="float32"||r[1].type!=="float32")throw new Error("ConvTranspose input(X,W) should be float tensor");if(r.length===3&&r[2].type!=="float32")throw new Error("ConvTranspose input(bias) should be float tensor")}},8138:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseConvAttributes=n.conv=n.calculateOutputShape=void 0;const c=s(246),l=s(2517),f=s(4770),a=s(1386),h=s(9828),p=s(2823),u=s(3248),o=s(5623);n.calculateOutputShape=(g,m,b,y,w)=>{const v=g[0],S=g.slice(2),A=S.length,O=m[0],x=m.slice(2).map(($,z)=>$+($-1)*(b[z]-1)),I=S.map(($,z)=>$+y[z]+y[z+A]).map(($,z)=>Math.floor(($-x[z]+w[z])/w[z]));return[v,O].concat(...I)},n.conv=(g,m,b)=>(d(m,b),t(g,m,b));const t=(g,m,b)=>{const y=i(b,m),w=g.session.pack,v=y.kernelShape[0]===1&&y.kernelShape[1]===1;return y.group>1?[g.run((0,f.createUnpackedGroupedConvProgramInfoLoader)(g,m,y),m)]:v&&w?[e(g,m,y)]:w&&m[0].dims.length===4&&m[0].dims[0]===1&&!v?[(0,a.conv2DPacked)(g,m,y)]:[r(g,m,y)]},e=(g,m,b)=>{const y=m[0].dims,w=m[1].dims,v=(0,n.calculateOutputShape)(y,w,b.dilations,b.pads,b.strides),S=g.reshapeUnpacked(m[0],[y[1],y[2]*y[3]]),A=g.reshapeUnpacked(m[1],[w[0],w[1]]),O=m.length>2?[A,S,m[2]]:[A,S],x=g.run((0,o.createMatmulProgramInfoLoader)(O,b),O);return g.reshapeUnpacked(x,v)},r=(g,m,b)=>{const y=m[0].dims,w=m[1].dims,v=(0,n.calculateOutputShape)(y,w,b.dilations,b.pads,b.strides),S=g.run((0,u.createIm2ColProgramInfoLoader)(g,m[0],m[1],v,b),[m[0]]),A=m.length===3?[S,m[1],m[2]]:[S,m[1]];return g.run((0,h.createDotProductProgramInfoLoader)(g,m,v,b),A)},i=(g,m)=>{const b=g.kernelShape.slice();if(g.kernelShape.length===0)for(let v=2;v{const m=g.attributes,b=(0,p.parseInternalActivationAttributes)(m),y=m.getString("auto_pad","NOTSET"),w=m.getInts("dilations",[1,1]),v=m.getInt("group",1),S=m.getInts("kernel_shape",[]),A=m.getInts("pads",[0,0,0,0]),O=m.getInts("strides",[1,1]);return(0,c.createAttributeWithCacheKey)(Object.assign({autoPad:y,dilations:w,group:v,kernelShape:S,pads:A,strides:O},b))};const d=(g,m)=>{if(!g||g.length!==2&&g.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(g[0].dims.length!==4||g[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");if(g[0].dims[1]!==g[1].dims[1]*m.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(g.length===3&&(g[2].dims.length!==1||g[1].dims[0]!==g[2].dims[0]))throw new Error("invalid bias");const b=g[0].dims.length-2;if(m.dilations.length!==b)throw new Error(`dilations should be ${b}D`);if(m.strides.length!==b)throw new Error(`strides should be ${b}D`);if(m.pads.length!==2*b)throw new Error(`pads should be ${2*b}D`);if(m.kernelShape.length!==0&&m.kernelShape.length!==g[1].dims.length-2)throw new Error("invalid kernel shape");if(g[0].type!=="float32"||g[1].type!=="float32")throw new Error("Conv input(X,W) should be float tensor");if(g.length===3&&g[2].type!=="float32")throw new Error("Conv input(bias) should be float tensor")}},5193:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseDepthToSpaceAttributes=n.depthToSpace=void 0;const c=s(3738);n.depthToSpace=(f,a,h)=>{l(a);const p=h.blocksize,u=p*p,o=h.mode==="DCR"?[0,3,4,1,5,2]:[0,1,4,2,5,3],t=h.mode==="DCR"?[a[0].dims[0],p,p,a[0].dims[1]/u,a[0].dims[2],a[0].dims[3]]:[a[0].dims[0],a[0].dims[1]/u,p,p,a[0].dims[2],a[0].dims[3]],e=f.reshapeUnpacked(a[0],t),r={perm:o,cacheKey:`${o}`},[i]=(0,c.transpose)(f,[e],r),d=[a[0].dims[0],a[0].dims[1]/u,a[0].dims[2]*p,a[0].dims[3]*p];return[f.reshapeUnpacked(i,d)]},n.parseDepthToSpaceAttributes=f=>{const a=f.attributes.getInt("blocksize");if(a<1)throw new Error(`blocksize must be >= 1, but got : ${a} for DepthToSpace`);const h=f.attributes.getString("mode","DCR");if(h!=="DCR"&&h!=="CRD")throw new Error(`unrecognized mode: ${h} for DepthToSpace`);return{mode:h,blocksize:a}};const l=f=>{if(f.length!==1)throw new Error(`DepthToSpace expect 1 inputs, but got ${f.length}`);if(f[0].type==="string"||f[0].dims.length!==4)throw new TypeError("DepthToSpace input should be a 4-D numeric tensor")}},9828:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createDotProductProgramInfoLoader=void 0;const c=s(2517),l=s(5060),f=s(2039),a=s(2823),h=s(3248);n.createDotProductProgramInfoLoader=(p,u,o,t)=>{const e=((r,i)=>({name:"ConvDotProduct",inputNames:r?["Im2Col","K","B"]:["Im2Col","K"],inputTypes:r?[f.TextureType.unpacked,f.TextureType.packedLastDimension,f.TextureType.unpacked]:[f.TextureType.unpacked,f.TextureType.packedLastDimension],cacheKey:i.activationCacheKey}))(u.length>2,t);return Object.assign(Object.assign({},e),{get:()=>((r,i,d,g,m)=>{const b=d[0].dims,y=d[1].dims,w=[y[0],Math.ceil(b[1]*y[2]*y[3]/4)],v=(0,h.calculateIm2ColDims)(b,y,g),[S,A]=r.calculateTextureWidthAndHeight(w,f.TextureType.packedLastDimension),O=c.ShapeUtil.computeStrides(v),[x,I]=r.calculateTextureWidthAndHeight(v,f.TextureType.packedLastDimension),$=g.length,z=d.length<3?"0.0":"_B(b)",L=Math.ceil(b[1]*y[2]*y[3]/4),{activationFunction:N,applyActivation:H}=(0,a.getActivationSnippet)(m),M=(0,l.getGlsl)(r.session.backend.glContext.version),j=` -${N} -float process(int indices[${$}]) { - int b[1]; - b[0] = indices[1]; - int im2col[4]; - im2col[0] = indices[0]; - im2col[1] = indices[2]; - im2col[2] = indices[3]; - int im2colOffset = im2col[0] * ${O[0]} + im2col[1] * ${O[1]} + im2col[2] * ${O[2]}; - int kernelOffset = indices[1] * ${w[1]}; - float value = ${z}; - for (int i = 0; i < ${L}; ++i) { - vec2 im2colCoords = offsetToCoords(im2colOffset, ${x}, ${I}); - vec2 kernelCoords = offsetToCoords(kernelOffset, ${S}, ${A}); - value += dot(${M.texture2D}(Im2Col, im2colCoords), ${M.texture2D}(K, kernelCoords)); - ++im2colOffset; - ++kernelOffset; - } - ${H} - return value; -}`;return Object.assign(Object.assign({},i),{output:{dims:g,type:d[0].type,textureType:f.TextureType.unpacked},shaderSource:j})})(p,e,u,o,t)})}},7992:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseFlattenAttributes=n.flatten=void 0;const c=s(2517);n.flatten=(f,a,h)=>{l(a,h);const p=c.ShapeUtil.flattenShape(a[0].dims,h);return[f.reshapeUnpacked(a[0],p)]},n.parseFlattenAttributes=f=>f.attributes.getInt("axis",1);const l=(f,a)=>{if(!f||f.length!==1)throw new Error("Flatten requires 1 input.");const h=f[0].dims.length;if(h===0)throw new Error("scalar tensor is not supported.");if(a<-h||a>h)throw new Error("Invalid axis");if(f[0].type==="string")throw new Error("string tensor is not supported.")}},2823:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseInternalActivationAttributes=n.getActivationSnippet=void 0;const c=s(2517),l=s(4909);n.getActivationSnippet=function(f){let a;switch(f.activation){case"Relu":a=(0,l.glslRelu)();break;case"Sigmoid":a=(0,l.glslSigmoid)();break;case"Clip":a=(0,l.glslClip)(f.clipMin,f.clipMax);break;default:return{activationFunction:"",applyActivation:""}}const h=a.name;return{activationFunction:a.body,applyActivation:`value = ${h}_(value);`}},n.parseInternalActivationAttributes=f=>{const a=f.getString("activation","");if(a==="Clip"){const[h,p]=f.getFloats("activation_params",[c.MIN_CLIP,c.MAX_CLIP]);return{activation:a,clipMax:p,clipMin:h,activationCacheKey:`${a}:${h},${p}`}}return{activation:a,activationCacheKey:a}}},1253:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseGatherAttributes=n.gather=void 0;const c=s(246),l=s(782),f=s(2517),a=s(2039);n.gather=(o,t,e)=>(u(t,e.axis),[o.run(p(o,t,e),t)]),n.parseGatherAttributes=o=>(0,c.createAttributeWithCacheKey)({axis:o.attributes.getInt("axis",0)});const h={name:"Gather",inputNames:["A","B"],inputTypes:[a.TextureType.unpacked,a.TextureType.unpacked]},p=(o,t,e)=>{const r=Object.assign(Object.assign({},h),{cacheHint:e.cacheKey});return Object.assign(Object.assign({},r),{get:()=>((i,d,g,m)=>{const b=g[0].dims.slice(),y=g[1].dims.slice(),w=new Array(b.length+y.length-1);m=f.ShapeUtil.normalizeAxis(m,b.length);const v=[];for(let A=0;A{if(!o||o.length!==2)throw new Error("Gather requires 2 inputs.");const e=o[0].dims.length;if(e<1)throw new Error("Invalid input shape.");if(t<-e||t>e-1)throw new Error("Invalid axis.");if(l.NUMBER_TYPES.indexOf(o[0].type)===-1)throw new Error("Invaid input type.");if(o[1].type!=="int32"&&o[1].type!=="int16")throw new Error("Invaid input type.")}},4776:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseGemmAttributesV11=n.parseGemmAttributesV7=n.gemm=void 0;const c=s(246),l=s(2517),f=s(2039);n.gemm=(o,t,e)=>(u(t,e),[o.run(h(t,e),t)]);const a=(o,t)=>{const e=o.attributes.getInt("transA",0)!==0,r=o.attributes.getInt("transB",0)!==0,i=o.attributes.getFloat("alpha",1),d=o.attributes.getFloat("beta",1);return(0,c.createAttributeWithCacheKey)({transA:e,transB:r,alpha:i,beta:d,isOptionalC:t})};n.parseGemmAttributesV7=o=>a(o,!1),n.parseGemmAttributesV11=o=>a(o,!0);const h=(o,t)=>{const e={name:"Gemm",inputNames:o.length===3?["A","B","C"]:["A","B"],inputTypes:o.length===3?[f.TextureType.unpacked,f.TextureType.unpacked,f.TextureType.unpacked]:[f.TextureType.unpacked,f.TextureType.unpacked],key:t.cacheKey};return Object.assign(Object.assign({},e),{get:()=>p(e,o,t)})},p=(o,t,e)=>{const r=t[0].dims.slice(),i=t[1].dims.slice(),[d,g]=l.GemmUtil.getShapeOfGemmResult(r,e.transA,i,e.transB,t.length===3?t[2].dims:void 0),m=[d,g];if(!m)throw new Error("Can't use gemm on the given tensors");let b=r[r.length-1],y="";e.transA&&(b=r[0]),e.transA&&e.transB?y="value += _A_T(a) * _B_T(b);":e.transA&&!e.transB?y="value += _A_T(a) * _B(b);":!e.transA&&e.transB?y="value += _A(a) * _B_T(b);":e.transA||e.transB||(y="value += _A(a) * _B(b);");const w=m.length,v=` - float process(int indices[${w}]) { - int a[${w}]; - int b[${w}]; - ${t.length===3?`int c[${t[2].dims.length}];`:""} - - copyVec(indices, a); - copyVec(indices, b); - ${t.length===3?"bcastIndices_C(indices, c);":""} - - float value = 0.0; - for (int k=0; k<${b}; ++k) { - a[${w-1}] = k; - b[${w-2}] = k; - ${y} - } - - value = value * alpha; - ${t.length===3?"value += beta * _C(c);":""} - return value; - }`;return Object.assign(Object.assign({},o),{output:{dims:m,type:t[0].type,textureType:f.TextureType.unpacked},variables:[{name:"alpha",type:"float",data:e.alpha},{name:"beta",type:"float",data:e.beta}],shaderSource:v})},u=(o,t)=>{if(!o)throw new Error("Input is missing");if(t.isOptionalC&&(o.length<2||o.length>3))throw new Error("Invaid input shape.");if(!t.isOptionalC&&o.length!==3)throw new Error("Gemm requires 3 inputs");if(o.length===3&&o[2].dims.length!==1&&o[2].dims.length!==2)throw new Error("Invalid input shape of C");if(o[0].type!=="float32"&&o[0].type!=="float64"||o[1].type!=="float32"&&o[1].type!=="float64"||o.length===3&&o[2].type!=="float32"&&o[2].type!=="float64")throw new Error("Invalid input type.");if(o[0].type!==o[1].type||o.length===3&&o[0].type!==o[2].type)throw new Error("Input types are mismatched")}},8555:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createPackedIm2ColProgramInfoLoader=void 0;const c=s(5060),l=s(2039),f=s(2827);n.createPackedIm2ColProgramInfoLoader=(a,h,p,u,o)=>{const t=(e=o.cacheKey,{name:"Im2Col (packed)",inputNames:["A"],inputTypes:[l.TextureType.packed],cacheHint:e});var e;return Object.assign(Object.assign({},t),{get:()=>((r,i,d,g,m,b)=>{const y=d.dims,w=g.dims,v=m.length,S=[w[1]*w[2]*w[3],m[2]*m[3]],A=w[2]*w[3],O=(0,f.unpackFromChannel)(),x=(0,c.getGlsl)(r.session.backend.glContext.version);let I="";for(let z=0;z<=1;z++)for(let L=0;L<=1;L++)I+=` - blockIndex = rc.x + ${L}; - pos = rc.y + ${z}; - - if(blockIndex < ${S[1]} && pos < ${S[0]}) { - offsetY = int(blockIndex / (${m[v-1]})) * ${b.strides[0]} - - ${b.pads[0]}; - d0 = offsetY + ${b.dilations[0]} * (imod(pos, ${A}) / ${w[2]}); - - if(d0 < ${y[2]} && d0 >= 0) { - offsetX = imod(blockIndex, ${m[v-1]}) * ${b.strides[1]} - - ${b.pads[1]}; - d1 = offsetX + ${b.dilations[1]} * imod(imod(pos, ${A}), ${w[2]}); - - if(d1 < ${y[3]} && d1 >= 0) { - - ch = int(float(pos)/ ${A}.); - innerDims = vec2(d0, d1); - result[${2*z+L}] = getChannel( - getA(0, ch, int(innerDims.x), - int(innerDims.y)), innerDims); - } - } - } - - `;const $=` - ${O} - - void main() { - ivec2 rc = getOutputCoords(); - vec4 result = vec4(0.0); - int blockIndex, pos, offsetY, d0, offsetX, d1, ch; - vec2 innerDims; - ${I} - ${x.output} = result; - } - `;return Object.assign(Object.assign({},i),{output:{dims:S,type:d.type,textureType:l.TextureType.packed},shaderSource:$,hasMain:!0})})(a,t,h,p,u,o)})}},3248:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.calculateIm2ColDims=n.createIm2ColProgramInfoLoader=void 0;const c=s(2039);n.createIm2ColProgramInfoLoader=(l,f,a,h,p)=>{const u=(o=p.cacheKey,{name:"Im2Col",inputNames:["X"],inputTypes:[c.TextureType.unpacked],cacheHint:o});var o;return Object.assign(Object.assign({},u),{get:()=>((t,e,r,i,d,g)=>{const m=r.dims,b=i.dims,y=d.length,w=(0,n.calculateIm2ColDims)(m,b,d,4),v=` - const int XC = ${m[1]}; - const int XH = ${m[2]}; - const int XW = ${m[3]}; - const int KH = ${g.kernelShape[0]}; - const int KW = ${g.kernelShape[1]}; - const int dilationH = ${g.dilations[0]}; - const int dilationW = ${g.dilations[1]}; - const int strideH = ${g.strides[0]}; - const int strideW = ${g.strides[1]}; - const int padH = ${g.pads[0]}; - const int padW = ${g.pads[1]}; - const int KHKW = KH*KW; - const int XCKHKW = XC * KHKW; - const int outputChannels = 4; - vec4 process(int indices[${y}]) { - int b = indices[0]; // batch size - int oh = indices[1] * strideH - padH; //output height - int ow = indices[2] * strideW - padW; //output width - int p = indices[3] * outputChannels; //patch - vec4 value = vec4(0.0); - for(int i=0; i < outputChannels; ++i) { - if(p < XCKHKW) { - int patchC = p / KHKW; - int patchH = (p - patchC*KHKW) / KW; - int patchW = (p - patchC*KHKW) - patchH * KW; - int xh2 = oh + patchH * dilationH; - int xw2 = ow + patchW * dilationW; - int x[${m.length}]; - x[0] = b; - x[1] = patchC; - x[2] = xh2; - x[3] = xw2; - if(xh2 >= 0 && - xh2 < XH && - xw2 >= 0 && - xw2 < XW) { - value[i] = _X(x); - } - } - ++p; - } - return value; - } - `;return Object.assign(Object.assign({},e),{output:{dims:w,type:r.type,textureType:c.TextureType.packedLastDimension},shaderSource:v})})(0,u,f,a,h,p)})},n.calculateIm2ColDims=(l,f,a,h=4)=>[a[0],a[2],a[3],Math.ceil(l[1]*f[2]*f[3]/h)]},6572:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseImageScalerAttributes=n.imageScaler=void 0;const c=s(246),l=s(2039);n.imageScaler=(u,o,t)=>(p(o),[u.run(a(u,o,t),o)]),n.parseImageScalerAttributes=u=>{const o=u.attributes.getFloat("scale"),t=u.attributes.getFloats("bias");return(0,c.createAttributeWithCacheKey)({scale:o,bias:t})};const f={name:"ImageScaler",inputNames:["X"],inputTypes:[l.TextureType.unpacked]},a=(u,o,t)=>{const e=Object.assign(Object.assign({},f),{cacheHint:t.cacheKey});return Object.assign(Object.assign({},e),{get:()=>((r,i,d,g)=>{const m=d[0].dims.slice(),b=m.length,y=` - ${h(g.bias.length)} - float process(int indices[${b}]) { - return _X(indices) * scale + getBias(bias, indices[1]); - }`;return Object.assign(Object.assign({},i),{output:{dims:m,type:d[0].type,textureType:l.TextureType.unpacked},variables:[{name:"bias",type:"float",arrayLength:g.bias.length,data:g.bias},{name:"scale",type:"float",data:g.scale}],shaderSource:y})})(0,e,o,t)})},h=u=>{const o=[`float getBias(float bias[${u}], int channel) {`];for(let t=0;t{if(!u||u.length!==1)throw new Error("ImageScaler requires 1 input.");if(u[0].dims.length!==4)throw new Error("Invalid input shape.");if(u[0].type!=="float32"&&u[0].type!=="float64")throw new Error("Invalid input type.")}},3346:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseInstanceNormalizationAttributes=n.instanceNormalization=void 0;const c=s(5060),l=s(2039);n.instanceNormalization=(o,t,e)=>{u(t);const r=o.run(a(t[0]),t);return[o.run(p(o,t[0],e,r.dims),[t[0],r,t[1],t[2]])]},n.parseInstanceNormalizationAttributes=o=>o.attributes.getFloat("epsilon",1e-5);const f={name:"InstanceNormalization_MeanAndVariance",inputNames:["X"],inputTypes:[l.TextureType.unpacked]},a=o=>Object.assign(Object.assign({},f),{get:()=>((t,e)=>{const r=e.dims.slice(),i=r[1],d=r[2]*r[3],g=[r[0],i],m=` - vec4 process(int[2] indices) { - vec4 v = vec4(0.0); - int a[4]; - a[0] = indices[0]; - a[1] = indices[1]; - float temp = 0.0; - for(int a2=0; a2<${r[2]}; a2++) { - a[2] = a2; - for(int a3=0; a3<${r[3]}; a3++) { - a[3] = a3; - float x = _X(a); - temp += x; - } - } - float mean = temp / float(${d}); - temp = 0.0; - for(int a2=0; a2<${r[2]}; a2++) { - a[2] = a2; - for(int a3=0; a3<${r[3]}; a3++) { - a[3] = a3; - float x = _X(a); - temp += (x - mean) * (x - mean); - } - } - v.r = mean; - v.g = temp / float(${d}); - - return v; - }`;return Object.assign(Object.assign({},t),{output:{dims:g,type:e.type,textureType:l.TextureType.packedLastDimension},shaderSource:m})})(f,o)}),h={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[l.TextureType.unpacked,l.TextureType.packedLastDimension,l.TextureType.unpacked,l.TextureType.unpacked]},p=(o,t,e,r)=>{const i=Object.assign(Object.assign({},h),{cacheHint:`${e}`});return Object.assign(Object.assign({},i),{get:()=>((d,g,m,b,y)=>{const w=(0,c.getGlsl)(d.session.backend.glContext.version),[v,S]=d.calculateTextureWidthAndHeight(y,l.TextureType.packedLastDimension),[A,O]=[v/4,S],x=` - vec4 get_MeanAndVariance(int[2] mv) { - int offset = indicesToOffset_MeanAndVariance(mv); - vec2 coords = offsetToCoords(offset, ${A}, ${O}); - return ${w.texture2D}(MeanAndVariance, coords); - } - - float process(int[4] indices) { - int mv[2]; - mv[0] = indices[0]; - mv[1] = indices[1]; - vec4 mean_and_variance = get_MeanAndVariance(mv); - float mean = mean_and_variance.r; - float variance = mean_and_variance.g; - - int sb[1]; - sb[0] = indices[1]; - float scale = _Scale(sb); - float b = _B(sb); - - return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b; - }`;return Object.assign(Object.assign({},g),{output:{dims:m.dims,type:m.type,textureType:l.TextureType.unpacked},variables:[{name:"epsilon",type:"float",data:b}],shaderSource:x})})(o,i,t,e,r)})},u=o=>{if(!o||o.length!==3)throw new Error("InstanceNormalization requires 3 inputs.");const t=o[0],e=o[1],r=o[2];if(t.dims.length<3||e.dims.length!==1||r.dims.length!==1)throw new Error("Invalid input shape.");if(e.dims[0]!==t.dims[1]||r.dims[0]!==t.dims[1])throw new Error("Input shapes are mismatched.");if(t.type!=="float32"&&t.type!=="float64"||e.type!=="float32"&&e.type!=="float64"||r.type!=="float32"&&r.type!=="float64")throw new Error("Invalid input type.");if(o[0].dims.length!==4)throw new Error("Only support 4-D input shape.")}},708:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createPackedMatmulProgramInfoLoader=void 0;const c=s(2517),l=s(5060),f=s(2039),a=s(9390),h=s(2823),p=s(5623);n.createPackedMatmulProgramInfoLoader=(u,o,t)=>{const e=(r=o.length>2,i=t.activationCacheKey,{name:"MatMul (packed)",inputNames:r?["A","B","Bias"]:["A","B"],inputTypes:r?[f.TextureType.packed,f.TextureType.packed,f.TextureType.packed]:[f.TextureType.packed,f.TextureType.packed],cacheHint:i});var r,i;return Object.assign(Object.assign({},e),{get:()=>((d,g,m,b)=>{const y=m.length>2,w=y?"value += getBiasForMatmul();":"",v=m[0].dims,S=m[1].dims,A=c.BroadcastUtil.calcShape(v,S,!0),O=!c.ShapeUtil.areEqual(m[0].dims,m[1].dims);if(!A)throw new Error("Can't use matmul on the given tensors");const x=v[v.length-1],I=Math.ceil(x/2),$=v.length,z=S.length,L=(0,l.getGlsl)(d.session.backend.glContext.version),N=(0,a.getCoordsDataType)(A.length),H=A.length,M=(0,a.getGlChannels)(),{activationFunction:j,applyActivation:Z}=(0,h.getActivationSnippet)(b),X=y?`${(0,p.getBiasForMatmul)(N,M,m[2].dims,A,!0)}`:"",Q=O?`${function(xe,oe,we,ye){let ke=[],Ne=[];const Te=we[0].dims,$e=we[1].dims,Ce=Te.length,Ee=$e.length,Oe=ye.length,ze=Oe-Ce,Ve=Oe-Ee;ke=Te.map((Ie,je)=>`coords.${oe[je+ze]}`),ke[Ce-1]="i*2",ke.join(", "),Ne=$e.map((Ie,je)=>`coords.${oe[je+Ve]}`),Ne[Ee-2]="i*2",Ne.join(", ");const Ge=c.BroadcastUtil.getBroadcastDims(Te,ye),Ye=c.BroadcastUtil.getBroadcastDims($e,ye),Je=Ge.map(Ie=>`coords.${oe[Ie+ze]} = 0;`).join(` -`),qe=Ye.map(Ie=>`coords.${oe[Ie+Ve]} = 0;`).join(` -`),Ue=`int lastDim = coords.${oe[Oe-1]}; - coords.${oe[Oe-1]} = coords.${oe[Oe-2]}; - coords.${oe[Oe-2]} = lastDim;`;return` -vec4 getAAtOutCoordsMatmul(int i) { - ${xe} coords = getOutputCoords(); - ${Ue} - ${Je} - vec4 outputValue = getA(${ke}); - return outputValue; -} - -vec4 getBAtOutCoordsMatmul(int i) { - ${xe} coords = getOutputCoords(); - ${Ue} - ${qe} - vec4 outputValue = getB(${Ne}); - return outputValue; -}`}(N,M,m,A)}`:"",ee=O?"getAAtOutCoordsMatmul(i)":`getA(${function(xe,oe){let we="";for(let ye=0;ye{Object.defineProperty(n,"__esModule",{value:!0}),n.getBiasForMatmul=n.createMatmulProgramInfoLoader=n.parseMatMulAttributes=n.matMul=void 0;const c=s(2517),l=s(2039),f=s(9390),a=s(2823),h=s(708);function p(t,e){const r=(i=t.length>2,d=e.activationCacheKey,{name:"MatMul",inputNames:i?["A","B","Bias"]:["A","B"],inputTypes:i?[l.TextureType.unpacked,l.TextureType.unpacked,l.TextureType.unpacked]:[l.TextureType.unpacked,l.TextureType.unpacked],cacheHint:d});var i,d;return Object.assign(Object.assign({},r),{get:()=>function(g,m,b){const y=m[0].dims,w=m[1].dims,v=c.BroadcastUtil.calcShape(y,w,!0);if(!v)throw new Error("Can't use matmul on the given tensors");const S=(0,f.getCoordsDataType)(v.length),A=(0,f.getGlChannels)(),{activationFunction:O,applyActivation:x}=(0,a.getActivationSnippet)(b),I=m.length>2,$=I?"value += getBiasForMatmul();":"",z=I?`${o(S,A,m[2].dims,v,!1)}`:"",L=v.length,N=y.length,H=w.length,M=` - ${O} - ${z} - float process(int indices[${L}]) { - int a[${N}]; - int b[${H}]; - bcastMatmulIndices_A(indices, a); - bcastMatmulIndices_B(indices, b); - - float value; - for (int k=0; k<${y[y.length-1]}; ++k) { - a[${N-1}] = k; - b[${H-2}] = k; - value += _A(a) * _B(b); - } - ${$} - ${x} - return value; - }`;return Object.assign(Object.assign({},g),{output:{dims:v,type:m[0].type,textureType:l.TextureType.unpacked},shaderSource:M})}(r,t,e)})}n.matMul=(t,e,r)=>(u(e),t.session.pack?[t.run((0,h.createPackedMatmulProgramInfoLoader)(t,e,r),e)]:[t.run(p(e,r),e)]),n.parseMatMulAttributes=t=>(0,a.parseInternalActivationAttributes)(t.attributes),n.createMatmulProgramInfoLoader=p;const u=t=>{if(!t||t.length!==2)throw new Error("MatMul requires 2 inputs.");if(t[0].dims[t[0].dims.length-1]!==t[1].dims[t[1].dims.length-2])throw new Error("shared dimension does not match.");if(t[0].type!=="float32"&&t[0].type!=="float64"||t[1].type!=="float32"&&t[1].type!=="float64")throw new Error("inputs should be float type");if(t[0].type!==t[1].type)throw new Error("inputs types should match")};function o(t,e,r,i,d){let g="";const m=r.length,b=i.length,y=b-m;g=b<2&&m>0?"coords":r.map((S,A)=>`coords.${e[A+y]}`).join(", ");const w=c.BroadcastUtil.getBroadcastDims(r,i).map(S=>`coords.${e[S+y]} = 0;`).join(` -`);let v="vec4(outputValue.xx, outputValue.yy)";return c.ShapeUtil.size(r)===1&&(v="vec4(outputValue.x)"),d?` -vec4 getBiasForMatmul() { - ${t} coords = getOutputCoords(); - ${w} - vec4 outputValue = getBias(${g}); - return ${v}; -}`:` -float getBiasForMatmul() { - ${t} coords = getOutputCoords(); - ${w} - return getBias(coords.x); -}`}n.getBiasForMatmul=o},2403:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createPackProgramInfoLoader=void 0;const c=s(5060),l=s(2039),f=s(9390),a=s(2827),h={name:"pack",inputNames:["A"],inputTypes:[l.TextureType.unpackedReversed]};n.createPackProgramInfoLoader=(p,u)=>Object.assign(Object.assign({},h),{get:()=>((o,t)=>{const e=(0,c.getGlsl)(o.session.backend.glContext.version),r=t.dims,i=r.length,d=t.dims.length,g=(0,f.getCoordsDataType)(d),m=(0,a.getChannels)("rc",d),b=(y=d,w=m,v=r[r.length-2],S=r[r.length-1],y===0||y===1?"":` - int r = ${w[y-2]}; - int c = ${w[y-1]}; - int rp1 = ${w[y-2]} + 1; - int cp1 = ${w[y-1]} + 1; - bool rEdge = rp1 >= ${S}; - bool cEdge = cp1 >= ${v}; - `);var y,w,v,S;let A;A=i===0?[1,1]:i===1?[r[0],1]:[r[d-1],r[d-2]];const O=function($,z,L){if($===0)return"false";if($===1)return`rc > ${z[0]}`;let N="";for(let H=$-2;H<$;H++)N+=`${L[H]} >= ${z[H-$+2]}`,H<$-1&&(N+="||");return N}(d,A,m),x=function($,z){const L=$.length;if(L===0)return"getA(), 0, 0, 0";if(L===1)return`getA(rc), - rc + 1 >= ${$[0]} ? 0. : getA(rc + 1), - 0, 0`;let N="";if(L>2)for(let H=0;H{Object.defineProperty(n,"__esModule",{value:!0}),n.unpackFromChannel=n.getChannels=n.getVecChannels=void 0;const c=s(9390);function l(f,a){return(0,c.getGlChannels)(a).map(h=>`${f}.${h}`)}n.getVecChannels=l,n.getChannels=function(f,a){return a===1?[f]:l(f,a)},n.unpackFromChannel=function(){return` - float getChannel(vec4 frag, int dim) { - int modCoord = imod(dim, 2); - return modCoord == 0 ? frag.r : frag.g; - } - - float getChannel(vec4 frag, vec2 innerDims) { - vec2 modCoord = mod(innerDims, 2.); - return modCoord.x == 0. ? - (modCoord.y == 0. ? frag.r : frag.g) : - (modCoord.y == 0. ? frag.b : frag.a); - } - `}},2870:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parsePadAttributesV11=n.padV11=n.parsePadAttributesV2=n.padV2=void 0;const c=s(246),l=s(2517),f=s(5060),a=s(2039),h={name:"Pad",inputNames:["A"],inputTypes:[a.TextureType.unpacked]};n.padV2=(g,m,b)=>(o(m),[g.run(Object.assign(Object.assign({},h),{cacheHint:b.cacheKey,get:()=>u(g,m[0],b)}),m)]),n.parsePadAttributesV2=g=>{const m=g.attributes.getString("mode","constant"),b=g.attributes.getFloat("value",0),y=g.attributes.getInts("pads");return(0,c.createAttributeWithCacheKey)({mode:m,value:b,pads:y})},n.padV11=(g,m,b)=>{t(m);const y=p(g,m,b);return(0,n.padV2)(g,[m[0]],y)},n.parsePadAttributesV11=g=>g.attributes.getString("mode","constant");const p=(g,m,b)=>{if(!g.session.isInitializer(m[1].dataId)||m.length>=3&&!g.session.isInitializer(m[2].dataId))throw new Error("dynamic pad attributes are not allowed");const y=Array.from(m[1].integerData),w=m.length>=3?m[2].floatData[0]:0;return(0,c.createAttributeWithCacheKey)({mode:b,pads:y,value:w})},u=(g,m,b)=>{const y=l.ShapeUtil.padShape(m.dims.slice(),b.pads),w=y.length,v=` - ${e(g,m,b)} - float process(int[${w}] indices) { - return padA(indices); - }`;return{name:"Pad",inputNames:["A"],inputTypes:[a.TextureType.unpacked],output:{dims:y,type:m.type,textureType:a.TextureType.unpacked},shaderSource:v}},o=g=>{if(!g||g.length!==1)throw new Error("Pad requires 1 input");if(g[0].type!=="float32"&&g[0].type!=="float64")throw new Error("Invalid input type.")},t=g=>{if(!g||g.length!==2&&g.length!==3)throw new Error("Pad requires 2 or 3 inputs");if(g[1].type!=="int32")throw new Error("Invalid input type.");if(g.length>=3&&g[2].type==="string")throw new Error("Invalid input type.")},e=(g,m,b)=>{const y=(0,f.getGlsl)(g.session.backend.glContext.version),[w,v]=g.calculateTextureWidthAndHeight(m.dims,a.TextureType.unpacked),S=l.ShapeUtil.computeStrides(m.dims);switch(b.mode){case"constant":return r(y,m.dims,S,w,v,b.pads,b.value);case"reflect":return i(y,m.dims,S,w,v,b.pads);case"edge":return d(y,m.dims,S,w,v,b.pads);default:throw new Error("Invalid mode")}},r=(g,m,b,y,w,v,S)=>{const A=m.length;let O="";for(let x=A-1;x>=0;--x)O+=` - k = m[${x}] - ${v[x]}; - if (k < 0) return constant; - if (k >= ${m[x]}) return constant; - offset += k * ${b[x]}; - `;return` - float padA(int m[${A}]) { - const float constant = float(${S}); - int offset = 0; - int k = 0; - ${O} - vec2 coords = offsetToCoords(offset, ${y}, ${w}); - float value = getColorAsFloat(${g.texture2D}(A, coords)); - return value; - } - `},i=(g,m,b,y,w,v)=>{const S=m.length;let A="";for(let O=S-1;O>=0;--O)A+=` - k = m[${O}] - ${v[O]}; - if (k < 0) { k = -k; } - { - const int _2n_1 = ${2*(m[O]-1)}; - k = int( mod( float(k), float(_2n_1) ) ) ; - if(k >= ${m[O]}) { k = _2n_1 - k; } - } - offset += k * ${b[O]}; - `;return` - float padA(int m[${S}]) { - int offset = 0; - int k = 0; - ${A} - vec2 coords = offsetToCoords(offset, ${y}, ${w}); - float value = getColorAsFloat(${g.texture2D}(A, coords)); - return value; - } - `},d=(g,m,b,y,w,v)=>{const S=m.length;let A="";for(let O=S-1;O>=0;--O)A+=` - k = m[${O}] - ${v[O]}; - if (k < 0) k = 0; - if (k >= ${m[O]}) k = ${m[O]-1}; - offset += k * ${b[O]}; - `;return` - float padA(int m[${S}]) { - int offset = 0; - int k = 0; - ${A} - vec2 coords = offsetToCoords(offset, ${y}, ${w}); - float value = getColorAsFloat(${g.texture2D}(A, coords)); - return value; - } - `}},2143:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.globalMaxPool=n.parseMaxPoolAttributes=n.maxPool=n.parseGlobalAveragePoolAttributes=n.globalAveragePool=n.parseAveragePoolAttributes=n.averagePool=void 0;const c=s(246),l=s(2517),f=s(2039);n.averagePool=(d,g,m)=>{t(g);const b={name:"AveragePool",inputNames:["X"],inputTypes:[f.TextureType.unpacked],cacheHint:m.cacheKey};return[d.run(Object.assign(Object.assign({},b),{get:()=>a(g,b,!1,m)}),g)]},n.parseAveragePoolAttributes=d=>{const g=d.attributes.getString("auto_pad","NOTSET"),m=d.attributes.getInt("ceil_mode",0),b=d.attributes.getInt("count_include_pad",0)!==0,y=d.attributes.getInts("kernel_shape"),w=d.attributes.getInts("strides",[]),v=d.attributes.getInts("pads",[]);if(m!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return(0,c.createAttributeWithCacheKey)({autoPad:g,ceilMode:m,countIncludePad:b,kernelShape:y,strides:w,pads:v})};const a=(d,g,m,b)=>{const[y,w]=p(d,b,m),v=l.ShapeUtil.size(y.kernelShape);let S="";y.countIncludePad?S+=`value /= float(${v});`:S+=`value /= float(${v} - pad);`;const A=` - ${e(d[0].dims,y,"value += _X(x);",S,"0.0")} - `;return Object.assign(Object.assign({},g),{output:{dims:w,type:d[0].type,textureType:f.TextureType.unpacked},shaderSource:A})};n.globalAveragePool=(d,g,m)=>{t(g);const b={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[f.TextureType.unpacked],cacheHint:`${m.countIncludePad}`};return[d.run(Object.assign(Object.assign({},b),{get:()=>a(g,b,!0,m)}),g)]},n.parseGlobalAveragePoolAttributes=d=>{const g=d.attributes.getInt("count_include_pad",0)!==0;return(0,c.createAttributeWithCacheKey)({autoPad:"",ceilMode:0,countIncludePad:g,kernelShape:[],strides:[],pads:[]})},n.maxPool=(d,g,m)=>{t(g);const b={name:"MaxPool",inputNames:["X"],inputTypes:[f.TextureType.unpacked],cacheHint:m.cacheKey};return[d.run(Object.assign(Object.assign({},b),{get:()=>h(g,b,!1,m)}),g)]},n.parseMaxPoolAttributes=d=>{const g=d.attributes.getString("auto_pad","NOTSET"),m=d.attributes.getInt("ceil_mode",0),b=d.attributes.getInts("kernel_shape"),y=d.attributes.getInts("strides",[]),w=d.attributes.getInts("pads",[]),v=d.attributes.getInt("storage_order",0),S=d.attributes.getInts("dilations",[]);if(v!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(m!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return(0,c.createAttributeWithCacheKey)({autoPad:g,ceilMode:m,countIncludePad:!1,kernelShape:b,strides:y,pads:w,storageOrder:v,dilations:S})};const h=(d,g,m,b)=>{const[y,w]=p(d,b,m),v=` - ${e(d[0].dims,y,` - value = max(_X(x), value); - `,"","-1e5")} - `;return Object.assign(Object.assign({},g),{output:{dims:w,type:d[0].type,textureType:f.TextureType.unpacked},shaderSource:v})},p=(d,g,m)=>{const b=d[0].dims.slice(),y=Object.hasOwnProperty.call(g,"dilations"),w=g.kernelShape.slice(),v=g.strides.slice(),S=y?g.dilations.slice():[],A=g.pads.slice();l.PoolConvUtil.adjustPoolAttributes(m,b,w,v,S,A);const O=l.PoolConvUtil.computePoolOutputShape(m,b,v,S,w,A,g.autoPad),x=Object.assign({},g);return y?Object.assign(x,{kernelShape:w,strides:v,pads:A,dilations:S,cacheKey:g.cacheKey}):Object.assign(x,{kernelShape:w,strides:v,pads:A,cacheKey:g.cacheKey}),[x,O]},u={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},o={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[f.TextureType.unpacked]};n.globalMaxPool=(d,g)=>(t(g),[d.run(Object.assign(Object.assign({},o),{get:()=>h(g,o,!0,u)}),g)]);const t=d=>{if(!d||d.length!==1)throw new Error("Pool ops requires 1 input.");if(d[0].type!=="float32"&&d[0].type!=="float64")throw new Error("Invalid input type.")},e=(d,g,m,b,y)=>{const w=d.length;if(g.kernelShape.length<=2){const v=g.kernelShape[g.kernelShape.length-1],S=g.strides[g.strides.length-1],A=g.pads[g.pads.length/2-1],O=g.pads[g.pads.length-1],x=d[w-1];let I="",$="",z="";if(I=A+O!==0?` - for (int i = 0; i < ${v}; i++) { - x[${w} - 1] = indices[${w} - 1] * ${S} - ${A} + i; - if (x[${w} - 1] < 0 || x[${w} - 1] >= ${x}) { - pad++; - continue; - } - ${m} - }`:` - for (int i = 0; i < ${v}; i++) { - x[${w} - 1] = indices[${w} - 1] * ${S} - ${A} + i; - ${m} - }`,g.kernelShape.length===2){const L=g.kernelShape[g.kernelShape.length-2],N=g.strides[g.strides.length-2],H=g.pads[g.pads.length/2-2],M=g.pads[g.pads.length-2],j=d[w-2];$=H+M!==0?` - for (int j = 0; j < ${L}; j++) { - x[${w} - 2] = indices[${w} - 2] * ${N} - ${H} + j; - if (x[${w} - 2] < 0 || x[${w} - 2] >= ${j}) { - pad+= ${v}; - continue; - } - `:` - for (int j = 0; j < ${L}; j++) { - x[${w} - 2] = indices[${w} - 2] * ${N} - ${H} + j; - `,z=` - } - `}return` - float process(int indices[${w}]) { - int x[${w}]; - copyVec(indices, x); - - float value = ${y}; - int pad = 0; - ${$} - ${I} - ${z} - ${b} - return value; - } - `}{const v=l.ShapeUtil.size(g.kernelShape),S=l.ShapeUtil.computeStrides(g.kernelShape),A=S.length,O=g.pads.length,x=i(A),I=r(d,"inputDims"),$=r(g.pads,"pads"),z=r(S,"kernelStrides"),L=r(g.strides,"strides");let N="";return N=g.pads.reduce((H,M)=>H+M)?` - if (x[j] >= inputDims[j] || x[j] < 0) { - pad++; - isPad = true; - break; - } - } - if (!isPad) { - ${m} - }`:` - } - ${m} - `,` - ${x} - float process(int indices[${w}]) { - int x[${w}]; - copyVec(indices, x); - int offset[${A}]; - int pads[${O}]; - int inputDims[${w}]; - int kernelStrides[${A}]; - int strides[${A}]; - ${$} - ${I} - ${L} - ${z} - - float value = ${y}; - int pad = 0; - bool isPad = false; - for (int i = 0; i < ${v}; i++) { - offsetToIndices(i, kernelStrides, offset); - isPad = false; - for (int j = ${w} - ${A}; j < ${w}; j++) { - x[j] = indices[j] * strides[j - ${w} + ${A}] - + offset[j - ${w} + ${A}] - pads[j - 2]; - ${N} - } - ${b} - - return value; - } - `}},r=(d,g)=>{let m="";for(let b=0;b` - void offsetToIndices(int offset, int[${d}] strides, out int[${d}] indices) { - if (${d} == 0) { - return; - } - for (int i = 0; i < ${d} - 1; ++i) { - indices[i] = offset / strides[i]; - offset -= indices[i] * strides[i]; - } - indices[${d} - 1] = offset; - }`},4939:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.reduceLogSumSquare=n.reduceLogSum=n.reduceProd=n.reduceMin=n.reduceMax=n.reduceMean=n.reduceSum=n.parseReduceAttributes=void 0;const c=s(246),l=s(782),f=s(2517),a=s(2039),h=(o,t,e,r,i)=>{u(t);const d={name:r,inputNames:["A"],inputTypes:[a.TextureType.unpacked]};return[o.run(Object.assign(Object.assign({},d),{cacheHint:e.cacheKey,get:()=>p(o,t,e,r,i,d)}),t)]};n.parseReduceAttributes=o=>{const t=o.attributes.getInts("axes",[]),e=o.attributes.getInt("keepdims",1)===1;return(0,c.createAttributeWithCacheKey)({axes:t,keepDims:e})};const p=(o,t,e,r,i,d)=>{const g=[],m=t[0].dims.length||1,b=[],y=f.ShapeUtil.normalizeAxes(e.axes,t[0].dims.length),w=i(t,y);let v=w[1];for(let A=0;A=0||y.length===0?(e.keepDims&&g.push(1),v=` - for(int j${A} = 0; j${A} < ${t[0].dims[A]}; j${A}++) { - inputIdx[${A}] = j${A}; - ${v} - }`):(b.push(`inputIdx[${A}] = outputIdx[${g.length}];`),g.push(t[0].dims[A]));const S=` - float process(int outputIdx[${g.length||1}]) { - float value; // final result - int inputIdx[${m}]; // addressing input data - ${b.join(` -`)} - ${w[0]} // init ops for reduce max/min - ${v} - ${w[2]} // final computation for reduce mean - return value; - }`;return Object.assign(Object.assign({},d),{output:{dims:g,type:t[0].type,textureType:a.TextureType.unpacked},shaderSource:S})},u=o=>{if(!o||o.length!==1)throw new Error("Reduce op requires 1 input.");if(l.NUMBER_TYPES.indexOf(o[0].type)===-1)throw new Error("Invalid input type.")};n.reduceSum=(o,t,e)=>h(o,t,e,"ReduceSum",()=>["value = 0.0;","value += _A(inputIdx);",""]),n.reduceMean=(o,t,e)=>h(o,t,e,"ReduceMean",(r,i)=>{let d=1;for(let g=0;g=0||i.length===0)&&(d*=r[0].dims[g]);return["value = 0.0;","value += _A(inputIdx);",`value /= ${d}.;`]}),n.reduceMax=(o,t,e)=>h(o,t,e,"ReduceMax",(r,i)=>{const d=[];for(let g=0;g=0||i.length===0)&&d.push(`inputIdx[${g}] = 0;`);return[`${d.join(` -`)} -value = _A(inputIdx);`,"value = max(value, _A(inputIdx));",""]}),n.reduceMin=(o,t,e)=>h(o,t,e,"ReduceMin",(r,i)=>{const d=[];for(let g=0;g=0||i.length===0)&&d.push(`inputIdx[${g}] = 0;`);return[`${d.join(` -`)} -value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),n.reduceProd=(o,t,e)=>h(o,t,e,"ReduceProd",()=>["value = 1.0;","value *= _A(inputIdx);",""]),n.reduceLogSum=(o,t,e)=>h(o,t,e,"ReduceLogSum",()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"]),n.reduceLogSumSquare=(o,t,e)=>h(o,t,e,"ReduceLogSumSquare",()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""])},7019:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.isReshapeCheap=n.processDims3D=n.createPackedReshape3DProgramInfoLoader=void 0;const c=s(2517),l=s(5060),f=s(2039),a=s(2827);n.createPackedReshape3DProgramInfoLoader=(h,p,u)=>{const o=(t=>({name:"Reshape (packed)",inputTypes:[f.TextureType.packed],inputNames:["A"],cacheHint:`${t}`}))(u);return Object.assign(Object.assign({},o),{get:()=>((t,e,r,i)=>{const d=e.dims,g=i;let m="";for(let w=0;w<4;w++){let v="";switch(w){case 0:v="outputCoords = rc;";break;case 1:v="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:v="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:v="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw new Error}m+=` - ${v} - ${w>0?"if(outputCoords.y < rows && outputCoords.z < cols){":""} - int flattenedIndex = getFlattenedIndex(outputCoords); - - ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex); - vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z)); - - result[${w}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims); - - ${w>0?"}":""} - `}const b=(0,l.getGlsl)(t.session.backend.glContext.version),y=` - ${function(w){const v=c.ShapeUtil.computeStrides(w),S=["b","r","c"],A="index";return` - ivec3 inputCoordsFromReshapedOutCoords(int index) { - ${v.map((O,x)=>`int ${S[x]} = ${A} / ${O}; ${x===v.length-1?`int ${S[x+1]} = ${A} - ${S[x]} * ${O}`:`index -= ${S[x]} * ${O}`};`).join("")} - return ivec3(b, r, c); - } - `}(d)} - ${function(w){const v=c.ShapeUtil.computeStrides(w);return` - int getFlattenedIndex(ivec3 coords) { - // reverse y, z order - return coords.x * ${v[0]} + coords.z * ${v[1]} + coords.y; - } -`}(g)} - ${(0,a.unpackFromChannel)()} - - void main() { - ivec3 rc = getOutputCoords(); - - vec4 result = vec4(0.0); - - ivec3 outputCoords; - int rows = ${g[2]}; - int cols = ${g[1]}; - - ${m} - ${b.output} = result; - } - `;return Object.assign(Object.assign({},r),{output:{dims:g,type:e.type,textureType:f.TextureType.packed},shaderSource:y,hasMain:!0})})(h,p,o,u)})},n.processDims3D=function(h){if(h.length===0)return[1,1,1];let p=1;for(let u=0;u1?h[h.length-2]:1,h[h.length-1]]},n.isReshapeCheap=function(h,p){let u=!1;return u=h.length===0||p.length===0||(h.length<2||p.length<2?h[h.length-1]===p[p.length-1]:h[h.length-1]===p[p.length-1]&&h[h.length-2]===p[p.length-2]),u}},718:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.reshape=void 0;const c=s(2517);n.reshape=(l,f)=>{const a=c.ShapeUtil.calculateReshapedDims(f[0].dims,f[1].integerData);return l.session.pack?[l.reshapePacked(f[0],a)]:[l.reshapeUnpacked(f[0],a)]}},2268:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseResizeAttributesV11=n.parseResizeAttributesV10=n.resize=void 0;const c=s(5060),l=s(2039),f=s(9390),a=s(2827),h=s(9793),p={name:"Resize",inputNames:["A"],inputTypes:[l.TextureType.packed]};n.resize=(r,i,d)=>((0,h.validateInputs)(i,d),[r.run(Object.assign(Object.assign({},p),{cacheHint:d.cacheKey,get:()=>u(r,i,d)}),i)]),n.parseResizeAttributesV10=r=>(0,h.parseUpsampleAttributes)(r,10),n.parseResizeAttributesV11=r=>(0,h.parseUpsampleAttributes)(r,11);const u=(r,i,d)=>{const g=(0,c.getGlsl)(r.session.backend.glContext.version),[m,b]=o(i,d);if(m.every(N=>N===1)&&d.coordinateTransformMode!=="tf_crop_and_resize")return Object.assign(Object.assign({},p),{output:{dims:b,type:i[0].type,textureType:l.TextureType.packed},hasMain:!0,shaderSource:`void main() { - vec4 v = ${g.texture2D}(X, TexCoords); - ${g.output} = v; - }`});const y=b.length;if(y<2)throw new Error(`output dimension should be at least 2, but got ${y}`);const w=b[y-2],v=b[y-1],S=i[0].dims;if(y!==S.length)throw new Error(`output dimension should match input ${S.length}, but got ${y}`);const A=S[y-2],O=S[y-1],x=m[y-2],I=m[y-1];let $="";if(d.mode!=="linear")throw new Error(`resize (packed) does not support mode: '${d.mode}'`);switch(d.coordinateTransformMode){case"asymmetric":$=` - vec4 getSourceFracIndex(ivec4 coords) { - return vec4(coords) / scaleWHWH; - } - `;break;case"half_pixel":$=` - vec4 getSourceFracIndex(ivec4 coords) { - return (vec4(coords) + 0.5) / scaleWHWH - 0.5; - } - `;break;case"pytorch_half_pixel":$=` - vec4 getSourceFracIndex(ivec4 coords) { - vec4 fcoords = vec4(coords); - return vec4( - ${v}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0, - ${w}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0, - ${v}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0, - ${w}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0 - ); - } - `;break;case"align_corners":$=` - vec4 getSourceFracIndex(ivec4 coords) { - vec4 resized = vec4(${v}.0 - 1.0, ${w}.0 - 1.0, ${v}.0 - 1.0, - ${w}.0 - 1.0); - vec4 original = vec4(${O}.0 - 1.0, ${A}.0 - 1.0, ${O}.0 - 1.0, - ${A}.0 - 1.0); - vec4 new_scale = original / resized; - return vec4(coords) * new_scale; - } - `;break;default:throw new Error(`resize (packed) does not support coordinateTransformMode: '${d.coordinateTransformMode}'`)}const z=(0,f.getCoordsDataType)(y),L=` - const vec2 inputWH = vec2(${A}.0, ${O}.0); - const vec4 scaleWHWH = vec4(float(${x}), float(${I}), float(${x}), float(${I})); - ${(0,a.unpackFromChannel)()} - ${$} - float getAValue(int x10, int r, int c, int d) { - return getChannel(getA(x10, r, c, d), vec2(c, d)); - } - void main() { - ${z} rc = getOutputCoords(); - - int batch = rc[0]; - int depth = rc[1]; - - // retrieve the 4 coordinates that is used in the 4 packed output values. - ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1); - - // calculate the source index in fraction - vec4 sourceFrac = getSourceFracIndex(coords); - - // get the lower and upper bound of the 4 values that will be packed into one texel. - ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy))); - ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw))); - ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy))); - ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw))); - - bool hasNextRow = rc.w < ${w-1}; - bool hasNextCol = rc.z < ${v-1}; - - // pack x00, x01, x10, x11's top-left corner into one vec4 structure - vec4 topLeft = vec4( - getAValue(batch, depth, x00.x, x00.y), - hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0, - hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0, - (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0); - - // pack x00, x01, x10, x11's top-right corner into one vec4 structure - vec4 topRight = vec4( - getAValue(batch, depth, x00.x, x00.w), - hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0, - hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0, - (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0); - - // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure - vec4 bottomLeft = vec4( - getAValue(batch, depth, x00.z, x00.y), - hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0, - hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0, - (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0); - - // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure - vec4 bottomRight = vec4( - getAValue(batch, depth, x00.z, x00.w), - hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0, - hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0, - (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0); - - // calculate the interpolation fraction on u and v direction - vec4 frac = vec4(sourceFrac) - floor(sourceFrac); - vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0)); - - vec4 top = mix(topLeft, topRight, clampFrac.ywyw); - vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw); - vec4 newValue = mix(top, bottom, clampFrac.xxzz); - - ${g.output} = vec4(newValue); - } - `;return Object.assign(Object.assign({},p),{output:{dims:b,type:i[0].type,textureType:l.TextureType.packed},hasMain:!0,shaderSource:L})},o=(r,i)=>{const d=r[0].dims;let g,m=i.scales;if(m.length===0){const y=r[i.scalesInputIdx];if(y&&y.size!==0){if(r[i.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");m=t(y,i.mode,i.isResize)}else{const w=r[i.sizesInputIdx];if(!w||w.size===0)throw new Error("Either scales or sizes MUST be provided as input.");g=Array.from(w.integerData),m=e(g,d,i.mode,i.isResize)}}else if(r[i.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");const b=g||d.map((y,w)=>Math.floor(y*m[w]));return[m,b]},t=(r,i,d)=>{const g=Array.from(r.floatData);return(0,h.scalesValidation)(g,i,d),g},e=(r,i,d,g)=>{const m=i.length,b=new Array(m);for(let y=0,w=m;y{Object.defineProperty(n,"__esModule",{value:!0}),n.shape=void 0;const c=s(9162);n.shape=(f,a)=>(l(a),[new c.Tensor([a[0].dims.length],"int32",void 0,void 0,new Int32Array(a[0].dims))]);const l=f=>{if(!f||f.length!==1)throw new Error("Shape requires 1 input.")}},2278:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.sliceV10=n.parseSliceAttributes=n.slice=void 0;const c=s(246),l=s(782),f=s(2517),a=s(2039),h={name:"Slice",inputNames:["A"],inputTypes:[a.TextureType.unpacked]};n.slice=(e,r,i)=>(u(r),[e.run(Object.assign(Object.assign({},h),{cacheHint:i.cacheKey,get:()=>p(e,r[0],i)}),r)]),n.parseSliceAttributes=e=>{const r=e.attributes.getInts("starts"),i=e.attributes.getInts("ends"),d=e.attributes.getInts("axes",[]);return(0,c.createAttributeWithCacheKey)({starts:r,ends:i,axes:d})};const p=(e,r,i)=>{const d=i.axes.length===0?r.dims.slice(0).map((S,A)=>A):i.axes,g=f.ShapeUtil.normalizeAxes(d,r.dims.length),m=i.starts.map((S,A)=>S>r.dims[g[A]]-1?r.dims[g[A]]:f.ShapeUtil.normalizeAxis(S,r.dims[g[A]])),b=i.ends.map((S,A)=>S>r.dims[g[A]]-1?r.dims[g[A]]:f.ShapeUtil.normalizeAxis(S,r.dims[g[A]])),y=r.dims.slice(),w=[];for(let S=0;S0&&w.push(`outputIdx[${g[S]}] += ${m[S]};`);const v=` - float process(int outputIdx[${y.length}]) { - ${w.join(` - `)} - return _A(outputIdx); - }`;return Object.assign(Object.assign({},h),{output:{dims:y,type:r.type,textureType:a.TextureType.unpacked},shaderSource:v})},u=e=>{if(!e||e.length!==1)throw new Error("Slice requires 1 input.");if(l.NUMBER_TYPES.indexOf(e[0].type)===-1)throw new Error("Invalid input type.")};n.sliceV10=(e,r)=>{t(r);const i=o(e,r);return[e.run(Object.assign(Object.assign({},h),{cacheHint:i.cacheKey,get:()=>p(e,r[0],i)}),[r[0]])]};const o=(e,r)=>{if(!e.session.isInitializer(r[1].dataId)||!e.session.isInitializer(r[2].dataId)||r.length>=4&&!e.session.isInitializer(r[3].dataId)||r.length>=5&&!e.session.isInitializer(r[4].dataId))throw new Error("dynamic slice attributes are not allowed");if(r.length>=5&&r[4].integerData.some(m=>m!==1))throw new Error("currently non-1 steps is not supported for Slice");const i=Array.from(r[1].integerData),d=Array.from(r[2].integerData),g=r.length>=4?Array.from(r[3].integerData):[];return{starts:i,ends:d,axes:g,cacheKey:`${g};${i};${d}`}},t=e=>{if(!e||e.length<3||e.length>5)throw new Error("Invalid input number.");if(e[1].type!=="int32"||e[1].dims.length!==1)throw new Error("Invalid input type.");if(e[2].type!=="int32"||e[2].dims.length!==1)throw new Error("Invalid input type.");if(e.length>=4&&(e[3].type!=="int32"||e[3].dims.length!==1))throw new Error("Invalid input type.");if(e.length>=5&&(e[4].type!=="int32"||e[4].dims.length!==1))throw new Error("Invalid input type.")}},5524:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.softmaxV13=n.parseSoftmaxAttributesV13=n.parseSoftmaxAttributes=n.softmax=void 0;const c=s(246),l=s(2517),f=s(5060),a=s(2039),h=s(3738),p={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[a.TextureType.unpacked]},u={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[a.TextureType.unpacked,a.TextureType.unpacked]},o={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[a.TextureType.unpacked,a.TextureType.unpacked,a.TextureType.unpacked]};n.softmax=(g,m,b)=>{d(m);const y=m[0].dims.slice(),w=l.ShapeUtil.normalizeAxis(b.axis,y.length),v=l.ShapeUtil.sizeToDimension(y,w),S=l.ShapeUtil.sizeFromDimension(y,w);return t(g,m,b,v,S)},n.parseSoftmaxAttributes=g=>(0,c.createAttributeWithCacheKey)({axis:g.attributes.getInt("axis",1)}),n.parseSoftmaxAttributesV13=g=>(0,c.createAttributeWithCacheKey)({axis:g.attributes.getInt("axis",-1)}),n.softmaxV13=(g,m,b)=>{d(m);const y=m[0].dims.slice(),w=l.ShapeUtil.normalizeAxis(b.axis,y.length),v=y.length,S=w!==v-1,A=[];let O,x=[],I=[];S&&(x=Array.from({length:v}).map((N,H)=>H),x[w]=v-1,x[v-1]=w,x.map(N=>A.push(y[N])),O=(0,c.createAttributeWithCacheKey)({perm:x}),I=(0,h.transpose)(g,m,O));const $=S?l.ShapeUtil.sizeToDimension(A,v-1):l.ShapeUtil.sizeToDimension(y,v-1),z=S?l.ShapeUtil.sizeFromDimension(A,v-1):l.ShapeUtil.sizeFromDimension(y,v-1),L=t(g,S?I:m,b,$,z);return S?(0,h.transpose)(g,L,O):L};const t=(g,m,b,y,w)=>{const v=e(g,m[0],y,w,[y]),S=g.run(Object.assign(Object.assign({},p),{cacheHint:b.cacheKey,get:()=>v}),m),A=r(g,m[0],y,w,v.output.dims,[y]),O=g.run(Object.assign(Object.assign({},u),{cacheHint:b.cacheKey,get:()=>A}),[m[0],S]),x=i(g,m[0],y,w,v.output.dims,A.output.dims);return[g.run(Object.assign(Object.assign({},o),{cacheHint:b.cacheKey,get:()=>x}),[m[0],S,O])]},e=(g,m,b,y,w)=>{const[v,S]=g.calculateTextureWidthAndHeight(m.dims,a.TextureType.unpacked),A=w.length;if(b<1||y<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(w.length!==1)throw new Error("Dimensionality of the output should be 1");if(w[0]!==b)throw new Error("Shape of the output should be equal to logical row count");const O=(0,f.getGlsl)(g.session.backend.glContext.version),x=` - float process(int[${A}] indices) { - int logical_row_start_offset = indices[0] * ${y}; - - float max = getColorAsFloat(${O.texture2D}(A, offsetToCoords(logical_row_start_offset, ${v}, - ${S} ))); - for(int i=1; i<${y}; ++i) - { - float current = getColorAsFloat(${O.texture2D}(A, offsetToCoords(logical_row_start_offset + i, - ${v}, ${S}))); - if(current > max) - max = current; - } - - return max; - }`;return Object.assign(Object.assign({},p),{output:{dims:w,type:m.type,textureType:a.TextureType.unpacked},shaderSource:x})},r=(g,m,b,y,w,v)=>{const[S,A]=g.calculateTextureWidthAndHeight(m.dims,a.TextureType.unpacked),O=v.length;if(b<1||y<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(v.length!==1)throw new Error("Dimensionality of the output should be 1");if(v[0]!==b)throw new Error("Shape of the output should be equal to logical row count");if(w.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(w[0]!==b)throw new Error("Shape of the intermediate results should be equal to logical row count");const x=` - float process(int[${O}] indices) { - int logical_row_start_offset = indices[0] * ${y}; - - float norm_factor = 0.0; - float max = _Max(indices); - for(int i=0; i<${y}; ++i) - { - norm_factor += exp(getColorAsFloat(${(0,f.getGlsl)(g.session.backend.glContext.version).texture2D}(A, offsetToCoords(logical_row_start_offset + i, - ${S}, ${A}))) - max); - } - - return norm_factor; - }`;return Object.assign(Object.assign({},u),{output:{dims:v,type:m.type,textureType:a.TextureType.unpacked},shaderSource:x})},i=(g,m,b,y,w,v)=>{const[S,A]=g.calculateTextureWidthAndHeight(m.dims,a.TextureType.unpacked),O=m.dims.length;if(b<1||y<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(w.length!==1||v.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(w[0]!==b||v[0]!==b)throw new Error("Shape of the intermediate results should be equal to logical row count");const x=` - float process(int[${O}] indices) { - - // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords) - int offset = coordsToOffset(TexCoords, ${S}, ${A}); - - //determine the logical row for this index - int logical_row_index[1]; - logical_row_index[0] = offset / ${y}; - - float norm_factor = _Norm(logical_row_index); - - // avoid possible division by 0 - // if norm_facor is 0, all elements are zero - // if so, return 0 - if(norm_factor == 0.0) - return 0.0; - - return exp(_A(indices) - _Max(logical_row_index)) / norm_factor; - }`;return Object.assign(Object.assign({},o),{output:{dims:m.dims,type:m.type,textureType:a.TextureType.unpacked},shaderSource:x})},d=g=>{if(!g||g.length!==1)throw new Error("Softmax requires 1 input.");if(g[0].type!=="float32"&&g[0].type!=="float64")throw new Error("Invalid input type")}},5975:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseSplitAttributes=n.split=void 0;const c=s(246),l=s(2517),f=s(2039),a={name:"Split",inputNames:["A"],inputTypes:[f.TextureType.unpacked]};n.split=(o,t,e)=>{u(t);const r=l.ShapeUtil.normalizeAxis(e.axis,t[0].dims.length),i=h(o,t,r,e),d=[];for(let g=0;gp(o,t[0],e,r,g)}),t));return d},n.parseSplitAttributes=o=>{const t=o.attributes.getInt("axis",0),e=o.attributes.getInts("split",[]),r=o.outputs.length;return(0,c.createAttributeWithCacheKey)({axis:t,split:e,numOutputs:r})};const h=(o,t,e,r)=>{const[,i]=l.SplitUtil.splitShape(t[0].dims,e,r.split,r.numOutputs);return i.length},p=(o,t,e,r,i)=>{const[d,g]=l.SplitUtil.splitShape(t.dims,r,e.split,e.numOutputs),m=g[i],b=d[i],y=` - float process(int indices[${b.length}]) { - indices[${r}] += ${m}; - return _A(indices); - } - `;return Object.assign(Object.assign({},a),{cacheHint:`${e.cacheKey}:${i}`,output:{dims:b,type:t.type,textureType:f.TextureType.unpacked},shaderSource:y})},u=o=>{if(!o||o.length!==1)throw new Error("Split requires one input.");if(o[0].type!=="int8"&&o[0].type!=="uint8"&&o[0].type!=="int16"&&o[0].type!=="uint16"&&o[0].type!=="int32"&&o[0].type!=="uint32"&&o[0].type!=="float32"&&o[0].type!=="float64"&&o[0].type!=="bool")throw new Error("Invalid input type.")}},3933:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseSqueezeAttributes=n.squeezeV13=n.squeeze=void 0;const c=s(2517);n.squeeze=(a,h,p)=>{l(h);const u=c.ShapeUtil.squeezeShape(h[0].dims,p);return[a.reshapeUnpacked(h[0],u)]},n.squeezeV13=(a,h)=>(f(h),(0,n.squeeze)(a,[h[0]],Array.from(h[1].integerData))),n.parseSqueezeAttributes=a=>a.attributes.getInts("axes");const l=a=>{if(!a||a.length!==1)throw new Error("Squeeze requires 1 input.");if(a[0].type==="string")throw new Error("invalid input tensor types.")},f=a=>{if(!a||a.length!==2)throw new Error("Squeeze requires 2 inputs.");if(a[1].type!=="int32")throw new Error("Invalid input type.")}},6558:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.sum=void 0;const c=s(5060),l=s(2039);n.sum=(h,p)=>{a(p);const u={name:"Sum",inputNames:p.map((o,t)=>`X${t}`),inputTypes:new Array(p.length).fill(l.TextureType.unpacked)};return[h.run(Object.assign(Object.assign({},u),{get:()=>f(h,p,u)}),p)]};const f=(h,p,u)=>{const o=(0,c.getGlsl)(h.session.backend.glContext.version),t=p[0].dims.slice(),e=` - void main() { - vec4 result = ${p.map((r,i)=>`${o.texture2D}(X${i},TexCoords)`).join(" + ")}; - ${o.output} = result; - } - `;return Object.assign(Object.assign({},u),{output:{dims:t,type:p[0].type,textureType:l.TextureType.unpacked},hasMain:!0,shaderSource:e})},a=h=>{if(!h||h.length===0)throw new Error("Sum requires inputs.");const p=h[0].dims.length;for(let u=1;u{Object.defineProperty(n,"__esModule",{value:!0}),n.tile=void 0;const c=s(782),l=s(2039);n.tile=(h,p)=>{a(p);const u={name:"Tile",inputNames:["A"],inputTypes:[l.TextureType.unpacked]};return[h.run(Object.assign(Object.assign({},u),{get:()=>f(h,p,u)}),p)]};const f=(h,p,u)=>{const o=p[0].dims.slice(),t=new Array(o.length),e=[];for(let d=0;d{if(!h||h.length!==2)throw new Error("Tile requires 2 input.");if(h[1].dims.length!==1)throw new Error("The second input shape must 1 dimension.");if(h[1].dims[0]!==h[0].dims.length)throw new Error("Invalid input shape.");if(c.NUMBER_TYPES.indexOf(h[0].type)===-1)throw new Error("Invalid input type.");if(h[1].type!=="int32"&&h[1].type!=="int16")throw new Error("Invalid repeat type.")}},3738:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseTransposeAttributes=n.transpose=void 0;const c=s(246),l=s(2517),f=s(2039),a={name:"Transpose",inputNames:["A"],inputTypes:[f.TextureType.unpacked]};n.transpose=(e,r,i)=>(t(r),[e.run(Object.assign(Object.assign({},a),{cacheHint:i.cacheKey,get:()=>h(e,r[0],i.perm)}),r)]),n.parseTransposeAttributes=e=>(0,c.createAttributeWithCacheKey)({perm:e.attributes.getInts("perm",[])});const h=(e,r,i)=>{const d=r.dims;i=p(d,i);const g=u(d,i),m=d.length,b=` - ${o("perm",i,m)} - float process(int indices[${m}]) { - int a[${m}]; - perm(a, indices); - return _A(a); - }`;return Object.assign(Object.assign({},a),{output:{dims:g,type:r.type,textureType:f.TextureType.unpacked},shaderSource:b})},p=(e,r)=>(r&&r.length!==e.length&&(r=[...e.keys()].reverse()),r),u=(e,r)=>(r=p(e,r),l.ShapeUtil.sortBasedOnPerm(e,r)),o=(e,r,i)=>{const d=[];d.push(`void ${e}(out int a[${i}], int src[${i}]) {`);for(let g=0;g{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(e[0].type!=="float32"&&e[0].type!=="float64")throw new Error("input should be float tensor")}},8710:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.encodeAsUint8=void 0;const c=s(5060),l=s(2039);n.encodeAsUint8=(f,a)=>{const h=a.shape,p=(0,c.getGlsl)(f.session.backend.glContext.version),u=` - const float FLOAT_MAX = 1.70141184e38; - const float FLOAT_MIN = 1.17549435e-38; - - bool isNaN(float val) { - return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true; - } - - highp vec4 encodeAsUint8(highp float v) { - if (isNaN(v)) { - return vec4(255, 255, 255, 255); - } - - highp float av = abs(v); - - if(av < FLOAT_MIN) { - return vec4(0.0, 0.0, 0.0, 0.0); - } else if(v > FLOAT_MAX) { - return vec4(0.0, 0.0, 128.0, 127.0) / 255.0; - } else if(v < -FLOAT_MAX) { - return vec4(0.0, 0.0, 128.0, 255.0) / 255.0; - } - - highp vec4 c = vec4(0,0,0,0); - - highp float e = floor(log2(av)); - highp float m = exp2(fract(log2(av))) - 1.0; - - c[2] = floor(128.0 * m); - m -= c[2] / 128.0; - c[1] = floor(32768.0 * m); - m -= c[1] / 32768.0; - c[0] = floor(8388608.0 * m); - - highp float ebias = e + 127.0; - c[3] = floor(ebias / 2.0); - ebias -= c[3] * 2.0; - c[2] += floor(ebias) * 128.0; - - c[3] += 128.0 * step(0.0, -v); - - return c / 255.0; - } - - void main() { - float value = ${p.texture2D}(X,TexCoords).r; - ${p.output} = encodeAsUint8(value); - }`,o={name:"Uint8Encode",inputTypes:[l.TextureType.unpacked],inputNames:["X"],output:{dims:h,type:a.tensor.type,textureType:l.TextureType.downloadUint8AsFloat},shaderSource:u,hasMain:!0};return f.executeProgram(o,[a.tensor])}},4909:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.tanh=n.tan=n.sqrt=n.sin=n.sigmoid=n.relu=n.not=n.neg=n.log=n.parseLeakyReluAttributes=n.leakyRelu=n.identity=n.floor=n.exp=n.parseEluAttributes=n.elu=n.cos=n.ceil=n.clipV11=n.parseClipAttributes=n.clip=n.atan=n.asin=n.acos=n.abs=n.glslTanh=n.glslTan=n.glslSqrt=n.glslSigmoid=n.glslRelu=n.glslSin=n.glslNot=n.glslNeg=n.glslLog=n.glslLeakyRelu=n.glslIdentity=n.glslClip=n.glslFloor=n.glslExp=n.glslElu=n.glslCos=n.glslCeil=n.glslAtan=n.glslAsin=n.glslAcos=n.glslAbs=void 0;const c=s(246),l=s(2517),f=s(8520),a=s(5060),h=s(2039);function p(){return L("abs")}function u(){return L("acos")}function o(){return L("asin")}function t(){return L("atan")}function e(){return L("ceil")}function r(){return L("cos")}function i(M){const j="elu";return{body:` - const float alpha = float(${M}); - - float ${j}_(float a) { - return a >= 0.0 ? a: (exp(a) - 1.0) * alpha; - } - vec4 ${j}_(vec4 v) { - return vec4(${j}_(v.x), ${j}_(v.y), ${j}_(v.z), ${j}_(v.w)); - } - `,name:j,type:f.FunctionType.ValueBased}}function d(){return L("exp")}function g(){return L("floor")}function m(M,j){const Z="clip";return{body:` - const float min = float(${M}); - const float max = float(${j}); - - float ${Z}_(float a) { - return clamp(a, min, max); - } - vec4 ${Z}_(vec4 v) { - return clamp(v, min, max); - } - `,name:Z,type:f.FunctionType.ValueBased}}function b(){const M="indentity";return{body:` - float ${M}_(float a) { - return a; - } - vec4 ${M}_(vec4 v) { - return v; - } - `,name:M,type:f.FunctionType.ValueBased}}function y(M){const j="leakyRelu";return{body:` - const float alpha = float(${M}); - - float ${j}_(float a) { - return a < 0.0 ? a * alpha : a; - } - vec4 ${j}_(vec4 v) { - return vec4(${j}_(v.x), ${j}_(v.y), ${j}_(v.z), ${j}_(v.w)); - } - `,name:j,type:f.FunctionType.ValueBased}}function w(){return L("log")}function v(){const M="neg";return{body:` - float ${M}_(float a) { - return -a; - } - vec4 ${M}_(vec4 v) { - return -v; - } - `,name:M,type:f.FunctionType.ValueBased}}function S(){const M="not";return{body:` - float ${M}_(float a) { - return float( ! bool(a) ); - } - bool ${M}_(bool a) { - return !a; - } - vec4 ${M}_(vec4 v) { - return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w)); - } - bvec4 ${M}_(bvec4 v) { - return bvec4(!v.x, !v.y, !v.z, !v.w); - } - `,name:M,type:f.FunctionType.ValueBased}}function A(){return L("sin")}function O(){const M="relu";return{body:` - float ${M}_(float a) { - return max( a, 0.0 ); - } - vec4 ${M}_(vec4 v) { - return max( v, 0.0 ); - } - `,name:M,type:f.FunctionType.ValueBased}}function x(){const M="sigmoid";return{body:` - float ${M}_(float a) { - return 1.0 / (1.0 + exp(-a)); - } - vec4 ${M}_(vec4 v) { - return 1.0 / (1.0 + exp(-v)); - } - `,name:M,type:f.FunctionType.ValueBased}}function I(){return L("sqrt")}function $(){return L("tan")}function z(){const M="tanh";return{body:` - float ${M}_(float a) { - a = clamp(a, -10., 10.); - a = exp(2.*a); - return (a - 1.) / (a + 1.); - } - vec4 ${M}_(vec4 v) { - v = clamp(v, -10., 10.); - v = exp(2.*v); - return (v - 1.) / (v + 1.); - } - `,name:M,type:f.FunctionType.ValueBased}}function L(M){return{body:` - float ${M}_(float a) { - return ${M}(a); - } - vec4 ${M}_(vec4 v) { - return ${M}(v); - } - `,name:M,type:f.FunctionType.ValueBased}}n.glslAbs=p,n.glslAcos=u,n.glslAsin=o,n.glslAtan=t,n.glslCeil=e,n.glslCos=r,n.glslElu=i,n.glslExp=d,n.glslFloor=g,n.glslClip=m,n.glslIdentity=b,n.glslLeakyRelu=y,n.glslLog=w,n.glslNeg=v,n.glslNot=S,n.glslSin=A,n.glslRelu=O,n.glslSigmoid=x,n.glslSqrt=I,n.glslTan=$,n.glslTanh=z;const N=(M,j,Z,X)=>{const Q=M.session.pack?h.TextureType.packed:h.TextureType.unpacked,ee={name:Z.name,inputTypes:[Q],inputNames:["A"],cacheHint:X};return Object.assign(Object.assign({},ee),{get:()=>((ue,Ae,xe,oe)=>{const we=ue.session.pack?h.TextureType.packed:h.TextureType.unpacked,ye=(0,a.getGlsl)(ue.session.backend.glContext.version);return Object.assign(Object.assign({},Ae),{output:{dims:xe.dims,type:xe.type,textureType:we},shaderSource:` - ${oe.body} - void main() { - vec4 v = ${ye.texture2D}(A, TexCoords); - v = ${oe.name}_(v); - ${ye.output} = v; - } - `,hasMain:!0})})(M,ee,j,Z)})};n.abs=(M,j)=>[M.run(N(M,j[0],p()),j)],n.acos=(M,j)=>[M.run(N(M,j[0],u()),j)],n.asin=(M,j)=>[M.run(N(M,j[0],o()),j)],n.atan=(M,j)=>[M.run(N(M,j[0],t()),j)],n.clip=(M,j,Z)=>[M.run(N(M,j[0],m(Z.min,Z.max),Z.cacheKey),j)],n.parseClipAttributes=M=>(0,c.createAttributeWithCacheKey)({min:M.attributes.getFloat("min",l.MIN_CLIP),max:M.attributes.getFloat("max",l.MAX_CLIP)}),n.clipV11=(M,j)=>{const Z=H(M,j);return(0,n.clip)(M,[j[0]],Z)};const H=(M,j)=>{if(j.length>=3&&(!M.session.isInitializer(j[1].dataId)||!M.session.isInitializer(j[2].dataId)))throw new Error("dynamic clip attributes are not allowed");const Z=j.length>=3?j[1].numberData[0]:l.MIN_CLIP,X=j.length>=3?j[2].numberData[0]:l.MAX_CLIP;return(0,c.createAttributeWithCacheKey)({min:Z,max:X})};n.ceil=(M,j)=>[M.run(N(M,j[0],e()),j)],n.cos=(M,j)=>[M.run(N(M,j[0],r()),j)],n.elu=(M,j,Z)=>[M.run(N(M,j[0],i(Z.alpha),Z.cacheKey),j)],n.parseEluAttributes=M=>(0,c.createAttributeWithCacheKey)({alpha:M.attributes.getFloat("alpha",1)}),n.exp=(M,j)=>[M.run(N(M,j[0],d()),j)],n.floor=(M,j)=>[M.run(N(M,j[0],g()),j)],n.identity=(M,j)=>[M.run(N(M,j[0],b()),j)],n.leakyRelu=(M,j,Z)=>[M.run(N(M,j[0],y(Z.alpha),Z.cacheKey),j)],n.parseLeakyReluAttributes=M=>(0,c.createAttributeWithCacheKey)({alpha:M.attributes.getFloat("alpha",.01)}),n.log=(M,j)=>[M.run(N(M,j[0],w()),j)],n.neg=(M,j)=>[M.run(N(M,j[0],v()),j)],n.not=(M,j)=>[M.run(N(M,j[0],S()),j)],n.relu=(M,j)=>[M.run(N(M,j[0],O()),j)],n.sigmoid=(M,j)=>[M.run(N(M,j[0],x()),j)],n.sin=(M,j)=>[M.run(N(M,j[0],A()),j)],n.sqrt=(M,j)=>[M.run(N(M,j[0],I()),j)],n.tan=(M,j)=>[M.run(N(M,j[0],$()),j)],n.tanh=(M,j)=>[M.run(N(M,j[0],z()),j)]},5611:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createUnpackProgramInfoLoader=n.createUnpackProgramInfo=void 0;const c=s(5060),l=s(2039),f=s(9390),a=s(2827),h={name:"unpack",inputNames:["A"],inputTypes:[l.TextureType.packed]};n.createUnpackProgramInfo=(p,u)=>{const o=u.dims.length,t=(0,a.getChannels)("rc",o),e=t.slice(-2),r=(0,f.getCoordsDataType)(o),i=(0,a.unpackFromChannel)(),d=u.dims.length===0?"":function(b,y){if(b===1)return"rc";let w="";for(let v=0;vObject.assign(Object.assign({},h),{get:()=>(0,n.createUnpackProgramInfo)(p,u)})},8428:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.parseUnsqueezeAttributes=n.unsqueezeV13=n.unsqueeze=void 0;const c=s(2517);n.unsqueeze=(a,h,p)=>{l(h);const u=c.ShapeUtil.unsqueezeShape(h[0].dims,p);return[a.reshapeUnpacked(h[0],u)]},n.unsqueezeV13=(a,h)=>(f(h),(0,n.unsqueeze)(a,[h[0]],Array.from(h[1].integerData))),n.parseUnsqueezeAttributes=a=>a.attributes.getInts("axes");const l=a=>{if(!a||a.length!==1)throw new Error("Unsqueeze requires 1 input.");if(a[0].type==="string")throw new Error("invalid input tensor types.")},f=a=>{if(!a||a.length!==2)throw new Error("Unsqueeze requires 2 inputs.");if(a[1].type!=="int32")throw new Error("Invalid input type.")}},9793:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.scalesValidation=n.validateInputs=n.parseUpsampleAttributes=n.parseUpsampleAttributesV9=n.parseUpsampleAttributesV7=n.upsample=void 0;const c=s(246),l=s(5060),f=s(2039),a={name:"Upsample",inputNames:["X"],inputTypes:[f.TextureType.unpacked]};n.upsample=(p,u,o)=>((0,n.validateInputs)(u,o),[p.run(Object.assign(Object.assign({},a),{cacheHint:o.cacheKey,get:()=>h(p,u,o)}),u)]),n.parseUpsampleAttributesV7=p=>(0,n.parseUpsampleAttributes)(p,7),n.parseUpsampleAttributesV9=p=>(0,n.parseUpsampleAttributes)(p,9),n.parseUpsampleAttributes=(p,u)=>{const o=u>=10,t=p.attributes.getString("mode","nearest");if(t!=="nearest"&&t!=="linear"&&(u<11||t!=="cubic"))throw new Error(`unrecognized mode: ${t}`);let e=[];u<9&&(e=p.attributes.getFloats("scales"),(0,n.scalesValidation)(e,t,o));const r=p.attributes.getFloat("extrapolation_value",0),i=u>10?p.attributes.getString("coordinate_transformation_mode","half_pixel"):"asymmetric";if(["asymmetric","pytorch_half_pixel","tf_half_pixel_for_nn","align_corners","tf_crop_and_resize","half_pixel"].indexOf(i)===-1)throw new Error(`coordinate_transform_mode '${i}' is not supported`);const d=i==="tf_crop_and_resize",g=d,m=t==="nearest"&&u>=11?p.attributes.getString("nearest_mode","round_prefer_floor"):"";if(["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(m)===-1)throw new Error(`nearest_mode '${m}' is not supported`);const b=p.attributes.getFloat("cubic_coeff_a",-.75),y=p.attributes.getInt("exclude_outside",0)!==0;if(y&&t!=="cubic")throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");const w=u<11||t==="nearest"&&i==="asymmetric"&&m==="floor";let v=0,S=0,A=0;return u>10?p.inputs.length>2?(v=1,S=2,A=3):(S=1,A=2):u===9&&(S=1),(0,c.createAttributeWithCacheKey)({opset:u,isResize:o,mode:t,scales:e,extrapolationValue:r,coordinateTransformMode:i,useExtrapolation:g,needRoiInput:d,nearestMode:m,cubicCoefficientA:b,excludeOutside:y,useNearest2xOptimization:w,roiInputIdx:v,scalesInputIdx:S,sizesInputIdx:A})};const h=(p,u,o)=>{const t=(0,l.getGlsl)(p.session.backend.glContext.version),[e,r]=p.calculateTextureWidthAndHeight(u[0].dims,f.TextureType.unpacked),i=u[0].dims.map((A,O)=>Math.floor(A*o.scales[O])),[d,g]=p.calculateTextureWidthAndHeight(i,f.TextureType.unpacked),m=i.length,b=new Array(m),y=new Array(m);let w=` - int output_pitches[${m}]; - int input_pitches[${m}]; - `;for(let A=m-1;A>=0;A--)b[A]=A===m-1?1:b[A+1]*i[A+1],y[A]=A===m-1?1:y[A+1]*u[0].dims[A+1],w+=` - output_pitches[${A}] = ${b[A]}; - input_pitches[${A}] = ${y[A]}; - `;const v=` - float getInputFloat(int index) { - vec2 coords = offsetToCoords(index, ${e}, ${r}); - float value = getColorAsFloat(${t.texture2D}(X, coords)); - return value; - } - `,S=o.mode==="nearest"?` - ${v} - float process(int indices[${m}]) { - int input_index = 0; - int output_index = coordsToOffset(TexCoords, ${d}, ${g}); - - ${w} - - int d, m; - for (int dim = 0; dim < ${m}; ++dim) { - d = output_index / output_pitches[dim]; - m = output_index - d * output_pitches[dim]; - output_index = m; - - if (scales[dim] != 1 && d > 0) { - int d2 = d / scales[dim]; - m = d - d2 * scales[dim]; - d = d2; - } - input_index += input_pitches[dim] * d; - } - - return getInputFloat(input_index); - }`:m===4?` - ${v} - float process(int indices[4]) { - int input_index = 0; - int output_index = coordsToOffset(TexCoords, ${d}, ${g}); - - ${w} - - int m; - int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3; - index_of_dim0 = output_index / output_pitches[0]; - m = output_index - index_of_dim0 * output_pitches[0]; - index_of_dim1 = m / output_pitches[1]; - m = m - index_of_dim1 * output_pitches[1]; - index_of_dim2 = m / output_pitches[2]; - m = m - index_of_dim2 * output_pitches[2]; - index_of_dim3 = m; - - int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset; - index_of_input_dim2 = index_of_dim2 / scales[2]; - y_offset = index_of_dim2 - index_of_input_dim2 * scales[2]; - index_of_input_dim3 = index_of_dim3 / scales[3]; - x_offset = index_of_dim3 - index_of_input_dim3 * scales[3]; - - input_index = index_of_dim0 * input_pitches[0] + - index_of_dim1 * input_pitches[1] + - index_of_input_dim2 * input_pitches[2] + - index_of_input_dim3; - - float x00 = getInputFloat(input_index); - float x10, x01, x11; - - bool end_of_dim2 = false; - if (index_of_input_dim2 == (${u[0].dims[2]} - 1)) { - // It's the end in dimension 2 - x01 = x00; - end_of_dim2 = true; - } else { - x01 = getInputFloat(input_index + input_pitches[2]); - } - - if (index_of_input_dim3 == (input_pitches[2] - 1)) { - // It's the end in dimension 3 - x10 = x00; - x11 = x01; - } - else { - x10 = getInputFloat(input_index + 1); - x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1); - } - - float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]); - float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]); - return y0 + float(x_offset) * (y1 - y0) / float(scales[3]); - }`:` - ${v} - float process(int indices[2]) { - int input_index = 0; - int output_index = coordsToOffset(TexCoords, ${d}, ${g}); - - ${w} - - int m; - int index_of_dim0, index_of_dim1; - index_of_dim0 = output_index / output_pitches[0]; - m = output_index - index_of_dim0 * output_pitches[0]; - index_of_dim1 = m; - - int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset; - index_of_input_dim0 = index_of_dim0 / scales[0]; - y_offset = index_of_dim0 - index_of_input_dim0 * scales[0]; - index_of_input_dim1 = index_of_dim1 / scales[1]; - x_offset = index_of_dim1 - index_of_input_dim1 * scales[1]; - - input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1; - - float x00 = getInputFloat(input_index); - float x10, x01, x11; - - bool end_of_dim0 = false; - if (index_of_input_dim0 == (${u[0].dims[0]} - 1)) { - // It's the end in dimension 0 - x01 = x00; - end_of_dim0 = true; - } else { - x01 = getInputFloat(input_index + input_pitches[0]); - } - - if (index_of_input_dim1 == (input_pitches[0] - 1)) { - // It's the end in dimension 1 - x10 = x00; - x11 = x01; - } - else { - x10 = getInputFloat(input_index + 1); - x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1); - } - - float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]); - float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]); - return y0 + float(x_offset) * (y1 - y0) / float(scales[1]); - }`;return Object.assign(Object.assign({},a),{output:{dims:i,type:u[0].type,textureType:f.TextureType.unpacked},shaderSource:S,variables:[{name:"scales",type:"int",arrayLength:o.scales.length,data:o.scales.map(A=>Math.ceil(A))}]})};n.validateInputs=(p,u)=>{if(!p||u.opset<9&&p.length!==1||u.opset>=9&&u.opset<11&&p.length!==2||u.opset>=11&&p.length<2)throw new Error("invalid inputs.");if(u.scales.length>0&&p[0].dims.length!==u.scales.length)throw new Error("Invalid input shape.");if(p[0].type==="string")throw new Error("Invalid input tensor types.")},n.scalesValidation=(p,u,o)=>{if(o){for(const t of p)if(t<=0)throw new Error("Scale value should be greater than 0.")}else for(const t of p)if(t<1)throw new Error("Scale value should be greater than or equal to 1.");if(!(u!=="linear"&&u!=="cubic"||p.length===2||p.length===4&&p[0]===1&&p[1]===1))throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the ${o?"Resize":"Upsample"} opeartor.`)}},1958:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ProgramManager=void 0;const c=s(1670),l=s(6231),f=s(8879),a=s(5060);n.ProgramManager=class{constructor(h,p,u){this.profiler=h,this.glContext=p,this.textureLayoutStrategy=u,this.repo=new Map,this.attributesBound=!1}getArtifact(h){return this.repo.get(h)}setArtifact(h,p){this.repo.set(h,p)}run(h,p,u){var o;this.profiler.event("op",`ProgramManager.run ${(o=h.programInfo.name)!==null&&o!==void 0?o:"unknown kernel"}`,()=>{var t;const e=this.glContext.gl,r=h.program;e.useProgram(r);try{this.bindOutput(u),this.attributesBound||this.bindAttributes(h.attribLocations),this.bindUniforms(h.uniformLocations,(t=h.programInfo.variables)!==null&&t!==void 0?t:[],p)}catch(i){throw l.Logger.error("ProgramManager",h.programInfo.shaderSource),i}this.profiler.event("backend","GlContext.draw()",()=>{this.glContext.draw()})},this.glContext)}dispose(){this.vertexShader&&this.glContext.deleteShader(this.vertexShader),this.repo.forEach(h=>this.glContext.deleteProgram(h.program))}build(h,p,u){return this.profiler.event("backend","ProgramManager.build",()=>{const o=new f.GlslPreprocessor(this.glContext,h,p,u),t=o.preprocess(),e=this.compile(t);return{programInfo:h,program:e,uniformLocations:this.getUniformLocations(e,o.context.programInfo.inputNames,o.context.programInfo.variables),attribLocations:this.getAttribLocations(e)}})}compile(h){if(!this.vertexShader){l.Logger.verbose("ProrgramManager","Compiling and caching Vertex shader for the first time");const o=(0,a.getVertexShaderSource)(this.glContext.version);this.vertexShader=this.glContext.compileShader(o,this.glContext.gl.VERTEX_SHADER)}c.env.debug&&l.Logger.verbose("ProrgramManager",`FragShader: -${h} -`);const p=this.glContext.compileShader(h,this.glContext.gl.FRAGMENT_SHADER),u=this.glContext.createProgram(this.vertexShader,p);return this.glContext.deleteShader(p),u}bindOutput(h){const p=h.width,u=h.height;l.Logger.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${p}/${u}, shape=${h.shape}, type=${h.tensor.type}`),this.glContext.attachFramebuffer(h.texture,p,u)}bindAttributes(h){const p=h.position,u=h.textureCoord;this.glContext.setVertexAttributes(p,u),this.attributesBound=!0}bindUniforms(h,p,u){var o;const t=this.glContext.gl;let e=0;for(const{name:r,type:i,location:d,arrayLength:g}of h){const m=(o=p.find(b=>b.name===r))===null||o===void 0?void 0:o.data;if(i!=="sampler2D"&&!m)throw new Error(`variable '${r}' does not have data defined in program info`);switch(i){case"sampler2D":this.bindTexture(u[e],d,e),e++;break;case"float":g?t.uniform1fv(d,m):t.uniform1f(d,m);break;case"int":g?t.uniform1iv(d,m):t.uniform1i(d,m);break;default:throw new Error(`Uniform not implemented: ${i}`)}}}bindTexture(h,p,u){this.glContext.bindTextureToUniform(h.texture,u,p)}getAttribLocations(h){return{position:this.getAttribLocation(h,"position"),textureCoord:this.getAttribLocation(h,"textureCoord")}}getUniformLocations(h,p,u){const o=[];if(p)for(const t of p)o.push({name:t,type:"sampler2D",location:this.getUniformLocation(h,t)});if(u)for(const t of u)o.push(Object.assign(Object.assign({},t),{location:this.getUniformLocation(h,t.name)}));return o}getUniformLocation(h,p){const u=this.glContext.gl.getUniformLocation(h,p);if(u===null)throw new Error(`Uniform ${p} not found.`);return u}getAttribLocation(h,p){return this.glContext.gl.getAttribLocation(h,p)}}},6416:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.WebGLSessionHandler=void 0;const c=s(6231),l=s(1047),f=s(8316),a=s(1640),h=s(1958),p=s(7859),u=s(5702);n.WebGLSessionHandler=class{constructor(o,t){this.backend=o,this.context=t,this.layoutStrategy=new p.PreferLogicalStrategy(o.glContext.maxTextureSize),this.programManager=new h.ProgramManager(this.context.profiler,o.glContext,this.layoutStrategy),this.textureManager=new u.TextureManager(o.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:o.textureCacheMode==="full"}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=o.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new f.WebGLInferenceHandler(this)}onGraphInitialized(o){const t=o.getValues().filter(e=>e.from===-1&&e.tensor).map(e=>e.tensor.dataId);this.initializers=new Set(t)}isInitializer(o){return!!this.initializers&&this.initializers.has(o)}addInitializer(o){this.initializers.add(o)}getTextureData(o,t){return t?this.packedTextureDataCache.get(o):this.unpackedTextureDataCache.get(o)}setTextureData(o,t,e=!1){c.Logger.verbose("WebGLSessionHandler","Storing Texture data in cache"),e?this.packedTextureDataCache.set(o,t):this.unpackedTextureDataCache.set(o,t)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(o=>this.textureManager.releaseTexture(o,!0)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(o=>this.textureManager.releaseTexture(o,!0)),this.unpackedTextureDataCache=new Map}resolve(o,t,e){const r=(0,l.resolveOperator)(o,t,a.WEBGL_OP_RESOLVE_RULES);return{impl:r.opImpl,context:r.opInit?r.opInit(o,e):o}}}},7769:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Uint8DataEncoder=n.RGBAFloatDataEncoder=n.RedFloat32DataEncoder=void 0;const c=s(6231);n.RedFloat32DataEncoder=class{constructor(l,f=1){if(f===1)this.internalFormat=l.R32F,this.format=l.RED,this.textureType=l.FLOAT,this.channelSize=f;else{if(f!==4)throw new Error(`Invalid number of channels: ${f}`);this.internalFormat=l.RGBA32F,this.format=l.RGBA,this.textureType=l.FLOAT,this.channelSize=f}}encode(l,f){let a,h;return l.constructor!==Float32Array&&(c.Logger.warning("Encoder","data was not of type Float32; creating new Float32Array"),h=new Float32Array(l)),f*this.channelSize>l.length?(c.Logger.warning("Encoder","Source data too small. Allocating larger array"),h=l,a=this.allocate(f*this.channelSize),h.forEach((p,u)=>a[u]=p)):(h=l,a=h),a}allocate(l){return new Float32Array(4*l)}decode(l,f){return this.channelSize===1?l.filter((a,h)=>h%4==0).subarray(0,f):l.subarray(0,f)}},n.RGBAFloatDataEncoder=class{constructor(l,f=1,a){if(f!==1&&f!==4)throw new Error(`Invalid number of channels: ${f}`);this.internalFormat=l.RGBA,this.format=l.RGBA,this.channelSize=f,this.textureType=a||l.FLOAT}encode(l,f){let a=l;return this.channelSize===1&&(c.Logger.verbose("Encoder","Exploding into a larger array"),a=this.allocate(f),l.forEach((h,p)=>a[4*p]=h)),a}allocate(l){return new Float32Array(4*l)}decode(l,f){return this.channelSize===1?l.filter((a,h)=>h%4==0).subarray(0,f):l.subarray(0,f)}},n.Uint8DataEncoder=class{constructor(l,f=1){if(this.channelSize=4,f===1)this.internalFormat=l.ALPHA,this.format=l.ALPHA,this.textureType=l.UNSIGNED_BYTE,this.channelSize=f;else{if(f!==4)throw new Error(`Invalid number of channels: ${f}`);this.internalFormat=l.RGBA,this.format=l.RGBA,this.textureType=l.UNSIGNED_BYTE,this.channelSize=f}}encode(l,f){return new Uint8Array(l.buffer,l.byteOffset,l.byteLength)}allocate(l){return new Uint8Array(l*this.channelSize)}decode(l,f){if(l instanceof Uint8Array)return l.subarray(0,f);throw new Error(`Invalid array type: ${l.constructor}`)}}},7859:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.getBatchDim=n.sizeToSquarishShape=n.getRowsCols=n.sizeFromShape=n.isInt=n.parseAxisParam=n.squeezeShape=n.PreferLogicalStrategy=n.AlwaysKeepOriginalSizeStrategy=void 0;const c=s(6231),l=s(2517);function f(o,t){const e=[],r=[],i=t!=null&&Array.isArray(t)&&t.length===0,d=t==null||i?null:a(t,o).sort();let g=0;for(let m=0;mm)&&o[m]===1&&(e.push(o[m]),r.push(m)),d[g]<=m&&g++}o[m]!==1&&(e.push(o[m]),r.push(m))}return{newShape:e,keptDims:r}}function a(o,t){const e=t.length;return o=o==null?t.map((r,i)=>i):[].concat(o),(0,l.assert)(o.every(r=>r>=-e&&r`All values in axis param must be in range [-${e}, ${e}) but got axis ${o}`),(0,l.assert)(o.every(h),()=>`All values in axis param must be integers but got axis ${o}`),o.map(r=>r<0?e+r:r)}function h(o){return o%1==0}function p(o){if(o.length===0)return 1;let t=o[0];for(let e=1;e=o.length?1:o.slice(t.breakAxis).reduce((m,b)=>m*b),g=t.breakAxis<=0?1:o.slice(0,t.breakAxis).reduce((m,b)=>m*b);if(!(d>e||g>e))return[d,g];c.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${o}, breakAxis:${t.breakAxis}`)}const r=o.reduce((d,g)=>d*g);let i=Math.floor(Math.sqrt(r));for(;i=e||r%i!=0)throw new Error(`The given dimensions are outside this GPU's boundaries: ${o}`);return[i,r/i]}},n.PreferLogicalStrategy=class{constructor(o){this.maxTextureSize=o}computeTextureWH(o,t){const e=this.computeTexture(o,t);return t&&t.isPacked&&(e[0]/=2,e[1]/=2),t&&t.reverseWH?[e[1],e[0]]:e}computeTexture(o,t){const e=t&&t.isPacked;if(o.length===0)return e?[2,2]:[1,1];let r=this.maxTextureSize;if(t&&t.breakAxis!==void 0){const g=t.breakAxis>=o.length?1:o.slice(t.breakAxis).reduce((b,y)=>b*y),m=t.breakAxis<=0?1:o.slice(0,t.breakAxis).reduce((b,y)=>b*y);if(!(g>r||m>r))return[g,m];c.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${o}, breakAxis:${t.breakAxis}`)}let i=o.slice(0);e&&(r*=2,i=i.map((g,m)=>m>=i.length-2?i[m]%2==0?i[m]:i[m]+1:i[m]),i.length===1&&(i=[2,i[0]])),i.length!==2&&(i=f(i).newShape);const d=p(i);return i.length<=1&&d<=r?[1,d]:i.length===2&&i[0]<=r&&i[1]<=r?i:i.length===3&&i[0]*i[1]<=r&&i[2]<=r?[i[0]*i[1],i[2]]:i.length===3&&i[0]<=r&&i[1]*i[2]<=r?[i[0],i[1]*i[2]]:i.length===4&&i[0]*i[1]*i[2]<=r&&i[3]<=r?[i[0]*i[1]*i[2],i[3]]:i.length===4&&i[0]<=r&&i[1]*i[2]*i[3]<=r?[i[0],i[1]*i[2]*i[3]]:e?u(d/4).map(g=>2*g):u(d)}},n.squeezeShape=f,n.parseAxisParam=a,n.isInt=h,n.sizeFromShape=p,n.getRowsCols=function(o){if(o.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[o.length>1?o[o.length-2]:1,o[o.length-1]]},n.sizeToSquarishShape=u,n.getBatchDim=function(o,t=2){return p(o.slice(0,o.length-t))}},4057:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createTextureLayoutFromShape=n.calculateTextureWidthAndHeight=n.createTextureLayoutFromTextureType=void 0;const c=s(2517),l=s(2039);n.createTextureLayoutFromTextureType=(f,a,h)=>{const p=h===l.TextureType.unpacked||h===l.TextureType.unpackedReversed?1:4,u=h===l.TextureType.packed,o=h===l.TextureType.unpackedReversed||h===l.TextureType.packed,t=h===l.TextureType.packedLastDimension?a.length-1:void 0,e=h===l.TextureType.packedLastDimension?a.map((r,i)=>i===a.length-1?4*r:r):void 0;return(0,n.createTextureLayoutFromShape)(f,a,p,e,{isPacked:u,reverseWH:o,breakAxis:t})},n.calculateTextureWidthAndHeight=(f,a,h)=>{const p=(0,n.createTextureLayoutFromTextureType)(f,a,h);return[p.width,p.height]},n.createTextureLayoutFromShape=(f,a,h=1,p,u)=>{const o=!(!u||!u.isPacked),[t,e]=f.computeTextureWH(o&&p||a,u),r=a.length;let i=a.slice(0);if(r===0&&(i=[1]),h===1)p=a;else if(o){if(h!==4)throw new Error("a packed texture must be 4-channel");p=a,r>0&&(i[r-1]=Math.ceil(i[r-1]/2)),r>1&&(i[r-2]=Math.ceil(i[r-2]/2))}else if(!p)throw new Error("Unpacked shape is needed when using channels > 1");return{width:t,height:e,channels:h,isPacked:o,shape:i,strides:c.ShapeUtil.computeStrides(i),unpackedShape:p,reversedWH:u&&u.reverseWH}}},5702:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.TextureManager=void 0;const c=s(6231);n.TextureManager=class{constructor(l,f,a,h){this.glContext=l,this.layoutStrategy=f,this.profiler=a,this.config=h,this.pendingRead=new Map,h.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(l,f,a,h){const p=this.toEncoderType(l),u=this.glContext.getEncoder(p,f.channels||1,h);if(f.isPacked&&h===1)throw new Error("not implemented");const o=f.width,t=f.height;let e,r;if(this.config.reuseTextures){e=`${o}x${t}_${u.format}_${u.internalFormat}_${u.textureType}`,r=this.inUseTextures.get(e),r||(r=[],this.inUseTextures.set(e,r));const d=this.idleTextures.get(e);if(d&&d.length>0){const g=d.pop();return r.push(g),h===1&&this.glContext.updateTexture(g,o,t,u,this.toTextureData(l,a)),g}}c.Logger.verbose("TextureManager",`Creating new texture of size ${f.width}x${f.height}`);const i=this.glContext.allocateTexture(o,t,u,this.toTextureData(l,a));return this.config.reuseTextures&&(r.push(i),this.textureLookup.set(i,e)),i}readTexture(l,f,a){return a||(a=1),this.profiler.event("backend","TextureManager.readTexture",()=>{const h=l.shape.reduce((u,o)=>u*o)*a,p=this.glContext.readTexture(l.texture,l.width,l.height,h,this.toEncoderType(f),a);return this.toTensorData(f,p)})}async readTextureAsync(l,f,a){const h=l.tensor.dataId;if(a||(a=1),this.pendingRead.has(h)){const p=this.pendingRead.get(h);return new Promise(u=>p==null?void 0:p.push(u))}return this.profiler.event("backend","TextureManager.readTextureAsync",async()=>{this.pendingRead.set(h,[]);const p=l.shape.reduce((e,r)=>e*r)*a;await this.glContext.createAndWaitForFence();const u=this.glContext.readTexture(l.texture,l.width,l.height,p,this.toEncoderType(f),a),o=this.toTensorData(f,u),t=this.pendingRead.get(h);return this.pendingRead.delete(h),t==null||t.forEach(e=>e(o)),o})}readUint8TextureAsFloat(l){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",()=>{const f=l.shape.reduce((h,p)=>h*p),a=this.glContext.readTexture(l.texture,l.width,l.height,4*f,"byte",4);return new Float32Array(a.buffer,a.byteOffset,f)})}releaseTexture(l,f){let a;if(this.config.reuseTextures&&(a=this.textureLookup.get(l.texture),a)){f&&this.textureLookup.delete(a);const h=this.inUseTextures.get(a);if(h){const p=h.indexOf(l.texture);if(p!==-1){h.splice(p,1);let u=this.idleTextures.get(a);u||(u=[],this.idleTextures.set(a,u)),u.push(l.texture)}}}a&&!f||(c.Logger.verbose("TextureManager",`Deleting texture of size ${l.width}x${l.height}`),this.glContext.deleteTexture(l.texture))}toTensorData(l,f){switch(l){case"int16":return f instanceof Int16Array?f:Int16Array.from(f);case"int32":return f instanceof Int32Array?f:Int32Array.from(f);case"int8":return f instanceof Int8Array?f:Int8Array.from(f);case"uint16":return f instanceof Uint16Array?f:Uint16Array.from(f);case"uint32":return f instanceof Uint32Array?f:Uint32Array.from(f);case"uint8":case"bool":return f instanceof Uint8Array?f:Uint8Array.from(f);case"float32":return f instanceof Float32Array?f:Float32Array.from(f);case"float64":return f instanceof Float64Array?f:Float64Array.from(f);default:throw new Error(`TensorData type ${l} is not supported`)}}toTextureData(l,f){if(f)return f instanceof Float32Array?f:new Float32Array(f)}toEncoderType(l){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}},2039:(_,n)=>{var s;Object.defineProperty(n,"__esModule",{value:!0}),n.TextureType=void 0,(s=n.TextureType||(n.TextureType={}))[s.unpacked=0]="unpacked",s[s.unpackedReversed=1]="unpackedReversed",s[s.packed=2]="packed",s[s.downloadUint8AsFloat=3]="downloadUint8AsFloat",s[s.packedLastDimension=4]="packedLastDimension"},9390:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.getGlChannels=n.getCoordsDataType=n.getSqueezedParams=n.squeezeInputShape=n.generateShaderFuncNameFromInputSamplerNameAtOutCoords=n.generateShaderFuncNameFromInputSamplerName=n.repeatedTry=n.getPackedShape=void 0;const c=s(2517);n.getPackedShape=function(l){const f=l.length;return l.slice(0,f-1).concat(l[f-1]/4)},n.repeatedTry=async function(l,f=h=>0,a){return new Promise((h,p)=>{let u=0;const o=()=>{if(l())return void h();u++;const t=f(u);a!=null&&u>=a?p():setTimeout(o,t)};o()})},n.generateShaderFuncNameFromInputSamplerName=function(l){return(0,c.assert)(l!==void 0&&l.length!==0,()=>"empty string found for sampler name"),"get"+l.charAt(0).toUpperCase()+l.slice(1)},n.generateShaderFuncNameFromInputSamplerNameAtOutCoords=function(l){return(0,c.assert)(l!==void 0&&l.length!==0,()=>"empty string found for sampler name"),"get"+l.charAt(0).toUpperCase()+l.slice(1)+"AtOutCoords"},n.squeezeInputShape=function(l,f){let a=JSON.parse(JSON.stringify(l));return a=f,a},n.getSqueezedParams=function(l,f){return f.map(a=>l[a]).join(", ")},n.getCoordsDataType=function(l){if(l<=1)return"int";if(l===2)return"ivec2";if(l===3)return"ivec3";if(l===4)return"ivec4";if(l===5)return"ivec5";if(l===6)return"ivec6";throw Error(`GPU for rank ${l} is not yet supported`)},n.getGlChannels=function(l=6){return["x","y","z","w","u","v"].slice(0,l)}},7305:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createNewWebGLContext=n.createWebGLContext=void 0;const c=s(6231),l=s(1713),f={};function a(h){const p=function(){if(typeof document>"u"){if(typeof OffscreenCanvas>"u")throw new TypeError("failed to create canvas: OffscreenCanvas is not supported");return new OffscreenCanvas(1,1)}const t=document.createElement("canvas");return t.width=1,t.height=1,t}();let u;const o={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1};if((!h||h==="webgl2")&&(u=p.getContext("webgl2",o),u))try{return new l.WebGLContext(u,2)}catch(t){c.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${t}`)}if((!h||h==="webgl")&&(u=p.getContext("webgl",o)||p.getContext("experimental-webgl",o),u))try{return new l.WebGLContext(u,1)}catch(t){c.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${t}`)}throw new Error("WebGL is not supported")}n.createWebGLContext=function h(p){let u;p&&p!=="webgl2"||!("webgl2"in f)?p&&p!=="webgl"||!("webgl"in f)||(u=f.webgl):u=f.webgl2,u=u||a(p),p=p||u.version===1?"webgl":"webgl2";const o=u.gl;return f[p]=u,o.isContextLost()?(delete f[p],h(p)):(o.disable(o.DEPTH_TEST),o.disable(o.STENCIL_TEST),o.disable(o.BLEND),o.disable(o.DITHER),o.disable(o.POLYGON_OFFSET_FILL),o.disable(o.SAMPLE_COVERAGE),o.enable(o.SCISSOR_TEST),o.enable(o.CULL_FACE),o.cullFace(o.BACK),u)},n.createNewWebGLContext=a},1713:function(_,n,s){var c=this&&this.__createBinding||(Object.create?function(o,t,e,r){r===void 0&&(r=e);var i=Object.getOwnPropertyDescriptor(t,e);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(o,r,i)}:function(o,t,e,r){r===void 0&&(r=e),o[r]=t[e]}),l=this&&this.__setModuleDefault||(Object.create?function(o,t){Object.defineProperty(o,"default",{enumerable:!0,value:t})}:function(o,t){o.default=t}),f=this&&this.__importStar||function(o){if(o&&o.__esModule)return o;var t={};if(o!=null)for(var e in o)e!=="default"&&Object.prototype.hasOwnProperty.call(o,e)&&c(t,o,e);return l(t,o),t};Object.defineProperty(n,"__esModule",{value:!0}),n.WebGLContext=n.linearSearchLastTrue=void 0;const a=s(1670),h=f(s(7769)),p=s(9390);function u(o){let t=0;for(;tthis.isTimerResultAvailable(o)),this.getTimerResult(o)}async createAndWaitForFence(){const o=this.createFence(this.gl);return this.pollFence(o)}createFence(o){let t;const e=o,r=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return o.flush(),t=r===null?()=>!0:()=>{const i=e.clientWaitSync(r,0,0);return i===e.ALREADY_SIGNALED||i===e.CONDITION_SATISFIED},{query:r,isFencePassed:t}}async pollFence(o){return new Promise(t=>{this.addItemToPoll(()=>o.isFencePassed(),()=>t())})}pollItems(){const o=u(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=o;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(o+1)}async addItemToPoll(o,t){this.itemsToPoll.push({isDoneFn:o,resolveFn:t}),this.itemsToPoll.length>1||await(0,p.repeatedTry)(()=>(this.pollItems(),this.itemsToPoll.length===0))}}},1036:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ExecutionPlan=void 0;const c=s(6231);class l{constructor(a,h){this.op=a,this.node=h}}n.ExecutionPlan=class{constructor(f,a,h){this.graph=f,this.profiler=h,this.initialize(a)}initialize(f){this.profiler.event("session","ExecutionPlan.initialize",()=>{const a=this.graph.getNodes();if(a.length!==f.length)throw new Error("The size of nodes and OPs do not match.");this._ops=f.map((h,p)=>new l(h,a[p])),this.reset(),this._starter=[],this._ops.forEach((h,p)=>{let u=!0;for(const o of h.node.inputs)if(!this._values[o]&&this.graph.getInputIndices().indexOf(o)===-1){u=!1;break}u&&this._starter.push(p)})})}reset(){this._values=this.graph.getValues().map(f=>f.tensor)}async execute(f,a){return this.profiler.event("session","ExecutionPlan.execute",async()=>{this.reset();const h=f.createInferenceHandler(),p=this.graph.getInputIndices();if(a.length!==p.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${a.length} expected: ${p.length}`);a.forEach((i,d)=>{const g=p[d];this._values[g]=i});const u=this._starter.slice(0),o=this.graph.getValues(),t=this.graph.getNodes();let e=0;for(;ethis._values[w]);if(g.indexOf(void 0)!==-1)throw new Error(`unresolved input detected: op: ${d.node}`);const m=g;c.Logger.verbose("ExecPlan",`Runing op:${d.node.name} (${m.map((w,v)=>`'${d.node.inputs[v]}': ${w.type}[${w.dims.join(",")}]`).join(", ")})`);const b=await this.profiler.event("node",d.node.name,async()=>d.op.impl(h,m,d.op.context));if(b.length!==d.node.outputs.length)throw new Error("the size of output does not match model definition.");b.forEach((w,v)=>{const S=d.node.outputs[v];if(this._values[S])throw new Error(`output [${S}] already has value: op:${d.node.name}`);this._values[S]=w});const y=new Set;b.forEach((w,v)=>{const S=d.node.outputs[v];for(const A of o[S].to){const O=t[A];let x=!0;for(const I of O.inputs)if(!this._values[I]){x=!1;break}x&&y.add(A)}}),u.push(...y)}const r=[];for(let i=0;i{Object.defineProperty(n,"__esModule",{value:!0}),n.Graph=void 0;const c=s(1446),l=s(7778),f=s(9395),a=s(9162),h=s(2517);var p=f.onnxruntime.experimental.fbs;n.Graph={from:(e,r)=>new t(e,r)};class u{constructor(r){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,r&&(this.type=h.ProtoUtil.tensorValueTypeFromProto(r.type.tensorType))}get from(){return this._from}get to(){return this._to}}class o{constructor(r,i){r instanceof c.onnx.NodeProto?(this.name=r.name,this.opType=r.opType,this.attributes=new l.Attribute(r.attribute)):r instanceof p.Node&&(this.name=i??r.name(),this.opType=r.opType(),this.attributes=new l.Attribute(h.ProtoUtil.tensorAttributesFromORTFormat(r))),this.inputs=[],this.outputs=[],this.executeNode=!0}}class t{constructor(r,i){if(!r)throw new TypeError("graph is empty");this.buildGraph(r),this.transformGraph(i),this.checkIsAcyclic()}getInputIndices(){return this._allInputIndices}getInputNames(){return this._allInputNames}getOutputIndices(){return this._allOutputIndices}getOutputNames(){return this._allOutputNames}getValues(){return this._allData}getNodes(){return this._nodes}buildGraph(r){if(r instanceof c.onnx.GraphProto)this.buildGraphFromOnnxFormat(r);else{if(!(r instanceof p.Graph))throw new TypeError("Graph type is not supported.");this.buildGraphFromOrtFormat(r)}}buildGraphFromOnnxFormat(r){const i=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];const d=new Map;if(!r.input)throw new Error("missing information in graph: input");const g=[];for(const m of r.input){if(i.has(m.name))throw new Error(`duplicated input name: ${m.name}`);const b=this._allData.push(new u(m))-1;i.set(m.name,b),g.push(m.name)}if(!r.initializer)throw new Error("missing information in graph: initializer");for(const m of r.initializer){let b=i.get(m.name);if(b===void 0){const y=new u;y.type={shape:{dims:h.ProtoUtil.tensorDimsFromProto(m.dims)},tensorType:h.ProtoUtil.tensorDataTypeFromProto(m.dataType)},b=this._allData.push(y)-1,i.set(m.name,b)}this._allData[b]._from=-1,this._allData[b].tensor=a.Tensor.fromProto(m)}for(let m=0;m{this._allData[g]._to.forEach(m=>{r.add(m)})});const i=Array.from(r),d=new Array(this._nodes.length).fill("white");for(;i.length>0;){const g=i.pop();d[g]==="gray"?d[g]="black":(i.push(g),d[g]="gray",this._nodes[g].outputs.forEach(m=>{const b=this._allData[m];if(b.tensor!==void 0)throw new Error("node outputs should not be initialized");if(b._from!==g)throw new Error("from property of the Value object doesn't match index of Node being processed");b._to.forEach(y=>{if(d[y]==="gray")throw new Error("model graph is cyclic");d[y]==="white"&&i.push(y)})}))}}transformGraph(r){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),r&&r.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let r=0;for(let i=0;i0&&(this._nodes[i].inputs.forEach(d=>{const g=this._allData[d]._to.indexOf(i+r);g!==-1&&(this._allData[d]._to[g]=i)}),this._nodes[i].outputs.forEach(d=>{this._allData[d]._from&&this._allData[d]._from===i+r&&(this._allData[d]._from=i)})):(r++,this._nodes[i].outputs.forEach(d=>{this._allData[d]._from=-2}),this._nodes.splice(i,1),i--);r=0;for(let i=0;i0){let d=-1;this._allData[i].from!==void 0&&this._allData[i].from!==-1?(d=this._nodes[this._allData[i].from].outputs.indexOf(i+r),d!==-1&&(this._nodes[this._allData[i].from].outputs[d]=i)):(d=this._allInputIndices.indexOf(i+r),d!==-1&&(this._allInputIndices[d]=i)),this._allData[i].to.forEach(g=>{d=this._nodes[g].inputs.indexOf(i+r),d!==-1&&(this._nodes[g].inputs[d]=i)}),this._allData[i].to.length===0&&(d=this._allOutputIndices.indexOf(i+r),d!==-1&&(this._allOutputIndices[d]=i))}}else r++,this._allData.splice(i,1),i--}deleteNode(r){const i=this._nodes[r];if(i.outputs.length>1){for(let w=1;w0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ")}i.executeNode=!1;const d=i.inputs[0],g=i.outputs[0],m=this._allData[g].to,b=this._allData[d].to.indexOf(r);if(b===-1)throw new Error("The Value object doesn't have the current Node in it's 'to' property ");this._allData[d].to.splice(b,1),this._allData[g]._to=[];const y=this._allOutputIndices.indexOf(g);if(y!==-1&&(this._allOutputIndices[y]=d),m&&m.length>0)for(const w of m){const v=this._nodes[w].inputs.indexOf(g);if(v===-1)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[w].inputs[v]=d,this._allData[d].to.push(w)}}removeAllDropoutNodes(){let r=0;for(const i of this._nodes){if(i.opType==="Dropout"){if(i.inputs.length!==1)throw new Error("Dropout nodes should only contain one input. ");if(i.outputs.length!==1&&i.outputs.length!==2)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(i.outputs.length===2&&this._allData[i.outputs[1]]._to.length!==0)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(r)}r++}}removeAllIdentityNodes(){let r=0;for(const i of this._nodes)i.opType==="Identity"&&this.deleteNode(r),r++}isActivation(r){switch(r.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(const r of this._nodes)if(r.opType==="Conv"){const i=this._allData[r.outputs[0]]._to;if(i.length===1&&this.isActivation(this._nodes[i[0]])){const d=this._nodes[i[0]];if(d.opType==="Clip")if(d.inputs.length===1)try{r.attributes.set("activation_params","floats",[d.attributes.getFloat("min"),d.attributes.getFloat("max")])}catch{r.attributes.set("activation_params","floats",[h.MIN_CLIP,h.MAX_CLIP])}else{if(!(d.inputs.length>=3&&this._allData[d.inputs[1]].tensor!==void 0&&this._allData[d.inputs[2]].tensor!==void 0))continue;r.attributes.set("activation_params","floats",[this._allData[d.inputs[1]].tensor.floatData[0],this._allData[d.inputs[2]].tensor.floatData[0]])}r.attributes.set("activation","string",d.opType),this.deleteNode(i[0])}}}}},6231:(_,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.now=n.Profiler=n.Logger=void 0;const s={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},c={none:new class{log(o,t,e){}},console:new class{log(o,t,e){console.log(`${this.color(o)} ${e?"\x1B[35m"+e+"\x1B[0m ":""}${t}`)}color(o){switch(o){case"verbose":return"\x1B[34;40mv\x1B[0m";case"info":return"\x1B[32mi\x1B[0m";case"warning":return"\x1B[30;43mw\x1B[0m";case"error":return"\x1B[31;40me\x1B[0m";case"fatal":return"\x1B[101mf\x1B[0m";default:throw new Error(`unsupported severity: ${o}`)}}}},l={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1};let f={"":l};function a(o,t,e,r){if(t===void 0)return i=o,{verbose:a.verbose.bind(null,i),info:a.info.bind(null,i),warning:a.warning.bind(null,i),error:a.error.bind(null,i),fatal:a.fatal.bind(null,i)};if(e===void 0)h(o,t);else if(typeof e=="number"&&r===void 0)h(o,t);else if(typeof e=="string"&&r===void 0)h(o,e,0,t);else{if(typeof e!="string"||typeof r!="number")throw new TypeError("input is valid");h(o,e,0,t)}var i}function h(o,t,e,r){const i=f[r||""]||f[""];s[o]{g.then(async y=>{i&&await i.end(),m(y)},async y=>{i&&await i.end(),b(y)})});if(!d&&i){const m=i.end();if(m&&typeof m.then=="function")return new Promise((b,y)=>{m.then(()=>{b(g)},w=>{y(w)})})}return g}begin(o,t,e){if(!this._started)throw new Error("profiler is not started yet");if(e===void 0){const r=(0,n.now)();return this.flush(r),new p(o,t,r,i=>this.endSync(i))}{const r=e.beginTimer();return new p(o,t,0,async i=>this.end(i),r,e)}}async end(o){const t=await o.checkTimer();this._timingEvents.length=this._flushBatchSize||o-this._flushTime>=this._flushIntervalInMilliseconds){for(const t=this._flushPointer;this._flushPointerperformance.now():Date.now},2644:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Model=void 0;const c=s(5686),l=s(1446),f=s(7070),a=s(9395),h=s(2517);var p=a.onnxruntime.experimental.fbs;n.Model=class{constructor(){}load(u,o,t){if(!t)try{return void this.loadFromOnnxFormat(u,o)}catch(e){if(t!==void 0)throw e}this.loadFromOrtFormat(u,o)}loadFromOnnxFormat(u,o){const t=l.onnx.ModelProto.decode(u);if(h.LongUtil.longToNumber(t.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=t.opsetImport.map(e=>({domain:e.domain,version:h.LongUtil.longToNumber(e.version)})),this._graph=f.Graph.from(t.graph,o)}loadFromOrtFormat(u,o){const t=new c.flatbuffers.ByteBuffer(u),e=p.InferenceSession.getRootAsInferenceSession(t).model();if(h.LongUtil.longToNumber(e.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let r=0;r{Object.defineProperty(n,"__esModule",{value:!0}),n.FLOAT_TYPES=n.INT_TYPES=n.NUMBER_TYPES=void 0,n.NUMBER_TYPES=["float32","float64","int32","int16","int8","uint16","uint32","uint8"],n.INT_TYPES=["int32","int16","int8","uint16","uint32","uint8"],n.FLOAT_TYPES=["float32","float64"]},1047:(_,n)=>{function s(c,l){if(l.endsWith("+")){const f=Number.parseInt(l.substring(0,l.length-1),10);return!isNaN(f)&&f<=c}if(l.split("-").length===2){const f=l.split("-"),a=Number.parseInt(f[0],10),h=Number.parseInt(f[1],10);return!isNaN(a)&&!isNaN(h)&&a<=c&&c<=h}return Number.parseInt(l,10)===c}Object.defineProperty(n,"__esModule",{value:!0}),n.resolveOperator=void 0,n.resolveOperator=function(c,l,f){for(const a of f){const h=a[0],p=a[1],u=a[2],o=a[3],t=a[4];if(c.opType===h){for(const e of l)if((e.domain===p||e.domain==="ai.onnx"&&p==="")&&s(e.version,u))return{opImpl:o,opInit:t}}}throw new TypeError(`cannot resolve operator '${c.opType}' with opsets: ${l.map(a=>`${a.domain||"ai.onnx"} v${a.version}`).join(", ")}`)}},9395:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.onnxruntime=void 0;const c=s(5686);var l,f;l=n.onnxruntime||(n.onnxruntime={}),function(a){(function(h){h[h.UNDEFINED=0]="UNDEFINED",h[h.FLOAT=1]="FLOAT",h[h.INT=2]="INT",h[h.STRING=3]="STRING",h[h.TENSOR=4]="TENSOR",h[h.GRAPH=5]="GRAPH",h[h.FLOATS=6]="FLOATS",h[h.INTS=7]="INTS",h[h.STRINGS=8]="STRINGS",h[h.TENSORS=9]="TENSORS",h[h.GRAPHS=10]="GRAPHS",h[h.SPARSE_TENSOR=11]="SPARSE_TENSOR",h[h.SPARSE_TENSORS=12]="SPARSE_TENSORS"})(a.AttributeType||(a.AttributeType={}))}((f=l.experimental||(l.experimental={})).fbs||(f.fbs={})),function(a){(function(h){(function(p){(function(u){u[u.UNKNOWN=0]="UNKNOWN",u[u.VALUE=1]="VALUE",u[u.PARAM=2]="PARAM"})(p.DimensionValueType||(p.DimensionValueType={}))})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){(function(u){u[u.UNDEFINED=0]="UNDEFINED",u[u.FLOAT=1]="FLOAT",u[u.UINT8=2]="UINT8",u[u.INT8=3]="INT8",u[u.UINT16=4]="UINT16",u[u.INT16=5]="INT16",u[u.INT32=6]="INT32",u[u.INT64=7]="INT64",u[u.STRING=8]="STRING",u[u.BOOL=9]="BOOL",u[u.FLOAT16=10]="FLOAT16",u[u.DOUBLE=11]="DOUBLE",u[u.UINT32=12]="UINT32",u[u.UINT64=13]="UINT64",u[u.COMPLEX64=14]="COMPLEX64",u[u.COMPLEX128=15]="COMPLEX128",u[u.BFLOAT16=16]="BFLOAT16"})(p.TensorDataType||(p.TensorDataType={}))})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){(function(u){u[u.Primitive=0]="Primitive",u[u.Fused=1]="Fused"})(p.NodeType||(p.NodeType={}))})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){(function(u){u[u.NONE=0]="NONE",u[u.tensor_type=1]="tensor_type",u[u.sequence_type=2]="sequence_type",u[u.map_type=3]="map_type"})(p.TypeInfoValue||(p.TypeInfoValue={}))})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsShape(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsShape(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}dim(t,e){let r=this.bb.__offset(this.bb_pos,4);return r?(e||new a.experimental.fbs.Dimension).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}dimLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}static startShape(t){t.startObject(1)}static addDim(t,e){t.addFieldOffset(0,e,0)}static createDimVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startDimVector(t,e){t.startVector(4,e,4)}static endShape(t){return t.endObject()}static createShape(t,e){return u.startShape(t),u.addDim(t,e),u.endShape(t)}}p.Shape=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDimension(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDimension(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}value(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new a.experimental.fbs.DimensionValue).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}denotation(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}static startDimension(t){t.startObject(2)}static addValue(t,e){t.addFieldOffset(0,e,0)}static addDenotation(t,e){t.addFieldOffset(1,e,0)}static endDimension(t){return t.endObject()}static createDimension(t,e,r){return u.startDimension(t),u.addValue(t,e),u.addDenotation(t,r),u.endDimension(t)}}p.Dimension=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDimensionValue(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDimensionValue(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}dimType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt8(this.bb_pos+t):a.experimental.fbs.DimensionValueType.UNKNOWN}dimValue(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}dimParam(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}static startDimensionValue(t){t.startObject(3)}static addDimType(t,e){t.addFieldInt8(0,e,a.experimental.fbs.DimensionValueType.UNKNOWN)}static addDimValue(t,e){t.addFieldInt64(1,e,t.createLong(0,0))}static addDimParam(t,e){t.addFieldOffset(2,e,0)}static endDimensionValue(t){return t.endObject()}static createDimensionValue(t,e,r,i){return u.startDimensionValue(t),u.addDimType(t,e),u.addDimValue(t,r),u.addDimParam(t,i),u.endDimensionValue(t)}}p.DimensionValue=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTensorTypeAndShape(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTensorTypeAndShape(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}elemType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):a.experimental.fbs.TensorDataType.UNDEFINED}shape(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new a.experimental.fbs.Shape).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startTensorTypeAndShape(t){t.startObject(2)}static addElemType(t,e){t.addFieldInt32(0,e,a.experimental.fbs.TensorDataType.UNDEFINED)}static addShape(t,e){t.addFieldOffset(1,e,0)}static endTensorTypeAndShape(t){return t.endObject()}static createTensorTypeAndShape(t,e,r){return u.startTensorTypeAndShape(t),u.addElemType(t,e),u.addShape(t,r),u.endTensorTypeAndShape(t)}}p.TensorTypeAndShape=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsMapType(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMapType(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}keyType(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt32(this.bb_pos+t):a.experimental.fbs.TensorDataType.UNDEFINED}valueType(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new a.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startMapType(t){t.startObject(2)}static addKeyType(t,e){t.addFieldInt32(0,e,a.experimental.fbs.TensorDataType.UNDEFINED)}static addValueType(t,e){t.addFieldOffset(1,e,0)}static endMapType(t){return t.endObject()}static createMapType(t,e,r){return u.startMapType(t),u.addKeyType(t,e),u.addValueType(t,r),u.endMapType(t)}}p.MapType=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSequenceType(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSequenceType(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}elemType(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new a.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startSequenceType(t){t.startObject(1)}static addElemType(t,e){t.addFieldOffset(0,e,0)}static endSequenceType(t){return t.endObject()}static createSequenceType(t,e){return u.startSequenceType(t),u.addElemType(t,e),u.endSequenceType(t)}}p.SequenceType=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(h.fbs||(h.fbs={})).EdgeEnd=class{constructor(){this.bb=null,this.bb_pos=0}__init(p,u){return this.bb_pos=p,this.bb=u,this}nodeIndex(){return this.bb.readUint32(this.bb_pos)}srcArgIndex(){return this.bb.readInt32(this.bb_pos+4)}dstArgIndex(){return this.bb.readInt32(this.bb_pos+8)}static createEdgeEnd(p,u,o,t){return p.prep(4,12),p.writeInt32(t),p.writeInt32(o),p.writeInt32(u),p.offset()}}})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsNodeEdge(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNodeEdge(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}nodeIndex(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readUint32(this.bb_pos+t):0}inputEdges(t,e){let r=this.bb.__offset(this.bb_pos,6);return r?(e||new a.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*t,this.bb):null}inputEdgesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}outputEdges(t,e){let r=this.bb.__offset(this.bb_pos,8);return r?(e||new a.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*t,this.bb):null}outputEdgesLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startNodeEdge(t){t.startObject(3)}static addNodeIndex(t,e){t.addFieldInt32(0,e,0)}static addInputEdges(t,e){t.addFieldOffset(1,e,0)}static startInputEdgesVector(t,e){t.startVector(12,e,4)}static addOutputEdges(t,e){t.addFieldOffset(2,e,0)}static startOutputEdgesVector(t,e){t.startVector(12,e,4)}static endNodeEdge(t){return t.endObject()}static createNodeEdge(t,e,r,i){return u.startNodeEdge(t),u.addNodeIndex(t,e),u.addInputEdges(t,r),u.addOutputEdges(t,i),u.endNodeEdge(t)}}p.NodeEdge=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsNode(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNode(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}domain(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}sinceVersion(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt32(this.bb_pos+t):0}index(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readUint32(this.bb_pos+t):0}opType(t){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,t):null}type(){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.readInt32(this.bb_pos+t):a.experimental.fbs.NodeType.Primitive}executionProviderType(t){let e=this.bb.__offset(this.bb_pos,18);return e?this.bb.__string(this.bb_pos+e,t):null}inputs(t,e){let r=this.bb.__offset(this.bb_pos,20);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}inputsLength(){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__vector_len(this.bb_pos+t):0}outputs(t,e){let r=this.bb.__offset(this.bb_pos,22);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}outputsLength(){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.__vector_len(this.bb_pos+t):0}attributes(t,e){let r=this.bb.__offset(this.bb_pos,24);return r?(e||new a.experimental.fbs.Attribute).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}attributesLength(){let t=this.bb.__offset(this.bb_pos,24);return t?this.bb.__vector_len(this.bb_pos+t):0}inputArgCounts(t){let e=this.bb.__offset(this.bb_pos,26);return e?this.bb.readInt32(this.bb.__vector(this.bb_pos+e)+4*t):0}inputArgCountsLength(){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.__vector_len(this.bb_pos+t):0}inputArgCountsArray(){let t=this.bb.__offset(this.bb_pos,26);return t?new Int32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}implicitInputs(t,e){let r=this.bb.__offset(this.bb_pos,28);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}implicitInputsLength(){let t=this.bb.__offset(this.bb_pos,28);return t?this.bb.__vector_len(this.bb_pos+t):0}static startNode(t){t.startObject(13)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addDomain(t,e){t.addFieldOffset(2,e,0)}static addSinceVersion(t,e){t.addFieldInt32(3,e,0)}static addIndex(t,e){t.addFieldInt32(4,e,0)}static addOpType(t,e){t.addFieldOffset(5,e,0)}static addType(t,e){t.addFieldInt32(6,e,a.experimental.fbs.NodeType.Primitive)}static addExecutionProviderType(t,e){t.addFieldOffset(7,e,0)}static addInputs(t,e){t.addFieldOffset(8,e,0)}static createInputsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startInputsVector(t,e){t.startVector(4,e,4)}static addOutputs(t,e){t.addFieldOffset(9,e,0)}static createOutputsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startOutputsVector(t,e){t.startVector(4,e,4)}static addAttributes(t,e){t.addFieldOffset(10,e,0)}static createAttributesVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startAttributesVector(t,e){t.startVector(4,e,4)}static addInputArgCounts(t,e){t.addFieldOffset(11,e,0)}static createInputArgCountsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addInt32(e[r]);return t.endVector()}static startInputArgCountsVector(t,e){t.startVector(4,e,4)}static addImplicitInputs(t,e){t.addFieldOffset(12,e,0)}static createImplicitInputsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startImplicitInputsVector(t,e){t.startVector(4,e,4)}static endNode(t){return t.endObject()}static createNode(t,e,r,i,d,g,m,b,y,w,v,S,A,O){return u.startNode(t),u.addName(t,e),u.addDocString(t,r),u.addDomain(t,i),u.addSinceVersion(t,d),u.addIndex(t,g),u.addOpType(t,m),u.addType(t,b),u.addExecutionProviderType(t,y),u.addInputs(t,w),u.addOutputs(t,v),u.addAttributes(t,S),u.addInputArgCounts(t,A),u.addImplicitInputs(t,O),u.endNode(t)}}p.Node=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsValueInfo(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsValueInfo(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}type(t){let e=this.bb.__offset(this.bb_pos,8);return e?(t||new a.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startValueInfo(t){t.startObject(3)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addType(t,e){t.addFieldOffset(2,e,0)}static endValueInfo(t){return t.endObject()}static createValueInfo(t,e,r,i){return u.startValueInfo(t),u.addName(t,e),u.addDocString(t,r),u.addType(t,i),u.endValueInfo(t)}}p.ValueInfo=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTypeInfo(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTypeInfo(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}denotation(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}valueType(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readUint8(this.bb_pos+t):a.experimental.fbs.TypeInfoValue.NONE}value(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__union(t,this.bb_pos+e):null}static startTypeInfo(t){t.startObject(3)}static addDenotation(t,e){t.addFieldOffset(0,e,0)}static addValueType(t,e){t.addFieldInt8(1,e,a.experimental.fbs.TypeInfoValue.NONE)}static addValue(t,e){t.addFieldOffset(2,e,0)}static endTypeInfo(t){return t.endObject()}static createTypeInfo(t,e,r,i){return u.startTypeInfo(t),u.addDenotation(t,e),u.addValueType(t,r),u.addValue(t,i),u.endTypeInfo(t)}}p.TypeInfo=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsOperatorSetId(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsOperatorSetId(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}domain(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}version(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}static startOperatorSetId(t){t.startObject(2)}static addDomain(t,e){t.addFieldOffset(0,e,0)}static addVersion(t,e){t.addFieldInt64(1,e,t.createLong(0,0))}static endOperatorSetId(t){return t.endObject()}static createOperatorSetId(t,e,r){return u.startOperatorSetId(t),u.addDomain(t,e),u.addVersion(t,r),u.endOperatorSetId(t)}}p.OperatorSetId=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTensor(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTensor(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}dims(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}dimsLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}dataType(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt32(this.bb_pos+t):a.experimental.fbs.TensorDataType.UNDEFINED}rawData(t){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.readUint8(this.bb.__vector(this.bb_pos+e)+t):0}rawDataLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}rawDataArray(){let t=this.bb.__offset(this.bb_pos,12);return t?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}stringData(t,e){let r=this.bb.__offset(this.bb_pos,14);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}stringDataLength(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__vector_len(this.bb_pos+t):0}static startTensor(t){t.startObject(6)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addDims(t,e){t.addFieldOffset(2,e,0)}static createDimsVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addInt64(e[r]);return t.endVector()}static startDimsVector(t,e){t.startVector(8,e,8)}static addDataType(t,e){t.addFieldInt32(3,e,a.experimental.fbs.TensorDataType.UNDEFINED)}static addRawData(t,e){t.addFieldOffset(4,e,0)}static createRawDataVector(t,e){t.startVector(1,e.length,1);for(let r=e.length-1;r>=0;r--)t.addInt8(e[r]);return t.endVector()}static startRawDataVector(t,e){t.startVector(1,e,1)}static addStringData(t,e){t.addFieldOffset(5,e,0)}static createStringDataVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startStringDataVector(t,e){t.startVector(4,e,4)}static endTensor(t){return t.endObject()}static createTensor(t,e,r,i,d,g,m){return u.startTensor(t),u.addName(t,e),u.addDocString(t,r),u.addDims(t,i),u.addDataType(t,d),u.addRawData(t,g),u.addStringData(t,m),u.endTensor(t)}}p.Tensor=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSparseTensor(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSparseTensor(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}values(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new a.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}indices(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new a.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}dims(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}dimsLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startSparseTensor(t){t.startObject(3)}static addValues(t,e){t.addFieldOffset(0,e,0)}static addIndices(t,e){t.addFieldOffset(1,e,0)}static addDims(t,e){t.addFieldOffset(2,e,0)}static createDimsVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addInt64(e[r]);return t.endVector()}static startDimsVector(t,e){t.startVector(8,e,8)}static endSparseTensor(t){return t.endObject()}static createSparseTensor(t,e,r,i){return u.startSparseTensor(t),u.addValues(t,e),u.addIndices(t,r),u.addDims(t,i),u.endSparseTensor(t)}}p.SparseTensor=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsAttribute(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsAttribute(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}type(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.readInt32(this.bb_pos+t):a.experimental.fbs.AttributeType.UNDEFINED}f(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readFloat32(this.bb_pos+t):0}i(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}s(t){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,t):null}t(t){let e=this.bb.__offset(this.bb_pos,16);return e?(t||new a.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}g(t){let e=this.bb.__offset(this.bb_pos,18);return e?(t||new a.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}floats(t){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.readFloat32(this.bb.__vector(this.bb_pos+e)+4*t):0}floatsLength(){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__vector_len(this.bb_pos+t):0}floatsArray(){let t=this.bb.__offset(this.bb_pos,20);return t?new Float32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}ints(t){let e=this.bb.__offset(this.bb_pos,22);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}intsLength(){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.__vector_len(this.bb_pos+t):0}strings(t,e){let r=this.bb.__offset(this.bb_pos,24);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}stringsLength(){let t=this.bb.__offset(this.bb_pos,24);return t?this.bb.__vector_len(this.bb_pos+t):0}tensors(t,e){let r=this.bb.__offset(this.bb_pos,26);return r?(e||new a.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}tensorsLength(){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.__vector_len(this.bb_pos+t):0}graphs(t,e){let r=this.bb.__offset(this.bb_pos,28);return r?(e||new a.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}graphsLength(){let t=this.bb.__offset(this.bb_pos,28);return t?this.bb.__vector_len(this.bb_pos+t):0}static startAttribute(t){t.startObject(13)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addType(t,e){t.addFieldInt32(2,e,a.experimental.fbs.AttributeType.UNDEFINED)}static addF(t,e){t.addFieldFloat32(3,e,0)}static addI(t,e){t.addFieldInt64(4,e,t.createLong(0,0))}static addS(t,e){t.addFieldOffset(5,e,0)}static addT(t,e){t.addFieldOffset(6,e,0)}static addG(t,e){t.addFieldOffset(7,e,0)}static addFloats(t,e){t.addFieldOffset(8,e,0)}static createFloatsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addFloat32(e[r]);return t.endVector()}static startFloatsVector(t,e){t.startVector(4,e,4)}static addInts(t,e){t.addFieldOffset(9,e,0)}static createIntsVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addInt64(e[r]);return t.endVector()}static startIntsVector(t,e){t.startVector(8,e,8)}static addStrings(t,e){t.addFieldOffset(10,e,0)}static createStringsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startStringsVector(t,e){t.startVector(4,e,4)}static addTensors(t,e){t.addFieldOffset(11,e,0)}static createTensorsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startTensorsVector(t,e){t.startVector(4,e,4)}static addGraphs(t,e){t.addFieldOffset(12,e,0)}static createGraphsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startGraphsVector(t,e){t.startVector(4,e,4)}static endAttribute(t){return t.endObject()}static createAttribute(t,e,r,i,d,g,m,b,y,w,v,S,A,O){return u.startAttribute(t),u.addName(t,e),u.addDocString(t,r),u.addType(t,i),u.addF(t,d),u.addI(t,g),u.addS(t,m),u.addT(t,b),u.addG(t,y),u.addFloats(t,w),u.addInts(t,v),u.addStrings(t,S),u.addTensors(t,A),u.addGraphs(t,O),u.endAttribute(t)}}p.Attribute=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsGraph(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsGraph(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}initializers(t,e){let r=this.bb.__offset(this.bb_pos,4);return r?(e||new a.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}initializersLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}nodeArgs(t,e){let r=this.bb.__offset(this.bb_pos,6);return r?(e||new a.experimental.fbs.ValueInfo).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}nodeArgsLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}nodes(t,e){let r=this.bb.__offset(this.bb_pos,8);return r?(e||new a.experimental.fbs.Node).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}nodesLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}maxNodeIndex(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readUint32(this.bb_pos+t):0}nodeEdges(t,e){let r=this.bb.__offset(this.bb_pos,12);return r?(e||new a.experimental.fbs.NodeEdge).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}nodeEdgesLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}inputs(t,e){let r=this.bb.__offset(this.bb_pos,14);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}inputsLength(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__vector_len(this.bb_pos+t):0}outputs(t,e){let r=this.bb.__offset(this.bb_pos,16);return r?this.bb.__string(this.bb.__vector(this.bb_pos+r)+4*t,e):null}outputsLength(){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.__vector_len(this.bb_pos+t):0}sparseInitializers(t,e){let r=this.bb.__offset(this.bb_pos,18);return r?(e||new a.experimental.fbs.SparseTensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}sparseInitializersLength(){let t=this.bb.__offset(this.bb_pos,18);return t?this.bb.__vector_len(this.bb_pos+t):0}static startGraph(t){t.startObject(8)}static addInitializers(t,e){t.addFieldOffset(0,e,0)}static createInitializersVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startInitializersVector(t,e){t.startVector(4,e,4)}static addNodeArgs(t,e){t.addFieldOffset(1,e,0)}static createNodeArgsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startNodeArgsVector(t,e){t.startVector(4,e,4)}static addNodes(t,e){t.addFieldOffset(2,e,0)}static createNodesVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startNodesVector(t,e){t.startVector(4,e,4)}static addMaxNodeIndex(t,e){t.addFieldInt32(3,e,0)}static addNodeEdges(t,e){t.addFieldOffset(4,e,0)}static createNodeEdgesVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startNodeEdgesVector(t,e){t.startVector(4,e,4)}static addInputs(t,e){t.addFieldOffset(5,e,0)}static createInputsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startInputsVector(t,e){t.startVector(4,e,4)}static addOutputs(t,e){t.addFieldOffset(6,e,0)}static createOutputsVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startOutputsVector(t,e){t.startVector(4,e,4)}static addSparseInitializers(t,e){t.addFieldOffset(7,e,0)}static createSparseInitializersVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startSparseInitializersVector(t,e){t.startVector(4,e,4)}static endGraph(t){return t.endObject()}static createGraph(t,e,r,i,d,g,m,b,y){return u.startGraph(t),u.addInitializers(t,e),u.addNodeArgs(t,r),u.addNodes(t,i),u.addMaxNodeIndex(t,d),u.addNodeEdges(t,g),u.addInputs(t,m),u.addOutputs(t,b),u.addSparseInitializers(t,y),u.endGraph(t)}}p.Graph=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsModel(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsModel(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}irVersion(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}opsetImport(t,e){let r=this.bb.__offset(this.bb_pos,6);return r?(e||new a.experimental.fbs.OperatorSetId).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}opsetImportLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}producerName(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}producerVersion(t){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__string(this.bb_pos+e,t):null}domain(t){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__string(this.bb_pos+e,t):null}modelVersion(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}docString(t){let e=this.bb.__offset(this.bb_pos,16);return e?this.bb.__string(this.bb_pos+e,t):null}graph(t){let e=this.bb.__offset(this.bb_pos,18);return e?(t||new a.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}graphDocString(t){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.__string(this.bb_pos+e,t):null}static startModel(t){t.startObject(9)}static addIrVersion(t,e){t.addFieldInt64(0,e,t.createLong(0,0))}static addOpsetImport(t,e){t.addFieldOffset(1,e,0)}static createOpsetImportVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startOpsetImportVector(t,e){t.startVector(4,e,4)}static addProducerName(t,e){t.addFieldOffset(2,e,0)}static addProducerVersion(t,e){t.addFieldOffset(3,e,0)}static addDomain(t,e){t.addFieldOffset(4,e,0)}static addModelVersion(t,e){t.addFieldInt64(5,e,t.createLong(0,0))}static addDocString(t,e){t.addFieldOffset(6,e,0)}static addGraph(t,e){t.addFieldOffset(7,e,0)}static addGraphDocString(t,e){t.addFieldOffset(8,e,0)}static endModel(t){return t.endObject()}static createModel(t,e,r,i,d,g,m,b,y,w){return u.startModel(t),u.addIrVersion(t,e),u.addOpsetImport(t,r),u.addProducerName(t,i),u.addProducerVersion(t,d),u.addDomain(t,g),u.addModelVersion(t,m),u.addDocString(t,b),u.addGraph(t,y),u.addGraphDocString(t,w),u.endModel(t)}}p.Model=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsKernelCreateInfos(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsKernelCreateInfos(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}nodeIndices(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readUint32(this.bb.__vector(this.bb_pos+e)+4*t):0}nodeIndicesLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}nodeIndicesArray(){let t=this.bb.__offset(this.bb_pos,4);return t?new Uint32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}kernelDefHashes(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}kernelDefHashesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}static startKernelCreateInfos(t){t.startObject(2)}static addNodeIndices(t,e){t.addFieldOffset(0,e,0)}static createNodeIndicesVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addInt32(e[r]);return t.endVector()}static startNodeIndicesVector(t,e){t.startVector(4,e,4)}static addKernelDefHashes(t,e){t.addFieldOffset(1,e,0)}static createKernelDefHashesVector(t,e){t.startVector(8,e.length,8);for(let r=e.length-1;r>=0;r--)t.addInt64(e[r]);return t.endVector()}static startKernelDefHashesVector(t,e){t.startVector(8,e,8)}static endKernelCreateInfos(t){return t.endObject()}static createKernelCreateInfos(t,e,r){return u.startKernelCreateInfos(t),u.addNodeIndices(t,e),u.addKernelDefHashes(t,r),u.endKernelCreateInfos(t)}}p.KernelCreateInfos=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSubGraphSessionState(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSubGraphSessionState(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}graphId(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}sessionState(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new a.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startSubGraphSessionState(t){t.startObject(2)}static addGraphId(t,e){t.addFieldOffset(0,e,0)}static addSessionState(t,e){t.addFieldOffset(1,e,0)}static endSubGraphSessionState(t){let e=t.endObject();return t.requiredField(e,4),e}static createSubGraphSessionState(t,e,r){return u.startSubGraphSessionState(t),u.addGraphId(t,e),u.addSessionState(t,r),u.endSubGraphSessionState(t)}}p.SubGraphSessionState=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSessionState(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSessionState(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}kernels(t){let e=this.bb.__offset(this.bb_pos,4);return e?(t||new a.experimental.fbs.KernelCreateInfos).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}subGraphSessionStates(t,e){let r=this.bb.__offset(this.bb_pos,6);return r?(e||new a.experimental.fbs.SubGraphSessionState).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*t),this.bb):null}subGraphSessionStatesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}static startSessionState(t){t.startObject(2)}static addKernels(t,e){t.addFieldOffset(0,e,0)}static addSubGraphSessionStates(t,e){t.addFieldOffset(1,e,0)}static createSubGraphSessionStatesVector(t,e){t.startVector(4,e.length,4);for(let r=e.length-1;r>=0;r--)t.addOffset(e[r]);return t.endVector()}static startSubGraphSessionStatesVector(t,e){t.startVector(4,e,4)}static endSessionState(t){return t.endObject()}static createSessionState(t,e,r){return u.startSessionState(t),u.addKernels(t,e),u.addSubGraphSessionStates(t,r),u.endSessionState(t)}}p.SessionState=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={})),function(a){(function(h){(function(p){class u{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsInferenceSession(t,e){return(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsInferenceSession(t,e){return t.setPosition(t.position()+c.flatbuffers.SIZE_PREFIX_LENGTH),(e||new u).__init(t.readInt32(t.position())+t.position(),t)}static bufferHasIdentifier(t){return t.__has_identifier("ORTM")}ortVersion(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}model(t){let e=this.bb.__offset(this.bb_pos,6);return e?(t||new a.experimental.fbs.Model).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}sessionState(t){let e=this.bb.__offset(this.bb_pos,8);return e?(t||new a.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+e),this.bb):null}static startInferenceSession(t){t.startObject(3)}static addOrtVersion(t,e){t.addFieldOffset(0,e,0)}static addModel(t,e){t.addFieldOffset(1,e,0)}static addSessionState(t,e){t.addFieldOffset(2,e,0)}static endInferenceSession(t){return t.endObject()}static finishInferenceSessionBuffer(t,e){t.finish(e,"ORTM")}static finishSizePrefixedInferenceSessionBuffer(t,e){t.finish(e,"ORTM",!0)}static createInferenceSession(t,e,r,i){return u.startInferenceSession(t),u.addOrtVersion(t,e),u.addModel(t,r),u.addSessionState(t,i),u.endInferenceSession(t)}}p.InferenceSession=u})(h.fbs||(h.fbs={}))})(a.experimental||(a.experimental={}))}(n.onnxruntime||(n.onnxruntime={}))},7448:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.OnnxjsSessionHandler=void 0;const c=s(1670),l=s(9162);n.OnnxjsSessionHandler=class{constructor(f){this.session=f,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}async dispose(){}async run(f,a,h){const p=new Map;for(const t in f)if(Object.hasOwnProperty.call(f,t)){const e=f[t];p.set(t,new l.Tensor(e.dims,e.type,void 0,void 0,e.data))}const u=await this.session.run(p),o={};return u.forEach((t,e)=>{o[e]=new c.Tensor(t.type,t.data,t.dims)}),o}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}},6919:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Session=void 0;const c=s(7067),l=s(1296),f=s(7091),a=s(1036),h=s(6231),p=s(2644);n.Session=class{constructor(u={}){this._initialized=!1,this.backendHint=u.backendHint,this.profiler=h.Profiler.create(u.profiler),this.context={profiler:this.profiler,graphInputTypes:[],graphInputDims:[]}}get inputNames(){return this._model.graph.getInputNames()}get outputNames(){return this._model.graph.getOutputNames()}startProfiling(){this.profiler.start()}endProfiling(){this.profiler.stop()}async loadModel(u,o,t){await this.profiler.event("session","Session.loadModel",async()=>{const e=await(0,f.resolveBackend)(this.backendHint);if(this.sessionHandler=e.createSessionHandler(this.context),this._model=new p.Model,typeof u=="string"){const r=u.endsWith(".ort");if(typeof fetch>"u"){const i=await(0,l.promisify)(c.readFile)(u);this.initialize(i,r)}else{const i=await fetch(u),d=await i.arrayBuffer();this.initialize(new Uint8Array(d),r)}}else if(ArrayBuffer.isView(u))this.initialize(u);else{const r=new Uint8Array(u,o||0,t||u.byteLength);this.initialize(r)}})}initialize(u,o){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",()=>{const t=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(u,t,o),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new a.ExecutionPlan(this._model.graph,this._ops,this.profiler)}),this._initialized=!0}async run(u){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",async()=>{const o=this.normalizeAndValidateInputs(u),t=await this._executionPlan.execute(this.sessionHandler,o);return this.createOutput(t)})}normalizeAndValidateInputs(u){const o=this._model.graph.getInputNames();if(Array.isArray(u)){if(u.length!==o.length)throw new Error(`incorrect input array length: expected ${o.length} but got ${u.length}`)}else{if(u.size!==o.length)throw new Error(`incorrect input map size: expected ${o.length} but got ${u.size}`);const t=new Array(u.size);let e=0;for(let r=0;rtypeof O=="string")))throw new TypeError("cache should be a string array");A&&(this.cache=new Array(S))}else{if(w!==void 0){const O=e(m);if(!(w instanceof O))throw new TypeError(`cache should be type ${O.name}`)}if(A){const O=new ArrayBuffer(S*function(x){switch(x){case"bool":case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;case"float64":return 8;default:throw new Error(`cannot calculate sizeof() on type ${x}`)}}(m));this.cache=function(x,I){return new(e(I))(x)}(O,m)}}}static fromProto(g){if(!g)throw new Error("cannot construct Value from an empty tensor");const m=p.ProtoUtil.tensorDataTypeFromProto(g.dataType),b=p.ProtoUtil.tensorDimsFromProto(g.dims),y=new o(b,m);if(m==="string")g.stringData.forEach((w,v)=>{y.data[v]=(0,p.decodeUtf8String)(w)});else if(g.rawData&&typeof g.rawData.byteLength=="number"&&g.rawData.byteLength>0){const w=y.data,v=new DataView(g.rawData.buffer,g.rawData.byteOffset,g.rawData.byteLength),S=t(g.dataType),A=g.rawData.byteLength/S;if(g.rawData.byteLength%S!=0)throw new Error("invalid buffer length");if(w.length!==A)throw new Error("buffer length mismatch");for(let O=0;O0){const w=y.data,v=new DataView(g.rawDataArray().buffer,g.rawDataArray().byteOffset,g.rawDataLength()),S=t(g.dataType()),A=g.rawDataLength()/S;if(g.rawDataLength()%S!=0)throw new Error("invalid buffer length");if(w.length!==A)throw new Error("buffer length mismatch");for(let O=0;O1&&I>1)return;A[S-O]=Math.max(x,I)}return A}static index(m,b){const y=new Array(b.length);return u.fillIndex(m,b,y),y}static fillIndex(m,b,y){const w=m.length-b.length;for(let v=0;v=0;Z--)x[Z]=z%S[Z],z=Math.floor(z/S[Z]);H||(u.fillIndex(x,m.dims,I),L=m.get(I)),M||(u.fillIndex(x,b.dims,$),N=b.get($)),O.set(x,y(L,N))}}return O}}static isValidBroadcast(m,b){const y=m.length,w=b.length;if(y>w)return!1;for(let v=1;v<=y;v++)if(m[y-v]!==1&&m[y-v]!==b[w-v])return!1;return!0}static getBroadcastDims(m,b){const y=m.length,w=[];for(let v=0;v1&&A===1&&w.unshift(S)}return w}}n.BroadcastUtil=u,n.arrayCopyHelper=function(g,m,b,y,w){if(y<0||y>=m.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(y+w>m.length)throw new Error("source indices to be copied are outside bounds");if(b+w>g.length)throw new Error("target array is too small to hold result");for(let v=0;vf.default.isLong(b)?b.toNumber():b)}static tensorValueTypeFromProto(m){return{tensorType:o.tensorDataTypeFromProto(m.elemType),shape:{dims:o.tensorDimsFromProto(m.shape.dim.map(b=>b.dimValue))}}}static tensorDimsFromORTFormat(m){const b=[];for(let y=0;ym.length)throw new Error(`invalid dimension of ${b} for sizeFromDimension as Tensor has ${m.length} dimensions.`);return e.getSizeFromDimensionRange(m,b,m.length)}static sizeToDimension(m,b){if(b<0||b>m.length)throw new Error(`invalid dimension of ${b} for sizeToDimension as Tensor has ${m.length} dimensions.`);return e.getSizeFromDimensionRange(m,0,b)}static getSizeFromDimensionRange(m,b,y){let w=1;for(let v=b;v=0;--w)y[w]=y[w+1]*m[w+1];return y}static transpose(m){return m.slice().reverse()}static indicesToOffset(m,b,y){y===void 0&&(y=m.length);let w=0;for(let v=0;v=b)throw new Error("unsupported axis for this operation.");return m<0?m+b:m}static normalizeAxes(m,b){return m.map(y=>this.normalizeAxis(y,b))}static incrementIndex(m,b,y){if(b.length===0||m.length===0)throw new Error("Index incrementing unsupported for scalar Tensor");if(y===void 0)y=b.length;else if(y<=0||y>b.length)throw new Error("Incorrect axis to increment on");for(let w=y-1;w>=0&&(m[w]++,!(m[w]=m.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");w[O]=m[O]}else w[O]=b[O];S*=w[O]}}const A=e.size(m);if(v!==-1){if(A%S!=0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${m}] Output shape: [${b}]`);w[v]=A/S}else if(S!==A)throw new Error("reshapedDims and originalDims don't have matching sizes");return w}static sortBasedOnPerm(m,b){return b?b.map(y=>m[y]):m.slice().reverse()}static padShape(m,b){const y=m.length;return m.map((w,v)=>w+b[v]+b[v+y])}static areEqual(m,b){return m.length===b.length&&m.every((y,w)=>y===b[w])}static validateDimsAndCalcSize(m){if(m.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let b=1;for(const y of m){if(!Number.isInteger(y))throw new TypeError(`Invalid shape: ${y} is not an integer`);if(y<0||y>2147483647)throw new TypeError(`Invalid shape: length ${y} is not allowed`);b*=y}return b}static flattenShape(m,b){b<0&&(b+=m.length);const y=m.reduce((v,S)=>v*S,1),w=m.slice(b).reduce((v,S)=>v*S,1);return[y/w,w]}static squeezeShape(m,b){const y=new Array;b=e.normalizeAxes(b,m.length);for(let w=0;w=0;if(v&&m[w]!==1)throw new Error("squeeze an axis of size different than 1");(b.length===0&&m[w]>1||b.length>0&&!v)&&y.push(m[w])}return y}static unsqueezeShape(m,b){const y=new Array(m.length+b.length);y.fill(0);for(let v=0;v=y.length)throw new Error("'axes' has an out of range axis");if(y[S]!==0)throw new Error("'axes' has a duplicate axis");y[S]=1}let w=0;for(let v=0;v=m.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(y+w>m.length)throw new Error("source indices to be copied are outside bounds");if(b+w>g.length)throw new Error("target array is too small to hold result");for(let v=0;v=m.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(y+w>m.length)throw new Error("source indices to be copied are outside bounds");if(b+w>g.length)throw new Error("target array is too small to hold result");for(let S=0;S=m.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(y+w>m.length)throw new Error("source indices to be copied are outside bounds");if(b+w>g.length)throw new Error("target array is too small to hold result");for(let S=0;S=m.length)throw new Error("sourceIndex out of bounds");if(b<0||b>=g.length)throw new Error("targetIndex out of bounds");if(y+w>m.length)throw new Error("source indices to be copied are outside bounds");if(b+w>g.length)throw new Error("target array is too small to hold result");for(let v=0;vb.push(N));const A=i.calcReduceShape(S,b,!0),O=e.size(A),x=new h.Tensor(A,m.type),I=e.computeStrides(A),$=e.computeStrides(S),z=new Array(S.length);for(let L=0;L=b.length)return S(m[v]);const x=b[w],I=x>=y.length?1:e.size(y.slice(x+1));for(let $=0;$v!==0)}}n.ReduceUtil=i;class d{static adjustPoolAttributes(m,b,y,w,v,S){if(!m&&y.length!==b.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(m)for(let A=0;A=y.length?y.push(b[A+2]):y[A]=b[A+2];for(let A=0;A=y[A]||S[A+y.length]>=y[A])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(m,b,y,w,v,S){if(S){if(v.length!==2*(m.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(b.length!==m.length-2)throw new Error("length of strides should be the length of data dimensions");if(w.length!==m.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let A=0;A{Object.defineProperty(n,"__esModule",{value:!0}),n.iterateExtraOptions=void 0,n.iterateExtraOptions=(s,c,l,f)=>{if(typeof s=="object"&&s!==null){if(l.has(s))throw new Error("Circular reference in options");l.add(s)}Object.entries(s).forEach(([a,h])=>{const p=c?c+a:a;if(typeof h=="object")(0,n.iterateExtraOptions)(h,p+".",l,f);else if(typeof h=="string"||typeof h=="number")f(p,h.toString());else{if(typeof h!="boolean")throw new Error("Can't handle extra config type: "+typeof h);f(p,h?"1":"0")}})}},2157:function(_,n,s){var c,l=this&&this.__createBinding||(Object.create?function(I,$,z,L){L===void 0&&(L=z);var N=Object.getOwnPropertyDescriptor($,z);N&&!("get"in N?!$.__esModule:N.writable||N.configurable)||(N={enumerable:!0,get:function(){return $[z]}}),Object.defineProperty(I,L,N)}:function(I,$,z,L){L===void 0&&(L=z),I[L]=$[z]}),f=this&&this.__setModuleDefault||(Object.create?function(I,$){Object.defineProperty(I,"default",{enumerable:!0,value:$})}:function(I,$){I.default=$}),a=this&&this.__importStar||function(I){if(I&&I.__esModule)return I;var $={};if(I!=null)for(var z in I)z!=="default"&&Object.prototype.hasOwnProperty.call(I,z)&&l($,I,z);return f($,I),$};Object.defineProperty(n,"__esModule",{value:!0}),n.endProfiling=n.run=n.releaseSession=n.createSession=n.createSessionFinalize=n.createSessionAllocate=n.initOrt=n.initWasm=void 0;const h=s(1670),p=a(s(349)),u=s(6361),o=()=>!!h.env.wasm.proxy&&typeof document<"u";let t,e,r,i=!1,d=!1,g=!1;const m=[],b=[],y=[],w=[],v=[],S=[],A=()=>{if(i||!d||g||!t)throw new Error("worker not ready")},O=I=>{switch(I.data.type){case"init-wasm":i=!1,I.data.err?(g=!0,e[1](I.data.err)):(d=!0,e[0]());break;case"init-ort":I.data.err?r[1](I.data.err):r[0]();break;case"create_allocate":I.data.err?m.shift()[1](I.data.err):m.shift()[0](I.data.out);break;case"create_finalize":I.data.err?b.shift()[1](I.data.err):b.shift()[0](I.data.out);break;case"create":I.data.err?y.shift()[1](I.data.err):y.shift()[0](I.data.out);break;case"release":I.data.err?w.shift()[1](I.data.err):w.shift()[0]();break;case"run":I.data.err?v.shift()[1](I.data.err):v.shift()[0](I.data.out);break;case"end-profiling":I.data.err?S.shift()[1](I.data.err):S.shift()[0]()}},x=typeof document<"u"?(c=document==null?void 0:document.currentScript)===null||c===void 0?void 0:c.src:void 0;n.initWasm=async()=>{if(o()){if(d)return;if(i)throw new Error("multiple calls to 'initWasm()' detected.");if(g)throw new Error("previous call to 'initWasm()' failed.");return i=!0,h.env.wasm.wasmPaths===void 0&&x&&x.indexOf("blob:")!==0&&(h.env.wasm.wasmPaths=x.substr(0,+x.lastIndexOf("/")+1)),new Promise((I,$)=>{t==null||t.terminate(),t=s(9710).Z(),t.onmessage=O,e=[I,$];const z={type:"init-wasm",in:h.env.wasm};t.postMessage(z)})}return(0,u.initializeWebAssembly)(h.env.wasm)},n.initOrt=async(I,$)=>{if(o())return A(),new Promise((z,L)=>{r=[z,L];const N={type:"init-ort",in:{numThreads:I,loggingLevel:$}};t.postMessage(N)});p.initOrt(I,$)},n.createSessionAllocate=async I=>o()?(A(),new Promise(($,z)=>{m.push([$,z]);const L={type:"create_allocate",in:{model:I}};t.postMessage(L,[I.buffer])})):p.createSessionAllocate(I),n.createSessionFinalize=async(I,$)=>o()?(A(),new Promise((z,L)=>{b.push([z,L]);const N={type:"create_finalize",in:{modeldata:I,options:$}};t.postMessage(N)})):p.createSessionFinalize(I,$),n.createSession=async(I,$)=>o()?(A(),new Promise((z,L)=>{y.push([z,L]);const N={type:"create",in:{model:I,options:$}};t.postMessage(N,[I.buffer])})):p.createSession(I,$),n.releaseSession=async I=>{if(o())return A(),new Promise(($,z)=>{w.push([$,z]);const L={type:"release",in:I};t.postMessage(L)});p.releaseSession(I)},n.run=async(I,$,z,L,N)=>o()?(A(),new Promise((H,M)=>{v.push([H,M]);const j={type:"run",in:{sessionId:I,inputIndices:$,inputs:z,outputIndices:L,options:N}};t.postMessage(j,p.extractTransferableBuffers(z))})):p.run(I,$,z,L,N),n.endProfiling=async I=>{if(o())return A(),new Promise(($,z)=>{S.push([$,z]);const L={type:"end-profiling",in:I};t.postMessage(L)});p.endProfiling(I)}},586:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.setRunOptions=void 0;const c=s(7967),l=s(4983),f=s(6361);n.setRunOptions=a=>{const h=(0,f.getInstance)();let p=0;const u=[],o=a||{};try{if((a==null?void 0:a.logSeverityLevel)===void 0)o.logSeverityLevel=2;else if(typeof a.logSeverityLevel!="number"||!Number.isInteger(a.logSeverityLevel)||a.logSeverityLevel<0||a.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${a.logSeverityLevel}`);if((a==null?void 0:a.logVerbosityLevel)===void 0)o.logVerbosityLevel=0;else if(typeof a.logVerbosityLevel!="number"||!Number.isInteger(a.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${a.logVerbosityLevel}`);(a==null?void 0:a.terminate)===void 0&&(o.terminate=!1);let t=0;if((a==null?void 0:a.tag)!==void 0&&(t=(0,l.allocWasmString)(a.tag,u)),p=h._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,t),p===0)throw new Error("Can't create run options");return(a==null?void 0:a.extra)!==void 0&&(0,c.iterateExtraOptions)(a.extra,"",new WeakSet,(e,r)=>{const i=(0,l.allocWasmString)(e,u),d=(0,l.allocWasmString)(r,u);if(h._OrtAddRunConfigEntry(p,i,d)!==0)throw new Error(`Can't set a run config entry: ${e} - ${r}`)}),[p,u]}catch(t){throw p!==0&&h._OrtReleaseRunOptions(p),u.forEach(h._free),t}}},2306:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.OnnxruntimeWebAssemblySessionHandler=void 0;const c=s(2806),l=s(1670),f=s(2850),a=s(2157);let h;n.OnnxruntimeWebAssemblySessionHandler=class{async createSessionAllocate(p){const u=await fetch(p),o=await u.arrayBuffer();return(0,a.createSessionAllocate)(new Uint8Array(o))}async loadModel(p,u){if(h||(await(0,a.initOrt)(l.env.wasm.numThreads,(o=>{switch(o){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: ${o}`)}})(l.env.logLevel)),h=!0),typeof p=="string")if(typeof fetch>"u"){const o=await(0,f.promisify)(c.readFile)(p);[this.sessionId,this.inputNames,this.outputNames]=await(0,a.createSession)(o,u)}else{const o=await this.createSessionAllocate(p);[this.sessionId,this.inputNames,this.outputNames]=await(0,a.createSessionFinalize)(o,u)}else[this.sessionId,this.inputNames,this.outputNames]=await(0,a.createSession)(p,u)}async dispose(){return(0,a.releaseSession)(this.sessionId)}async run(p,u,o){const t=[],e=[];Object.entries(p).forEach(g=>{const m=g[0],b=g[1],y=this.inputNames.indexOf(m);if(y===-1)throw new Error(`invalid input '${m}'`);t.push(b),e.push(y)});const r=[];Object.entries(u).forEach(g=>{const m=g[0],b=this.outputNames.indexOf(m);if(b===-1)throw new Error(`invalid output '${m}'`);r.push(b)});const i=await(0,a.run)(this.sessionId,e,t.map(g=>[g.type,g.dims,g.data]),r,o),d={};for(let g=0;g{Object.defineProperty(n,"__esModule",{value:!0}),n.setSessionOptions=void 0;const c=s(7967),l=s(4983),f=s(6361);n.setSessionOptions=a=>{const h=(0,f.getInstance)();let p=0;const u=[],o=a||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(o);try{(a==null?void 0:a.graphOptimizationLevel)===void 0&&(o.graphOptimizationLevel="all");const t=(i=>{switch(i){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${i}`)}})(o.graphOptimizationLevel);(a==null?void 0:a.enableCpuMemArena)===void 0&&(o.enableCpuMemArena=!0),(a==null?void 0:a.enableMemPattern)===void 0&&(o.enableMemPattern=!0),(a==null?void 0:a.executionMode)===void 0&&(o.executionMode="sequential");const e=(i=>{switch(i){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${i}`)}})(o.executionMode);let r=0;if((a==null?void 0:a.logId)!==void 0&&(r=(0,l.allocWasmString)(a.logId,u)),(a==null?void 0:a.logSeverityLevel)===void 0)o.logSeverityLevel=2;else if(typeof a.logSeverityLevel!="number"||!Number.isInteger(a.logSeverityLevel)||a.logSeverityLevel<0||a.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${a.logSeverityLevel}`);if((a==null?void 0:a.logVerbosityLevel)===void 0)o.logVerbosityLevel=0;else if(typeof a.logVerbosityLevel!="number"||!Number.isInteger(a.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${a.logVerbosityLevel}`);if((a==null?void 0:a.enableProfiling)===void 0&&(o.enableProfiling=!1),p=h._OrtCreateSessionOptions(t,!!o.enableCpuMemArena,!!o.enableMemPattern,e,!!o.enableProfiling,0,r,o.logSeverityLevel,o.logVerbosityLevel),p===0)throw new Error("Can't create session options");return a!=null&&a.executionProviders&&((i,d,g)=>{for(const m of d){let b=typeof m=="string"?m:m.name;switch(b){case"xnnpack":b="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${b}`)}const y=(0,l.allocWasmString)(b,g);if((0,f.getInstance)()._OrtAppendExecutionProvider(i,y)!==0)throw new Error(`Can't append execution provider: ${b}`)}})(p,a.executionProviders,u),(a==null?void 0:a.extra)!==void 0&&(0,c.iterateExtraOptions)(a.extra,"",new WeakSet,(i,d)=>{const g=(0,l.allocWasmString)(i,u),m=(0,l.allocWasmString)(d,u);if(h._OrtAddSessionConfigEntry(p,g,m)!==0)throw new Error(`Can't set a session config entry: ${i} - ${d}`)}),[p,u]}catch(t){throw p!==0&&h._OrtReleaseSessionOptions(p),u.forEach(h._free),t}}},4983:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.allocWasmString=void 0;const c=s(6361);n.allocWasmString=(l,f)=>{const a=(0,c.getInstance)(),h=a.lengthBytesUTF8(l)+1,p=a._malloc(h);return a.stringToUTF8(l,p,h),f.push(p),p}},349:(_,n,s)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.extractTransferableBuffers=n.endProfiling=n.run=n.releaseSession=n.createSession=n.createSessionFinalize=n.createSessionAllocate=n.initOrt=void 0;const c=s(586),l=s(4919),f=s(4983),a=s(6361);n.initOrt=(t,e)=>{const r=(0,a.getInstance)()._OrtInit(t,e);if(r!==0)throw new Error(`Can't initialize onnxruntime. error code = ${r}`)};const h=new Map;n.createSessionAllocate=t=>{const e=(0,a.getInstance)(),r=e._malloc(t.byteLength);return e.HEAPU8.set(t,r),[r,t.byteLength]},n.createSessionFinalize=(t,e)=>{const r=(0,a.getInstance)();let i=0,d=0,g=[];try{if([d,g]=(0,l.setSessionOptions)(e),i=r._OrtCreateSession(t[0],t[1],d),i===0)throw new Error("Can't create a session")}finally{r._free(t[0]),r._OrtReleaseSessionOptions(d),g.forEach(r._free)}const m=r._OrtGetInputCount(i),b=r._OrtGetOutputCount(i),y=[],w=[],v=[],S=[];for(let A=0;A{const r=(0,n.createSessionAllocate)(t);return(0,n.createSessionFinalize)(r,e)},n.releaseSession=t=>{const e=(0,a.getInstance)(),r=h.get(t);if(!r)throw new Error("invalid session id");const i=r[0],d=r[1],g=r[2];d.forEach(e._OrtFree),g.forEach(e._OrtFree),e._OrtReleaseSession(i),h.delete(t)};const p=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},u=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},o=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};n.run=(t,e,r,i,d)=>{const g=(0,a.getInstance)(),m=h.get(t);if(!m)throw new Error("invalid session id");const b=m[0],y=m[1],w=m[2],v=e.length,S=i.length;let A=0,O=[];const x=[],I=[];try{[A,O]=(0,c.setRunOptions)(d);for(let M=0;Mg.HEAP32[xe++]=we);const oe=g._OrtCreateTensor(p(j),Q,ee,Ae,Z.length);if(oe===0)throw new Error("Can't create a tensor");x.push(oe)}finally{g.stackRestore(ue)}}const $=g.stackSave(),z=g.stackAlloc(4*v),L=g.stackAlloc(4*v),N=g.stackAlloc(4*S),H=g.stackAlloc(4*S);try{let M=z/4,j=L/4,Z=N/4,X=H/4;for(let ue=0;ueOe*ze);if(we=u(Ne),we==="string"){const Oe=[];let ze=ye/4;for(let Ve=0;Ve{const e=(0,a.getInstance)(),r=h.get(t);if(!r)throw new Error("invalid session id");const i=r[0],d=e._OrtEndProfiling(i);if(d===0)throw new Error("Can't get an profile file name");e._OrtFree(d)},n.extractTransferableBuffers=t=>{const e=[];for(const r of t){const i=r[2];!Array.isArray(i)&&i.buffer&&e.push(i.buffer)}return e}},6361:function(_,n,s){var c=this&&this.__createBinding||(Object.create?function(d,g,m,b){b===void 0&&(b=m);var y=Object.getOwnPropertyDescriptor(g,m);y&&!("get"in y?!g.__esModule:y.writable||y.configurable)||(y={enumerable:!0,get:function(){return g[m]}}),Object.defineProperty(d,b,y)}:function(d,g,m,b){b===void 0&&(b=m),d[b]=g[m]}),l=this&&this.__setModuleDefault||(Object.create?function(d,g){Object.defineProperty(d,"default",{enumerable:!0,value:g})}:function(d,g){d.default=g}),f=this&&this.__importStar||function(d){if(d&&d.__esModule)return d;var g={};if(d!=null)for(var m in d)m!=="default"&&Object.prototype.hasOwnProperty.call(d,m)&&c(g,d,m);return l(g,d),g},a=this&&this.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(n,"__esModule",{value:!0}),n.dispose=n.getInstance=n.initializeWebAssembly=void 0;const h=f(s(6449)),p=a(s(932)),u=s(3474);let o,t=!1,e=!1,r=!1;const i=(d,g)=>g?d?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":d?"ort-wasm-simd.wasm":"ort-wasm.wasm";n.initializeWebAssembly=async d=>{if(t)return Promise.resolve();if(e)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(r)throw new Error("previous call to 'initializeWebAssembly()' failed.");e=!0;const g=d.initTimeout,m=d.numThreads,b=d.simd,y=m>1&&(()=>{try{return typeof SharedArrayBuffer<"u"&&(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}})(),w=b&&(()=>{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}})(),v=typeof d.wasmPaths=="string"?d.wasmPaths:void 0,S=i(!1,y),A=i(w,y),O=typeof d.wasmPaths=="object"?d.wasmPaths[A]:void 0;let x=!1;const I=[];if(g>0&&I.push(new Promise($=>{setTimeout(()=>{x=!0,$()},g)})),I.push(new Promise(($,z)=>{const L=y?u:p.default,N={locateFile:(H,M)=>y&&H.endsWith(".worker.js")&&typeof Blob<"u"?URL.createObjectURL(new Blob([s(4154)],{type:"text/javascript"})):H===S?O??(v??M)+A:M+H};if(y)if(typeof Blob>"u")N.mainScriptUrlOrBlob=h.join("/","ort-wasm-threaded.js");else{const H=`var ortWasmThreaded=(function(){var _scriptDir;return ${L.toString()}})();`;N.mainScriptUrlOrBlob=new Blob([H],{type:"text/javascript"})}L(N).then(H=>{e=!1,t=!0,o=H,$()},H=>{e=!1,r=!0,z(H)})})),await Promise.race(I),x)throw new Error(`WebAssembly backend initializing failed due to timeout: ${g}ms`)},n.getInstance=()=>{if(t&&o)return o;throw new Error("WebAssembly is not initialized yet.")},n.dispose=()=>{var d;!t||e||r||(e=!0,(d=o.PThread)===null||d===void 0||d.terminateAllThreads(),o=void 0,e=!1,t=!1,r=!0)}},9710:(_,n,s)=>{s.d(n,{Z:()=>f});var c=s(477),l=s.n(c);function f(){return l()('/*!\n* ONNX Runtime Web v1.14.0\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\n(()=>{var t={474:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){function e(){return j.buffer!=D&&N(j.buffer),P}function r(){return j.buffer!=D&&N(j.buffer),U}function a(){return j.buffer!=D&&N(j.buffer),F}function i(){return j.buffer!=D&&N(j.buffer),I}function o(){return j.buffer!=D&&N(j.buffer),W}var u,c,s;t=t||{},u||(u=void 0!==t?t:{}),u.ready=new Promise((function(t,e){c=t,s=e}));var l,f,p,h,d,y,b=Object.assign({},u),m="./this.program",g=(t,e)=>{throw e},v="object"==typeof window,w="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,O=u.ENVIRONMENT_IS_PTHREAD||!1,A="";function S(t){return u.locateFile?u.locateFile(t,A):A+t}if(_){let e;A=w?n(908).dirname(A)+"/":"//",y=()=>{d||(h=n(384),d=n(908))},l=function(t,e){return y(),t=d.normalize(t),h.readFileSync(t,e?void 0:"utf8")},p=t=>((t=l(t,!0)).buffer||(t=new Uint8Array(t)),t),f=(t,e,n)=>{y(),t=d.normalize(t),h.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(Q())throw process.exitCode=t,e;e instanceof ct||x("exiting due to exception: "+e),process.exit(t)},u.inspect=function(){return"[Emscripten Module object]"};try{e=n(925)}catch(t){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),t}n.g.Worker=e.Worker}else(v||w)&&(w?A=self.location.href:"undefined"!=typeof document&&document.currentScript&&(A=document.currentScript.src),_scriptDir&&(A=_scriptDir),A=0!==A.indexOf("blob:")?A.substr(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(l=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},w&&(p=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),f=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)}));_&&"undefined"==typeof performance&&(n.g.performance=n(953).performance);var T=console.log.bind(console),E=console.warn.bind(console);_&&(y(),T=t=>h.writeSync(1,t+"\\n"),E=t=>h.writeSync(2,t+"\\n"));var M,C=u.print||T,x=u.printErr||E;Object.assign(u,b),b=null,u.thisProgram&&(m=u.thisProgram),u.quit&&(g=u.quit),u.wasmBinary&&(M=u.wasmBinary);var R=u.noExitRuntime||!1;"object"!=typeof WebAssembly&&at("no native wasm support detected");var j,k,D,P,U,F,I,W,H=!1,L="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function z(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function Y(t,e){return(t>>>=0)?z(r(),t,e):""}function B(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var i=0;i=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function G(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function N(t){D=t,u.HEAP8=P=new Int8Array(t),u.HEAP16=new Int16Array(t),u.HEAP32=F=new Int32Array(t),u.HEAPU8=U=new Uint8Array(t),u.HEAPU16=new Uint16Array(t),u.HEAPU32=I=new Uint32Array(t),u.HEAPF32=new Float32Array(t),u.HEAPF64=W=new Float64Array(t)}O&&(D=u.buffer);var V=u.INITIAL_MEMORY||16777216;if(O)j=u.wasmMemory,D=u.buffer;else if(u.wasmMemory)j=u.wasmMemory;else if(!((j=new WebAssembly.Memory({initial:V/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw x("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"),_&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");j&&(D=j.buffer),V=D.byteLength,N(D);var $,q=[],X=[],J=[],Z=[];function Q(){return R||!1}function K(){var t=u.preRun.shift();q.unshift(t)}var tt,et=0,nt=null,rt=null;function at(t){throw O?postMessage({cmd:"onAbort",arg:t}):u.onAbort&&u.onAbort(t),x(t="Aborted("+t+")"),H=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),s(t),t}function it(){return tt.startsWith("data:application/octet-stream;base64,")}function ot(){var t=tt;try{if(t==tt&&M)return new Uint8Array(M);if(p)return p(t);throw"both async and sync fetching of the wasm failed"}catch(t){at(t)}}tt="ort-wasm-threaded.wasm",it()||(tt=S(tt));var ut={};function ct(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function st(t){(t=ht.Vb[t])||at(),ht.mc(t)}function lt(t){var e=ht.Cc();if(!e)return 6;ht.ac.push(e),ht.Vb[t.Ub]=e,e.Ub=t.Ub;var n={cmd:"run",start_routine:t.Ic,arg:t.zc,pthread_ptr:t.Ub};return e.$b=()=>{n.time=performance.now(),e.postMessage(n,t.Nc)},e.loaded&&(e.$b(),delete e.$b),0}function ft(t){if(O)return $t(1,1,t);Q()||(ht.oc(),u.onExit&&u.onExit(t),H=!0),g(t,new ct(t))}function pt(t,e){if(!e&&O)throw bt(t),"unwind";Q()||O||(me(),dt(J),be(0),re[1].length&&ae(1,10),re[2].length&&ae(2,10),ht.oc()),ft(t)}var ht={Yb:[],ac:[],qc:[],Vb:{},fc:function(){O&&ht.Ec()},Pc:function(){},Ec:function(){ht.receiveObjectTransfer=ht.Gc,ht.threadInitTLS=ht.pc,ht.setExitStatus=ht.nc,R=!1},nc:function(){},oc:function(){for(var t of Object.values(ht.Vb))ht.mc(t);for(t of ht.Yb)t.terminate();ht.Yb=[]},mc:function(t){var e=t.Ub;delete ht.Vb[e],ht.Yb.push(t),ht.ac.splice(ht.ac.indexOf(t),1),t.Ub=0,Oe(e)},Gc:function(){},pc:function(){ht.qc.forEach((t=>t()))},Fc:function(t,e){t.onmessage=n=>{var r=(n=n.data).cmd;if(t.Ub&&(ht.Bc=t.Ub),n.targetThread&&n.targetThread!=he()){var a=ht.Vb[n.Qc];a?a.postMessage(n,n.transferList):x(\'Internal error! Worker sent a message "\'+r+\'" to target pthread \'+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?zt(n.queue):"spawnThread"===r?lt(n):"cleanupThread"===r?st(n.thread):"killThread"===r?(n=n.thread,r=ht.Vb[n],delete ht.Vb[n],r.terminate(),Oe(n),ht.ac.splice(ht.ac.indexOf(r),1),r.Ub=0):"cancelThread"===r?ht.Vb[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(t.loaded=!0,e&&e(t),t.$b&&(t.$b(),delete t.$b)):"print"===r?C("Thread "+n.threadId+": "+n.text):"printErr"===r?x("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?t.postMessage(n):"onAbort"===r?u.onAbort&&u.onAbort(n.arg):r&&x("worker sent an unknown command "+r);ht.Bc=void 0},t.onerror=t=>{throw x("worker sent an error! "+t.filename+":"+t.lineno+": "+t.message),t},_&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){}))),t.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||_scriptDir,wasmMemory:j,wasmModule:k})},yc:function(){var t=S("ort-wasm-threaded.worker.js");ht.Yb.push(new Worker(t))},Cc:function(){return 0==ht.Yb.length&&(ht.yc(),ht.Fc(ht.Yb[0])),ht.Yb.pop()}};function dt(t){for(;0>2>>>0];t=a()[t+48>>2>>>0],Te(e,e-t),Me(e)};var mt=[];function gt(t){var e=mt[t];return e||(t>=mt.length&&(mt.length=t+1),mt[t]=e=$.get(t)),e}u.invokeEntryPoint=function(t,e){t=gt(t)(e),Q()?ht.nc(t):Ae(t)};var vt,wt,_t=[],Ot=0,At=0;function St(t){this.Zb=t,this.Sb=t-24,this.xc=function(t){i()[this.Sb+4>>2>>>0]=t},this.bc=function(){return i()[this.Sb+4>>2>>>0]},this.wc=function(t){i()[this.Sb+8>>2>>>0]=t},this.Dc=function(){return i()[this.Sb+8>>2>>>0]},this.rc=function(){a()[this.Sb>>2>>>0]=0},this.hc=function(t){t=t?1:0,e()[this.Sb+12>>0>>>0]=t},this.uc=function(){return 0!=e()[this.Sb+12>>0>>>0]},this.ic=function(t){t=t?1:0,e()[this.Sb+13>>0>>>0]=t},this.kc=function(){return 0!=e()[this.Sb+13>>0>>>0]},this.fc=function(t,e){this.cc(0),this.xc(t),this.wc(e),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(a(),this.Sb>>2,1)},this.Hc=function(){return 1===Atomics.sub(a(),this.Sb>>2,1)},this.cc=function(t){i()[this.Sb+16>>2>>>0]=t},this.tc=function(){return i()[this.Sb+16>>2>>>0]},this.vc=function(){if(Re(this.bc()))return i()[this.Zb>>2>>>0];var t=this.tc();return 0!==t?t:this.Zb}}function Tt(t){return ye(new St(t).Sb)}function Et(t,e,n,r){return O?$t(3,1,t,e,n,r):Mt(t,e,n,r)}function Mt(t,e,n,r){if("undefined"==typeof SharedArrayBuffer)return x("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];return O&&0===a.length?Et(t,e,n,r):(t={Ic:n,Ub:t,zc:r,Nc:a},O?(t.Oc="spawnThread",postMessage(t,a),0):lt(t))}function Ct(t,e,n){return O?$t(4,1,t,e,n):0}function xt(t,e){if(O)return $t(5,1,t,e)}function Rt(t,e){if(O)return $t(6,1,t,e)}function jt(t,e,n){if(O)return $t(7,1,t,e,n)}function kt(t,e,n){return O?$t(8,1,t,e,n):0}function Dt(t,e){if(O)return $t(9,1,t,e)}function Pt(t,e,n){if(O)return $t(10,1,t,e,n)}function Ut(t,e,n,r){if(O)return $t(11,1,t,e,n,r)}function Ft(t,e,n,r){if(O)return $t(12,1,t,e,n,r)}function It(t,e,n,r){if(O)return $t(13,1,t,e,n,r)}function Wt(t){if(O)return $t(14,1,t)}function Ht(t,e){if(O)return $t(15,1,t,e)}function Lt(t,e,n){if(O)return $t(16,1,t,e,n)}function zt(t){Atomics.store(a(),t>>2,1),he()&&_e(t),Atomics.compareExchange(a(),t>>2,1,0)}function Yt(t){return i()[t>>>2]+4294967296*a()[t+4>>>2]}function Bt(t,e,n,r,a,i){return O?$t(17,1,t,e,n,r,a,i):-52}function Gt(t,e,n,r,a,i){if(O)return $t(18,1,t,e,n,r,a,i)}function Nt(t){var n=G(t)+1,r=de(n);return r&&B(t,e(),r,n),r}function Vt(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}if(O)return $t(19,1,t,e,n);var o=(new Date).getFullYear(),u=new Date(o,0,1),c=new Date(o,6,1);o=u.getTimezoneOffset();var s=c.getTimezoneOffset(),l=Math.max(o,s);a()[t>>2>>>0]=60*l,a()[e>>2>>>0]=Number(o!=s),t=r(u),e=r(c),t=Nt(t),e=Nt(e),s>2>>>0]=t,i()[n+4>>2>>>0]=e):(i()[n>>2>>>0]=e,i()[n+4>>2>>>0]=t)}function $t(t,e){var n=arguments.length-2,r=arguments;return yt((()=>{for(var a=Ce(8*n),i=a>>3,u=0;u>>0]=c}return we(t,n,a,e)}))}u.executeNotifiedProxyingQueue=zt,wt=_?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:O?()=>performance.now()-u.__performance_now_clock_drift:()=>performance.now();var qt,Xt=[],Jt={};function Zt(){if(!qt){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:m||"./this.program"};for(t in Jt)void 0===Jt[t]?delete e[t]:e[t]=Jt[t];var n=[];for(t in e)n.push(t+"="+e[t]);qt=n}return qt}function Qt(t,n){if(O)return $t(20,1,t,n);var r=0;return Zt().forEach((function(a,o){var u=n+r;for(o=i()[t+4*o>>2>>>0]=u,u=0;u>0>>>0]=a.charCodeAt(u);e()[o>>0>>>0]=0,r+=a.length+1})),0}function Kt(t,e){if(O)return $t(21,1,t,e);var n=Zt();i()[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),i()[e>>2>>>0]=r,0}function te(t){return O?$t(22,1,t):52}function ee(t,e,n,r){return O?$t(23,1,t,e,n,r):52}function ne(t,e,n,r,a){return O?$t(24,1,t,e,n,r,a):70}var re=[null,[],[]];function ae(t,e){var n=re[t];0===e||10===e?((1===t?C:x)(z(n,0)),n.length=0):n.push(e)}function ie(t,e,n,a){if(O)return $t(25,1,t,e,n,a);for(var o=0,u=0;u>2>>>0],s=i()[e+4>>2>>>0];e+=8;for(var l=0;l>>0]);o+=s}return i()[a>>2>>>0]=o,0}var oe=0;function ue(t){return 0==t%4&&(0!=t%100||0==t%400)}var ce=[31,29,31,30,31,30,31,31,30,31,30,31],se=[31,28,31,30,31,30,31,31,30,31,30,31];function le(t,n,r,i){function o(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=s(new Date(t.getFullYear(),0,4)),n=s(n),0>=c(e,t)?0>=c(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var f=a()[i+40>>2>>>0];for(var p in i={Lc:a()[i>>2>>>0],Kc:a()[i+4>>2>>>0],dc:a()[i+8>>2>>>0],jc:a()[i+12>>2>>>0],ec:a()[i+16>>2>>>0],Xb:a()[i+20>>2>>>0],Tb:a()[i+24>>2>>>0],Wb:a()[i+28>>2>>>0],Rc:a()[i+32>>2>>>0],Jc:a()[i+36>>2>>>0],Mc:f?Y(f):""},r=Y(r),f={"%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"})r=r.replace(new RegExp(p,"g"),f[p]);var h="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),d="January February March April May June July August September October November December".split(" ");for(p in f={"%a":function(t){return h[t.Tb].substring(0,3)},"%A":function(t){return h[t.Tb]},"%b":function(t){return d[t.ec].substring(0,3)},"%B":function(t){return d[t.ec]},"%C":function(t){return u((t.Xb+1900)/100|0,2)},"%d":function(t){return u(t.jc,2)},"%e":function(t){return o(t.jc,2," ")},"%g":function(t){return l(t).toString().substring(2)},"%G":function(t){return l(t)},"%H":function(t){return u(t.dc,2)},"%I":function(t){return 0==(t=t.dc)?t=12:12t.dc?"AM":"PM"},"%S":function(t){return u(t.Lc,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Tb||7},"%U":function(t){return u(Math.floor((t.Wb+7-t.Tb)/7),2)},"%V":function(t){var e=Math.floor((t.Wb+7-(t.Tb+6)%7)/7);if(2>=(t.Tb+371-t.Wb-2)%7&&e++,e)53==e&&(4==(n=(t.Tb+371-t.Wb)%7)||3==n&&ue(t.Xb)||(e=1));else{e=52;var n=(t.Tb+7-t.Wb-1)%7;(4==n||5==n&&ue(t.Xb%400-1))&&e++}return u(e,2)},"%w":function(t){return t.Tb},"%W":function(t){return u(Math.floor((t.Wb+7-(t.Tb+6)%7)/7),2)},"%y":function(t){return(t.Xb+1900).toString().substring(2)},"%Y":function(t){return t.Xb+1900},"%z":function(t){var e=0<=(t=t.Jc);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.Mc},"%%":function(){return"%"}},r=r.replace(/%%/g,"\\0\\0"),f)r.includes(p)&&(r=r.replace(new RegExp(p,"g"),f[p](i)));return p=function(t){var e=Array(G(t)+1);return B(t,e,0,e.length),e}(r=r.replace(/\\0\\0/g,"%")),p.length>n?0:(function(t,n){e().set(t,n>>>0)}(p,t),p.length-1)}ht.fc();var fe=[null,ft,bt,Et,Ct,xt,Rt,jt,kt,Dt,Pt,Ut,Ft,It,Wt,Ht,Lt,Bt,Gt,Vt,Qt,Kt,te,ee,ne,ie],pe={b:function(t){return de(t+24)+24},n:function(t){return(t=new St(t)).uc()||(t.hc(!0),Ot--),t.ic(!1),_t.push(t),t.sc(),t.vc()},ma:function(t){throw x("Unexpected exception thrown, this is not properly supported - aborting"),H=!0,t},x:function(){Se(0);var t=_t.pop();if(t.Hc()&&!t.kc()){var e=t.Dc();e&>(e)(t.Zb),Tt(t.Zb)}At=0},e:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;azt(r)));else if(O)postMessage({targetThread:t,cmd:"processProxyingQueue",queue:r});else{if(!(t=ht.Vb[t]))return;t.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},Ea:function(){return-1},Pa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getUTCSeconds(),a()[e+4>>2>>>0]=t.getUTCMinutes(),a()[e+8>>2>>>0]=t.getUTCHours(),a()[e+12>>2>>>0]=t.getUTCDate(),a()[e+16>>2>>>0]=t.getUTCMonth(),a()[e+20>>2>>>0]=t.getUTCFullYear()-1900,a()[e+24>>2>>>0]=t.getUTCDay(),t=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[e+28>>2>>>0]=t},Qa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getSeconds(),a()[e+4>>2>>>0]=t.getMinutes(),a()[e+8>>2>>>0]=t.getHours(),a()[e+12>>2>>>0]=t.getDate(),a()[e+16>>2>>>0]=t.getMonth(),a()[e+20>>2>>>0]=t.getFullYear()-1900,a()[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1),r=(t.getTime()-n.getTime())/864e5|0;a()[e+28>>2>>>0]=r,a()[e+36>>2>>>0]=-60*t.getTimezoneOffset(),r=new Date(t.getFullYear(),6,1).getTimezoneOffset(),t=0|(r!=(n=n.getTimezoneOffset())&&t.getTimezoneOffset()==Math.min(n,r)),a()[e+32>>2>>>0]=t},Ra:function(t){var e=new Date(a()[t+20>>2>>>0]+1900,a()[t+16>>2>>>0],a()[t+12>>2>>>0],a()[t+8>>2>>>0],a()[t+4>>2>>>0],a()[t>>2>>>0],0),n=a()[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),o=new Date(e.getFullYear(),6,1).getTimezoneOffset(),u=i.getTimezoneOffset(),c=Math.min(u,o);return 0>n?a()[t+32>>2>>>0]=Number(o!=u&&c==r):0>2>>>0]=e.getDay(),n=(e.getTime()-i.getTime())/864e5|0,a()[t+28>>2>>>0]=n,a()[t>>2>>>0]=e.getSeconds(),a()[t+4>>2>>>0]=e.getMinutes(),a()[t+8>>2>>>0]=e.getHours(),a()[t+12>>2>>>0]=e.getDate(),a()[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},Aa:Bt,Ba:Gt,Sa:function t(e,n,r){t.Ac||(t.Ac=!0,Vt(e,n,r))},y:function(){at("")},U:function(){if(!_&&!w){var t="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";vt||(vt={}),vt[t]||(vt[t]=1,_&&(t="warning: "+t),x(t))}},ra:function(){return 4294901760},B:wt,Ia:function(t,e,n){r().copyWithin(t>>>0,e>>>0,e+n>>>0)},F:function(){return _?n(993).cpus().length:navigator.hardwareConcurrency},Da:function(t,e,n){Xt.length=e,n>>=3;for(var r=0;r>>0];return(0>t?ut[-t-1]:fe[t]).apply(null,Xt)},qa:function(t){var e=r().length;if((t>>>=0)<=e||4294901760=n;n*=2){var a=e*(1+.2/n);a=Math.min(a,t+100663296);var i=Math;a=Math.max(t,a),i=i.min.call(i,4294901760,a+(65536-a%65536)%65536);t:{try{j.grow(i-D.byteLength+65535>>>16),N(j.buffer);var o=1;break t}catch(t){}o=void 0}if(o)return!0}return!1},Na:function(){throw"unwind"},Ga:Qt,Ha:Kt,J:pt,I:te,S:ee,ga:ne,R:ie,d:function(){return oe},na:function t(r,a){t.lc||(t.lc=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(_)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>at("randomDevice")}());for(var i=0;i>0>>>0]=t.lc();return 0},ia:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ja:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},K:function(t){var e=Ee();try{return gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},f:function(t,e){var n=Ee();try{return gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},P:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},Q:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},k:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},p:function(t,e,n,r){var a=Ee();try{return gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},q:function(t,e,n,r,a){var i=Ee();try{return gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},N:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},s:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},w:function(t,e,n,r,a,i,o){var u=Ee();try{return gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},L:function(t,e,n,r,a,i,o,u){var c=Ee();try{return gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},E:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{return gt(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=Ee();try{return He(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},_:function(t,e,n,r,a,i,o){var u=Ee();try{return ke(t,e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},Z:function(t,e,n,r,a){var i=Ee();try{return Le(t,e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},ca:function(t,e,n,r){var a=Ee();try{return Ie(t,e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},$:function(t){var e=Ee();try{return je(t)}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},ba:function(t,e){var n=Ee();try{return We(t,e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},Y:function(t,e,n){var r=Ee();try{return De(t,e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},g:function(t){var e=Ee();try{gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},r:function(t,e){var n=Ee();try{gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},i:function(t,e,n){var r=Ee();try{gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ha:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},m:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},v:function(t,e,n,r,a){var i=Ee();try{gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},u:function(t,e,n,r,a,i){var o=Ee();try{gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},O:function(t,e,n,r,a,i,o){var u=Ee();try{gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},A:function(t,e,n,r,a,i,o,u){var c=Ee();try{gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},ka:function(t,e,n,r,a,i,o,u,c){var s=Ee();try{gt(t)(e,n,r,a,i,o,u,c)}catch(t){if(Me(s),t!==t+0)throw t;Se(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l){var f=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(Me(f),t!==t+0)throw t;Se(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(Me(b),t!==t+0)throw t;Se(1,0)}},fa:function(t,e,n,r,a,i,o,u){var c=Ee();try{Pe(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},da:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{Fe(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},ea:function(t,e,n,r,a,i){var o=Ee();try{Ue(t,e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},o:function(t){return t},a:j||u.wasmMemory,G:function(t){oe=t},la:le,z:function(t,e,n,r){return le(t,e,n,r)}};!function(){function t(t,e){u.asm=t.exports,ht.qc.push(u.asm.sb),$=u.asm.ub,X.unshift(u.asm.Va),k=e,O||(et--,u.monitorRunDependencies&&u.monitorRunDependencies(et),0==et&&(null!==nt&&(clearInterval(nt),nt=null),rt&&(t=rt,rt=null,t())))}function e(e){t(e.instance,e.module)}function n(t){return function(){if(!M&&(v||w)){if("function"==typeof fetch&&!tt.startsWith("file://"))return fetch(tt,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+tt+"\'";return t.arrayBuffer()})).catch((function(){return ot()}));if(f)return new Promise((function(t,e){f(tt,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return ot()}))}().then((function(t){return WebAssembly.instantiate(t,r)})).then((function(t){return t})).then(t,(function(t){x("failed to asynchronously prepare wasm: "+t),at(t)}))}var r={a:pe};if(O||(et++,u.monitorRunDependencies&&u.monitorRunDependencies(et)),u.instantiateWasm)try{return u.instantiateWasm(r,t)}catch(t){return x("Module.instantiateWasm callback failed with error: "+t),!1}(M||"function"!=typeof WebAssembly.instantiateStreaming||it()||tt.startsWith("file://")||_||"function"!=typeof fetch?n(e):fetch(tt,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,r).then(e,(function(t){return x("wasm streaming compile failed: "+t),x("falling back to ArrayBuffer instantiation"),n(e)}))}))).catch(s)}(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm.Va).apply(null,arguments)},u._OrtInit=function(){return(u._OrtInit=u.asm.Wa).apply(null,arguments)},u._OrtCreateSessionOptions=function(){return(u._OrtCreateSessionOptions=u.asm.Xa).apply(null,arguments)},u._OrtAppendExecutionProvider=function(){return(u._OrtAppendExecutionProvider=u.asm.Ya).apply(null,arguments)},u._OrtAddSessionConfigEntry=function(){return(u._OrtAddSessionConfigEntry=u.asm.Za).apply(null,arguments)},u._OrtReleaseSessionOptions=function(){return(u._OrtReleaseSessionOptions=u.asm._a).apply(null,arguments)},u._OrtCreateSession=function(){return(u._OrtCreateSession=u.asm.$a).apply(null,arguments)},u._OrtReleaseSession=function(){return(u._OrtReleaseSession=u.asm.ab).apply(null,arguments)},u._OrtGetInputCount=function(){return(u._OrtGetInputCount=u.asm.bb).apply(null,arguments)},u._OrtGetOutputCount=function(){return(u._OrtGetOutputCount=u.asm.cb).apply(null,arguments)},u._OrtGetInputName=function(){return(u._OrtGetInputName=u.asm.db).apply(null,arguments)},u._OrtGetOutputName=function(){return(u._OrtGetOutputName=u.asm.eb).apply(null,arguments)},u._OrtFree=function(){return(u._OrtFree=u.asm.fb).apply(null,arguments)},u._OrtCreateTensor=function(){return(u._OrtCreateTensor=u.asm.gb).apply(null,arguments)},u._OrtGetTensorData=function(){return(u._OrtGetTensorData=u.asm.hb).apply(null,arguments)},u._OrtReleaseTensor=function(){return(u._OrtReleaseTensor=u.asm.ib).apply(null,arguments)},u._OrtCreateRunOptions=function(){return(u._OrtCreateRunOptions=u.asm.jb).apply(null,arguments)},u._OrtAddRunConfigEntry=function(){return(u._OrtAddRunConfigEntry=u.asm.kb).apply(null,arguments)},u._OrtReleaseRunOptions=function(){return(u._OrtReleaseRunOptions=u.asm.lb).apply(null,arguments)},u._OrtRun=function(){return(u._OrtRun=u.asm.mb).apply(null,arguments)},u._OrtEndProfiling=function(){return(u._OrtEndProfiling=u.asm.nb).apply(null,arguments)};var he=u._pthread_self=function(){return(he=u._pthread_self=u.asm.ob).apply(null,arguments)},de=u._malloc=function(){return(de=u._malloc=u.asm.pb).apply(null,arguments)},ye=u._free=function(){return(ye=u._free=u.asm.qb).apply(null,arguments)},be=u._fflush=function(){return(be=u._fflush=u.asm.rb).apply(null,arguments)};u.__emscripten_tls_init=function(){return(u.__emscripten_tls_init=u.asm.sb).apply(null,arguments)};var me=u.___funcs_on_exit=function(){return(me=u.___funcs_on_exit=u.asm.tb).apply(null,arguments)},ge=u.__emscripten_thread_init=function(){return(ge=u.__emscripten_thread_init=u.asm.vb).apply(null,arguments)};u.__emscripten_thread_crashed=function(){return(u.__emscripten_thread_crashed=u.asm.wb).apply(null,arguments)};var ve,we=u._emscripten_run_in_main_runtime_thread_js=function(){return(we=u._emscripten_run_in_main_runtime_thread_js=u.asm.xb).apply(null,arguments)},_e=u.__emscripten_proxy_execute_task_queue=function(){return(_e=u.__emscripten_proxy_execute_task_queue=u.asm.yb).apply(null,arguments)},Oe=u.__emscripten_thread_free_data=function(){return(Oe=u.__emscripten_thread_free_data=u.asm.zb).apply(null,arguments)},Ae=u.__emscripten_thread_exit=function(){return(Ae=u.__emscripten_thread_exit=u.asm.Ab).apply(null,arguments)},Se=u._setThrew=function(){return(Se=u._setThrew=u.asm.Bb).apply(null,arguments)},Te=u._emscripten_stack_set_limits=function(){return(Te=u._emscripten_stack_set_limits=u.asm.Cb).apply(null,arguments)},Ee=u.stackSave=function(){return(Ee=u.stackSave=u.asm.Db).apply(null,arguments)},Me=u.stackRestore=function(){return(Me=u.stackRestore=u.asm.Eb).apply(null,arguments)},Ce=u.stackAlloc=function(){return(Ce=u.stackAlloc=u.asm.Fb).apply(null,arguments)},xe=u.___cxa_can_catch=function(){return(xe=u.___cxa_can_catch=u.asm.Gb).apply(null,arguments)},Re=u.___cxa_is_pointer_type=function(){return(Re=u.___cxa_is_pointer_type=u.asm.Hb).apply(null,arguments)},je=u.dynCall_j=function(){return(je=u.dynCall_j=u.asm.Ib).apply(null,arguments)},ke=u.dynCall_iiiiij=function(){return(ke=u.dynCall_iiiiij=u.asm.Jb).apply(null,arguments)},De=u.dynCall_jii=function(){return(De=u.dynCall_jii=u.asm.Kb).apply(null,arguments)},Pe=u.dynCall_viiiiij=function(){return(Pe=u.dynCall_viiiiij=u.asm.Lb).apply(null,arguments)},Ue=u.dynCall_vjji=function(){return(Ue=u.dynCall_vjji=u.asm.Mb).apply(null,arguments)},Fe=u.dynCall_viiijjjii=function(){return(Fe=u.dynCall_viiijjjii=u.asm.Nb).apply(null,arguments)},Ie=u.dynCall_iij=function(){return(Ie=u.dynCall_iij=u.asm.Ob).apply(null,arguments)},We=u.dynCall_ji=function(){return(We=u.dynCall_ji=u.asm.Pb).apply(null,arguments)},He=u.dynCall_iiiiiij=function(){return(He=u.dynCall_iiiiiij=u.asm.Qb).apply(null,arguments)},Le=u.dynCall_iiij=function(){return(Le=u.dynCall_iiij=u.asm.Rb).apply(null,arguments)};function ze(){function t(){if(!ve&&(ve=!0,u.calledRun=!0,!H)&&(O||dt(X),c(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),!O)){if(u.postRun)for("function"==typeof u.postRun&&(u.postRun=[u.postRun]);u.postRun.length;){var t=u.postRun.shift();Z.unshift(t)}dt(Z)}}if(!(0{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){var e,r,a;t=t||{},e||(e=void 0!==t?t:{}),e.ready=new Promise((function(t,e){r=t,a=e}));var i,o,u,c,s,l,f=Object.assign({},e),p="./this.program",h=(t,e)=>{throw e},d="object"==typeof window,y="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";b?(m=y?n(908).dirname(m)+"/":"//",l=()=>{s||(c=n(384),s=n(908))},i=function(t,e){return l(),t=s.normalize(t),c.readFileSync(t,e?void 0:"utf8")},u=t=>((t=i(t,!0)).buffer||(t=new Uint8Array(t)),t),o=(t,e,n)=>{l(),t=s.normalize(t),c.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(_||0{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},y&&(u=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),o=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)});var g,v=e.print||console.log.bind(console),w=e.printErr||console.warn.bind(console);Object.assign(e,f),f=null,e.thisProgram&&(p=e.thisProgram),e.quit&&(h=e.quit),e.wasmBinary&&(g=e.wasmBinary);var _=e.noExitRuntime||!1;"object"!=typeof WebAssembly&&V("no native wasm support detected");var O,A,S,T,E,M,C=!1,x="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function R(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function j(t,e){return(t>>>=0)?R(T,t,e):""}function k(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var i=0;i=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function D(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function P(){var t=O.buffer;A=t,e.HEAP8=S=new Int8Array(t),e.HEAP16=new Int16Array(t),e.HEAP32=E=new Int32Array(t),e.HEAPU8=T=new Uint8Array(t),e.HEAPU16=new Uint16Array(t),e.HEAPU32=M=new Uint32Array(t),e.HEAPF32=new Float32Array(t),e.HEAPF64=new Float64Array(t)}var U,F=[],I=[],W=[],H=[],L=0;function z(){var t=e.preRun.shift();F.unshift(t)}var Y,B=0,G=null,N=null;function V(t){throw e.onAbort&&e.onAbort(t),w(t="Aborted("+t+")"),C=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),a(t),t}function $(){return Y.startsWith("data:application/octet-stream;base64,")}if(Y="ort-wasm.wasm",!$()){var q=Y;Y=e.locateFile?e.locateFile(q,m):m+q}function X(){var t=Y;try{if(t==Y&&g)return new Uint8Array(g);if(u)return u(t);throw"both async and sync fetching of the wasm failed"}catch(t){V(t)}}function J(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function Z(t){for(;0>2>>>0]=t},this.Eb=function(){return M[this.zb+4>>2>>>0]},this.Sb=function(t){M[this.zb+8>>2>>>0]=t},this.Wb=function(){return M[this.zb+8>>2>>>0]},this.Tb=function(){E[this.zb>>2>>>0]=0},this.Ib=function(t){S[this.zb+12>>0>>>0]=t?1:0},this.Pb=function(){return 0!=S[this.zb+12>>0>>>0]},this.Jb=function(t){S[this.zb+13>>0>>>0]=t?1:0},this.Lb=function(){return 0!=S[this.zb+13>>0>>>0]},this.Rb=function(t,e){this.Fb(0),this.Ub(t),this.Sb(e),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){E[this.zb>>2>>>0]+=1},this.Xb=function(){var t=E[this.zb>>2>>>0];return E[this.zb>>2>>>0]=t-1,1===t},this.Fb=function(t){M[this.zb+16>>2>>>0]=t},this.Ob=function(){return M[this.zb+16>>2>>>0]},this.Qb=function(){if(Mt(this.Eb()))return M[this.Db>>2>>>0];var t=this.Ob();return 0!==t?t:this.Db}}function nt(t){return vt(new et(t).zb)}var rt=[];function at(t){var e=rt[t];return e||(t>=rt.length&&(rt.length=t+1),rt[t]=e=U.get(t)),e}function it(t){var e=D(t)+1,n=gt(e);return n&&k(t,S,n,e),n}var ot={};function ut(){if(!ct){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"};for(t in ot)void 0===ot[t]?delete e[t]:e[t]=ot[t];var n=[];for(t in e)n.push(t+"="+e[t]);ct=n}return ct}var ct,st=[null,[],[]];function lt(t,e){var n=st[t];0===e||10===e?((1===t?v:w)(R(n,0)),n.length=0):n.push(e)}var ft=0;function pt(t){return 0==t%4&&(0!=t%100||0==t%400)}var ht=[31,29,31,30,31,30,31,31,30,31,30,31],dt=[31,28,31,30,31,30,31,31,30,31,30,31];function yt(t,e,n,r){function a(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=u(new Date(t.getFullYear(),0,4)),n=u(n),0>=o(e,t)?0>=o(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var s=E[r+40>>2>>>0];for(var l in r={$b:E[r>>2>>>0],Zb:E[r+4>>2>>>0],Gb:E[r+8>>2>>>0],Kb:E[r+12>>2>>>0],Hb:E[r+16>>2>>>0],Cb:E[r+20>>2>>>0],Ab:E[r+24>>2>>>0],Bb:E[r+28>>2>>>0],bc:E[r+32>>2>>>0],Yb:E[r+36>>2>>>0],ac:s?j(s):""},n=j(n),s={"%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"})n=n.replace(new RegExp(l,"g"),s[l]);var f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),p="January February March April May June July August September October November December".split(" ");for(l in s={"%a":function(t){return f[t.Ab].substring(0,3)},"%A":function(t){return f[t.Ab]},"%b":function(t){return p[t.Hb].substring(0,3)},"%B":function(t){return p[t.Hb]},"%C":function(t){return i((t.Cb+1900)/100|0,2)},"%d":function(t){return i(t.Kb,2)},"%e":function(t){return a(t.Kb,2," ")},"%g":function(t){return c(t).toString().substring(2)},"%G":function(t){return c(t)},"%H":function(t){return i(t.Gb,2)},"%I":function(t){return 0==(t=t.Gb)?t=12:12t.Gb?"AM":"PM"},"%S":function(t){return i(t.$b,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Ab||7},"%U":function(t){return i(Math.floor((t.Bb+7-t.Ab)/7),2)},"%V":function(t){var e=Math.floor((t.Bb+7-(t.Ab+6)%7)/7);if(2>=(t.Ab+371-t.Bb-2)%7&&e++,e)53==e&&(4==(n=(t.Ab+371-t.Bb)%7)||3==n&&pt(t.Cb)||(e=1));else{e=52;var n=(t.Ab+7-t.Bb-1)%7;(4==n||5==n&&pt(t.Cb%400-1))&&e++}return i(e,2)},"%w":function(t){return t.Ab},"%W":function(t){return i(Math.floor((t.Bb+7-(t.Ab+6)%7)/7),2)},"%y":function(t){return(t.Cb+1900).toString().substring(2)},"%Y":function(t){return t.Cb+1900},"%z":function(t){var e=0<=(t=t.Yb);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.ac},"%%":function(){return"%"}},n=n.replace(/%%/g,"\\0\\0"),s)n.includes(l)&&(n=n.replace(new RegExp(l,"g"),s[l](r)));return l=function(t){var e=Array(D(t)+1);return k(t,e,0,e.length),e}(n=n.replace(/\\0\\0/g,"%")),l.length>e?0:(S.set(l,t>>>0),l.length-1)}var bt={a:function(t){return gt(t+24)+24},m:function(t){return(t=new et(t)).Pb()||(t.Ib(!0),K--),t.Jb(!1),Q.push(t),t.Nb(),t.Qb()},ia:function(t){throw w("Unexpected exception thrown, this is not properly supported - aborting"),C=!0,t},w:function(){Ot(0);var t=Q.pop();if(t.Xb()&&!t.Lb()){var e=t.Wb();e&&at(e)(t.Db),nt(t.Db)}tt=0},d:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getUTCSeconds(),E[e+4>>2>>>0]=t.getUTCMinutes(),E[e+8>>2>>>0]=t.getUTCHours(),E[e+12>>2>>>0]=t.getUTCDate(),E[e+16>>2>>>0]=t.getUTCMonth(),E[e+20>>2>>>0]=t.getUTCFullYear()-1900,E[e+24>>2>>>0]=t.getUTCDay(),E[e+28>>2>>>0]=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(t,e){t=new Date(1e3*(M[t>>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getSeconds(),E[e+4>>2>>>0]=t.getMinutes(),E[e+8>>2>>>0]=t.getHours(),E[e+12>>2>>>0]=t.getDate(),E[e+16>>2>>>0]=t.getMonth(),E[e+20>>2>>>0]=t.getFullYear()-1900,E[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1);E[e+28>>2>>>0]=(t.getTime()-n.getTime())/864e5|0,E[e+36>>2>>>0]=-60*t.getTimezoneOffset();var r=new Date(t.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),E[e+32>>2>>>0]=0|(r!=n&&t.getTimezoneOffset()==Math.min(n,r))},Fa:function(t){var e=new Date(E[t+20>>2>>>0]+1900,E[t+16>>2>>>0],E[t+12>>2>>>0],E[t+8>>2>>>0],E[t+4>>2>>>0],E[t>>2>>>0],0),n=E[t+32>>2>>>0],r=e.getTimezoneOffset(),a=new Date(e.getFullYear(),0,1),i=new Date(e.getFullYear(),6,1).getTimezoneOffset(),o=a.getTimezoneOffset(),u=Math.min(o,i);return 0>n?E[t+32>>2>>>0]=Number(i!=o&&u==r):0>2>>>0]=e.getDay(),E[t+28>>2>>>0]=(e.getTime()-a.getTime())/864e5|0,E[t>>2>>>0]=e.getSeconds(),E[t+4>>2>>>0]=e.getMinutes(),E[t+8>>2>>>0]=e.getHours(),E[t+12>>2>>>0]=e.getDate(),E[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function t(e,n,r){t.Vb||(t.Vb=!0,function(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}var a=(new Date).getFullYear(),i=new Date(a,0,1),o=new Date(a,6,1);a=i.getTimezoneOffset();var u=o.getTimezoneOffset();E[t>>2>>>0]=60*Math.max(a,u),E[e>>2>>>0]=Number(a!=u),t=r(i),e=r(o),t=it(t),e=it(e),u>2>>>0]=t,M[n+4>>2>>>0]=e):(M[n>>2>>>0]=e,M[n+4>>2>>>0]=t)}(e,n,r))},B:function(){V("")},ma:function(){return 4294901760},I:b?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:()=>performance.now(),xa:function(t,e,n){T.copyWithin(t>>>0,e>>>0,e+n>>>0)},G:function(t){var e=T.length;if(4294901760<(t>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=e*(1+.2/n);r=Math.min(r,t+100663296);var a=Math;r=Math.max(t,r),a=a.min.call(a,4294901760,r+(65536-r%65536)%65536);t:{try{O.grow(a-A.byteLength+65535>>>16),P();var i=1;break t}catch(t){}i=void 0}if(i)return!0}return!1},va:function(t,e){var n=0;return ut().forEach((function(r,a){var i=e+n;for(a=M[t+4*a>>2>>>0]=i,i=0;i>0>>>0]=r.charCodeAt(i);S[a>>0>>>0]=0,n+=r.length+1})),0},wa:function(t,e){var n=ut();M[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),M[e>>2>>>0]=r,0},ba:function(t){_||0>2>>>0],u=M[e+4>>2>>>0];e+=8;for(var c=0;c>>0]);a+=u}return M[r>>2>>>0]=a,0},c:function(){return ft},ja:function t(e,r){t.Mb||(t.Mb=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(b)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>V("randomDevice")}());for(var a=0;a>0>>>0]=t.Mb();return 0},ea:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},fa:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},J:function(t){var e=At();try{return at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},e:function(t,e){var n=At();try{return at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},N:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},O:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},j:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},o:function(t,e,n,r){var a=At();try{return at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},p:function(t,e,n,r,a){var i=At();try{return at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},M:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},r:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},v:function(t,e,n,r,a,i,o){var u=At();try{return at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},K:function(t,e,n,r,a,i,o,u){var c=At();try{return at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{return at(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},X:function(t,e,n,r,a,i,o,u){var c=At();try{return Ft(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},V:function(t,e,n,r,a,i,o){var u=At();try{return xt(t,e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},U:function(t,e,n,r,a){var i=At();try{return It(t,e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},Z:function(t,e,n,r){var a=At();try{return Pt(t,e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},W:function(t){var e=At();try{return Ct(t)}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},Y:function(t,e){var n=At();try{return Ut(t,e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},T:function(t,e,n){var r=At();try{return Rt(t,e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},f:function(t){var e=At();try{at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},q:function(t,e){var n=At();try{at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},h:function(t,e,n){var r=At();try{at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},da:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},l:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},t:function(t,e,n,r,a){var i=At();try{at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},u:function(t,e,n,r,a,i){var o=At();try{at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},x:function(t,e,n,r,a,i,o){var u=At();try{at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},z:function(t,e,n,r,a,i,o,u){var c=At();try{at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},ga:function(t,e,n,r,a,i,o,u,c){var s=At();try{at(t)(e,n,r,a,i,o,u,c)}catch(t){if(St(s),t!==t+0)throw t;Ot(1,0)}},A:function(t,e,n,r,a,i,o,u,c,s,l){var f=At();try{at(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(St(f),t!==t+0)throw t;Ot(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=At();try{at(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(St(b),t!==t+0)throw t;Ot(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=At();try{jt(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},_:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{Dt(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},$:function(t,e,n,r,a,i){var o=At();try{kt(t,e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},n:function(t){return t},F:function(t){ft=t},ha:yt,y:function(t,e,n,r){return yt(t,e,n,r)}};!function(){function t(t){e.asm=t.exports,O=e.asm.Ka,P(),U=e.asm.ib,I.unshift(e.asm.La),B--,e.monitorRunDependencies&&e.monitorRunDependencies(B),0==B&&(null!==G&&(clearInterval(G),G=null),N&&(t=N,N=null,t()))}function n(e){t(e.instance)}function r(t){return function(){if(!g&&(d||y)){if("function"==typeof fetch&&!Y.startsWith("file://"))return fetch(Y,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+Y+"\'";return t.arrayBuffer()})).catch((function(){return X()}));if(o)return new Promise((function(t,e){o(Y,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return X()}))}().then((function(t){return WebAssembly.instantiate(t,i)})).then((function(t){return t})).then(t,(function(t){w("failed to asynchronously prepare wasm: "+t),V(t)}))}var i={a:bt};if(B++,e.monitorRunDependencies&&e.monitorRunDependencies(B),e.instantiateWasm)try{return e.instantiateWasm(i,t)}catch(t){return w("Module.instantiateWasm callback failed with error: "+t),!1}(g||"function"!=typeof WebAssembly.instantiateStreaming||$()||Y.startsWith("file://")||b||"function"!=typeof fetch?r(n):fetch(Y,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,i).then(n,(function(t){return w("wasm streaming compile failed: "+t),w("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(a)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.La).apply(null,arguments)},e._OrtInit=function(){return(e._OrtInit=e.asm.Ma).apply(null,arguments)},e._OrtCreateSessionOptions=function(){return(e._OrtCreateSessionOptions=e.asm.Na).apply(null,arguments)},e._OrtAppendExecutionProvider=function(){return(e._OrtAppendExecutionProvider=e.asm.Oa).apply(null,arguments)},e._OrtAddSessionConfigEntry=function(){return(e._OrtAddSessionConfigEntry=e.asm.Pa).apply(null,arguments)},e._OrtReleaseSessionOptions=function(){return(e._OrtReleaseSessionOptions=e.asm.Qa).apply(null,arguments)},e._OrtCreateSession=function(){return(e._OrtCreateSession=e.asm.Ra).apply(null,arguments)},e._OrtReleaseSession=function(){return(e._OrtReleaseSession=e.asm.Sa).apply(null,arguments)},e._OrtGetInputCount=function(){return(e._OrtGetInputCount=e.asm.Ta).apply(null,arguments)},e._OrtGetOutputCount=function(){return(e._OrtGetOutputCount=e.asm.Ua).apply(null,arguments)},e._OrtGetInputName=function(){return(e._OrtGetInputName=e.asm.Va).apply(null,arguments)},e._OrtGetOutputName=function(){return(e._OrtGetOutputName=e.asm.Wa).apply(null,arguments)},e._OrtFree=function(){return(e._OrtFree=e.asm.Xa).apply(null,arguments)},e._OrtCreateTensor=function(){return(e._OrtCreateTensor=e.asm.Ya).apply(null,arguments)},e._OrtGetTensorData=function(){return(e._OrtGetTensorData=e.asm.Za).apply(null,arguments)},e._OrtReleaseTensor=function(){return(e._OrtReleaseTensor=e.asm._a).apply(null,arguments)},e._OrtCreateRunOptions=function(){return(e._OrtCreateRunOptions=e.asm.$a).apply(null,arguments)},e._OrtAddRunConfigEntry=function(){return(e._OrtAddRunConfigEntry=e.asm.ab).apply(null,arguments)},e._OrtReleaseRunOptions=function(){return(e._OrtReleaseRunOptions=e.asm.bb).apply(null,arguments)},e._OrtRun=function(){return(e._OrtRun=e.asm.cb).apply(null,arguments)},e._OrtEndProfiling=function(){return(e._OrtEndProfiling=e.asm.db).apply(null,arguments)};var mt,gt=e._malloc=function(){return(gt=e._malloc=e.asm.eb).apply(null,arguments)},vt=e._free=function(){return(vt=e._free=e.asm.fb).apply(null,arguments)},wt=e._fflush=function(){return(wt=e._fflush=e.asm.gb).apply(null,arguments)},_t=e.___funcs_on_exit=function(){return(_t=e.___funcs_on_exit=e.asm.hb).apply(null,arguments)},Ot=e._setThrew=function(){return(Ot=e._setThrew=e.asm.jb).apply(null,arguments)},At=e.stackSave=function(){return(At=e.stackSave=e.asm.kb).apply(null,arguments)},St=e.stackRestore=function(){return(St=e.stackRestore=e.asm.lb).apply(null,arguments)},Tt=e.stackAlloc=function(){return(Tt=e.stackAlloc=e.asm.mb).apply(null,arguments)},Et=e.___cxa_can_catch=function(){return(Et=e.___cxa_can_catch=e.asm.nb).apply(null,arguments)},Mt=e.___cxa_is_pointer_type=function(){return(Mt=e.___cxa_is_pointer_type=e.asm.ob).apply(null,arguments)},Ct=e.dynCall_j=function(){return(Ct=e.dynCall_j=e.asm.pb).apply(null,arguments)},xt=e.dynCall_iiiiij=function(){return(xt=e.dynCall_iiiiij=e.asm.qb).apply(null,arguments)},Rt=e.dynCall_jii=function(){return(Rt=e.dynCall_jii=e.asm.rb).apply(null,arguments)},jt=e.dynCall_viiiiij=function(){return(jt=e.dynCall_viiiiij=e.asm.sb).apply(null,arguments)},kt=e.dynCall_vjji=function(){return(kt=e.dynCall_vjji=e.asm.tb).apply(null,arguments)},Dt=e.dynCall_viiijjjii=function(){return(Dt=e.dynCall_viiijjjii=e.asm.ub).apply(null,arguments)},Pt=e.dynCall_iij=function(){return(Pt=e.dynCall_iij=e.asm.vb).apply(null,arguments)},Ut=e.dynCall_ji=function(){return(Ut=e.dynCall_ji=e.asm.wb).apply(null,arguments)},Ft=e.dynCall_iiiiiij=function(){return(Ft=e.dynCall_iiiiiij=e.asm.xb).apply(null,arguments)},It=e.dynCall_iiij=function(){return(It=e.dynCall_iiij=e.asm.yb).apply(null,arguments)};function Wt(){function t(){if(!mt&&(mt=!0,e.calledRun=!0,!C)){if(Z(I),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var t=e.postRun.shift();H.unshift(t)}Z(H)}}if(!(0{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.iterateExtraOptions=void 0,e.iterateExtraOptions=(t,n,r,a)=>{if("object"==typeof t&&null!==t){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach((([t,i])=>{const o=n?n+t:t;if("object"==typeof i)(0,e.iterateExtraOptions)(i,o+".",r,a);else if("string"==typeof i||"number"==typeof i)a(o,i.toString());else{if("boolean"!=typeof i)throw new Error("Can\'t handle extra config type: "+typeof i);a(o,i?"1":"0")}}))}},586:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setRunOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setRunOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};try{if(void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);void 0===(null==t?void 0:t.terminate)&&(u.terminate=!1);let i=0;if(void 0!==(null==t?void 0:t.tag)&&(i=(0,a.allocWasmString)(t.tag,o)),n=e._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,i),0===n)throw new Error("Can\'t create run options");return void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddRunConfigEntry(n,i,u))throw new Error(`Can\'t set a run config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseRunOptions(n),o.forEach(e._free),t}}},919:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setSessionOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setSessionOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(u);try{void 0===(null==t?void 0:t.graphOptimizationLevel)&&(u.graphOptimizationLevel="all");const c=(t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}})(u.graphOptimizationLevel);void 0===(null==t?void 0:t.enableCpuMemArena)&&(u.enableCpuMemArena=!0),void 0===(null==t?void 0:t.enableMemPattern)&&(u.enableMemPattern=!0),void 0===(null==t?void 0:t.executionMode)&&(u.executionMode="sequential");const s=(t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}})(u.executionMode);let l=0;if(void 0!==(null==t?void 0:t.logId)&&(l=(0,a.allocWasmString)(t.logId,o)),void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);if(void 0===(null==t?void 0:t.enableProfiling)&&(u.enableProfiling=!1),n=e._OrtCreateSessionOptions(c,!!u.enableCpuMemArena,!!u.enableMemPattern,s,!!u.enableProfiling,0,l,u.logSeverityLevel,u.logVerbosityLevel),0===n)throw new Error("Can\'t create session options");return(null==t?void 0:t.executionProviders)&&((t,e,n)=>{for(const r of e){let e="string"==typeof r?r:r.name;switch(e){case"xnnpack":e="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${e}`)}const o=(0,a.allocWasmString)(e,n);if(0!==(0,i.getInstance)()._OrtAppendExecutionProvider(t,o))throw new Error(`Can\'t append execution provider: ${e}`)}})(n,t.executionProviders,o),void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddSessionConfigEntry(n,i,u))throw new Error(`Can\'t set a session config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseSessionOptions(n),o.forEach(e._free),t}}},983:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.allocWasmString=void 0;const r=n(361);e.allocWasmString=(t,e)=>{const n=(0,r.getInstance)(),a=n.lengthBytesUTF8(t)+1,i=n._malloc(a);return n.stringToUTF8(t,i,a),e.push(i),i}},349:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.extractTransferableBuffers=e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=void 0;const r=n(586),a=n(919),i=n(983),o=n(361);e.initOrt=(t,e)=>{const n=(0,o.getInstance)()._OrtInit(t,e);if(0!==n)throw new Error(`Can\'t initialize onnxruntime. error code = ${n}`)};const u=new Map;e.createSessionAllocate=t=>{const e=(0,o.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},e.createSessionFinalize=(t,e)=>{const n=(0,o.getInstance)();let r=0,i=0,c=[];try{if([i,c]=(0,a.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],i),0===r)throw new Error("Can\'t create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(i),c.forEach(n._free)}const s=n._OrtGetInputCount(r),l=n._OrtGetOutputCount(r),f=[],p=[],h=[],d=[];for(let t=0;t{const r=(0,e.createSessionAllocate)(t);return(0,e.createSessionFinalize)(r,n)},e.releaseSession=t=>{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=n[1],i=n[2];a.forEach(e._OrtFree),i.forEach(e._OrtFree),e._OrtReleaseSession(r),u.delete(t)};const c=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},s=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},l=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};e.run=(t,e,n,a,f)=>{const p=(0,o.getInstance)(),h=u.get(t);if(!h)throw new Error("invalid session id");const d=h[0],y=h[1],b=h[2],m=e.length,g=a.length;let v=0,w=[];const _=[],O=[];try{[v,w]=(0,r.setRunOptions)(f);for(let t=0;tp.HEAP32[t++]=e));const n=p._OrtCreateTensor(c(e),o,u,l,r.length);if(0===n)throw new Error("Can\'t create a tensor");_.push(n)}finally{p.stackRestore(s)}}const t=p.stackSave(),o=p.stackAlloc(4*m),u=p.stackAlloc(4*m),h=p.stackAlloc(4*g),A=p.stackAlloc(4*g);try{let n=o/4,r=u/4,i=h/4,c=A/4;for(let t=0;tt*e));if(a=s(o),"string"===a){const t=[];let e=i/4;for(let n=0;n{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=e._OrtEndProfiling(r);if(0===a)throw new Error("Can\'t get an profile file name");e._OrtFree(a)},e.extractTransferableBuffers=t=>{const e=[];for(const n of t){const t=n[2];!Array.isArray(t)&&t.buffer&&e.push(t.buffer)}return e}},361:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(e,n);a&&!("get"in a?!e.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,a)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),a=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return a(e,t),e},o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.dispose=e.getInstance=e.initializeWebAssembly=void 0;const u=i(n(449)),c=o(n(932)),s=n(474);let l,f=!1,p=!1,h=!1;const d=(t,e)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":t?"ort-wasm-simd.wasm":"ort-wasm.wasm";e.initializeWebAssembly=async t=>{if(f)return Promise.resolve();if(p)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(h)throw new Error("previous call to \'initializeWebAssembly()\' failed.");p=!0;const e=t.initTimeout,r=t.numThreads,a=t.simd,i=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(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(t){return!1}})(),o=a&&(()=>{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(t){return!1}})(),y="string"==typeof t.wasmPaths?t.wasmPaths:void 0,b=d(!1,i),m=d(o,i),g="object"==typeof t.wasmPaths?t.wasmPaths[m]:void 0;let v=!1;const w=[];if(e>0&&w.push(new Promise((t=>{setTimeout((()=>{v=!0,t()}),e)}))),w.push(new Promise(((t,e)=>{const r=i?s:c.default,a={locateFile:(t,e)=>i&&t.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(154)],{type:"text/javascript"})):t===b?null!=g?g:(null!=y?y:e)+m:e+t};if(i)if("undefined"==typeof Blob)a.mainScriptUrlOrBlob=u.join("/","ort-wasm-threaded.js");else{const t=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;a.mainScriptUrlOrBlob=new Blob([t],{type:"text/javascript"})}r(a).then((e=>{p=!1,f=!0,l=e,t()}),(t=>{p=!1,h=!0,e(t)}))}))),await Promise.race(w),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},e.getInstance=()=>{if(f&&l)return l;throw new Error("WebAssembly is not initialized yet.")},e.dispose=()=>{var t;!f||p||h||(p=!0,null===(t=l.PThread)||void 0===t||t.terminateAllThreads(),l=void 0,p=!1,f=!1,h=!0)}},154:t=>{"use strict";t.exports=\'"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\\n\'},384:()=>{},993:()=>{},908:()=>{},953:()=>{},925:()=>{},449:()=>{}},e={};function n(r){var a=e[r];if(void 0!==a)return a.exports;var i=e[r]={exports:{}};return t[r].call(i.exports,i,i.exports,n),i.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),(()=>{"use strict";const t=n(349),e=n(361);self.onmessage=n=>{switch(n.data.type){case"init-wasm":(0,e.initializeWebAssembly)(n.data.in).then((()=>postMessage({type:"init-wasm"})),(t=>postMessage({type:"init-wasm",err:t})));break;case"init-ort":try{const{numThreads:e,loggingLevel:r}=n.data.in;(0,t.initOrt)(e,r),postMessage({type:"init-ort"})}catch(t){postMessage({type:"init-ort",err:t})}break;case"create_allocate":try{const{model:e}=n.data.in,r=(0,t.createSessionAllocate)(e);postMessage({type:"create_allocate",out:r})}catch(t){postMessage({type:"create_allocate",err:t})}break;case"create_finalize":try{const{modeldata:e,options:r}=n.data.in,a=(0,t.createSessionFinalize)(e,r);postMessage({type:"create_finalize",out:a})}catch(t){postMessage({type:"create_finalize",err:t})}break;case"create":try{const{model:e,options:r}=n.data.in,a=(0,t.createSession)(e,r);postMessage({type:"create",out:a})}catch(t){postMessage({type:"create",err:t})}break;case"release":try{const e=n.data.in;(0,t.releaseSession)(e),postMessage({type:"release"})}catch(t){postMessage({type:"release",err:t})}break;case"run":try{const{sessionId:e,inputIndices:r,inputs:a,outputIndices:i,options:o}=n.data.in,u=(0,t.run)(e,r,a,i,o);postMessage({type:"run",out:u},(0,t.extractTransferableBuffers)(u))}catch(t){postMessage({type:"run",err:t})}break;case"end-profiling":try{const e=n.data.in;(0,t.endProfiling)(e),postMessage({type:"end-profiling"})}catch(t){postMessage({type:"end-profiling",err:t})}}}})()})();\n',"Worker",void 0,void 0)}},477:_=>{_.exports=function(n,s,c,l){var f=self||window;try{try{var a;try{a=new f.Blob([n])}catch{(a=new(f.BlobBuilder||f.WebKitBlobBuilder||f.MozBlobBuilder||f.MSBlobBuilder)).append(n),a=a.getBlob()}var h=f.URL||f.webkitURL,p=h.createObjectURL(a),u=new f[s](p,c);return h.revokeObjectURL(p),u}catch{return new f[s]("data:application/javascript,".concat(encodeURIComponent(n)),c)}}catch{if(!l)throw Error("Inline worker is not supported");return new f[s](l,c)}}},4154:_=>{_.exports=`"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}}; -`},1670:_=>{_.exports=__WEBPACK_EXTERNAL_MODULE__1670__},7067:()=>{},1296:()=>{},1384:()=>{},3993:()=>{},908:()=>{},6953:()=>{},9925:()=>{},2806:()=>{},6449:()=>{},2850:()=>{},5381:()=>{},5686:(_,n,s)=>{s.r(n),s.d(n,{flatbuffers:()=>c});var c={};c.Offset,c.Table,c.SIZEOF_SHORT=2,c.SIZEOF_INT=4,c.FILE_IDENTIFIER_LENGTH=4,c.SIZE_PREFIX_LENGTH=4,c.Encoding={UTF8_BYTES:1,UTF16_STRING:2},c.int32=new Int32Array(2),c.float32=new Float32Array(c.int32.buffer),c.float64=new Float64Array(c.int32.buffer),c.isLittleEndian=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1,c.Long=function(l,f){this.low=0|l,this.high=0|f},c.Long.create=function(l,f){return l==0&&f==0?c.Long.ZERO:new c.Long(l,f)},c.Long.prototype.toFloat64=function(){return(this.low>>>0)+4294967296*this.high},c.Long.prototype.equals=function(l){return this.low==l.low&&this.high==l.high},c.Long.ZERO=new c.Long(0,0),c.Builder=function(l){if(l)f=l;else var f=1024;this.bb=c.ByteBuffer.allocate(f),this.space=f,this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},c.Builder.prototype.clear=function(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},c.Builder.prototype.forceDefaults=function(l){this.force_defaults=l},c.Builder.prototype.dataBuffer=function(){return this.bb},c.Builder.prototype.asUint8Array=function(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())},c.Builder.prototype.prep=function(l,f){l>this.minalign&&(this.minalign=l);for(var a=1+~(this.bb.capacity()-this.space+f)&l-1;this.space=0&&this.vtable[f]==0;f--);for(var a=f+1;f>=0;f--)this.addInt16(this.vtable[f]!=0?l-this.vtable[f]:0);this.addInt16(l-this.object_start);var h=(a+2)*c.SIZEOF_SHORT;this.addInt16(h);var p=0,u=this.space;e:for(f=0;f=0;u--)this.writeInt8(p.charCodeAt(u))}this.prep(this.minalign,c.SIZEOF_INT+h),this.addOffset(l),h&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)},c.Builder.prototype.finishSizePrefixed=function(l,f){this.finish(l,f,!0)},c.Builder.prototype.requiredField=function(l,f){var a=this.bb.capacity()-l,h=a-this.bb.readInt32(a);if(this.bb.readInt16(h+f)==0)throw new Error("FlatBuffers: field "+f+" must be set")},c.Builder.prototype.startVector=function(l,f,a){this.notNested(),this.vector_num_elems=f,this.prep(c.SIZEOF_INT,l*f),this.prep(a,l*f)},c.Builder.prototype.endVector=function(){return this.writeInt32(this.vector_num_elems),this.offset()},c.Builder.prototype.createString=function(l){if(l instanceof Uint8Array)var f=l;else{f=[];for(var a=0;a=56320?p:(p<<10)+l.charCodeAt(a++)+-56613888)<128?f.push(h):(h<2048?f.push(h>>6&31|192):(h<65536?f.push(h>>12&15|224):f.push(h>>18&7|240,h>>12&63|128),f.push(h>>6&63|128)),f.push(63&h|128))}}this.addInt8(0),this.startVector(1,f.length,1),this.bb.setPosition(this.space-=f.length),a=0;for(var u=this.space,o=this.bb.bytes();a>24},c.ByteBuffer.prototype.readUint8=function(l){return this.bytes_[l]},c.ByteBuffer.prototype.readInt16=function(l){return this.readUint16(l)<<16>>16},c.ByteBuffer.prototype.readUint16=function(l){return this.bytes_[l]|this.bytes_[l+1]<<8},c.ByteBuffer.prototype.readInt32=function(l){return this.bytes_[l]|this.bytes_[l+1]<<8|this.bytes_[l+2]<<16|this.bytes_[l+3]<<24},c.ByteBuffer.prototype.readUint32=function(l){return this.readInt32(l)>>>0},c.ByteBuffer.prototype.readInt64=function(l){return new c.Long(this.readInt32(l),this.readInt32(l+4))},c.ByteBuffer.prototype.readUint64=function(l){return new c.Long(this.readUint32(l),this.readUint32(l+4))},c.ByteBuffer.prototype.readFloat32=function(l){return c.int32[0]=this.readInt32(l),c.float32[0]},c.ByteBuffer.prototype.readFloat64=function(l){return c.int32[c.isLittleEndian?0:1]=this.readInt32(l),c.int32[c.isLittleEndian?1:0]=this.readInt32(l+4),c.float64[0]},c.ByteBuffer.prototype.writeInt8=function(l,f){this.bytes_[l]=f},c.ByteBuffer.prototype.writeUint8=function(l,f){this.bytes_[l]=f},c.ByteBuffer.prototype.writeInt16=function(l,f){this.bytes_[l]=f,this.bytes_[l+1]=f>>8},c.ByteBuffer.prototype.writeUint16=function(l,f){this.bytes_[l]=f,this.bytes_[l+1]=f>>8},c.ByteBuffer.prototype.writeInt32=function(l,f){this.bytes_[l]=f,this.bytes_[l+1]=f>>8,this.bytes_[l+2]=f>>16,this.bytes_[l+3]=f>>24},c.ByteBuffer.prototype.writeUint32=function(l,f){this.bytes_[l]=f,this.bytes_[l+1]=f>>8,this.bytes_[l+2]=f>>16,this.bytes_[l+3]=f>>24},c.ByteBuffer.prototype.writeInt64=function(l,f){this.writeInt32(l,f.low),this.writeInt32(l+4,f.high)},c.ByteBuffer.prototype.writeUint64=function(l,f){this.writeUint32(l,f.low),this.writeUint32(l+4,f.high)},c.ByteBuffer.prototype.writeFloat32=function(l,f){c.float32[0]=f,this.writeInt32(l,c.int32[0])},c.ByteBuffer.prototype.writeFloat64=function(l,f){c.float64[0]=f,this.writeInt32(l,c.int32[c.isLittleEndian?0:1]),this.writeInt32(l+4,c.int32[c.isLittleEndian?1:0])},c.ByteBuffer.prototype.getBufferIdentifier=function(){if(this.bytes_.length>10),56320+(1023&u)))}return h},c.ByteBuffer.prototype.__indirect=function(l){return l+this.readInt32(l)},c.ByteBuffer.prototype.__vector=function(l){return l+this.readInt32(l)+c.SIZEOF_INT},c.ByteBuffer.prototype.__vector_len=function(l){return this.readInt32(l+this.readInt32(l))},c.ByteBuffer.prototype.__has_identifier=function(l){if(l.length!=c.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+c.FILE_IDENTIFIER_LENGTH);for(var f=0;f{var n=_&&_.__esModule?()=>_.default:()=>_;return __webpack_require__.d(n,{a:n}),n},__webpack_require__.d=(_,n)=>{for(var s in n)__webpack_require__.o(n,s)&&!__webpack_require__.o(_,s)&&Object.defineProperty(_,s,{enumerable:!0,get:n[s]})},__webpack_require__.g=function(){if(typeof globalThis=="object")return globalThis;try{return this||new Function("return this")()}catch{if(typeof window=="object")return window}}(),__webpack_require__.o=(_,n)=>Object.prototype.hasOwnProperty.call(_,n),__webpack_require__.r=_=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(_,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(_,"__esModule",{value:!0})};var __webpack_exports__=__webpack_require__(6018);return __webpack_exports__})())})(ortWeb_min$1);var ortWeb_minExports=ortWeb_min$1.exports,ortWeb_min=getDefaultExportFromCjs(ortWeb_minExports),ONNX_WEB=_mergeNamespaces({__proto__:null,default:ortWeb_min},[ortWeb_minExports]);let ONNX;const executionProviders=["wasm"];typeof process<"u"&&((rt=process==null?void 0:process.release)==null?void 0:rt.name)==="node"?(ONNX=ONNX_NODE,executionProviders.unshift("cpu")):(ONNX=ONNX_WEB,typeof navigator<"u"&&/iP(hone|od|ad)/.test(navigator.userAgent)&&(ONNX.env.wasm.simd=!1)),ONNX=ONNX.default??ONNX;const{env:onnx_env}=ONNX,WEB_CACHE_AVAILABLE=typeof self<"u"&&"caches"in self,FS_AVAILABLE=!isEmpty(fs),PATH_AVAILABLE=!isEmpty(fs),RUNNING_LOCALLY=FS_AVAILABLE&&PATH_AVAILABLE,__dirname=RUNNING_LOCALLY?fs.dirname(fs.dirname(fs.fileURLToPath(self.location.href))):"./",DEFAULT_CACHE_DIR=RUNNING_LOCALLY?fs.join(__dirname,"/.cache/"):null,DEFAULT_LOCAL_MODEL_PATH="/models/",localModelPath=RUNNING_LOCALLY?fs.join(__dirname,DEFAULT_LOCAL_MODEL_PATH):DEFAULT_LOCAL_MODEL_PATH;onnx_env.wasm.wasmPaths=RUNNING_LOCALLY?fs.join(__dirname,"/dist/"):"https://cdn.jsdelivr.net/npm/@xenova/transformers/dist/";const env={backends:{onnx:onnx_env,tfjs:{}},__dirname,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowRemoteModels:!0,localModelPath,useFS:FS_AVAILABLE,useBrowserCache:WEB_CACHE_AVAILABLE,useFSCache:FS_AVAILABLE,cacheDir:DEFAULT_CACHE_DIR};function isEmpty(_){return Object.keys(_).length===0}globalThis.ReadableStream||(globalThis.ReadableStream=fs.ReadableStream);class Headers extends Object{constructor(...n){super(),Object.assign(this,n)}get(n){return this[n]}clone(){return new Headers(this)}}class FileResponse{constructor(n){fe(this,"_CONTENT_TYPE_MAP",{txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"});if(this.filePath=n,this.headers=new Headers,this.exists=fs.existsSync(n),this.exists){this.status=200,this.statusText="OK";let s=fs.statSync(n);this.headers["content-length"]=s.size,this.updateContentType();let c=this;this.body=new ReadableStream({start(l){c.arrayBuffer().then(f=>{l.enqueue(new Uint8Array(f)),l.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const n=this.filePath.toString().split(".").pop().toLowerCase();this.headers["content-type"]=this._CONTENT_TYPE_MAP[n]??"application/octet-stream"}clone(){let n=new FileResponse(this.filePath);return n.exists=this.exists,n.status=this.status,n.statusText=this.statusText,n.headers=this.headers.clone(),n}async arrayBuffer(){return(await fs.promises.readFile(this.filePath)).buffer}async blob(){const n=await fs.promises.readFile(this.filePath);return new Blob([n],{type:this.headers["content-type"]})}async text(){return await fs.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function isValidHttpUrl(_){let n;try{n=new URL(_)}catch{return!1}return n.protocol==="http:"||n.protocol==="https:"}async function getFile(_){return env.useFS&&!isValidHttpUrl(_)?new FileResponse(_):fetch(_)}function handleError(_,n,s){if(!s)return null;switch(_){case 400:throw Error(`Bad request error occurred while trying to load file: "${n}".`);case 401:throw Error(`Unauthorized access to file: "${n}".`);case 403:throw Error(`Forbidden access to file: "${n}".`);case 404:throw Error(`Could not locate file: "${n}".`);case 408:throw Error(`Request timeout error occurred while trying to load file: "${n}".`);case 500:throw Error(`Internal server error error occurred while trying to load file: "${n}".`);case 502:throw Error(`Bad gateway error occurred while trying to load file: "${n}".`);case 503:throw Error(`Service unavailable error occurred while trying to load file: "${n}".`);case 504:throw Error(`Gateway timeout error occurred while trying to load file: "${n}".`);default:throw Error(`Error (${_}) occurred while trying to load file: "${n}".`)}}class FileCache{constructor(n){this.path=n}async match(n){let s=fs.join(this.path,n),c=new FileResponse(s);if(c.exists)return c}async put(n,s){const c=Buffer.from(await s.arrayBuffer());let l=fs.join(this.path,n);try{await fs.promises.mkdir(fs.dirname(l),{recursive:!0}),await fs.promises.writeFile(l,c)}catch(f){console.warn("An error occurred while writing the file to cache:",f)}}}async function getModelFile(_,n,s=!0,c={}){dispatchCallback(c.progress_callback,{status:"initiate",name:_,file:n});let l;if(!l&&env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");l=await caches.open("transformers-cache")}!l&&env.useFSCache&&(l=new FileCache(c.cache_dir??env.cacheDir));const f=pathJoin(_,n);let a,h;if(l&&(h=await l.match(f)),h===void 0){let u=isValidHttpUrl(f),o=pathJoin(env.localModelPath,f);if(!u)h=await getFile(o);else if(c.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${f}.`);if(h===void 0||h.status===404){if(c.local_files_only||!env.allowRemoteModels){if(s)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${o}".`);return null}let t=pathJoin(env.remoteHost,env.remotePathTemplate.replace("{model}",_).replace("{revision}",c.revision??"main"),n);if(h=await getFile(t),h.status!==200)return handleError(h.status,t,s)}l&&h instanceof Response&&h.status===200&&(a=h.clone())}dispatchCallback(c.progress_callback,{status:"download",name:_,file:n});const p=await readResponse(h,u=>{dispatchCallback(c.progress_callback,{status:"progress",...u,name:_,file:n})});return a&&await l.match(f)===void 0&&await l.put(f,a).catch(u=>{console.warn(`Unable to add ${f} to browser cache: ${u}.`)}),dispatchCallback(c.progress_callback,{status:"done",name:_,file:n}),p}async function getModelJSON(_,n,s=!0,c={}){let l=await getModelFile(_,n,s,c);if(l===null)return{};let a=new TextDecoder("utf-8").decode(l);return JSON.parse(a)}async function readResponse(_,n){const s=_.headers.get("Content-Length");s===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let c=parseInt(s??"0"),l=new Uint8Array(c),f=0;const a=_.body.getReader();async function h(){const{done:p,value:u}=await a.read();if(p)return;let o=f+u.length;if(o>c){c=o;let e=new Uint8Array(c);e.set(l),l=e}l.set(u,f),f=o;const t=f/c*100;return n({progress:t,loaded:f,total:c}),h()}return await h(),l}function pathJoin(..._){return _=_.map((n,s)=>(s&&(n=n.replace(new RegExp("^/"),"")),s!==_.length-1&&(n=n.replace(new RegExp("/$"),"")),n)),_.join("/")}function interpolate_data(_,[n,s,c],[l,f],a="bilinear",h=!1){const p=f/c,u=l/s,o=new _.constructor(l*f*n),t=s*c,e=l*f;for(let r=0;r=0;--h)l[h]=p,c[h]=n[s[h]],p*=c[h];const f=s.map((h,p)=>l[s.indexOf(p)]),a=new _.constructor(_.length);for(let h=0;h<_.length;++h){let p=0;for(let u=n.length-1,o=h;u>=0;--u)p+=o%n[u]*f[u],o=Math.floor(o/n[u]);a[p]=_[h]}return[a,c]}function softmax(_){const n=max(_)[0],s=_.map(f=>Math.exp(f-n)),c=s.reduce((f,a)=>f+a,0);return s.map(f=>f/c)}function log_softmax(_){return softmax(_).map(c=>Math.log(c))}function dot(_,n){return _.reduce((s,c,l)=>s+c*n[l],0)}function getTopItems(_,n=0){return _=Array.from(_).map((s,c)=>[c,s]).sort((s,c)=>c[1]-s[1]),n>0&&(_=_.slice(0,n)),_}function cos_sim(_,n){const s=dot(_,n),c=magnitude(_),l=magnitude(n);return s/(c*l)}function magnitude(_){return Math.sqrt(_.reduce((n,s)=>n+s*s,0))}function min(_){if(_.length===0)throw Error("Array must not be empty");let n=_[0],s=0;for(let c=1;c<_.length;++c)_[c]n&&(n=_[c],s=c);return[n,s]}class FFT{constructor(n){if(this.size=n|0,this.size<=1||this.size&this.size-1)throw new Error("FFT size must be a power of two and bigger than 1");this._csize=n<<1,this.table=new Float32Array(this.size*2);for(let c=0;cc;c<<=1)++s;this._width=s%2===0?s-1:s,this._bitrev=new Int32Array(1<>>l&3)<>>1);for(let l=0;l>>1]=n[l];return c}toComplexArray(n,s){const c=s||this.createComplexArray();for(let l=0;l>>1],c[l+1]=0;return c}completeSpectrum(n){const s=this._csize,c=s>>>1;for(let l=2;l>=2;a>=2;a>>=2){h=l/a<<1;let t=h>>>2;for(p=0;p>>1,a>>>1)}else for(p=0,u=0;p>>1,a>>>1,c)}for(a>>=2;a>=2;a>>=2){h=l/a<<1;const t=h>>>1,e=t>>>1,r=e>>>1;for(p=0;p0){const c=s.reduce((l,f)=>l*f);for(let l=0;l0){const c=s.reduce((l,f)=>l*f);return this._subarray(n,c,s)}else return this.data[n]}indexOf(n){for(let s=0;s=this.dims[p])throw new Error(`IndexError: index ${u} is out of bounds for dimension ${p} with size ${this.dims[p]}`);c.push([u,u+1])}else if(Array.isArray(u)&&u.length===2){if(u[0]>u[1])throw new Error(`Invalid slice: ${u}`);let o=[Math.max(u[0],0),Math.min(u[1],this.dims[p])];c.push(o),s.push(o[1]-o[0])}else throw new Error(`Invalid slice: ${u}`)}let l=c.map(([p,u])=>u-p),f=l.reduce((p,u)=>p*u),a=new this.data.constructor(f);const h=new Array(this.dims.length);for(let p=l.length-1,u=1;p>=0;--p)h[p]=u,u*=this.dims[p];for(let p=0;p=0;--o){const e=l[o];u+=(t%e+c[o][0])*h[o],t=Math.floor(t/e)}a[p]=this.data[u]}return new Tensor(this.type,a,s)}transpose(...n){return transpose(this,n)}}function reshape(_,n){const s=_.length,c=n.reduce((f,a)=>f*a);if(s!==c)throw Error(`cannot reshape array of size ${s} into shape (${n})`);let l=_;for(let f=n.length-1;f>=0;f--)l=l.reduce((a,h)=>{let p=a[a.length-1];return p.lengththis.tokens_to_ids.get(s)??this.unk_token_id)}convert_ids_to_tokens(n){return n.map(s=>this.vocab[s]??this.unk_token)}}class WordPieceTokenizer extends TokenizerModel{constructor(n){super(n),this.tokens_to_ids=n.vocab,this.unk_token_id=this.tokens_to_ids.get(n.unk_token),this.unk_token=n.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[s,c]of this.tokens_to_ids)this.vocab[c]=s}encode(n){let s=[];for(let c of n){let l=[...c],f=!1,a=0,h=[];for(;a0&&(o=this.config.continuing_subword_prefix+o),this.tokens_to_ids.has(o)){u=o;break}--p}if(u===null){f=!0;break}h.push(u),a=p}f?s.push(this.unk_token):s.push(...h)}return s}}class Unigram extends TokenizerModel{constructor(n,s){super(n),this.vocab=new Array(n.vocab.size),this.scores=new Array(n.vocab.size);let c=0;n.vocab.forEach((l,f)=>{this.vocab[c]=f,this.scores[c]=l,++c}),this.unk_token_id=n.unk_id,this.unk_token=this.vocab[n.unk_id],this.tokens_to_ids=new Map(this.vocab.map((l,f)=>[l,f])),this.bosToken=" ",this.bosTokenId=this.tokens_to_ids.get(this.bosToken),this.eosToken=s.eos_token,this.eosTokenId=this.tokens_to_ids.get(this.eosToken),this.unkToken=this.vocab[this.unk_token_id],this.minScore=min(this.scores)[0],this.unkScore=this.minScore-10,this.scores[this.unk_token_id]=this.unkScore,this.trie=new CharTrie,this.trie.extend(this.vocab)}populateNodes(n){const s=n.sentence,c=s.length;let l=0;for(;l{const _=[...Array.from({length:"~".charCodeAt(0)-"!".charCodeAt(0)+1},(l,f)=>f+"!".charCodeAt(0)),...Array.from({length:"¬".charCodeAt(0)-"¡".charCodeAt(0)+1},(l,f)=>f+"¡".charCodeAt(0)),...Array.from({length:"ÿ".charCodeAt(0)-"®".charCodeAt(0)+1},(l,f)=>f+"®".charCodeAt(0))];let n=_.slice(),s=0;for(let l=0;l<256;l++)_.includes(l)||(_.push(l),n.push(256+s),s+=1);let c=n.map(l=>String.fromCharCode(l));return Object.fromEntries(_.map((l,f)=>[l,c[f]]))})(),UNICODE_TO_BYTES=reverseDictionary(BYTES_TO_UNICODE);class BPE extends TokenizerModel{constructor(n){super(n),this.tokens_to_ids=n.vocab,this.unk_token_id=this.tokens_to_ids.get(n.unk_token),this.unk_token=n.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[s,c]of this.tokens_to_ids)this.vocab[c]=s;this.bpe_ranks=Object.fromEntries(n.merges.map((s,c)=>[s,c])),this.merges=n.merges.map(s=>s.split(/\s+/)),this.end_of_word_suffix=n.end_of_word_suffix,this.byte_fallback=this.config.byte_fallback??!1,this.cache=Object.create(null)}get_pairs(n){let s=new Set,c=n[0];for(let l=1;l{let r=this.bpe_ranks[t]??1/0,i=this.bpe_ranks[e]??1/0;return r<=i?t:e});if(!(f in this.bpe_ranks))break;let[a,h]=f.split(/\s+/g),p=[],u=0,o=-1;for(;uNormalizer.fromConfig(s))}normalize(n){for(let s of this.normalizers)n=s.normalize(n);return n}}class BertNormalizer extends Normalizer{_tokenize_chinese_chars(n){let s=[];for(let c=0;c=19968&&n<=40959||n>=13312&&n<=19903||n>=131072&&n<=173791||n>=173824&&n<=177983||n>=177984&&n<=178207||n>=178208&&n<=183983||n>=63744&&n<=64255||n>=194560&&n<=195103}stripAccents(n){return n.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}normalize(n){return this.config.handle_chinese_chars&&(n=this._tokenize_chinese_chars(n)),this.config.lowercase?(n=n.toLowerCase(),this.config.strip_accents!==!1&&(n=this.stripAccents(n))):this.config.strip_accents&&(n=this.stripAccents(n)),n}}class PreTokenizer extends Callable{static fromConfig(n){switch(n.type){case"BertPreTokenizer":return new BertPreTokenizer(n);case"Sequence":return new PreTokenizerSequence(n);case"WhitespaceSplit":return new WhitespaceSplit(n);case"Metaspace":return new MetaspacePreTokenizer(n);case"ByteLevel":return new ByteLevelPreTokenizer(n);case"Split":return new SplitPreTokenizer(n);default:throw new Error(`Unknown PreTokenizer type: ${n.type}`)}}pre_tokenize_text(n){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize(n){let s=[];return Array.isArray(n)?s=n.map(c=>this.pre_tokenize_text(c)):s=this.pre_tokenize_text(n),s.flat()}_call(n){return this.pre_tokenize(n)}}class BertPreTokenizer extends PreTokenizer{constructor(n){super(),this.pattern=/\b\p{L}+\b|[^\s\p{L}]/gu}pre_tokenize_text(n){return n.trim().match(this.pattern)||[]}}class ByteLevelPreTokenizer extends PreTokenizer{constructor(n){super(),this.config=n,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=BYTES_TO_UNICODE,this.text_encoder=new TextEncoder}pre_tokenize_text(n){return(this.use_regex?n.match(this.pattern)||[]:[n]).map(c=>(this.add_prefix_space&&!c.startsWith(" ")&&(c=" "+c),c=Array.from(this.text_encoder.encode(c),l=>this.byte_encoder[l]).join(""),c))}}class SplitPreTokenizer extends PreTokenizer{constructor(n){super(),this.config=n}pre_tokenize_text(n){let s=createPattern(this.config.pattern);if(s===null)return[];switch(this.config.behavior.toLowerCase()){case"isolated":case"removed":return n.match(s)||[];default:return console.warn(`Unknown split behavior: "${this.config.behavior}"`),[]}}}class PostProcessor extends Callable{constructor(n){super(),this.config=n}static fromConfig(n){switch(n.type){case"TemplateProcessing":return new TemplateProcessing(n);case"ByteLevel":return new ByteLevelPostProcessor(n);case"RobertaProcessing":return new RobertaProcessing(n);default:throw new Error(`Unknown PostProcessor type: ${n.type}`)}}post_process(n,...s){throw Error("post_process should be implemented in subclass.")}_call(n,...s){return this.post_process(n,...s)}}class RobertaProcessing extends PostProcessor{constructor(n){super(n),this.cls=n.cls[0],this.sep=n.sep[0]}post_process(n,s=null){return n=[this.cls,...n,this.sep],s!==null&&(n=[...n,this.sep,...s,this.sep]),n}}class TemplateProcessing extends PostProcessor{constructor(n){super(n),this.single=n.single,this.pair=n.pair}post_process(n,s=null){let c=s===null?this.single:this.pair,l=[];for(let f of c)"SpecialToken"in f?l.push(f.SpecialToken.id):"Sequence"in f&&(f.Sequence.id==="A"?l.push(...n):f.Sequence.id==="B"&&l.push(...s));return l}}class ByteLevelPostProcessor extends PostProcessor{post_process(n){return n}}class Decoder extends Callable{constructor(n){super(),this.config=n,this.added_tokens=[],this.end_of_word_suffix=null}static fromConfig(n){switch(n.type){case"WordPiece":return new WordPieceDecoder(n);case"Metaspace":return new MetaspaceDecoder(n);case"ByteLevel":return new ByteLevelDecoder(n);default:throw new Error(`Unknown Decoder type: ${n.type}`)}}convert_tokens_to_string(n){return n.join("").trim()}_call(n){return this.decode(n)}decode(n){throw Error("decode should be implemented in subclass.")}}class WordPieceDecoder extends Decoder{constructor(n){super(n),this.convertRegex=new RegExp(` ${n.prefix}`,"g"),this.cleanup=n.cleanup}convert_tokens_to_string(n){return n.join(" ").replace(this.convertRegex,"").trim()}decode(n){return this.convert_tokens_to_string(n)}}class ByteLevelDecoder extends Decoder{constructor(n){super(n),this.byte_decoder=UNICODE_TO_BYTES,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(n){let s=n.join("");this.config.trim_offsets?s=s.trim():this.config.add_prefix_space&&(s=" "+s);let c=new Uint8Array([...s].map(f=>this.byte_decoder[f])),l=this.text_decoder.decode(c);return this.end_of_word_suffix&&(l=l.replaceAll(this.end_of_word_suffix," ").trim()),l}decode(n){let s=[],c=[];for(let f of n)this.added_tokens.includes(f)?(c.length>0&&(s.push(this.convert_tokens_to_string(c)),c=[]),s.push(f)):c.push(f);return c.length>0&&s.push(this.convert_tokens_to_string(c)),s.join("")}}class MetaspacePreTokenizer extends PreTokenizer{constructor(n){super(),this.addPrefixSpace=n.add_prefix_space,this.replacement=n.replacement,this.strRep=n.str_rep||this.replacement}pre_tokenize(n){(typeof n=="string"||n instanceof String)&&(n=n.split(/\s+/));const s=[];for(let c of n){let l=c.replace(" ",this.strRep);this.addPrefixSpace&&!l.startsWith(this.replacement)&&(l=this.strRep+l),s.push(l)}return s}}class MetaspaceDecoder extends Decoder{constructor(n){super(n),this.addPrefixSpace=n.add_prefix_space,this.replacement=n.replacement}decode(n){let s=[];for(let c=0;cPreTokenizer.fromConfig(s))}pre_tokenize_text(n){return typeof n=="string"&&(n=[n]),this.tokenizers.reduce((s,c)=>c.pre_tokenize(s),n)}}class WhitespaceSplit extends PreTokenizer{constructor(n){super()}pre_tokenize_text(n){return n.split(/\s+/)}}class PreTrainedTokenizer extends Callable{constructor(n,s){super(),this.normalizer=Normalizer.fromConfig(n.normalizer),this.pre_tokenizer=PreTokenizer.fromConfig(n.pre_tokenizer),n.model.vocab&&(Array.isArray(n.model.vocab)||(n.model.vocab=Object.entries(n.model.vocab)),n.model.vocab=new Map(n.model.vocab)),this.model=TokenizerModel.fromConfig(n.model,s),this.post_processor=PostProcessor.fromConfig(n.post_processor),this.decoder=Decoder.fromConfig(n.decoder),this.decoder.end_of_word_suffix=this.model.end_of_word_suffix,this.special_tokens=[],this.all_special_ids=[];for(let c of n.added_tokens){let l=c.id,f=c.content;this.decoder.added_tokens.push(f),this.model.tokens_to_ids.set(f,l),this.model.vocab[l]=f,c.special&&(this.special_tokens.push(f),this.all_special_ids.push(l))}this.special_tokens_regex=new RegExp("("+this.special_tokens.map(escapeRegExp).join("|")+")"),this.mask_token=this.getToken(s,"mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken(s,"pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken(s,"sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.model_max_length=s.model_max_length,this.remove_space=s.remove_space,this.padding_side="right"}getToken(n,...s){for(let c of s){let l=n[c];if(l)if(typeof l=="object"){if(l.__type==="AddedToken")return l.content;throw Error(`Unknown token: ${l}`)}else return l}return null}static async from_pretrained(n,{progress_callback:s=null,config:c=null,cache_dir:l=null,local_files_only:f=!1,revision:a="main"}={}){let h=await loadTokenizer(n,{progress_callback:s,config:c,cache_dir:l,local_files_only:f,revision:a});return new this(...h)}prepare_model_inputs(n){return n}_call(n,{text_pair:s=null,padding:c=!1,truncation:l=null,max_length:f=null,return_tensor:a=!0}={}){let h;if(Array.isArray(n)){if(n.length===0)throw Error("text array must be non-empty");if(s!==null){if(Array.isArray(s)){if(n.length!==s.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");h=n.map((t,e)=>this.encode(t,s[e]))}else h=n.map(t=>this.encode(t))}else{if(n===null)throw Error("text may not be null");if(Array.isArray(s))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");h=[this.encode(n,s)]}let p=Math.max(...h.map(t=>t.length));f===null&&(f=p),f=Math.min(f,this.model_max_length);let u=[];if(c||l)for(let t=0;tf)l&&(h[t]=h[t].slice(0,f)),u.push(new Array(h[t].length).fill(1));else if(c){let e=f-h[t].length;this.padding_side==="right"?(u.push(new Array(h[t].length).fill(1).concat(new Array(e).fill(0))),h[t].push(...new Array(e).fill(this.pad_token_id))):(u.push(new Array(e).fill(0).concat(new Array(h[t].length).fill(1))),h[t].unshift(...new Array(e).fill(this.pad_token_id)))}else u.push(new Array(h[t].length).fill(1));else u=h.map(t=>new Array(t.length).fill(1));if(a){if(!(c&&l)&&h.some(e=>e.length!==h[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");let t=[h.length,h[0].length];h=new Tensor("int64",BigInt64Array.from(h.flat().map(BigInt)),t),u=new Tensor("int64",BigInt64Array.from(u.flat().map(BigInt)),t)}else Array.isArray(n)||(h=h[0],u=u[0]);let o={input_ids:h,attention_mask:u};return o=this.prepare_model_inputs(o),o}_encode_text(n){return n===null?null:n.split(this.special_tokens_regex).filter(l=>l).map(l=>{if(this.special_tokens.includes(l))return l;{this.remove_space===!0&&(l=l.trim().split(/\s+/).join(" ")),this.normalizer!==null&&(l=this.normalizer(l));let f=this.pre_tokenizer(l);return this.model(f)}}).flat()}encode(n,s=null){let c=this._encode_text(n),l=this._encode_text(s),f=this.post_processor(c,l);return this.model.convert_tokens_to_ids(f)}clean_up_tokenization(n){return n.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n\'t/g,"n't").replace(/ \'m/g,"'m").replace(/ \'s/g,"'s").replace(/ \'ve/g,"'ve").replace(/ \'re/g,"'re")}batch_decode(n,s={}){return n.map(c=>this.decode(c,s))}decode(n,s={}){if(!Array.isArray(n)||n.length===0||!isIntegralNumber(n[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(n,s)}decode_single(n,{skip_special_tokens:s=!1,clean_up_tokenization_spaces:c=!0}){let l=this.model.convert_ids_to_tokens(n);s&&(l=l.filter(a=>!this.special_tokens.includes(a)));let f=this.decoder(l);return"cleanup"in this.decoder&&this.decoder.cleanup!==c&&(console.warn(`clean_up_tokenization_spaces disagrees with decoder's cleanup setting. Overriding to use decoder's cleanup setting (${this.decoder.cleanup})`),c=this.decoder.cleanup),c&&(f=this.clean_up_tokenization(f)),f}}function bert_prepare_model_inputs(_){if(_.input_ids instanceof Tensor)_.token_type_ids=new Tensor("int64",new BigInt64Array(_.input_ids.data.length),_.input_ids.dims);else if(Array.isArray(_.input_ids))Array.isArray(_.input_ids[0])?_.token_type_ids=_.input_ids.map(n=>new Array(n.length).fill(0)):_.token_type_ids=new Array(_.input_ids.length).fill(0);else throw new Error("Input ids must be a Tensor or an Array");return _}class BertTokenizer extends PreTrainedTokenizer{prepare_model_inputs(n){return bert_prepare_model_inputs(n)}}class AlbertTokenizer extends PreTrainedTokenizer{prepare_model_inputs(n){return bert_prepare_model_inputs(n)}}class MobileBertTokenizer extends PreTrainedTokenizer{prepare_model_inputs(n){return bert_prepare_model_inputs(n)}}class SqueezeBertTokenizer extends PreTrainedTokenizer{prepare_model_inputs(n){return bert_prepare_model_inputs(n)}}class DistilBertTokenizer extends PreTrainedTokenizer{}class T5Tokenizer extends PreTrainedTokenizer{}class GPT2Tokenizer extends PreTrainedTokenizer{}class BartTokenizer extends PreTrainedTokenizer{}class RobertaTokenizer extends PreTrainedTokenizer{}class BloomTokenizer extends PreTrainedTokenizer{}class NllbTokenizer extends PreTrainedTokenizer{constructor(n,s){super(n,s),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(c=>this.languageRegex.test(c))}_build_translation_inputs(n,s,c){if(!this.language_codes.includes(c.tgt_lang))throw new Error(`Target language code "${c.tgt_lang}" is not valid. Must be one of: {${this.language_codes.join(", ")}}`);if(c.src_lang!==void 0){if(!this.language_codes.includes(c.src_lang))throw new Error(`Source language code "${c.src_lang}" is not valid. Must be one of: {${this.language_codes.join(", ")}}`);for(let l of this.post_processor.config.single)if("SpecialToken"in l&&this.languageRegex.test(l.SpecialToken.id)){l.SpecialToken.id=c.src_lang;break}}return c.forced_bos_token_id=this.model.convert_tokens_to_ids([c.tgt_lang])[0],this._call(n,s)}}const Xe=class extends PreTrainedTokenizer{_decode_asr(n,{return_timestamps:s=!1,return_language:c=!1,time_precision:l=null,force_full_sequences:f=!0}={}){if(l===null)throw Error("Must specify time_precision");let a=null;function h(){return{language:a,timestamp:[null,null],text:""}}const p=[];let u=h(),o=0;const t=this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1;let e=[],r=!1,i=null;const d=new Set(this.all_special_ids);for(let b of n){const y=b.tokens;let w=null,v=t;if("stride"in b){const[A,O,x]=b.stride;if(o-=O,i=A-x,O&&(v=O/l+t),x)for(let I=y.length-1;I>=0;--I){const $=y[I];if($>=t){if(w!==null&&($-t)*l=t){const O=(A-t)*l+o,x=Math.round(O*100)/100;if(w!==null&&A>=w)r=!0;else if(r||e.length>0&&A0?e.push(S):e.every(A=>A.length===0)&&(u=h(),e=[],S=[])}if(e.length>0){if(f&&s)throw new Error("There was an error while processing timestamps, we haven't found a timestamp as last token.");const b=this.findLongestCommonSequence(e),y=this.decode(b);u.text=y,p.push(u)}let g=Object.create(null);const m=p.map(b=>b.text).join("");if(s||c){for(let b=0;bI===A[$]).length,x=O/g+m;O>1&&x>h&&(h=x,p=[b,y,v,S])}const[o,t,e,r]=p,i=Math.floor((t+o)/2),d=Math.floor((r+e)/2);l.push(...s.slice(0,i)),s=a.slice(d),c=s.length}return l.push(...s),l}};let WhisperTokenizer=Xe;fe(WhisperTokenizer,"LANGUAGES",{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"});class CodeGenTokenizer extends PreTrainedTokenizer{}class CLIPTokenizer extends PreTrainedTokenizer{}class MarianTokenizer extends PreTrainedTokenizer{constructor(n,s){super(n,s),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(c=>this.languageRegex.test(c)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(n){if(n===null)return null;let[s,...c]=n.trim().split(this.languageRegex);if(c.length===0)return super._encode_text(s);if(c.length===2){let[l,f]=c;return this.supported_language_codes.includes(l)||console.warn(`Unsupported language code "${l}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),[l,...super._encode_text(f)]}}}class CharTrie{constructor(){this.root=CharTrieNode.default()}extend(n){for(let s of n)this.push(s)}push(n){let s=this.root;for(let c of n){let l=s.children.get(c);l===void 0&&(l=CharTrieNode.default(),s.children.set(c,l)),s=l}s.isLeaf=!0}*commonPrefixSearch(n){let s=this.root,c="";for(let l=0;lp)&&(u=o.clone(),p=t)}if(u!==null)h.prev=u,h.backtraceScore=p;else return[]}s++}const c=[],f=this.beginNodes[n][0].prev;if(f===null)return[];let a=f.clone();for(;a.prev!==null;)c.push(a.clone()),a=a.clone().prev.clone();return c.reverse(),c}piece(n){return this.sentence.slice(n.pos,n.pos+n.length)}tokens(){return this.viterbi().map(s=>this.piece(s))}tokenIds(){return this.viterbi().map(s=>s.tokenId)}}class TokenLatticeNode{constructor(n,s,c,l,f){this.tokenId=n,this.nodeId=s,this.pos=c,this.length=l,this.score=f,this.prev=null,this.backtraceScore=0}clone(){const n=new TokenLatticeNode(this.tokenId,this.nodeId,this.pos,this.length,this.score);return n.prev=this.prev,n.backtraceScore=this.backtraceScore,n}}class AutoTokenizer{static async from_pretrained(n,{quantized:s=!0,progress_callback:c=null,config:l=null,cache_dir:f=null,local_files_only:a=!1,revision:h="main"}={}){let[p,u]=await loadTokenizer(n,{quantized:s,progress_callback:c,config:l,cache_dir:f,local_files_only:a,revision:h}),o=u.tokenizer_class.replace(/Fast$/,""),t=this.TOKENIZER_CLASS_MAPPING[o];return t||(console.warn(`Unknown tokenizer class "${o}", attempting to construct from base class.`),t=PreTrainedTokenizer),new t(p,u)}}fe(AutoTokenizer,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer,DistilBertTokenizer,BertTokenizer,MobileBertTokenizer,SqueezeBertTokenizer,AlbertTokenizer,GPT2Tokenizer,BartTokenizer,RobertaTokenizer,WhisperTokenizer,CodeGenTokenizer,CLIPTokenizer,MarianTokenizer,BloomTokenizer,NllbTokenizer});class LogitsProcessorList extends Callable{constructor(){super(),this.processors=[]}push(n){this.processors.push(n)}extend(n){this.processors.push(...n)}_call(n,s){for(let c of s)this.processors.forEach(l=>l(n,c))}[Symbol.iterator](){return this.processors.values()}}class LogitsProcessor extends Callable{_call(n,s){throw Error("`_call` should be implemented in a subclass")}}class ForceTokensLogitsProcessor extends LogitsProcessor{constructor(n){super(),this.force_token_map=Object.fromEntries(n??[])}_call(n,s){let c=this.force_token_map[n.length];return exists(c)&&(s.data.fill(-1/0),s.data[c]=0),s}}class ForcedBOSTokenLogitsProcessor extends LogitsProcessor{constructor(n){super(),this.bos_token_id=n}_call(n,s){n.length===1&&(s.data.fill(-1/0),s.data[this.bos_token_id]=0)}}class ForcedEOSTokenLogitsProcessor extends LogitsProcessor{constructor(n,s){super(),this.max_length=n,this.forced_eos_token_id=s}_call(n,s){}}class WhisperTimeStampLogitsProcessor extends LogitsProcessor{constructor(n){super(),this.eos_token_id=n.eos_token_id,this.no_timestamps_token_id=n.no_timestamps_token_id,this.timestamp_begin=this.no_timestamps_token_id+1,this.begin_index=(n.forced_decoder_ids||[]).length+2,n.forced_decoder_ids.slice(-1)[0][1]===this.no_timestamps_token_id&&(this.begin_index-=1),this.max_initial_timestamp_index=n.max_initial_timestamp_index}_call(n,s){if(s.data[this.no_timestamps_token_id]=-1/0,n.length===this.begin_index-1)return s.data.fill(-1/0),s.data[this.timestamp_begin]=0,s;const c=n.slice(this.begin_index),l=c.length>=1&&c[c.length-1]>=this.timestamp_begin,f=c.length<2||c[c.length-2]>=this.timestamp_begin;if(l&&(f?s.data.subarray(this.timestamp_begin).fill(-1/0):s.data.subarray(0,this.eos_token_id).fill(-1/0)),n.length===this.begin_index&&this.max_initial_timestamp_index!==null){const u=this.timestamp_begin+this.max_initial_timestamp_index;s.data.subarray(u+1).fill(-1/0)}const a=log_softmax(s.data),h=Math.log(a.subarray(this.timestamp_begin).map(Math.exp).reduce((u,o)=>u+o)),p=Math.max(...a.subarray(0,this.timestamp_begin));return h>p&&s.data.subarray(0,this.timestamp_begin).fill(-1/0),s}}class NoRepeatNGramLogitsProcessor extends LogitsProcessor{constructor(n){super(),this.no_repeat_ngram_size=n}getNgrams(n){const s=n.length,c=[];for(let f=0;f0&&(l=l.map(f=>f/this.temperature)),l}randomSelect(n){let s=n.reduce((l,f)=>l+f,0),c=Math.random()*s;for(let l=0;l1)return new BeamSearchSampler(n.temperature,n.num_beams,n.do_sample,n.top_k);if(n.do_sample)return new TopKSampler(n.temperature,n.top_k);if(n.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${n.num_return_sequences}.`);return new GreedySampler(n.temperature)}}class GreedySampler extends Sampler{sample(n,s=-1){let c=this.getLogits(n,s);return[[max(c)[1],0]]}}class TopKSampler extends Sampler{constructor(n,s){super(n),this.k=s}sample(n,s=-1){let[c,l,f]=n.dims,a=f;this.k>0&&(a=Math.min(this.k,a));let h=this.getLogits(n,s),p=getTopItems(h,a),u=softmax(p.map(r=>r[1])),o=this.randomSelect(u),t=p[o][0],e=Math.log(u[o]);return[[t,e]]}}class BeamSearchSampler extends Sampler{constructor(n,s,c,l){super(n),this.num_beams=s,this.do_sample=c,this.top_k=l}sample(n,s=-1){let c=this.getLogits(n,s);if(this.do_sample||this.top_k>0){const[l,f,a]=n.dims;let h=a;this.top_k>0&&(h=Math.min(this.top_k,h));const p=getTopItems(c,h),u=softmax(p.map(o=>o[1]));return Array.from({length:this.num_beams},()=>{const o=this.randomSelect(u);return[p[o][0],Math.log(u[o])]})}else{const l=log_softmax(c);return getTopItems(l,this.num_beams)}}}const{InferenceSession,Tensor:ONNXTensor}=ONNX;async function constructSession(_,n,s){let c=`onnx/${n}${s.quantized?"_quantized":""}.onnx`,l=await getModelFile(_,c,!0,s);try{return await InferenceSession.create(l,{executionProviders})}catch(f){if(executionProviders.length===1&&executionProviders[0]==="wasm")throw f;return console.warn(f),console.warn("Something went wrong during model construction (most likely a missing operation). Using `wasm` as a fallback. "),await InferenceSession.create(l,{executionProviders:["wasm"]})}}async function sessionRun(_,n){try{let s=await _.run(n);return s=replaceTensors(s),s}catch(s){throw console.error(`An error occurred during model execution: "${s}".`),console.error("Inputs given to model:",n),s}}function replaceTensors(_){for(let n in _)_[n]instanceof ONNXTensor&&(_[n]=new Tensor(_[n]));return _}function toI64Tensor(_){if(_ instanceof Tensor)return _;if(_.length===0)throw Error("items must be non-empty");if(Array.isArray(_[0])){if(_.some(n=>n.length!==_[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(_.flat().map(n=>BigInt(n))),[_.length,_[0].length])}else return new Tensor("int64",BigInt64Array.from(_.map(n=>BigInt(n))),[1,_.length])}function _prepare_attention_mask(_,n){let s=_.config.pad_token_id??null,c=_.config.eos_token_id??null;isIntegralNumber(c)&&(c=[c]);let l=n.indexOf(s)!==-1,f=c===null||!c.includes(s);if(l&&f){let a=BigInt64Array.from(n.data.map(h=>h!=s));return new Tensor("int64",a,n.dims)}else return new Tensor("int64",new BigInt64Array(n.data.length).fill(1n),n.dims)}function boolTensor(_){return new Tensor("bool",[_],[1])}async function loadAutoModel(_,n){let s=n.config??await getModelJSON(_,"config.json",!0,n),c=s.is_encoder_decoder?"encoder_model":"model",l=await constructSession(_,c,n);return[s,l]}async function loadModel(_,n){return await Promise.all([n.config??getModelJSON(_,"config.json",!0,n),constructSession(_,"model",n)])}async function seq2seqLoadModel(_,n){return await Promise.all([n.config??getModelJSON(_,"config.json",!0,n),constructSession(_,"encoder_model",n),constructSession(_,"decoder_model_merged",n),getModelJSON(_,"generation_config.json",!1,n)])}async function encoderDecoderLoadModel(_,n){return await Promise.all([n.config??getModelJSON(_,"config.json",!0,n),constructSession(_,"encoder_model",n),constructSession(_,"decoder_model_merged",n)])}async function decoderLoadModel(_,n){return await Promise.all([n.config??getModelJSON(_,"config.json",!0,n),constructSession(_,"decoder_model_merged",n)])}async function seq2seq_forward(_,n,{encoder_input_name:s="input_ids",add_decoder_pkv:c=!0}={}){let l=n.encoder_outputs,f=n.past_key_values;if(l===null){const u={[s]:n[s]};_.session.inputNames.includes("attention_mask")&&(u.attention_mask=n.attention_mask),l=(await sessionRun(_.session,u)).last_hidden_state}let a={input_ids:n.decoder_input_ids,encoder_hidden_states:l,use_cache_branch:boolTensor(f!==null)};_.decoder_merged_session.inputNames.includes("encoder_attention_mask")&&(a.encoder_attention_mask=n.attention_mask),_.addPastKeyValues(a,f,c);const h=await sessionRun(_.decoder_merged_session,a);let p=h.logits;return f=_.getPastKeyValues(h,f),new Seq2SeqLMOutput(p,f,l)}function seq2seqStartBeams(_,n,s,c=!0){let l=[],f=0;for(let a of n){a.dims=[1,...a.dims];let h={inputs:a,encoder_outputs:null,past_key_values:null,output_token_ids:[_.config.decoder_start_token_id],done:!1,score:0,id:f++};c&&(h.attention_mask=_prepare_attention_mask(_,a)),l.push(h)}return l}async function seq2seqRunBeam(_,n,{input_name:s="input_ids"}={}){let c={[s]:n.inputs,decoder_input_ids:toI64Tensor(n.output_token_ids.slice(-1)),encoder_outputs:n.encoder_outputs,past_key_values:n.past_key_values};n.attention_mask&&(c.attention_mask=n.attention_mask);let l=await _.forward(c);return n.past_key_values=l.past_key_values,n.encoder_outputs=l.encoder_outputs,l}async function textgen_forward(_,n){let s=n.past_key_values,c={input_ids:n.input_ids,attention_mask:n.attention_mask,use_cache_branch:boolTensor(s!==null)};_.addPastKeyValues(c,s);let l=await sessionRun(_.session,c),f=l.logits;return s=_.getPastKeyValues(l,s),{logits:f,past_key_values:s}}function textgenStartBeams(_,n,s,c){let l=[],f=0;for(let a of n){a.dims=[1,...a.dims];let h;c?(h=c.get(f),h.dims=[1,...h.dims]):h=_prepare_attention_mask(_,a);let p={input:a,model_input_ids:a,attention_mask:h,past_key_values:null,output_token_ids:[],num_output_tokens:s,done:!1,score:0,id:f++};l.push(p)}return l}async function textgenRunBeam(_,n){let s=new BigInt64Array(n.input.data.length+n.output_token_ids.length).fill(1n),c={input_ids:n.model_input_ids,attention_mask:new Tensor("int64",s,[1,s.length]),past_key_values:n.past_key_values},l=await _.forward(c);return n.past_key_values=l.past_key_values,l}function textgenUpdatebeam(_,n){_.output_token_ids=[..._.output_token_ids,n],_.model_input_ids=new Tensor("int64",[BigInt(n)],[1,1])}class PreTrainedModel extends Callable{constructor(n,s){super(),this.config=n,this.session=s}async dispose(){let n=[];for(let s of Object.keys(this)){let c=this[s];c instanceof InferenceSession&&n.push(c.handler.dispose())}return await Promise.all(n)}static async from_pretrained(n,{quantized:s=!0,progress_callback:c=null,config:l=null,cache_dir:f=null,local_files_only:a=!1,revision:h="main"}={}){let p=await loadAutoModel(n,{quantized:s,progress_callback:c,config:l,cache_dir:f,local_files_only:a,revision:h});return new this(...p)}async _call(n){return await sessionRun(this.session,n)}async forward(n){throw Error("forward should be implemented in subclasses.")}_get_logits_processor(n,s,c=null){const l=new LogitsProcessorList;return n.repetition_penalty!==null&&n.repetition_penalty!==1&&l.push(new RepetitionPenaltyLogitsProcessor(n.repetition_penalty)),n.no_repeat_ngram_size!==null&&n.no_repeat_ngram_size>0&&l.push(new NoRepeatNGramLogitsProcessor(n.no_repeat_ngram_size)),n.forced_bos_token_id!==null&&l.push(new ForcedBOSTokenLogitsProcessor(n.forced_bos_token_id)),n.forced_eos_token_id!==null&&l.push(new ForcedEOSTokenLogitsProcessor(n.max_length,n.forced_eos_token_id)),n.forced_decoder_ids!==null&&l.push(new ForceTokensLogitsProcessor(n.forced_decoder_ids)),c!==null&&l.extend(c),l}_get_generation_config(n){let s=new GenerationConfig;return"generation_config"in this&&Object.assign(s,this.generation_config),n!==null&&Object.assign(s,n),s}async generate(n,s=null,c=null,{inputs_attention_mask:l=null}={}){if(!(n instanceof Tensor)&&!isTypedArray(n)&&!Array.isArray(n))throw Error(`\`inputs\` must be a Tensor, TypedArray, or Array, but is "${n.constructor.name}".`);if(n.length===0)throw Error("Must supply a non-empty array of input token ids.");s=this._get_generation_config(s),c=c??new LogitsProcessorList,c=this._get_logits_processor(s,n.length,c);let f=1;const a=f+(s.max_new_tokens??1/0);let h=Sampler.getSampler(s),p=this.getStartBeams(n,f,l);for(;p.some(u=>!u.done)&&fo.sort((t,e)=>e.score-t.score).slice(0,s.num_beams)),p=u.flat(),s.callback_function&&s.callback_function(p)}return this.groupBeams(p).map(u=>s.num_return_sequences>1?u.slice(0,s.num_return_sequences).map(o=>o.output_token_ids):[u[0].output_token_ids])}groupBeams(n){const s=Object.create(null);for(const c of n)s[c.id]===void 0?s[c.id]=[c]:s[c.id].push(c);return Object.values(s)}getPastKeyValues(n,s){const c=Object.create(null);for(const l in n)if(l.startsWith("present")){let f=l.replace("present","past_key_values");s!==null&&l.includes("encoder")?c[f]=s[f]:c[f]=n[l]}return c}addPastKeyValues(n,s,c=!1){if(s===null)if(c){let l=[1,this.num_encoder_heads,0,this.encoder_dim_kv];for(let a=0;a{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(_,n)},loadImageFunction=self.createImageBitmap,ImageDataClass=self.ImageData;else if(fs)loadImageFunction=async _=>{let{data:n,info:s}=await _.raw().toBuffer({resolveWithObject:!0});return new CustomImage(new Uint8ClampedArray(n),s.width,s.height,s.channels)};else throw new Error("Unable to load image processing library.");const RESAMPLING_MAPPING={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"};class CustomImage{constructor(n,s,c,l){this._update(n,s,c,l)}static async read(n){if(n instanceof CustomImage)return n;if(isString(n)||n instanceof URL)return await this.fromURL(n);throw new Error(`Unsupported input type: ${typeof n}`)}static async fromURL(n){let c=await(await getFile(n)).blob();return this.fromBlob(c)}static async fromBlob(n){if(BROWSER_ENV){let s=await loadImageFunction(n);const c=createCanvasFunction(s.width,s.height).getContext("2d");return c.drawImage(s,0,0),new this(c.getImageData(0,0,s.width,s.height).data,s.width,s.height,4)}else{let s=fs(await n.arrayBuffer());return await loadImageFunction(s)}}grayscale(){if(this.channels===1)return this;let n=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 3:case 4:for(let s=0,c=0;s=0?p=c:o=-c,l>=0?u=l:t=-l,h.drawImage(a,p,u,n,s,o,t,n,s),new CustomImage(h.getImageData(0,0,n,s).data,n,s,4).convert(f)}else{let f=fs(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}});if(c>=0&&l>=0)f=f.extract({left:Math.floor(c),top:Math.floor(l),width:n,height:s});else if(c<=0&&l<=0){let a=Math.floor(-l),h=Math.floor(-c);f=f.extend({top:a,left:h,right:n-this.width-h,bottom:s-this.height-a})}else{let a=[0,0],h=0;l<0?(a[0]=Math.floor(-l),a[1]=s-this.height-a[0]):h=Math.floor(l);let p=[0,0],u=0;c<0?(p[0]=Math.floor(-c),p[1]=n-this.width-p[0]):u=Math.floor(c),f=f.extend({top:a[0],bottom:a[1],left:p[0],right:p[1]}).extract({left:u,top:h,width:n,height:s})}return await loadImageFunction(f)}}toCanvas(){let n=this.clone().rgba(),s=createCanvasFunction(n.width,n.height),c=new ImageDataClass(n.data,n.width,n.height);return s.getContext("2d").putImageData(c,0,0),s}_update(n,s,c,l=null){return this.data=n,this.width=s,this.height=c,l!==null&&(this.channels=l),this}clone(){return new CustomImage(this.data.slice(),this.width,this.height,this.channels)}convert(n){if(this.channels===n)return this;switch(n){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}save(n,s="image/png"){if(!env.useFS)throw new Error("Unable to save the image because filesystem is disabled in this environment.");const l=this.toCanvas().toBuffer(s);fs.writeFileSync(n,l)}}class FeatureExtractor extends Callable{constructor(n){super(),this.config=n}}class ImageFeatureExtractor extends FeatureExtractor{constructor(n){super(n),this.image_mean=this.config.image_mean,this.image_std=this.config.image_std,this.resample=this.config.resample??2,this.do_rescale=this.config.do_rescale??!0,this.rescale_factor=this.config.rescale_factor??1/255,this.do_normalize=this.config.do_normalize,this.do_resize=this.config.do_resize,this.size=this.config.size,this.do_center_crop=this.config.do_center_crop,this.crop_size=this.config.crop_size,this.do_convert_rgb=this.config.do_convert_rgb??!0,this.pad_size=this.config.pad_size,this.do_pad=(this.config.do_pad??!1)&&this.pad_size}async preprocess(n){this.do_convert_rgb&&(n=n.rgb());const s=n.width,c=n.height;if(this.do_resize){let u,o;if(Number.isInteger(this.size)?(u=this.size,o=this.config.max_size??u):(u=this.size.shortest_edge,o=this.size.longest_edge),u!==void 0||o!==void 0){const t=u===void 0?1:Math.max(u/s,u/c),e=s*t,r=c*t,i=o===void 0?1:Math.min(o/e,o/r);n=await n.resize(Math.floor(e*i),Math.floor(r*i),{resample:this.resample})}else if(this.size.width!==void 0&&this.size.height!==void 0)n=await n.resize(this.size.width,this.size.height,{resample:this.resample});else throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(this.size)}`)}if(this.do_center_crop){let u,o;Number.isInteger(this.crop_size)?(u=this.crop_size,o=this.crop_size):(u=this.crop_size.width,o=this.crop_size.height),n=await n.center_crop(u,o)}let l=[n.height,n.width];if(this.do_pad){let u=0,o=this.pad_size.width-n.width,t=0,e=this.pad_size.height-n.height;n=await n.pad([u,o,t,e])}const f=Float32Array.from(n.data);if(this.do_rescale)for(let u=0;uthis.preprocess(l)));return s.forEach(l=>l.pixel_values.dims=[1,...l.pixel_values.dims]),{pixel_values:cat(s.map(l=>l.pixel_values)),original_sizes:s.map(l=>l.original_size),reshaped_input_sizes:s.map(l=>l.reshaped_input_size)}}}class ViTFeatureExtractor extends ImageFeatureExtractor{}class DetrFeatureExtractor extends ImageFeatureExtractor{async _call(n){let s=await super._call(n),c=[s.pixel_values.dims[0],64,64];return s.pixel_mask=new Tensor("int64",new BigInt64Array(c.reduce((l,f)=>l*f)).fill(1n),c),s}center_to_corners_format([n,s,c,l]){return[n-c/2,s-l/2,n+c/2,s+l/2]}post_process_object_detection(n,s=.5,c=null){const l=n.logits,f=n.pred_boxes,[a,h,p]=l.dims;if(c!==null&&c.length!==a)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let u=[];for(let o=0;os){let w=i.get(d).data;w=this.center_to_corners_format(w),t!==null&&(w=w.map((v,S)=>v*t[(S+1)%2])),e.boxes.push(w),e.classes.push(m),e.scores.push(y)}}u.push(e)}return u}remove_low_and_no_objects(n,s,c,l){let f=[],a=[],h=[];for(let p=0;pc&&(f.push(o),a.push(r),h.push(t))}return[f,a,h]}check_segment_validity(n,s,c,l=.5,f=.8){let a=[],h=0,p=0;for(let o=0;o=l&&++p;let u=h>0&&p>0;return u&&(u=h/p>f),[u,a]}compute_segments(n,s,c,l,f,a=null,h=null){let[p,u]=h??n[0].dims,o=new Tensor("int32",new Int32Array(p*u),[p,u]),t=[];if(h!==null)for(let d=0;dr[m]&&(e[m]=d,r[m]=n[d].data[m])}let i=0;for(let d=0;dBigInt(Math.round(p)))),a);return{pixel_values:c,original_sizes:l,reshaped_input_sizes:f,input_points:h}}post_process_masks(n,s,c,{mask_threshold:l=0,binarize:f=!0,pad_size:a=null}={}){let h=[];a=a??this.pad_size;let p=[a.height,a.width];for(let u=0;ub>l),m.dims)),m.dims=[1,...m.dims],r.push(m)}let i=cat(r);h.push(i)}return h}}class WhisperFeatureExtractor extends FeatureExtractor{calcOffset(n,s){return Math.abs((n+s)%(2*s)-s)}padReflect(n,s,c){const l=new Float32Array(n.length+s+c),f=n.length-1;for(let a=0;a>1;++v){const S=(v+1-c)**2/2,A=Math.sqrt(m**2+b**2)**S,O=S*Math.atan2(b,m);let x=2*v;u[x]=A*Math.cos(O),u[x+1]=A*Math.sin(O),o[x]=u[x],o[x+1]=-u[x+1]}const y=u.subarray(l,f),w=new FFT(a>>1);w.transform(r,o);for(let v=0;v>1,$=S[I]*s[I];t[O]=$*y[O],t[x]=$*y[x]}w.transform(i,t);for(let O=0;Ol?a-l:0,u=a>1,u=new Float32Array(h*p);for(let m=0;mthis.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`.");let s=n.slice(0,this.config.n_samples),c=this._extract_fbank_features(s);return{input_features:new Tensor("float32",c.data,[1,...c.dims])}}}class Processor extends Callable{constructor(n){super(),this.feature_extractor=n}async _call(n){return await this.feature_extractor(n)}}class SamProcessor extends Processor{async _call(n,s){return await this.feature_extractor(n,s)}post_process_masks(...n){return this.feature_extractor.post_process_masks(...n)}}class WhisperProcessor extends Processor{async _call(n){return await this.feature_extractor(n)}}class AutoProcessor{static async from_pretrained(n,{progress_callback:s=null,config:c=null,cache_dir:l=null,local_files_only:f=!1,revision:a="main"}={}){let h=c??await getModelJSON(n,"preprocessor_config.json",!0,{progress_callback:s,config:c,cache_dir:l,local_files_only:f,revision:a}),p=h.feature_extractor_type??h.image_processor_type,u=this.FEATURE_EXTRACTOR_CLASS_MAPPING[p];if(!u)if(h.size!==void 0)console.warn("Feature extractor type not specified, assuming ImageFeatureExtractor due to size parameter in config."),u=ImageFeatureExtractor;else throw new Error(`Unknown Feature Extractor type: ${h.feature_extractor_type}`);let o=this.PROCESSOR_CLASS_MAPPING[h.processor_class]??Processor,t=new u(h);return new o(t)}}fe(AutoProcessor,"FEATURE_EXTRACTOR_CLASS_MAPPING",{WhisperFeatureExtractor,ViTFeatureExtractor,DetrFeatureExtractor,SamImageProcessor}),fe(AutoProcessor,"PROCESSOR_CLASS_MAPPING",{WhisperProcessor,SamProcessor});async function read_audio(_,n){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. As a result, audio data must be passed directly to the processor. If you are running in node.js, you can use an external library (e.g., https://github.com/audiojs/web-audio-api) to do this.");const s=await(await getFile(_)).arrayBuffer(),l=await new AudioContext({sampleRate:n}).decodeAudioData(s);let f;if(l.numberOfChannels===2){const a=Math.sqrt(2);let h=l.getChannelData(0),p=l.getChannelData(1);f=new Float32Array(h.length);for(let u=0;uCustomImage.read(n))),_}class Pipeline extends Callable{constructor(n,s,c){super(),this.task=n,this.tokenizer=s,this.model=c}async dispose(){await this.model.dispose()}async _call(n){let s=this.tokenizer(n,{padding:!0,truncation:!0}),c=await this.model(s);return[s,c]}}class TextClassificationPipeline extends Pipeline{async _call(n,{topk:s=1}={}){let[c,l]=await super._call(n),f=this.model.config.id2label,a=[];for(let h of l.logits){let u=getTopItems(softmax(h.data),s).map(function(o){return{label:f[o[0]],score:o[1]}});s===1?a.push(...u):a.push(u)}return Array.isArray(n)||s===1?a:a[0]}}class TokenClassificationPipeline extends Pipeline{async _call(n,{ignore_labels:s=["O"]}={}){let c=Array.isArray(n);c||(n=[n]);let l=this.tokenizer,[f,a]=await super._call(n),h=a.logits,p=this.model.config.id2label,u=[];for(let o=0;o[r,i]).filter(r=>r[1]>u),t=Array.from(softmax(f.end_logits.get(h).data)).map((r,i)=>[r,i]).filter(r=>r[1]>u),e=product(o,t).filter(r=>r[0][1]<=r[1][1]).map(r=>[r[0][1],r[1][1],r[0][0]*r[1][0]]).sort((r,i)=>i[2]-r[2]);for(let r=0;r{let i=[...p];return i[u]=r[0],{score:r[1],token:r[0],token_str:f.model.vocab[r[0]],sequence:f.decode(i,{skip_special_tokens:!0})}}))}return Array.isArray(n)?a:a[0]}}class Text2TextGenerationPipeline extends Pipeline{constructor(){super(...arguments);fe(this,"_key",null)}async _call(s,c={}){Array.isArray(s)||(s=[s]),this.model.config.prefix&&(s=s.map(u=>this.model.config.prefix+u));let l=this.model.config.task_specific_params;l&&l[this.task]&&l[this.task].prefix&&(s=s.map(u=>l[this.task].prefix+u));let f={padding:!0,truncation:!0},a;this instanceof TranslationPipeline&&"_build_translation_inputs"in this.tokenizer?a=this.tokenizer._build_translation_inputs(s,f,c).input_ids:a=this.tokenizer(s,f).input_ids;let h=(await this.model.generate(a,c)).flat(),p=this.tokenizer.batch_decode(h,{skip_special_tokens:!0});return this._key!==null&&(p=p.map(u=>this._key===null?u:{[this._key]:u})),p}}class SummarizationPipeline extends Text2TextGenerationPipeline{constructor(){super(...arguments);fe(this,"_key","summary_text")}}class TranslationPipeline extends Text2TextGenerationPipeline{constructor(){super(...arguments);fe(this,"_key","translation_text")}}class TextGenerationPipeline extends Pipeline{async _call(n,s={}){let c=typeof n=="string"||n instanceof String;c&&(n=[n]),this.tokenizer.padding_side="left";let l=this.tokenizer(n,{padding:!0,truncation:!0}),f=l.input_ids,a=l.attention_mask,p=(await this.model.generate(f,s,null,{inputs_attention_mask:a})).map((u,o)=>{let t=n[o].trim();return this.tokenizer.batch_decode(u,{skip_special_tokens:!0}).map(r=>({generated_text:t+r}))});return c&&p.length===1?p[0]:p}}class ZeroShotClassificationPipeline extends Pipeline{constructor(n,s,c){super(n,s,c),this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([l,f])=>[l.toLowerCase(),f])),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.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(n,s,{hypothesis_template:c="This example is {}.",multi_label:l=!1}={}){let f=Array.isArray(n);f||(n=[n]),Array.isArray(s)||(s=[s]);let a=s.map(u=>c.replace("{}",u)),h=l||s.length===1,p=[];for(let u of n){let o=[];for(let r of a){let i=this.tokenizer(u,{text_pair:r}),d=await this.model(i);h?o.push([d.logits.data[this.contradiction_id],d.logits.data[this.entailment_id]]):o.push(d.logits.data[this.entailment_id])}let t;h?t=o.map(r=>softmax(r)[1]):t=softmax(o);let e=t.map((r,i)=>[r,i]).sort((r,i)=>i[0]-r[0]);p.push({sequence:u,labels:e.map(r=>s[r[1]]),scores:e.map(r=>r[0])})}return f?p:p[0]}}class FeatureExtractionPipeline extends Pipeline{_mean_pooling(n,s){let c=[n.dims[0],n.dims[2]],l=new n.data.constructor(c[0]*c[1]),[f,a,h]=n.dims,p=0;for(let u=0;ul+f*f));for(let l=0;l0){if(f===null)f=l/6;else if(l<=f)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const g=u*l,m=u*f,b=g-2*m;let y=0;for(;y=e.length;r.push({stride:[w.length,S?0:m,A?0:m],input_features:v.input_features,is_last:A}),y+=b}}else r=[{stride:[e.length,0,0],input_features:(await this.processor(e)).input_features,is_last:!0}];for(let g of r){let m=await this.model.generate(g.input_features,s);g.tokens=m[0].flat(),g.stride=g.stride.map(b=>b/u),a!==null&&a(g)}let[i,d]=this.tokenizer._decode_asr(r,{time_precision:o,return_timestamps:c,force_full_sequences:h});t.push({text:i,...d})}return p?t[0]:t}}class ImageToTextPipeline extends Pipeline{constructor(n,s,c,l){super(n,s,c),this.processor=l}async _call(n,s={}){let c=Array.isArray(n);n=await prepareImages(n);let l=(await this.processor(n)).pixel_values,f=[];for(let a of l){a.dims=[1,...a.dims];let h=(await this.model.generate(a,s)).flat(),p=this.tokenizer.batch_decode(h,{skip_special_tokens:!0}).map(u=>({generated_text:u.trim()}));f.push(p)}return c?f:f[0]}}class ImageClassificationPipeline extends Pipeline{constructor(n,s,c){super(n,null,s),this.processor=c}async _call(n,{topk:s=1}={}){let c=Array.isArray(n);n=await prepareImages(n);let l=await this.processor(n),f=await this.model(l),a=this.model.config.id2label,h=[];for(let p of f.logits){let o=getTopItems(softmax(p.data),s).map(function(t){return{label:a[t[0]],score:t[1]}});s===1?h.push(...o):h.push(o)}return c||s===1?h:h[0]}}class ImageSegmentationPipeline extends Pipeline{constructor(n,s,c){super(n,null,s),this.processor=c,this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(n,{threshold:s=.5,mask_threshold:c=.5,overlap_mask_area_threshold:l=.8,label_ids_to_fuse:f=null,target_sizes:a=null,subtask:h=null}={}){if(Array.isArray(n)&&n.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");n=await prepareImages(n);let u=n.map(i=>[i.height,i.width]),o=await this.processor(n),t=await this.model(o),e=null;if(h!==null)e=this.subtasks_mapping[h];else for(let[i,d]of Object.entries(this.subtasks_mapping))if(d in this.processor.feature_extractor){e=this.processor.feature_extractor[d].bind(this.processor.feature_extractor),h=i;break}let r=[];if(h==="panoptic"||h==="instance"){let i=e(t,s,c,l,f,a??u)[0],d=i.segmentation,g=this.model.config.id2label;for(let m of i.segments_info){let b=new Uint8ClampedArray(d.data.length);for(let w=0;wc.replace("{}",o)),a=this.tokenizer(f,{padding:!0,truncation:!0}),h=await this.processor(n),p=await this.model({...a,...h}),u=[];for(let o of p.logits_per_image){let t=softmax(o.data);u.push([...t].map((e,r)=>({score:e,label:s[r]})))}return l?u:u[0]}}class ObjectDetectionPipeline extends Pipeline{constructor(n,s,c){super(n,null,s),this.processor=c}async _call(n,{threshold:s=.9,percentage:c=!1}={}){let l=Array.isArray(n);if(l&&n.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");n=await prepareImages(n);let f=c?null:n.map(o=>[o.height,o.width]),a=await this.processor(n),h=await this.model(a),p=this.processor.feature_extractor.post_process_object_detection(h,s,f),u=this.model.config.id2label;return p.forEach(o=>o.labels=o.classes.map(t=>u[t])),l?p:p[0]}}const SUPPORTED_TASKS={"text-classification":{tokenizer:AutoTokenizer,pipeline:TextClassificationPipeline,model:AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:AutoTokenizer,pipeline:TokenClassificationPipeline,model:AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:AutoTokenizer,pipeline:QuestionAnsweringPipeline,model:AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:AutoTokenizer,pipeline:FillMaskPipeline,model:AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:AutoTokenizer,pipeline:SummarizationPipeline,model:AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:AutoTokenizer,pipeline:TranslationPipeline,model:AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:AutoTokenizer,pipeline:Text2TextGenerationPipeline,model:AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:AutoTokenizer,pipeline:TextGenerationPipeline,model:AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:AutoTokenizer,pipeline:ZeroShotClassificationPipeline,model:AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"automatic-speech-recognition":{tokenizer:AutoTokenizer,pipeline:AutomaticSpeechRecognitionPipeline,model:AutoModelForSeq2SeqLM,processor:AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"image-to-text":{tokenizer:AutoTokenizer,pipeline:ImageToTextPipeline,model:AutoModelForVision2Seq,processor:AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:ImageClassificationPipeline,model:AutoModelForImageClassification,processor:AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:ImageSegmentationPipeline,model:AutoModelForImageSegmentation,processor:AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:AutoTokenizer,pipeline:ZeroShotImageClassificationPipeline,model:AutoModel,processor:AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ObjectDetectionPipeline,model:AutoModelForObjectDetection,processor:AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"feature-extraction":{tokenizer:AutoTokenizer,pipeline:FeatureExtractionPipeline,model:AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"}},TASK_ALIASES={"sentiment-analysis":"text-classification",ner:"token-classification",vqa:"visual-question-answering",embeddings:"feature-extraction"};async function pipeline(_,n=null,{quantized:s=!0,progress_callback:c=null,config:l=null,cache_dir:f=null,local_files_only:a=!1,revision:h="main"}={}){_=TASK_ALIASES[_]??_;let p=SUPPORTED_TASKS[_.split("_",1)[0]];if(!p)throw Error(`Unsupported pipeline: ${_}. Must be one of [${Object.keys(SUPPORTED_TASKS)}]`);n||(n=p.default.model,console.log(`No model specified. Using default model: "${n}".`));let u=p.tokenizer,o=p.model,t=p.pipeline,e=p.processor,r=[],i={quantized:s,progress_callback:c,config:l,cache_dir:f,local_files_only:a,revision:h};u&&r.push(u.from_pretrained(n,i)),o&&r.push(o.from_pretrained(n,i)),e&&r.push(e.from_pretrained(n,i));let d=await Promise.all(r);return dispatchCallback(c,{status:"ready",task:_,model:n}),new t(_,...d)}function product(..._){return _.reduce((n,s)=>n.flatMap(c=>s.map(l=>[c,l])))}class MyTranslationPipeline{static async getInstance(n=null){return this.instance===null&&(this.instance=pipeline(this.task,this.model,{progress_callback:n})),this.instance}}fe(MyTranslationPipeline,"task","translation"),fe(MyTranslationPipeline,"model","Xenova/nllb-200-distilled-600M"),fe(MyTranslationPipeline,"instance",null),self.addEventListener("message",async _=>{let n=await MyTranslationPipeline.getInstance(c=>{self.postMessage(c)}),s=await n(_.data.text,{tgt_lang:_.data.tgt_lang,src_lang:_.data.src_lang,callback_function:c=>{self.postMessage({status:"update",output:n.tokenizer.decode(c[0].output_token_ids,{skip_special_tokens:!0})})}});self.postMessage({status:"complete",output:s})})})(); diff --git a/assets/worker-CMOjGuql.js b/assets/worker-CMOjGuql.js new file mode 100644 index 0000000000000000000000000000000000000000..07ad54412385db8d99cde2d48b62458212961789 --- /dev/null +++ b/assets/worker-CMOjGuql.js @@ -0,0 +1,2787 @@ +var C_=Object.defineProperty;var k_=(cr,Xr,ti)=>Xr in cr?C_(cr,Xr,{enumerable:!0,configurable:!0,writable:!0,value:ti}):cr[Xr]=ti;var fe=(cr,Xr,ti)=>k_(cr,typeof Xr!="symbol"?Xr+"":Xr,ti);(function(){"use strict";var cr={},Xr={"./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm":(ze,A,r)=>{ze.exports=r.p+"ort-wasm-simd-threaded.jsep.wasm"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb":(ze,A,r)=>{ze.exports=r.p+"ort.bundle.min.mjs"},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(ze,A,r)=>{r.r(A),r.d(A,{Environment:()=>st,Interpreter:()=>dt,Template:()=>ht,parse:()=>ye,tokenize:()=>M});var _=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",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"}),D=Object.freeze({set:_.Set,for:_.For,in:_.In,is:_.Is,if:_.If,else:_.Else,endif:_.EndIf,elif:_.ElseIf,endfor:_.EndFor,and:_.And,or:_.Or,not:_.Not,"not in":_.NotIn,macro:_.Macro,endmacro:_.EndMacro,true:_.BooleanLiteral,false:_.BooleanLiteral,none:_.NullLiteral,True:_.BooleanLiteral,False:_.BooleanLiteral,None:_.NullLiteral}),j=class{constructor(L,oe){this.value=L,this.type=oe}};function Y(L){return/\w/.test(L)}function N(L){return/[0-9]/.test(L)}var g=[["{%",_.OpenStatement],["%}",_.CloseStatement],["{{",_.OpenExpression],["}}",_.CloseExpression],["(",_.OpenParen],[")",_.CloseParen],["{",_.OpenCurlyBracket],["}",_.CloseCurlyBracket],["[",_.OpenSquareBracket],["]",_.CloseSquareBracket],[",",_.Comma],[".",_.Dot],[":",_.Colon],["|",_.Pipe],["<=",_.ComparisonBinaryOperator],[">=",_.ComparisonBinaryOperator],["==",_.ComparisonBinaryOperator],["!=",_.ComparisonBinaryOperator],["<",_.ComparisonBinaryOperator],[">",_.ComparisonBinaryOperator],["+",_.AdditiveBinaryOperator],["-",_.AdditiveBinaryOperator],["*",_.MultiplicativeBinaryOperator],["/",_.MultiplicativeBinaryOperator],["%",_.MultiplicativeBinaryOperator],["=",_.Equals]],v=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function y(L,oe={}){return L.endsWith(` +`)&&(L=L.slice(0,-1)),L=L.replace(/{#.*?#}/gs,"{##}"),oe.lstrip_blocks&&(L=L.replace(/^[ \t]*({[#%])/gm,"$1")),oe.trim_blocks&&(L=L.replace(/([#%]})\n/g,"$1")),L.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function M(L,oe={}){var Je,ut,mt;const H=[],me=y(L,oe);let $e=0;const We=vt=>{let kt="";for(;vt(me[$e]);){if(me[$e]==="\\"){if(++$e,$e>=me.length)throw new SyntaxError("Unexpected end of input");const At=me[$e++],is=v.get(At);if(is===void 0)throw new SyntaxError(`Unexpected escaped character: ${At}`);kt+=is;continue}if(kt+=me[$e++],$e>=me.length)throw new SyntaxError("Unexpected end of input")}return kt};e:for(;$e0){H.push(new j(At,_.Text));continue}}We(At=>/\s/.test(At));const kt=me[$e];if(kt==="-"||kt==="+"){const At=(ut=H.at(-1))==null?void 0:ut.type;if(At===_.Text||At===void 0)throw new SyntaxError(`Unexpected character: ${kt}`);switch(At){case _.Identifier:case _.NumericLiteral:case _.BooleanLiteral:case _.NullLiteral:case _.StringLiteral:case _.CloseParen:case _.CloseSquareBracket:break;default:{++$e;const is=We(N);H.push(new j(`${kt}${is}`,is.length>0?_.NumericLiteral:_.UnaryOperator));continue}}}for(const[At,is]of g)if(me.slice($e,$e+At.length)===At){H.push(new j(At,is)),$e+=At.length;continue e}if(kt==="'"||kt==='"'){++$e;const At=We(is=>is!==kt);H.push(new j(At,_.StringLiteral)),++$e;continue}if(N(kt)){const At=We(N);H.push(new j(At,_.NumericLiteral));continue}if(Y(kt)){const At=We(Y),is=Object.hasOwn(D,At)?D[At]:_.Identifier;is===_.In&&((mt=H.at(-1))==null?void 0:mt.type)===_.Not?(H.pop(),H.push(new j("not in",_.NotIn))):H.push(new j(At,is));continue}throw new SyntaxError(`Unexpected character: ${kt}`)}return H}var b=class{constructor(){fe(this,"type","Statement")}},I=class extends b{constructor(oe){super();fe(this,"type","Program");this.body=oe}},K=class extends b{constructor(oe,H,me){super();fe(this,"type","If");this.test=oe,this.body=H,this.alternate=me}},te=class extends b{constructor(oe,H,me,$e){super();fe(this,"type","For");this.loopvar=oe,this.iterable=H,this.body=me,this.defaultBlock=$e}},ne=class extends b{constructor(oe,H){super();fe(this,"type","Set");this.assignee=oe,this.value=H}},W=class extends b{constructor(oe,H,me){super();fe(this,"type","Macro");this.name=oe,this.args=H,this.body=me}},U=class extends b{constructor(){super(...arguments);fe(this,"type","Expression")}},X=class extends U{constructor(oe,H,me){super();fe(this,"type","MemberExpression");this.object=oe,this.property=H,this.computed=me}},$=class extends U{constructor(oe,H){super();fe(this,"type","CallExpression");this.callee=oe,this.args=H}},S=class extends U{constructor(oe){super();fe(this,"type","Identifier");this.value=oe}},w=class extends U{constructor(oe){super();fe(this,"type","Literal");this.value=oe}},x=class extends w{constructor(){super(...arguments);fe(this,"type","NumericLiteral")}},O=class extends w{constructor(){super(...arguments);fe(this,"type","StringLiteral")}},ae=class extends w{constructor(){super(...arguments);fe(this,"type","BooleanLiteral")}},ie=class extends w{constructor(){super(...arguments);fe(this,"type","NullLiteral")}},ve=class extends w{constructor(){super(...arguments);fe(this,"type","ArrayLiteral")}},we=class extends w{constructor(){super(...arguments);fe(this,"type","TupleLiteral")}},re=class extends w{constructor(){super(...arguments);fe(this,"type","ObjectLiteral")}},xe=class extends U{constructor(oe,H,me){super();fe(this,"type","BinaryExpression");this.operator=oe,this.left=H,this.right=me}},ce=class extends U{constructor(oe,H){super();fe(this,"type","FilterExpression");this.operand=oe,this.filter=H}},ke=class extends U{constructor(oe,H){super();fe(this,"type","SelectExpression");this.iterable=oe,this.test=H}},Ae=class extends U{constructor(oe,H,me){super();fe(this,"type","TestExpression");this.operand=oe,this.negate=H,this.test=me}},Ee=class extends U{constructor(oe,H){super();fe(this,"type","UnaryExpression");this.operator=oe,this.argument=H}},tt=class extends U{constructor(oe=void 0,H=void 0,me=void 0){super();fe(this,"type","SliceExpression");this.start=oe,this.stop=H,this.step=me}},Ge=class extends U{constructor(oe,H){super();fe(this,"type","KeywordArgumentExpression");this.key=oe,this.value=H}};function ye(L){const oe=new I([]);let H=0;function me(it,Tt){const Dt=L[H++];if(!Dt||Dt.type!==it)throw new Error(`Parser Error: ${Tt}. ${Dt.type} !== ${it}.`);return Dt}function $e(){switch(L[H].type){case _.Text:return ut();case _.OpenStatement:return mt();case _.OpenExpression:return vt();default:throw new SyntaxError(`Unexpected token type: ${L[H].type}`)}}function We(...it){return H+it.length<=L.length&&it.some((Tt,Dt)=>Tt!==L[H+Dt].type)}function Je(...it){return H+it.length<=L.length&&it.every((Tt,Dt)=>Tt===L[H+Dt].type)}function ut(){return new O(me(_.Text,"Expected text token").value)}function mt(){me(_.OpenStatement,"Expected opening statement token");let it;switch(L[H].type){case _.Set:++H,it=kt(),me(_.CloseStatement,"Expected closing statement token");break;case _.If:++H,it=At(),me(_.OpenStatement,"Expected {% token"),me(_.EndIf,"Expected endif token"),me(_.CloseStatement,"Expected %} token");break;case _.Macro:++H,it=is(),me(_.OpenStatement,"Expected {% token"),me(_.EndMacro,"Expected endmacro token"),me(_.CloseStatement,"Expected %} token");break;case _.For:++H,it=ks(),me(_.OpenStatement,"Expected {% token"),me(_.EndFor,"Expected endfor token"),me(_.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${L[H].type}`)}return it}function vt(){me(_.OpenExpression,"Expected opening expression token");const it=Ds();return me(_.CloseExpression,"Expected closing expression token"),it}function kt(){const it=Ds();if(Je(_.Equals)){++H;const Tt=kt();return new ne(it,Tt)}return it}function At(){var Vs,jr,Or,Ms,ar,Is,Pr,ts;const it=Ds();me(_.CloseStatement,"Expected closing statement token");const Tt=[],Dt=[];for(;!(((Vs=L[H])==null?void 0:Vs.type)===_.OpenStatement&&(((jr=L[H+1])==null?void 0:jr.type)===_.ElseIf||((Or=L[H+1])==null?void 0:Or.type)===_.Else||((Ms=L[H+1])==null?void 0:Ms.type)===_.EndIf));)Tt.push($e());if(((ar=L[H])==null?void 0:ar.type)===_.OpenStatement&&((Is=L[H+1])==null?void 0:Is.type)!==_.EndIf)if(++H,Je(_.ElseIf))me(_.ElseIf,"Expected elseif token"),Dt.push(At());else for(me(_.Else,"Expected else token"),me(_.CloseStatement,"Expected closing statement token");!(((Pr=L[H])==null?void 0:Pr.type)===_.OpenStatement&&((ts=L[H+1])==null?void 0:ts.type)===_.EndIf);)Dt.push($e());return new K(it,Tt,Dt)}function is(){const it=or();if(it.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Tt=Ar();me(_.CloseStatement,"Expected closing statement token");const Dt=[];for(;We(_.OpenStatement,_.EndMacro);)Dt.push($e());return new W(it,Tt,Dt)}function ws(it=!1){const Tt=it?or:Ds,Dt=[Tt()],Vs=Je(_.Comma);for(;Vs&&(++H,Dt.push(Tt()),!!Je(_.Comma)););return Vs?new we(Dt):Dt[0]}function ks(){const it=ws(!0);if(!(it instanceof S||it instanceof we))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${it.type} instead`);me(_.In,"Expected `in` keyword following loop variable");const Tt=Ds();me(_.CloseStatement,"Expected closing statement token");const Dt=[];for(;We(_.OpenStatement,_.EndFor)&&We(_.OpenStatement,_.Else);)Dt.push($e());const Vs=[];if(Je(_.OpenStatement,_.Else))for(++H,++H,me(_.CloseStatement,"Expected closing statement token");We(_.OpenStatement,_.EndFor);)Vs.push($e());return new te(it,Tt,Dt,Vs)}function Ds(){return sr()}function sr(){const it=Sr();if(Je(_.If)){++H;const Tt=Sr();if(Je(_.Else)){++H;const Dt=Sr();return new K(Tt,[it],[Dt])}else return new ke(it,Tt)}return it}function Sr(){let it=Yr();for(;Je(_.Or);){const Tt=L[H];++H;const Dt=Yr();it=new xe(Tt,it,Dt)}return it}function Yr(){let it=Us();for(;Je(_.And);){const Tt=L[H];++H;const Dt=Us();it=new xe(Tt,it,Dt)}return it}function Us(){let it;for(;Je(_.Not);){const Tt=L[H];++H;const Dt=Us();it=new Ee(Tt,Dt)}return it??Tr()}function Tr(){let it=Nt();for(;Je(_.ComparisonBinaryOperator)||Je(_.In)||Je(_.NotIn);){const Tt=L[H];++H;const Dt=Nt();it=new xe(Tt,it,Dt)}return it}function Nt(){let it=Ir();for(;Je(_.AdditiveBinaryOperator);){const Tt=L[H];++H;const Dt=Ir();it=new xe(Tt,it,Dt)}return it}function Jr(){const it=en();return Je(_.OpenParen)?$r(it):it}function $r(it){let Tt=new $(it,Ar());return Je(_.OpenParen)&&(Tt=$r(Tt)),Tt}function Ar(){me(_.OpenParen,"Expected opening parenthesis for arguments list");const it=Zr();return me(_.CloseParen,"Expected closing parenthesis for arguments list"),it}function Zr(){const it=[];for(;!Je(_.CloseParen);){let Tt=Ds();if(Je(_.Equals)){if(++H,!(Tt instanceof S))throw new SyntaxError("Expected identifier for keyword argument");const Dt=Ds();Tt=new Ge(Tt,Dt)}it.push(Tt),Je(_.Comma)&&++H}return it}function pr(){const it=[];let Tt=!1;for(;!Je(_.CloseSquareBracket);)Je(_.Colon)?(it.push(void 0),++H,Tt=!0):(it.push(Ds()),Je(_.Colon)&&(++H,Tt=!0));if(it.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Tt){if(it.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new tt(...it)}return it[0]}function en(){let it=or();for(;Je(_.Dot)||Je(_.OpenSquareBracket);){const Tt=L[H];++H;let Dt;const Vs=Tt.type!==_.Dot;if(Vs)Dt=pr(),me(_.CloseSquareBracket,"Expected closing square bracket");else if(Dt=or(),Dt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");it=new X(it,Dt,Vs)}return it}function Ir(){let it=Rr();for(;Je(_.MultiplicativeBinaryOperator);){const Tt=L[H];++H;const Dt=Rr();it=new xe(Tt,it,Dt)}return it}function Rr(){let it=Nr();for(;Je(_.Is);){++H;const Tt=Je(_.Not);Tt&&++H;let Dt=or();if(Dt instanceof ae?Dt=new S(Dt.value.toString()):Dt instanceof ie&&(Dt=new S("none")),!(Dt instanceof S))throw new SyntaxError("Expected identifier for the test");it=new Ae(it,Tt,Dt)}return it}function Nr(){let it=Jr();for(;Je(_.Pipe);){++H;let Tt=or();if(!(Tt instanceof S))throw new SyntaxError("Expected identifier for the filter");Je(_.OpenParen)&&(Tt=$r(Tt)),it=new ce(it,Tt)}return it}function or(){const it=L[H];switch(it.type){case _.NumericLiteral:return++H,new x(Number(it.value));case _.StringLiteral:return++H,new O(it.value);case _.BooleanLiteral:return++H,new ae(it.value.toLowerCase()==="true");case _.NullLiteral:return++H,new ie(null);case _.Identifier:return++H,new S(it.value);case _.OpenParen:{++H;const Tt=ws();if(L[H].type!==_.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${L[H].type} instead`);return++H,Tt}case _.OpenSquareBracket:{++H;const Tt=[];for(;!Je(_.CloseSquareBracket);)Tt.push(Ds()),Je(_.Comma)&&++H;return++H,new ve(Tt)}case _.OpenCurlyBracket:{++H;const Tt=new Map;for(;!Je(_.CloseCurlyBracket);){const Dt=Ds();me(_.Colon,"Expected colon between key and value in object literal");const Vs=Ds();Tt.set(Dt,Vs),Je(_.Comma)&&++H}return++H,new re(Tt)}default:throw new SyntaxError(`Unexpected token: ${it.type}`)}}for(;H=0?(oe=(oe??(oe=0))<0?Math.max(L.length+oe,0):Math.min(oe,L.length),H=(H??(H=L.length))<0?Math.max(L.length+H,0):Math.min(H,L.length)):(oe=(oe??(oe=L.length-1))<0?Math.max(L.length+oe,-1):Math.min(oe,L.length-1),H=(H??(H=-1))<-1?Math.max(L.length+H,-1):Math.min(H,L.length-1));const We=[];for(let Je=oe;$e*Je<$e*H;Je+=me)We.push(L[Je]);return We}function Ce(L){return L.replace(/\b\w/g,oe=>oe.toUpperCase())}var Be=class{constructor(L=void 0){fe(this,"type","RuntimeValue");fe(this,"value");fe(this,"builtins",new Map);this.value=L}__bool__(){return new Ke(!!this.value)}},Ze=class extends Be{constructor(){super(...arguments);fe(this,"type","NumericValue")}},se=class extends Be{constructor(){super(...arguments);fe(this,"type","StringValue");fe(this,"builtins",new Map([["upper",new Ve(()=>new se(this.value.toUpperCase()))],["lower",new Ve(()=>new se(this.value.toLowerCase()))],["strip",new Ve(()=>new se(this.value.trim()))],["title",new Ve(()=>new se(Ce(this.value)))],["length",new Ze(this.value.length)],["rstrip",new Ve(()=>new se(this.value.trimEnd()))],["lstrip",new Ve(()=>new se(this.value.trimStart()))]]))}},Ke=class extends Be{constructor(){super(...arguments);fe(this,"type","BooleanValue")}},je=class extends Be{constructor(){super(...arguments);fe(this,"type","ObjectValue");fe(this,"builtins",new Map([["get",new Ve(([oe,H])=>{if(!(oe instanceof se))throw new Error(`Object key must be a string: got ${oe.type}`);return this.value.get(oe.value)??H??new Ne})],["items",new Ve(()=>new Te(Array.from(this.value.entries()).map(([oe,H])=>new Te([new se(oe),H]))))]]))}__bool__(){return new Ke(this.value.size>0)}},le=class extends je{constructor(){super(...arguments);fe(this,"type","KeywordArgumentsValue")}},Te=class extends Be{constructor(){super(...arguments);fe(this,"type","ArrayValue");fe(this,"builtins",new Map([["length",new Ze(this.value.length)]]))}__bool__(){return new Ke(this.value.length>0)}},Ue=class extends Te{constructor(){super(...arguments);fe(this,"type","TupleValue")}},Ve=class extends Be{constructor(){super(...arguments);fe(this,"type","FunctionValue")}},Ne=class extends Be{constructor(){super(...arguments);fe(this,"type","NullValue")}},Re=class extends Be{constructor(){super(...arguments);fe(this,"type","UndefinedValue")}},st=class{constructor(L){fe(this,"variables",new Map([["namespace",new Ve(L=>{if(L.length===0)return new je(new Map);if(L.length!==1||!(L[0]instanceof je))throw new Error("`namespace` expects either zero arguments or a single object argument");return L[0]})]]));fe(this,"tests",new Map([["boolean",L=>L.type==="BooleanValue"],["callable",L=>L instanceof Ve],["odd",L=>{if(L.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${L.type}`);return L.value%2!==0}],["even",L=>{if(L.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${L.type}`);return L.value%2===0}],["false",L=>L.type==="BooleanValue"&&!L.value],["true",L=>L.type==="BooleanValue"&&L.value],["none",L=>L.type==="NullValue"],["string",L=>L.type==="StringValue"],["number",L=>L.type==="NumericValue"],["integer",L=>L.type==="NumericValue"&&Number.isInteger(L.value)],["iterable",L=>L.type==="ArrayValue"||L.type==="StringValue"],["mapping",L=>L.type==="ObjectValue"],["lower",L=>{const oe=L.value;return L.type==="StringValue"&&oe===oe.toLowerCase()}],["upper",L=>{const oe=L.value;return L.type==="StringValue"&&oe===oe.toUpperCase()}],["none",L=>L.type==="NullValue"],["defined",L=>L.type!=="UndefinedValue"],["undefined",L=>L.type==="UndefinedValue"],["equalto",(L,oe)=>L.value===oe.value],["eq",(L,oe)=>L.value===oe.value]]));this.parent=L}set(L,oe){return this.declareVariable(L,ct(oe))}declareVariable(L,oe){if(this.variables.has(L))throw new SyntaxError(`Variable already declared: ${L}`);return this.variables.set(L,oe),oe}setVariable(L,oe){return this.variables.set(L,oe),oe}resolve(L){if(this.variables.has(L))return this;if(this.parent)return this.parent.resolve(L);throw new Error(`Unknown variable: ${L}`)}lookupVariable(L){try{return this.resolve(L).variables.get(L)??new Re}catch{return new Re}}},dt=class{constructor(L){fe(this,"global");this.global=L??new st}run(L){return this.evaluate(L,this.global)}evaluateBinaryExpression(L,oe){const H=this.evaluate(L.left,oe);switch(L.operator.value){case"and":return H.__bool__().value?this.evaluate(L.right,oe):H;case"or":return H.__bool__().value?H:this.evaluate(L.right,oe)}const me=this.evaluate(L.right,oe);switch(L.operator.value){case"==":return new Ke(H.value==me.value);case"!=":return new Ke(H.value!=me.value)}if(H instanceof Re||me instanceof Re)throw new Error("Cannot perform operation on undefined values");if(H instanceof Ne||me instanceof Ne)throw new Error("Cannot perform operation on null values");if(H instanceof Ze&&me instanceof Ze)switch(L.operator.value){case"+":return new Ze(H.value+me.value);case"-":return new Ze(H.value-me.value);case"*":return new Ze(H.value*me.value);case"/":return new Ze(H.value/me.value);case"%":return new Ze(H.value%me.value);case"<":return new Ke(H.value":return new Ke(H.value>me.value);case">=":return new Ke(H.value>=me.value);case"<=":return new Ke(H.value<=me.value)}else if(H instanceof Te&&me instanceof Te)switch(L.operator.value){case"+":return new Te(H.value.concat(me.value))}else if(me instanceof Te){const $e=me.value.find(We=>We.value===H.value)!==void 0;switch(L.operator.value){case"in":return new Ke($e);case"not in":return new Ke(!$e)}}if(H instanceof se||me instanceof se)switch(L.operator.value){case"+":return new se(H.value.toString()+me.value.toString())}if(H instanceof se&&me instanceof se)switch(L.operator.value){case"in":return new Ke(me.value.includes(H.value));case"not in":return new Ke(!me.value.includes(H.value))}if(H instanceof se&&me instanceof je)switch(L.operator.value){case"in":return new Ke(me.value.has(H.value));case"not in":return new Ke(!me.value.has(H.value))}throw new SyntaxError(`Unknown operator "${L.operator.value}" between ${H.type} and ${me.type}`)}evaluateArguments(L,oe){const H=[],me=new Map;for(const $e of L)if($e.type==="KeywordArgumentExpression"){const We=$e;me.set(We.key.value,this.evaluate(We.value,oe))}else{if(me.size>0)throw new Error("Positional arguments must come before keyword arguments");H.push(this.evaluate($e,oe))}return[H,me]}evaluateFilterExpression(L,oe){const H=this.evaluate(L.operand,oe);if(L.filter.type==="Identifier"){const me=L.filter;if(me.value==="tojson")return new se(lt(H));if(H instanceof Te)switch(me.value){case"list":return H;case"first":return H.value[0];case"last":return H.value[H.value.length-1];case"length":return new Ze(H.value.length);case"reverse":return new Te(H.value.reverse());case"sort":return new Te(H.value.sort(($e,We)=>{if($e.type!==We.type)throw new Error(`Cannot compare different types: ${$e.type} and ${We.type}`);switch($e.type){case"NumericValue":return $e.value-We.value;case"StringValue":return $e.value.localeCompare(We.value);default:throw new Error(`Cannot compare type: ${$e.type}`)}}));default:throw new Error(`Unknown ArrayValue filter: ${me.value}`)}else if(H instanceof se)switch(me.value){case"length":return new Ze(H.value.length);case"upper":return new se(H.value.toUpperCase());case"lower":return new se(H.value.toLowerCase());case"title":return new se(Ce(H.value));case"capitalize":return new se(H.value.charAt(0).toUpperCase()+H.value.slice(1));case"trim":return new se(H.value.trim());case"indent":return new se(H.value.split(` +`).map(($e,We)=>We===0||$e.length===0?$e:" "+$e).join(` +`));case"string":return H;default:throw new Error(`Unknown StringValue filter: ${me.value}`)}else if(H instanceof Ze)switch(me.value){case"abs":return new Ze(Math.abs(H.value));default:throw new Error(`Unknown NumericValue filter: ${me.value}`)}else if(H instanceof je)switch(me.value){case"items":return new Te(Array.from(H.value.entries()).map(([$e,We])=>new Te([new se($e),We])));case"length":return new Ze(H.value.size);default:throw new Error(`Unknown ObjectValue filter: ${me.value}`)}throw new Error(`Cannot apply filter "${me.value}" to type: ${H.type}`)}else if(L.filter.type==="CallExpression"){const me=L.filter;if(me.callee.type!=="Identifier")throw new Error(`Unknown filter: ${me.callee.type}`);const $e=me.callee.value;if($e==="tojson"){const[,We]=this.evaluateArguments(me.args,oe),Je=We.get("indent")??new Ne;if(!(Je instanceof Ze||Je instanceof Ne))throw new Error("If set, indent must be a number");return new se(lt(H,Je.value))}if(H instanceof Te){switch($e){case"selectattr":case"rejectattr":{const We=$e==="selectattr";if(H.value.some(At=>!(At instanceof je)))throw new Error(`\`${$e}\` can only be applied to array of objects`);if(me.args.some(At=>At.type!=="StringLiteral"))throw new Error(`arguments of \`${$e}\` must be strings`);const[Je,ut,mt]=me.args.map(At=>this.evaluate(At,oe));let vt;if(ut){const At=oe.tests.get(ut.value);if(!At)throw new Error(`Unknown test: ${ut.value}`);vt=At}else vt=(...At)=>At[0].__bool__().value;const kt=H.value.filter(At=>{const is=At.value.get(Je.value),ws=is?vt(is,mt):!1;return We?ws:!ws});return new Te(kt)}case"map":{const[,We]=this.evaluateArguments(me.args,oe);if(We.has("attribute")){const Je=We.get("attribute");if(!(Je instanceof se))throw new Error("attribute must be a string");const ut=We.get("default"),mt=H.value.map(vt=>{if(!(vt instanceof je))throw new Error("items in map must be an object");return vt.value.get(Je.value)??ut??new Re});return new Te(mt)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${$e}`)}else if(H instanceof se){switch($e){case"indent":{const[We,Je]=this.evaluateArguments(me.args,oe),ut=We.at(0)??Je.get("width")??new Ze(4);if(!(ut instanceof Ze))throw new Error("width must be a number");const mt=We.at(1)??Je.get("first")??new Ke(!1),vt=We.at(2)??Je.get("blank")??new Ke(!1),kt=H.value.split(` +`),At=" ".repeat(ut.value),is=kt.map((ws,ks)=>!mt.value&&ks===0||!vt.value&&ws.length===0?ws:At+ws);return new se(is.join(` +`))}}throw new Error(`Unknown StringValue filter: ${$e}`)}else throw new Error(`Cannot apply filter "${$e}" to type: ${H.type}`)}throw new Error(`Unknown filter: ${L.filter.type}`)}evaluateTestExpression(L,oe){const H=this.evaluate(L.operand,oe),me=oe.tests.get(L.test.value);if(!me)throw new Error(`Unknown test: ${L.test.value}`);const $e=me(H);return new Ke(L.negate?!$e:$e)}evaluateUnaryExpression(L,oe){const H=this.evaluate(L.argument,oe);switch(L.operator.value){case"not":return new Ke(!H.value);default:throw new SyntaxError(`Unknown operator: ${L.operator.value}`)}}evalProgram(L,oe){return this.evaluateBlock(L.body,oe)}evaluateBlock(L,oe){let H="";for(const me of L){const $e=this.evaluate(me,oe);$e.type!=="NullValue"&&$e.type!=="UndefinedValue"&&(H+=$e.value)}return new se(H)}evaluateIdentifier(L,oe){return oe.lookupVariable(L.value)}evaluateCallExpression(L,oe){const[H,me]=this.evaluateArguments(L.args,oe);me.size>0&&H.push(new le(me));const $e=this.evaluate(L.callee,oe);if($e.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${$e.type}`);return $e.value(H,oe)}evaluateSliceExpression(L,oe,H){if(!(L instanceof Te||L instanceof se))throw new Error("Slice object must be an array or string");const me=this.evaluate(oe.start,H),$e=this.evaluate(oe.stop,H),We=this.evaluate(oe.step,H);if(!(me instanceof Ze||me instanceof Re))throw new Error("Slice start must be numeric or undefined");if(!($e instanceof Ze||$e instanceof Re))throw new Error("Slice stop must be numeric or undefined");if(!(We instanceof Ze||We instanceof Re))throw new Error("Slice step must be numeric or undefined");return L instanceof Te?new Te(de(L.value,me.value,$e.value,We.value)):new se(de(Array.from(L.value),me.value,$e.value,We.value).join(""))}evaluateMemberExpression(L,oe){const H=this.evaluate(L.object,oe);let me;if(L.computed){if(L.property.type==="SliceExpression")return this.evaluateSliceExpression(H,L.property,oe);me=this.evaluate(L.property,oe)}else me=new se(L.property.value);let $e;if(H instanceof je){if(!(me instanceof se))throw new Error(`Cannot access property with non-string: got ${me.type}`);$e=H.value.get(me.value)??H.builtins.get(me.value)}else if(H instanceof Te||H instanceof se)if(me instanceof Ze)$e=H.value.at(me.value),H instanceof se&&($e=new se(H.value.at(me.value)));else if(me instanceof se)$e=H.builtins.get(me.value);else throw new Error(`Cannot access property with non-string/non-number: got ${me.type}`);else{if(!(me instanceof se))throw new Error(`Cannot access property with non-string: got ${me.type}`);$e=H.builtins.get(me.value)}return $e instanceof Be?$e:new Re}evaluateSet(L,oe){const H=this.evaluate(L.value,oe);if(L.assignee.type==="Identifier"){const me=L.assignee.value;oe.setVariable(me,H)}else if(L.assignee.type==="MemberExpression"){const me=L.assignee,$e=this.evaluate(me.object,oe);if(!($e instanceof je))throw new Error("Cannot assign to member of non-object");if(me.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");$e.value.set(me.property.value,H)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(L.assignee)}`);return new Ne}evaluateIf(L,oe){const H=this.evaluate(L.test,oe);return this.evaluateBlock(H.__bool__().value?L.body:L.alternate,oe)}evaluateFor(L,oe){const H=new st(oe);let me,$e;if(L.iterable.type==="SelectExpression"){const vt=L.iterable;$e=this.evaluate(vt.iterable,H),me=vt.test}else $e=this.evaluate(L.iterable,H);if(!($e instanceof Te))throw new Error(`Expected iterable type in for loop: got ${$e.type}`);const We=[],Je=[];for(let vt=0;vt<$e.value.length;++vt){const kt=new st(H),At=$e.value[vt];let is;if(L.loopvar.type==="Identifier")is=ws=>ws.setVariable(L.loopvar.value,At);else if(L.loopvar.type==="TupleLiteral"){const ws=L.loopvar;if(At.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${At.type}`);const ks=At;if(ws.value.length!==ks.value.length)throw new Error(`Too ${ws.value.length>ks.value.length?"few":"many"} items to unpack`);is=Ds=>{for(let sr=0;sr0?We[vt-1]:new Re],["nextitem",vt{var Je;const $e=new st(me);H=H.slice();let We;((Je=H.at(-1))==null?void 0:Je.type)==="KeywordArgumentsValue"&&(We=H.pop());for(let ut=0;utthis.evaluate(H,oe)));case"TupleLiteral":return new Ue(L.value.map(H=>this.evaluate(H,oe)));case"ObjectLiteral":{const H=new Map;for(const[me,$e]of L.value){const We=this.evaluate(me,oe);if(!(We instanceof se))throw new Error(`Object keys must be strings: got ${We.type}`);H.set(We.value,this.evaluate($e,oe))}return new je(H)}case"Identifier":return this.evaluateIdentifier(L,oe);case"CallExpression":return this.evaluateCallExpression(L,oe);case"MemberExpression":return this.evaluateMemberExpression(L,oe);case"UnaryExpression":return this.evaluateUnaryExpression(L,oe);case"BinaryExpression":return this.evaluateBinaryExpression(L,oe);case"FilterExpression":return this.evaluateFilterExpression(L,oe);case"TestExpression":return this.evaluateTestExpression(L,oe);default:throw new SyntaxError(`Unknown node type: ${L.type}`)}}};function ct(L){switch(typeof L){case"number":return new Ze(L);case"string":return new se(L);case"boolean":return new Ke(L);case"undefined":return new Re;case"object":return L===null?new Ne:Array.isArray(L)?new Te(L.map(ct)):new je(new Map(Object.entries(L).map(([oe,H])=>[oe,ct(H)])));case"function":return new Ve((oe,H)=>{const me=L(...oe.map($e=>$e.value))??null;return ct(me)});default:throw new Error(`Cannot convert to runtime value: ${L}`)}}function lt(L,oe,H){const me=H??0;switch(L.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(L.value);case"ArrayValue":case"ObjectValue":{const $e=oe?" ".repeat(oe):"",We=` +`+$e.repeat(me),Je=We+$e;if(L.type==="ArrayValue"){const ut=L.value.map(mt=>lt(mt,oe,me+1));return oe?`[${Je}${ut.join(`,${Je}`)}${We}]`:`[${ut.join(", ")}]`}else{const ut=Array.from(L.value.entries()).map(([mt,vt])=>{const kt=`"${mt}": ${lt(vt,oe,me+1)}`;return oe?`${Je}${kt}`:kt});return oe?`{${ut.join(",")}${We}}`:`{${ut.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${L.type}`)}}var ht=class{constructor(L){fe(this,"parsed");const oe=M(L,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=ye(oe)}render(L){const oe=new st;oe.set("false",!1),oe.set("true",!0),oe.set("raise_exception",$e=>{throw new Error($e)}),oe.set("range",J);for(const[$e,We]of Object.entries(L))oe.set($e,We);return new dt(oe).run(this.parsed).value}}},"./node_modules/onnxruntime-common/dist/esm/backend-impl.js":(ze,A,r)=>{r.r(A),r.d(A,{registerBackend:()=>j,resolveBackendAndExecutionProviders:()=>N});const _=new Map,D=[],j=(g,v,y)=>{if(v&&typeof v.init=="function"&&typeof v.createInferenceSessionHandler=="function"){const M=_.get(g);if(M===void 0)_.set(g,{backend:v,priority:y});else{if(M.priority>y)return;if(M.priority===y&&M.backend!==v)throw new Error(`cannot register backend "${g}" using priority ${y}`)}if(y>=0){const b=D.indexOf(g);b!==-1&&D.splice(b,1);for(let I=0;I{const v=_.get(g);if(!v)return"backend not found.";if(v.initialized)return v.backend;if(v.aborted)return v.error;{const y=!!v.initPromise;try{return y||(v.initPromise=v.backend.init(g)),await v.initPromise,v.initialized=!0,v.backend}catch(M){return y||(v.error=`${M}`,v.aborted=!0),v.error}finally{delete v.initPromise}}},N=async g=>{const v=g.executionProviders||[],y=v.map(ne=>typeof ne=="string"?ne:ne.name),M=y.length===0?D:y;let b;const I=[],K=new Set;for(const ne of M){const W=await Y(ne);typeof W=="string"?I.push({name:ne,err:W}):(b||(b=W),b===W&&K.add(ne))}if(!b)throw new Error(`no available backend found. ERR: ${I.map(ne=>`[${ne.name}] ${ne.err}`).join(", ")}`);for(const{name:ne,err:W}of I)y.includes(ne)&&console.warn(`removing requested execution provider "${ne}" from session options because it is not available: ${W}`);const te=v.filter(ne=>K.has(typeof ne=="string"?ne:ne.name));return[b,new Proxy(g,{get:(ne,W)=>W==="executionProviders"?te:Reflect.get(ne,W)})]}},"./node_modules/onnxruntime-common/dist/esm/backend.js":(ze,A,r)=>{r.r(A),r.d(A,{registerBackend:()=>_.registerBackend});var _=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js")},"./node_modules/onnxruntime-common/dist/esm/env-impl.js":(ze,A,r)=>{r.r(A),r.d(A,{env:()=>j});var _=r("./node_modules/onnxruntime-common/dist/esm/version.js");let D="warning";const j={wasm:{},webgl:{},webgpu:{},versions:{common:_.version},set logLevel(Y){if(Y!==void 0){if(typeof Y!="string"||["verbose","info","warning","error","fatal"].indexOf(Y)===-1)throw new Error(`Unsupported logging level: ${Y}`);D=Y}},get logLevel(){return D}};Object.defineProperty(j,"logLevel",{enumerable:!0})},"./node_modules/onnxruntime-common/dist/esm/env.js":(ze,A,r)=>{r.r(A),r.d(A,{env:()=>D});var _=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const D=_.env},"./node_modules/onnxruntime-common/dist/esm/index.js":(ze,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>j.InferenceSession,TRACE:()=>N.TRACE,TRACE_FUNC_BEGIN:()=>N.TRACE_FUNC_BEGIN,TRACE_FUNC_END:()=>N.TRACE_FUNC_END,Tensor:()=>Y.Tensor,TrainingSession:()=>g.TrainingSession,env:()=>D.env,registerBackend:()=>_.registerBackend});var _=r("./node_modules/onnxruntime-common/dist/esm/backend.js"),D=r("./node_modules/onnxruntime-common/dist/esm/env.js"),j=r("./node_modules/onnxruntime-common/dist/esm/inference-session.js"),Y=r("./node_modules/onnxruntime-common/dist/esm/tensor.js");r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"),r("./node_modules/onnxruntime-common/dist/esm/tensor-factory.js");var N=r("./node_modules/onnxruntime-common/dist/esm/trace.js");r("./node_modules/onnxruntime-common/dist/esm/onnx-model.js"),r("./node_modules/onnxruntime-common/dist/esm/onnx-value.js");var g=r("./node_modules/onnxruntime-common/dist/esm/training-session.js")},"./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js":(ze,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>Y});var _=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),D=r("./node_modules/onnxruntime-common/dist/esm/tensor.js"),j=r("./node_modules/onnxruntime-common/dist/esm/trace.js");class Y{constructor(g){this.handler=g}async run(g,v,y){(0,j.TRACE_FUNC_BEGIN)();const M={};let b={};if(typeof g!="object"||g===null||g instanceof D.Tensor||Array.isArray(g))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let I=!0;if(typeof v=="object"){if(v===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(v instanceof D.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(v)){if(v.length===0)throw new TypeError("'fetches' cannot be an empty array.");I=!1;for(const ne of v){if(typeof ne!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(ne)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ne}.`);M[ne]=null}if(typeof y=="object"&&y!==null)b=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else{let ne=!1;const W=Object.getOwnPropertyNames(v);for(const U of this.outputNames)if(W.indexOf(U)!==-1){const X=v[U];(X===null||X instanceof D.Tensor)&&(ne=!0,I=!1,M[U]=X)}if(ne){if(typeof y=="object"&&y!==null)b=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else b=v}}else if(typeof v<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const ne of this.inputNames)if(typeof g[ne]>"u")throw new Error(`input '${ne}' is missing in 'feeds'.`);if(I)for(const ne of this.outputNames)M[ne]=null;const K=await this.handler.run(g,M,b),te={};for(const ne in K)if(Object.hasOwnProperty.call(K,ne)){const W=K[ne];W instanceof D.Tensor?te[ne]=W:te[ne]=new D.Tensor(W.type,W.data,W.dims)}return(0,j.TRACE_FUNC_END)(),te}async release(){return this.handler.dispose()}static async create(g,v,y,M){(0,j.TRACE_FUNC_BEGIN)();let b,I={};if(typeof g=="string"){if(b=g,typeof v=="object"&&v!==null)I=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else if(g instanceof Uint8Array){if(b=g,typeof v=="object"&&v!==null)I=v;else if(typeof v<"u")throw new TypeError("'options' must be an object.")}else if(g instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&g instanceof SharedArrayBuffer){const W=g;let U=0,X=g.byteLength;if(typeof v=="object"&&v!==null)I=v;else if(typeof v=="number"){if(U=v,!Number.isSafeInteger(U))throw new RangeError("'byteOffset' must be an integer.");if(U<0||U>=W.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${W.byteLength}).`);if(X=g.byteLength-U,typeof y=="number"){if(X=y,!Number.isSafeInteger(X))throw new RangeError("'byteLength' must be an integer.");if(X<=0||U+X>W.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${W.byteLength-U}].`);if(typeof M=="object"&&M!==null)I=M;else if(typeof M<"u")throw new TypeError("'options' must be an object.")}else if(typeof y<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof v<"u")throw new TypeError("'options' must be an object.");b=new Uint8Array(W,U,X)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[K,te]=await(0,_.resolveBackendAndExecutionProviders)(I),ne=await K.createInferenceSessionHandler(b,te);return(0,j.TRACE_FUNC_END)(),new Y(ne)}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":(ze,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>D});var _=r("./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js");const D=_.InferenceSession},"./node_modules/onnxruntime-common/dist/esm/onnx-model.js":(ze,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/onnx-value.js":(ze,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js":(ze,A,r)=>{r.r(A),r.d(A,{tensorToDataURL:()=>_,tensorToImageData:()=>D});const _=(j,Y)=>{const N=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);N.width=j.dims[3],N.height=j.dims[2];const g=N.getContext("2d");if(g!=null){let v,y;(Y==null?void 0:Y.tensorLayout)!==void 0&&Y.tensorLayout==="NHWC"?(v=j.dims[2],y=j.dims[3]):(v=j.dims[3],y=j.dims[2]);const M=(Y==null?void 0:Y.format)!==void 0?Y.format:"RGB",b=Y==null?void 0:Y.norm;let I,K;b===void 0||b.mean===void 0?I=[255,255,255,255]:typeof b.mean=="number"?I=[b.mean,b.mean,b.mean,b.mean]:(I=[b.mean[0],b.mean[1],b.mean[2],0],b.mean[3]!==void 0&&(I[3]=b.mean[3])),b===void 0||b.bias===void 0?K=[0,0,0,0]:typeof b.bias=="number"?K=[b.bias,b.bias,b.bias,b.bias]:(K=[b.bias[0],b.bias[1],b.bias[2],0],b.bias[3]!==void 0&&(K[3]=b.bias[3]));const te=y*v;let ne=0,W=te,U=te*2,X=-1;M==="RGBA"?(ne=0,W=te,U=te*2,X=te*3):M==="RGB"?(ne=0,W=te,U=te*2):M==="RBG"&&(ne=0,U=te,W=te*2);for(let $=0;${const N=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let g;if(N!=null){let v,y,M;(Y==null?void 0:Y.tensorLayout)!==void 0&&Y.tensorLayout==="NHWC"?(v=j.dims[2],y=j.dims[1],M=j.dims[3]):(v=j.dims[3],y=j.dims[2],M=j.dims[1]);const b=Y!==void 0&&Y.format!==void 0?Y.format:"RGB",I=Y==null?void 0:Y.norm;let K,te;I===void 0||I.mean===void 0?K=[255,255,255,255]:typeof I.mean=="number"?K=[I.mean,I.mean,I.mean,I.mean]:(K=[I.mean[0],I.mean[1],I.mean[2],255],I.mean[3]!==void 0&&(K[3]=I.mean[3])),I===void 0||I.bias===void 0?te=[0,0,0,0]:typeof I.bias=="number"?te=[I.bias,I.bias,I.bias,I.bias]:(te=[I.bias[0],I.bias[1],I.bias[2],0],I.bias[3]!==void 0&&(te[3]=I.bias[3]));const ne=y*v;if(Y!==void 0&&(Y.format!==void 0&&M===4&&Y.format!=="RGBA"||M===3&&Y.format!=="RGB"&&Y.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const W=4;let U=0,X=1,$=2,S=3,w=0,x=ne,O=ne*2,ae=-1;b==="RGBA"?(w=0,x=ne,O=ne*2,ae=ne*3):b==="RGB"?(w=0,x=ne,O=ne*2):b==="RBG"&&(w=0,O=ne,x=ne*2),g=N.createImageData(v,y);for(let ie=0;ie{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js":(ze,A,r)=>{r.r(A),r.d(A,{bufferToTensor:()=>D,tensorFromGpuBuffer:()=>N,tensorFromImage:()=>j,tensorFromMLTensor:()=>g,tensorFromPinnedBuffer:()=>v,tensorFromTexture:()=>Y});var _=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const D=(y,M)=>{if(y===void 0)throw new Error("Image buffer must be defined");if(M.height===void 0||M.width===void 0)throw new Error("Image height and width must be defined");if(M.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:b,width:I}=M,K=M.norm??{mean:255,bias:0};let te,ne;typeof K.mean=="number"?te=[K.mean,K.mean,K.mean,K.mean]:te=[K.mean[0],K.mean[1],K.mean[2],K.mean[3]??255],typeof K.bias=="number"?ne=[K.bias,K.bias,K.bias,K.bias]:ne=[K.bias[0],K.bias[1],K.bias[2],K.bias[3]??0];const W=M.format!==void 0?M.format:"RGBA",U=M.tensorFormat!==void 0&&M.tensorFormat!==void 0?M.tensorFormat:"RGB",X=b*I,$=U==="RGBA"?new Float32Array(X*4):new Float32Array(X*3);let S=4,w=0,x=1,O=2,ae=3,ie=0,ve=X,we=X*2,re=-1;W==="RGB"&&(S=3,w=0,x=1,O=2,ae=-1),U==="RGBA"?re=X*3:U==="RBG"?(ie=0,we=X,ve=X*2):U==="BGR"&&(we=0,ve=X,ie=X*2);for(let ce=0;ce{const b=typeof HTMLImageElement<"u"&&y instanceof HTMLImageElement,I=typeof ImageData<"u"&&y instanceof ImageData,K=typeof ImageBitmap<"u"&&y instanceof ImageBitmap,te=typeof y=="string";let ne,W=M??{};const U=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},X=$=>typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement||$ instanceof OffscreenCanvas?$.getContext("2d"):null;if(b){const $=U();$.width=y.width,$.height=y.height;const S=X($);if(S!=null){let w=y.height,x=y.width;if(M!==void 0&&M.resizedHeight!==void 0&&M.resizedWidth!==void 0&&(w=M.resizedHeight,x=M.resizedWidth),M!==void 0){if(W=M,M.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");W.tensorFormat="RGBA",W.height=w,W.width=x}else W.tensorFormat="RGBA",W.height=w,W.width=x;S.drawImage(y,0,0),ne=S.getImageData(0,0,x,w).data}else throw new Error("Can not access image data")}else if(I){let $,S;if(M!==void 0&&M.resizedWidth!==void 0&&M.resizedHeight!==void 0?($=M.resizedHeight,S=M.resizedWidth):($=y.height,S=y.width),M!==void 0&&(W=M),W.format="RGBA",W.height=$,W.width=S,M!==void 0){const w=U();w.width=S,w.height=$;const x=X(w);if(x!=null)x.putImageData(y,0,0),ne=x.getImageData(0,0,S,$).data;else throw new Error("Can not access image data")}else ne=y.data}else if(K){if(M===void 0)throw new Error("Please provide image config with format for Imagebitmap");const $=U();$.width=y.width,$.height=y.height;const S=X($);if(S!=null){const w=y.height,x=y.width;return S.drawImage(y,0,0,x,w),ne=S.getImageData(0,0,x,w).data,W.height=w,W.width=x,D(ne,W)}else throw new Error("Can not access image data")}else{if(te)return new Promise(($,S)=>{const w=U(),x=X(w);if(!y||!x)return S();const O=new Image;O.crossOrigin="Anonymous",O.src=y,O.onload=()=>{w.width=O.width,w.height=O.height,x.drawImage(O,0,0,w.width,w.height);const ae=x.getImageData(0,0,w.width,w.height);W.height=w.height,W.width=w.width,$(D(ae.data,W))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(ne!==void 0)return D(ne,W);throw new Error("Input data provided is not supported - aborted tensor creation")},Y=(y,M)=>{const{width:b,height:I,download:K,dispose:te}=M,ne=[1,I,b,4];return new _.Tensor({location:"texture",type:"float32",texture:y,dims:ne,download:K,dispose:te})},N=(y,M)=>{const{dataType:b,dims:I,download:K,dispose:te}=M;return new _.Tensor({location:"gpu-buffer",type:b??"float32",gpuBuffer:y,dims:I,download:K,dispose:te})},g=(y,M)=>{const{dataType:b,dims:I,download:K,dispose:te}=M;return new _.Tensor({location:"ml-tensor",type:b??"float32",mlTensor:y,dims:I,download:K,dispose:te})},v=(y,M,b)=>new _.Tensor({location:"cpu-pinned",type:y,data:M,dims:b??[M.length]})},"./node_modules/onnxruntime-common/dist/esm/tensor-factory.js":(ze,A,r)=>{r.r(A)},"./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js":(ze,A,r)=>{r.r(A),r.d(A,{NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP:()=>D,NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP:()=>_,checkTypedArray:()=>Y});const _=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),D=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let j=!1;const Y=()=>{if(!j){j=!0;const N=typeof BigInt64Array<"u"&&BigInt64Array.from,g=typeof BigUint64Array<"u"&&BigUint64Array.from,v=typeof Float16Array<"u"&&Float16Array.from;N&&(_.set("int64",BigInt64Array),D.set(BigInt64Array,"int64")),g&&(_.set("uint64",BigUint64Array),D.set(BigUint64Array,"uint64")),v?(_.set("float16",Float16Array),D.set(Float16Array,"float16")):_.set("float16",Uint16Array)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-impl.js":(ze,A,r)=>{r.r(A),r.d(A,{Tensor:()=>N});var _=r("./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"),D=r("./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"),j=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"),Y=r("./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js");class N{constructor(v,y,M){(0,j.checkTypedArray)();let b,I;if(typeof v=="object"&&"location"in v)switch(this.dataLocation=v.location,b=v.type,I=v.dims,v.location){case"cpu-pinned":{const te=j.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(b);if(!te)throw new TypeError(`unsupported type "${b}" to create tensor from pinned buffer`);if(!(v.data instanceof te))throw new TypeError(`buffer should be of type ${te.name}`);this.cpuData=v.data;break}case"texture":{if(b!=="float32")throw new TypeError(`unsupported type "${b}" to create tensor from texture`);this.gpuTextureData=v.texture,this.downloader=v.download,this.disposer=v.dispose;break}case"gpu-buffer":{if(b!=="float32"&&b!=="float16"&&b!=="int32"&&b!=="int64"&&b!=="uint32"&&b!=="uint8"&&b!=="bool"&&b!=="uint4"&&b!=="int4")throw new TypeError(`unsupported type "${b}" to create tensor from gpu buffer`);this.gpuBufferData=v.gpuBuffer,this.downloader=v.download,this.disposer=v.dispose;break}case"ml-tensor":{if(b!=="float32"&&b!=="float16"&&b!=="int32"&&b!=="int64"&&b!=="uint32"&&b!=="uint64"&&b!=="int8"&&b!=="uint8"&&b!=="bool")throw new TypeError(`unsupported type "${b}" to create tensor from MLTensor`);this.mlTensorData=v.mlTensor,this.downloader=v.download,this.disposer=v.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let te,ne;if(typeof v=="string")if(b=v,ne=M,v==="string"){if(!Array.isArray(y))throw new TypeError("A string tensor's data must be a string array.");te=y}else{const W=j.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(v);if(W===void 0)throw new TypeError(`Unsupported tensor type: ${v}.`);if(Array.isArray(y)){if(v==="float16"&&W===Uint16Array||v==="uint4"||v==="int4")throw new TypeError(`Creating a ${v} tensor from number array is not supported. Please use ${W.name} as data.`);v==="uint64"||v==="int64"?te=W.from(y,BigInt):te=W.from(y)}else if(y instanceof W)te=y;else if(y instanceof Uint8ClampedArray)if(v==="uint8")te=Uint8Array.from(y);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${b} tensor's data must be type of ${W}`)}else if(ne=y,Array.isArray(v)){if(v.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const W=typeof v[0];if(W==="string")b="string",te=v;else if(W==="boolean")b="bool",te=Uint8Array.from(v);else throw new TypeError(`Invalid element type of data array: ${W}.`)}else if(v instanceof Uint8ClampedArray)b="uint8",te=Uint8Array.from(v);else{const W=j.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(v.constructor);if(W===void 0)throw new TypeError(`Unsupported type for tensor data: ${v.constructor}.`);b=W,te=v}if(ne===void 0)ne=[te.length];else if(!Array.isArray(ne))throw new TypeError("A tensor's dims must be a number array");I=ne,this.cpuData=te,this.dataLocation="cpu"}const K=(0,Y.calculateSize)(I);if(this.cpuData&&K!==this.cpuData.length&&!((b==="uint4"||b==="int4")&&Math.ceil(K/2)===this.cpuData.length))throw new Error(`Tensor's size(${K}) does not match data length(${this.cpuData.length}).`);this.type=b,this.dims=I,this.size=K}static async fromImage(v,y){return(0,D.tensorFromImage)(v,y)}static fromTexture(v,y){return(0,D.tensorFromTexture)(v,y)}static fromGpuBuffer(v,y){return(0,D.tensorFromGpuBuffer)(v,y)}static fromMLTensor(v,y){return(0,D.tensorFromMLTensor)(v,y)}static fromPinnedBuffer(v,y,M){return(0,D.tensorFromPinnedBuffer)(v,y,M)}toDataURL(v){return(0,_.tensorToDataURL)(this,v)}toImageData(v){return(0,_.tensorToImageData)(this,v)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(v){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const y=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=y,v&&this.disposer&&(this.disposer(),this.disposer=void 0),y}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(v){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,Y.tensorReshape)(this,v)}}},"./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js":(ze,A,r)=>{r.r(A),r.d(A,{calculateSize:()=>D,tensorReshape:()=>j});var _=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const D=Y=>{let N=1;for(let g=0;g{switch(Y.location){case"cpu":return new _.Tensor(Y.type,Y.data,N);case"cpu-pinned":return new _.Tensor({location:"cpu-pinned",data:Y.data,type:Y.type,dims:N});case"texture":return new _.Tensor({location:"texture",texture:Y.texture,type:Y.type,dims:N});case"gpu-buffer":return new _.Tensor({location:"gpu-buffer",gpuBuffer:Y.gpuBuffer,type:Y.type,dims:N});case"ml-tensor":return new _.Tensor({location:"ml-tensor",mlTensor:Y.mlTensor,type:Y.type,dims:N});default:throw new Error(`tensorReshape: tensor location ${Y.location} is not supported`)}}},"./node_modules/onnxruntime-common/dist/esm/tensor.js":(ze,A,r)=>{r.r(A),r.d(A,{Tensor:()=>D});var _=r("./node_modules/onnxruntime-common/dist/esm/tensor-impl.js");const D=_.Tensor},"./node_modules/onnxruntime-common/dist/esm/trace.js":(ze,A,r)=>{r.r(A),r.d(A,{TRACE:()=>D,TRACE_FUNC_BEGIN:()=>Y,TRACE_FUNC_END:()=>N});var _=r("./node_modules/onnxruntime-common/dist/esm/env-impl.js");const D=(g,v)=>{(typeof _.env.trace>"u"?!_.env.wasm.trace:!_.env.trace)||console.timeStamp(`${g}::ORT::${v}`)},j=(g,v)=>{var b;const y=((b=new Error().stack)==null?void 0:b.split(/\r\n|\r|\n/g))||[];let M=!1;for(let I=0;I{(typeof _.env.trace>"u"?!_.env.wasm.trace:!_.env.trace)||j("BEGIN",g)},N=g=>{(typeof _.env.trace>"u"?!_.env.wasm.trace:!_.env.trace)||j("END",g)}},"./node_modules/onnxruntime-common/dist/esm/training-session-impl.js":(ze,A,r)=>{r.r(A),r.d(A,{TrainingSession:()=>Y});var _=r("./node_modules/onnxruntime-common/dist/esm/backend-impl.js"),D=r("./node_modules/onnxruntime-common/dist/esm/tensor.js");const j="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";class Y{constructor(g,v,y){this.handler=g,this.hasOptimizerModel=v,this.hasEvalModel=y}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(g,v){const y=g.evalModel||"",M=g.optimizerModel||"",b=v||{},[I,K]=await(0,_.resolveBackendAndExecutionProviders)(b);if(I.createTrainingSessionHandler){const te=await I.createTrainingSessionHandler(g.checkpointState,g.trainModel,y,M,K);return new Y(te,!!g.optimizerModel,!!g.evalModel)}else throw new Error(j)}typeNarrowingForRunStep(g,v,y,M,b){const I={};let K={};if(typeof y!="object"||y===null||y instanceof D.Tensor||Array.isArray(y))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let te=!0;if(typeof M=="object"){if(M===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(M instanceof D.Tensor)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.");te=!1;for(const ne of M){if(typeof ne!="string")throw new TypeError("'fetches' must be a string array or an object.");if(v.indexOf(ne)===-1)throw new RangeError(`'fetches' contains invalid output name: ${ne}.`);I[ne]=null}if(typeof b=="object"&&b!==null)K=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else{let ne=!1;const W=Object.getOwnPropertyNames(M);for(const U of v)if(W.indexOf(U)!==-1){const X=M[U];(X===null||X instanceof D.Tensor)&&(ne=!0,te=!1,I[U]=X)}if(ne){if(typeof b=="object"&&b!==null)K=b;else if(typeof b<"u")throw new TypeError("'options' must be an object.")}else K=M}}else if(typeof M<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const ne of g)if(typeof y[ne]>"u")throw new Error(`input '${ne}' is missing in 'feeds'.`);if(te)for(const ne of v)I[ne]=null;return[I,K]}convertHandlerReturnTypeToMapOfTensors(g){const v={};for(const y in g)if(Object.hasOwnProperty.call(g,y)){const M=g[y];M instanceof D.Tensor?v[y]=M:v[y]=new D.Tensor(M.type,M.data,M.dims)}return v}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(g,v,y){const[M,b]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,g,v,y),I=await this.handler.runTrainStep(g,M,b);return this.convertHandlerReturnTypeToMapOfTensors(I)}async runOptimizerStep(g){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(g||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(g,v,y){if(this.hasEvalModel){const[M,b]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,g,v,y),I=await this.handler.runEvalStep(g,M,b);return this.convertHandlerReturnTypeToMapOfTensors(I)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(g=!0){return this.handler.getParametersSize(g)}async loadParametersBuffer(g,v=!0){const y=await this.getParametersSize(v);if(g.length!==4*y)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(g,v)}async getContiguousParameters(g=!0){return this.handler.getContiguousParameters(g)}async release(){return this.handler.dispose()}}},"./node_modules/onnxruntime-common/dist/esm/training-session.js":(ze,A,r)=>{r.r(A),r.d(A,{TrainingSession:()=>D});var _=r("./node_modules/onnxruntime-common/dist/esm/training-session-impl.js");const D=_.TrainingSession},"./node_modules/onnxruntime-common/dist/esm/version.js":(ze,A,r)=>{r.r(A),r.d(A,{version:()=>_});const _="1.20.1"},"./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?3a96":(ze,A,r)=>{r.r(A),r.d(A,{InferenceSession:()=>lt,TRACE:()=>Ue,TRACE_FUNC_BEGIN:()=>Ne,TRACE_FUNC_END:()=>Re,Tensor:()=>le,default:()=>lf,env:()=>O,registerBackend:()=>K});/*! + * ONNX Runtime Web v1.21.0-dev.20250114-228dd16893 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var _=Object.defineProperty,D=Object.getOwnPropertyDescriptor,j=Object.getOwnPropertyNames,Y=Object.prototype.hasOwnProperty,N=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,s)=>(typeof require<"u"?require:t)[s]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),g=(e,t)=>()=>(e&&(t=e(e=0)),t),v=(e,t)=>{for(var s in t)_(e,s,{get:t[s],enumerable:!0})},y=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of j(t))!Y.call(e,i)&&i!==s&&_(e,i,{get:()=>t[i],enumerable:!(n=D(t,i))||n.enumerable});return e},M=e=>y(_({},"__esModule",{value:!0}),e),b,I,K,te,ne,W=g(()=>{b=new Map,I=[],K=(e,t,s)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=b.get(e);if(n===void 0)b.set(e,{backend:t,priority:s});else{if(n.priority>s)return;if(n.priority===s&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${s}`)}if(s>=0){let i=I.indexOf(e);i!==-1&&I.splice(i,1);for(let a=0;a{let t=b.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let s=!!t.initPromise;try{return s||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return s||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},ne=async e=>{let t=e.executionProviders||[],s=t.map(p=>typeof p=="string"?p:p.name),n=s.length===0?I:s,i,a=[],o=new Set;for(let p of n){let h=await te(p);typeof h=="string"?a.push({name:p,err:h}):(i||(i=h),i===h&&o.add(p))}if(!i)throw new Error(`no available backend found. ERR: ${a.map(p=>`[${p.name}] ${p.err}`).join(", ")}`);for(let{name:p,err:h}of a)s.includes(p)&&console.warn(`removing requested execution provider "${p}" from session options because it is not available: ${h}`);let u=t.filter(p=>o.has(typeof p=="string"?p:p.name));return[i,new Proxy(e,{get:(p,h)=>h==="executionProviders"?u:Reflect.get(p,h)})]}}),U=g(()=>{W()}),X,$=g(()=>{X="1.21.0-dev.20241212-1f88284f96"}),S,w,x=g(()=>{$(),S="warning",w={wasm:{},webgl:{},webgpu:{},versions:{common:X},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);S=e}},get logLevel(){return S}},Object.defineProperty(w,"logLevel",{enumerable:!0})}),O,ae=g(()=>{x(),O=w}),ie,ve,we=g(()=>{ie=(e,t)=>{let s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=e.dims[3],s.height=e.dims[2];let n=s.getContext("2d");if(n!=null){let i,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=(t==null?void 0:t.format)!==void 0?t.format:"RGB",u=t==null?void 0:t.norm,p,h;u===void 0||u.mean===void 0?p=[255,255,255,255]:typeof u.mean=="number"?p=[u.mean,u.mean,u.mean,u.mean]:(p=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(p[3]=u.mean[3])),u===void 0||u.bias===void 0?h=[0,0,0,0]:typeof u.bias=="number"?h=[u.bias,u.bias,u.bias,u.bias]:(h=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(h[3]=u.bias[3]));let k=a*i,E=0,d=k,z=k*2,B=-1;o==="RGBA"?(E=0,d=k,z=k*2,B=k*3):o==="RGB"?(E=0,d=k,z=k*2):o==="RBG"&&(E=0,z=k,d=k*2);for(let V=0;V{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(s!=null){let i,a,o;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let u=t!==void 0&&t.format!==void 0?t.format:"RGB",p=t==null?void 0:t.norm,h,k;p===void 0||p.mean===void 0?h=[255,255,255,255]:typeof p.mean=="number"?h=[p.mean,p.mean,p.mean,p.mean]:(h=[p.mean[0],p.mean[1],p.mean[2],255],p.mean[3]!==void 0&&(h[3]=p.mean[3])),p===void 0||p.bias===void 0?k=[0,0,0,0]:typeof p.bias=="number"?k=[p.bias,p.bias,p.bias,p.bias]:(k=[p.bias[0],p.bias[1],p.bias[2],0],p.bias[3]!==void 0&&(k[3]=p.bias[3]));let E=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!=="RGBA"||o===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let d=4,z=0,B=1,V=2,Z=3,ee=0,Q=E,he=E*2,pe=-1;u==="RGBA"?(ee=0,Q=E,he=E*2,pe=E*3):u==="RGB"?(ee=0,Q=E,he=E*2):u==="RBG"&&(ee=0,he=E,Q=E*2),n=s.createImageData(i,a);for(let Me=0;Me{je(),re=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:s,width:n}=t,i=t.norm??{mean:255,bias:0},a,o;typeof i.mean=="number"?a=[i.mean,i.mean,i.mean,i.mean]:a=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?o=[i.bias,i.bias,i.bias,i.bias]:o=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let u=t.format!==void 0?t.format:"RGBA",p=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",h=s*n,k=p==="RGBA"?new Float32Array(h*4):new Float32Array(h*3),E=4,d=0,z=1,B=2,V=3,Z=0,ee=h,Q=h*2,he=-1;u==="RGB"&&(E=3,d=0,z=1,B=2,V=-1),p==="RGBA"?he=h*3:p==="RBG"?(Z=0,Q=h,ee=h*2):p==="BGR"&&(Q=0,ee=h,Z=h*2);for(let pe=0;pe{let s=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,a=typeof e=="string",o,u=t??{},p=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},h=k=>typeof HTMLCanvasElement<"u"&&k instanceof HTMLCanvasElement||k instanceof OffscreenCanvas?k.getContext("2d"):null;if(s){let k=p();k.width=e.width,k.height=e.height;let E=h(k);if(E!=null){let d=e.height,z=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(d=t.resizedHeight,z=t.resizedWidth),t!==void 0){if(u=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=d,u.width=z}else u.tensorFormat="RGBA",u.height=d,u.width=z;E.drawImage(e,0,0),o=E.getImageData(0,0,z,d).data}else throw new Error("Can not access image data")}else if(n){let k,E;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(k=t.resizedHeight,E=t.resizedWidth):(k=e.height,E=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=k,u.width=E,t!==void 0){let d=p();d.width=E,d.height=k;let z=h(d);if(z!=null)z.putImageData(e,0,0),o=z.getImageData(0,0,E,k).data;else throw new Error("Can not access image data")}else o=e.data}else if(i){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let k=p();k.width=e.width,k.height=e.height;let E=h(k);if(E!=null){let d=e.height,z=e.width;return E.drawImage(e,0,0,z,d),o=E.getImageData(0,0,z,d).data,u.height=d,u.width=z,re(o,u)}else throw new Error("Can not access image data")}else{if(a)return new Promise((k,E)=>{let d=p(),z=h(d);if(!e||!z)return E();let B=new Image;B.crossOrigin="Anonymous",B.src=e,B.onload=()=>{d.width=B.width,d.height=B.height,z.drawImage(B,0,0,d.width,d.height);let V=z.getImageData(0,0,d.width,d.height);u.height=d.height,u.width=d.width,k(re(V.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return re(o,u);throw new Error("Input data provided is not supported - aborted tensor creation")},ce=(e,t)=>{let{width:s,height:n,download:i,dispose:a}=t,o=[1,n,s,4];return new Ke({location:"texture",type:"float32",texture:e,dims:o,download:i,dispose:a})},ke=(e,t)=>{let{dataType:s,dims:n,download:i,dispose:a}=t;return new Ke({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:n,download:i,dispose:a})},Ae=(e,t)=>{let{dataType:s,dims:n,download:i,dispose:a}=t;return new Ke({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:n,download:i,dispose:a})},Ee=(e,t,s)=>new Ke({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]})}),Ge,ye,J,de,Ce=g(()=>{Ge=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ye=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),J=!1,de=()=>{if(!J){J=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,s=typeof Float16Array<"u"&&Float16Array.from;e&&(Ge.set("int64",BigInt64Array),ye.set(BigInt64Array,"int64")),t&&(Ge.set("uint64",BigUint64Array),ye.set(BigUint64Array,"uint64")),s?(Ge.set("float16",Float16Array),ye.set(Float16Array,"float16")):Ge.set("float16",Uint16Array)}}}),Be,Ze,se=g(()=>{je(),Be=e=>{let t=1;for(let s=0;s{switch(e.location){case"cpu":return new Ke(e.type,e.data,t);case"cpu-pinned":return new Ke({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Ke({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Ke({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Ke({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Ke,je=g(()=>{we(),tt(),Ce(),se(),Ke=class{constructor(e,t,s){de();let n,i;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,i=e.dims,e.location){case"cpu-pinned":{let o=Ge.get(n);if(!o)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,u;if(typeof e=="string")if(n=e,u=s,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");o=t}else{let p=Ge.get(e);if(p===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&p===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${p.name} as data.`);e==="uint64"||e==="int64"?o=p.from(t,BigInt):o=p.from(t)}else if(t instanceof p)o=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")o=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${n} tensor's data must be type of ${p}`)}else if(u=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let p=typeof e[0];if(p==="string")n="string",o=e;else if(p==="boolean")n="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${p}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",o=Uint8Array.from(e);else{let p=ye.get(e.constructor);if(p===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=p,o=e}if(u===void 0)u=[o.length];else if(!Array.isArray(u))throw new TypeError("A tensor's dims must be a number array");i=u,this.cpuData=o,this.dataLocation="cpu"}let a=Be(i);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=i,this.size=a}static async fromImage(e,t){return xe(e,t)}static fromTexture(e,t){return ce(e,t)}static fromGpuBuffer(e,t){return ke(e,t)}static fromMLTensor(e,t){return Ae(e,t)}static fromPinnedBuffer(e,t,s){return Ee(e,t,s)}toDataURL(e){return ie(this,e)}toImageData(e){return ve(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Ze(this,e)}}}),le,Te=g(()=>{je(),le=Ke}),Ue,Ve,Ne,Re,st=g(()=>{x(),Ue=(e,t)=>{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||console.timeStamp(`${e}::ORT::${t}`)},Ve=(e,t)=>{var i;let s=((i=new Error().stack)==null?void 0:i.split(/\r\n|\r|\n/g))||[],n=!1;for(let a=0;a{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||Ve("BEGIN",e)},Re=e=>{(typeof w.trace>"u"?!w.wasm.trace:!w.trace)||Ve("END",e)}}),dt,ct=g(()=>{W(),Te(),st(),dt=class ef{constructor(t){this.handler=t}async run(t,s,n){Ne();let i={},a={};if(typeof t!="object"||t===null||t instanceof le||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof le)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(s.length===0)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(let h of s){if(typeof h!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(h)===-1)throw new RangeError(`'fetches' contains invalid output name: ${h}.`);i[h]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let h=!1,k=Object.getOwnPropertyNames(s);for(let E of this.outputNames)if(k.indexOf(E)!==-1){let d=s[E];(d===null||d instanceof le)&&(h=!0,o=!1,i[E]=d)}if(h){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let h of this.inputNames)if(typeof t[h]>"u")throw new Error(`input '${h}' is missing in 'feeds'.`);if(o)for(let h of this.outputNames)i[h]=null;let u=await this.handler.run(t,i,a),p={};for(let h in u)if(Object.hasOwnProperty.call(u,h)){let k=u[h];k instanceof le?p[h]=k:p[h]=new le(k.type,k.data,k.dims)}return Re(),p}async release(){return this.handler.dispose()}static async create(t,s,n,i){Ne();let a,o={};if(typeof t=="string"){if(a=t,typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(a=t,typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let k=t,E=0,d=t.byteLength;if(typeof s=="object"&&s!==null)o=s;else if(typeof s=="number"){if(E=s,!Number.isSafeInteger(E))throw new RangeError("'byteOffset' must be an integer.");if(E<0||E>=k.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${k.byteLength}).`);if(d=t.byteLength-E,typeof n=="number"){if(d=n,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||E+d>k.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${k.byteLength-E}].`);if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof s<"u")throw new TypeError("'options' must be an object.");a=new Uint8Array(k,E,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,p]=await ne(o),h=await u.createInferenceSessionHandler(a,p);return Re(),new ef(h)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),lt,ht=g(()=>{ct(),lt=dt}),L=g(()=>{}),oe=g(()=>{}),H=g(()=>{}),me=g(()=>{}),$e={};v($e,{InferenceSession:()=>lt,TRACE:()=>Ue,TRACE_FUNC_BEGIN:()=>Ne,TRACE_FUNC_END:()=>Re,Tensor:()=>le,env:()=>O,registerBackend:()=>K});var We=g(()=>{U(),ae(),ht(),Te(),L(),oe(),st(),H(),me()}),Je=g(()=>{}),ut={};v(ut,{default:()=>kt});var mt,vt,kt,At=g(()=>{var e;bh(),ar(),Nr(),mt="ort-wasm-proxy-worker",vt=((e=globalThis.self)==null?void 0:e.name)===mt,vt&&(self.onmessage=t=>{let{type:s,in:n}=t.data;try{switch(s){case"init-wasm":Or(n.wasm).then(()=>{Sc(n).then(()=>{postMessage({type:s})},i=>{postMessage({type:s,err:i})})},i=>{postMessage({type:s,err:i})});break;case"init-ep":{let{epName:i,env:a}=n;$c(a,i).then(()=>{postMessage({type:s})},o=>{postMessage({type:s,err:o})});break}case"copy-from":{let{buffer:i}=n,a=dr(i);postMessage({type:s,out:a});break}case"create":{let{model:i,options:a}=n;Up(i,a).then(o=>{postMessage({type:s,out:o})},o=>{postMessage({type:s,err:o})});break}case"release":Vp(n),postMessage({type:s});break;case"run":{let{sessionId:i,inputIndices:a,inputs:o,outputIndices:u,options:p}=n;Gp(i,a,o,u,new Array(u.length).fill(null),p).then(h=>{h.some(k=>k[3]!=="cpu")?postMessage({type:s,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:s,out:h},Hp([...o,...h]))},h=>{postMessage({type:s,err:h})});break}case"end-profiling":Kp(n),postMessage({type:s});break;default:}}catch(i){postMessage({type:s,err:i})}}),kt=vt?null:t=>new Worker(t??Us,{type:"module",name:mt})}),is={};v(is,{default:()=>Ds});var ws,ks,Ds,sr=g(()=>{var e;ks=(ws=self.location.href,async function(t={}){function s(){return Ft.buffer!=Rt.buffer&&Ps(),Rt}function n(){return Ft.buffer!=Rt.buffer&&Ps(),_s}function i(){return Ft.buffer!=Rt.buffer&&Ps(),ot}function a(){return Ft.buffer!=Rt.buffer&&Ps(),Et}function o(){return Ft.buffer!=Rt.buffer&&Ps(),cs}function u(){return Ft.buffer!=Rt.buffer&&Ps(),Ns}function p(){return Ft.buffer!=Rt.buffer&&Ps(),xr}function h(){return Ft.buffer!=Rt.buffer&&Ps(),Oi}var k,E,d=Object.assign({},t),z=new Promise((l,m)=>{k=l,E=m}),B=typeof window=="object",V=typeof importScripts=="function",Z=V&&self.name=="em-pthread";d.mountExternalData=(l,m)=>{l.startsWith("./")&&(l=l.substring(2)),(d.Fb||(d.Fb=new Map)).set(l,m)},d.unmountExternalData=()=>{delete d.Fb};var ee=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let Q=()=>{let l=(P,F,G)=>(...ge)=>{let Xe=mn,nt=F==null?void 0:F();ge=P(...ge);let wt=F==null?void 0:F();return nt!==wt&&(P=wt,G(nt),F=G=null),mn!=Xe?new Promise((Ct,Wt)=>{hh={resolve:Ct,reject:Wt}}):ge},m=P=>async(...F)=>{var G;try{if(d.Gb)throw Error("Session already started");let ge=d.Gb={hc:F[0],errors:[]},Xe=await P(...F);if(d.Gb!==ge)throw Error("Session mismatch");(G=d.Hb)==null||G.flush();let nt=ge.errors;if(0Ct),0d._OrtCreateSession,P=>d._OrtCreateSession=P),d._OrtRun=m(l(d._OrtRun,()=>d._OrtRun,P=>d._OrtRun=P)),d._OrtRunWithBinding=m(l(d._OrtRunWithBinding,()=>d._OrtRunWithBinding,P=>d._OrtRunWithBinding=P)),d._OrtBindInput=l(d._OrtBindInput,()=>d._OrtBindInput,P=>d._OrtBindInput=P),Q=void 0};d.jsepInit=(l,m)=>{if(Q==null||Q(),l==="webgpu"){[d.Hb,d.Vb,d.Zb,d.Ob,d.Yb,d.kb,d.$b,d.cc,d.Wb,d.Xb,d.ac]=m;let P=d.Hb;d.jsepRegisterBuffer=(F,G,ge,Xe)=>P.registerBuffer(F,G,ge,Xe),d.jsepGetBuffer=F=>P.getBuffer(F),d.jsepCreateDownloader=(F,G,ge)=>P.createDownloader(F,G,ge),d.jsepOnCreateSession=F=>{P.onCreateSession(F)},d.jsepOnReleaseSession=F=>{P.onReleaseSession(F)},d.jsepOnRunStart=F=>P.onRunStart(F),d.dc=(F,G)=>{P.upload(F,G)}}else if(l==="webnn"){[d.Hb,d.bc,d.Pb,d.jsepEnsureTensor,d.ec,d.jsepDownloadTensor]=m,d.jsepReleaseTensorId=d.Pb;let P=d.Hb;d.jsepOnRunStart=F=>P.onRunStart(F),d.jsepRegisterMLContext=(F,G)=>{P.registerMLContext(F,G)},d.jsepOnReleaseSession=F=>{P.onReleaseSession(F)},d.jsepCreateMLTensorDownloader=(F,G)=>P.createMLTensorDownloader(F,G),d.jsepRegisterMLTensor=(F,G,ge)=>P.registerMLTensor(F,G,ge),d.jsepCreateMLContext=F=>P.createMLContext(F),d.jsepRegisterMLConstant=(F,G,ge,Xe,nt)=>P.registerMLConstant(F,G,ge,Xe,nt,d.Fb)}};var he,pe,Me=Object.assign({},d),Fe="./this.program",De=(l,m)=>{throw m},Ye="";(B||V)&&(V?Ye=self.location.href:typeof document<"u"&&document.currentScript&&(Ye=document.currentScript.src),ws&&(Ye=ws),Ye=Ye.startsWith("blob:")?"":Ye.substr(0,Ye.replace(/[?#].*/,"").lastIndexOf("/")+1),V&&(pe=l=>{var m=new XMLHttpRequest;return m.open("GET",l,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),he=(l,m,P)=>{var F=new XMLHttpRequest;F.open("GET",l,!0),F.responseType="arraybuffer",F.onload=()=>{F.status==200||F.status==0&&F.response?m(F.response):P()},F.onerror=P,F.send(null)});var at,Pt=console.log.bind(console),Xt=console.error.bind(console),Zt=Pt,bt=Xt;if(Object.assign(d,Me),Me=null,Z){let l=function(m){try{var P=m.data,F=P.cmd;if(F==="load"){let G=[];self.onmessage=ge=>G.push(ge),self.startWorker=()=>{postMessage({cmd:"loaded"});for(let ge of G)l(ge);self.onmessage=l};for(let ge of P.handlers)d[ge]&&!d[ge].proxy||(d[ge]=(...Xe)=>{postMessage({Nb:"callHandler",pc:ge,args:Xe})},ge=="print"&&(Zt=d[ge]),ge=="printErr"&&(bt=d[ge]));Ft=P.wasmMemory,Ps(),ss(P.wasmModule)}else if(F==="run"){gh(P.pthread_ptr,0,0,1,0,0),ch(P.pthread_ptr),cf(),Gh(),St||(Um(),St=!0);try{pf(P.start_routine,P.arg)}catch(G){if(G!="unwind")throw G}}else F==="cancel"?Ia()&&zp(-1):P.target!=="setimmediate"&&(F==="checkMailbox"?St&&Cp():F&&(bt(`worker: received unknown command ${F}`),bt(P)))}catch(G){throw Vm(),G}};var ss,St=!1;bt=function(...m){m=m.join(" "),console.error(m)},self.alert=function(...m){postMessage({Nb:"alert",text:m.join(" "),rc:Ia()})},d.instantiateWasm=(m,P)=>new Promise(F=>{ss=G=>{G=new WebAssembly.Instance(G,Nh()),P(G),F()}}),self.onunhandledrejection=m=>{throw m.reason||m},self.onmessage=l}d.wasmBinary&&(at=d.wasmBinary);var Ft,bs,Ht,Rt,_s,ot,Et,cs,Ns,xr,er,cn,Oi,Bs=!1;function Ps(){var l=Ft.buffer;d.HEAP8=Rt=new Int8Array(l),d.HEAP16=ot=new Int16Array(l),d.HEAPU8=_s=new Uint8Array(l),d.HEAPU16=Et=new Uint16Array(l),d.HEAP32=cs=new Int32Array(l),d.HEAPU32=Ns=new Uint32Array(l),d.HEAPF32=xr=new Float32Array(l),d.HEAPF64=Oi=new Float64Array(l),d.HEAP64=er=new BigInt64Array(l),d.HEAPU64=cn=new BigUint64Array(l)}if(!Z){if(!((Ft=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0})).buffer instanceof ee))throw bt("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");Ps()}var Qn=[],Oc=[],Jp=[],Fc=0,Dc=null;function Dh(){if(--Fc==0&&Dc){var l=Dc;Dc=null,l()}}function Xn(l){throw bt(l="Aborted("+l+")"),Bs=!0,Ht=1,l=new WebAssembly.RuntimeError(l+". Build with -sASSERTIONS for more info."),E(l),l}var Zp,Lh=l=>l.startsWith("data:application/octet-stream;base64,"),zh=l=>l.startsWith("file://");function Bh(l){if(l==Zp&&at)return new Uint8Array(at);if(pe)return pe(l);throw"both async and sync fetching of the wasm failed"}function Rh(l,m,P){return function(F){if(!at&&(B||V)){if(typeof fetch=="function"&&!zh(F))return fetch(F,{credentials:"same-origin"}).then(G=>{if(!G.ok)throw`failed to load wasm binary file at '${F}'`;return G.arrayBuffer()}).catch(()=>Bh(F));if(he)return new Promise((G,ge)=>{he(F,Xe=>G(new Uint8Array(Xe)),ge)})}return Promise.resolve().then(()=>Bh(F))}(l).then(F=>WebAssembly.instantiate(F,m)).then(P,F=>{bt(`failed to asynchronously prepare wasm: ${F}`),Xn(F)})}function Nh(){return{a:{O:df,Aa:uf,b:mf,aa:Qh,B:Jh,qa:Zh,Y:tm,_:sm,ra:rm,oa:nm,ha:im,na:om,L:am,Z:lm,W:um,pa:dm,X:cm,va:ff,F:_f,Q:gf,P:yf,E:bf,u:vf,q:xf,G:Tf,A:Af,R:If,ua:Of,ka:Ff,U:Df,ba:Lf,H:zf,ja:ch,ta:Bf,t:Rf,Ba:Nf,x:Vf,n:Wf,l:Kf,c:uh,o:Hf,j:Xf,w:Yf,p:Jf,f:Zf,s:e_,m:t_,e:s_,k:r_,i:n_,h:i_,d:o_,ea:a_,fa:l_,ga:u_,ca:Pm,da:Em,T:d_,g:c_,D:p_,I:h_,M:m_,y:f_,sa:__,V:g_,v:km,z:w_,N:y_,S:M_,za:b_,ya:v_,la:Am,ma:Im,$:nh,C:Om,K:Fm,ia:Dm,J:Lm,a:Ft,xa:rh,wa:Rm,r:P_}}}var eh={913700:(l,m,P,F,G)=>{if(d===void 0||!d.Fb)return 1;if((l=Hs(Number(l>>>0))).startsWith("./")&&(l=l.substring(2)),!(l=d.Fb.get(l)))return 2;if(m=Number(m>>>0),P=Number(P>>>0),F=Number(F>>>0),m+P>l.byteLength)return 3;try{let ge=l.subarray(m,m+P);switch(G){case 0:n().set(ge,F>>>0);break;case 1:d.dc(F,ge);break;default:return 4}return 0}catch{return 4}},914415:(l,m,P)=>{d.ec(l,n().subarray(m>>>0,m+P>>>0))},914478:()=>d.bc(),914519:l=>{d.Pb(l)},914555:()=>{d.Wb()},914586:()=>{d.Xb()},914615:()=>{d.ac()},914640:l=>d.Vb(l),914673:l=>d.Zb(l),914705:(l,m,P)=>{d.Ob(Number(l),Number(m),Number(P),!0)},914768:(l,m,P)=>{d.Ob(Number(l),Number(m),Number(P))},914825:()=>typeof wasmOffsetConverter<"u",914882:l=>{d.kb("Abs",l,void 0)},914933:l=>{d.kb("Neg",l,void 0)},914984:l=>{d.kb("Floor",l,void 0)},915037:l=>{d.kb("Ceil",l,void 0)},915089:l=>{d.kb("Reciprocal",l,void 0)},915147:l=>{d.kb("Sqrt",l,void 0)},915199:l=>{d.kb("Exp",l,void 0)},915250:l=>{d.kb("Erf",l,void 0)},915301:l=>{d.kb("Sigmoid",l,void 0)},915356:(l,m,P)=>{d.kb("HardSigmoid",l,{alpha:m,beta:P})},915435:l=>{d.kb("Log",l,void 0)},915486:l=>{d.kb("Sin",l,void 0)},915537:l=>{d.kb("Cos",l,void 0)},915588:l=>{d.kb("Tan",l,void 0)},915639:l=>{d.kb("Asin",l,void 0)},915691:l=>{d.kb("Acos",l,void 0)},915743:l=>{d.kb("Atan",l,void 0)},915795:l=>{d.kb("Sinh",l,void 0)},915847:l=>{d.kb("Cosh",l,void 0)},915899:l=>{d.kb("Asinh",l,void 0)},915952:l=>{d.kb("Acosh",l,void 0)},916005:l=>{d.kb("Atanh",l,void 0)},916058:l=>{d.kb("Tanh",l,void 0)},916110:l=>{d.kb("Not",l,void 0)},916161:(l,m,P)=>{d.kb("Clip",l,{min:m,max:P})},916230:l=>{d.kb("Clip",l,void 0)},916282:(l,m)=>{d.kb("Elu",l,{alpha:m})},916340:l=>{d.kb("Gelu",l,void 0)},916392:l=>{d.kb("Relu",l,void 0)},916444:(l,m)=>{d.kb("LeakyRelu",l,{alpha:m})},916508:(l,m)=>{d.kb("ThresholdedRelu",l,{alpha:m})},916578:(l,m)=>{d.kb("Cast",l,{to:m})},916636:l=>{d.kb("Add",l,void 0)},916687:l=>{d.kb("Sub",l,void 0)},916738:l=>{d.kb("Mul",l,void 0)},916789:l=>{d.kb("Div",l,void 0)},916840:l=>{d.kb("Pow",l,void 0)},916891:l=>{d.kb("Equal",l,void 0)},916944:l=>{d.kb("Greater",l,void 0)},916999:l=>{d.kb("GreaterOrEqual",l,void 0)},917061:l=>{d.kb("Less",l,void 0)},917113:l=>{d.kb("LessOrEqual",l,void 0)},917172:(l,m,P,F,G)=>{d.kb("ReduceMean",l,{keepDims:!!m,noopWithEmptyAxes:!!P,axes:F?Array.from(o().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},917347:(l,m,P,F,G)=>{d.kb("ReduceMax",l,{keepDims:!!m,noopWithEmptyAxes:!!P,axes:F?Array.from(o().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},917521:(l,m,P,F,G)=>{d.kb("ReduceMin",l,{keepDims:!!m,noopWithEmptyAxes:!!P,axes:F?Array.from(o().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},917695:(l,m,P,F,G)=>{d.kb("ReduceProd",l,{keepDims:!!m,noopWithEmptyAxes:!!P,axes:F?Array.from(o().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},917870:(l,m,P,F,G)=>{d.kb("ReduceSum",l,{keepDims:!!m,noopWithEmptyAxes:!!P,axes:F?Array.from(o().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},918044:(l,m,P,F,G)=>{d.kb("ReduceL1",l,{keepDims:!!m,noopWithEmptyAxes:!!P,axes:F?Array.from(o().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},918217:(l,m,P,F,G)=>{d.kb("ReduceL2",l,{keepDims:!!m,noopWithEmptyAxes:!!P,axes:F?Array.from(o().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},918390:(l,m,P,F,G)=>{d.kb("ReduceLogSum",l,{keepDims:!!m,noopWithEmptyAxes:!!P,axes:F?Array.from(o().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},918567:(l,m,P,F,G)=>{d.kb("ReduceSumSquare",l,{keepDims:!!m,noopWithEmptyAxes:!!P,axes:F?Array.from(o().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},918747:(l,m,P,F,G)=>{d.kb("ReduceLogSumExp",l,{keepDims:!!m,noopWithEmptyAxes:!!P,axes:F?Array.from(o().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},918927:l=>{d.kb("Where",l,void 0)},918980:(l,m,P)=>{d.kb("Transpose",l,{perm:m?Array.from(o().subarray(Number(m)>>>0,Number(P)>>>0)):[]})},919104:(l,m,P,F)=>{d.kb("DepthToSpace",l,{blocksize:m,mode:Hs(P),format:F?"NHWC":"NCHW"})},919237:(l,m,P,F)=>{d.kb("DepthToSpace",l,{blocksize:m,mode:Hs(P),format:F?"NHWC":"NCHW"})},919370:(l,m,P,F,G,ge,Xe,nt,wt,Ct,Wt,ps,vs,He,ls)=>{d.kb("ConvTranspose",l,{format:wt?"NHWC":"NCHW",autoPad:m,dilations:[P],group:F,kernelShape:[G],pads:[ge,Xe],strides:[nt],wIsConst:()=>!!s()[Ct>>>0],outputPadding:Wt?Array.from(o().subarray(Number(Wt)>>>0,Number(ps)>>>0)):[],outputShape:vs?Array.from(o().subarray(Number(vs)>>>0,Number(He)>>>0)):[],activation:Hs(ls)})},919803:(l,m,P,F,G,ge,Xe,nt,wt,Ct,Wt,ps,vs,He)=>{d.kb("ConvTranspose",l,{format:nt?"NHWC":"NCHW",autoPad:m,dilations:Array.from(o().subarray(Number(P)>>>0,2+(Number(P)>>>0)>>>0)),group:F,kernelShape:Array.from(o().subarray(Number(G)>>>0,2+(Number(G)>>>0)>>>0)),pads:Array.from(o().subarray(Number(ge)>>>0,4+(Number(ge)>>>0)>>>0)),strides:Array.from(o().subarray(Number(Xe)>>>0,2+(Number(Xe)>>>0)>>>0)),wIsConst:()=>!!s()[wt>>>0],outputPadding:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],outputShape:ps?Array.from(o().subarray(Number(ps)>>>0,Number(vs)>>>0)):[],activation:Hs(He)})},920464:(l,m,P,F,G,ge,Xe,nt,wt,Ct,Wt,ps,vs,He,ls)=>{d.kb("ConvTranspose",l,{format:wt?"NHWC":"NCHW",autoPad:m,dilations:[P],group:F,kernelShape:[G],pads:[ge,Xe],strides:[nt],wIsConst:()=>!!s()[Ct>>>0],outputPadding:Wt?Array.from(o().subarray(Number(Wt)>>>0,Number(ps)>>>0)):[],outputShape:vs?Array.from(o().subarray(Number(vs)>>>0,Number(He)>>>0)):[],activation:Hs(ls)})},920897:(l,m,P,F,G,ge,Xe,nt,wt,Ct,Wt,ps,vs,He)=>{d.kb("ConvTranspose",l,{format:nt?"NHWC":"NCHW",autoPad:m,dilations:Array.from(o().subarray(Number(P)>>>0,2+(Number(P)>>>0)>>>0)),group:F,kernelShape:Array.from(o().subarray(Number(G)>>>0,2+(Number(G)>>>0)>>>0)),pads:Array.from(o().subarray(Number(ge)>>>0,4+(Number(ge)>>>0)>>>0)),strides:Array.from(o().subarray(Number(Xe)>>>0,2+(Number(Xe)>>>0)>>>0)),wIsConst:()=>!!s()[wt>>>0],outputPadding:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],outputShape:ps?Array.from(o().subarray(Number(ps)>>>0,Number(vs)>>>0)):[],activation:Hs(He)})},921558:(l,m)=>{d.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},921649:(l,m,P,F,G,ge,Xe,nt,wt,Ct,Wt,ps,vs,He)=>{d.kb("AveragePool",l,{format:He?"NHWC":"NCHW",auto_pad:m,ceil_mode:P,count_include_pad:F,storage_order:G,dilations:ge?Array.from(o().subarray(Number(ge)>>>0,Number(Xe)>>>0)):[],kernel_shape:nt?Array.from(o().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],pads:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],strides:ps?Array.from(o().subarray(Number(ps)>>>0,Number(vs)>>>0)):[]})},922128:(l,m)=>{d.kb("GlobalAveragePool",l,{format:m?"NHWC":"NCHW"})},922219:(l,m,P,F,G,ge,Xe,nt,wt,Ct,Wt,ps,vs,He)=>{d.kb("AveragePool",l,{format:He?"NHWC":"NCHW",auto_pad:m,ceil_mode:P,count_include_pad:F,storage_order:G,dilations:ge?Array.from(o().subarray(Number(ge)>>>0,Number(Xe)>>>0)):[],kernel_shape:nt?Array.from(o().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],pads:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],strides:ps?Array.from(o().subarray(Number(ps)>>>0,Number(vs)>>>0)):[]})},922698:(l,m)=>{d.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},922785:(l,m,P,F,G,ge,Xe,nt,wt,Ct,Wt,ps,vs,He)=>{d.kb("MaxPool",l,{format:He?"NHWC":"NCHW",auto_pad:m,ceil_mode:P,count_include_pad:F,storage_order:G,dilations:ge?Array.from(o().subarray(Number(ge)>>>0,Number(Xe)>>>0)):[],kernel_shape:nt?Array.from(o().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],pads:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],strides:ps?Array.from(o().subarray(Number(ps)>>>0,Number(vs)>>>0)):[]})},923260:(l,m)=>{d.kb("GlobalMaxPool",l,{format:m?"NHWC":"NCHW"})},923347:(l,m,P,F,G,ge,Xe,nt,wt,Ct,Wt,ps,vs,He)=>{d.kb("MaxPool",l,{format:He?"NHWC":"NCHW",auto_pad:m,ceil_mode:P,count_include_pad:F,storage_order:G,dilations:ge?Array.from(o().subarray(Number(ge)>>>0,Number(Xe)>>>0)):[],kernel_shape:nt?Array.from(o().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],pads:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],strides:ps?Array.from(o().subarray(Number(ps)>>>0,Number(vs)>>>0)):[]})},923822:(l,m,P,F,G)=>{d.kb("Gemm",l,{alpha:m,beta:P,transA:F,transB:G})},923926:l=>{d.kb("MatMul",l,void 0)},923980:(l,m,P,F)=>{d.kb("ArgMax",l,{keepDims:!!m,selectLastIndex:!!P,axis:F})},924088:(l,m,P,F)=>{d.kb("ArgMin",l,{keepDims:!!m,selectLastIndex:!!P,axis:F})},924196:(l,m)=>{d.kb("Softmax",l,{axis:m})},924259:(l,m)=>{d.kb("Concat",l,{axis:m})},924319:(l,m,P,F,G)=>{d.kb("Split",l,{axis:m,numOutputs:P,splitSizes:F?Array.from(o().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},924475:l=>{d.kb("Expand",l,void 0)},924529:(l,m)=>{d.kb("Gather",l,{axis:Number(m)})},924600:(l,m)=>{d.kb("GatherElements",l,{axis:Number(m)})},924679:(l,m)=>{d.kb("GatherND",l,{batch_dims:Number(m)})},924758:(l,m,P,F,G,ge,Xe,nt,wt,Ct,Wt)=>{d.kb("Resize",l,{antialias:m,axes:P?Array.from(o().subarray(Number(P)>>>0,Number(F)>>>0)):[],coordinateTransformMode:Hs(G),cubicCoeffA:ge,excludeOutside:Xe,extrapolationValue:nt,keepAspectRatioPolicy:Hs(wt),mode:Hs(Ct),nearestMode:Hs(Wt)})},925120:(l,m,P,F,G,ge,Xe)=>{d.kb("Slice",l,{starts:m?Array.from(o().subarray(Number(m)>>>0,Number(P)>>>0)):[],ends:F?Array.from(o().subarray(Number(F)>>>0,Number(G)>>>0)):[],axes:ge?Array.from(o().subarray(Number(ge)>>>0,Number(Xe)>>>0)):[]})},925384:l=>{d.kb("Tile",l,void 0)},925436:(l,m,P)=>{d.kb("InstanceNormalization",l,{epsilon:m,format:P?"NHWC":"NCHW"})},925550:(l,m,P)=>{d.kb("InstanceNormalization",l,{epsilon:m,format:P?"NHWC":"NCHW"})},925664:l=>{d.kb("Range",l,void 0)},925717:(l,m)=>{d.kb("Einsum",l,{equation:Hs(m)})},925798:(l,m,P,F,G)=>{d.kb("Pad",l,{mode:m,value:P,pads:F?Array.from(o().subarray(Number(F)>>>0,Number(G)>>>0)):[]})},925941:(l,m,P,F,G,ge)=>{d.kb("BatchNormalization",l,{epsilon:m,momentum:P,spatial:!!G,trainingMode:!!F,format:ge?"NHWC":"NCHW"})},926110:(l,m,P,F,G,ge)=>{d.kb("BatchNormalization",l,{epsilon:m,momentum:P,spatial:!!G,trainingMode:!!F,format:ge?"NHWC":"NCHW"})},926279:(l,m,P)=>{d.kb("CumSum",l,{exclusive:Number(m),reverse:Number(P)})},926376:(l,m,P)=>{d.kb("DequantizeLinear",l,{axis:m,blockSize:P})},926466:(l,m,P,F,G)=>{d.kb("GridSample",l,{align_corners:m,mode:Hs(P),padding_mode:Hs(F),format:G?"NHWC":"NCHW"})},926636:(l,m,P,F,G)=>{d.kb("GridSample",l,{align_corners:m,mode:Hs(P),padding_mode:Hs(F),format:G?"NHWC":"NCHW"})},926806:(l,m,P,F,G,ge,Xe,nt,wt)=>{d.kb("Attention",l,{numHeads:m,isUnidirectional:P,maskFilterValue:F,scale:G,doRotary:ge,qkvHiddenSizes:Xe?Array.from(o().subarray(Number(nt)>>>0,Number(nt)+Xe>>>0)):[],pastPresentShareBuffer:!!wt})},927078:l=>{d.kb("BiasAdd",l,void 0)},927133:l=>{d.kb("BiasSplitGelu",l,void 0)},927194:l=>{d.kb("FastGelu",l,void 0)},927250:(l,m,P,F,G,ge,Xe,nt,wt,Ct,Wt,ps,vs,He,ls,js)=>{d.kb("Conv",l,{format:ps?"NHWC":"NCHW",auto_pad:m,dilations:P?Array.from(o().subarray(Number(P)>>>0,Number(F)>>>0)):[],group:G,kernel_shape:ge?Array.from(o().subarray(Number(ge)>>>0,Number(Xe)>>>0)):[],pads:nt?Array.from(o().subarray(Number(nt)>>>0,Number(wt)>>>0)):[],strides:Ct?Array.from(o().subarray(Number(Ct)>>>0,Number(Wt)>>>0)):[],w_is_const:()=>!!s()[Number(vs)>>>0],activation:Hs(He),activation_params:ls?Array.from(p().subarray(Number(ls)>>>0,Number(js)>>>0)):[]})},927834:l=>{d.kb("Gelu",l,void 0)},927886:(l,m,P,F,G,ge,Xe,nt,wt)=>{d.kb("GroupQueryAttention",l,{numHeads:m,kvNumHeads:P,scale:F,softcap:G,doRotary:ge,rotaryInterleaved:Xe,smoothSoftmax:nt,localWindowSize:wt})},928103:(l,m,P,F)=>{d.kb("LayerNormalization",l,{axis:m,epsilon:P,simplified:!!F})},928214:(l,m,P,F)=>{d.kb("LayerNormalization",l,{axis:m,epsilon:P,simplified:!!F})},928325:(l,m,P,F,G,ge)=>{d.kb("MatMulNBits",l,{k:m,n:P,accuracyLevel:F,bits:G,blockSize:ge})},928452:(l,m,P,F,G,ge)=>{d.kb("MultiHeadAttention",l,{numHeads:m,isUnidirectional:P,maskFilterValue:F,scale:G,doRotary:ge})},928611:(l,m)=>{d.kb("QuickGelu",l,{alpha:m})},928675:(l,m,P,F,G)=>{d.kb("RotaryEmbedding",l,{interleaved:!!m,numHeads:P,rotaryEmbeddingDim:F,scale:G})},928814:(l,m,P)=>{d.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!P})},928916:(l,m,P)=>{d.kb("SkipLayerNormalization",l,{epsilon:m,simplified:!!P})},929018:(l,m,P,F)=>{d.kb("GatherBlockQuantized",l,{gatherAxis:m,quantizeAxis:P,blockSize:F})},929139:l=>{d.$b(l)},929173:(l,m)=>d.cc(Number(l),Number(m),d.Gb.hc,d.Gb.errors)};function uf(l,m,P){return Mm(async()=>{await d.Yb(Number(l),Number(m),Number(P))})}function df(){return typeof wasmOffsetConverter<"u"}function th(l){this.name="ExitStatus",this.message=`Program terminated with exit(${l})`,this.status=l}var sh=l=>{l.terminate(),l.onmessage=()=>{}},jh=l=>{Yn.length==0&&(Hh(),Kh(Yn[0]));var m=Yn.pop();if(!m)return 6;Di.push(m),pn[l.Bb]=m,m.Bb=l.Bb;var P={cmd:"run",start_routine:l.ic,arg:l.Rb,pthread_ptr:l.Bb};return m.postMessage(P,l.nc),0},Fi=0,Rs=(l,m,...P)=>{for(var F=2*P.length,G=Mh(),ge=yh(8*F),Xe=ge>>>3,nt=0;nt>>0]=wt)}return l=Wm(l,0,F,ge,m),Bp(G),l};function rh(l){if(Z)return Rs(0,1,l);if(Ht=l,!(0{if(Ht=l,Z)throw Uh(l),"unwind";rh(l)},Yn=[],Di=[],Vh=[],pn={},Wh=l=>{var m=l.Bb;delete pn[m],Yn.push(l),Di.splice(Di.indexOf(l),1),l.Bb=0,wh(m)};function Gh(){Vh.forEach(l=>l())}var Kh=l=>new Promise(m=>{l.onmessage=G=>{var ge=(G=G.data).cmd;if(G.targetThread&&G.targetThread!=Ia()){var Xe=pn[G.targetThread];Xe?Xe.postMessage(G,G.transferList):bt(`Internal error! Worker sent a message "${ge}" to target pthread ${G.targetThread}, but that thread no longer exists!`)}else ge==="checkMailbox"?Cp():ge==="spawnThread"?jh(G):ge==="cleanupThread"?Wh(pn[G.thread]):ge==="killThread"?(G=G.thread,ge=pn[G],delete pn[G],sh(ge),wh(G),Di.splice(Di.indexOf(ge),1),ge.Bb=0):ge==="cancelThread"?pn[G.thread].postMessage({cmd:"cancel"}):ge==="loaded"?(l.loaded=!0,m(l)):ge==="alert"?alert(`Thread ${G.threadId}: ${G.text}`):G.target==="setimmediate"?l.postMessage(G):ge==="callHandler"?d[G.handler](...G.args):ge&&bt(`worker sent an unknown command ${ge}`)},l.onerror=G=>{throw bt(`worker sent an error! ${G.filename}:${G.lineno}: ${G.message}`),G};var P,F=[];for(P of[])d.hasOwnProperty(P)&&F.push(P);l.postMessage({cmd:"load",handlers:F,wasmMemory:Ft,wasmModule:bs})});function Hh(){var l=new Worker(self.location.href.startsWith("file:")?new URL(r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb"),r.b):new URL(self.location.href),{type:"module",workerData:"em-pthread",name:"em-pthread"});Yn.push(l)}var Ep=l=>{for(;0{var l=Ia(),m=u()[l+52>>>2>>>0];l=u()[l+56>>>2>>>0],Km(m,m-l),Bp(m)},pf=(l,m)=>{Fi=0,l=Hm(l,m),0>>=0);throw m>>>=0,P>>>=0,u()[F.Kb+16>>>2>>>0]=0,u()[F.Kb+4>>>2>>>0]=m,u()[F.Kb+8>>>2>>>0]=P,l}function qh(l,m,P,F){return Z?Rs(2,1,l,m,P,F):Qh(l,m,P,F)}function Qh(l,m,P,F){if(l>>>=0,m>>>=0,P>>>=0,F>>>=0,ee===void 0)return bt("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var G=[];return Z&&G.length===0?qh(l,m,P,F):(l={ic:P,Bb:l,Rb:F,nc:G},Z?(l.Nb="spawnThread",postMessage(l,G),0):jh(l))}var Xh=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Yh=(l,m,P)=>{var F=(m>>>=0)+P;for(P=m;l[P]&&!(P>=F);)++P;if(16(G=(240&G)==224?(15&G)<<12|ge<<6|Xe:(7&G)<<18|ge<<12|Xe<<6|63&l[m++])?F+=String.fromCharCode(G):(G-=65536,F+=String.fromCharCode(55296|G>>10,56320|1023&G))}}else F+=String.fromCharCode(G)}return F},Hs=(l,m)=>(l>>>=0)?Yh(n(),l,m):"";function Jh(l,m,P){return Z?Rs(3,1,l,m,P):0}function Zh(l,m){if(Z)return Rs(4,1,l,m)}var ih=l=>{for(var m=0,P=0;P=F?m++:2047>=F?m+=2:55296<=F&&57343>=F?(m+=4,++P):m+=3}return m},em=(l,m,P,F)=>{if(!(0>>=0;F=P+F-1;for(var ge=0;ge=Xe&&(Xe=65536+((1023&Xe)<<10)|1023&l.charCodeAt(++ge)),127>=Xe){if(P>=F)break;m[P++>>>0]=Xe}else{if(2047>=Xe){if(P+1>=F)break;m[P++>>>0]=192|Xe>>6}else{if(65535>=Xe){if(P+2>=F)break;m[P++>>>0]=224|Xe>>12}else{if(P+3>=F)break;m[P++>>>0]=240|Xe>>18,m[P++>>>0]=128|Xe>>12&63}m[P++>>>0]=128|Xe>>6&63}m[P++>>>0]=128|63&Xe}}return m[P>>>0]=0,P-G},$a=(l,m,P)=>em(l,n(),m,P);function tm(l,m){if(Z)return Rs(5,1,l,m)}function sm(l,m,P){if(Z)return Rs(6,1,l,m,P)}function rm(l,m,P){return Z?Rs(7,1,l,m,P):0}function nm(l,m){if(Z)return Rs(8,1,l,m)}function im(l,m,P){if(Z)return Rs(9,1,l,m,P)}function om(l,m,P,F){if(Z)return Rs(10,1,l,m,P,F)}function am(l,m,P,F){if(Z)return Rs(11,1,l,m,P,F)}function lm(l,m,P,F){if(Z)return Rs(12,1,l,m,P,F)}function um(l){if(Z)return Rs(13,1,l)}function dm(l,m){if(Z)return Rs(14,1,l,m)}function cm(l,m,P){if(Z)return Rs(15,1,l,m,P)}var pm,Jn,ff=()=>{Xn("")},hn=l=>{for(var m="";n()[l>>>0];)m+=pm[n()[l++>>>0]];return m},oh={},ah={};function kn(l,m,P={}){if(!("argPackAdvance"in m))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(F,G,ge={}){var Xe=G.name;if(!F)throw new Jn(`type "${Xe}" must have a positive integer typeid pointer`);if(ah.hasOwnProperty(F)){if(ge.Tb)return;throw new Jn(`Cannot register type '${Xe}' twice`)}ah[F]=G,oh.hasOwnProperty(F)&&(G=oh[F],delete oh[F],G.forEach(nt=>nt()))}(l,m,P)}var hm=(l,m,P)=>{switch(m){case 1:return P?F=>s()[F>>>0]:F=>n()[F>>>0];case 2:return P?F=>i()[F>>>1>>>0]:F=>a()[F>>>1>>>0];case 4:return P?F=>o()[F>>>2>>>0]:F=>u()[F>>>2>>>0];case 8:return P?F=>er[F>>>3]:F=>cn[F>>>3];default:throw new TypeError(`invalid integer width (${m}): ${l}`)}};function _f(l,m,P){P>>>=0,kn(l>>>=0,{name:m=hn(m>>>0),fromWireType:F=>F,toWireType:function(F,G){if(typeof G!="bigint"&&typeof G!="number")throw G=G===null?"null":(F=typeof G)=="object"||F==="array"||F==="function"?G.toString():""+G,new TypeError(`Cannot convert "${G}" to ${this.name}`);return typeof G=="number"&&(G=BigInt(G)),G},argPackAdvance:Zn,readValueFromPointer:hm(m,P,m.indexOf("u")==-1),Eb:null})}var Zn=8;function gf(l,m,P,F){kn(l>>>=0,{name:m=hn(m>>>0),fromWireType:function(G){return!!G},toWireType:function(G,ge){return ge?P:F},argPackAdvance:Zn,readValueFromPointer:function(G){return this.fromWireType(n()[G>>>0])},Eb:null})}var lh=[],Sn=[];function uh(l){9<(l>>>=0)&&--Sn[l+1]==0&&(Sn[l]=void 0,lh.push(l))}var kr=l=>{if(!l)throw new Jn("Cannot use deleted val. handle = "+l);return Sn[l]},Br=l=>{switch(l){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=lh.pop()||Sn.length;return Sn[m]=l,Sn[m+1]=1,m}};function dh(l){return this.fromWireType(u()[l>>>2>>>0])}var wf={name:"emscripten::val",fromWireType:l=>{var m=kr(l);return uh(l),m},toWireType:(l,m)=>Br(m),argPackAdvance:Zn,readValueFromPointer:dh,Eb:null};function yf(l){return kn(l>>>0,wf)}var Mf=(l,m)=>{switch(m){case 4:return function(P){return this.fromWireType(p()[P>>>2>>>0])};case 8:return function(P){return this.fromWireType(h()[P>>>3>>>0])};default:throw new TypeError(`invalid float width (${m}): ${l}`)}};function bf(l,m,P){P>>>=0,kn(l>>>=0,{name:m=hn(m>>>0),fromWireType:F=>F,toWireType:(F,G)=>G,argPackAdvance:Zn,readValueFromPointer:Mf(m,P),Eb:null})}function vf(l,m,P,F,G){if(l>>>=0,P>>>=0,m=hn(m>>>0),G===-1&&(G=4294967295),G=nt=>nt,F===0){var ge=32-8*P;G=nt=>nt<>>ge}var Xe=m.includes("unsigned")?function(nt,wt){return wt>>>0}:function(nt,wt){return wt};kn(l,{name:m,fromWireType:G,toWireType:Xe,argPackAdvance:Zn,readValueFromPointer:hm(m,P,F!==0),Eb:null})}function xf(l,m,P){function F(ge){var Xe=u()[ge>>>2>>>0];return ge=u()[ge+4>>>2>>>0],new G(s().buffer,ge,Xe)}var G=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];kn(l>>>=0,{name:P=hn(P>>>0),fromWireType:F,argPackAdvance:Zn,readValueFromPointer:F},{Tb:!0})}function Tf(l,m){l>>>=0;var P=(m=hn(m>>>0))==="std::string";kn(l,{name:m,fromWireType:function(F){var G=u()[F>>>2>>>0],ge=F+4;if(P)for(var Xe=ge,nt=0;nt<=G;++nt){var wt=ge+nt;if(nt==G||n()[wt>>>0]==0){if(Xe=Hs(Xe,wt-Xe),Ct===void 0)var Ct=Xe;else Ct+="\0",Ct+=Xe;Xe=wt+1}}else{for(Ct=Array(G),nt=0;nt>>0]);Ct=Ct.join("")}return fn(F),Ct},toWireType:function(F,G){G instanceof ArrayBuffer&&(G=new Uint8Array(G));var ge=typeof G=="string";if(!(ge||G instanceof Uint8Array||G instanceof Uint8ClampedArray||G instanceof Int8Array))throw new Jn("Cannot pass non-string to std::string");var Xe=P&&ge?ih(G):G.length,nt=Lp(4+Xe+1),wt=nt+4;if(u()[nt>>>2>>>0]=Xe,P&&ge)$a(G,wt,Xe+1);else if(ge)for(ge=0;ge>>0]=Ct}else for(ge=0;ge>>0]=G[ge];return F!==null&&F.push(fn,nt),nt},argPackAdvance:Zn,readValueFromPointer:dh,Eb(F){fn(F)}})}var mm=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Pf=(l,m)=>{for(var P=l>>1,F=P+m/2;!(P>=F)&&a()[P>>>0];)++P;if(32<(P<<=1)-l&&mm)return mm.decode(n().slice(l,P));for(P="",F=0;!(F>=m/2);++F){var G=i()[l+2*F>>>1>>>0];if(G==0)break;P+=String.fromCharCode(G)}return P},Ef=(l,m,P)=>{if(P??(P=2147483647),2>P)return 0;var F=m;P=(P-=2)<2*l.length?P/2:l.length;for(var G=0;G>>1>>>0]=ge,m+=2}return i()[m>>>1>>>0]=0,m-F},Cf=l=>2*l.length,kf=(l,m)=>{for(var P=0,F="";!(P>=m/4);){var G=o()[l+4*P>>>2>>>0];if(G==0)break;++P,65536<=G?(G-=65536,F+=String.fromCharCode(55296|G>>10,56320|1023&G)):F+=String.fromCharCode(G)}return F},Sf=(l,m,P)=>{if(m>>>=0,P??(P=2147483647),4>P)return 0;var F=m;P=F+P-4;for(var G=0;G=ge&&(ge=65536+((1023&ge)<<10)|1023&l.charCodeAt(++G)),o()[m>>>2>>>0]=ge,(m+=4)+4>P)break}return o()[m>>>2>>>0]=0,m-F},$f=l=>{for(var m=0,P=0;P=F&&++P,m+=4}return m};function Af(l,m,P){if(l>>>=0,m>>>=0,P=hn(P>>>=0),m===2)var F=Pf,G=Ef,ge=Cf,Xe=nt=>a()[nt>>>1>>>0];else m===4&&(F=kf,G=Sf,ge=$f,Xe=nt=>u()[nt>>>2>>>0]);kn(l,{name:P,fromWireType:nt=>{for(var wt,Ct=u()[nt>>>2>>>0],Wt=nt+4,ps=0;ps<=Ct;++ps){var vs=nt+4+ps*m;ps!=Ct&&Xe(vs)!=0||(Wt=F(Wt,vs-Wt),wt===void 0?wt=Wt:(wt+="\0",wt+=Wt),Wt=vs+m)}return fn(nt),wt},toWireType:(nt,wt)=>{if(typeof wt!="string")throw new Jn(`Cannot pass non-string to C++ string type ${P}`);var Ct=ge(wt),Wt=Lp(4+Ct+m);return u()[Wt>>>2>>>0]=Ct/m,G(wt,Wt+4,Ct+m),nt!==null&&nt.push(fn,Wt),Wt},argPackAdvance:Zn,readValueFromPointer:dh,Eb(nt){fn(nt)}})}function If(l,m){kn(l>>>=0,{Ub:!0,name:m=hn(m>>>0),argPackAdvance:0,fromWireType:()=>{},toWireType:()=>{}})}var Of=()=>1;function Ff(l){gh(l>>>0,!V,1,!B,131072,!1),Gh()}var fm=l=>{if(!Bs)try{if(l(),!(0>>=0,typeof Atomics.oc=="function"&&(Atomics.oc(o(),l>>>2,l).value.then(Cp),l+=128,Atomics.store(o(),l>>>2,1))}var Cp=()=>{var l=Ia();l&&(ch(l),fm(Gm))};function Df(l,m){(l>>>=0)==m>>>0?setTimeout(Cp):Z?postMessage({targetThread:l,cmd:"checkMailbox"}):(l=pn[l])&&l.postMessage({cmd:"checkMailbox"})}var ph=[];function Lf(l,m,P,F,G){for(m>>>=0,F/=2,ph.length=F,P=G>>>0>>>3,G=0;G>>0];return(m?eh[m]:E_[l])(...ph)}function zf(l){l>>>=0,Z?postMessage({cmd:"cleanupThread",thread:l}):Wh(pn[l])}function Bf(l){}var kp=(l,m)=>{var P=ah[l];if(P===void 0)throw l=jm(l),P=hn(l),fn(l),new Jn(`${m} has unknown type ${P}`);return P},_m=(l,m,P)=>{var F=[];return l=l.toWireType(F,P),F.length&&(u()[m>>>2>>>0]=Br(F)),l};function Rf(l,m,P){return m>>>=0,P>>>=0,l=kr(l>>>0),m=kp(m,"emval::as"),_m(m,P,l)}function Nf(l,m){return m>>>=0,l=kr(l>>>0),(m=kp(m,"emval::as")).toWireType(null,l)}var Sp=l=>{try{l()}catch(m){Xn(m)}},ei=0,mn=null,gm=0,$p=[],wm={},ym={},jf=0,hh=null,Uf=[];function Mm(l){return function(m){if(!Bs){if(ei===0){var P=!1,F=!1;m((G=0)=>{if(!Bs&&(gm=G,P=!0,F)){ei=2,Sp(()=>Xm(mn)),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.resume(),G=!1;try{var ge=function(){var wt=o()[mn+8>>>2>>>0];return wt=Ut[ym[wt]],--Fi,wt()}()}catch(wt){ge=wt,G=!0}var Xe=!1;if(!mn){var nt=hh;nt&&(hh=null,(G?nt.reject:nt.resolve)(ge),Xe=!0)}if(G&&!Xe)throw ge}}),F=!0,P||(ei=1,mn=function(){var G=Lp(65548),ge=G+12;u()[G>>>2>>>0]=ge,u()[G+4>>>2>>>0]=ge+65536,ge=$p[0];var Xe=wm[ge];return Xe===void 0&&(Xe=jf++,wm[ge]=Xe,ym[Xe]=ge),ge=Xe,o()[G+8>>>2>>>0]=ge,G}(),typeof Browser<"u"&&Browser.Lb.Sb&&Browser.Lb.pause(),Sp(()=>qm(mn)))}else ei===2?(ei=0,Sp(Ym),fn(mn),mn=null,Uf.forEach(fm)):Xn(`invalid state: ${ei}`);return gm}}(m=>{l().then(m)})}function Vf(l){return l>>>=0,Mm(()=>(l=kr(l)).then(Br))}var Ap=[];function Wf(l,m,P,F){return P>>>=0,F>>>=0,(l=Ap[l>>>0])(null,m=kr(m>>>0),P,F)}var Gf={},Ip=l=>{var m=Gf[l];return m===void 0?hn(l):m};function Kf(l,m,P,F,G){return P>>>=0,F>>>=0,G>>>=0,(l=Ap[l>>>0])(m=kr(m>>>0),m[P=Ip(P)],F,G)}var bm=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Hf(l){return(l>>>=0)==0?Br(bm()):(l=Ip(l),Br(bm()[l]))}var qf=l=>{var m=Ap.length;return Ap.push(l),m},Qf=(l,m)=>{for(var P=Array(l),F=0;F>>2>>>0],"parameter "+F);return P},vm=(l,m)=>Object.defineProperty(m,"name",{value:l});function Xf(l,m,P){var F=(m=Qf(l,m>>>0)).shift();l--;var G=`return function (obj, func, destructorsRef, args) { +`,ge=0,Xe=[];P===0&&Xe.push("obj");for(var nt=["retType"],wt=[F],Ct=0;CtWt.name).join(", ")}) => ${F.name}>`,qf(vm(P,l))}function Yf(l){return l=Ip(l>>>0),Br(d[l])}function Jf(l,m){return m>>>=0,l=kr(l>>>0),m=kr(m),Br(l[m])}function Zf(l){9<(l>>>=0)&&(Sn[l+1]+=1)}function e_(){return Br([])}function t_(l){l=kr(l>>>0);for(var m=Array(l.length),P=0;P>>0))}function r_(){return Br({})}function n_(l){for(var m=kr(l>>>=0);m.length;){var P=m.pop();m.pop()(P)}uh(l)}function i_(l,m,P){m>>>=0,P>>>=0,l=kr(l>>>0),m=kr(m),P=kr(P),l[m]=P}function o_(l,m){return m>>>=0,l=(l=kp(l>>>0,"_emval_take_value")).readValueFromPointer(m),Br(l)}function a_(l,m){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),o()[m>>>2>>>0]=l.getUTCSeconds(),o()[m+4>>>2>>>0]=l.getUTCMinutes(),o()[m+8>>>2>>>0]=l.getUTCHours(),o()[m+12>>>2>>>0]=l.getUTCDate(),o()[m+16>>>2>>>0]=l.getUTCMonth(),o()[m+20>>>2>>>0]=l.getUTCFullYear()-1900,o()[m+24>>>2>>>0]=l.getUTCDay(),l=(l.getTime()-Date.UTC(l.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,o()[m+28>>>2>>>0]=l}var Aa=l=>l%4==0&&(l%100!=0||l%400==0),xm=[0,31,60,91,121,152,182,213,244,274,305,335],Tm=[0,31,59,90,120,151,181,212,243,273,304,334];function l_(l,m){l=-9007199254740992>l||9007199254740992>>=0,l=new Date(1e3*l),o()[m>>>2>>>0]=l.getSeconds(),o()[m+4>>>2>>>0]=l.getMinutes(),o()[m+8>>>2>>>0]=l.getHours(),o()[m+12>>>2>>>0]=l.getDate(),o()[m+16>>>2>>>0]=l.getMonth(),o()[m+20>>>2>>>0]=l.getFullYear()-1900,o()[m+24>>>2>>>0]=l.getDay();var P=(Aa(l.getFullYear())?xm:Tm)[l.getMonth()]+l.getDate()-1|0;o()[m+28>>>2>>>0]=P,o()[m+36>>>2>>>0]=-60*l.getTimezoneOffset(),P=new Date(l.getFullYear(),6,1).getTimezoneOffset();var F=new Date(l.getFullYear(),0,1).getTimezoneOffset();l=0|(P!=F&&l.getTimezoneOffset()==Math.min(F,P)),o()[m+32>>>2>>>0]=l}function u_(l){l>>>=0;var m=new Date(o()[l+20>>>2>>>0]+1900,o()[l+16>>>2>>>0],o()[l+12>>>2>>>0],o()[l+8>>>2>>>0],o()[l+4>>>2>>>0],o()[l>>>2>>>0],0),P=o()[l+32>>>2>>>0],F=m.getTimezoneOffset(),G=new Date(m.getFullYear(),6,1).getTimezoneOffset(),ge=new Date(m.getFullYear(),0,1).getTimezoneOffset(),Xe=Math.min(ge,G);return 0>P?o()[l+32>>>2>>>0]=+(G!=ge&&Xe==F):0>>2>>>0]=m.getDay(),P=(Aa(m.getFullYear())?xm:Tm)[m.getMonth()]+m.getDate()-1|0,o()[l+28>>>2>>>0]=P,o()[l>>>2>>>0]=m.getSeconds(),o()[l+4>>>2>>>0]=m.getMinutes(),o()[l+8>>>2>>>0]=m.getHours(),o()[l+12>>>2>>>0]=m.getDate(),o()[l+16>>>2>>>0]=m.getMonth(),o()[l+20>>>2>>>0]=m.getYear(),l=m.getTime(),BigInt(isNaN(l)?-1:l/1e3)}function Pm(l,m,P,F,G,ge,Xe){return Z?Rs(16,1,l,m,P,F,G,ge,Xe):-52}function Em(l,m,P,F,G,ge){if(Z)return Rs(17,1,l,m,P,F,G,ge)}function d_(l,m,P,F){l>>>=0,m>>>=0,P>>>=0,F>>>=0;var G=new Date().getFullYear(),ge=new Date(G,0,1),Xe=new Date(G,6,1);G=ge.getTimezoneOffset();var nt=Xe.getTimezoneOffset(),wt=Math.max(G,nt);u()[l>>>2>>>0]=60*wt,o()[m>>>2>>>0]=+(G!=nt),ge=(l=Ct=>Ct.toLocaleTimeString(void 0,{hour12:!1,timeZoneName:"short"}).split(" ")[1])(ge),Xe=l(Xe),nt{mh.length=0;for(var P;P=n()[l++>>>0];){var F=P!=105;m+=(F&=P!=112)&&m%8?4:0,mh.push(P==112?u()[m>>>2>>>0]:P==106?er[m>>>3]:P==105?o()[m>>>2>>>0]:h()[m>>>3>>>0]),m+=F?8:4}return mh};function c_(l,m,P){return l>>>=0,m=Cm(m>>>0,P>>>0),eh[l](...m)}function p_(l,m,P){return l>>>=0,m=Cm(m>>>0,P>>>0),eh[l](...m)}var h_=()=>{},m_=()=>Date.now();function f_(l,m){return bt(Hs(l>>>0,m>>>0))}var km,__=()=>{throw Fi+=1,"unwind"};function g_(){return 4294901760}km=()=>performance.timeOrigin+performance.now();var w_=()=>navigator.hardwareConcurrency;function y_(){return Xn("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function M_(l){l>>>=0;var m=n().length;if(l<=m||4294901760=P;P*=2){var F=m*(1+.2/P);F=Math.min(F,l+100663296);var G=Math;F=Math.max(l,F);e:{G=(G.min.call(G,4294901760,F+(65536-F%65536)%65536)-Ft.buffer.byteLength+65535)/65536;try{Ft.grow(G),Ps();var ge=1;break e}catch{}ge=void 0}if(ge)return!0}return!1}var Op=()=>(Xn("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Lc={},Sm=l=>{l.forEach(m=>{Op()})};function b_(){var l=Error().stack.toString().split(` +`);return l[0]=="Error"&&l.shift(),Sm(l),Lc.Qb=Op(),Lc.fc=l,Lc.Qb}function v_(l,m,P){if(l>>>=0,m>>>=0,Lc.Qb==l)var F=Lc.fc;else(F=Error().stack.toString().split(` +`))[0]=="Error"&&F.shift(),Sm(F);for(var G=3;F[G]&&Op()!=l;)++G;for(l=0;l>>2>>>0]=Op();return l}var fh,_h={},$m=()=>{if(!fh){var l,m={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",_:Fe};for(l in _h)_h[l]===void 0?delete m[l]:m[l]=_h[l];var P=[];for(l in m)P.push(`${l}=${m[l]}`);fh=P}return fh};function Am(l,m){if(Z)return Rs(18,1,l,m);l>>>=0,m>>>=0;var P=0;return $m().forEach((F,G)=>{var ge=m+P;for(G=u()[l+4*G>>>2>>>0]=ge,ge=0;ge>>0]=F.charCodeAt(ge);s()[G>>>0]=0,P+=F.length+1}),0}function Im(l,m){if(Z)return Rs(19,1,l,m);l>>>=0,m>>>=0;var P=$m();u()[l>>>2>>>0]=P.length;var F=0;return P.forEach(G=>F+=G.length+1),u()[m>>>2>>>0]=F,0}function Om(l){return Z?Rs(20,1,l):52}function Fm(l,m,P,F){return Z?Rs(21,1,l,m,P,F):52}function Dm(l,m,P,F){return Z?Rs(22,1,l,m,P,F):70}var x_=[null,[],[]];function Lm(l,m,P,F){if(Z)return Rs(23,1,l,m,P,F);m>>>=0,P>>>=0,F>>>=0;for(var G=0,ge=0;ge>>2>>>0],nt=u()[m+4>>>2>>>0];m+=8;for(var wt=0;wt>>0],Wt=x_[l];Ct===0||Ct===10?((l===1?Zt:bt)(Yh(Wt,0)),Wt.length=0):Wt.push(Ct)}G+=nt}return u()[F>>>2>>>0]=G,0}var zm=[31,29,31,30,31,30,31,31,30,31,30,31],Bm=[31,28,31,30,31,30,31,31,30,31,30,31],T_=(l,m)=>{s().set(l,m>>>0)};function Rm(l,m,P,F){function G(He,ls,js){for(He=typeof He=="number"?He.toString():He||"";He.lengthZm?-1:0Li-He.getDate())){He.setDate(He.getDate()+ls);break}ls-=Li-He.getDate()+1,He.setDate(1),11>js?He.setMonth(js+1):(He.setMonth(0),He.setFullYear(He.getFullYear()+1))}return js=new Date(He.getFullYear()+1,0,4),ls=nt(new Date(He.getFullYear(),0,4)),js=nt(js),0>=Xe(ls,He)?0>=Xe(js,He)?He.getFullYear()+1:He.getFullYear():He.getFullYear()-1}l>>>=0,m>>>=0,P>>>=0,F>>>=0;var Ct=u()[F+40>>>2>>>0];for(var Wt in F={lc:o()[F>>>2>>>0],kc:o()[F+4>>>2>>>0],Ib:o()[F+8>>>2>>>0],Mb:o()[F+12>>>2>>>0],Jb:o()[F+16>>>2>>>0],Db:o()[F+20>>>2>>>0],vb:o()[F+24>>>2>>>0],Cb:o()[F+28>>>2>>>0],sc:o()[F+32>>>2>>>0],jc:o()[F+36>>>2>>>0],mc:Ct?Hs(Ct):""},P=Hs(P),Ct={"%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"})P=P.replace(new RegExp(Wt,"g"),Ct[Wt]);var ps="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),vs="January February March April May June July August September October November December".split(" ");for(Wt in Ct={"%a":He=>ps[He.vb].substring(0,3),"%A":He=>ps[He.vb],"%b":He=>vs[He.Jb].substring(0,3),"%B":He=>vs[He.Jb],"%C":He=>ge((He.Db+1900)/100|0,2),"%d":He=>ge(He.Mb,2),"%e":He=>G(He.Mb,2," "),"%g":He=>wt(He).toString().substring(2),"%G":wt,"%H":He=>ge(He.Ib,2),"%I":He=>((He=He.Ib)==0?He=12:12{for(var ls=0,js=0;js<=He.Jb-1;ls+=(Aa(He.Db+1900)?zm:Bm)[js++]);return ge(He.Mb+ls,3)},"%m":He=>ge(He.Jb+1,2),"%M":He=>ge(He.kc,2),"%n":()=>` +`,"%p":He=>0<=He.Ib&&12>He.Ib?"AM":"PM","%S":He=>ge(He.lc,2),"%t":()=>" ","%u":He=>He.vb||7,"%U":He=>ge(Math.floor((He.Cb+7-He.vb)/7),2),"%V":He=>{var ls=Math.floor((He.Cb+7-(He.vb+6)%7)/7);if(2>=(He.vb+371-He.Cb-2)%7&&ls++,ls)ls==53&&((js=(He.vb+371-He.Cb)%7)==4||js==3&&Aa(He.Db)||(ls=1));else{ls=52;var js=(He.vb+7-He.Cb-1)%7;(js==4||js==5&&Aa(He.Db%400-1))&&ls++}return ge(ls,2)},"%w":He=>He.vb,"%W":He=>ge(Math.floor((He.Cb+7-(He.vb+6)%7)/7),2),"%y":He=>(He.Db+1900).toString().substring(2),"%Y":He=>He.Db+1900,"%z":He=>{var ls=0<=(He=He.jc);return He=Math.abs(He)/60,(ls?"+":"-")+("0000"+(He/60*100+He%60)).slice(-4)},"%Z":He=>He.mc,"%%":()=>"%"},P=P.replace(/%%/g,"\0\0"),Ct)P.includes(Wt)&&(P=P.replace(new RegExp(Wt,"g"),Ct[Wt](F)));return Wt=function(He){var ls=Array(ih(He)+1);return em(He,ls,0,ls.length),ls}(P=P.replace(/\0\0/g,"%")),Wt.length>m?0:(T_(Wt,l),Wt.length-1)}function P_(l,m,P,F){return Rm(l>>>0,m>>>0,P>>>0,F>>>0)}Z||function(){for(var l=d.numThreads-1;l--;)Hh();Qn.unshift(()=>{Fc++,function(m){Z?m():Promise.all(Yn.map(Kh)).then(m)}(()=>Dh())})}();for(var Nm=Array(256),Fp=0;256>Fp;++Fp)Nm[Fp]=String.fromCharCode(Fp);pm=Nm,Jn=d.BindingError=class extends Error{constructor(l){super(l),this.name="BindingError"}},d.InternalError=class extends Error{constructor(l){super(l),this.name="InternalError"}},Sn.push(0,1,void 0,1,null,1,!0,1,!1,1),d.count_emval_handles=()=>Sn.length/2-5-lh.length;var E_=[rh,Uh,qh,Jh,Zh,tm,sm,rm,nm,im,om,am,lm,um,dm,cm,Pm,Em,Am,Im,Om,Fm,Dm,Lm],Ut=function(){function l(P,F){return Ut=P.exports,Ut=function(){var G=Ut,ge={};for(let[Xe,nt]of Object.entries(G))ge[Xe]=typeof nt=="function"?(...wt)=>{$p.push(Xe);try{return nt(...wt)}finally{Bs||($p.pop(),mn&&ei===1&&$p.length===0&&(ei=0,Fi+=1,Sp(Qm),typeof Fibers<"u"&&Fibers.tc()))}}:nt;return ge}(),Ut=function(){var G=Ut,ge=nt=>wt=>nt(wt)>>>0,Xe=nt=>()=>nt()>>>0;return(G=Object.assign({},G)).Da=ge(G.Da),G.gb=Xe(G.gb),G.ib=ge(G.ib),G.emscripten_main_runtime_thread_id=Xe(G.emscripten_main_runtime_thread_id),G.tb=ge(G.tb),G.ub=Xe(G.ub),G}(),Vh.push(Ut.jb),Oc.unshift(Ut.Ca),bs=F,Dh(),Ut}var m=Nh();if(Fc++,d.instantiateWasm)try{return d.instantiateWasm(m,l)}catch(P){bt(`Module.instantiateWasm callback failed with error: ${P}`),E(P)}return Zp||(Zp=d.locateFile?Lh("ort-wasm-simd-threaded.jsep.wasm")?"ort-wasm-simd-threaded.jsep.wasm":d.locateFile?d.locateFile("ort-wasm-simd-threaded.jsep.wasm",Ye):Ye+"ort-wasm-simd-threaded.jsep.wasm":new URL(r("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),r.b).href),function(P,F){var G=Zp;return at||typeof WebAssembly.instantiateStreaming!="function"||Lh(G)||zh(G)||typeof fetch!="function"?Rh(G,P,F):fetch(G,{credentials:"same-origin"}).then(ge=>WebAssembly.instantiateStreaming(ge,P).then(F,function(Xe){return bt(`wasm streaming compile failed: ${Xe}`),bt("falling back to ArrayBuffer instantiation"),Rh(G,P,F)}))}(m,function(P){l(P.instance,P.module)}).catch(E),{}}(),jm=l=>(jm=Ut.Da)(l),Um=()=>(Um=Ut.Ea)();d._OrtInit=(l,m)=>(d._OrtInit=Ut.Fa)(l,m),d._OrtGetLastError=(l,m)=>(d._OrtGetLastError=Ut.Ga)(l,m),d._OrtCreateSessionOptions=(l,m,P,F,G,ge,Xe,nt,wt,Ct)=>(d._OrtCreateSessionOptions=Ut.Ha)(l,m,P,F,G,ge,Xe,nt,wt,Ct),d._OrtAppendExecutionProvider=(l,m)=>(d._OrtAppendExecutionProvider=Ut.Ia)(l,m),d._OrtAddFreeDimensionOverride=(l,m,P)=>(d._OrtAddFreeDimensionOverride=Ut.Ja)(l,m,P),d._OrtAddSessionConfigEntry=(l,m,P)=>(d._OrtAddSessionConfigEntry=Ut.Ka)(l,m,P),d._OrtReleaseSessionOptions=l=>(d._OrtReleaseSessionOptions=Ut.La)(l),d._OrtCreateSession=(l,m,P)=>(d._OrtCreateSession=Ut.Ma)(l,m,P),d._OrtReleaseSession=l=>(d._OrtReleaseSession=Ut.Na)(l),d._OrtGetInputOutputCount=(l,m,P)=>(d._OrtGetInputOutputCount=Ut.Oa)(l,m,P),d._OrtGetInputName=(l,m)=>(d._OrtGetInputName=Ut.Pa)(l,m),d._OrtGetOutputName=(l,m)=>(d._OrtGetOutputName=Ut.Qa)(l,m),d._OrtFree=l=>(d._OrtFree=Ut.Ra)(l),d._OrtCreateTensor=(l,m,P,F,G,ge)=>(d._OrtCreateTensor=Ut.Sa)(l,m,P,F,G,ge),d._OrtGetTensorData=(l,m,P,F,G)=>(d._OrtGetTensorData=Ut.Ta)(l,m,P,F,G),d._OrtReleaseTensor=l=>(d._OrtReleaseTensor=Ut.Ua)(l),d._OrtCreateRunOptions=(l,m,P,F)=>(d._OrtCreateRunOptions=Ut.Va)(l,m,P,F),d._OrtAddRunConfigEntry=(l,m,P)=>(d._OrtAddRunConfigEntry=Ut.Wa)(l,m,P),d._OrtReleaseRunOptions=l=>(d._OrtReleaseRunOptions=Ut.Xa)(l),d._OrtCreateBinding=l=>(d._OrtCreateBinding=Ut.Ya)(l),d._OrtBindInput=(l,m,P)=>(d._OrtBindInput=Ut.Za)(l,m,P),d._OrtBindOutput=(l,m,P,F)=>(d._OrtBindOutput=Ut._a)(l,m,P,F),d._OrtClearBoundOutputs=l=>(d._OrtClearBoundOutputs=Ut.$a)(l),d._OrtReleaseBinding=l=>(d._OrtReleaseBinding=Ut.ab)(l),d._OrtRunWithBinding=(l,m,P,F,G)=>(d._OrtRunWithBinding=Ut.bb)(l,m,P,F,G),d._OrtRun=(l,m,P,F,G,ge,Xe,nt)=>(d._OrtRun=Ut.cb)(l,m,P,F,G,ge,Xe,nt),d._OrtEndProfiling=l=>(d._OrtEndProfiling=Ut.db)(l),d._JsepOutput=(l,m,P)=>(d._JsepOutput=Ut.eb)(l,m,P),d._JsepGetNodeName=l=>(d._JsepGetNodeName=Ut.fb)(l);var Dp,Ia=()=>(Ia=Ut.gb)(),fn=d._free=l=>(fn=d._free=Ut.hb)(l),Lp=d._malloc=l=>(Lp=d._malloc=Ut.ib)(l),gh=(l,m,P,F,G,ge)=>(gh=Ut.lb)(l,m,P,F,G,ge),Vm=()=>(Vm=Ut.mb)(),Wm=(l,m,P,F,G)=>(Wm=Ut.nb)(l,m,P,F,G),wh=l=>(wh=Ut.ob)(l),zp=l=>(zp=Ut.pb)(l),Gm=()=>(Gm=Ut.qb)(),Km=(l,m)=>(Km=Ut.rb)(l,m),Bp=l=>(Bp=Ut.sb)(l),yh=l=>(yh=Ut.tb)(l),Mh=()=>(Mh=Ut.ub)(),Hm=d.dynCall_ii=(l,m)=>(Hm=d.dynCall_ii=Ut.wb)(l,m),qm=l=>(qm=Ut.xb)(l),Qm=()=>(Qm=Ut.yb)(),Xm=l=>(Xm=Ut.zb)(l),Ym=()=>(Ym=Ut.Ab)();function Jm(){0Mh(),d.stackRestore=l=>Bp(l),d.stackAlloc=l=>yh(l),d.setValue=function(l,m,P="i8"){switch(P.endsWith("*")&&(P="*"),P){case"i1":case"i8":s()[l>>>0]=m;break;case"i16":i()[l>>>1>>>0]=m;break;case"i32":o()[l>>>2>>>0]=m;break;case"i64":er[l>>>3]=BigInt(m);break;case"float":p()[l>>>2>>>0]=m;break;case"double":h()[l>>>3>>>0]=m;break;case"*":u()[l>>>2>>>0]=m;break;default:Xn(`invalid type for setValue: ${P}`)}},d.getValue=function(l,m="i8"){switch(m.endsWith("*")&&(m="*"),m){case"i1":case"i8":return s()[l>>>0];case"i16":return i()[l>>>1>>>0];case"i32":return o()[l>>>2>>>0];case"i64":return er[l>>>3];case"float":return p()[l>>>2>>>0];case"double":return h()[l>>>3>>>0];case"*":return u()[l>>>2>>>0];default:Xn(`invalid type for getValue: ${m}`)}},d.UTF8ToString=Hs,d.stringToUTF8=$a,d.lengthBytesUTF8=ih,Dc=function l(){Dp||Jm(),Dp||(Dc=l)},Jm(),d.PTR_SIZE=4,z}),Ds=ks,((e=globalThis.self)==null?void 0:e.name)==="em-pthread"&&ks()}),Sr,Yr,Us,Tr,Nt,Jr,$r,Ar,Zr,pr,en,Ir,Rr,Nr=g(()=>{Je(),Sr=typeof location>"u"?void 0:location.origin,Yr=()=>{var e;return(e=self.location.href)!=null&&e.startsWith("file:")?new URL(new URL(r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb"),r.b).href,Sr).href:self.location.href},Us=Yr(),Tr=()=>{if(Us&&!Us.startsWith("blob:"))return Us.substring(0,Us.lastIndexOf("/")+1)},Nt=(e,t)=>{try{let s=t??Us;return(s?new URL(e,s):new URL(e)).origin===Sr}catch{return!1}},Jr=(e,t)=>{let s=t??Us;try{return(s?new URL(e,s):new URL(e)).href}catch{return}},$r=(e,t)=>`${t??"./"}${e}`,Ar=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Zr=async e=>(await import(e)).default,pr=(At(),M(ut)).default,en=async()=>{if(!Us)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Nt(Us))return[void 0,pr()];let e=await Ar(Us);return[e,pr(e)]},Ir=(sr(),M(is)).default,Rr=async(e,t,s)=>{if(!e&&!t&&Ir&&Us&&Nt(Us))return[void 0,Ir];{let n="ort-wasm-simd-threaded.jsep.mjs",i=e??Jr(n,t),a=s&&i&&!Nt(i,t),o=a?await Ar(i):i??$r(n,t);return[a?o:void 0,await Zr(o)]}}}),or,it,Tt,Dt,Vs,jr,Or,Ms,ar=g(()=>{Nr(),it=!1,Tt=!1,Dt=!1,Vs=()=>{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}},jr=()=>{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}},Or=async e=>{if(it)return Promise.resolve();if(Tt)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Dt)throw new Error("previous call to 'initializeWebAssembly()' failed.");Tt=!0;let t=e.initTimeout,s=e.numThreads;if(!jr())throw new Error("WebAssembly SIMD is not supported in the current environment.");let n=Vs();s>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+s+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=s=1);let i=e.wasmPaths,a=typeof i=="string"?i:void 0,o=i==null?void 0:i.mjs,u=(o==null?void 0:o.href)??o,p=i==null?void 0:i.wasm,h=(p==null?void 0:p.href)??p,k=e.wasmBinary,[E,d]=await Rr(u,a,s>1),z=!1,B=[];if(t>0&&B.push(new Promise(V=>{setTimeout(()=>{z=!0,V()},t)})),B.push(new Promise((V,Z)=>{let ee={numThreads:s};if(k)ee.wasmBinary=k;else if(h||a)ee.locateFile=Q=>h??a+Q;else if(u&&u.indexOf("blob:")!==0)ee.locateFile=Q=>new URL(Q,u).href;else if(E){let Q=Tr();Q&&(ee.locateFile=he=>Q+he)}d(ee).then(Q=>{Tt=!1,it=!0,or=Q,V(),E&&URL.revokeObjectURL(E)},Q=>{Tt=!1,Dt=!0,Z(Q)})})),await Promise.race(B),z)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Ms=()=>{if(it&&or)return or;throw new Error("WebAssembly is not initialized yet.")}}),Is,Pr,ts,_n=g(()=>{ar(),Is=(e,t)=>{let s=Ms(),n=s.lengthBytesUTF8(e)+1,i=s._malloc(n);return s.stringToUTF8(e,i,n),t.push(i),i},Pr=(e,t,s,n)=>{if(typeof e=="object"&&e!==null){if(s.has(e))throw new Error("Circular reference in options");s.add(e)}Object.entries(e).forEach(([i,a])=>{let o=t?t+i:i;if(typeof a=="object")Pr(a,o+".",s,n);else if(typeof a=="string"||typeof a=="number")n(o,a.toString());else if(typeof a=="boolean")n(o,a?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof a}`)})},ts=e=>{let t=Ms(),s=t.stackSave();try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetLastError(i,i+n);let a=Number(t.getValue(i,n===4?"i32":"i64")),o=t.getValue(i+n,"*"),u=o?t.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${a}, ERROR_MESSAGE: ${u}`)}finally{t.stackRestore(s)}}}),Ur,si=g(()=>{ar(),_n(),Ur=e=>{let t=Ms(),s=0,n=[],i=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if((e==null?void 0:e.logVerbosityLevel)===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(i.terminate=!1);let a=0;return(e==null?void 0:e.tag)!==void 0&&(a=Is(e.tag,n)),s=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),s===0&&ts("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&Pr(e.extra,"",new WeakSet,(o,u)=>{let p=Is(o,n),h=Is(u,n);t._OrtAddRunConfigEntry(s,p,h)!==0&&ts(`Can't set a run config entry: ${o} - ${u}.`)}),[s,n]}catch(a){throw s!==0&&t._OrtReleaseRunOptions(s),n.forEach(o=>t._free(o)),a}}}),$n,An,In,Vr,On,ri=g(()=>{ar(),_n(),$n=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},An=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},In=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(s=>(typeof s=="string"?s:s.name)==="webgpu")&&(e.enableMemPattern=!1)},Vr=(e,t,s)=>{for(let n of t){let i=typeof n=="string"?n:n.name;switch(i){case"webnn":if(i="WEBNN",typeof n!="string"){let o=n==null?void 0:n.deviceType;if(o){let u=Is("deviceType",s),p=Is(o,s);Ms()._OrtAddSessionConfigEntry(e,u,p)!==0&&ts(`Can't set a session config entry: 'deviceType' - ${o}.`)}}break;case"webgpu":if(i="JS",typeof n!="string"){let o=n;if(o!=null&&o.preferredLayout){if(o.preferredLayout!=="NCHW"&&o.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${o.preferredLayout}`);let u=Is("preferredLayout",s),p=Is(o.preferredLayout,s);Ms()._OrtAddSessionConfigEntry(e,u,p)!==0&&ts(`Can't set a session config entry: 'preferredLayout' - ${o.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let a=Is(i,s);Ms()._OrtAppendExecutionProvider(e,a)!==0&&ts(`Can't append execution provider: ${i}.`)}},On=e=>{let t=Ms(),s=0,n=[],i=e||{};In(i);try{let a=$n(i.graphOptimizationLevel??"all"),o=An(i.executionMode??"sequential"),u=typeof i.logId=="string"?Is(i.logId,n):0,p=i.logSeverityLevel??2;if(!Number.isInteger(p)||p<0||p>4)throw new Error(`log serverity level is not valid: ${p}`);let h=i.logVerbosityLevel??0;if(!Number.isInteger(h)||h<0||h>4)throw new Error(`log verbosity level is not valid: ${h}`);let k=typeof i.optimizedModelFilePath=="string"?Is(i.optimizedModelFilePath,n):0;if(s=t._OrtCreateSessionOptions(a,!!i.enableCpuMemArena,!!i.enableMemPattern,o,!!i.enableProfiling,0,u,p,h,k),s===0&&ts("Can't create session options."),i.executionProviders&&Vr(s,i.executionProviders,n),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let E=Is("enableGraphCapture",n),d=Is(i.enableGraphCapture.toString(),n);t._OrtAddSessionConfigEntry(s,E,d)!==0&&ts(`Can't set a session config entry: 'enableGraphCapture' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[E,d]of Object.entries(i.freeDimensionOverrides)){if(typeof E!="string")throw new Error(`free dimension override name must be a string: ${E}`);if(typeof d!="number"||!Number.isInteger(d)||d<0)throw new Error(`free dimension override value must be a non-negative integer: ${d}`);let z=Is(E,n);t._OrtAddFreeDimensionOverride(s,z,d)!==0&&ts(`Can't set a free dimension override: ${E} - ${d}.`)}return i.extra!==void 0&&Pr(i.extra,"",new WeakSet,(E,d)=>{let z=Is(E,n),B=Is(d,n);t._OrtAddSessionConfigEntry(s,z,B)!==0&&ts(`Can't set a session config entry: ${E} - ${d}.`)}),[s,n]}catch(a){throw s!==0&&t._OrtReleaseSessionOptions(s)!==0&&ts("Can't release session options."),n.forEach(o=>t._free(o)),a}}}),Wr,_r,lr,gn,tn,wn,yn,Mn,zt=g(()=>{Wr=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},_r=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},lr=(e,t)=>{let s=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((i,a)=>i*a,1);return s>0?Math.ceil(n*s):void 0},gn=e=>{switch(e){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},tn=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},wn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",yn=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Mn=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),bn,Fn=g(()=>{Je(),bn=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let i=t.body.getReader(),a;try{a=new ArrayBuffer(n)}catch(u){if(u instanceof RangeError){let p=Math.ceil(n/65536);a=new WebAssembly.Memory({initial:p,maximum:p}).buffer}else throw u}let o=0;for(;;){let{done:u,value:p}=await i.read();if(u)break;let h=p.byteLength;new Uint8Array(a,o,h).set(p),o+=h}return new Uint8Array(a,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Dn,Ln,Gr,zn,vn,Bn,as,Pe=g(()=>{zt(),Dn=["V","I","W","E","F"],Ln=(e,t)=>{console.log(`[${Dn[e]},${new Date().toISOString()}]${t}`)},vn=(e,t)=>{Gr=e,zn=t},Bn=(e,t)=>{let s=tn(e),n=tn(Gr);s>=n&&Ln(s,typeof t=="function"?t():t)},as=(...e)=>{zn&&Bn(...e)}}),C,q=g(()=>{zt(),C=(e,t)=>new(gn(t))(e)}),ue=g(()=>{}),be,Se,Qe,pt,gt,ft,xt,Kt,hs,us=g(()=>{Pe(),ue(),be=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]]),Se=[],Qe=e=>Math.ceil(Number(e)/16)*16,pt=e=>{for(let t=0;tgt++,xt=async(e,t,s,n)=>{let i=Qe(s),a=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let o=e.getCommandEncoder();e.endComputePass(),o.copyBufferToBuffer(t,0,a,0,i),e.flush(),await a.mapAsync(GPUMapMode.READ);let u=a.getMappedRange();if(n){let p=n();return p.set(new Uint8Array(u,0,s)),p}else return new Uint8Array(u.slice(0,s))}finally{a.destroy()}},Kt=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of be)Se.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let s=t.buffer,n=t.byteOffset,i=t.byteLength,a=Qe(i),o=this.storageCache.get(e);if(!o)throw new Error("gpu data for uploading does not exist");if(Number(o.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${o.originalSize}, data size=${i}`);let u=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),p=u.getMappedRange();new Uint8Array(p).set(new Uint8Array(s,n,i)),u.unmap();let h=this.backend.device.createCommandEncoder();h.copyBufferToBuffer(u,0,o.gpuData.buffer,0,a),this.backend.device.queue.submit([h.finish()]),u.destroy(),as("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let s=this.storageCache.get(e);if(!s)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(t);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(s.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let i=Qe(s.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(s.gpuData.buffer,0,n.gpuData.buffer,0,i)}registerExternalBuffer(e,t,s){let n;if(s){if(n=s[0],e===s[1])return as("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, buffer is the same, skip.`),n;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!`)}else n=ft();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),as("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),as("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=pt(e),n,i=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let u=(i?this.freeBuffers:this.freeUniformBuffers).get(s);u?u.length>0?n=u.pop():n=this.backend.device.createBuffer({size:s,usage:t}):n=this.backend.device.createBuffer({size:s,usage:t})}else n=this.backend.device.createBuffer({size:s,usage:t});let o={id:ft(),type:0,buffer:n};return this.storageCache.set(o.id,{gpuData:o,originalSize:Number(e)}),as("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${o.id}`),o}get(e){var t;return(t=this.storageCache.get(e))==null?void 0:t.gpuData}release(e){let t=typeof e=="bigint"?Number(e):e,s=this.storageCache.get(t);if(!s){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return as("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${s.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(s.gpuData.buffer),s.originalSize}async download(e,t){let s=this.storageCache.get(Number(e));if(!s)throw new Error("data does not exist");await xt(this.backend,s.gpuData.buffer,s.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=be.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let s=this.freeBuffers.get(e.size)||[];t===void 0||s.length>=t?e.destroy():s.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let s=this.freeUniformBuffers.get(e.size)||[];t===void 0||s.length>=t?e.destroy():s.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(s=>{s.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(as("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(s=>{s.gpuData.buffer.destroy()}),this.storageCache=new Map)}},hs=(...e)=>new Kt(...e)}),Fs,Bt,rs=g(()=>{Fs=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},Bt=e=>new Fs(e)}),rr,Ws,Le,Js,Fr,Ss,qs,Ot=g(()=>{rr=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Ws=class{static calcShape(e,t,s=!1){let n=e.length,i=t.length;if(n===0)return t;if(i===0)return e;let a=Math.max(e.length,t.length),o=new Array(a);if(s){if(n<2||i<2)return;let u=rr.calcMatMulShape([e[n-2],e[n-1]],[t[i-2],t[i-1]]);if(u===void 0)return;[o[a-2],o[a-1]]=u}for(let u=s?3:1;u<=a;u++){let p=n-u<0?1:e[n-u],h=i-u<0?1:t[i-u];if(p!==h&&p>1&&h>1)return;let k=Math.max(p,h);if(p&&h)o[a-u]=Math.max(p,h);else{if(k>1)return;o[a-u]=0}}return o}static isValidBroadcast(e,t){let s=e.length,n=t.length;if(s>n)return!1;for(let i=1;i<=s;i++)if(e[s-i]!==1&&e[s-i]!==t[n-i])return!1;return!0}},Le=class Rp{static size(t){return Rp.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,s=4){let n=t.length;if(n===0)return[];let i=new Array(n),a=n-1;for(;a>=0;){if(t[a]%s===0){i[a]=t[a]/s;break}if(s%t[a]!==0)throw new Error("cannot convert shape");i[a]=1,s/=t[a],a--}for(a--;a>=0;a--)i[a]=t[a];return i}static sizeFromDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Rp.getSizeFromDimensionRange(t,s,t.length)}static sizeToDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Rp.getSizeFromDimensionRange(t,0,s)}static getSizeFromDimensionRange(t,s,n){let i=1;for(let a=s;a=0;--i)n[i]=n[i+1]*t[i+1];return n}static normalizeAxis(t,s){if(t<-s&&t>=s)throw new Error("unsupported axis for this operation.");return t<0?t+s:t}static normalizeAxes(t,s){return t.map(n=>this.normalizeAxis(n,s??t.length))}static sortBasedOnPerm(t,s){return s?s.map(n=>t[n]):t.slice().reverse()}static padShape(t,s){let n=t.length;return t.map((i,a)=>i+s[a]+s[a+n])}static areEqual(t,s){return t.length!==s.length?!1:t.every((n,i)=>n===s[i])}},Js=class zc{static adjustPoolAttributes(t,s,n,i,a,o){if(!t&&n.length!==s.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let u=0;u=n.length?n.push(s[u+2]):n[u]=s[u+2];for(let u=0;u=n[u]||o[u+n.length]>=n[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,s,n,i,a,o,u){if(u){if(a.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(s.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(i.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let p=0;p{zt(),Ot(),nr=64,gr=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==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: ${e}`)}},ms=(e,t=1)=>{let s=gr(e,t);return typeof s=="string"?s:s[0]},$s=(e,t=1)=>{let s=gr(e,t);return typeof s=="string"?s:s[1]},yt=(...e)=>{let t=[];return e.forEach(s=>{s.length!==0&&t.push({type:12,data:s},{type:12,data:Le.computeStrides(s)})}),t},qt=e=>e%4===0?4:e%2===0?2:1,Ls=(e="f32",t,s="0")=>!t||t===1?`${e}(${s})`:`vec${t}<${e}>(${s})`,As=(e,t,s)=>e==="f32"?s:t===1?`f32(${s})`:`vec${t}(${s})`,Gs=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,$t=(e,t,s,n)=>e.startsWith("uniforms.")&&s>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:s>1?`${e}[${t}]`:e,sn=(e,t,s,n,i)=>{let a=typeof s=="number",o=a?s:s.length,u=[...new Array(o).keys()],p=o<2?"u32":o<=4?`vec${o}`:`array`,h=gr(t,i),k=typeof h=="string"?h:h[1],E=typeof h=="string"?h:h[0],d={indices:p,value:k,storage:E,tensor:t},z=ot=>typeof ot=="string"?ot:`${ot}u`,B={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},V=a?"uniforms.":"",Z=`${V}${e}_shape`,ee=`${V}${e}_strides`,Q="";for(let ot=0;ot ${d.indices} { + var indices: ${d.indices}; + var current = offset; + ${Q} + return indices; + }`,pe=ot=>(B.offsetToIndices=!0,o<2?ot:`o2i_${e}(${ot})`),Me=[];if(o>=2)for(let ot=o-1;ot>=0;ot--)Me.push(`${$t(ee,ot,o)} * (indices[${ot}])`);let Fe=o<2?"":` + fn i2o_${e}(indices: ${d.indices}) -> u32 { + return ${Me.join("+")}; + }`,De=ot=>(B.indicesToOffset=!0,o<2?ot:`i2o_${e}(${ot})`),Ye=(...ot)=>o===0?"0u":`${d.indices}(${ot.map(z).join(",")})`,at=(ot,Et)=>o<2?`${ot}`:`${$t(ot,Et,o)}`,Pt=(ot,Et,cs)=>o<2?`${ot}=${cs};`:`${$t(ot,Et,o)}=${cs};`,Xt={},Zt=(ot,Et)=>{B.broadcastedIndicesToOffset=!0;let cs=`${Et.name}broadcastedIndicesTo${e}Offset`;if(cs in Xt)return`${cs}(${ot})`;let Ns=[];for(let xr=o-1;xr>=0;xr--){let er=Et.indicesGet("outputIndices",xr+Et.rank-o);Ns.push(`${at(ee,xr)} * (${er} % ${at(Z,xr)})`)}return Xt[cs]=`fn ${cs}(outputIndices: ${Et.type.indices}) -> u32 { + return ${Ns.length>0?Ns.join("+"):"0u"}; + }`,`${cs}(${ot})`},bt=(ot,Et)=>(()=>{if(d.storage===d.value)return`${e}[${ot}]=${Et};`;if(d.storage==="vec2"&&d.value==="i32")return`${e}[${ot}]=vec2(u32(${Et}), select(0u, 0xFFFFFFFFu, ${Et} < 0));`;if(d.storage==="vec2"&&d.value==="u32")return`${e}[${ot}]=vec2(u32(${Et}), 0u);`;if(d.storage==="u32"&&d.value==="vec4")return`${e}[${ot}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${Et}));`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),ss=ot=>(()=>{if(d.storage===d.value)return`${e}[${ot}]`;if(d.storage==="vec2"&&d.value==="i32")return`i32(${e}[${ot}].x)`;if(d.storage==="vec2"&&d.value==="u32")return`u32(${e}[${ot}].x)`;if(d.storage==="u32"&&d.value==="vec4")return`vec4(bool(${e}[${ot}] & 0xFFu), bool(${e}[${ot}] & 0xFF00u), bool(${e}[${ot}] & 0xFF0000u), bool(${e}[${ot}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),St=o<2?"":` + fn get_${e}ByIndices(indices: ${d.indices}) -> ${k} { + return ${ss(`i2o_${e}(indices)`)}; + }`,Ft=o<2?"":(()=>{let ot=u.map(cs=>`d${cs}: u32`).join(", "),Et=u.map(cs=>`d${cs}`).join(", ");return` + fn get_${e}(${ot}) -> ${k} { + return get_${e}ByIndices(${Ye(Et)}); + }`})(),bs=(...ot)=>{if(ot.length!==o)throw new Error(`indices length must be ${o}`);let Et=ot.map(z).join(",");return o===0?ss("0u"):o===1?ss(Et[0]):(B.get=!0,B.getByIndices=!0,B.indicesToOffset=!0,`get_${e}(${Et})`)},Ht=ot=>o<2?ss(ot):(B.getByIndices=!0,B.indicesToOffset=!0,`get_${e}ByIndices(${ot})`),Rt=o<2?"":` + fn set_${e}ByIndices(indices: ${d.indices}, value: ${k}) { + ${bt(`i2o_${e}(indices)`,"value")} + }`,_s=o<2?"":(()=>{let ot=u.map(cs=>`d${cs}: u32`).join(", "),Et=u.map(cs=>`d${cs}`).join(", ");return` + fn set_${e}(${ot}, value: ${k}) { + set_${e}ByIndices(${Ye(Et)}, value); + }`})();return{impl:()=>{let ot=[],Et=!1;return B.offsetToIndices&&(ot.push(he),Et=!0),B.indicesToOffset&&(ot.push(Fe),Et=!0),B.broadcastedIndicesToOffset&&(Object.values(Xt).forEach(cs=>ot.push(cs)),Et=!0),B.set&&(ot.push(_s),Et=!0),B.setByIndices&&(ot.push(Rt),Et=!0),B.get&&(ot.push(Ft),Et=!0),B.getByIndices&&(ot.push(St),Et=!0),!a&&Et&&ot.unshift(`const ${Z} = ${d.indices}(${s.join(",")});`,`const ${ee} = ${d.indices}(${Le.computeStrides(s).join(",")});`),ot.join(` +`)},type:d,offsetToIndices:pe,indicesToOffset:De,broadcastedIndicesToOffset:Zt,indices:Ye,indicesGet:at,indicesSet:Pt,set:(...ot)=>{if(ot.length!==o+1)throw new Error(`indices length must be ${o}`);let Et=ot[o];if(typeof Et!="string")throw new Error("value must be string");let cs=ot.slice(0,o).map(z).join(",");return o===0?bt("0u",Et):o===1?bt(cs[0],Et):(B.set=!0,B.setByIndices=!0,B.indicesToOffset=!0,`set_${e}(${cs}, ${Et})`)},setByOffset:bt,setByIndices:(ot,Et)=>o<2?bt(ot,Et):(B.setByIndices=!0,B.indicesToOffset=!0,`set_${e}ByIndices(${ot}, ${Et});`),get:bs,getByOffset:ss,getByIndices:Ht,usage:n,name:e,strides:ee,shape:Z,rank:o}},qe=(e,t,s,n=1)=>sn(e,t,s,"input",n),It=(e,t,s,n=1)=>sn(e,t,s,"output",n),Oa=(e,t,s)=>sn(e,t,s,"atomicOutput",1),zi=(e,t,s,n=1)=>sn(e,t,s,"internal",n),Fa=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=nr){let t=typeof e=="number"?e:e[0],s=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||s>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*s*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=i?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @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`,o=i?`let global_idx = global_id.x; + let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x; + let global_idx = workgroup_index * ${t*s*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${s}, ${n}) + fn main(${a}) { + ${o} + `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let s=e.usage==="input"?"read":"read_write",n=e.usage==="atomicOutput"?"atomic":e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${n}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,this.variableIndex++)).join(` +`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,s=1){return this.uniforms.push({name:e,type:t,length:s}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:s,length:n}of this.uniforms)if(n&&n>4)s==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let i=n==null||n===1?s:`vec${n}<${s}>`;e.push(`${t}:${i}`)}return` + struct Uniforms { ${e.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` +`)+this.internalVariables.map(e=>e.impl()).join(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},Da=(e,t)=>new Fa(e,t)}),La,Bi,Ri,za,Ba,Ni,hr,Ra,ji,Kr=g(()=>{zt(),Ot(),rs(),Yt(),La=(e,t)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(t.length!==0&&t.length!==e[0].dims.length)throw new Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`)},Bi=(e,t)=>t.length!==0?t:[...new Array(e).keys()].reverse(),Ri=(e,t)=>Le.sortBasedOnPerm(e,Bi(e.length,t)),za=(e,t,s,n)=>{let i=`fn perm(i: ${n.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`;for(let a=0;a{let s=[],n=[];for(let i=0;i{let s=0;for(let n=0;n{let s=e.dataType,n=e.dims.length,i=Bi(n,t),a=Ri(e.dims,i),o=e.dims,u=a,p=n<2||Ni(i,e.dims),h;if(p)return h=B=>{let V=qe("input",s,o,4),Z=It("output",s,u,4);return` + ${B.registerUniform("output_size","u32").declareVariables(V,Z)} + ${B.mainStart()} + ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let B=Le.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(B/64/4)},programUniforms:[{type:12,data:Math.ceil(B/4)}]}},getShaderSource:h};let{newShape:k,newPerm:E}=Ba(e.dims,i),d=Le.areEqual(E,[2,3,1]),z=Le.areEqual(E,[3,1,2]);if(k.length===2||d||z){o=d?[k[0],k[1]*k[2]]:z?[k[0]*k[1],k[2]]:k,u=[o[1],o[0]];let B=16;return h=V=>{let Z=qe("a",s,o.length),ee=It("output",s,u.length);return` + ${V.registerUniform("output_size","u32").declareVariables(Z,ee)} + var tile : array, ${B}>; + ${V.mainStart([B,B,1])} + let stride = (uniforms.output_shape[1] - 1) / ${B} + 1; + let workgroup_id_x = workgroup_index % stride; + let workgroup_id_y = workgroup_index / stride; + let input_col = workgroup_id_y * ${B}u + local_id.x; + let input_row = workgroup_id_x * ${B}u + local_id.y; + if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { + tile[local_id.y][local_id.x] = ${Z.getByIndices(`${Z.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + let output_col = workgroup_id_x * ${B}u + local_id.x; + let output_row = workgroup_id_y * ${B}u + local_id.y; + if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { + ${ee.setByIndices(`${ee.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let V=Le.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u[1]/B),y:Math.ceil(u[0]/B)},programUniforms:[{type:12,data:V},...yt(o,u)]}},getShaderSource:h}}return h=B=>{let V=qe("a",s,o.length),Z=It("output",s,u.length);return` + ${B.registerUniform("output_size","u32").declareVariables(V,Z)} + + ${za(i,n,V,Z)} + + ${B.mainStart()} + ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${Z.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${Z.setByOffset("global_idx",V.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let B=Le.size(a);return{outputs:[{dims:a,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(B/64)},programUniforms:[{type:12,data:B},...yt(o,u)]}},getShaderSource:h}},Ra=(e,t)=>{La(e.inputs,t.perm),e.compute(hr(e.inputs[0],t.perm))},ji=e=>Bt({perm:e.perm})}),ni,Na,ja,Ua,Va,Wa,Ga,Ka,Ui,Ha,mr,rn,qa,Rc,Qa,Nc,Xa,Vi,Ya,Ja,Za,jc=g(()=>{zt(),Ot(),Yt(),ai(),Kr(),ni={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"},Na={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"},ja={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Ua={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Va=(e,t)=>{let s=[];for(let n=t-e;n{let s=[],n=e.length;for(let a=0;ae[a]);return[s,i]},Ga=(e,t)=>{let s=e.length+t.length,n=[],i=0;for(let a=0;a{for(let s=0;s{let s=[];if(!Ka(e,t)){for(let n=0;ns.push(n))}return s},Ha=(e,t,s,n,i,a,o)=>{let u=s[0].dims,p=Le.size(a),h=Le.size(o),k=qe("_A",s[0].dataType,u),E=It("output",i,a),d=64;p===1&&(d=256);let z=` + var aBestValues : array; + `,B=V=>` + ${V.registerUniform("reduceSize","u32").declareVariables(k,E)} + ${z} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${V.mainStart(d)} + + let outputIndex = global_idx / ${d}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${ja[n]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${d}) { + let candidate = f32(${k.getByOffset("offset + k")}); + bestValue = ${ni[n]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${d}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 = ${Na[n]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${E.setByOffset("outputIndex",`${n==="mean"?`${E.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${E.type.storage}(${Ua[n]})`}`)}; + } + }`;return{name:e,shaderCache:{hint:`${t};${d}`,inputDependencies:["type"]},getShaderSource:B,getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:p},programUniforms:[{type:12,data:h}]})}},mr=(e,t,s,n)=>{let i=e.inputs.length===1?s:Wi(e.inputs,s),a=i.axes;a.length===0&&!i.noopWithEmptyAxes&&(a=e.inputs[0].dims.map((z,B)=>B));let o=Le.normalizeAxes(a,e.inputs[0].dims.length),u=o,p=e.inputs[0],h=Ui(u,e.inputs[0].dims.length);h.length>0&&(p=e.compute(hr(e.inputs[0],h),{inputs:[0],outputs:[-1]})[0],u=Va(u.length,p.dims.length));let[k,E]=Wa(p.dims,u),d=k;i.keepDims&&(d=Ga(k,o)),e.compute(Ha(t,i.cacheKey,[p],n,e.inputs[0].dataType,d,E),{inputs:[p]})},rn=(e,t)=>{mr(e,"ReduceMeanShared",t,"mean")},qa=(e,t)=>{mr(e,"ReduceL1Shared",t,"l1")},Rc=(e,t)=>{mr(e,"ReduceL2Shared",t,"l2")},Qa=(e,t)=>{mr(e,"ReduceLogSumExpShared",t,"logSumExp")},Nc=(e,t)=>{mr(e,"ReduceMaxShared",t,"max")},Xa=(e,t)=>{mr(e,"ReduceMinShared",t,"min")},Vi=(e,t)=>{mr(e,"ReduceProdShared",t,"prod")},Ya=(e,t)=>{mr(e,"ReduceSumShared",t,"sum")},Ja=(e,t)=>{mr(e,"ReduceSumSquareShared",t,"sumSquare")},Za=(e,t)=>{mr(e,"ReduceLogSumShared",t,"logSum")}}),wr,ii,oi,Wi,yr,Gi,el,tl,Ki,sl,rl,Hi,nl,il,qi,Mr,ol,Qi,al,ll,Xi,ul,dl,Yi,cl,pl,ai=g(()=>{zt(),Ot(),rs(),Yt(),jc(),wr=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},ii=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],oi=(e,t,s,n,i,a,o=!1,u=!1)=>{let p=[],h=s[0].dims,k=h.length,E=Le.normalizeAxes(i,k),d=!u&&E.length===0;h.forEach((V,Z)=>{d||E.indexOf(Z)>=0?o&&p.push(1):p.push(V)});let z=p.length,B=Le.size(p);return{name:e,shaderCache:t,getShaderSource:V=>{let Z=[],ee=qe("_A",s[0].dataType,k),Q=It("output",a,z),he=n(ee,Q,E),pe=he[2];for(let Me=0,Fe=0;Me=0?(o&&Fe++,pe=`for(var j${Me}: u32 = 0; j${Me} < ${h[Me]}; j${Me}++) { + ${he[2].includes("last_index")?`let last_index = j${Me};`:""} + ${ee.indicesSet("input_indices",Me,`j${Me}`)} + ${pe} + }`):(Z.push(`${ee.indicesSet("input_indices",Me,Q.indicesGet("output_indices",Fe))};`),Fe++);return` + + ${V.registerUniform("output_size","u32").declareVariables(ee,Q)} + + ${V.mainStart()} + ${V.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${ee.type.indices}; + let output_indices = ${Q.offsetToIndices("global_idx")}; + + ${Z.join(` +`)} + ${he[0]} // init ops for reduce max/min + ${he[1]} + ${pe} + ${he[3]} + ${he.length===4?Q.setByOffset("global_idx","value"):he.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:p,dataType:a}],dispatchGroup:{x:Math.ceil(B/64)},programUniforms:[{type:12,data:B},...yt(h,p)]})}},Wi=(e,t)=>{let s=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>s.push(Number(n))),Bt({axes:s,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},yr=(e,t,s,n)=>{let i=e.inputs,a=i.length===1?s:Wi(i,s);e.compute(oi(t,{hint:a.cacheKey,inputDependencies:["rank"]},[i[0]],a.noopWithEmptyAxes&&a.axes.length===0?ii:n,a.axes,i[0].dataType,a.keepDims,a.noopWithEmptyAxes),{inputs:[0]})},Gi=(e,t)=>{wr(e.inputs),yr(e,"ReduceLogSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},el=(e,t)=>{wr(e.inputs),yr(e,"ReduceL1",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},tl=(e,t)=>{wr(e.inputs),yr(e,"ReduceL2",t,(s,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Ki=(e,t)=>{wr(e.inputs),yr(e,"ReduceLogSumExp",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},sl=(e,t)=>{wr(e.inputs),yr(e,"ReduceMax",t,(s,n,i)=>{let a=[];for(let o=0;o=0||i.length===0)&&a.push(s.indicesSet("input_indices",o,0));return[`${a.join(` +`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = max(value, ${s.getByIndices("input_indices")});`,""]})},rl=(e,t)=>{wr(e.inputs),yr(e,"ReduceMean",t,(s,n,i)=>{let a=1;for(let o=0;o=0||i.length===0)&&(a*=e.inputs[0].dims[o]);return["var sum = f32(0);","",`sum += f32(${s.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${a});`]})},Hi=(e,t)=>{wr(e.inputs),yr(e,"ReduceMin",t,(s,n,i)=>{let a=[];for(let o=0;o=0||i.length===0)&&a.push(`input_indices[${o}] = 0;`);return[`${a.join(` +`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = min(value, ${s.getByIndices("input_indices")});`,""]})},nl=(e,t)=>{wr(e.inputs),yr(e,"ReduceProd",t,(s,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},il=(e,t)=>{wr(e.inputs),yr(e,"ReduceSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},qi=(e,t)=>{wr(e.inputs),yr(e,"ReduceSumSquare",t,(s,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += t * t;`,""])},Mr=(e,t,s)=>{if(t.length===0)return s;let n=1,i=1;for(let a=0;a1024},ol=(e,t)=>{Mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?rl(e,t):rn(e,t)},Qi=(e,t)=>{Mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?el(e,t):qa(e,t)},al=(e,t)=>{Mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?tl(e,t):Rc(e,t)},ll=(e,t)=>{Mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ki(e,t):Qa(e,t)},Xi=(e,t)=>{Mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?sl(e,t):Nc(e,t)},ul=(e,t)=>{Mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Hi(e,t):Xa(e,t)},dl=(e,t)=>{Mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?nl(e,t):Vi(e,t)},Yi=(e,t)=>{Mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?il(e,t):Ya(e,t)},cl=(e,t)=>{Mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?qi(e,t):Ja(e,t)},pl=(e,t)=>{Mr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Gi(e,t):Za(e,t)}}),Ji,hl,Zi,eo,Uc=g(()=>{zt(),rs(),ai(),Ji=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},hl=(e,t)=>{Ji(e.inputs);let s=(n,i,a)=>{let o=[];for(let u=0;u=0||a.length===0)&&o.push(`input_indices[${u}] = 0;`);return[`${o.join(` +`)}`,`var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",i.setByOffset("global_idx","best_index")]};e.compute(oi("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},Zi=(e,t)=>{Ji(e.inputs);let s=(n,i,a)=>{let o=[];for(let u=0;u=0||a.length===0)&&o.push(`input_indices[${u}] = 0;`);return[`${o.join(` +`)}`,`var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",i.setByOffset("global_idx","best_index")]};e.compute(oi("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},eo=e=>Bt(e)}),to,li,ml,so,fl,Rn,ro,_l,no=g(()=>{zt(),Ot(),ue(),Yt(),to=(e,t)=>{let s=e[0],n=e[1],i=e[2],a=e[3],o=e[4],u=e[5];if(o&&u)throw new Error("Attention cannot have both past and attention_bias");if(s.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let p=s.dims[0],h=s.dims[1],k=s.dims[2];if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==k)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let E=i.dims[0]/3,d=E,z=d;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let he of t.qkvHiddenSizes)if(he%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");E=t.qkvHiddenSizes[0],d=t.qkvHiddenSizes[1],z=t.qkvHiddenSizes[2]}let B=h;if(E!==d)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==E+d+z)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let V=0;if(o){if(d!==z)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(o.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(o.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(o.dims[1]!==p)throw new Error('Input "past" second dimension must be batch_size');if(o.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(o.dims[4]!==d/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(V=o.dims[3])}let Z=B+V,ee=-1,Q=0;if(a)throw new Error("Mask not supported");if(o)throw new Error("past is not supported");if(u){if(u.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(u.dims[0]!==p||u.dims[1]!==t.numHeads||u.dims[2]!==h||u.dims[3]!==Z)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:h,pastSequenceLength:V,kvSequenceLength:B,totalSequenceLength:Z,maxSequenceLength:ee,inputHiddenSize:k,hiddenSize:E,vHiddenSize:z,headSize:Math.floor(E/t.numHeads),vHeadSize:Math.floor(z/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:Q,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},li=(e,t,s)=>t&&e?` + let total_sequence_length_input = u32(${t.getByOffset("0")}); + let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); + let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; + let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; + total_sequence_length = u32(${e==null?void 0:e.getByOffset("batchIdx")}) + 1; + var past_sequence_length: u32 = 0; + if (is_first_prompt == false) { + past_sequence_length = total_sequence_length - sequence_length; + } + `:` + ${s?"let past_sequence_length = uniforms.past_sequence_length":""}; + let present_sequence_length = total_sequence_length; + `,ml=(e,t,s,n,i,a,o,u)=>{let p=qt(o?1:a),h=64,k=a/p;k{let Q=It("x",e.dataType,e.dims,p),he=[Q],pe=o?qe("seq_lens",o.dataType,o.dims):void 0;pe&&he.push(pe);let Me=u?qe("total_sequence_length_input",u.dataType,u.dims):void 0;Me&&he.push(Me);let Fe=$s(e.dataType),De=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${ee.registerUniforms(De).declareVariables(...he)} + ${ee.mainStart([h,1,1])} + let batchIdx = workgroup_id.z / uniforms.num_heads; + let headIdx = workgroup_id.z % uniforms.num_heads; + let sequence_length = uniforms.sequence_length; + var total_sequence_length = uniforms.total_sequence_length; + ${li(pe,Me,!1)} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${h}) * uniforms.total_sequence_length + local_offset; + let seq_causal_length = ${o?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; + var thread_max_vector = ${B}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + thread_max_vector = max(${B}(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 < ${h}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${B}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + sum_vector += exp(${B}(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 < ${h}; i++) { + sum += thread_sum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + x[offset + i] = ${Q.type.value}(${Fe}(1.0) / ${Fe}(seq_causal_length)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + var f32input = ${B}(x[offset + i]); + x[offset + i] = ${Q.type.value}(exp(f32input - max_value) / sum); + } + } + ${o?` + for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { + x[offset + total_seq_id] = ${Q.type.value}(${Fe}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${h};${z};${p}`,inputDependencies:V},getShaderSource:Z,getRunData:()=>({outputs:[],dispatchGroup:{x:Math.ceil(a/h),y:i,z:t*s},programUniforms:d})}},so=(e,t,s,n,i,a,o,u,p)=>{let h=o+a.kvSequenceLength,k=[a.batchSize,a.numHeads,a.sequenceLength,h],E=e>1&&n,d=a.kvNumHeads?a.kvNumHeads:a.numHeads,z=E?[a.batchSize,d,h,a.headSize]:void 0,B=a.nReps?a.nReps:1,V=a.scale===0?1/Math.sqrt(a.headSize):a.scale,Z=qt(a.headSize),ee=a.headSize/Z,Q=12,he={x:Math.ceil(h/Q),y:Math.ceil(a.sequenceLength/Q),z:a.batchSize*a.numHeads},pe=[{type:12,data:a.sequenceLength},{type:12,data:ee},{type:12,data:h},{type:12,data:a.numHeads},{type:12,data:a.headSize},{type:1,data:V},{type:12,data:o},{type:12,data:a.kvSequenceLength},{type:12,data:B}],Me=E&&n&&Le.size(n.dims)>0,Fe=["type","type"];Me&&Fe.push("type"),i&&Fe.push("type"),u&&Fe.push("type"),p&&Fe.push("type");let De=[{dims:k,dataType:t.dataType,gpuDataType:0}];E&&De.push({dims:z,dataType:t.dataType,gpuDataType:0});let Ye=at=>{let Pt=qe("q",t.dataType,t.dims,Z),Xt=qe("key",s.dataType,s.dims,Z),Zt=[Pt,Xt];if(Me){let Rt=qe("past_key",n.dataType,n.dims,Z);Zt.push(Rt)}i&&Zt.push(qe("attention_bias",i.dataType,i.dims));let bt=u?qe("seq_lens",u.dataType,u.dims):void 0;bt&&Zt.push(bt);let ss=p?qe("total_sequence_length_input",p.dataType,p.dims):void 0;ss&&Zt.push(ss);let St=It("output",t.dataType,k),Ft=[St];E&&Ft.push(It("present_key",t.dataType,z,Z));let bs=$s(1,Z),Ht=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${Q}u; + + var tileQ: array<${Pt.type.storage}, ${Q*Q}>; + var tileK: array<${Pt.type.storage}, ${Q*Q}>; + ${at.registerUniforms(Ht).declareVariables(...Zt,...Ft)} + ${at.mainStart([Q,Q,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + let kvHeadIdx = ${B===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${B===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.N; + ${li(bt,ss,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${Me&&E?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${E?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} + var value = ${bs}(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&&E?` + if (n + local_id.y < past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; + }`:` + if (n + local_id.y < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + }`} + ${E?`if (n + local_id.y < present_sequence_length) { + 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 += ${bs}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { + let headOffset = workgroup_id.z * uniforms.M * uniforms.N; + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(()=>{switch(Z){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: ${Z}`)}})()}; + output[outputIdx] = ${St.type.value} (sum * uniforms.alpha) + ${i?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${Z};${i!==void 0};${n!==void 0};${e}`,inputDependencies:Fe},getRunData:()=>({outputs:De,dispatchGroup:he,programUniforms:pe}),getShaderSource:Ye}},fl=(e,t,s,n,i,a,o=void 0,u=void 0)=>{let p=a+i.kvSequenceLength,h=i.nReps?i.nReps:1,k=i.vHiddenSize*h,E=e>1&&n,d=i.kvNumHeads?i.kvNumHeads:i.numHeads,z=E?[i.batchSize,d,p,i.headSize]:void 0,B=[i.batchSize,i.sequenceLength,k],V=12,Z={x:Math.ceil(i.vHeadSize/V),y:Math.ceil(i.sequenceLength/V),z:i.batchSize*i.numHeads},ee=[{type:12,data:i.sequenceLength},{type:12,data:p},{type:12,data:i.vHeadSize},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:k},{type:12,data:a},{type:12,data:i.kvSequenceLength},{type:12,data:h}],Q=E&&n&&Le.size(n.dims)>0,he=["type","type"];Q&&he.push("type"),o&&he.push("type"),u&&he.push("type");let pe=[{dims:B,dataType:t.dataType,gpuDataType:0}];E&&pe.push({dims:z,dataType:t.dataType,gpuDataType:0});let Me=Fe=>{let De=qe("probs",t.dataType,t.dims),Ye=qe("v",s.dataType,s.dims),at=[De,Ye];Q&&at.push(qe("past_value",n.dataType,n.dims));let Pt=o?qe("seq_lens",o.dataType,o.dims):void 0;o&&at.push(Pt);let Xt=u?qe("total_sequence_length_input",u.dataType,u.dims):void 0;u&&at.push(Xt);let Zt=[It("output",t.dataType,B)];E&&Zt.push(It("present_value",t.dataType,z));let bt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${V}u; + var tileQ: array<${De.type.value}, ${V*V}>; + var tileV: array<${De.type.value}, ${V*V}>; + ${Fe.registerUniforms(bt).declareVariables(...at,...Zt)} + ${Fe.mainStart([V,V,1])} + let headIdx = workgroup_id.z % uniforms.num_heads; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let kvHeadIdx = ${h===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${h===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let m = global_id.y; + let n = global_id.x; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.K; + ${li(Pt,Xt,!0)} + let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch + ${Q&&E?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${E?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} + var value = ${De.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; + ${Q&&E?` + if (w + local_id.y < past_sequence_length) { + tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; + } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; + } + `:` + if (w + local_id.y < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; + }`} + ${E?` + if (w + local_id.y < present_sequence_length) { + present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; + }`:""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + headIdx * uniforms.N + n; + output[outputIdx] = value; + } + }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:he},getRunData:()=>({outputs:pe,dispatchGroup:Z,programUniforms:ee}),getShaderSource:Me}},Rn=(e,t,s,n,i,a,o,u,p,h,k=void 0,E=void 0)=>{let d=Math.min(e.outputCount,1+(o?1:0)+(u?1:0)),z=d>1?h.pastSequenceLength:0,B=z+h.kvSequenceLength,V=p&&Le.size(p.dims)>0?p:void 0,Z=[t,s];d>1&&o&&Le.size(o.dims)>0&&Z.push(o),V&&Z.push(V),k&&Z.push(k),E&&Z.push(E);let ee=e.compute(so(d,t,s,o,V,h,z,k,E),{inputs:Z,outputs:d>1?[-1,1]:[-1]})[0];e.compute(ml(ee,h.batchSize,h.numHeads,z,h.sequenceLength,B,k,E),{inputs:k&&E?[ee,k,E]:[ee],outputs:[]});let Q=[ee,n];d>1&&u&&Le.size(u.dims)>0&&Q.push(u),k&&Q.push(k),E&&Q.push(E),e.compute(fl(d,ee,n,u,h,z,k,E),{inputs:Q,outputs:d>1?[0,2]:[0]})},ro=(e,t)=>{let s=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,i=t.inputHiddenSize,a=t.headSize,o=12,u={x:Math.ceil(t.headSize/o),y:Math.ceil(t.sequenceLength/o),z:t.batchSize*t.numHeads},p=[e.inputs[0],e.inputs[1],e.inputs[2]],h=[{type:12,data:n},{type:12,data:i},{type:12,data:a},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],k=E=>{let d=It("output_q",p[0].dataType,s),z=It("output_k",p[0].dataType,s),B=It("output_v",p[0].dataType,s),V=qe("input",p[0].dataType,p[0].dims),Z=qe("weight",p[1].dataType,p[1].dims),ee=qe("bias",p[2].dataType,p[2].dims),Q=V.type.storage,he=[{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 = ${o}u; + var tileInput: array<${Q}, ${o*o}>; + var tileWeightQ: array<${Q}, ${o*o}>; + var tileWeightK: array<${Q}, ${o*o}>; + var tileWeightV: array<${Q}, ${o*o}>; + ${E.registerUniforms(he).declareVariables(V,Z,ee,d,z,B)} + ${E.mainStart([o,o,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 = ${Q}(0); + var valueK = ${Q}(0); + var valueV = ${Q}(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:s,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:h}),getShaderSource:k},{inputs:p,outputs:[-1,-1,-1]})},_l=(e,t)=>{let s=to(e.inputs,t),[n,i,a]=ro(e,s);return Rn(e,n,i,a,e.inputs[4],void 0,void 0,void 0,e.inputs[5],s)}}),io,gl,wl,oo,Vc=g(()=>{We(),zt(),Ot(),rs(),Yt(),io=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let s=(n,i,a)=>{let o=i.length;if(o!==n.length)throw new Error(`${a}: num dimensions != ${o}`);i.forEach((u,p)=>{if(u!==n[p])throw new Error(`${a}: dim[${p}] do not match`)})};if(e[0].dims.length>1){let n=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);s(e[1].dims,n,"Invalid input scale"),s(e[2].dims,n,"Invalid input B"),s(e[3].dims,n,"Invalid input mean"),s(e[4].dims,n,"Invalid input var")}else s(e[1].dims,[1],"Invalid input scale"),s(e[2].dims,[1],"Invalid input B"),s(e[3].dims,[1],"Invalid input mean"),s(e[4].dims,[1],"Invalid input var")},gl=(e,t)=>{let{epsilon:s,spatial:n,format:i}=t,a=e[0].dims,o=n?qt(a[a.length-1]):1,u=i==="NHWC"&&a.length>1?o:1,p=Le.size(a)/o,h=n,k=h?a.length:a,E=qe("x",e[0].dataType,e[0].dims,o),d=qe("scale",e[1].dataType,e[1].dims,u),z=qe("bias",e[2].dataType,e[2].dims,u),B=qe("inputMean",e[3].dataType,e[3].dims,u),V=qe("inputVar",e[4].dataType,e[4].dims,u),Z=It("y",e[0].dataType,k,o),ee=()=>{let he="";if(n)he=`let cOffset = ${a.length===1?"0u":i==="NHWC"?`outputIndices[${a.length-1}] / ${o}`:"outputIndices[1]"};`;else if(i==="NCHW")he=` + ${Z.indicesSet("outputIndices","0","0")} + let cOffset = ${Z.indicesToOffset("outputIndices")};`;else{he=`var cIndices = ${d.type.indices}(0); + cIndices[0] = outputIndices[${a.length-1}];`;for(let pe=1;pe` + const epsilon = ${s}; + ${he.registerUniform("outputSize","u32").declareVariables(E,d,z,B,V,Z)} + ${he.mainStart()} + ${he.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${Z.offsetToIndices(`global_idx * ${o}`)}; + ${ee()} + let scale = ${d.getByOffset("cOffset")}; + let bias = ${z.getByOffset("cOffset")}; + let inputMean = ${B.getByOffset("cOffset")}; + let inputVar = ${V.getByOffset("cOffset")}; + let x = ${E.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${Z.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${o}`,inputDependencies:h?["rank","type","type","type","type"]:void 0},getShaderSource:Q,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h?[{type:12,data:p},...yt(a)]:[{type:12,data:p}]})}},wl=e=>Bt(e),oo=(e,t)=>{let{inputs:s,outputCount:n}=e,i=wl({...t,outputCount:n});if(O.webgpu.validateInputContent&&io(s,i),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(gl(s,i))}}),yl,ao,Ml,Wc=g(()=>{Ot(),Yt(),yl=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},ao=e=>{let t=e[0].dims,s=e[0].dims[2],n=Le.size(t)/4,i=e[0].dataType,a=qe("input",i,t,4),o=qe("bias",i,[s],4),u=qe("residual",i,t,4),p=It("output",i,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:h=>` + const channels = ${s}u / 4; + ${h.declareVariables(a,o,u,p)} + + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let value = ${a.getByOffset("global_idx")} + + ${o.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; + ${p.setByOffset("global_idx","value")} + }`}},Ml=e=>{yl(e.inputs),e.compute(ao(e.inputs))}}),lo,ds,bl,uo,vl,xl,co,Tl,Pl,po,El,Cl,kl,Sl,ho,$l,Nn,mo,ui,Al,fo,Il,Ol,_o,Fl,Dl,go,Ll,zl,wo,Bl,Rl,yo,Nl,jl,Mo,Ul,di,bo,Vl,Wl,Gl,vo,Kl,Hl,xo=g(()=>{zt(),Ot(),rs(),Yt(),lo=(e,t,s,n,i,a,o)=>{let u=Math.ceil(t/4),p="";typeof i=="string"?p=`${i}(a)`:p=i("a");let h=qe("inputData",s,[u],4),k=It("outputData",n,[u],4),E=[{name:"vec_size",type:"u32"}];return o&&E.push(...o),` + ${e.registerUniforms(E).declareVariables(h,k)} + + ${a??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${h.getByOffset("global_idx")}; + ${k.setByOffset("global_idx",p)} + }`},ds=(e,t,s,n,i,a=e.dataType,o,u)=>{let p=[{type:12,data:Math.ceil(Le.size(e.dims)/4)}];return o&&p.push(...o),{name:t,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:h=>lo(h,Le.size(e.dims),e.dataType,a,s,n,u),getRunData:h=>({outputs:[{dims:e.dims,dataType:a}],dispatchGroup:{x:Math.ceil(Le.size(h[0].dims)/64/4)},programUniforms:p})}},bl=e=>{e.compute(ds(e.inputs[0],"Abs","abs"))},uo=e=>{e.compute(ds(e.inputs[0],"Acos","acos"))},vl=e=>{e.compute(ds(e.inputs[0],"Acosh","acosh"))},xl=e=>{e.compute(ds(e.inputs[0],"Asin","asin"))},co=e=>{e.compute(ds(e.inputs[0],"Asinh","asinh"))},Tl=e=>{e.compute(ds(e.inputs[0],"Atan","atan"))},Pl=e=>{e.compute(ds(e.inputs[0],"Atanh","atanh"))},po=e=>Bt(e),El=(e,t)=>{let s;switch(t.to){case 10:s="vec4";break;case 1:s="vec4";break;case 12:s="vec4";break;case 6:s="vec4";break;case 9:s="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(ds(e.inputs[0],"Cast",s,void 0,t.cacheKey,t.to))},Cl=e=>{let t,s,n=e.length>=2&&e[1].data!==0,i=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,s=i?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,s=i?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return Bt({min:t,max:s})},kl=(e,t)=>{let s=t||Cl(e.inputs),n=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Clip",i=>`clamp(${i}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,s.cacheKey,void 0,[{type:e.inputs[0].dataType,data:s.min},{type:e.inputs[0].dataType,data:s.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},Sl=e=>{e.compute(ds(e.inputs[0],"Ceil","ceil"))},ho=e=>{e.compute(ds(e.inputs[0],"Cos","cos"))},$l=e=>{e.compute(ds(e.inputs[0],"Cosh","cosh"))},Nn=e=>Bt(e),mo=(e,t)=>{let s=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Elu",n=>`elu_vf32(${n})`,` + const elu_alpha_ = ${s}(${t.alpha}); + + fn elu_f32(a: ${s}) -> ${s} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${s}>) -> vec4<${s}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,t.cacheKey))},ui=(e="f32")=>` +const r0: ${e} = 0.3275911; +const r1: ${e} = 0.254829592; +const r2: ${e} = -0.284496736; +const r3: ${e} = 1.421413741; +const r4: ${e} = -1.453152027; +const r5: ${e} = 1.061405429; + +fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> { + 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)); +}`,Al=e=>{let t=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Erf",s=>`erf_vf32(${s})`,ui(t)))},fo=e=>{e.compute(ds(e.inputs[0],"Exp","exp"))},Il=e=>{e.compute(ds(e.inputs[0],"Floor","floor"))},Ol=e=>{let t=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Gelu",s=>`0.5 * ${s} * (1.0 + erf_vf32(${s} * 0.7071067811865475))`,ui(t)))},_o=(e,t)=>{let s=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${s}>(0.0))`,`const leaky_relu_alpha_ = ${s}(${t.alpha});`,t.cacheKey))},Fl=e=>{e.compute(ds(e.inputs[0],"Not",t=>`!${t}`))},Dl=e=>{e.compute(ds(e.inputs[0],"Neg",t=>`-${t}`))},go=e=>{e.compute(ds(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},Ll=e=>{let t=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"Relu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > vec4<${t}>(0.0))`))},zl=e=>{e.compute(ds(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},wo=e=>Bt(e),Bl=(e,t)=>{let s=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"HardSigmoid",n=>`max(vec4<${s}>(0.0), min(vec4<${s}>(1.0), ${t.alpha} * ${n} + vec4<${s}>(${t.beta})))`,void 0,t.cacheKey))},Rl=e=>{e.compute(ds(e.inputs[0],"Sin","sin"))},yo=e=>{e.compute(ds(e.inputs[0],"Sinh","sinh"))},Nl=e=>{e.compute(ds(e.inputs[0],"Sqrt","sqrt"))},jl=e=>{e.compute(ds(e.inputs[0],"Tan","tan"))},Mo=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Ul=e=>{e.compute(ds(e.inputs[0],"Tanh",Mo))},di=(e="f32")=>` +const fast_gelu_a: ${e} = 0.5; +const fast_gelu_b: ${e} = 0.7978845608028654; +const fast_gelu_c: ${e} = 0.035677408136300125; + +fn tanh_v(v: vec4<${e}>) -> vec4<${e}> { + return ${Mo("v")}; +} +`,bo=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Vl=e=>{let t=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"FastGelu",bo,di(t),void 0,e.inputs[0].dataType))},Wl=(e,t)=>{let s=$s(e.inputs[0].dataType);return e.compute(ds(e.inputs[0],"ThresholdedRelu",n=>`select(vec4<${s}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${s}>(${t.alpha});`,t.cacheKey)),0},Gl=e=>{e.compute(ds(e.inputs[0],"Log","log"))},vo=(e,t)=>` +const alpha = vec4<${e}>(${t}); +const one = ${e}(1.0); +const zero = ${e}(0.0); + +fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { + let v = x *alpha; + var x1 : vec4<${e}>; + 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; +} +`,Kl=e=>`quick_gelu_impl(${e})`,Hl=(e,t)=>{let s=$s(e.inputs[0].dataType);e.compute(ds(e.inputs[0],"QuickGelu",Kl,vo(s,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),ql,To,Ql,Gc=g(()=>{Ot(),Yt(),xo(),ql=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},To=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let s=qe("input",e[0].dataType,e[0].dims,4),n=qe("bias",e[0].dataType,[e[0].dims[2]],4),i=It("output",e[0].dataType,t,4),a=Le.size(t)/4,o=ms(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)}}),getShaderSource:u=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${u.declareVariables(s,n,i)} + + ${ui(o)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes(a)} + 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); + + ${i.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Ql=e=>{ql(e.inputs),e.compute(To(e.inputs))}}),Xl,Yl,fr,Jl,Zl,Po,eu,tu,Eo,su,ru,Co,nu,Kc=g(()=>{zt(),Ot(),Yt(),Xl=(e,t,s,n,i,a,o,u,p,h,k,E)=>{let d,z;typeof u=="string"?d=z=(Q,he)=>`${u}((${Q}),(${he}))`:typeof u=="function"?d=z=u:(d=u.scalar,z=u.vector);let B=It("outputData",k,n.length,4),V=qe("aData",p,t.length,4),Z=qe("bData",h,s.length,4),ee;if(i)if(a){let Q=Le.size(t)===1,he=Le.size(s)===1,pe=t.length>0&&t[t.length-1]%4===0,Me=s.length>0&&s[s.length-1]%4===0;Q||he?ee=B.setByOffset("global_idx",z(Q?`${V.type.value}(${V.getByOffset("0")}.x)`:V.getByOffset("global_idx"),he?`${Z.type.value}(${Z.getByOffset("0")}.x)`:Z.getByOffset("global_idx"))):ee=` + let outputIndices = ${B.offsetToIndices("global_idx * 4u")}; + let offsetA = ${V.broadcastedIndicesToOffset("outputIndices",B)}; + let offsetB = ${Z.broadcastedIndicesToOffset("outputIndices",B)}; + ${B.setByOffset("global_idx",z(o||pe?V.getByOffset("offsetA / 4u"):`${V.type.value}(${V.getByOffset("offsetA / 4u")}[offsetA % 4u])`,o||Me?Z.getByOffset("offsetB / 4u"):`${Z.type.value}(${Z.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else ee=B.setByOffset("global_idx",z(V.getByOffset("global_idx"),Z.getByOffset("global_idx")));else{if(!a)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let Q=(he,pe,Me="")=>{let Fe=`aData[indexA${pe}][componentA${pe}]`,De=`bData[indexB${pe}][componentB${pe}]`;return` + let outputIndices${pe} = ${B.offsetToIndices(`global_idx * 4u + ${pe}u`)}; + let offsetA${pe} = ${V.broadcastedIndicesToOffset(`outputIndices${pe}`,B)}; + let offsetB${pe} = ${Z.broadcastedIndicesToOffset(`outputIndices${pe}`,B)}; + let indexA${pe} = offsetA${pe} / 4u; + let indexB${pe} = offsetB${pe} / 4u; + let componentA${pe} = offsetA${pe} % 4u; + let componentB${pe} = offsetB${pe} % 4u; + ${he}[${pe}] = ${Me}(${d(Fe,De)}); + `};k===9?ee=` + var data = vec4(0); + ${Q("data",0,"u32")} + ${Q("data",1,"u32")} + ${Q("data",2,"u32")} + ${Q("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:ee=` + ${Q("outputData[global_idx]",0)} + ${Q("outputData[global_idx]",1)} + ${Q("outputData[global_idx]",2)} + ${Q("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(V,Z,B)} + + ${E??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${ee} + }`},Yl=(e,t,s,n,i,a,o=s.dataType)=>{let u=s.dims.map(V=>Number(V)??1),p=n.dims.map(V=>Number(V)??1),h=!Le.areEqual(u,p),k=u,E=Le.size(u),d=!1,z=!1,B=[h];if(h){let V=Ws.calcShape(u,p,!1);if(!V)throw new Error("Can't perform binary op on the given tensors");k=V.slice(),E=Le.size(k);let Z=Le.size(u)===1,ee=Le.size(p)===1,Q=u.length>0&&u[u.length-1]%4===0,he=p.length>0&&p[p.length-1]%4===0;B.push(Z),B.push(ee),B.push(Q),B.push(he);let pe=1;for(let Me=1;MeV.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:V=>Xl(V,u,p,k,d,h,z,i,s.dataType,n.dataType,o,a),getRunData:()=>({outputs:[{dims:k,dataType:o}],dispatchGroup:{x:Math.ceil(E/64/4)},programUniforms:[{type:12,data:Math.ceil(Le.size(k)/4)},...yt(u,p,k)]})}},fr=(e,t,s,n,i,a)=>{e.compute(Yl(t,i??"",e.inputs[0],e.inputs[1],s,n,a))},Jl=e=>{fr(e,"Add",(t,s)=>`${t}+${s}`)},Zl=e=>{fr(e,"Div",(t,s)=>`${t}/${s}`)},Po=e=>{fr(e,"Equal",{scalar:(t,s)=>`u32(${t}==${s})`,vector:(t,s)=>`vec4(${t}==${s})`},void 0,void 0,9)},eu=e=>{fr(e,"Mul",(t,s)=>`${t}*${s}`)},tu=e=>{let t=qe("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;fr(e,"Pow",{scalar:(s,n)=>`pow_custom(${s},${n})`,vector:(s,n)=>`pow_vector_custom(${s},${n})`},` + fn pow_custom(a : ${t}, b : ${t}) -> ${t} { + if (b == ${t}(0.0)) { + return ${t}(1.0); + } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) { + return ${t}(pow(f32(a), f32(b))); // NaN + } + return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); + } + fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> { + // TODO: implement vectorized pow + return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); + } + `)},Eo=e=>{fr(e,"Sub",(t,s)=>`${t}-${s}`)},su=e=>{fr(e,"Greater",{scalar:(t,s)=>`u32(${t}>${s})`,vector:(t,s)=>`vec4(${t}>${s})`},void 0,void 0,9)},ru=e=>{fr(e,"Less",{scalar:(t,s)=>`u32(${t}<${s})`,vector:(t,s)=>`vec4(${t}<${s})`},void 0,void 0,9)},Co=e=>{fr(e,"GreaterOrEqual",{scalar:(t,s)=>`u32(${t}>=${s})`,vector:(t,s)=>`vec4(${t}>=${s})`},void 0,void 0,9)},nu=e=>{fr(e,"LessOrEqual",{scalar:(t,s)=>`u32(${t}<=${s})`,vector:(t,s)=>`vec4(${t}<=${s})`},void 0,void 0,9)}}),ko,iu,ou,ci,au,lu,uu=g(()=>{zt(),Ot(),rs(),Yt(),ko=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let s=0,n=e[s],i=n.dataType,a=n.dims.length;e.forEach((o,u)=>{if(u!==s){if(o.dataType!==i)throw new Error("input tensors should be one type");if(o.dims.length!==a)throw new Error("input tensors should have the same shape");o.dims.forEach((p,h)=>{if(h!==t&&p!==n.dims[h])throw new Error("non concat dimensions must match")})}})},iu=(e,t)=>` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array(${t}); + for (var i: u32 = 0u; i < ${e}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${e}u; + }`,ou=(e,t)=>{let s=e.length,n=[];for(let i=0;i{let i=Le.size(s),a=new Array(e.length),o=new Array(e.length),u=0,p=[],h=[],k=[{type:12,data:i}];for(let V=0;V`uniforms.sizeInConcatAxis${V}`).join(","),B=V=>` + + ${(()=>{V.registerUniform("outputSize","u32");for(let Z=0;Z(${z}); + ${d} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${ou(o,E)} + }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:p},getRunData:()=>({outputs:[{dims:s,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:k}),getShaderSource:B}},au=(e,t)=>{let s=e.inputs,n=s[0].dims,i=Le.normalizeAxis(t.axis,n.length);ko(s,i);let a=n.slice();a[i]=s.reduce((u,p)=>u+(p.dims.length>i?p.dims[i]:0),0);let o=s.filter(u=>Le.size(u.dims)>0);e.compute(ci(o,i,a,s[0].dataType),{inputs:o})},lu=e=>Bt({axis:e.axis})}),Hr,nn,qr,So,on=g(()=>{zt(),Ot(),Hr=(e,t,s="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${s}(uniforms.clip_min)), ${t}(${s}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${s}(uniforms.alpha) * value + ${s}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${s}(uniforms.alpha) * value, value, value >= ${t}(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 ${e.activation}`)}},nn=(e,t)=>{e.activation==="Clip"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&t.push({type:1,data:e.alpha})},qr=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},So=e=>{let t=(e==null?void 0:e.activation)||"";if(t==="HardSigmoid"){let[s,n]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:t,alpha:s,beta:n}}else if(t==="Clip"){let[s,n]=(e==null?void 0:e.activation_params)||[Ss,qs];return{activation:t,clipMax:n,clipMin:s}}else if(t==="LeakyRelu"){let[s]=(e==null?void 0:e.activation_params)||[.01];return{activation:t,alpha:s}}return{activation:t}}}),Qs,$o,Ao=g(()=>{Qs=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},$o=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),du,Hc=g(()=>{du=e=>` +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(${e}.x), i32(${e}.y), i32(${e}.z), 1)); +} +`}),xn,Io,Oo=g(()=>{zt(),Ot(),Yt(),on(),xn=(e,t,s,n,i)=>{let a=n-s;return` + ${Array.from({length:s}).map((o,u)=>` + if (${$t(t.shape,u,t.rank)} != 1) { + ${t.indicesSet(e,u,$t(i,u+a,n))} + } else { + ${t.indicesSet(e,u,0)} + }`).join("")} +`},Io=(e,t,s,n,i=!1,a)=>{let o=e[0].dims,u=e[1].dims,p=o[o.length-2],h=u[u.length-1],k=o[o.length-1],E=qt(h),d=qt(k),z=qt(p),B=Le.size(s)/E/z,V=e.length>2,Z=n?n.slice(0,-2):s.slice(0,-2),ee=[Le.size(Z),p,h],Q=[{type:12,data:B},{type:12,data:p},{type:12,data:h},{type:12,data:k}];nn(t,Q),Q.push(...yt(Z,o,u)),V&&Q.push(...yt(e[2].dims)),Q.push(...yt(ee));let he=pe=>{let Me=zi("batch_dims",e[0].dataType,Z.length),Fe=qe("a",e[0].dataType,o.length,d),De=qe("b",e[1].dataType,u.length,E),Ye=It("output",e[0].dataType,ee.length,E),at=ms(Ye.type.tensor),Pt=Hr(t,Ye.type.value,at),Xt=[Fe,De],Zt="";if(V){let St=i?E:1;Xt.push(qe("bias",e[2].dataType,e[2].dims.length,St)),Zt=`${i?`value += bias[col / ${St}];`:`value += ${Ye.type.value}(bias[row + i]);`}`}let bt=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];qr(t,bt);let ss=()=>{let St=`var a_data: ${Fe.type.value};`;for(let Ft=0;Ft; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${d}) { + ${ss()} + } + for (var i = 0u; i < ${z}u; i++) { + var value = values[i]; + ${Zt} + ${Pt} + let cur_indices = ${Ye.type.indices}(batch, row + i, col); + let offset = ${Ye.indicesToOffset("cur_indices")}; + ${Ye.setByOffset(`offset / ${E}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${E};${d};${z};${i}`,inputDependencies:V?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:a?a(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(B/64)},programUniforms:Q}),getShaderSource:he}}}),Fo,cu,Do,pi,pu,Lo,zo,hi,Bo=g(()=>{zt(),Ot(),Yt(),on(),Oo(),Ao(),Fo=(e,t)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart / innerElementSize + inputCol${t?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRow + innerRow, + kStart / innerElementSize + inputCol${t?", batchIndices":""}); + `,cu=(e,t)=>e?` + let ACached0 = mm_Asub[k * innerElementSize][localRow]; + let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; + let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; + ${t===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]; + ${t===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]; + ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} + }`,Do=(e,t,s="f32",n,i=!1,a=32,o=!1,u=32)=>{let p=t[1]*e[1],h=t[0]*e[0],k=i?p:a,E=i?a:p,d=k/t[0],z=a/t[1];if(!((i&&d===4&&e[1]===4||!i&&(d===3||d===4))&&k%t[0]===0&&a%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${d} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${d} must be 3 or 4. + tileAWidth ${k} must be divisible by workgroupSize[0]${t[0]}. tileInner ${a} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` +var mm_Asub: array, ${k/d}>, ${E}>; +var mm_Bsub: array, ${h/e[0]}>, ${a}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${d}; +const tileInner = ${a}; + +@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[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 = ${o?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${p}; + + let num_tiles = ${o?`${Math.ceil(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${o?`i32(globalId.z) * ${u}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${z}; + 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; + ${Fo(i,n)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${z}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", 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]; + ${d===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${cu(i,d)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},pi=(e,t)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart + inputCol${t?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRowStart + inputRow, + kStart + inputCol${t?", batchIndices":""}); + `,pu=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Lo=(e,t,s="f32",n,i=!1,a=32,o=!1,u=32,p=!1)=>{let h=e[1]*t[1],k=e[0]*t[0],E=i?h:a,d=i?a:h;if(!(d%t[1]===0&&E%t[0]===0&&a%t[1]===0))throw new Error(`tileAHight ${d} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${E} must be divisible by workgroupSize[0]${t[0]}, tileInner ${a} must be divisible by workgroupSize[1]${t[1]}`);let z=d/t[1],B=E/t[0],V=a/t[1],Z=p?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${h}; + let globalColStart = i32(workgroupId.x) * ${k}; + + // 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 < ${d}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${E}; inputCol = inputCol + ${t[0]}) { + ${pi(i,n)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${a}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${k}; inputCol = inputCol + ${t[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${s}, 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 * ${t[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${i?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[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 * ${t[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${t[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) * ${h}; + +let tileRowA = i32(localId.y) * ${z}; +let tileColA = i32(localId.x) * ${B}; +let tileRowB = i32(localId.y) * ${V}; +// 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 < ${z}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${B}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${pi(i,n)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${V}; 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${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${s}, 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) { + ${pu(i)} + 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, ${d}>; + var mm_Bsub : array, ${a}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${a}; + +@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${o?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${o?`${Math.ceil(u/a)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${o?`i32(globalId.z) * ${u}`:"0"}; + + var acc : array, rowPerThread>; + ${Z} + } +`},zo=(e,t,s,n,i=!1)=>{let[a,o,u,p]=n,h=ms(n[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Qs(e,h)} { + var value = ${Qs(e,h)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${o.type.indices}; + ${xn("aIndices",o,o.rank-2,a.rank,"batchIndices")} + ${o.indicesSet("aIndices",o.rank-2,"u32(row)")} + ${o.indicesSet("aIndices",o.rank-1,"u32(colIn)")} + value = ${o.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${a.type.indices}) -> ${Qs(e,h)} { + var value = ${Qs(e,h)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${u.type.indices}; + ${xn("bIndices",u,u.rank-2,a.rank,"batchIndices")} + ${u.indicesSet("bIndices",u.rank-2,"u32(row)")} + ${u.indicesSet("bIndices",u.rank-1,"u32(colIn)")} + value = ${u.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Qs(e,h)}) { + let col = colIn * ${e}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${t?`value = value + ${i?"bias[colIn]":`${Qs(e,h)}(bias[row])`};`:""} + ${s} + ${p.setByIndices("vec3(coords)","value")} + } + } + `},hi=(e,t,s,n,i=!1,a)=>{let o=e[0].dims,u=e[1].dims,p=o.slice(0,-2),h=u.slice(0,-2),k=n?n.slice(0,-2):s.slice(0,-2),E=Le.size(k),d=o[o.length-2],z=o[o.length-1],B=u[u.length-1],V=z%4===0&&B%4===0,Z=d<=8?[4,1,1]:[4,4,1],ee=[8,8,1],Q=[Math.ceil(B/ee[0]/Z[0]),Math.ceil(d/ee[1]/Z[1]),Math.ceil(E/ee[2]/Z[2])],he=V?4:1,pe=[...p,d,z/he],Me=pe.length,Fe=[...h,z,B/he],De=Fe.length,Ye=[E,d,B/he],at=[{type:6,data:d},{type:6,data:B},{type:6,data:z}];nn(t,at),at.push(...yt(k,pe,Fe));let Pt=["rank","rank"],Xt=e.length>2;Xt&&(at.push(...yt(e[2].dims)),Pt.push("rank")),at.push(...yt(Ye));let Zt=bt=>{let ss=k.length,St=zi("batchDims",e[0].dataType,ss,1),Ft=ms(e[0].dataType),bs=qe("a",e[0].dataType,Me,he),Ht=qe("b",e[1].dataType,De,he),Rt=It("result",e[0].dataType,Ye.length,he),_s=[bs,Ht];if(Xt){let xr=i?he:1;_s.push(qe("bias",e[2].dataType,e[2].dims.length,xr))}let ot=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];qr(t,ot);let Et=ms(Rt.type.tensor),cs=Hr(t,Rt.type.value,Et),Ns=zo(he,Xt,cs,[St,bs,Ht,Rt],i);return` + ${bt.registerUniforms(ot).registerInternalVariables(St).declareVariables(..._s,Rt)} + ${Ns} + ${V?Do(Z,ee,Ft,St):Lo(Z,ee,Ft,St)} + `};return{name:"MatMul",shaderCache:{hint:`${Z};${t.activation};${V};${i}`,inputDependencies:Pt},getRunData:()=>({outputs:[{dims:a?a(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Q[0],y:Q[1],z:Q[2]},programUniforms:at}),getShaderSource:Zt}}}),Ro,hu,qc=g(()=>{zt(),Pe(),Yt(),on(),Ao(),Hc(),Bo(),Ro=(e,t,s,n,i=!1,a,o=4,u=4,p=4,h="f32")=>{let k=at=>{switch(at){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${h}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${at} is not supported.`)}},E=at=>{switch(at){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 ${at} is not supported.`)}},d=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,z=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,B=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",V=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",Z=e?"row":"col",ee=e?"col":"row",Q=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${Z} / outWidth; + let outCol = ${Z} % outWidth; + + let WRow = ${ee} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${ee} / 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 = ${ee} % inChannels; + var resData = ${Qs(o,h)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${B} && xCol >= 0 && xCol < ${V}) { + ${d} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${k(o)} + } + return resData;`,he=e?t&&n?` + let col = colIn * ${o}; + ${Q}`:` + let col = colIn * ${o}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${Q} + } + return ${Qs(o,h)}(0.0);`:n&&s?` + let col = colIn * ${o}; + ${Q}`:` + let col = colIn * ${o}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${Q} + } + return ${Qs(o,h)}(0.0);`,pe=e?n&&s?E(u):` + let col = colIn * ${u}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${E(u)} + } + return ${Qs(u,h)}(0.0);`:` + let col = colIn * ${u}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${E(u)} + } + return ${Qs(u,h)}(0.0);`,Me=Qs(p,h),Fe=Qs(e?o:u,h),De=Qs(e?u:o,h),Ye=Hr(a,Me,h);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Fe} { + ${e?he:pe} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${De} { + ${e?pe:he} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${Me}) { + let col = colIn * ${p}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${z} + ${$o(i)} + ${Ye} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},hu=(e,t,s,n,i,a,o,u,p)=>{let h=t.format==="NHWC",k=h?e[0].dims[3]:e[0].dims[1],E=s[0],d=h?s[2]:s[3],z=h?s[1]:s[2],B=h?s[3]:s[1],V=h&&(k%4===0||k%3===0)&&B%4===0,Z=h?B:d*z,ee=h?d*z:B,Q=[8,8,1],he=n<=8?[4,1,1]:[4,4,1],pe=[Math.ceil(Z/Q[0]/he[0]),Math.ceil(ee/Q[1]/he[1]),Math.ceil(E/Q[2]/he[2])];as("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${pe}`);let Me=V?h&&k%4!==0?3:4:1,Fe=Q[1]*he[1],De=Q[0]*he[0],Ye=Math.max(Q[0]*Me,Q[1]),at=n%Fe===0,Pt=i%De===0,Xt=a%Ye===0,Zt=V?[Me,4,4]:[1,1,1],bt=[{type:6,data:n},{type:6,data:i},{type:6,data:a},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];nn(t,bt),bt.push(...yt(e[0].dims,e[1].dims));let ss=["rank","rank"];o&&(bt.push(...yt(e[2].dims)),ss.push("rank")),bt.push(...yt(s));let St=Ft=>{let bs=[{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}];qr(t,bs);let Ht=V?4:1,Rt=ms(e[0].dataType),_s=` + fn setOutputAtIndex(flatIndex : i32, value : ${V?`vec4<${Rt}>`:Rt}) { + result[flatIndex] = ${V?`vec4<${Rt}>`:Rt}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${V?`vec4<${Rt}>`:Rt}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${V?"/ 4":""}, value); + }`,ot=qe("x",e[0].dataType,e[0].dims.length,Me===3?1:Me),Et=qe("w",e[1].dataType,e[1].dims.length,Ht),cs=[ot,Et],Ns=It("result",e[0].dataType,s.length,Ht);if(o){let xr=qe("bias",e[2].dataType,e[2].dims.length,Ht);cs.push(xr),_s+=` + fn getBiasByOutputCoords(coords : vec4) -> ${V?`vec4<${Rt}>`:Rt} { + return bias[coords.${h?"w":"y"}${V?"/ 4":""}]; + }`}return` + ${du("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 }; + ${Ft.registerUniforms(bs).declareVariables(...cs,Ns)} + ${_s} + ${Ro(h,at,Pt,Xt,o,t,Zt[0],Zt[1],Zt[2],Rt)} + ${V?Do(he,Q,Rt,void 0,!h,Ye):Lo(he,Q,Rt,void 0,!h,Ye,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${Me};${V};${at};${Pt};${Xt};${Fe};${De};${Ye}`,inputDependencies:ss},getRunData:()=>({outputs:[{dims:p?p(s):s,dataType:e[0].dataType}],dispatchGroup:{x:pe[0],y:pe[1],z:pe[2]},programUniforms:bt}),getShaderSource:St}}}),No,jo,jn,mu,Uo,mi,fu,_u,Qc=g(()=>{zt(),Pe(),Ot(),Yt(),on(),Ao(),No=e=>{let t=1;for(let s=0;stypeof e=="number"?[e,e,e]:e,jn=(e,t)=>t<=1?e:e+(e-1)*(t-1),mu=(e,t,s,n=1)=>{let i=jn(t,n);return Math.floor((e[0]*(s-1)-s+i)/2)},Uo=(e,t,s,n,i)=>{i==null&&(i=mu(e,t[0],n[0]));let a=[0,0,0,s];for(let o=0;o<3;o++)e[o]+2*i>=t[o]&&(a[o]=Math.trunc((e[o]-t[o]+2*i)/n[o]+1));return a},mi=(e,t,s,n,i,a,o,u,p,h)=>{let k,E,d,z;if(e==="VALID"&&(e=0),typeof e=="number"){k={top:e,bottom:e,left:e,right:e,front:e,back:e};let B=Uo([t,s,n,1],[u,p,h],1,[i,a,o],e);E=B[0],d=B[1],z=B[2]}else if(Array.isArray(e)){if(!e.every((V,Z,ee)=>V===ee[0]))throw Error(`Unsupported padding parameter: ${e}`);k={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let B=Uo([t,s,n,1],[u,p,h],1,[i,a,o],e[0]);E=B[0],d=B[1],z=B[2]}else if(e==="SAME_UPPER"){E=Math.ceil(t/i),d=Math.ceil(s/a),z=Math.ceil(n/o);let B=(E-1)*i+u-t,V=(d-1)*a+p-s,Z=(z-1)*o+h-n,ee=Math.floor(B/2),Q=B-ee,he=Math.floor(V/2),pe=V-he,Me=Math.floor(Z/2),Fe=Z-Me;k={top:he,bottom:pe,left:Me,right:Fe,front:ee,back:Q}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:k,outDepth:E,outHeight:d,outWidth:z}},fu=(e,t,s,n,i,a=!1,o="channelsLast")=>{let u,p,h,k,E;if(o==="channelsLast")[u,p,h,k,E]=e;else if(o==="channelsFirst")[u,E,p,h,k]=e;else throw new Error(`Unknown dataFormat ${o}`);let[d,,z,B,V]=t,[Z,ee,Q]=jo(s),[he,pe,Me]=jo(n),Fe=jn(z,he),De=jn(B,pe),Ye=jn(V,Me),{padInfo:at,outDepth:Pt,outHeight:Xt,outWidth:Zt}=mi(i,p,h,k,Z,ee,Q,Fe,De,Ye),bt=a?d*E:d,ss=[0,0,0,0,0];return o==="channelsFirst"?ss=[u,bt,Pt,Xt,Zt]:o==="channelsLast"&&(ss=[u,Pt,Xt,Zt,bt]),{batchSize:u,dataFormat:o,inDepth:p,inHeight:h,inWidth:k,inChannels:E,outDepth:Pt,outHeight:Xt,outWidth:Zt,outChannels:bt,padInfo:at,strideDepth:Z,strideHeight:ee,strideWidth:Q,filterDepth:z,filterHeight:B,filterWidth:V,effectiveFilterDepth:Fe,effectiveFilterHeight:De,effectiveFilterWidth:Ye,dilationDepth:he,dilationHeight:pe,dilationWidth:Me,inShape:e,outShape:ss,filterShape:t}},_u=(e,t,s,n,i,a)=>{let o=a==="channelsLast";o?e[0].dims[3]:e[0].dims[1];let u=[64,1,1],p={x:s.map((Z,ee)=>ee)},h=[Math.ceil(No(p.x.map(Z=>s[Z]))/u[0]),1,1];as("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${h}`);let k=1,E=Le.size(s),d=[{type:12,data:E},{type:12,data:n},{type:12,data:i},{type:12,data:t.strides},{type:12,data:t.dilations}];nn(t,d),d.push(...yt(e[0].dims,e[1].dims));let z=["rank","rank"],B=e.length===3;B&&(d.push(...yt(e[2].dims)),z.push("rank")),d.push(...yt(s));let V=Z=>{let ee=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:i.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];qr(t,ee);let Q=1,he=ms(e[0].dataType),pe=qe("x",e[0].dataType,e[0].dims.length,k),Me=qe("W",e[1].dataType,e[1].dims.length,Q),Fe=[pe,Me],De=It("result",e[0].dataType,s.length,Q),Ye="";if(B){let Xt=qe("bias",e[2].dataType,e[2].dims.length,Q);Fe.push(Xt),Ye+=` + fn getBiasByOutputCoords(coords : array) -> ${he} { + return bias[${o?$t("coords",4,5):$t("coords",1,5)}]; + }`}let at=Qs(k,he),Pt=Hr(t,at,he);return` + ${Ye} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${pe.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${Me.getByIndices("aIndices")}; + } + ${Z.registerUniforms(ee).declareVariables(...Fe,De)} + ${Z.mainStart()} + ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${De.offsetToIndices("global_idx")}; + let batch = ${$t("coords",0,pe.rank)}; + let d2 = ${o?$t("coords",pe.rank-1,pe.rank):$t("coords",1,pe.rank)}; + let xFRCCorner = vec3(${o?$t("coords",1,pe.rank):$t("coords",2,pe.rank)}, + ${o?$t("coords",2,pe.rank):$t("coords",3,pe.rank)}, + ${o?$t("coords",3,pe.rank):$t("coords",4,pe.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${o?$t("uniforms.x_shape",1,pe.rank):$t("uniforms.x_shape",2,pe.rank)}; + let xShapeZ = ${o?$t("uniforms.x_shape",2,pe.rank):$t("uniforms.x_shape",3,pe.rank)}; + let xShapeW = ${o?$t("uniforms.x_shape",3,pe.rank):$t("uniforms.x_shape",4,pe.rank)}; + let xShapeU = ${o?$t("uniforms.x_shape",4,pe.rank):$t("uniforms.x_shape",1,pe.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) { + ${o?`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) { + ${o?`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) { + ${o?`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) { + ${o?`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); + } + } + } + } + ${B?"value = value + getBiasByOutputCoords(coords)":""}; + ${Pt} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${o};${k};${B}`,inputDependencies:z},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:h[0],y:h[1],z:h[2]},programUniforms:d}),getShaderSource:V}}}),gu,wu,yu=g(()=>{zt(),Ot(),Yt(),on(),gu=(e,t,s,n)=>{let i=e.length>2,a=i?"value += b[output_channel];":"",o=e[0].dims,u=e[1].dims,p=t.format==="NHWC",h=p?s[3]:s[1],k=h/t.group,E=p&&k>=4?qt(h):1,d=Le.size(s)/E,z=[{type:12,data:d},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:k}];nn(t,z),z.push(...yt(o,[u[0],u[1],u[2],u[3]/E]));let B=i?["rank","rank","rank"]:["rank","rank"];z.push(...yt([s[0],s[1],s[2],s[3]/E]));let V=Z=>{let ee=It("output",e[0].dataType,s.length,E),Q=ms(ee.type.tensor),he=Hr(t,ee.type.value,Q),pe=qe("x",e[0].dataType,o.length),Me=qe("w",e[1].dataType,u.length,E),Fe=[pe,Me];i&&Fe.push(qe("b",e[2].dataType,e[2].dims,E));let De=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];qr(t,De);let Ye=p?` + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { + continue; + } + + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + let xVal = ${pe.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${Me.get("wHeight","wWidth","wInChannel","output_channel")}; + value += xVal * wVal; + } + } + } + `:` + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = in_channel_offset + 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[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[3]) { + continue; + } + + let xVal = ${pe.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${Me.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${Z.registerUniforms(De).declareVariables(...Fe,ee)} + + ${Z.mainStart()} + ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${ee.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${p?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${p?1:2}], outputIndices[${p?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel * ${E} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${p?2:1}]; + + var value: ${ee.type.value} = ${ee.type.value}(0); + ${Ye} + ${a} + ${he} + ${ee.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${E}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:z}),getShaderSource:V}},wu=(e,t,s,n)=>{let i=e.length>2,a=qt(s[3]),o=qt(s[2]),u=Le.size(s)/a/o,p=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/a],h=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/a],k=[s[0],s[1],s[2],s[3]/a],E=[{type:12,data:u},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];nn(t,E),E.push(...yt(p,h,k));let d=(o-1)*t.strides[1]+h[1],z=B=>{let V=It("output",e[0].dataType,k.length,a),Z=ms(V.type.tensor),ee=Hr(t,V.type.value,Z),Q=qe("x",e[0].dataType,p.length,a),he=qe("w",e[1].dataType,h.length,a),pe=[Q,he];i&&pe.push(qe("b",e[2].dataType,e[2].dims,a));let Me=i?"value += b[output_channel];":"",Fe=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return qr(t,Fe),` + ${B.registerUniforms(Fe).declareVariables(...pe,V)} + ${B.mainStart()} + ${B.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] / ${o}u; + let col = (index1 % width1) * ${o}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<${Q.type.value}, ${d}>; + var values: array<${V.type.value}, ${o}>; + 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 < ${h[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 < ${d}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${Q.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${Q.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${h[1]}; w_width++) { + let w_val = ${he.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${o}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${o}u; i++) { + var value = values[i]; + ${Me} + ${ee} + ${V.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${a};${o};${d};${h[0]};${h[1]}`,inputDependencies:i?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:E}),getShaderSource:z}}}),Mu,fi,Vo,_i,Wo,Go,bu,Ko,Ho,Xc=g(()=>{Ot(),qc(),Qc(),Bo(),yu(),on(),Oo(),Kr(),Mu=(e,t,s,n,i,a)=>{let o=e[0],u=e.slice(a?1:2,a?3:4),p=u.length,h=t[0],k=t.slice(2).map((d,z)=>d+(d-1)*(s[z]-1)),E=u.map((d,z)=>d+n[z]+n[z+p]).map((d,z)=>Math.floor((d-k[z]+i[z])/i[z]));return E.splice(0,0,o),E.splice(a?3:1,0,h),E},fi=[2,3,1,0],Vo=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let s=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(s!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let i=e[0].dims.length-2;if(t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},_i=(e,t)=>{let s=e.kernelShape.slice();s.length{let t=So(e),s=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],i=e.dilations,a=e.group,o=e.kernel_shape,u=e.pads,p=e.strides,h=e.w_is_const();return{autoPad:n,format:s,dilations:i,group:a,kernelShape:o,pads:u,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},Go=(e,t,s,n)=>{let i=s.format==="NHWC",a=Mu(t[0].dims,t[1].dims,s.dilations,s.pads,s.strides,i);if(s.group!==1){let Fe=[t[0]];if(i){let De=e.kernelCustomData.wT??e.compute(hr(t[1],fi),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=De),Fe.push(De)}else Fe.push(t[1]);t.length===3&&Fe.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&i&&t[1].dims[0]===s.group&&t[1].dims[1]===1&&s.dilations[0]===1&&s.dilations[1]===1?e.compute(wu(Fe,s,a,n),{inputs:Fe}):e.compute(gu(Fe,s,a,n),{inputs:Fe});return}let o=t.length===3,u=t[0].dims[i?1:2],p=t[0].dims[i?2:3],h=t[0].dims[i?3:1],k=t[1].dims[2],E=t[1].dims[3],d=a[i?1:2],z=a[i?2:3],B=a[i?3:1],V=i&&k===u&&E===p&&s.pads[0]===0&&s.pads[1]===0;if(V||k===1&&E===1&&s.dilations[0]===1&&s.dilations[1]===1&&s.strides[0]===1&&s.strides[1]===1&&s.pads[0]===0&&s.pads[1]===0){let Fe=a[0],De,Ye,at,Pt=[];if(i){let bt=e.kernelCustomData.wT??e.compute(hr(t[1],fi),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];if(s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=bt),V){let ss=u*p*h;De=t[0].reshape([1,Fe,ss]),Ye=bt.reshape([1,ss,B]),at=[1,Fe,B]}else De=t[0].reshape([Fe,u*p,h]),Ye=bt.reshape([1,h,B]),at=[Fe,d*z,B];Pt.push(De),Pt.push(Ye)}else De=t[0].reshape([Fe,h,u*p]),Ye=t[1].reshape([1,B,h]),at=[Fe,B,d*z],Pt.push(Ye),Pt.push(De);o&&Pt.push(t[2]);let Xt=at[2],Zt=Pt[0].dims[Pt[0].dims.length-1];Xt<8&&Zt<8?e.compute(Io(Pt,s,a,at,i,n),{inputs:Pt}):e.compute(hi(Pt,s,a,at,i,n),{inputs:Pt});return}let Z=!0,ee=e.kernelCustomData.wT??e.compute(hr(t[1],fi),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=ee);let Q=[t[0],ee];o&&Q.push(t[2]);let he=i?d*z:B,pe=i?B:d*z,Me=k*E*h;e.compute(hu(Q,s,a,he,pe,Me,o,Z,n),{inputs:Q})},bu=(e,t)=>{let s=t.format==="NHWC",n=[e.inputs[0].reshape(s?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let i=[0,t.pads[0],0,t.pads[1]],a=[1].concat(t.strides),o=[1].concat(t.dilations),u=[1].concat(t.kernelShape),p=_i({...t,pads:i,strides:a,dilations:o,kernelShape:u},n);Go(e,n,p,h=>s?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},Ko=(e,t,s)=>{let n=s.format==="NHWC"?"channelsLast":"channelsFirst",i=_i(s,t),a=s.autoPad==="NOTSET"?s.pads:s.autoPad,o=fu(t[0].dims,t[1].dims,s.strides,s.dilations,a,!1,n);e.compute(_u(t,i,o.outShape,[o.filterDepth,o.filterHeight,o.filterWidth],[o.padInfo.front,o.padInfo.top,o.padInfo.left],n))},Ho=(e,t)=>{if(Vo(e.inputs,t),e.inputs[0].dims.length===3)bu(e,t);else if(e.inputs[0].dims.length===5)Ko(e,e.inputs,t);else{let s=_i(t,e.inputs);Go(e,e.inputs,s)}}}),qo,Yc=g(()=>{zt(),Pe(),Ot(),Yt(),qo=(e,t,s)=>{let n=e.length>2,i=t.outputShape,a=t.format==="NHWC",o=t.group,u=e[1].dims,p=u[2]/o,h=u[3],k=a?qt(p):1,E=a?qt(h):1,d=a?h===1?k:E:1,z=Le.size(i)/E,B=[Math.ceil(z/64),1,1];as("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${B}`);let V=["rank","rank"],Z=[t.strides[0],t.strides[1]],ee=[t.kernelShape[a?1:2],t.kernelShape[a?2:3]],Q=[t.dilations[0],t.dilations[1]],he=[ee[0]+(t.dilations[0]<=1?0:(t.kernelShape[a?1:2]-1)*(t.dilations[0]-1)),ee[1]+(t.dilations[1]<=1?0:(t.kernelShape[a?2:3]-1)*(t.dilations[1]-1))],pe=[he[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),he[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],Me=[{type:12,data:z},{type:12,data:Z},{type:12,data:ee},{type:12,data:Q},{type:12,data:he},{type:6,data:pe},{type:12,data:p},{type:12,data:h},...yt(e[0].dims,e[1].dims)];n&&(Me.push(...yt(e[2].dims)),V.push("rank")),Me.push(...yt(i));let Fe=De=>{let Ye=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:Z.length},{name:"filter_dims",type:"u32",length:ee.length},{name:"dilations",type:"u32",length:ee.length},{name:"effective_filter_dims",type:"u32",length:he.length},{name:"pads",type:"i32",length:pe.length},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],at=ms(e[0].dataType),Pt=a?1:2,Xt=a?2:3,Zt=a?3:1,bt=qe("W",e[1].dataType,e[1].dims.length,d),ss=qe("Dy",e[0].dataType,e[0].dims.length,k),St=[ss,bt];n&&St.push(qe("bias",e[2].dataType,[i[Zt]].length,E));let Ft=It("result",e[0].dataType,i.length,E),bs=()=>{let Rt="";if(k===1)Rt+=` + let w_offset = ${bt.indicesToOffset(`${bt.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${bt.getByOffset(`w_offset / ${d}`)}; + dotProd = dotProd + xValue * wValue;`;else if(h===1)Rt+=` + let wValue = ${bt.getByOffset(`${bt.indicesToOffset(`${bt.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)} / ${d}`)}; + dotProd = dotProd + dot(xValue, wValue);`;else for(let _s=0;_s(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 = ${Ft.type.value}(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 = (${at}(dyRCorner) + ${at}(wR)) / ${at}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${at}(uniforms.Dy_shape[${Pt}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + wR = wR + uniforms.strides[0] - 1; + 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 = (${at}(dyCCorner) + ${at}(wC)) / ${at}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${at}(uniforms.Dy_shape[${Xt}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + wC = wC + uniforms.strides.y - 1; + 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 + ${k}) { + let xValue = ${a?ss.getByOffset(`${ss.indicesToOffset(`${ss.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${k}`):ss.get("batch","inputChannel","idyR","idyC")}; + ${bs()} + inputChannel = inputChannel + ${k}; + } + } + } + let value = dotProd${n?` + bias[d1 / ${E}]`:""}; + ${Ft.setByOffset("global_idx","value")}; + `;return` + ${De.registerUniforms(Ye).declareVariables(...St,Ft)} + ${De.mainStart()} + ${De.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${Ht}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${k}${d}${E}${h===1}`,inputDependencies:V},getRunData:()=>({dispatchGroup:{x:B[0],y:B[1],z:B[2]},outputs:[{dims:s?s(i):i,dataType:e[0].dataType}],programUniforms:Me}),getShaderSource:Fe}}}),vu,Qo,xu,Xo,Yo,Tu,Jo,Pu,Eu,Cu=g(()=>{Yc(),on(),Kr(),vu=(e,t,s,n,i,a)=>(e-1)*t+s+(n-1)*i+1-a,Qo=(e,t,s,n,i)=>{let a=Math.floor(e/2);t==="SAME_UPPER"?(s[n]=a,s[i]=e-a):t==="SAME_LOWER"&&(s[n]=e-a,s[i]=a)},xu=(e,t,s,n,i,a,o,u,p,h)=>{let k=e.length-2,E=h.length===0;p.length{let s=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((E,d)=>E*d,1)===0){s.length=0;for(let E=2;EE+d,0)===0){let E=t[0].dims.length-2;p=new Array(E).fill(1)}let h=e.strides.slice();if(h.reduce((E,d)=>E+d,0)===0){let E=t[0].dims.length-2;h=new Array(E).fill(1)}xu(u,s,p,e.autoPad,e.group,i,h,n,o,a);let k=Object.assign({},e);return Object.assign(k,{kernelShape:s,pads:i,outputPadding:o,outputShape:a,dilations:p,strides:h}),k},Yo=e=>{let t=So(e),s=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,a=e.group,o=e.kernelShape,u=e.pads,p=e.strides,h=e.wIsConst(),k=e.outputPadding,E=e.outputShape;return{autoPad:n,format:s,dilations:i,group:a,kernelShape:o,outputPadding:k,outputShape:E,pads:u,strides:p,wIsConst:h,...t,cacheKey:`${e.format};${t.activation};`}},Tu=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let s=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(s!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let i=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==i))throw new Error("invalid bias");let a=e[0].dims.length-2;if(t.dilations.reduce((o,u)=>o+u,0)>0&&t.dilations.length!==a)throw new Error(`dilations should be ${a}D`);if(t.strides.reduce((o,u)=>o+u,0)>0&&t.strides.length!==a)throw new Error(`strides should be ${a}D`);if(t.pads.reduce((o,u)=>o+u,0)>0&&t.pads.length!==a*2)throw new Error(`pads should be ${a*2}D`);if(t.outputPadding.length!==a&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${a}D`);if(t.kernelShape.reduce((o,u)=>o+u,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},Jo=(e,t,s,n)=>{let i=e.kernelCustomData.wT??e.compute(hr(t[1],[2,3,0,1]),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=i);let a=[t[0],i];t.length===3&&a.push(t[2]),e.compute(qo(a,s,n),{inputs:a})},Pu=(e,t)=>{let s=t.format==="NHWC",n=[e.inputs[0].reshape(s?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let i=t.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let a=t.dilations;(a.length===0||a[0]===0)&&(a=[1]);let o=t.strides;(o.length===0||o[0]===0)&&(o=[1]);let u=t.pads;u.length===0&&(u=[0,0]),u=[0,u[0],0,u[1]],o=[1].concat(o),a=[1].concat(a),i=[1].concat(i);let p=Xo({...t,pads:u,strides:o,dilations:a,kernelShape:i},n);Jo(e,n,p,h=>s?[h[0],h[2],h[3]]:[h[0],h[1],h[3]])},Eu=(e,t)=>{if(Tu(e.inputs,t),e.inputs[0].dims.length===3)Pu(e,t);else{let s=Xo(t,e.inputs);Jo(e,e.inputs,s)}}}),ku,Su,$u,Jc=g(()=>{zt(),Ot(),rs(),Yt(),ku=(e,t,s,n)=>{let i=Le.size(t),a=t.length,o=qe("input",e,a),u=It("output",e,a),p=s.dataType===6?s.getInt32Array()[0]:Number(s.getBigInt64Array()[0]),h=Le.normalizeAxis(p,a),k=E=>{let d=` i32(${o.indicesGet("inputIndices","uniforms.axis")}) `,z=$t("uniforms.input_shape","uniforms.axis",a),B=n.reverse?d+(n.exclusive?" + 1":""):"0",V=n.reverse?z:d+(n.exclusive?"":" + 1");return` + ${E.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(o,u)} + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${u.offsetToIndices("global_idx")}; + var sum = ${u.type.value}(0); + let first : i32 = ${B}; + let last : i32 = ${V}; + for (var i : i32 = first; i < last; i++) { + ${o.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${o.getByIndices("inputIndices")}; + } + ${u.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:h},...yt(t,t)]}),getShaderSource:k}},Su=(e,t)=>{let s=e.inputs[0].dims,n=e.inputs[0].dataType,i=e.inputs[1];e.compute(ku(n,s,i,t),{inputs:[0]})},$u=e=>{let t=e.exclusive===1,s=e.reverse===1;return Bt({exclusive:t,reverse:s})}}),Au,Iu,Zo,Ou,Fu,Du=g(()=>{zt(),Ot(),rs(),Yt(),Au=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},Iu=(e,t,s,n)=>{let i=[];i.push(`fn perm(i: ${n.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`);for(let a=0;a{let s,n,i,a,o,u,p=t.format==="NHWC",h=t.blocksize,k=t.mode==="DCR";p?([s,n,i,a]=e.dims,o=k?[s,n,i,h,h,a/h**2]:[s,n,i,a/h**2,h,h],u=k?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([s,n,i,a]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],o=k?[s,h,h,a/h**2,n,i]:[s,a/h**2,h,h,n,i],u=k?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let E=e.reshape(o),d=E.dims.length,z=e.dataType,B=qe("a",z,d),V=It("output",z,d),Z=ee=>` + ${ee.registerUniform("output_size","u32").declareVariables(B,V)} + + ${Iu(u,d,B,V)} + + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${V.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${V.setByOffset("global_idx",B.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:ee=>{let Q=p?[s,n*h,i*h,a/h**2]:[s,a/h**2,n*h,i*h],he=Le.size(Q),pe=E.dims,Me=Le.sortBasedOnPerm(pe,u);return{outputs:[{dims:Q,dataType:ee[0].dataType}],dispatchGroup:{x:Math.ceil(he/64)},programUniforms:[{type:12,data:he},...yt(pe,Me)]}},getShaderSource:Z}},Ou=(e,t)=>{Au(e.inputs),e.compute(Zo(e.inputs[0],t))},Fu=e=>Bt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),gi,Un,Dr,Lu,zu,Bu,Ru,wi,Nu,ju,Uu,Zc=g(()=>{zt(),Ot(),rs(),Yt(),gi="[a-zA-Z]|\\.\\.\\.",Un="("+gi+")+",Dr="^"+Un+"$",Lu="("+Un+",)*"+Un,zu="^"+Lu+"$",Bu=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let s=this.symbolToIndices.get(e);s===void 0?s=[t]:s.push(t),this.symbolToIndices.set(e,s)}},Ru=class{constructor(e,t){var i;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[s,n]=t.includes("->")?t.split("->",2):[t,""];if(!s.match(RegExp(zu)))throw new Error("Invalid LHS term");if(s.split(",").forEach((a,o)=>{let u=e[o].dims.slice();if(!a.match(RegExp(Dr)))throw new Error("Invalid LHS term");let p=this.processTerm(a,!0,u,o);this.lhs.push(p)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([a,o])=>o.count===1||a==="...").map(([a])=>a).join("");else if(!n.match(RegExp(Un)))throw new Error("Invalid RHS");(i=n.match(RegExp(gi,"g")))==null||i.forEach(a=>{if(a==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let o=this.symbolToInfo.get(a);if(o===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(o.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(e,t,s){let n=this.symbolToInfo.get(e);if(n!==void 0){if(n.dimValue!==t&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(s)}else n={count:1,dimValue:t,inputIndices:[s]};this.symbolToInfo.set(e,n)}processTerm(e,t,s,n=-1){let i=s.length,a=!1,o=[],u=0;if(!e.match(RegExp(Dr))&&!t&&e!=="")throw new Error("Invalid LHS term");let p=e.match(RegExp(gi,"g")),h=new Bu(n);return p==null||p.forEach((k,E)=>{if(k==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let d=i-p.length+1;if(d<0)throw new Error("Ellipsis out of bounds");if(o=s.slice(u,u+d),this.hasEllipsis){if(this.ellipsisDims.length!==o.length||this.ellipsisDims.toString()!==o.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=o;else throw new Error("Ellipsis must be specified in the LHS");for(let z=0;ze+"_max",Nu=(e,t,s,n)=>{let i=e.map(h=>h.length).map((h,k)=>qe(`input${k}`,t,h)),a=Le.size(n),o=It("output",t,n.length),u=[...s.symbolToInfo.keys()].filter(h=>!s.rhs.symbolToIndices.has(h)),p=h=>{let k=[],E="var prod = 1.0;",d="var sum = 0.0;",z="sum += prod;",B=[],V=[],Z=[],ee=[],Q=s.symbolToInfo.size===s.rhs.symbolToIndices.size;s.symbolToInfo.forEach((pe,Me)=>{var Fe;if(s.rhs.symbolToIndices.has(Me)){let De=(Fe=s.rhs.symbolToIndices.get(Me))==null?void 0:Fe[0];De!==void 0&&s.lhs.forEach((Ye,at)=>{if(pe.inputIndices.includes(at)){let Pt=Ye.symbolToIndices.get(Me);if(Pt===void 0)throw new Error("Invalid symbol error");Pt.forEach(Xt=>{k.push(`${i[at].indicesSet(`input${at}Indices`,Xt,o.indicesGet("outputIndices",De))}`)})}})}else s.lhs.forEach((De,Ye)=>{if(pe.inputIndices.includes(Ye)){let at=De.symbolToIndices.get(Me);if(at===void 0)throw new Error("Invalid symbol error");at.forEach(Pt=>{B.push(`${i[Ye].indicesSet(`input${Ye}Indices`,Pt,`${Me}`)}`)}),ee.push(`prod *= ${i[Ye].getByIndices(`input${Ye}Indices`)};`)}}),V.push(`for(var ${Me}: u32 = 0; ${Me} < uniforms.${wi(Me)}; ${Me}++) {`),Z.push("}")});let he=Q?[...k,`let sum = ${i.map((pe,Me)=>pe.getByIndices(`input${Me}Indices`)).join(" * ")};`]:[...k,d,...V,...B,E,...ee,z,...Z];return` + ${h.registerUniforms(u.map(pe=>({name:`${wi(pe)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...i,o)} + + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${o.offsetToIndices("global_idx")}; + ${i.map((pe,Me)=>`var input${Me}Indices: ${i[Me].type.indices};`).join(` +`)} + ${he.join(` +`)}; + ${o.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:s.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let h=u.filter(E=>s.symbolToInfo.has(E)).map(E=>{var d;return{type:12,data:((d=s.symbolToInfo.get(E))==null?void 0:d.dimValue)||0}});h.push({type:12,data:a});let k=e.map((E,d)=>[...yt(E)]).reduce((E,d)=>E.concat(d),h);return k.push(...yt(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:k}},getShaderSource:p}},ju=(e,t)=>{let s=new Ru(e.inputs,t.equation),n=s.outputDims,i=e.inputs.map((a,o)=>a.dims);e.compute(Nu(i,e.inputs[0].dataType,s,n))},Uu=e=>{let t=e.equation.replace(/\s+/g,"");return Bt({equation:t})}}),yi,ea,Vu,Wu,Vn,ep=g(()=>{zt(),Ot(),Yt(),yi=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),n=s.length{let s=e.length-t.length,n=[];for(let i=0;ie.length>t.length?ea(e,t):ea(t,e),Wu=e=>{let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),n=Vu(t,s),i=e[0].dataType,a=i===9||Le.size(t)===1,o=i===9||t.length>0&&t[t.length-1]%4===0?4:1,u=a||n.length>0&&n[n.length-1]%4===0?4:1,p=Math.ceil(Le.size(n)/u),h=E=>{let d=qe("input",i,t.length,o),z=It("output",i,n.length,u),B;if(i===9){let V=(Z,ee,Q="")=>` + let outputIndices${ee} = ${z.offsetToIndices(`outputOffset + ${ee}u`)}; + let offset${ee} = ${d.broadcastedIndicesToOffset(`outputIndices${ee}`,z)}; + let index${ee} = offset${ee} / 4u; + let component${ee} = offset${ee} % 4u; + ${Z}[${ee}] = ${Q}(${d.getByOffset(`index${ee}`)}[component${ee}]); + `;B=` + let outputOffset = global_idx * ${u}; + var data = vec4(0); + ${V("data",0,"u32")} + ${V("data",1,"u32")} + ${V("data",2,"u32")} + ${V("data",3,"u32")} + ${z.setByOffset("global_idx","data")} + }`}else B=` + let outputIndices = ${z.offsetToIndices(`global_idx * ${u}`)}; + let inputOffset = ${d.broadcastedIndicesToOffset("outputIndices",z)}; + let data = ${z.type.value}(${d.getByOffset(`inputOffset / ${o}`)}); + ${z.setByOffset("global_idx","data")} + }`;return` + ${E.registerUniform("vec_size","u32").declareVariables(d,z)} + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${B}`},k=[{type:12,data:p},...yt(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length};${o}${u}`,inputDependencies:["rank"]},getShaderSource:h,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:k})}},Vn=e=>{yi(e.inputs),e.compute(Wu(e.inputs),{inputs:[0]})}}),Gu,Ku,tp=g(()=>{zt(),Ot(),Yt(),xo(),Gu=e=>{let t=e[0].dataType,s=Le.size(e[0].dims),n=Le.size(e[1].dims),i=n%4===0,a=o=>{let u=qe("x",t,[1],4),p=qe("bias",t,[1],4),h=It("y",t,[1],4),k=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],E=z=>` + let bias${z}_offset: u32 = (global_idx * 4 + ${z}) % uniforms.bias_size; + let bias${z} = ${p.getByOffset(`bias${z}_offset / 4`)}[bias${z}_offset % 4];`,d=i?` + let bias = ${p.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${E(0)}${E(1)}${E(2)}${E(3)} + let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;return`${o.registerUniforms(k).declareVariables(u,p,h)} + + ${di($s(t))} + + ${o.mainStart(nr)} + ${o.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${u.getByOffset("global_idx")}; + ${d} + let x_in = x + bias; + ${h.setByOffset("global_idx",bo("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${i}`,inputDependencies:["type","type"]},getShaderSource:a,getRunData:o=>({outputs:[{dims:o[0].dims,dataType:o[0].dataType}],programUniforms:[{type:12,data:Math.ceil(s/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(s/nr/4)}})}},Ku=e=>{e.inputs.length<2||Le.size(e.inputs[1].dims)===0?Vl(e):e.compute(Gu(e.inputs))}}),Mi,Hu,qu,Qu,Np=g(()=>{zt(),Ot(),rs(),Yt(),Mi=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Hu=(e,t)=>{let s=e[0].dims,n=e[1].dims,i=s.length,a=Le.normalizeAxis(t.axis,i),o=s.slice(0);o.splice(a,1,...n);let u=s[a],p=e[0].dataType===9?4:1,h=Math.ceil(Le.size(o)/p),k=[{type:12,data:h},{type:6,data:u},{type:12,data:a},...yt(e[0].dims,e[1].dims,o)],E=d=>{let z=qe("data",e[0].dataType,e[0].dims.length,p),B=qe("inputIndices",e[1].dataType,e[1].dims.length),V=It("output",e[0].dataType,o.length,p),Z=Q=>{let he=n.length,pe=`var indicesIndices${Q} = ${B.type.indices}(0);`;for(let Me=0;Me1?`indicesIndices${Q}[${Me}]`:`indicesIndices${Q}`} = ${o.length>1?`outputIndices${Q}[uniforms.axis + ${Me}]`:`outputIndices${Q}`};`;pe+=` + var idx${Q} = ${B.getByIndices(`indicesIndices${Q}`)}; + if (idx${Q} < 0) { + idx${Q} = idx${Q} + uniforms.axisDimLimit; + } + var dataIndices${Q} : ${z.type.indices}; + `;for(let Me=0,Fe=0;Me1?`dataIndices${Q}[${Me}]`:`dataIndices${Q}`} = u32(idx${Q});`,Fe+=he):(pe+=`${i>1?`dataIndices${Q}[${Me}]`:`dataIndices${Q}`} = ${o.length>1?`outputIndices${Q}[${Fe}]`:`outputIndices${Q}`};`,Fe++);return pe},ee;if(e[0].dataType===9){let Q=(he,pe,Me="")=>` + let outputIndices${pe} = ${V.offsetToIndices(`outputOffset + ${pe}u`)}; + ${Z(pe)}; + let offset${pe} = ${z.indicesToOffset(`dataIndices${pe}`)}; + let index${pe} = offset${pe} / 4u; + let component${pe} = offset${pe} % 4u; + ${he}[${pe}] = ${Me}(${z.getByOffset(`index${pe}`)}[component${pe}]); + `;ee=` + let outputOffset = global_idx * ${p}; + var value = vec4(0); + ${Q("value",0,"u32")} + ${Q("value",1,"u32")} + ${Q("value",2,"u32")} + ${Q("value",3,"u32")} + ${V.setByOffset("global_idx","value")} + `}else ee=` + let outputIndices = ${V.offsetToIndices("global_idx")}; + ${Z("")}; + let value = ${z.getByIndices("dataIndices")}; + ${V.setByOffset("global_idx","value")}; + `;return` + ${d.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(z,B,V)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${ee} + }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:k}),getShaderSource:E}},qu=e=>Bt({axis:e.axis}),Qu=(e,t)=>{let s=e.inputs;Mi(s),e.compute(Hu(e.inputs,t))}}),Xu,Yu,Ju,Wn=g(()=>{zt(),Ot(),Yt(),Xu=(e,t,s,n,i,a,o,u,p)=>{let h=[{type:12,data:a},{type:12,data:n},{type:12,data:i},{type:12,data:s},{type:12,data:o},{type:12,data:u},{type:12,data:p}],k=[a];h.push(...yt(t.dims,k));let E=d=>{let z=qe("indices_data",t.dataType,t.dims.length),B=It("input_slice_offsets_data",12,1,1),V=[z,B],Z=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:i.length},{name:"sizes_from_slice_dims_data",type:"u32",length:s.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` + ${d.registerUniforms(Z).declareVariables(...V)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let batch_idx = global_idx / uniforms.num_slices_per_batch; + let base_offset = batch_idx * uniforms.input_batch_stride; + + let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; + var relative_slice_offset = 0; + for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { + var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); + let input_dim_idx = uniforms.batch_dims + dim_idx; + if (index < 0) { + ${i.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} + } + ${s.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} + } + + input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); + }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${i.length}_${s.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:k,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:h}),getShaderSource:E},{inputs:[t],outputs:[-1]})[0]},Yu=(e,t)=>{let s=e.inputs,n=s[0].dims,i=s[0].dataType,a=s[1].dims,o=a[a.length-1],u=Le.sizeToDimension(a,a.length-1),p=Le.sizeFromDimension(n,t.batchDims+o),h=Le.sizeToDimension(n,t.batchDims),k=Le.sizeFromDimension(n,t.batchDims),E=u/h,d=new Array(o),z=p;for(let pe=0;pen.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let Z=a.slice(0,-1).concat(n.slice(V)),ee=Le.size(Z),Q=[{type:12,data:ee},{type:12,data:p},...yt(s[0].dims,B.dims,Z)],he=pe=>{let Me=qe("data",s[0].dataType,s[0].dims.length),Fe=qe("slice_offsets",12,B.dims.length),De=It("output",s[0].dataType,Z.length);return` + ${pe.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(Me,Fe,De)} + ${pe.mainStart()} + ${pe.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; + output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; + }`};e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:Z,dataType:i}],dispatchGroup:{x:Math.ceil(ee/64)},programUniforms:Q}),getShaderSource:he},{inputs:[s[0],B]})},Ju=e=>({batchDims:e.batch_dims,cacheKey:""})}),Zu,ed,td,sd,sp=g(()=>{zt(),Ot(),rs(),Yt(),Zu=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let s=Le.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,i=e[0],a=e[2],o=e.length===4?e[3]:void 0;if(a.dims.length!==i.dims.length||!i.dims.map((u,p)=>p===s?Math.ceil(u/n)===a.dims[p]:u===a.dims[p]).reduce((u,p)=>u&&p,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(o){if(o.dataType!==i.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(o.dims.length!==a.dims.length||!o.dims.map((u,p)=>u===a.dims[p]).reduce((u,p)=>u&&p,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},ed=(e,t)=>{let s=e[0].dims,n=e[1].dims,i=s.length,a=Le.normalizeAxis(t.gatherAxis,i),o=Le.normalizeAxis(t.quantizeAxis,i),u=s.slice(0);u.splice(a,1,...n);let p=Le.size(u),h=e[2].dataType,k=e[0].dataType===22,E=[{type:12,data:p},{type:12,data:o},{type:12,data:a},{type:12,data:t.blockSize},...yt(...e.map((z,B)=>z.dims),u)],d=z=>{let B=qe("data",e[0].dataType,e[0].dims.length),V=qe("inputIndices",e[1].dataType,e[1].dims.length),Z=qe("scales",e[2].dataType,e[2].dims.length),ee=e.length>3?qe("zeroPoint",e[3].dataType,e[3].dims.length):void 0,Q=It("output",h,u.length),he=[B,V,Z];ee&&he.push(ee);let pe=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${z.registerUniforms(pe).declareVariables(...he,Q)} + ${z.mainStart()} + let output_indices = ${Q.offsetToIndices("global_idx")}; + var indices_indices = ${V.type.indices}(0); + ${n.length>1?` + for (var i: u32 = 0; i < ${n.length}; i++) { + let index = ${Q.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${V.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${Q.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${B.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${Q.indicesGet("output_indices","i")}; + ${B.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${V.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${s[a]}; + } + ${B.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) { + let index = ${Q.indicesGet("output_indices",`i + ${n.length} - 1`)}; + ${B.indicesSet("data_indices","i","index")}; + } + let data_offset = ${B.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${B.getByOffset("data_offset / 8")}; + let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; + let quantized_data_vec = ${k?"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 = ${Z.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${Z.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${Z.getByIndices("scale_indices")}; + ${ee?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${ee.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${ee.getByOffset("zero_point_offset / 8")}; + let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; + let zero_point_vec = ${k?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); + let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; + let dequantized_data = ${$s(h)}(quantized_data - zero_point) * scale; + ${Q.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((z,B)=>B!==1).map(z=>z.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(z,B)=>"rank")},getRunData:()=>({outputs:[{dims:u,dataType:h}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:E}),getShaderSource:d}},td=(e,t)=>{let s=e.inputs;Zu(s,t),e.compute(ed(e.inputs,t))},sd=e=>Bt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),rd,nd,bi,rp,np=g(()=>{zt(),Ot(),rs(),Yt(),rd=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and + indices input tensors be of same rank.`)},nd=(e,t)=>{let s=e[0].dims,n=e[0].dataType,i=s.length,a=e[1].dims,o=e[1].dataType,u=Le.normalizeAxis(t.axis,i),p=s[u],h=a.slice(0),k=Le.size(h),E=qe("input",n,i),d=qe("indicesInput",o,a.length),z=It("output",n,h.length),B=[{type:12,data:k},{type:6,data:p},{type:12,data:u}];return B.push(...yt(s,a,h)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:h,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:B}),getShaderSource:V=>` + ${V.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(E,d,z)} + ${V.mainStart()} + ${V.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${z.offsetToIndices("global_idx")}; + + var idx = ${d.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${E.type.indices}(outputIndices); + ${E.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${E.getByIndices("inputIndices")}; + + ${z.setByOffset("global_idx","value")}; + }`}},bi=e=>Bt({axis:e.axis}),rp=(e,t)=>{let s=e.inputs;rd(s),e.compute(nd(e.inputs,t))}}),id,od,ad,ld,ud=g(()=>{zt(),Ot(),Yt(),id=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},od=(e,t)=>{let s=e[0].dims.slice(),n=e[1].dims.slice(),[i,a,o]=Fr.getShapeOfGemmResult(s,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),u=[i,a];if(!u)throw new Error("Can't use gemm on the given tensors");let p=16,h=Math.ceil(a/p),k=Math.ceil(i/p),E=!0,d=Le.size(u),z=[{type:12,data:E?h:d},{type:12,data:i},{type:12,data:a},{type:12,data:o},{type:1,data:t.alpha},{type:1,data:t.beta}],B=["type","type"];e.length===3&&(z.push(...yt(e[2].dims)),B.push("rank")),z.push(...yt(u));let V=ee=>{let Q="";t.transA&&t.transB?Q="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?Q="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?Q="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(Q="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let he=t.alpha===1?"":"value *= uniforms.alpha;",pe=qe("a",e[0].dataType,e[0].dims),Me=qe("b",e[1].dataType,e[1].dims),Fe=pe.type.value,De=null,Ye=[pe,Me];e.length===3&&(De=qe("c",e[2].dataType,e[2].dims.length),Ye.push(De));let at=It("output",e[0].dataType,u.length);Ye.push(at);let Pt=[{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` + ${ee.registerUniforms(Pt).declareVariables(...Ye)} + + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${Fe}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${Q} + } + + ${he} + ${De!=null?`let cOffset = ${De.broadcastedIndicesToOffset("vec2(m, n)",at)}; value += ${Fe}(uniforms.beta) * ${De.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},Z=ee=>{let Q=qe("a",e[0].dataType,e[0].dims),he=qe("b",e[1].dataType,e[1].dims),pe=null,Me=[Q,he];e.length===3&&(pe=qe("c",e[2].dataType,e[2].dims.length),Me.push(pe));let Fe=It("output",e[0].dataType,u.length);Me.push(Fe);let De=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],Ye="",at="";t.transA&&t.transB?(at=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${Q.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${he.type.value}(0); + } + `,Ye="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(at=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${Q.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${he.type.value}(0); + } + `,Ye="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(at=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${Q.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${he.type.value}(0); + } + `,Ye="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(at=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${Q.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${he.type.value}(0); + } + `,Ye="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let Pt=t.alpha===1?"":"value *= uniforms.alpha;";return` + ${ee.registerUniforms(De).declareVariables(...Me)} + var tile_a: array, ${p}>; + var tile_b: array, ${p}>; + ${ee.mainStart([p,p,1])} + let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${p}; + let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${p}; + let num_tiles = (uniforms.K - 1) / ${p} + 1; + var k_start = 0u; + var value = ${Fe.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${at} + k_start = k_start + ${p}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${p}; k++) { + ${Ye} + } + workgroupBarrier(); + } + + ${Pt} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${pe!=null?`let cOffset = ${pe.broadcastedIndicesToOffset("vec2(m, n)",Fe)}; value += ${Fe.type.value}(uniforms.beta) * ${pe.getByOffset("cOffset")};`:""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`};return E?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:h*k},programUniforms:z}),getShaderSource:Z}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:z}),getShaderSource:V}},ad=e=>{let t=e.transA,s=e.transB,n=e.alpha,i=e.beta;return{transA:t,transB:s,alpha:n,beta:i,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},ld=(e,t)=>{id(e.inputs),e.compute(od(e.inputs,t))}}),Er,Lr,Qr,an,dd,ta,cd,pd,vi,hd,md,fd,_d,sa,ra=g(()=>{zt(),Ot(),rs(),Yt(),[Er,Lr,Qr,an]=[0,1,2,3],dd=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},ta=` + fn gs_get_cubic_coeffs(x: f32) -> vec4 { + let cubic_alpha = -0.75f; + let x_abs = abs(x); + var coeffs: vec4; + coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); + coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); + coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); + coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); + return coeffs; + } +`,cd=e=>` + fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { + var v: vec4; + var coeffs = gs_get_cubic_coeffs(x); + for (var i = 0; i < 4; i++) { + v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3]; + } + coeffs = gs_get_cubic_coeffs(y); + let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); + return pixel; + } +`,pd=e=>` + fn gs_denormalize(n: f32, length: i32) -> f32 { + ${e.alignCorners===0?` + // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] + return ((n + 1.0) * f32(length) - 1.0) / 2.0; + `:` + // alignCorners: true => [-1, 1] to [0, length - 1] + return (n + 1.0) / 2.0 * (f32(length - 1)); + `} + } +`,vi=e=>` + ${e.paddingMode==="reflection"?` + fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { + var dx = 0.0; + var fx = f32(x); + let range = x_max - x_min; + if (fx < x_min) { + dx = x_min - fx; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_min + r; + } else { + fx = x_max - r; + } + } else if (fx > x_max) { + dx = fx - x_max; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_max - r; + } else { + fx = x_min + r; + } + } + return u32(fx); + }`:""} +`,hd=(e,t,s)=>` + fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} { + var pixel = ${t}(0); + var indices = vec4(0); + indices[${Er}] = batch; + indices[${Lr}] = channel;`+(()=>{switch(s.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${Qr}] = u32(r); + indices[${an}] = u32(c); + } + `;case"border":return` + indices[${Qr}] = u32(clamp(r, 0, H - 1)); + indices[${an}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${Qr}] = gs_reflect(r, border[1], border[3]); + indices[${an}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${s.paddingMode} is not supported`)}})()+` + return ${e.getByIndices("indices")}; + } +`,md=(e,t,s)=>(()=>{switch(s.mode){case"nearest":return` + let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${Er}], indices[${Lr}], border); + `;case"bilinear":return` + let x1 = i32(floor(x)); + let y1 = i32(floor(y)); + let x2 = x1 + 1; + let y2 = y1 + 1; + + let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${Er}], indices[${Lr}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Er}], indices[${Lr}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Er}], indices[${Lr}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Er}], indices[${Lr}], border); + + let dx2 = ${t}(f32(x2) - x); + let dx1 = ${t}(x - f32(x1)); + let dy2 = ${t}(f32(y2) - y); + let dy1 = ${t}(y - f32(y1)); + let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); + `;case"bicubic":return` + let x0 = i32(floor(x)) - 1; + let y0 = i32(floor(y)) - 1; + var p: mat4x4<${t}>; + for (var h = 0; h < 4; h++) { + for (var w = 0; w < 4; w++) { + p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${Er}], indices[${Lr}], border); + } + } + + let dx = x - f32(x0 + 1); + let dy = y - f32(y0 + 1); + let result = gs_bicubic_interpolate(p, dx, dy); + `;default:throw new Error(`mode ${s.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,fd=(e,t)=>{let s=qe("x",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],i=qe("grid",e[1].dataType,n.length,2),a=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(a=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[Er,Lr,Qr,an]=[0,3,1,2]);let o=It("output",e[0].dataType,a.length),u=s.type.value,p=Le.size(a),h=[{type:12,data:p},...yt(e[0].dims,n,a)],k=E=>` + ${E.registerUniform("output_size","u32").declareVariables(s,i,o)} + ${ta} + ${cd(u)} + ${pd(t)} + ${vi(t)} + ${hd(s,u,t)} + + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${Qr}]); + let W_in = i32(uniforms.x_shape[${an}]); + + ${t.alignCorners===0?` + let x_min = -0.5; + let x_max = f32(W_in) - 0.5; + let y_min = -0.5; + let y_max = f32(H_in) - 0.5; + `:` + let x_min = 0.0; + let x_max = f32(W_in) - 1.0; + let y_min = 0.0; + let y_max = f32(H_in) - 1.0; + `}; + let border = vec4(x_min, y_min, x_max, y_max); + + let indices = ${o.offsetToIndices("global_idx")}; + var grid_indices = vec3(indices[${Er}], indices[${Qr}], indices[${an}]); + let nxy = ${i.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${md(o,u,t)} + }`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:E=>{let d=Le.size(a);return{outputs:[{dims:a,dataType:E[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:h}},getShaderSource:k}},_d=(e,t)=>{dd(e.inputs),e.compute(fd(e.inputs,t))},sa=e=>Bt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),ir,gd,wd,xi,yd,Gn,na,Md=g(()=>{zt(),Ot(),rs(),ue(),no(),Yt(),Kr(),ir=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,gd=(e,t)=>{let s=e[0],n=ir(e,1),i=ir(e,2),a=ir(e,3),o=ir(e,4),u=ir(e,5),p=ir(e,6),h=ir(e,7);if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let k=s.dims[0],E=s.dims[1],d=s.dims.length===3?s.dims[2]:t.numHeads*s.dims[4],z=E,B=0,V=0,Z=Math.floor(d/t.numHeads);if(p&&h&&Le.size(p.dims)&&Le.size(h.dims)){if(p.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(p.dims[0]!==k||p.dims[1]!==t.numHeads||p.dims[3]!==Z)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(h.dims[0]!==k||h.dims[1]!==t.numHeads||h.dims[3]!==Z)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(p.dims[2]!==h.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(h.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');B=p.dims[2],V=p.dims[2]}else if(p&&Le.size(p.dims)||h&&Le.size(h.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let ee;if(n&&Le.size(n.dims)>0){if(s.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(s.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==s.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');ee=2,z=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==Z)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');ee=5,z=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==Z)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');ee=0,z=n.dims[2]}}else{if(s.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(s.dims[2]!==t.numHeads||s.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');ee=3}if(a&&Le.size(a.dims)>0){if(a.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let Q=B+z,he=0;if(o&&Le.size(o.dims)>0){he=8;let De=o.dims;throw De.length===1?De[0]===k?he=1:De[0]===3*k+2&&(he=3):De.length===2&&De[0]===k&&De[1]===Q&&(he=5),he===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let pe=!1,Me=d;if(i&&Le.size(i.dims)>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(z!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');Me=i.dims[2]}else{if(z!==i.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');Me=i.dims[1]*i.dims[3],pe=!0}}let Fe=!1;if(o&&Le.size(o.dims)>0)throw new Error("Key padding mask is not supported");if(u&&Le.size(u.dims)>0){if(u.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(u.dims[0]!==k||u.dims[1]!==t.numHeads||u.dims[2]!==E||u.dims[3]!==Q)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:k,sequenceLength:E,pastSequenceLength:B,kvSequenceLength:z,totalSequenceLength:Q,maxSequenceLength:V,inputHiddenSize:0,hiddenSize:d,vHiddenSize:Me,headSize:Z,vHeadSize:Math.floor(Me/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:he,scale:t.scale,broadcastResPosBias:Fe,passPastInKv:pe,qkvFormat:ee}},wd=e=>Bt({...e}),xi=Bt({perm:[0,2,1,3]}),yd=(e,t,s,n,i,a,o)=>{let u=[n,i,a],p=Le.size(u),h=[{type:12,data:p},{type:12,data:o},{type:12,data:a}],k=E=>{let d=It("qkv_with_bias",t.dataType,u),z=qe("qkv",t.dataType,u),B=qe("bias",s.dataType,u),V=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${E.registerUniforms(V).declareVariables(z,B,d)} + ${E.mainStart()} + ${E.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 e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:u,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:k},{inputs:[t,s],outputs:[-1]})[0]},Gn=(e,t,s,n,i,a,o,u)=>{let p=a;if(o&&Le.size(o.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return p=yd(e,a,o,t,n,s*i,u),p=p.reshape([t,n,s,i]),s===1||n===1?p:e.compute(hr(p,xi.perm),{inputs:[p],outputs:[-1]})[0]}else return a.dims.length===3&&(p=a.reshape([t,n,s,i])),s===1||n===1?p:e.compute(hr(p,xi.perm),{inputs:[p],outputs:[-1]})[0]},na=(e,t)=>{let s=gd(e.inputs,t),n=e.inputs[0],i=ir(e.inputs,1),a=ir(e.inputs,2),o=ir(e.inputs,3),u=ir(e.inputs,4),p=ir(e.inputs,5),h=ir(e.inputs,6),k=ir(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if((i==null?void 0:i.dims.length)===5)throw new Error("Packed KV is not implemented");let E=i&&a&&i.dims.length===4&&a.dims.length===4,d=Gn(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,n,o,0);if(E)return Rn(e,d,i,a,u,void 0,h,k,p,s);if(!i||!a)throw new Error("key and value must be provided");let z=Gn(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.headSize,i,o,s.hiddenSize),B=Gn(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.vHeadSize,a,o,2*s.hiddenSize);Rn(e,d,z,B,u,void 0,h,k,p,s)}}),bd,ia,ip,op,Ti,oa,vd,xd=g(()=>{zt(),Ot(),rs(),Yt(),bd=e=>{if(!e||e.length<1)throw new Error("too few inputs")},ia=(e,t)=>{let s=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(i=>s.push(Number(i))),n=s.length),Bt({numOutputs:n,axis:t.axis,splitSizes:s})},ip=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${$t("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,op=e=>{let t=e.length,s=[];for(let n=0;n{let s=e[0].dims,n=Le.size(s),i=e[0].dataType,a=Le.normalizeAxis(t.axis,s.length),o=new Array(t.numOutputs),u=qe("input",i,s.length),p=new Array(t.numOutputs),h=[],k=[],E=0,d=[{type:12,data:n}];for(let B=0;B` + ${B.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",p.length).declareVariables(u,...o)} + ${ip(p.length)} + ${op(o)} + + ${B.mainStart()} + ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${u.offsetToIndices("global_idx")}; + var index = ${u.indicesGet("indices",a)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${$t("uniforms.size_in_split_axis","output_number - 1u",p.length)}; + ${u.indicesSet("indices",a,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:z,getRunData:()=>({outputs:h,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:d})}},oa=(e,t)=>{bd(e.inputs);let s=e.inputs.length===1?t:ia(e.inputs,t);e.compute(Ti(e.inputs,s),{inputs:[0]})},vd=e=>{let t=e.axis,s=e.splitSizes,n=e.numOutputs<0?s.length:e.numOutputs;if(n!==s.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Bt({axis:t,numOutputs:n,splitSizes:s})}}),aa,Td,la,ua,ap=g(()=>{rs(),no(),Md(),xd(),Kr(),aa=(e,t)=>{if(t.doRotary)throw new Error("GroupQuerryAttention do_rotary attribute is not supported");if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let s=e[0],n=e[1],i=e[2],a=e[3],o=e[4];if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let u=!1,p=s.dims[0],h=s.dims[1],k=s.dims.length===3?u?s.dims[2]/3:s.dims[2]:t.numHeads*s.dims[4],E=h,d=0,z=!n||n.dims.length===0,B=Math.floor(z?k/(t.numHeads+2*t.kvNumHeads):k/t.numHeads);z&&(k=B*t.numHeads);let V=a&&a.dims.length!==0,Z=o&&o.dims.length!==0;if(V&&a.dims.length===4&&a.dims[0]===p&&a.dims[1]!==t.kvNumHeads&&a.dims[2]===t.kvNumHeads&&a.dims[3]===B)throw new Error("BSNH pastKey/pastValue is not supported");if(V&&Z){if(a.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(o.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');d=a.dims[2]}else if(V||Z)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let ee=1;if(n&&n.dims.length>0){if(s.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(s.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(s.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');E=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==B)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');E=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==B)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');E=n.dims[2]}}else{if(s.dims.length!==3&&s.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(s.dims.length===5&&(s.dims[2]!==t.numHeads||s.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');ee=3}let Q=0,he=!1,pe=t.kvNumHeads?B*t.kvNumHeads:k;if(i&&i.dims.length>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(E!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');pe=i.dims[2]}else{if(E!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');pe=i.dims[1]*i.dims[3],he=!0}}let Me=e.length>4?e[5]:void 0;if(Me&&Me.dims.length!==1&&Me.dims[0]!==p)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:p,sequenceLength:h,pastSequenceLength:d,kvSequenceLength:E,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:k,vHiddenSize:pe,headSize:B,vHeadSize:Math.floor(pe/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:Q,scale:t.scale,broadcastResPosBias:!1,passPastInKv:he,qkvFormat:ee}},Td=Bt({perm:[0,2,1,3]}),la=(e,t,s)=>{let n=t,i=s.kvNumHeads;return t.dims.length===3&&s.kvSequenceLength!==0&&(n=t.reshape([s.batchSize,s.kvSequenceLength,i,s.headSize]),n=e.compute(hr(n,Td.perm),{inputs:[n],outputs:[-1]})[0]),n},ua=(e,t)=>{var Z;let s=aa(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((Z=e.inputs[1])==null?void 0:Z.dims.length)===5)throw new Error("Packed KV is not implemented");let n=e.inputs[0],i=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,a=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,o=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,u=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,p=e.inputs.length>4?e.inputs[5]:void 0,h=e.inputs.length>5?e.inputs[6]:void 0,k=s.kvNumHeads?s.kvNumHeads:s.numHeads,E=Bt({axis:2,numOutputs:3,splitSizes:[s.numHeads*s.headSize,k*s.headSize,k*s.headSize]}),[d,z,B]=!i&&!a?e.compute(Ti([n],E),{inputs:[n],outputs:[-1,-1,-1]}):[n,i,a],V=Gn(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,d,void 0,0);Rn(e,V,la(e,z,s),la(e,B,s),void 0,void 0,o,u,void 0,s,p,h)}}),da,ca,Pd,Ed,lp=g(()=>{zt(),Ot(),Kr(),Yt(),da=(e,t,s,n,i,a,o,u)=>{let p=qt(a),h=p===1?"f32":`vec${p}f`,k=p===1?"vec2f":`mat2x${p}f`,E=i*o,d=64;E===1&&(d=256);let z=[i,o,a/p],B=[i,o,2],V=["rank","type","type"],Z=[];Z.push(...yt(z,B));let ee=Q=>{let he=qe("x",t.dataType,3,p),pe=qe("scale",s.dataType,s.dims),Me=qe("bias",n.dataType,n.dims),Fe=It("output",1,3,2),De=[he,pe,Me,Fe];return` + var workgroup_shared : array<${k}, ${d}>; + const workgroup_size = ${d}u; + ${Q.declareVariables(...De)} + ${Q.mainStart(d)} + let batch = workgroup_index / uniforms.x_shape[1]; + let channel = workgroup_index % uniforms.x_shape[1]; + let hight = uniforms.x_shape[2]; + // initialize workgroup memory + var sum = ${h}(0); + var squared_sum = ${h}(0); + for (var h = local_idx; h < hight; h += workgroup_size) { + let value = ${h}(${he.get("batch","channel","h")}); + sum += value; + squared_sum += value * value; + } + workgroup_shared[local_idx] = ${k}(sum, squared_sum); + workgroupBarrier(); + + for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { + if (local_idx < currSize) { + workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; + } + workgroupBarrier(); + } + if (local_idx == 0) { + let sum_final = ${Gs("workgroup_shared[0][0]",p)} / f32(hight * ${p}); + let squared_sum_final = ${Gs("workgroup_shared[0][1]",p)} / f32(hight * ${p}); + + let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${u})); + let channel_scale = inv_std_dev * f32(scale[channel]); + let channel_shift = f32(bias[channel]) - sum_final * channel_scale; + output[workgroup_index] = vec2f(channel_scale, channel_shift); + } + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${p};${u};${d}`,inputDependencies:V},getRunData:()=>({outputs:[{dims:B,dataType:1}],dispatchGroup:{x:E},programUniforms:Z}),getShaderSource:ee},{inputs:[t,s,n],outputs:[-1]})[0]},ca=(e,t,s)=>{let n=t[0].dims,i=n,a=2,o=n[0],u=n[1],p=Le.sizeFromDimension(n,a),h=qt(p),k=Le.size(i)/h,E=da(e,t[0],t[1],t[2],o,p,u,s.epsilon),d=[o,u,p/h],z=[o,u],B=["type","none"],V=Z=>{let ee=qe("x",t[0].dataType,d.length,h),Q=qe("scale_shift",1,z.length,2),he=It("output",t[0].dataType,d.length,h),pe=[ee,Q,he];return` + ${Z.registerUniform("output_size","u32").declareVariables(...pe)} + ${Z.mainStart()} + ${Z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${he.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${Q.getByIndices("vec2(batch, channel)")}; + let value = ${ee.getByOffset("global_idx")} * ${he.type.value}(scale_shift.x) + ${he.type.value}(scale_shift.y); + ${he.setByOffset("global_idx","value")}; + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${h}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:[{type:12,data:k},...yt(d,z,d)]}),getShaderSource:V},{inputs:[t[0],E]})},Pd=(e,t,s)=>{let n=t[0].dims,i=n,a=n[0],o=n[n.length-1],u=Le.sizeFromDimension(n,1)/o,p=qt(o),h=Le.size(i)/p,k=[{type:12,data:u},{type:12,data:Math.floor(o/p)}],E=["type","type"],d=!1,z=[0,n.length-1];for(let ee=0;een[z[Q]])),V=da(e,B,t[1],t[2],a,u,o,s.epsilon),Z=ee=>{let Q=ms(t[0].dataType),he=p===1?"vec2f":`mat${p}x2f`,pe=De=>{let Ye=De===0?"x":"y",at=p===1?"f32":`vec${p}f`;switch(p){case 1:return`${Q}(${at}(scale.${Ye}))`;case 2:return`vec2<${Q}>(${at}(scale[0].${Ye}, scale[1].${Ye}))`;case 4:return`vec4<${Q}>(${at}(scale[0].${Ye}, scale[1].${Ye}, scale[2].${Ye}, scale[3].${Ye}))`;default:throw new Error(`Not supported compoents ${p}`)}},Me=qe("input",t[0].dataType,t[0].dims,p),Fe=It("output",t[0].dataType,i,p);return` + @group(0) @binding(0) var input : array<${Me.type.storage}>; + @group(0) @binding(1) var scale_input : array<${he}>; + @group(0) @binding(2) var output : array<${Fe.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${ee.mainStart()} + let current_image_number = global_idx / (uniforms.C * uniforms.H); + let current_channel_number = global_idx % uniforms.C; + + let scale_offset = current_image_number * uniforms.C + current_channel_number; + let scale = scale_input[scale_offset]; + output[global_idx] = fma(input[global_idx], ${pe(0)}, ${pe(1)}); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${p}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:k}),getShaderSource:Z},{inputs:[t[0],V]})},Ed=(e,t)=>{t.format==="NHWC"?Pd(e,e.inputs,t):ca(e,e.inputs,t)}}),Cd,kd,Sd,up=g(()=>{zt(),Ot(),Yt(),Cd=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},kd=(e,t,s)=>{let n=t.simplified,i=e[0].dims,a=e[1],o=!n&&e[2],u=i,p=Le.normalizeAxis(t.axis,i.length),h=Le.sizeToDimension(i,p),k=Le.sizeFromDimension(i,p),E=Le.size(a.dims),d=o?Le.size(o.dims):0;if(E!==k||o&&d!==k)throw new Error(`Size of X.shape()[axis:] == ${k}. + Size of scale and bias (if provided) must match this. + Got scale size of ${E} and bias size of ${d}`);let z=[];for(let Me=0;Me1,Q=s>2,he=Me=>{let Fe=ms(e[0].dataType),De=[qe("x",e[0].dataType,e[0].dims,B),qe("scale",a.dataType,a.dims,B)];o&&De.push(qe("bias",o.dataType,o.dims,B)),De.push(It("output",e[0].dataType,u,B)),ee&&De.push(It("mean_data_output",1,z)),Q&&De.push(It("inv_std_output",1,z));let Ye=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${Me.registerUniforms(Ye).declareVariables(...De)} + ${Me.mainStart()} + ${Me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${Ls("f32",B)}; + var mean_square_vector = ${Ls("f32",B)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${As(Fe,B,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Gs("mean_vector",B)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Gs("mean_square_vector",B)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${As(Fe,B,"x[j + offset]")}; + let f32scale = ${As(Fe,B,"scale[j]")}; + output[j + offset] = ${De[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale + ${o?`+ ${As(Fe,B,"bias[j]")}`:""} + ); + } + + ${ee?"mean_data_output[global_idx] = mean":""}; + ${Q?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},pe=[{dims:u,dataType:e[0].dataType}];return ee&&pe.push({dims:z,dataType:1}),Q&&pe.push({dims:z,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${B};${s};${n}`,inputDependencies:V},getRunData:()=>({outputs:pe,dispatchGroup:{x:Math.ceil(h/64)},programUniforms:Z}),getShaderSource:he}},Sd=(e,t)=>{Cd(e.inputs),e.compute(kd(e.inputs,t,e.outputCount))}}),$d,Ad,Id=g(()=>{Ot(),Oo(),Bo(),$d=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},Ad=e=>{$d(e.inputs);let t=Ws.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let s=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];if(s<8&&n<8)e.compute(Io(e.inputs,{activation:""},t));else{let i=t[t.length-2],a=Le.size(e.inputs[0].dims.slice(0,-2)),o=Le.size(e.inputs[1].dims.slice(0,-2));if(a!==1&&i===1&&o===1){let u=e.inputs[0].reshape([1,a,n]),p=e.inputs[1].reshape([1,n,s]),h=[1,a,s],k=[u,p];e.compute(hi(k,{activation:""},t,h),{inputs:k})}else e.compute(hi(e.inputs,{activation:""},t))}}}),Od,Fd,pa,Dd,Ld,ys=g(()=>{zt(),Ot(),rs(),Yt(),Od=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let s=e[0],n=s.dims.length;if(s.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let i=Math.floor((t.k+t.blockSize-1)/t.blockSize),a=t.blockSize/8*t.bits,o=e[1];if(!Le.areEqual(o.dims,[t.n,i,a]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let u=e[2].dims;if(Le.size(u)!==t.n*i)throw new Error("scales input size error.");if(e.length===4){let p=e[3].dims,h=t.bits>4?t.n*i:t.n*Math.floor((i+1)/2);if(Le.size(p)!==h)throw new Error("zeroPoints input size error.")}},Fd=(e,t)=>{let s=e[0].dims,n=s.length,i=s[n-2],a=t.k,o=t.n,u=s.slice(0,n-2),p=Le.size(u),h=e[1].dims[2]/4,k=e[0].dataType,E=qt(t.k),d=qt(h),z=qt(o),B=u.concat([i,o]),V=i>1&&o/z%2===0?2:1,Z=Le.size(B)/z/V,ee=64,Q=[],he=[p,i,a/E],pe=Le.convertShape(e[1].dims).slice();pe.splice(-1,1,h/d),Q.push(...yt(he)),Q.push(...yt(pe)),Q.push(...yt(e[2].dims)),e.length===4&&Q.push(...yt(Le.convertShape(e[3].dims)));let Me=[p,i,o/z];Q.push(...yt(Me));let Fe=De=>{let Ye=he.length,at=qe("a",e[0].dataType,Ye,E),Pt=qe("b",12,pe.length,d),Xt=qe("scales",e[2].dataType,e[2].dims.length),Zt=[at,Pt,Xt],bt=e.length===4?qe("zero_points",12,e[3].dims.length):void 0;bt&&Zt.push(bt);let ss=Me.length,St=It("output",e[0].dataType,ss,z),Ft=ms(e[0].dataType),bs=(()=>{switch(E){case 1:return`array<${Ft}, 8>`;case 2:return`mat4x2<${Ft}>`;case 4:return`mat2x4<${Ft}>`;default:throw new Error(`${E}-component is not supported.`)}})(),Ht=()=>{let ot=` + // reuse a data + var input_offset = ${at.indicesToOffset(`${at.type.indices}(batch, row, word_offset)`)}; + var a_data: ${bs}; + for (var j: u32 = 0; j < ${8/E}; j++) { + a_data[j] = ${at.getByOffset("input_offset")}; + input_offset++; + } + `;for(let Et=0;Et> 4) & b_mask); + b_quantized_values = ${bs}(${Array.from({length:4},(cs,Ns)=>`${Ft}(b_value_lower[${Ns}]), ${Ft}(b_value_upper[${Ns}])`).join(", ")}); + b_dequantized_values = ${E===1?`${bs}(${Array.from({length:8},(cs,Ns)=>`(b_quantized_values[${Ns}] - ${bt?`zero_point${Et}`:"zero_point"}) * scale${Et}`).join(", ")});`:`(b_quantized_values - ${bs}(${Array(8).fill(`${bt?`zero_point${Et}`:"zero_point"}`).join(",")})) * scale${Et};`}; + workgroup_shared[local_id.x * ${V} + ${Math.floor(Et/z)}]${z>1?`[${Et%z}]`:""} += ${Array.from({length:8/E},(cs,Ns)=>`${E===1?`a_data[${Ns}] * b_dequantized_values[${Ns}]`:`dot(a_data[${Ns}], b_dequantized_values[${Ns}])`}`).join(" + ")}; + `;return ot},Rt=()=>{let ot=` + var col_index = col * ${z}; + ${bt?` + 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 = ${Ft}(8);`} + `;for(let Et=0;Et> 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 = ${bt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${Et} = ${Ft}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return ot},_s=()=>{let ot=`col_index = col * ${z};`;for(let Et=0;Et; + var b_value_upper: vec4; + var b_quantized_values: ${bs}; + var b_dequantized_values: ${bs};`,ot};return` + var workgroup_shared: array<${St.type.value}, ${V*ee}>; + ${De.declareVariables(...Zt,St)} + ${De.mainStart([ee,1,1])} + let output_indices = ${St.offsetToIndices(`(global_idx / ${ee}) * ${V}`)}; + 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 += ${ee}) { + //process one block + var word_offset: u32 = block * ${t.blockSize/E}; + ${Rt()} + for (var word: u32 = 0; word < ${h}; word += ${d}) { + ${_s()} + for (var i: u32 = 0; i < ${d}; i++) { + ${Ht()} + word_offset += ${8/E}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${V}) { + var output_value: ${St.type.value} = ${St.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${ee}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${V}; + } + ${St.setByIndices(`${St.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${E};${d};${z};${V};${ee}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:B,dataType:k}],dispatchGroup:{x:Z},programUniforms:Q}),getShaderSource:Fe}},pa=(e,t)=>{let s=e[0].dims,n=s.length,i=s[n-2],a=t.k,o=t.n,u=s.slice(0,n-2),p=Le.size(u),h=e[1].dims[2]/4,k=e[0].dataType,E=qt(t.k),d=qt(h),z=u.concat([i,o]),B=128,V=o%8===0?8:o%4===0?4:1,Z=B/V,ee=Z*d*8,Q=ee/E,he=ee/t.blockSize,pe=Le.size(z)/V,Me=[],Fe=[p,i,a/E],De=Le.convertShape(e[1].dims).slice();De.splice(-1,1,h/d),Me.push(...yt(Fe)),Me.push(...yt(De)),Me.push(...yt(e[2].dims)),e.length===4&&Me.push(...yt(Le.convertShape(e[3].dims)));let Ye=[p,i,o];Me.push(...yt(Ye));let at=Pt=>{let Xt=Fe.length,Zt=qe("a",e[0].dataType,Xt,E),bt=qe("b",12,De.length,d),ss=qe("scales",e[2].dataType,e[2].dims.length),St=[Zt,bt,ss],Ft=e.length===4?qe("zero_points",12,e[3].dims.length):void 0;Ft&&St.push(Ft);let bs=Ye.length,Ht=It("output",e[0].dataType,bs),Rt=ms(e[0].dataType),_s=()=>{switch(E){case 1:return` + let a_data0 = vec4<${Rt}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${Rt}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` + let a_data0 = vec4<${Rt}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${Rt}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` + let a_data0 = sub_a[word_offset]; + let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${E}-component is not supported.`)}};return` + var sub_a: array<${Zt.type.value}, ${Q}>; + var inter_results: array, ${V}>; + ${Pt.declareVariables(...St,Ht)} + ${Pt.mainStart([Z,V,1])} + let output_indices = ${Ht.offsetToIndices(`workgroup_index * ${V}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let n_blocks_per_col = uniforms.b_shape[1]; + let num_tiles = (n_blocks_per_col - 1) / ${he} + 1; + + // Loop over shared dimension. + for (var tile: u32 = 0; tile < num_tiles; tile += 1) { + let a_col_start = tile * ${Q}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${Q}; a_offset += ${B}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${Zt.getByIndices(`${Zt.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${Zt.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${he} + local_id.x; + ${Ft?` + let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; + let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); + let zero_point_word_index = zero_point_byte_count >> 0x2u; + let zero_point_byte_offset = zero_point_byte_count & 0x3u; + let zero_point_nibble_offset: u32 = block & 0x1u; + let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + let zero_point_word = ${Ft.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${Rt}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${Rt}(8);`} + let scale = ${ss.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${bt.getByIndices(`${bt.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${t.blockSize/E}; + for (var i: u32 = 0; i < ${d}; i++) { + ${_s()} + let b_value = ${d===1?"b_data":"b_data[i]"}; + let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); + let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); + let b_quantized_values = mat2x4<${Rt}>(${Array.from({length:4},(ot,Et)=>`${Rt}(b_value_lower[${Et}]), ${Rt}(b_value_upper[${Et}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${Rt}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(ot,Et)=>`${`dot(a_data${Et}, b_dequantized_values[${Et}])`}`).join(" + ")}; + word_offset += ${8/E}; + } + workgroupBarrier(); + } + + if (local_idx < ${V}) { + var output_value: ${Ht.type.value} = ${Ht.type.value}(0); + for (var b = 0u; b < ${Z}; b++) { + output_value += inter_results[local_idx][b]; + } + if (col + local_idx < uniforms.output_shape[2]) + { + ${Ht.setByIndices(`${Ht.type.indices}(batch, row, col + local_idx)`,"output_value")} + } + } + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${E};${d};${Z};${V}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:z,dataType:k}],dispatchGroup:{x:pe},programUniforms:Me}),getShaderSource:at}},Dd=(e,t)=>{Od(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(pa(e.inputs,t)):e.compute(Fd(e.inputs,t))},Ld=e=>Bt(e)}),dp,cp,pp,ha,zd,Bd,Rd,Nd,ma,jd=g(()=>{zt(),Ot(),Yt(),dp=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},cp=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${$t("uniforms.pads",i,s)}; + if (k < 0) { + break; + } + if (k >= i32(${$t("uniforms.x_shape",i,t)})) { + break; + } + offset += k * i32(${$t("uniforms.x_strides",i,t)}); + `;return` + value = ${e.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + } + `},pp=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${$t("uniforms.pads",i,s)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${$t("uniforms.x_shape",i,t)}) - 1); + k = k % _2n_1; + if(k >= i32(${$t("uniforms.x_shape",i,t)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${$t("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},ha=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${$t("uniforms.pads",i,s)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${$t("uniforms.x_shape",i,t)})) { + k = i32(${$t("uniforms.x_shape",i,t)}) - 1; + } + offset += k * i32(${$t("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},zd=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${$t("uniforms.pads",i,s)}; + if (k < 0) { + k += i32(${$t("uniforms.x_shape",i,t)}]); + } + if (k >= i32(${$t("uniforms.x_shape",i,t)})) { + k -= i32(${$t("uniforms.x_shape",i,t)}); + } + offset += k * i32(${$t("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},Bd=(e,t,s)=>{switch(s.mode){case 0:return cp(e,t,s.pads.length);case 1:return pp(e,t,s.pads.length);case 2:return ha(e,t,s.pads.length);case 3:return zd(e,t,s.pads.length);default:throw new Error("Invalid mode")}},Rd=(e,t)=>{let s=Le.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,i=Le.size(s),a=[{type:12,data:i},{type:6,data:t.pads}],o=e.length>=3&&e[2].data;t.mode===0&&a.push({type:o?e[2].dataType:1,data:t.value}),a.push(...yt(e[0].dims,s));let u=["rank"],p=h=>{let k=It("output",e[0].dataType,s.length),E=qe("x",e[0].dataType,n.length),d=E.type.value,z=Bd(k,n.length,t),B=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&B.push({name:"constant_value",type:o?d:"f32"}),` + ${h.registerUniforms(B).declareVariables(E,k)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${k.offsetToIndices("global_idx")}; + + var value = ${d}(0); + ${z} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${o}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Le.size(s)/64)},programUniforms:a}),getShaderSource:p}},Nd=(e,t)=>{if(e.length>1){let s=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,i=e[0].dims.length,a=new Int32Array(2*i).fill(0);if(e.length>=4){let u=e[3].getBigInt64Array();for(let p=0;pa[Number(p)]=Number(u));let o=[];return a.forEach(u=>o.push(u)),{mode:t.mode,value:n,pads:o}}else return t},ma=(e,t)=>{dp(e.inputs);let s=Nd(e.inputs,t);e.compute(Rd(e.inputs,s),{inputs:[0]})}}),Pi,fa,_a,Ei,Ud,hp,Vd,ga,wa,Wd,Gd,ya,Kd,Hd,Ma,qd,Qd,Xd,mp,fp=g(()=>{We(),zt(),Ot(),Yt(),Pi=e=>{if(O.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},fa=(e,t,s)=>{let n=t.format==="NHWC",i=e.dims.slice();n&&i.splice(1,0,i.pop());let a=Object.hasOwnProperty.call(t,"dilations"),o=t.kernelShape.slice(),u=t.strides.slice(),p=a?t.dilations.slice():[],h=t.pads.slice();Js.adjustPoolAttributes(s,i,o,u,p,h);let k=Js.computePoolOutputShape(s,i,u,p,o,h,t.autoPad),E=Object.assign({},t);a?Object.assign(E,{kernelShape:o,strides:u,pads:h,dilations:p,cacheKey:t.cacheKey}):Object.assign(E,{kernelShape:o,strides:u,pads:h,cacheKey:t.cacheKey});let d=k.slice();return d.push(d.splice(1,1)[0]),[E,n?d:k]},_a=(e,t)=>{let s=t.format==="NHWC",n=Le.size(e),i=Le.size(t.kernelShape),a=[{type:12,data:n},{type:12,data:i}],o=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let u=t.kernelShape[t.kernelShape.length-1],p=t.strides[t.strides.length-1],h=t.pads[t.pads.length/2-1],k=t.pads[t.pads.length-1],E=!!(h+k);a.push({type:12,data:u},{type:12,data:p},{type:12,data:h},{type:12,data:k}),o.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let d=!1;if(t.kernelShape.length===2){let z=t.kernelShape[t.kernelShape.length-2],B=t.strides[t.strides.length-2],V=t.pads[t.pads.length/2-2],Z=t.pads[t.pads.length-2];d=!!(V+Z),a.push({type:12,data:z},{type:12,data:B},{type:12,data:V},{type:12,data:Z}),o.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[a,o,!0,E,d]}else{if(s)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=Le.computeStrides(t.kernelShape);a.push({type:12,data:u},{type:12,data:t.pads},{type:12,data:t.strides}),o.push({name:"kernelStrides",type:"u32",length:u.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let p=t.pads.reduce((h,k)=>h+k);return[a,o,!!p,!1,!1]}},Ei=(e,t,s,n,i,a,o,u,p,h,k,E)=>{let d=i.format==="NHWC",z=t.type.value,B=It("output",t.type.tensor,n);if(i.kernelShape.length<=2){let V="",Z="",ee="",Q=s-(d?2:1);if(k?V=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${Q}] = indices[${Q}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${Q}] < 0 || xIndices[${Q}] + >= uniforms.x_shape[${Q}]) { + pad++; + continue; + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`:V=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${Q}] = indices[${Q}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`,i.kernelShape.length===2){let he=s-(d?3:2);E?Z=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${he}] = indices[${he}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${he}] < 0 || xIndices[${he}] >= uniforms.x_shape[${he}]) { + pad += i32(uniforms.kw); + continue; + } + `:Z=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${he}] = indices[${he}] * uniforms.sh - uniforms.phStart + j; + `,ee=` + } + `}return` + ${e.registerUniforms(p).declareVariables(t,B)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${B.offsetToIndices("global_idx")}; + var xIndices = ${B.offsetToIndices("global_idx")}; + + var value = ${z}(${u}); + var pad = 0; + ${Z} + ${V} + ${ee} + ${o} + + output[global_idx] = value; + }`}else{if(d)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let V=i.kernelShape.length,Z=i.pads.length,ee="";return h?ee=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + }`:ee=` + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${a} + `,` + ${e.registerUniforms(p).declareVariables(t,B)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${B.offsetToIndices("global_idx")}; + var xIndices = ${B.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${z}(${u}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${V-1}u; j++) { + offsets[j] = offset / ${$t("uniforms.kernelStrides","j",V)}; + offset -= offsets[j] * ${$t("uniforms.kernelStrides","j",V)}; + } + offsets[${V-1}] = offset; + + isPad = false; + for (var j = ${s-V}u; j < ${s}u; j++) { + xIndices[j] = indices[j] * ${$t("uniforms.strides",`j - ${s-V}u`,V)} + + offsets[j - ${s-V}u] - ${$t("uniforms.pads","j - 2u",Z)}; + ${ee} + } + ${o} + + output[global_idx] = value; + }`}},Ud=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,hp=e=>`${Ud(e)};${e.countIncludePad}`,Vd=e=>`${Ud(e)};${e.storageOrder};${e.dilations}`,ga=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),wa=(e,t,s,n)=>{let[i,a]=fa(t,n,s),o=qe("x",t.dataType,t.dims.length),u=o.type.value,p="value += x_val;",h="";i.countIncludePad?h+=`value /= ${u}(uniforms.kernelSize);`:h+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[k,E,d,z,B]=_a(a,i);k.push(...yt(t.dims,a));let V=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${d};${z};${B}`,inputDependencies:V},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Le.size(a)/64)},programUniforms:k}),getShaderSource:Z=>Ei(Z,o,t.dims.length,a.length,i,p,h,0,E,d,z,B)}},Wd=e=>{let t=e.count_include_pad!==0,s=ga(e);if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...s,cacheKey:""};return{...n,cacheKey:hp(n)}},Gd=(e,t)=>{Pi(e.inputs),e.compute(wa("AveragePool",e.inputs[0],!1,t))},ya={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Kd=e=>{let t=e.format;return{format:t,...ya,cacheKey:t}},Hd=(e,t)=>{Pi(e.inputs),e.compute(wa("GlobalAveragePool",e.inputs[0],!0,t))},Ma=(e,t,s,n)=>{let[i,a]=fa(t,n,s),o=` + value = max(x_val, value); + `,u="",p=qe("x",t.dataType,t.dims.length),h=["rank"],[k,E,d,z,B]=_a(a,i);return k.push(...yt(t.dims,a)),{name:e,shaderCache:{hint:`${n.cacheKey};${d};${z};${B}`,inputDependencies:h},getRunData:()=>({outputs:[{dims:a,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Le.size(a)/64)},programUniforms:k}),getShaderSource:V=>Ei(V,p,t.dims.length,a.length,i,o,u,t.dataType===10?-65504:-1e5,E,d,z,B)}},qd=(e,t)=>{Pi(e.inputs),e.compute(Ma("MaxPool",e.inputs[0],!1,t))},Qd=e=>{let t=e.storage_order,s=e.dilations,n=ga(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let i={storageOrder:t,dilations:s,...n,cacheKey:""};return{...i,cacheKey:Vd(i)}},Xd=e=>{let t=e.format;return{format:t,...ya,cacheKey:t}},mp=(e,t)=>{Pi(e.inputs),e.compute(Ma("GlobalMaxPool",e.inputs[0],!0,t))}}),Yd,Jd,Zd,ec,_p=g(()=>{zt(),Ot(),rs(),Yt(),Yd=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[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(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((s,n)=>s===e[2].dims[n]).reduce((s,n)=>s&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((i,a)=>a===t.axis||i===e[0].dims[a]).reduce((i,a)=>i&&a,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let s=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(s/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Jd=(e,t)=>{let s=Le.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,i=n===3,a=e[0].dims,o=e[1].dataType,u=Le.size(a),p=n===3||n===2,h=p?[Math.ceil(Le.size(e[0].dims)/4)]:e[0].dims,k=e[1].dims,E=e.length>2?e[2]:void 0,d=E?p?[Math.ceil(Le.size(E.dims)/4)]:E.dims:void 0,z=k.length===0||k.length===1&&k[0]===1,B=z===!1&&k.length===1,V=qt(u),Z=z&&(!p||V===4),ee=Z?V:1,Q=Z&&!p?V:1,he=qe("input",p?12:n,h.length,Q),pe=qe("scale",o,k.length),Me=E?qe("zero_point",p?12:n,d.length):void 0,Fe=It("output",o,a.length,ee),De=[he,pe];Me&&De.push(Me);let Ye=[h,k];E&&Ye.push(d);let at=[{type:12,data:u/ee},{type:12,data:s},{type:12,data:t.blockSize},...yt(...Ye,a)],Pt=Xt=>{let Zt=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${Xt.registerUniforms(Zt).declareVariables(...De,Fe)} + ${Xt.mainStart()} + ${Xt.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${Fe.offsetToIndices("global_idx")}; + + // Set input x + ${p?` + let input = ${he.getByOffset("global_idx / 4")}; + let x_vec = ${i?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${ee===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${he.getByOffset("global_idx")};`}; + + // Set scale input + ${z?`let scale_value= ${pe.getByOffset("0")}`:B?` + let scale_index = ${Fe.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${pe.getByOffset("scale_index")};`:` + var scale_indices: ${pe.type.indices} = output_indices; + let index = ${pe.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${pe.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${pe.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${Me?z?p?` + let zero_point_input = ${Me.getByOffset("0")}; + let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${Me.getByOffset("0")}`:B?p?` + let zero_point_index = ${Fe.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${Me.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${Fe.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${Me.getByOffset("zero_point_index")};`:p?` + let zero_point_offset = ${pe.indicesToOffset("scale_indices")}; + let zero_point_input = ${Me.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${Me.getByIndices("scale_indices")};`:`let zero_point_value = ${p?i?"i32":"u32":he.type.value}(0);`}; + // Compute and write output + ${Fe.setByOffset("global_idx",`${Fe.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:Me?["rank","rank","rank"]:["rank","rank"]},getShaderSource:Pt,getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:Math.ceil(u/ee/64),y:1,z:1},programUniforms:at})}},Zd=(e,t)=>{Yd(e.inputs,t),e.compute(Jd(e.inputs,t))},ec=e=>Bt({axis:e.axis,blockSize:e.blockSize})}),gp,ba,tc,wp=g(()=>{We(),zt(),Yt(),gp=(e,t,s)=>{let n=e===t,i=et&&s>0;if(n||i||a)throw new Error("Range these inputs' contents are invalid.")},ba=(e,t,s,n)=>{let i=Math.abs(Math.ceil((t-e)/s)),a=[i],o=i,u=[{type:12,data:o},{type:n,data:e},{type:n,data:s},...yt(a)],p=h=>{let k=It("output",n,a.length),E=k.type.value,d=[{name:"outputSize",type:"u32"},{name:"start",type:E},{name:"delta",type:E}];return` + ${h.registerUniforms(d).declareVariables(k)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${E}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:p,getRunData:()=>({outputs:[{dims:a,dataType:n}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:u})}},tc=e=>{let t=0,s=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],s=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],s=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),O.webgpu.validateInputContent&&gp(t,s,n),e.compute(ba(t,s,n,e.inputs[0].dataType),{inputs:[]})}}),sc,rc,nc,ic,yp=g(()=>{zt(),Ot(),rs(),Yt(),sc=(e,t,s,n)=>{if(e!=="none"&&n!=="i32"&&n!=="u32"&&n!=="f32")throw new Error(`Input ${n} is not supported with reduction ${e}.`);let i=`{ + var oldValue = 0; + loop { + let newValueF32 =`,a=`; + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`;switch(e){case"none":return`${t}=${s};`;case"add":return n==="i32"||n==="u32"?`atomicAdd(&${t}, bitcast<${n}>(${s}));`:` + ${i}bitcast<${n}>(oldValue) + (${s})${a}`;case"max":return n==="i32"||n==="u32"?`atomicMax(&${t}, bitcast<${n}>(${s}));`:` + ${i}max(bitcast(oldValue), (${s}))${a}`;case"min":return n==="i32"||n==="u32"?`atomicMin(&${t}, bitcast<${n}>(${s}));`:`${i}min(bitcast<${n}>(oldValue), (${s}))${a}`;case"mul":return`${i}(bitcast<${n}>(oldValue) * (${s}))${a}`;default:throw new Error(`Reduction ${e} is not supported.`)}},rc=(e,t)=>{let s=e[0].dims,n=e[1].dims,i=s,a=1,o=Math.ceil(Le.size(n)/a),u=n[n.length-1],p=Le.sizeFromDimension(s,u),h=[{type:12,data:o},{type:12,data:u},{type:12,data:p},...yt(e[1].dims,e[2].dims,i)],k=E=>{let d=qe("indices",e[1].dataType,e[1].dims.length),z=qe("updates",e[2].dataType,e[2].dims.length,a),B=t.reduction!=="none"&&t.reduction!==""?Oa("output",e[0].dataType,i.length):It("output",e[0].dataType,i.length,a);return` + ${E.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(d,z,B)} + ${E.mainStart()} + ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var data_offset = 0u; + let indices_start = uniforms.last_index_dimension * global_idx; + let indices_end = indices_start + uniforms.last_index_dimension; + for (var i = indices_start; i < indices_end; i++) { + var index = i32(indices[i].x); + ${e[0].dims.length===1?` + let element_count_dim = uniforms.output_strides; + let dim_value = uniforms.output_shape;`:` + let element_count_dim = uniforms.output_strides[i - indices_start]; + let dim_value = uniforms.output_shape[i - indices_start + uniforms.last_index_dimension];`} + if (index >= 0) { + if (index >= i32(dim_value)) { + index = i32(dim_value - 1); + } + } else { + if (index < -i32(dim_value)) { + index = 0; + } else { + index += i32(dim_value); + } + } + data_offset += u32((u32(index) * element_count_dim)); + } + + for (var i = 0u; i < uniforms.num_updates_elements; i++) { + let value = updates[uniforms.num_updates_elements * global_idx + i]; + ${sc(t.reduction,"output[data_offset + i]","value",B.type.value)} + } + + }`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:h}),getShaderSource:k}},nc=e=>Bt({reduction:e.reduction}),ic=(e,t)=>{e.compute(rc(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),oc,ac,lc,uc,dc,cc,pc,hc,mc,fc,_c,va,gc,wc,yc,Mc,bc,vc,xc,Mp=g(()=>{zt(),Ot(),rs(),Yt(),oc=(e,t)=>{if(e.every(s=>s>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[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(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},ac=(e,t,s)=>{t.every(i=>i>=0&&i{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(s).fill(1);return t.forEach((i,a)=>n[i]=e[a]),n},lc=(e,t,s,n,i,a)=>{let[o,u,p]=s>10?[1,2,3]:[-1,e.length>1?1:-1,-1],h=e[0].dims.length;if(o>0&&e.length>o&&e[o].dims.length>0)e[o].getFloat32Array().forEach(k=>a.push(k));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(u>0&&e.length>u&&e[u].dims.length===1&&e[u].dims[0]>0){if(e[u].getFloat32Array().forEach(k=>n.push(k)),n.length!==0&&n.length!==h&&s>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");oc(n,t),t.axes.length>0&&ac(n,t.axes,h).forEach((k,E)=>n[E]=k)}if(p>0&&e.length>p&&e[p].dims.length===1&&e[p].dims[0]>0&&(e[p].getBigInt64Array().forEach(k=>i.push(Number(k))),i.length!==0&&i.length!==h&&s>=18&&i.length!==t.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(t.axes.length>0){if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(i.length!==0&&i.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof i<"u"&&n.length>0&&i.length>h)throw new Error("Resize requires only of scales or sizes to be specified")},uc=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return`return ${t}(xResized) / ${t}(xScale);`;case"pytorch_half_pixel":return`if (lengthResized > 1) { + return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5; + } else { + return 0.0; + }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(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 = ${t}(xResized * (lengthOriginal - 1) / (lengthResized - 1)); + let fract = + ${t}(xResized * (lengthOriginal - 1) % (lengthResized - 1)) / ${t}(lengthResized - 1); + return whole + fract; + }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { + return ${t}(roiStart) * ${t}(lengthOriginal - 1) + + (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) / + ${t}(lengthResized - 1); + } else { + return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1); + }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized); + const adjustment = ${t}(lengthResized) / outputWidth; + const center = ${t}(lengthOriginal) / 2; + const offset = center * (1 - adjustment); + return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",dc=(e,t,s)=>`fn getNearestPixelFromOriginal(xOriginal: ${s}, isDownSample: bool) -> ${s} {`+(()=>{switch(e){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(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",cc=(e,t,s)=>{let n=new Array(s).fill(0).concat(new Array(s).fill(1)),i=e.length===0?n:e.slice();return t.length>0?(t.forEach((a,o)=>{n[a]=i[o],n[o+s]=i[t.length+o]}),n):i},pc=(e,t,s,n)=>{let i=[];if(s.length>0)if(n.length>0){if(e.forEach(a=>i.push(a)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((a,o)=>i[a]=s[o])}else s.forEach(a=>i.push(a));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");i=e.map((a,o)=>Math.round(a*t[o]))}return i},hc=(e,t,s)=>{let n=(()=>{switch(s.keepAspectRatioPolicy){case"not_larger":return s.axes.length>0?Math.min(...s.axes.map(a=>t[a]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return s.axes.length>0?Math.max(...s.axes.map(a=>t[a]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${s.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let i=e.slice();return s.axes.length>0?(s.axes.forEach(a=>t[a]=n),s.axes.forEach(a=>i[a]=Math.round(e[a]*t[a]))):(t.fill(n,0,t.length),i.forEach((a,o)=>i[o]=Math.round(a*t[o]))),i},mc=(e,t,s,n,i)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${s.length}> { + var original_indices: array<${e.type.value}, ${s.length}>; + for (var i:u32 = 0; i < ${s.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${$t("uniforms.scales","i",n)}; + var roi_low = ${$t("uniforms.roi","i",i)}; + var roi_hi = ${$t("uniforms.roi",`i + ${t.length}`,i)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${$t("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${$t("uniforms.output_shape","i",s.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,fc=(e,t,s,n,i,a,o)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + for (var i:u32 = 0; i < ${n.length}; i++) { + var output_index = ${t.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${$t("uniforms.scales","i",i)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${$t("uniforms.roi","i",a)}; + var roi_hi = ${$t("uniforms.roi",`i + ${s.length}`,a)}; + var input_shape_i = ${$t("uniforms.input_shape","i",s.length)}; + var output_shape_i = ${$t("uniforms.output_shape","i",n.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${o} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${t.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); + } + } + ${e.indicesSet("input_indices","i"," input_index")} + } + return input_indices; + }`,_c=(e,t)=>` + fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { + for (var i:u32 = 0; i < ${t.length}; i++) { + var input_index = ${e.indicesGet("input_indices","i")}; + if (input_index < 0 || input_index >= ${$t("uniforms.input_shape","i",t.length)}) { + return false; + } + } + return true; + }`,va=(e,t,s,n)=>e.rank>n?` + ${e.indicesSet("input_indices",t,"channel")}; + ${e.indicesSet("input_indices",s,"batch")}; +`:"",gc=(e,t,s,n,i)=>{let[a,o,u,p]=s.length===2?[-1,0,1,-1]:[0,2,3,1],h=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${h} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",o,`max(0, min(row, ${s[o]} - 1))`)}; + ${e.indicesSet("input_indices",u,`max(0, min(col, ${s[u]} - 1))`)}; + ${va(e,p,a,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${h} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${h} = originalIndices[${o}]; + var col:${h} = originalIndices[${u}]; + ${n?`if (row < 0 || row > (${s[o]} - 1) || col < 0 || col > (${s[u]} - 1)) { + return ${i}; + }`:""}; + row = max(0, min(row, ${s[o]} - 1)); + col = max(0, min(col, ${s[u]} - 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 = ${s.length>2?`u32(originalIndices[${p}])`:"0"}; + var batch: u32 = ${s.length>2?`u32(originalIndices[${a}])`:"0"}; + var x11: ${h} = getInputValue(batch, channel, row1, col1); + var x12: ${h} = getInputValue(batch, channel, row1, col2); + var x21: ${h} = getInputValue(batch, channel, row2, col1); + var x22: ${h} = getInputValue(batch, channel, row2, col2); + var dx1: ${h} = abs(row - ${h}(row1)); + var dx2: ${h} = abs(${h}(row2) - row); + var dy1: ${h} = abs(col - ${h}(col1)); + var dy2: ${h} = abs(${h}(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); + }`},wc=(e,t,s,n,i,a,o,u,p,h)=>{let k=s.length===2,[E,d]=k?[0,1]:[2,3],z=e.type.value,B=V=>{let Z=V===E?"row":"col";return` + fn ${Z}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${z} { + var output_index = ${t.indicesGet("output_indices",V)}; + var originalIdx: ${z} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[V]}, + ${n[V]}, ${s[V]}, ${a[V]}, ${a[V]} + ${s.length}); + var fractOriginalIdx: ${z} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${u} && (originalIdx < 0 || originalIdx > (${s[V]} - 1))) { + return ${p}; + } + var data: array<${z}, 4> = array<${z}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${Z}: ${z} = originalIdx + ${z}(i); + if (${Z} < 0 || ${Z} >= ${s[V]}) { + ${h?`coefs[i + 1] = 0.0; + continue;`:u?`return ${p};`:`${Z} = max(0, min(${Z}, ${s[V]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",V,`u32(${Z})`)}; + data[i + 1] = ${V===E?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${B(E)}; + ${B(d)}; + fn getCubicInterpolationCoefs(s: ${z}) -> array<${z}, 4> { + var absS = abs(s); + var coeffs: array<${z}, 4> = array<${z}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${z} = 1.0 - absS; + var twoMinusAbsS: ${z} = 2.0 - absS; + var onePlusAbsS: ${z} = 1.0 + absS; + coeffs[0] = ((${o} * onePlusAbsS - 5 * ${o}) * onePlusAbsS + 8 * ${o}) * onePlusAbsS - 4 * ${o}; + coeffs[1] = ((${o} + 2) * absS - (${o} + 3)) * absS * absS + 1; + coeffs[2] = ((${o} + 2) * oneMinusAbsS - (${o} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${o} * twoMinusAbsS - 5 * ${o}) * twoMinusAbsS + 8 * ${o}) * twoMinusAbsS - 4 * ${o}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${z}, 4>, coefs: array<${z}, 4>) -> ${z} { + var coefsSum: ${z} = 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: ${t.type.indices}) -> ${z} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},yc=(e,t,s,n,i)=>{let[a,o,u,p,h]=s.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],k=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${k} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",o,`max(0, min(depth, ${s[o]} - 1))`)}; + ${e.indicesSet("input_indices",u,`max(0, min(height, ${s[u]} - 1))`)}; + ${e.indicesSet("input_indices",p,`max(0, min(width, ${s[p]} - 1))`)}; + ${va(e,h,a,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${k} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${k} = originalIndices[${o}]; + var height:${k} = originalIndices[${u}]; + var width:${k} = originalIndices[${p}]; + ${n?`if (depth < 0 || depth > (${s[o]} - 1) || height < 0 || height > (${s[u]} - 1) || width < 0 || (width > ${s[p]} - 1)) { + return ${i}; + }`:""}; + + depth = max(0, min(depth, ${s[o]} - 1)); + height = max(0, min(height, ${s[u]} - 1)); + width = max(0, min(width, ${s[p]} - 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 = ${s.length>3?`u32(originalIndices[${h}])`:"0"}; + var batch: u32 = ${s.length>3?`u32(originalIndices[${a}])`:"0"}; + + var x111: ${k} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${k} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${k} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${k} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${k} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${k} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${k} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${k} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${k} = abs(depth - ${k}(depth1)); + var dx2: ${k} = abs(${k}(depth2) - depth); + var dy1: ${k} = abs(height - ${k}(height1)); + var dy2: ${k} = abs(${k}(height2) - height); + var dz1: ${k} = abs(width - ${k}(width1)); + var dz2: ${k} = abs(${k}(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); + }`},Mc=(e,t,s,n,i,a)=>{let o=e.dims,u=cc(a,t.axes,o.length),p=pc(o,n,i,t.axes),h=n.slice();n.length===0&&(h=o.map((Q,he)=>Q===0?1:p[he]/Q),t.keepAspectRatioPolicy!=="stretch"&&(p=hc(o,h,t)));let k=It("output",e.dataType,p.length),E=qe("input",e.dataType,o.length),d=Le.size(p),z=o.length===p.length&&o.every((Q,he)=>Q===p[he]),B=t.coordinateTransformMode==="tf_crop_and_resize",V=t.extrapolationValue,Z=E.type.value,ee=Q=>` + ${z?"":` + ${uc(t.coordinateTransformMode,Z)}; + ${(()=>{switch(t.mode){case"nearest":return` + ${_c(E,o)}; + ${dc(t.nearestMode,s,Z)}; + ${fc(E,k,o,p,h.length,u.length,B)}; + `;case"linear":return` + ${mc(k,o,p,h.length,u.length)}; + ${(()=>{if(o.length===2||o.length===4)return`${gc(E,k,o,B,V)}`;if(o.length===3||o.length===5)return`${yc(E,k,o,B,V)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(o.length===2||o.length===4)return`${wc(E,k,o,p,h,u,t.cubicCoeffA,B,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + `;default:throw Error("Invalid resize mode")}})()}; + `} + ${Q.registerUniform("output_size","u32").registerUniform("scales","f32",h.length).registerUniform("roi","f32",u.length).declareVariables(E,k)} + ${Q.mainStart()} + ${Q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${z?"output[global_idx] = input[global_idx];":` + let output_indices = ${k.offsetToIndices("global_idx")}; + var input_indices: ${E.type.indices}; + ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${E.getByIndices("input_indices")}; + } else { + output[global_idx] = ${t.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${o.length===2||o.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${s}|${h.length>0?h:""}|${i.length>0?i:""}|${u.length>0?u:""}|${z}|${o}`,inputDependencies:["rank"]},getShaderSource:ee,getRunData:()=>({outputs:[{dims:p,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:[{type:12,data:d},{type:1,data:h},{type:1,data:u},...yt(o,p)]})}},bc=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},vc=(e,t)=>{let s=[],n=[],i=[],a=bc(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");lc(e.inputs,t,a,s,n,i),e.compute(Mc(e.inputs[0],t,a,s,n,i),{inputs:[0]})},xc=e=>{let t=e.antialias,s=e.axes,n=e.coordinateTransformMode,i=e.cubicCoeffA,a=e.excludeOutside!==0,o=e.extrapolationValue,u=e.keepAspectRatioPolicy,p=e.mode,h=e.nearestMode===""?"simple":e.nearestMode;return Bt({antialias:t,axes:s,coordinateTransformMode:n,cubicCoeffA:i,excludeOutside:a,extrapolationValue:o,keepAspectRatioPolicy:u,mode:p,nearestMode:h})}}),Tc,bp,Qt,vp=g(()=>{zt(),Ot(),rs(),Yt(),Tc=(e,t)=>{let[s,n,i,a]=e,{numHeads:o,rotaryEmbeddingDim:u}=t;if(s.dims.length!==3&&s.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${s.dims.length}`);if(!Le.areEqual(n.dims,[])&&!Le.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(a.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${a.dims.length}`);if(!Le.areEqual(i.dims,a.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(u>0&&o===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let p=s.dims[0],h=s.dims[s.dims.length-2],k=i.dims[0],E=Le.sizeFromDimension(s.dims,1)/h,d=u===0?i.dims[1]*2:E/o;if(u>d)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(p!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(h!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(d/2!==i.dims[1]&&u/2!==i.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(h>k)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},bp=(e,t)=>{let{interleaved:s,numHeads:n,rotaryEmbeddingDim:i,scale:a}=t,o=e[0].dims[0],u=Le.sizeFromDimension(e[0].dims,1),p=e[0].dims[e[0].dims.length-2],h=u/p,k=e[2].dims[1],E=i===0?k*2:h/n,d=new Array(o,p,h/E,E-k),z=Le.computeStrides(d),B=[{type:1,data:a},{type:12,data:d},{type:12,data:z},...e[0].dims.length===3?new Array({type:12,data:[u,h,E,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[u,E,p*E,1]}):[],...yt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],V=Z=>{let ee=qe("input",e[0].dataType,e[0].dims.length),Q=qe("position_ids",e[1].dataType,e[1].dims.length),he=qe("cos_cache",e[2].dataType,e[2].dims.length),pe=qe("sin_cache",e[3].dataType,e[3].dims.length),Me=It("output",e[0].dataType,e[0].dims.length);return Z.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:d.length},{name:"global_strides",type:"u32",length:z.length},{name:"input_output_strides",type:"u32",length:z.length}]),` + ${Z.declareVariables(ee,Q,he,pe,Me)} + + ${Z.mainStart(nr)} + let half_rotary_emb_dim = uniforms.${he.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${Z.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${Q.broadcastedIndicesToOffset("bsnh.xy",It("",Q.type.tensor,2))}; + let position_id = + u32(${Q.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${s}); + let j = i + select(half_rotary_emb_dim, 1, ${s}); + let re = ${ee.getByOffset("i")} * ${he.get("position_id","bsnh[3]")} - + ${ee.getByOffset("j")} * ${pe.get("position_id","bsnh[3]")}; + ${Me.setByOffset("i","re")} + let im = ${ee.getByOffset("i")} * ${pe.get("position_id","bsnh[3]")} + + ${ee.getByOffset("j")} * ${he.get("position_id","bsnh[3]")}; + ${Me.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${Me.setByOffset("k",ee.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:Bt({interleaved:s}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:V,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Le.size(d)/nr)},programUniforms:B})}},Qt=(e,t)=>{Tc(e.inputs,t),e.compute(bp(e.inputs,t))}}),Ks,Xs,tr,Tn=g(()=>{zt(),Ot(),Yt(),Ks=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],s=e[1],n=e[2];if(t.dataType!==s.dataType||t.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(s.dims.length!==3&&s.dims.length!==2)throw new Error("Skip must be 2D or 3D");let i=t.dims[t.dims.length-1],a=t.dims[t.dims.length-2];if(s.dims[s.dims.length-1]!==i)throw new Error("Skip must have the same hidden size as input");if(s.dims[s.dims.length-2]!==a)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==i)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let o=e[3];if(o.dims.length!==1)throw new Error("Beta must be 1D");if(o.dims[o.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let o=e[4];if(o.dims.length!==1)throw new Error("Bias must be 1D");if(o.dims[o.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},Xs=(e,t,s,n)=>{let i=t.simplified,a=e[0].dims,o=Le.size(a),u=a,p=o,h=a.slice(-1)[0],k=n?a.slice(0,-1).concat(1):[],E=!i&&e.length>3,d=e.length>4,z=n&&s>1,B=n&&s>2,V=s>3,Z=64,ee=qt(h),Q=[{type:12,data:p},{type:12,data:ee},{type:12,data:h},{type:1,data:t.epsilon}],he=Me=>{let Fe=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],De=[qe("x",e[0].dataType,e[0].dims,ee),qe("skip",e[1].dataType,e[1].dims,ee),qe("gamma",e[2].dataType,e[2].dims,ee)];E&&De.push(qe("beta",e[3].dataType,e[3].dims,ee)),d&&De.push(qe("bias",e[4].dataType,e[4].dims,ee)),De.push(It("output",e[0].dataType,u,ee)),z&&De.push(It("mean_output",1,k)),B&&De.push(It("inv_std_output",1,k)),V&&De.push(It("input_skip_bias_sum",e[0].dataType,u,ee));let Ye=ms(e[0].dataType),at=ms(1,ee);return` + + ${Me.registerUniforms(Fe).declareVariables(...De)} + var sum_shared : array<${at}, ${Z}>; + var sum_squared_shared : array<${at}, ${Z}>; + + ${Me.mainStart([Z,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${Z}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${Z}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${Z-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${d?"bias[offset1d + i]":Ye+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${V?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${As(Ye,ee,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${Z}; + 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 = ${Gs("sum",ee)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Gs("square_sum",ee)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon); + ${z?"mean_output[global_idx] = mean;":""} + ${B?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${i?"":`- ${Ye}(mean)`}) * + ${Ye}(inv_std_dev) * gamma[offset1d + i] + ${E?"+ beta[offset1d + i]":""}; + } + }`},pe=[{dims:u,dataType:e[0].dataType}];return s>1&&pe.push({dims:k,dataType:1}),s>2&&pe.push({dims:k,dataType:1}),s>3&&pe.push({dims:a,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${ee};${z};${B};${V}`,inputDependencies:e.map((Me,Fe)=>"type")},getShaderSource:he,getRunData:()=>({outputs:pe,dispatchGroup:{x:Math.ceil(p/h)},programUniforms:Q})}},tr=(e,t)=>{Ks(e.inputs);let s=[0];e.outputCount>1&&s.push(-3),e.outputCount>2&&s.push(-3),e.outputCount>3&&s.push(3),e.compute(Xs(e.inputs,t,e.outputCount,!1),{outputs:s})}}),xp,Kn,Pc,f,T,R,_e,Ie,Oe=g(()=>{zt(),Ot(),rs(),Yt(),xp=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((s,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},Kn=(e,t)=>{let s=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>s.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>s.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return s},Pc=(e,t)=>{if(e.length>1){let s=Kn(e,1),n=Kn(e,2),i=Kn(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),Bt({starts:s,ends:n,axes:i})}else return t},f=(e,t,s,n,i)=>{let a=e;return e<0&&(a+=s[n[t]]),i[t]<0?Math.max(0,Math.min(a,s[n[t]]-1)):Math.max(0,Math.min(a,s[n[t]]))},T=(e,t,s)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + var carry = 0u; + for (var i = ${s.length}; i >= 0; i--) { + let input_shape_i = ${$t("uniforms.input_shape","i",s.length)}; + let steps_i = ${$t("uniforms.steps","i",s.length)}; + let signs_i = ${$t("uniforms.signs","i",s.length)}; + let starts_i = ${$t("uniforms.starts","i",s.length)}; + var output_index = ${t.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; + } + ${e.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,R=(e,t)=>{let s=e[0].dims,n=Le.size(s),i=t.axes.length>0?Le.normalizeAxes(t.axes,s.length):[...Array(s.length).keys()],a=Kn(e,4);a.forEach(ee=>ee!==0||(()=>{throw new Error("step cannot be 0")})),a.length===0&&(a=Array(i.length).fill(1));let o=t.starts.map((ee,Q)=>f(ee,Q,s,i,a)),u=t.ends.map((ee,Q)=>f(ee,Q,s,i,a));if(i.length!==o.length||i.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==s.length)for(let ee=0;eeMath.sign(ee));a.forEach((ee,Q,he)=>{if(ee<0){let pe=(u[Q]-o[Q])/ee,Me=o[Q],Fe=Me+pe*a[Q];o[Q]=Fe,u[Q]=Me,he[Q]=-ee}});let h=s.slice(0);i.forEach((ee,Q)=>{h[ee]=Math.ceil((u[ee]-o[ee])/a[ee])});let k={dims:h,dataType:e[0].dataType},E=It("output",e[0].dataType,h.length),d=qe("input",e[0].dataType,e[0].dims.length),z=Le.size(h),B=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:o.length},{name:"signs",type:"i32",length:p.length},{name:"steps",type:"u32",length:a.length}],V=[{type:12,data:z},{type:12,data:o},{type:6,data:p},{type:12,data:a},...yt(e[0].dims,h)],Z=ee=>` + ${ee.registerUniforms(B).declareVariables(d,E)} + ${T(d,E,s)} + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${E.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${E.setByOffset("global_idx",d.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${p.length}_${o.length}_${a.length}`,inputDependencies:["rank"]},getShaderSource:Z,getRunData:()=>({outputs:[k],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:V})}},_e=(e,t)=>{xp(e.inputs,t);let s=Pc(e.inputs,t);e.compute(R(e.inputs,s),{inputs:[0]})},Ie=e=>{let t=e.starts,s=e.ends,n=e.axes;return Bt({starts:t,ends:s,axes:n})}}),et,rt,_t,Mt,jt=g(()=>{zt(),Ot(),rs(),Kr(),Yt(),et=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},rt=(e,t)=>{let s=e.inputs[0],n=s.dims,i=Le.size(n),a=n.length,o=Le.normalizeAxis(t.axis,a),u=oYe),h[o]=a-1,h[a-1]=o,p=e.compute(hr(s,h),{inputs:[s],outputs:[-1]})[0]):p=s;let k=p.dims,E=k[a-1],d=i/E,z=qt(E),B=E/z,V=64;d===1&&(V=256);let Z=(De,Ye)=>Ye===4?`max(max(${De}.x, ${De}.y), max(${De}.z, ${De}.w))`:Ye===2?`max(${De}.x, ${De}.y)`:Ye===3?`max(max(${De}.x, ${De}.y), ${De}.z)`:De,ee=qe("x",p.dataType,p.dims,z),Q=It("result",p.dataType,p.dims,z),he=ee.type.value,pe=ms(p.dataType)==="f32"?`var threadMax = ${he}(-3.402823e+38f);`:`var threadMax = ${he}(-65504.0h);`,Me=De=>` + var rowMaxShared : ${he}; + var rowSumShared : ${he}; + var threadShared : array<${he}, ${V}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${he} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${he}) { + let index = row * row_stride + col; + result[index] = value; + } + ${De.registerUniform("packedCols","i32").declareVariables(ee,Q)} + ${De.mainStart(V)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${V}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${pe} + 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 = ${he}(${Z("threadShared[0]",z)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${he}(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 = ${he}(${Gs("threadShared[0]",z)}); + } + 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); + } + }`,Fe=e.compute({name:"Softmax",shaderCache:{hint:`${z};${V}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:k,dataType:p.dataType}],dispatchGroup:{x:d},programUniforms:[{type:6,data:B}]}),getShaderSource:Me},{inputs:[p],outputs:[u?-1:0]})[0];u&&e.compute(hr(Fe,h),{inputs:[Fe]})},_t=(e,t)=>{et(e.inputs),rt(e,t)},Mt=e=>Bt({axis:e.axis})}),Vt,Lt,Gt,es,ns,Jt=g(()=>{zt(),Ot(),Yt(),Vt=e=>Array.from(e.getBigInt64Array(),Number),Lt=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Vt(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Gt=(e,t)=>{let s=[];for(let n=0;n{let s=e[0].dims,n=t??Vt(e[1]),i=Gt(s,n),a=Le.size(i),o=e[0].dataType,u=qe("input",o,s.length),p=It("output",o,i.length),h=k=>` + const inputShape = ${u.indices(...s)}; + ${k.registerUniform("output_size","u32").declareVariables(u,p)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${p.offsetToIndices("global_idx")}; + var input_indices: ${u.type.indices}; + for (var i = 0; i < ${s.length}; i++) { + let input_dim_i = ${u.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${p.indicesGet("output_indices","i")} % input_dim_i; + + ${u.indicesSet("input_indices","i","input_dim_value")} + } + ${p.setByOffset("global_idx",u.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:[{type:12,data:a},...yt(e[0].dims,i)]}),getShaderSource:h}},ns=e=>{Lt(e.inputs),e.compute(es(e.inputs),{inputs:[0]})}}),os,Cs,xs,fs=g(()=>{zt(),Ot(),Yt(),os=(e,t,s,n,i)=>{let a=It("output_data",i,s.length,4),o=qe("a_data",t[1].dataType,t[1].dims.length,4),u=qe("b_data",t[2].dataType,t[2].dims.length,4),p=qe("c_data",t[0].dataType,t[0].dims.length,4),h,k=(E,d,z)=>`select(${d}, ${E}, ${z})`;if(!n)h=a.setByOffset("global_idx",k(o.getByOffset("global_idx"),u.getByOffset("global_idx"),p.getByOffset("global_idx")));else{let E=(d,z,B="")=>{let V=`a_data[index_a${z}][component_a${z}]`,Z=`b_data[index_b${z}][component_b${z}]`,ee=`bool(c_data[index_c${z}] & (0xffu << (component_c${z} * 8)))`;return` + let output_indices${z} = ${a.offsetToIndices(`global_idx * 4u + ${z}u`)}; + let offset_a${z} = ${o.broadcastedIndicesToOffset(`output_indices${z}`,a)}; + let offset_b${z} = ${u.broadcastedIndicesToOffset(`output_indices${z}`,a)}; + let offset_c${z} = ${p.broadcastedIndicesToOffset(`output_indices${z}`,a)}; + let index_a${z} = offset_a${z} / 4u; + let index_b${z} = offset_b${z} / 4u; + let index_c${z} = offset_c${z} / 4u; + let component_a${z} = offset_a${z} % 4u; + let component_b${z} = offset_b${z} % 4u; + let component_c${z} = offset_c${z} % 4u; + ${d}[${z}] = ${B}(${k(V,Z,ee)}); + `};i===9?h=` + var data = vec4(0); + ${E("data",0,"u32")} + ${E("data",1,"u32")} + ${E("data",2,"u32")} + ${E("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:h=` + ${E("output_data[global_idx]",0)} + ${E("output_data[global_idx]",1)} + ${E("output_data[global_idx]",2)} + ${E("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(p,o,u,a)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${h} + }`},Cs=e=>{let t=e[1].dims,s=e[2].dims,n=e[0].dims,i=e[1].dataType,a=!(Le.areEqual(t,s)&&Le.areEqual(s,n)),o=t,u=Le.size(t);if(a){let h=Ws.calcShape(Ws.calcShape(t,s,!1),n,!1);if(!h)throw new Error("Can't perform where op on the given tensors");o=h,u=Le.size(o)}let p=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:h=>os(h,e,o,a,i),getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:p},...yt(n,t,s,o)]})}},xs=e=>{e.compute(Cs(e.inputs))}}),Es,Os=g(()=>{Uc(),no(),Vc(),Wc(),Gc(),Kc(),uu(),Xc(),Cu(),Jc(),Du(),Zc(),ep(),tp(),Np(),Wn(),sp(),np(),ud(),ra(),ap(),lp(),up(),Id(),ys(),Md(),jd(),fp(),_p(),wp(),yp(),ai(),Mp(),vp(),Tn(),Oe(),jt(),xd(),Jt(),Kr(),xo(),fs(),Es=new Map([["Abs",[bl]],["Acos",[uo]],["Acosh",[vl]],["Add",[Jl]],["ArgMax",[Zi,eo]],["ArgMin",[hl,eo]],["Asin",[xl]],["Asinh",[co]],["Atan",[Tl]],["Atanh",[Pl]],["Attention",[_l]],["AveragePool",[Gd,Wd]],["BatchNormalization",[oo]],["BiasAdd",[Ml]],["BiasSplitGelu",[Ql]],["Cast",[El,po]],["Ceil",[Sl]],["Clip",[kl]],["Concat",[au,lu]],["Conv",[Ho,Wo]],["ConvTranspose",[Eu,Yo]],["Cos",[ho]],["Cosh",[$l]],["CumSum",[Su,$u]],["DepthToSpace",[Ou,Fu]],["DequantizeLinear",[Zd,ec]],["Div",[Zl]],["Einsum",[ju,Uu]],["Elu",[mo,Nn]],["Equal",[Po]],["Erf",[Al]],["Exp",[fo]],["Expand",[Vn]],["FastGelu",[Ku]],["Floor",[Il]],["FusedConv",[Ho,Wo]],["Gather",[Qu,qu]],["GatherElements",[rp,bi]],["GatherBlockQuantized",[td,sd]],["GatherND",[Yu,Ju]],["Gelu",[Ol]],["Gemm",[ld,ad]],["GlobalAveragePool",[Hd,Kd]],["GlobalMaxPool",[mp,Xd]],["Greater",[su]],["GreaterOrEqual",[Co]],["GridSample",[_d,sa]],["GroupQueryAttention",[ua]],["HardSigmoid",[Bl,wo]],["InstanceNormalization",[Ed]],["LayerNormalization",[Sd]],["LeakyRelu",[_o,Nn]],["Less",[ru]],["LessOrEqual",[nu]],["Log",[Gl]],["MatMul",[Ad]],["MatMulNBits",[Dd,Ld]],["MaxPool",[qd,Qd]],["Mul",[eu]],["MultiHeadAttention",[na,wd]],["Neg",[Dl]],["Not",[Fl]],["Pad",[ma]],["Pow",[tu]],["QuickGelu",[Hl,Nn]],["Range",[tc]],["Reciprocal",[go]],["ReduceMin",[ul]],["ReduceMean",[ol]],["ReduceMax",[Xi]],["ReduceSum",[Yi]],["ReduceProd",[dl]],["ReduceL1",[Qi]],["ReduceL2",[al]],["ReduceLogSum",[pl]],["ReduceLogSumExp",[ll]],["ReduceSumSquare",[cl]],["Relu",[Ll]],["Resize",[vc,xc]],["RotaryEmbedding",[Qt]],["ScatterND",[ic,nc]],["Sigmoid",[zl]],["Sin",[Rl]],["Sinh",[yo]],["Slice",[_e,Ie]],["SkipLayerNormalization",[tr]],["Split",[oa,vd]],["Sqrt",[Nl]],["Softmax",[_t,Mt]],["Sub",[Eo]],["Tan",[jl]],["Tanh",[Ul]],["ThresholdedRelu",[Wl,Nn]],["Tile",[ns]],["Transpose",[Ra,ji]],["Where",[xs]]])}),Zs,Ys=g(()=>{We(),Pe(),Yt(),Zs=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,s,n,i){Ne(e.programInfo.name);let a=this.backend.device,o=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let u=[];for(let h of t)u.push({binding:u.length,resource:{buffer:h.buffer}});for(let h of s)u.push({binding:u.length,resource:{buffer:h.buffer}});i&&u.push({binding:u.length,resource:i});let p=a.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:u,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let h={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:p,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(h)}o.setPipeline(e.computePipeline),o.setBindGroup(0,p),o.dispatchWorkgroups(...n),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(),Re(e.programInfo.name)}dispose(){}build(e,t){Ne(e.name);let s=this.backend.device,n=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"},{feature:"subgroups-f16",extension:"subgroups_f16"}].forEach(h=>{s.features.has(h.feature)&&n.push(`enable ${h.extension};`)});let i=Da(t,this.backend.device.limits),a=e.getShaderSource(i),o=`${n.join(` +`)} +${i.additionalImplementations} +${a}`,u=s.createShaderModule({code:o,label:e.name});as("verbose",()=>`[WebGPU] ${e.name} shader code: ${o}`);let p=s.createComputePipeline({compute:{module:u,entryPoint:"main"},layout:"auto",label:e.name});return Re(e.name),{programInfo:e,computePipeline:p,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,s=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&s<=i&&n<=i)return[t,s,n];let a=t*s*n,o=Math.ceil(Math.sqrt(a));if(o>i){if(o=Math.ceil(Math.cbrt(a)),o>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[o,o,o]}else return[o,o,1]}}}),br,Pn,xa,ur,Cr,Ec=g(()=>{We(),zt(),Pe(),q(),us(),Os(),Ys(),br=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let s=[];for(let n=0;n{var i,a;let n=e.name;return(i=e.shaderCache)!=null&&i.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+s+`:${br(t,((a=e.shaderCache)==null?void 0:a.inputDependencies)??new Array(t.length).fill("dims"))}`,n},xa=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},ur=class{constructor(e){this.subgroupsSupported=e.features.has("subgroups"),this.subgroupsF16Supported=e.features.has("subgroups");let t=e.limits;!this.subgroupsSupported||!t.minSubgroupSize||!t.maxSubgroupSize?this.subgroupSizeRange=void 0:this.subgroupSizeRange=[t.minSubgroupSize,t.maxSubgroupSize]}},Cr=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 e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let s=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:s},i=a=>t.features.has(a)&&s.push(a)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups")&&i("subgroups-f16"),this.device=await t.requestDevice(n),this.deviceInfo=new ur(this.device),this.adapterInfo=new xa(t.info||await t.requestAdapterInfo()),this.gpuDataManager=hs(this),this.programManager=new Zs(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,vn(e.logLevel,!!e.debug),this.device.onuncapturederror=a=>{a.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${a.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,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 e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ne(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var n;let t=new BigUint64Array(e.getMappedRange()),s=this.pendingQueries.get(e);for(let i=0;i"u"&&(this.queryTimeBase=z);let V=Number(z-this.queryTimeBase),Z=Number(B-this.queryTimeBase);if(!Number.isSafeInteger(V)||!Number.isSafeInteger(Z))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:E.map(ee=>({dims:ee.dims,dataType:_r(ee.dataType)})),outputsMetadata:d.map(ee=>({dims:ee.dims,dataType:_r(ee.dataType)})),kernelId:o,kernelType:p,kernelName:h,programName:k,startTime:V,endTime:Z});else{let ee="";E.forEach((he,pe)=>{ee+=`input[${pe}]: [${he.dims}] | ${_r(he.dataType)}, `});let Q="";d.forEach((he,pe)=>{Q+=`output[${pe}]: [${he.dims}] | ${_r(he.dataType)}, `}),console.log(`[profiling] kernel "${o}|${p}|${h}|${k}" ${ee}${Q}execution time: ${Z-V} ns`)}Ue("GPU",`${k}::${z}::${B}`)}e.unmap(),this.pendingQueries.delete(e)}),Re()}run(e,t,s,n,i,a){Ne(e.name);let o=[];for(let Q=0;Qhe):s;if(k.length!==u.length)throw new Error(`Output size ${k.length} must be equal to ${u.length}.`);let E=[],d=[];for(let Q=0;Q=a)throw new Error(`Invalid output index: ${k[Q]}`);if(k[Q]===-3)continue;let he=k[Q]===-1,pe=k[Q]===-2,Me=he||pe?i(u[Q].dataType,u[Q].dims):n(k[Q],u[Q].dataType,u[Q].dims);if(E.push(Me),Me.data===0)continue;let Fe=this.gpuDataManager.get(Me.data);if(!Fe)throw new Error(`no GPU data for output: ${Me.data}`);if(he&&this.temporaryData.push(Fe),pe){let De=this.kernelPersistentData.get(this.currentKernelId);De||(De=[],this.kernelPersistentData.set(this.currentKernelId,De)),De.push(Fe)}d.push(Fe)}if(o.length!==t.length||d.length!==E.length){if(d.length===0)return Re(e.name),E;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let z;if(h){let Q=0,he=[];h.forEach(De=>{let Ye=typeof De.data=="number"?[De.data]:De.data;if(Ye.length===0)return;let at=De.type===10?2:4,Pt,Xt;De.type===10?(Xt=Ye.length>4?16:Ye.length>2?8:Ye.length*at,Pt=Ye.length>4?16:at*Ye.length):(Xt=Ye.length<=2?Ye.length*at:16,Pt=16),Q=Math.ceil(Q/Xt)*Xt,he.push(Q);let Zt=De.type===10?8:4;Q+=Ye.length>4?Math.ceil(Ye.length/Zt)*Pt:Ye.length*at});let pe=16;Q=Math.ceil(Q/pe)*pe;let Me=new ArrayBuffer(Q);h.forEach((De,Ye)=>{let at=he[Ye],Pt=typeof De.data=="number"?[De.data]:De.data;if(De.type===6)new Int32Array(Me,at,Pt.length).set(Pt);else if(De.type===12)new Uint32Array(Me,at,Pt.length).set(Pt);else if(De.type===10)new Uint16Array(Me,at,Pt.length).set(Pt);else if(De.type===1)new Float32Array(Me,at,Pt.length).set(Pt);else throw new Error(`Unsupported uniform type: ${_r(De.type)}`)});let Fe=this.gpuDataManager.create(Q,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Fe.buffer,0,Me,0,Q),this.gpuDataManager.release(Fe.id),z={offset:0,size:Q,buffer:Fe.buffer}}let B=this.programManager.normalizeDispatchGroupSize(p),V=B[1]===1&&B[2]===1,Z=Pn(e,t,V),ee=this.programManager.getArtifact(Z);if(ee||(ee=this.programManager.build(e,B),this.programManager.setArtifact(Z,ee),as("info",()=>`[artifact] key: ${Z}, programName: ${e.name}`)),h&&ee.uniformVariablesInfo){if(h.length!==ee.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${ee.uniformVariablesInfo.length}, got ${h.length} in program "${ee.programInfo.name}".`);for(let Q=0;Q`[ProgramManager] run "${e.name}" (key=${Z}) with ${B[0]}x${B[1]}x${B[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let Q={kernelId:this.currentKernelId,programName:ee.programInfo.name,inputTensorViews:t,outputTensorViews:E};this.pendingKernels.push(Q),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(Q)}return this.programManager.run(ee,o,d,B,z),Re(e.name),E}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,s,n){let i=Es.get(e);if(!i)throw new Error(`kernel not implemented: ${e}`);let a={kernelType:e,kernelName:n,kernelEntry:i[0],attributes:[i[1],s]};this.kernels.set(t,a)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let s of t)this.gpuDataManager.release(s.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,s){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let i=n.kernelType,a=n.kernelName,o=n.kernelEntry,u=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=e,u[0]&&(u[1]=u[0](u[1]),u[0]=void 0),as("info",()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`);let p=this.env.debug;this.temporaryData=[];try{return p&&this.device.pushErrorScope("validation"),o(t,u[1]),0}catch(h){return s.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${h}`)),1}finally{p&&s.push(this.device.popErrorScope().then(h=>h?`GPU validation error for kernel "[${i}] ${a}": ${h.message}`:null));for(let h of this.temporaryData)this.gpuDataManager.release(h.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,s,n){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let a=i.get(t),o=this.gpuDataManager.registerExternalBuffer(s,n,a);return i.set(t,[o,s]),o}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(s=>this.gpuDataManager.unregisterExternalBuffer(s[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,s){return async()=>{let n=await xt(this,e,t);return C(n.buffer,s)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){var e;this.queryType="none",(((e=this.env.webgpu.profiling)==null?void 0:e.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(){as("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(){as("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){as("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),s=e.length;this.pendingKernels=[];for(let n=0;n=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),Ci,Hn,ki,Ts,zs,zr,ln,En,Ta=g(()=>{Pe(),Ci=1,Hn=()=>Ci++,ki=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Ts=(e,t)=>{let s=ki.get(e);if(!s)throw new Error("Unsupported data type.");return t.length>0?Math.ceil(t.reduce((n,i)=>n*i)*s/8):0},zs=class{constructor(e){this.sessionId=e.sessionId,this.mlContext=e.context,this.mlTensor=e.tensor,this.dataType=e.dataType,this.tensorShape=e.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Ts(this.dataType,this.tensorShape)}destroy(){as("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,s){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===s.length&&this.tensorShape.every((n,i)=>n===s[i])}},zr=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,s,n){if(this.wrapper){if(this.wrapper.canReuseTensor(e,t,s))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==Ts(t,s))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,s,i,!0,!0),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper)if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else as("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(e){if(this.activeUpload)if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(this.activeUpload):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},ln=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}reserveTensorId(){let e=Hn();return this.tensorTrackersById.set(e,new zr(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,s,n){as("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${e}, dataType: ${t}, shape: ${s}, copyOld: ${n}}`);let i=this.tensorTrackersById.get(e);if(!i)throw new Error("Tensor not found.");return i.ensureTensor(this.backend.currentContext,t,s,n)}upload(e,t){let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");s.upload(t)}async download(e,t){as("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t==null?void 0:t.byteLength}}`);let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");return s.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,s,n){let i=Hn(),a=new zs({sessionId:this.backend.currentSessionId,context:e,tensor:t,dataType:s,shape:n});return this.tensorTrackersById.set(i,new zr(this,a)),this.externalTensors.add(a),i}async getCachedTensor(e,t,s,n,i){let a=this.backend.currentSessionId,o=this.backend.currentContext;for(let[p,h]of this.freeTensors.entries())if(h.canReuseTensor(o,e,t)){as("verbose",()=>`[WebNN] Reusing tensor {dataType: ${e}, shape: ${t}}`);let k=this.freeTensors.splice(p,1)[0];return k.sessionId=a,k}as("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${e}, shape: ${t}}`);let u=await o.createTensor({dataType:e,shape:t,dimensions:t,usage:s,writable:n,readable:i});return new zs({sessionId:a,context:o,tensor:u,dataType:e,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},En=(...e)=>new ln(...e)}),Si,Pa,Ea,jp=g(()=>{zt(),ar(),q(),Ta(),Pe(),Si=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Pa=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let s=Object.keys(e).sort(),n=Object.keys(t).sort();return s.length===n.length&&s.every((i,a)=>i===n[a]&&e[i]===t[i])},Ea=class{constructor(e){this.tensorManager=En(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],vn(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){this.activeSessionId=e}async createMLContext(e){if(e instanceof GPUDevice){let s=this.mlContextCache.findIndex(n=>n.gpuDevice===e);if(s!==-1)return this.mlContextCache[s].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let s=this.mlContextCache.findIndex(n=>n.options===void 0&&n.gpuDevice===void 0);if(s!==-1)return this.mlContextCache[s].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let t=this.mlContextCache.findIndex(s=>Pa(s.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:s}),s}}get currentContext(){let e=this.getMLContext(this.currentSessionId);if(!e)throw new Error(`No MLContext found for session ${this.currentSessionId}`);return e}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let s=this.sessionIdsByMLContext.get(t);s||(s=new Set,this.sessionIdsByMLContext.set(t,s)),s.add(e)}onReleaseSession(e){let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let s=this.sessionIdsByMLContext.get(t);if(s.delete(e),s.size===0){this.sessionIdsByMLContext.delete(t);let n=this.mlContextCache.findIndex(i=>i.mlContext===t);n!==-1&&this.mlContextCache.splice(n,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){as("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,s,n){let i=Si.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e,i,s,n)}uploadTensor(e,t){if(!Ms().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");as("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let s=await this.tensorManager.download(e);return C(s,t)}}registerMLTensor(e,t,s){let n=Si.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.registerTensor(this.currentContext,e,n,s);return as("verbose",()=>`[WebNN] registerMLTensor {tensor: ${e}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${i}}`),i}registerMLConstant(e,t,s,n,i,a){if(!a)throw new Error("External mounted files are not available.");let o=e;e.startsWith("./")&&(o=e.substring(2));let u=a.get(o);if(!u)throw new Error(`File with name ${o} not found in preloaded files.`);if(t+s>u.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=u.slice(t,t+s).buffer,h;switch(i.dataType){case"float32":h=new Float32Array(p);break;case"float16":h=new Uint16Array(p);break;case"int32":h=new Int32Array(p);break;case"uint32":h=new Uint32Array(p);break;case"int64":h=new BigInt64Array(p);break;case"uint64":h=new BigUint64Array(p);break;case"int8":h=new Int8Array(p);break;case"int4":case"uint4":case"uint8":h=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return as("verbose",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`),n.constant(i,h)}flush(){}}}),Ca={};v(Ca,{init:()=>Cc});var Cn,ka,Cc,kc=g(()=>{zt(),Ec(),Pe(),Ot(),jp(),Cn=class tf{constructor(t,s,n,i){this.module=t,this.dataType=s,this.data=n,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=Le.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=Le.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=Le.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=Le.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(Le.size(t)!==Le.size(this.dims))throw new Error("Invalid new shape");return new tf(this.module,this.dataType,this.data,t)}},ka=class{constructor(e,t,s){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo,this.deviceInfo=t.deviceInfo;let n=e.PTR_SIZE,i=s/e.PTR_SIZE,a=n===4?"i32":"i64";this.opKernelContext=Number(e.getValue(n*i++,a));let o=Number(e.getValue(n*i++,a));this.outputCount=Number(e.getValue(n*i++,a)),this.customDataOffset=Number(e.getValue(n*i++,"*")),this.customDataSize=Number(e.getValue(n*i++,a));let u=[];for(let p=0;ptypeof u=="number"?this.inputs[u]:u))??this.inputs,n=(t==null?void 0:t.outputs)??[],i=(u,p,h)=>new Cn(this.module,p,this.output(u,h),h),a=(u,p)=>{let h=lr(u,p);if(!h)throw new Error(`Unsupported data type: ${u}`);let k=h>0?this.backend.gpuDataManager.create(h).id:0;return new Cn(this.module,u,k,p)};return this.backend.run(e,s,n,i,a,this.outputCount)}output(e,t){let s=this.module.stackSave();try{let n=this.module.PTR_SIZE,i=n===4?"i32":"i64",a=this.module.stackAlloc((1+t.length)*n);this.module.setValue(a,t.length,i);for(let o=0;o{let i=t.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let a=new Cr;await a.initialize(s,n),i("webgpu",[a,o=>a.alloc(Number(o)),o=>a.free(o),(o,u,p,h=!1)=>{if(h)as("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(o)}, dst=${Number(u)}, size=${Number(p)}`),a.memcpy(Number(o),Number(u));else{as("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(o)}, gpuDataId=${Number(u)}, size=${Number(p)}`);let k=t.HEAPU8.subarray(Number(o>>>0),Number(o>>>0)+Number(p));a.upload(Number(u),k)}},async(o,u,p)=>{as("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${o}, dataOffset=${u}, size=${p}`),await a.download(Number(o),()=>t.HEAPU8.subarray(Number(u)>>>0,Number(u+p)>>>0))},(o,u,p)=>a.createKernel(o,Number(u),p,t.UTF8ToString(t._JsepGetNodeName(Number(u)))),o=>a.releaseKernel(o),(o,u,p,h)=>{as("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${p}, kernel=${o}, contextDataOffset=${u}`);let k=new ka(t,a,Number(u));return a.computeKernel(Number(o),k,h)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let a=new Ea(s);i("webnn",[a,()=>a.reserveTensorId(),o=>a.releaseTensorId(o),async(o,u,p,h)=>a.ensureTensor(o,u,p,h),(o,u)=>{a.uploadTensor(o,u)},async(o,u)=>a.downloadTensor(o,u)])}}}),$i,Sc,$c,un,dn,dr,Up,Vp,Wp,Gp,Kp,Hp,bh=g(()=>{si(),ri(),zt(),ar(),_n(),Fn(),$i=(e,t)=>{Ms()._OrtInit(e,t)!==0&&ts("Can't initialize onnxruntime.")},Sc=async e=>{$i(e.wasm.numThreads,tn(e.logLevel))},$c=async(e,t)=>{{let s=(kc(),M(Ca)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await s("webgpu",Ms(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await s("webnn",Ms(),e)}}},un=new Map,dn=e=>{let t=Ms(),s=t.stackSave();try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,i,i+n)!==0&&ts("Can't get session input/output count.");let a=n===4?"i32":"i64";return[Number(t.getValue(i,a)),Number(t.getValue(i+n,a))]}finally{t.stackRestore(s)}},dr=e=>{let t=Ms(),s=t._malloc(e.byteLength);if(s===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,s),[s,e.byteLength]},Up=async(e,t)=>{var E,d,z;let s,n,i=Ms();Array.isArray(e)?[s,n]=e:e.buffer===i.HEAPU8.buffer?[s,n]=[e.byteOffset,e.byteLength]:[s,n]=dr(e);let a=0,o=0,u=0,p=[],h=[],k=[];try{if([o,p]=On(t),(t==null?void 0:t.externalData)&&i.mountExternalData){let Me=[];for(let Fe of t.externalData){let De=typeof Fe=="string"?Fe:Fe.path;Me.push(bn(typeof Fe=="string"?Fe:Fe.data).then(Ye=>{i.mountExternalData(De,Ye)}))}await Promise.all(Me)}for(let Me of(t==null?void 0:t.executionProviders)??[])if((typeof Me=="string"?Me:Me.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof Me!="string"){let Fe=Me,De=Fe==null?void 0:Fe.context,Ye=Fe==null?void 0:Fe.gpuDevice,at=Fe==null?void 0:Fe.deviceType,Pt=Fe==null?void 0:Fe.powerPreference;De?i.currentContext=De:Ye?i.currentContext=await i.jsepCreateMLContext(Ye):i.currentContext=await i.jsepCreateMLContext({deviceType:at,powerPreference:Pt})}else i.currentContext=await i.jsepCreateMLContext();break}a=await i._OrtCreateSession(s,n,o),a===0&&ts("Can't create a session."),(E=i.jsepOnCreateSession)==null||E.call(i),i.currentContext&&(i.jsepRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[B,V]=dn(a),Z=!!(t!=null&&t.enableGraphCapture),ee=[],Q=[],he=[];for(let Me=0;MeMe==="gpu-buffer"||Me==="ml-tensor")&&(u=i._OrtCreateBinding(a),u===0&&ts("Can't create IO binding."),pe={handle:u,outputPreferredLocations:he,outputPreferredLocationsEncoded:he.map(Me=>Mn(Me))}),un.set(a,[a,h,k,pe,Z,!1]),[a,ee,Q]}catch(B){throw h.forEach(V=>i._OrtFree(V)),k.forEach(V=>i._OrtFree(V)),u!==0&&i._OrtReleaseBinding(u)!==0&&ts("Can't release IO binding."),a!==0&&i._OrtReleaseSession(a)!==0&&ts("Can't release session."),B}finally{i._free(s),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&ts("Can't release session options."),p.forEach(B=>i._free(B)),(z=i.unmountExternalData)==null||z.call(i)}},Vp=e=>{var p;let t=Ms(),s=un.get(e);if(!s)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,i,a,o,u]=s;o&&(u&&t._OrtClearBoundOutputs(o.handle)!==0&&ts("Can't clear bound outputs."),t._OrtReleaseBinding(o.handle)!==0&&ts("Can't release IO binding.")),(p=t.jsepOnReleaseSession)==null||p.call(t,e),i.forEach(h=>t._OrtFree(h)),a.forEach(h=>t._OrtFree(h)),t._OrtReleaseSession(n)!==0&&ts("Can't release session."),un.delete(e)},Wp=(e,t,s,n,i,a=!1)=>{if(!e){t.push(0);return}let o=Ms(),u=o.PTR_SIZE,p=e[0],h=e[1],k=e[3],E,d;if(p==="string"&&(k==="gpu-buffer"||k==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&k!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(k==="gpu-buffer"){let V=e[2].gpuBuffer;d=lr(Wr(p),h);let Z=o.jsepRegisterBuffer;if(!Z)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');E=Z(n,i,V,d)}else if(k==="ml-tensor"){let V=e[2].mlTensor;d=lr(Wr(p),h);let Z=o.jsepRegisterMLTensor;if(!Z)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');E=Z(V,Wr(p),h)}else{let V=e[2];if(Array.isArray(V)){d=u*V.length,E=o._malloc(d),s.push(E);for(let Z=0;Zo.setValue(B+ee*u,Z,u===4?"i32":"i64"));let V=o._OrtCreateTensor(Wr(p),E,d,B,h.length,Mn(k));V===0&&ts(`Can't create tensor for input/output. session=${n}, index=${i}.`),t.push(V)}finally{o.stackRestore(z)}},Gp=async(e,t,s,n,i,a)=>{var Xt,Zt;let o=Ms(),u=o.PTR_SIZE,p=un.get(e);if(!p)throw new Error(`cannot run inference. invalid session id: ${e}`);let h=p[0],k=p[1],E=p[2],d=p[3],z=p[4],B=p[5],V=t.length,Z=n.length,ee=0,Q=[],he=[],pe=[],Me=[],Fe=o.stackSave(),De=o.stackAlloc(V*u),Ye=o.stackAlloc(V*u),at=o.stackAlloc(Z*u),Pt=o.stackAlloc(Z*u);try{(Xt=o.jsepOnRunStart)==null||Xt.call(o,h),[ee,Q]=Ur(a);for(let St=0;StBs*Ps,1);_s=_r(cs);let Oi=d==null?void 0:d.outputPreferredLocations[n[St]];if(_s==="string"){if(Oi==="gpu-buffer"||Oi==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Bs=[];for(let Ps=0;Ps0){let Bs=o.jsepGetBuffer;if(!Bs)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ps=Bs(ot),Qn=lr(cs,cn);if(Qn===void 0||!wn(_s))throw new Error(`Unsupported data type: ${_s}`);Rt=!0,ss.push([_s,er,{gpuBuffer:Ps,download:o.jsepCreateDownloader(Ps,Qn,_s),dispose:()=>{o._OrtReleaseTensor(Ft)!==0&&ts("Can't release tensor.")}},"gpu-buffer"])}else if(Oi==="ml-tensor"&&cn>0){let Bs=o.jsepEnsureTensor;if(!Bs)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(lr(cs,cn)===void 0||!yn(_s))throw new Error(`Unsupported data type: ${_s}`);let Ps=await Bs(ot,cs,er,!1);Rt=!0,ss.push([_s,er,{mlTensor:Ps,download:o.jsepCreateMLTensorDownloader(ot,_s),dispose:()=>{o.jsepReleaseTensorId(ot),o._OrtReleaseTensor(Ft)}},"ml-tensor"])}else{let Bs=gn(_s),Ps=new Bs(cn);new Uint8Array(Ps.buffer,Ps.byteOffset,Ps.byteLength).set(o.HEAPU8.subarray(ot,ot+Ps.byteLength)),ss.push([_s,er,Ps,"cpu"])}}finally{o.stackRestore(bs),_s==="string"&&ot&&o._free(ot),Rt||o._OrtReleaseTensor(Ft)}}return d&&!z&&(o._OrtClearBoundOutputs(d.handle)!==0&&ts("Can't clear bound outputs."),un.set(e,[h,k,E,d,z,!1])),ss}finally{o.stackRestore(Fe),he.forEach(bt=>o._OrtReleaseTensor(bt)),pe.forEach(bt=>o._OrtReleaseTensor(bt)),Me.forEach(bt=>o._free(bt)),ee!==0&&o._OrtReleaseRunOptions(ee),Q.forEach(bt=>o._free(bt))}},Kp=e=>{let t=Ms(),s=un.get(e);if(!s)throw new Error("invalid session id");let n=s[0],i=t._OrtEndProfiling(n);i===0&&ts("Can't get an profile file name."),t._OrtFree(i)},Hp=e=>{let t=[];for(let s of e){let n=s[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),qn,vr,Sa,Ac,Ic,Tp,qp,Pp,Ai,Ii,vh,xh,Th,Ph,Eh,Ch,kh,Sh,$h=g(()=>{We(),bh(),ar(),Nr(),qn=()=>!!O.wasm.proxy&&typeof document<"u",Sa=!1,Ac=!1,Ic=!1,Pp=new Map,Ai=(e,t)=>{let s=Pp.get(e);s?s.push(t):Pp.set(e,[t])},Ii=()=>{if(Sa||!Ac||Ic||!vr)throw new Error("worker not ready")},vh=e=>{switch(e.data.type){case"init-wasm":Sa=!1,e.data.err?(Ic=!0,qp[1](e.data.err)):(Ac=!0,qp[0]()),Tp&&(URL.revokeObjectURL(Tp),Tp=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Pp.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},xh=async()=>{if(!Ac){if(Sa)throw new Error("multiple calls to 'initWasm()' detected.");if(Ic)throw new Error("previous call to 'initWasm()' failed.");if(Sa=!0,qn())return new Promise((e,t)=>{vr==null||vr.terminate(),en().then(([s,n])=>{var i;try{vr=n,vr.onerror=o=>t(o),vr.onmessage=vh,qp=[e,t];let a={type:"init-wasm",in:O};!a.in.wasm.wasmPaths&&(s||(i=self.location.href)!=null&&i.startsWith("file:"))&&(a.in.wasm.wasmPaths={wasm:new URL(r("./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"),r.b).href}),vr.postMessage(a),Tp=s}catch(a){t(a)}},t)});try{await Or(O.wasm),await Sc(O),Ac=!0}catch(e){throw Ic=!0,e}finally{Sa=!1}}},Th=async e=>{if(qn())return Ii(),new Promise((t,s)=>{Ai("init-ep",[t,s]);let n={type:"init-ep",in:{epName:e,env:O}};vr.postMessage(n)});await $c(O,e)},Ph=async e=>qn()?(Ii(),new Promise((t,s)=>{Ai("copy-from",[t,s]);let n={type:"copy-from",in:{buffer:e}};vr.postMessage(n,[e.buffer])})):dr(e),Eh=async(e,t)=>{if(qn()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ii(),new Promise((s,n)=>{Ai("create",[s,n]);let i={type:"create",in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),vr.postMessage(i,a)})}else return Up(e,t)},Ch=async e=>{if(qn())return Ii(),new Promise((t,s)=>{Ai("release",[t,s]);let n={type:"release",in:e};vr.postMessage(n)});Vp(e)},kh=async(e,t,s,n,i,a)=>{if(qn()){if(s.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return Ii(),new Promise((o,u)=>{Ai("run",[o,u]);let p=s,h={type:"run",in:{sessionId:e,inputIndices:t,inputs:p,outputIndices:n,options:a}};vr.postMessage(h,Hp(p))})}else return Gp(e,t,s,n,i,a)},Sh=async e=>{if(qn())return Ii(),new Promise((t,s)=>{Ai("end-profiling",[t,s]);let n={type:"end-profiling",in:e};vr.postMessage(n)});Kp(e)}}),Qp,Ah,Ih,nf=g(()=>{We(),$h(),zt(),Je(),Fn(),Qp=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},Ah=e=>{switch(e[3]){case"cpu":return new le(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!wn(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:s,download:n,dispose:i}=e[2];return le.fromGpuBuffer(s,{dataType:t,dims:e[1],download:n,dispose:i})}case"ml-tensor":{let t=e[0];if(!yn(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:s,download:n,dispose:i}=e[2];return le.fromMLTensor(s,{dataType:t,dims:e[1],download:n,dispose:i})}default:throw new Error(`invalid data location: ${e[3]}`)}},Ih=class{async fetchModelAndCopyToWasmMemory(e){return Ph(await bn(e))}async loadModel(e,t){Ne();let s;typeof e=="string"?s=await this.fetchModelAndCopyToWasmMemory(e):s=e,[this.sessionId,this.inputNames,this.outputNames]=await Eh(s,t),Re()}async dispose(){return Ch(this.sessionId)}async run(e,t,s){Ne();let n=[],i=[];Object.entries(e).forEach(E=>{let d=E[0],z=E[1],B=this.inputNames.indexOf(d);if(B===-1)throw new Error(`invalid input '${d}'`);n.push(z),i.push(B)});let a=[],o=[];Object.entries(t).forEach(E=>{let d=E[0],z=E[1],B=this.outputNames.indexOf(d);if(B===-1)throw new Error(`invalid output '${d}'`);a.push(z),o.push(B)});let u=n.map((E,d)=>Qp(E,()=>`input "${this.inputNames[i[d]]}"`)),p=a.map((E,d)=>E?Qp(E,()=>`output "${this.outputNames[o[d]]}"`):null),h=await kh(this.sessionId,i,u,o,p,s),k={};for(let E=0;EYp,initializeFlags:()=>Xp,wasmBackend:()=>Fh});var Xp,Yp,Fh,of=g(()=>{We(),$h(),nf(),Xp=()=>{if((typeof O.wasm.initTimeout!="number"||O.wasm.initTimeout<0)&&(O.wasm.initTimeout=0),O.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 O.wasm.proxy!="boolean"&&(O.wasm.proxy=!1),typeof O.wasm.trace!="boolean"&&(O.wasm.trace=!1),typeof O.wasm.numThreads!="number"||!Number.isInteger(O.wasm.numThreads)||O.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)O.wasm.numThreads=1;else{let e=typeof navigator>"u"?N("node:os").cpus().length:navigator.hardwareConcurrency;O.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},Yp=class{async init(e){Xp(),await xh(),await Th(e)}async createInferenceSessionHandler(e,t){let s=new Ih;return await s.loadModel(e,t),Promise.resolve(s)}},Fh=new Yp});We(),We(),We();var af="1.21.0-dev.20250114-228dd16893",lf=$e;{let e=(of(),M(Oh)).wasmBackend;K("webgpu",e,5),K("webnn",e,5),K("cpu",e,10),K("wasm",e,10)}Object.defineProperty(O.versions,"web",{value:af,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":(ze,A,r)=>{var _;r.r(A),r.d(A,{Tensor:()=>N.Tensor,createInferenceSession:()=>ne,deviceToExecutionProviders:()=>K,isONNXProxy:()=>X,isONNXTensor:()=>W});var D=r("./src/env.js"),j=r("?2ce3"),Y=r("./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?3a96"),N=r("./node_modules/onnxruntime-common/dist/esm/index.js");const g=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"}}),v=[];let y,M;const b=Symbol.for("onnxruntime");if(b in globalThis)M=globalThis[b];else if(D.apis.IS_NODE_ENV){switch(M=j??(_||(_=r.t(j,2))),process.platform){case"win32":v.push("dml");break;case"linux":process.arch==="x64"&&v.push("cuda");break}v.push("cpu"),y=["cpu"]}else M=Y,D.apis.IS_WEBNN_AVAILABLE&&v.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),D.apis.IS_WEBGPU_AVAILABLE&&v.push("webgpu"),v.push("wasm"),y=["wasm"];const I=M.InferenceSession;function K($=null){if(!$)return y;switch($){case"auto":return v;case"gpu":return v.filter(S=>["webgpu","cuda","dml","webnn-gpu"].includes(S))}if(v.includes($))return[g[$]??$];throw new Error(`Unsupported device: "${$}". Should be one of: ${v.join(", ")}.`)}let te=null;async function ne($,S,w){te&&await te;const x=I.create($,S);te??(te=x);const O=await x;return O.config=w,O}function W($){return $ instanceof M.Tensor}const U=M==null?void 0:M.env;U!=null&&U.wasm&&(U.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${D.env.version}/dist/`,U.wasm.proxy=!1,(typeof crossOriginIsolated>"u"||!crossOriginIsolated)&&(U.wasm.numThreads=1)),U!=null&&U.webgpu&&(U.webgpu.powerPreference="high-performance");function X(){var $;return($=U==null?void 0:U.wasm)==null?void 0:$.proxy}D.env.backends.onnx=U},"./src/base/feature_extraction_utils.js":(ze,A,r)=>{r.r(A),r.d(A,{FeatureExtractor:()=>Y,validate_audio_inputs:()=>N});var _=r("./src/utils/constants.js"),D=r("./src/utils/generic.js"),j=r("./src/utils/hub.js");class Y extends D.Callable{constructor(v){super(),this.config=v}static async from_pretrained(v,y){const M=await(0,j.getModelJSON)(v,_.FEATURE_EXTRACTOR_NAME,!0,y);return new this(M)}}function N(g,v){var y;if(!(g instanceof Float32Array||g instanceof Float64Array))throw new Error(`${v} expects input to be a Float32Array or a Float64Array, but got ${((y=g==null?void 0:g.constructor)==null?void 0:y.name)??typeof g} 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.`)}},"./src/base/image_processors_utils.js":(ze,A,r)=>{r.r(A),r.d(A,{ImageProcessor:()=>$,center_to_corners_format:()=>M,post_process_instance_segmentation:()=>X,post_process_object_detection:()=>b,post_process_panoptic_segmentation:()=>U,post_process_semantic_segmentation:()=>I});var _=r("./src/utils/generic.js"),D=r("./src/utils/tensor.js"),j=r("./src/utils/maths.js");r("./src/utils/image.js");var Y=r("./src/utils/core.js"),N=r("./src/utils/hub.js"),g=r("./src/utils/constants.js");function v(S,w,x=0,O=null){const ae=S/w;let ie=(0,j.bankers_round)(ae)*w;return O!==null&&ie>O&&(ie=Math.floor(ae)*w),iew&&J.push(Ce)}else{let Ce=(0,j.max)(ye.data)[1];if(Ce===re-1||(de=(0,j.softmax)(ye.data),de[Ce]Ze*ke[(se+1)%2])),Ae.boxes.push(Be),Ae.classes.push(Ce),Ae.scores.push(de[Ce])}}xe.push(Ae)}return xe}function I(S,w=null){const x=S.logits,O=x.dims[0];if(w!==null&&w.length!==O)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const ae=[];for(let ie=0;ieke[J]&&(ke[J]=ye[J],Ae[J]=Ge)}const Ee=new Array(we.dims[0]);for(let Ge=0;GeGe!==void 0);ae.push({segmentation:ce,labels:tt})}return ae}function K(S,w,x,O){const ae=[],ie=[],ve=[];for(let we=0;wex&&(ae.push(xe),ie.push(Ae),ve.push(ce))}return[ae,ie,ve]}function te(S,w,x,O=.5,ae=.8){const ie=[];let ve=0,we=0;const re=w[x].data;for(let ce=0;ce=O&&++we;let xe=ve>0&&we>0;return xe&&(xe=ve/we>ae),[xe,ie]}function ne(S,w,x,O,ae,ie=null,ve=null){const[we,re]=ve??S[0].dims,xe=new D.Tensor("int32",new Int32Array(we*re),[we,re]),ce=[];if(ve!==null)for(let Ge=0;GeAe[de]&&(ke[de]=Ge,Ae[de]=J[de])}let Ee=0;const tt=xe.data;for(let Ge=0;Ge200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(S,w)/Math.min(S,w)}`);let ie=Math.round(S/x)*x,ve=Math.round(w/x)*x;if(ie*ve>ae){const we=Math.sqrt(S*w/ae);ie=Math.floor(S/we/x)*x,ve=Math.floor(w/we/x)*x}else if(ie*veie?xe=Math.floor(ie*re/ae):ie>ae&&(re=Math.floor(ae*xe/ie)),await w.resize(xe,re,{resample:O}))}async crop_margin(w,x=200){const O=w.clone().grayscale(),ae=(0,j.min)(O.data)[0],ve=(0,j.max)(O.data)[0]-ae;if(ve===0)return w;const we=x/255;let re=O.width,xe=O.height,ce=0,ke=0;const Ae=O.data;for(let Ee=0;Eethis.preprocess(ie)));return{pixel_values:(0,D.stack)(O.map(ie=>ie.pixel_values),0),original_sizes:O.map(ie=>ie.original_size),reshaped_input_sizes:O.map(ie=>ie.reshaped_input_size)}}static async from_pretrained(w,x){const O=await(0,N.getModelJSON)(w,g.IMAGE_PROCESSOR_NAME,!0,x);return new this(O)}}},"./src/base/processing_utils.js":(ze,A,r)=>{r.r(A),r.d(A,{Processor:()=>Y});var _=r("./src/utils/constants.js"),D=r("./src/utils/generic.js"),j=r("./src/utils/hub.js");class Y extends D.Callable{constructor(g,v){super(),this.config=g,this.components=v}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(g,v={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(g,{tokenize:!1,...v})}batch_decode(...g){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...g)}decode(...g){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...g)}async _call(g,...v){for(const y of[this.image_processor,this.feature_extractor,this.tokenizer])if(y)return y(g,...v);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(g,v){const[y,M]=await Promise.all([this.uses_processor_config?(0,j.getModelJSON)(g,_.PROCESSOR_NAME,!0,v):{},Promise.all(this.classes.filter(b=>b in this).map(async b=>{const I=await this[b].from_pretrained(g,v);return[b.replace(/_class$/,""),I]})).then(Object.fromEntries)]);return new this(y,M)}}fe(Y,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),fe(Y,"uses_processor_config",!1)},"./src/configs.js":(ze,A,r)=>{r.r(A),r.d(A,{AutoConfig:()=>v,PretrainedConfig:()=>g,getKeyValueShapes:()=>N});var _=r("./src/utils/core.js"),D=r("./src/utils/hub.js");async function j(y,M){return await(0,D.getModelJSON)(y,"config.json",!0,M)}function Y(y){const M={};let b={};switch(y.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":case"idefics3":b=Y(y.text_config);break;case"moondream1":b=Y(y.phi_config);break;case"musicgen":b=Y(y.decoder);break;case"multi_modality":b=Y(y.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":M.num_heads="n_head",M.num_layers="n_layer",M.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":M.num_heads="num_attention_heads",M.num_layers="num_hidden_layers",M.hidden_size="hidden_size";break;case"llama":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":M.num_heads="num_key_value_heads",M.num_layers="num_hidden_layers",M.hidden_size="hidden_size",M.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":M.num_heads="num_key_value_heads",M.num_layers="num_hidden_layers",M.dim_kv="head_dim";break;case"openelm":M.num_heads="num_kv_heads",M.num_layers="num_transformer_layers",M.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":M.num_heads="num_heads",M.num_layers="num_layers",M.hidden_size="hidden_size";break;case"bloom":M.num_heads="n_head",M.num_layers="n_layer",M.hidden_size="hidden_size";break;case"mpt":M.num_heads="n_heads",M.num_layers="n_layers",M.hidden_size="d_model";break;case"exaone":M.num_heads="num_key_value_heads",M.num_layers="num_layers",M.dim_kv="head_dim",M.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":M.num_decoder_layers="num_decoder_layers",M.num_decoder_heads="num_heads",M.decoder_dim_kv="d_kv",M.num_encoder_layers="num_layers",M.num_encoder_heads="num_heads",M.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":M.num_decoder_layers="decoder_layers",M.num_decoder_heads="decoder_attention_heads",M.decoder_hidden_size="d_model",M.num_encoder_layers="encoder_layers",M.num_encoder_heads="encoder_attention_heads",M.encoder_hidden_size="d_model";break;case"speecht5":M.num_decoder_layers="decoder_layers",M.num_decoder_heads="decoder_attention_heads",M.decoder_hidden_size="hidden_size",M.num_encoder_layers="encoder_layers",M.num_encoder_heads="encoder_attention_heads",M.encoder_hidden_size="hidden_size";break;case"trocr":M.num_encoder_layers=M.num_decoder_layers="decoder_layers",M.num_encoder_heads=M.num_decoder_heads="decoder_attention_heads",M.encoder_hidden_size=M.decoder_hidden_size="d_model";break;case"musicgen_decoder":case"moonshine":M.num_encoder_layers=M.num_decoder_layers="num_hidden_layers",M.num_encoder_heads=M.num_decoder_heads="num_attention_heads",M.encoder_hidden_size=M.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const K=Y(y.decoder),te="num_decoder_layers"in K,ne=(0,_.pick)(y,["model_type","is_encoder_decoder"]);return te?(ne.num_decoder_layers=K.num_decoder_layers,ne.num_decoder_heads=K.num_decoder_heads,ne.decoder_hidden_size=K.decoder_hidden_size,ne.num_encoder_layers=K.num_encoder_layers,ne.num_encoder_heads=K.num_encoder_heads,ne.encoder_hidden_size=K.encoder_hidden_size):(ne.num_layers=K.num_layers,ne.num_heads=K.num_heads,ne.hidden_size=K.hidden_size),ne}const I={...b,...(0,_.pick)(y,["model_type","multi_query","is_encoder_decoder"])};for(const K in M)I[K]=y[M[K]];return I}function N(y,{prefix:M="past_key_values",batch_size:b=1}={}){const I={},K=y.normalized_config;if(K.is_encoder_decoder&&"num_encoder_heads"in K&&"num_decoder_heads"in K){const te=K.encoder_dim_kv??K.encoder_hidden_size/K.num_encoder_heads,ne=K.decoder_dim_kv??K.decoder_hidden_size/K.num_decoder_heads,W=[b,K.num_encoder_heads,0,te],U=[b,K.num_decoder_heads,0,ne];for(let X=0;X{var O,ae;r.r(A),r.d(A,{apis:()=>ne,env:()=>w});var _=r("?569f"),D=r("?3f59"),j=r("?154a");const Y="3.3.1",N=typeof window<"u"&&typeof window.document<"u",g=typeof self<"u"&&((O=self.constructor)==null?void 0:O.name)==="DedicatedWorkerGlobalScope",v=typeof self<"u"&&"caches"in self,y=typeof navigator<"u"&&"gpu"in navigator,M=typeof navigator<"u"&&"ml"in navigator,b=typeof process<"u",I=b&&((ae=process==null?void 0:process.release)==null?void 0:ae.name)==="node",K=!x(_),te=!x(D),ne=Object.freeze({IS_BROWSER_ENV:N,IS_WEBWORKER_ENV:g,IS_WEB_CACHE_AVAILABLE:v,IS_WEBGPU_AVAILABLE:y,IS_WEBNN_AVAILABLE:M,IS_PROCESS_AVAILABLE:b,IS_NODE_ENV:I,IS_FS_AVAILABLE:K,IS_PATH_AVAILABLE:te}),W=K&&te;let U="./";if(W){const ie=Object({url:self.location.href}).url;ie?U=D.dirname(D.dirname(j.fileURLToPath(ie))):typeof __dirname<"u"&&(U=D.dirname(__dirname))}const X=W?D.join(U,"/.cache/"):null,$="/models/",S=W?D.join(U,$):$,w={version:Y,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(N||g),localModelPath:S,useFS:K,useBrowserCache:v,useFSCache:K,cacheDir:X,useCustomCache:!1,customCache:null};function x(ie){return Object.keys(ie).length===0}},"./src/generation/configuration_utils.js":(ze,A,r)=>{r.r(A),r.d(A,{GenerationConfig:()=>D});var _=r("./src/utils/core.js");class D{constructor(Y){fe(this,"max_length",20);fe(this,"max_new_tokens",null);fe(this,"min_length",0);fe(this,"min_new_tokens",null);fe(this,"early_stopping",!1);fe(this,"max_time",null);fe(this,"do_sample",!1);fe(this,"num_beams",1);fe(this,"num_beam_groups",1);fe(this,"penalty_alpha",null);fe(this,"use_cache",!0);fe(this,"temperature",1);fe(this,"top_k",50);fe(this,"top_p",1);fe(this,"typical_p",1);fe(this,"epsilon_cutoff",0);fe(this,"eta_cutoff",0);fe(this,"diversity_penalty",0);fe(this,"repetition_penalty",1);fe(this,"encoder_repetition_penalty",1);fe(this,"length_penalty",1);fe(this,"no_repeat_ngram_size",0);fe(this,"bad_words_ids",null);fe(this,"force_words_ids",null);fe(this,"renormalize_logits",!1);fe(this,"constraints",null);fe(this,"forced_bos_token_id",null);fe(this,"forced_eos_token_id",null);fe(this,"remove_invalid_values",!1);fe(this,"exponential_decay_length_penalty",null);fe(this,"suppress_tokens",null);fe(this,"streamer",null);fe(this,"begin_suppress_tokens",null);fe(this,"forced_decoder_ids",null);fe(this,"guidance_scale",null);fe(this,"num_return_sequences",1);fe(this,"output_attentions",!1);fe(this,"output_hidden_states",!1);fe(this,"output_scores",!1);fe(this,"return_dict_in_generate",!1);fe(this,"pad_token_id",null);fe(this,"bos_token_id",null);fe(this,"eos_token_id",null);fe(this,"encoder_no_repeat_ngram_size",0);fe(this,"decoder_start_token_id",null);fe(this,"generation_kwargs",{});Object.assign(this,(0,_.pick)(Y,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(ze,A,r)=>{r.r(A),r.d(A,{ClassifierFreeGuidanceLogitsProcessor:()=>W,ForcedBOSTokenLogitsProcessor:()=>g,ForcedEOSTokenLogitsProcessor:()=>v,LogitsProcessor:()=>j,LogitsProcessorList:()=>N,LogitsWarper:()=>Y,MinLengthLogitsProcessor:()=>K,MinNewTokensLengthLogitsProcessor:()=>te,NoBadWordsLogitsProcessor:()=>ne,NoRepeatNGramLogitsProcessor:()=>b,RepetitionPenaltyLogitsProcessor:()=>I,SuppressTokensAtBeginLogitsProcessor:()=>y,TemperatureLogitsWarper:()=>U,TopKLogitsWarper:()=>$,TopPLogitsWarper:()=>X,WhisperTimeStampLogitsProcessor:()=>M});var _=r("./src/utils/generic.js");r("./src/utils/tensor.js");var D=r("./src/utils/maths.js");class j extends _.Callable{_call(w,x){throw Error("`_call` should be implemented in a subclass")}}class Y extends _.Callable{_call(w,x){throw Error("`_call` should be implemented in a subclass")}}class N extends _.Callable{constructor(){super(),this.processors=[]}push(w){this.processors.push(w)}extend(w){this.processors.push(...w)}_call(w,x){let O=x;for(const ae of this.processors)O=ae(w,O);return O}[Symbol.iterator](){return this.processors.values()}}class g extends j{constructor(w){super(),this.bos_token_id=w}_call(w,x){for(let O=0;O=1&&ie[ie.length-1]>=this.timestamp_begin,we=ie.length<2||ie[ie.length-2]>=this.timestamp_begin;if(ve&&(we?ae.subarray(this.timestamp_begin).fill(-1/0):ae.subarray(0,this.eos_token_id).fill(-1/0)),w[O].length===this.begin_index&&this.max_initial_timestamp_index!==null){const ke=this.timestamp_begin+this.max_initial_timestamp_index;ae.subarray(ke+1).fill(-1/0)}const re=(0,D.log_softmax)(ae),xe=Math.log(re.subarray(this.timestamp_begin).map(Math.exp).reduce((ke,Ae)=>ke+Ae)),ce=(0,D.max)(re.subarray(0,this.timestamp_begin))[0];xe>ce&&ae.subarray(0,this.timestamp_begin).fill(-1/0)}return x}}class b extends j{constructor(w){super(),this.no_repeat_ngram_size=w}getNgrams(w){const x=w.length,O=[];for(let ie=0;ie1 to use the classifier free guidance processor, got guidance scale ${w}.`);this.guidance_scale=w}_call(w,x){if(x.dims[0]!==2*w.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 ${x.dims[0]} for the logits and ${w.length} for the input ids.`);const O=w.length,ae=x.slice([0,O],null),ie=x.slice([O,x.dims[0]],null);for(let ve=0;ve1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${w}`);if(!Number.isInteger(O)||O<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${O}`);this.top_p=w,this.filter_value=x,this.min_tokens_to_keep=O}}class $ extends Y{constructor(w,{filter_value:x=-1/0,min_tokens_to_keep:O=1}={}){if(super(),!Number.isInteger(w)||w<0)throw new Error(`\`top_k\` must be a positive integer, but is ${w}`);this.top_k=Math.max(w,O),this.filter_value=x}}},"./src/generation/logits_sampler.js":(ze,A,r)=>{r.r(A),r.d(A,{LogitsSampler:()=>Y});var _=r("./src/utils/generic.js"),D=r("./src/utils/tensor.js"),j=r("./src/utils/maths.js");r("./src/generation/configuration_utils.js");class Y extends _.Callable{constructor(M){super(),this.generation_config=M}async _call(M){return this.sample(M)}async sample(M){throw Error("sample should be implemented in subclasses.")}getLogits(M,b){let I=M.dims.at(-1),K=M.data;if(b===-1)K=K.slice(-I);else{let te=b*I;K=K.slice(te,te+I)}return K}randomSelect(M){let b=0;for(let K=0;K1)return new v(M);if(M.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${M.num_return_sequences}.`);return new N(M)}}class N extends Y{async sample(M){const b=(0,j.max)(M.data)[1];return[[BigInt(b),0]]}}class g extends Y{async sample(M){let b=M.dims.at(-1);this.generation_config.top_k>0&&(b=Math.min(this.generation_config.top_k,b));const[I,K]=await(0,D.topk)(M,b),te=(0,j.softmax)(I.data);return Array.from({length:this.generation_config.num_beams},()=>{const ne=this.randomSelect(te);return[K.data[ne],Math.log(te[ne])]})}}class v extends Y{async sample(M){let b=M.dims.at(-1);this.generation_config.top_k>0&&(b=Math.min(this.generation_config.top_k,b));const[I,K]=await(0,D.topk)(M,b),te=(0,j.softmax)(I.data);return Array.from({length:this.generation_config.num_beams},(ne,W)=>[K.data[W],Math.log(te[W])])}}},"./src/generation/stopping_criteria.js":(ze,A,r)=>{r.r(A),r.d(A,{EosTokenCriteria:()=>N,InterruptableStoppingCriteria:()=>g,MaxLengthCriteria:()=>Y,StoppingCriteria:()=>D,StoppingCriteriaList:()=>j});var _=r("./src/utils/generic.js");class D extends _.Callable{_call(y,M){throw Error("StoppingCriteria needs to be subclassed")}}class j extends _.Callable{constructor(){super(),this.criteria=[]}push(y){this.criteria.push(y)}extend(y){y instanceof j?y=y.criteria:y instanceof D&&(y=[y]),this.criteria.push(...y)}_call(y,M){const b=new Array(y.length).fill(!1);for(const I of this.criteria){const K=I(y,M);for(let te=0;teM.length>=this.max_length)}}class N extends D{constructor(y){super(),Array.isArray(y)||(y=[y]),this.eos_token_id=y}_call(y,M){return y.map(b=>{const I=b.at(-1);return this.eos_token_id.some(K=>I==K)})}}class g extends D{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(y,M){return new Array(y.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(ze,A,r)=>{r.r(A),r.d(A,{BaseStreamer:()=>Y,TextStreamer:()=>g,WhisperTextStreamer:()=>v});var _=r("./src/utils/core.js"),D=r("./src/tokenizers.js"),j=r("./src/env.js");class Y{put(M){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const N=j.apis.IS_PROCESS_AVAILABLE?y=>process.stdout.write(y):y=>console.log(y);class g extends Y{constructor(M,{skip_prompt:b=!1,callback_function:I=null,token_callback_function:K=null,skip_special_tokens:te=!0,decode_kwargs:ne={},...W}={}){super(),this.tokenizer=M,this.skip_prompt=b,this.callback_function=I??N,this.token_callback_function=K,this.decode_kwargs={skip_special_tokens:te,...ne,...W},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(M){var te;if(M.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 b=M[0];(te=this.token_callback_function)==null||te.call(this,b),this.token_cache=(0,_.mergeArrays)(this.token_cache,b);const I=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let K;I.endsWith(` +`)?(K=I.slice(this.print_len),this.token_cache=[],this.print_len=0):I.length>0&&(0,D.is_chinese_char)(I.charCodeAt(I.length-1))?(K=I.slice(this.print_len),this.print_len+=K.length):(K=I.slice(this.print_len,I.lastIndexOf(" ")+1),this.print_len+=K.length),this.on_finalized_text(K,!1)}end(){let M;this.token_cache.length>0?(M=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):M="",this.next_tokens_are_prompt=!0,this.on_finalized_text(M,!0)}on_finalized_text(M,b){var I,K;M.length>0&&((I=this.callback_function)==null||I.call(this,M)),b&&this.callback_function===N&&j.apis.IS_PROCESS_AVAILABLE&&((K=this.callback_function)==null||K.call(this,` +`))}}class v extends g{constructor(M,{skip_prompt:b=!1,callback_function:I=null,token_callback_function:K=null,on_chunk_start:te=null,on_chunk_end:ne=null,on_finalize:W=null,time_precision:U=.02,skip_special_tokens:X=!0,decode_kwargs:$={}}={}){super(M,{skip_prompt:b,skip_special_tokens:X,callback_function:I,token_callback_function:K,decode_kwargs:$}),this.timestamp_begin=M.timestamp_begin,this.on_chunk_start=te,this.on_chunk_end=ne,this.on_finalize=W,this.time_precision=U,this.waiting_for_timestamp=!1}put(M){var I,K;if(M.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const b=M[0];if(b.length===1){const te=Number(b[0])-this.timestamp_begin;if(te>=0){const ne=te*this.time_precision;this.waiting_for_timestamp?(I=this.on_chunk_end)==null||I.call(this,ne):(K=this.on_chunk_start)==null||K.call(this,ne),this.waiting_for_timestamp=!this.waiting_for_timestamp,M=[[]]}}return super.put(M)}end(){var M;super.end(),(M=this.on_finalize)==null||M.call(this)}}},"./src/models.js":(ze,A,r)=>{r.r(A),r.d(A,{ASTForAudioClassification:()=>Bi,ASTModel:()=>La,ASTPreTrainedModel:()=>Yt,AlbertForMaskedLM:()=>as,AlbertForQuestionAnswering:()=>Bn,AlbertForSequenceClassification:()=>vn,AlbertModel:()=>zn,AlbertPreTrainedModel:()=>Gr,AutoModel:()=>ba,AutoModelForAudioClassification:()=>va,AutoModelForAudioFrameClassification:()=>wc,AutoModelForCTC:()=>_c,AutoModelForCausalLM:()=>yp,AutoModelForDepthEstimation:()=>vc,AutoModelForDocumentQuestionAnswering:()=>yc,AutoModelForImageClassification:()=>uc,AutoModelForImageFeatureExtraction:()=>Tc,AutoModelForImageMatting:()=>Mc,AutoModelForImageSegmentation:()=>dc,AutoModelForImageToImage:()=>bc,AutoModelForMaskGeneration:()=>fc,AutoModelForMaskedLM:()=>oc,AutoModelForNormalEstimation:()=>xc,AutoModelForObjectDetection:()=>hc,AutoModelForPoseEstimation:()=>Mp,AutoModelForQuestionAnswering:()=>ac,AutoModelForSemanticSegmentation:()=>cc,AutoModelForSeq2SeqLM:()=>sc,AutoModelForSequenceClassification:()=>tc,AutoModelForSpeechSeq2Seq:()=>rc,AutoModelForTextToSpectrogram:()=>nc,AutoModelForTextToWaveform:()=>ic,AutoModelForTokenClassification:()=>wp,AutoModelForUniversalSegmentation:()=>pc,AutoModelForVision2Seq:()=>lc,AutoModelForXVector:()=>gc,AutoModelForZeroShotObjectDetection:()=>mc,BartForConditionalGeneration:()=>Kt,BartForSequenceClassification:()=>hs,BartModel:()=>xt,BartPretrainedModel:()=>ft,BaseModelOutput:()=>je,BeitForImageClassification:()=>ou,BeitModel:()=>iu,BeitPreTrainedModel:()=>ko,BertForMaskedLM:()=>Ue,BertForQuestionAnswering:()=>Re,BertForSequenceClassification:()=>Ve,BertForTokenClassification:()=>Ne,BertModel:()=>Te,BertPreTrainedModel:()=>le,BlenderbotForConditionalGeneration:()=>Js,BlenderbotModel:()=>Le,BlenderbotPreTrainedModel:()=>Ws,BlenderbotSmallForConditionalGeneration:()=>qs,BlenderbotSmallModel:()=>Ss,BlenderbotSmallPreTrainedModel:()=>Fr,BloomForCausalLM:()=>Ol,BloomModel:()=>Il,BloomPreTrainedModel:()=>fo,CLIPModel:()=>qa,CLIPPreTrainedModel:()=>rn,CLIPSegForImageSegmentation:()=>tl,CLIPSegModel:()=>el,CLIPSegPreTrainedModel:()=>Gi,CLIPTextModel:()=>Rc,CLIPTextModelWithProjection:()=>Qa,CLIPVisionModel:()=>Nc,CLIPVisionModelWithProjection:()=>Xa,CamembertForMaskedLM:()=>Jr,CamembertForQuestionAnswering:()=>Zr,CamembertForSequenceClassification:()=>$r,CamembertForTokenClassification:()=>Ar,CamembertModel:()=>Nt,CamembertPreTrainedModel:()=>Tr,CausalLMOutput:()=>Tn,CausalLMOutputWithPast:()=>xp,ChineseCLIPModel:()=>wr,ChineseCLIPPreTrainedModel:()=>jc,ClapAudioModelWithProjection:()=>fd,ClapModel:()=>hd,ClapPreTrainedModel:()=>vi,ClapTextModelWithProjection:()=>md,CodeGenForCausalLM:()=>hl,CodeGenModel:()=>Ji,CodeGenPreTrainedModel:()=>ai,CohereForCausalLM:()=>Wc,CohereModel:()=>Ml,CoherePreTrainedModel:()=>ao,ConvBertForMaskedLM:()=>kt,ConvBertForQuestionAnswering:()=>ws,ConvBertForSequenceClassification:()=>At,ConvBertForTokenClassification:()=>is,ConvBertModel:()=>vt,ConvBertPreTrainedModel:()=>mt,ConvNextForImageClassification:()=>Xc,ConvNextModel:()=>Ho,ConvNextPreTrainedModel:()=>Ko,ConvNextV2ForImageClassification:()=>vu,ConvNextV2Model:()=>Yc,ConvNextV2PreTrainedModel:()=>qo,DPTForDepthEstimation:()=>jn,DPTModel:()=>jo,DPTPreTrainedModel:()=>No,DebertaForMaskedLM:()=>Ir,DebertaForQuestionAnswering:()=>or,DebertaForSequenceClassification:()=>Rr,DebertaForTokenClassification:()=>Nr,DebertaModel:()=>en,DebertaPreTrainedModel:()=>pr,DebertaV2ForMaskedLM:()=>Dt,DebertaV2ForQuestionAnswering:()=>Or,DebertaV2ForSequenceClassification:()=>Vs,DebertaV2ForTokenClassification:()=>jr,DebertaV2Model:()=>Tt,DebertaV2PreTrainedModel:()=>it,DecisionTransformerModel:()=>Cd,DecisionTransformerPreTrainedModel:()=>lp,DeiTForImageClassification:()=>Oo,DeiTModel:()=>Io,DeiTPreTrainedModel:()=>xn,DepthAnythingForDepthEstimation:()=>Uo,DepthAnythingPreTrainedModel:()=>mu,DepthProForDepthEstimation:()=>wu,DepthProPreTrainedModel:()=>gu,DetrForObjectDetection:()=>lu,DetrForSegmentation:()=>uu,DetrModel:()=>au,DetrObjectDetectionOutput:()=>Hr,DetrPreTrainedModel:()=>ci,DetrSegmentationOutput:()=>nn,Dinov2ForImageClassification:()=>Xo,Dinov2Model:()=>xu,Dinov2PreTrainedModel:()=>Qo,Dinov2WithRegistersForImageClassification:()=>Jo,Dinov2WithRegistersModel:()=>Tu,Dinov2WithRegistersPreTrainedModel:()=>Yo,DistilBertForMaskedLM:()=>_n,DistilBertForQuestionAnswering:()=>ts,DistilBertForSequenceClassification:()=>Is,DistilBertForTokenClassification:()=>Pr,DistilBertModel:()=>ar,DistilBertPreTrainedModel:()=>Ms,DonutSwinModel:()=>bu,DonutSwinPreTrainedModel:()=>Go,EfficientNetForImageClassification:()=>bd,EfficientNetModel:()=>Md,EfficientNetPreTrainedModel:()=>na,ElectraForMaskedLM:()=>sr,ElectraForQuestionAnswering:()=>Us,ElectraForSequenceClassification:()=>Sr,ElectraForTokenClassification:()=>Yr,ElectraModel:()=>Ds,ElectraPreTrainedModel:()=>ks,EsmForMaskedLM:()=>$n,EsmForSequenceClassification:()=>An,EsmForTokenClassification:()=>In,EsmModel:()=>si,EsmPreTrainedModel:()=>Ur,ExaoneForCausalLM:()=>ml,ExaoneModel:()=>li,ExaonePreTrainedModel:()=>to,FalconForCausalLM:()=>pd,FalconModel:()=>cd,FalconPreTrainedModel:()=>ta,FastViTForImageClassification:()=>Gc,FastViTModel:()=>Ql,FastViTPreTrainedModel:()=>To,Florence2ForConditionalGeneration:()=>Va,Florence2PreTrainedModel:()=>Ua,GLPNForDepthEstimation:()=>Wo,GLPNModel:()=>_i,GLPNPreTrainedModel:()=>Vo,GPT2LMHeadModel:()=>rl,GPT2Model:()=>sl,GPT2PreTrainedModel:()=>Ki,GPTBigCodeForCausalLM:()=>pl,GPTBigCodeModel:()=>cl,GPTBigCodePreTrainedModel:()=>Yi,GPTJForCausalLM:()=>dl,GPTJModel:()=>ul,GPTJPreTrainedModel:()=>Xi,GPTNeoForCausalLM:()=>ol,GPTNeoModel:()=>Mr,GPTNeoPreTrainedModel:()=>qi,GPTNeoXForCausalLM:()=>ll,GPTNeoXModel:()=>al,GPTNeoXPreTrainedModel:()=>Qi,Gemma2ForCausalLM:()=>xl,Gemma2Model:()=>vl,Gemma2PreTrainedModel:()=>uo,GemmaForCausalLM:()=>bl,GemmaModel:()=>ds,GemmaPreTrainedModel:()=>lo,GraniteForCausalLM:()=>yl,GraniteModel:()=>Vc,GranitePreTrainedModel:()=>oo,GroundingDinoForObjectDetection:()=>Eu,GroundingDinoPreTrainedModel:()=>Pu,GroupViTModel:()=>ql,GroupViTPreTrainedModel:()=>xo,HieraForImageClassification:()=>Do,HieraModel:()=>cu,HieraPreTrainedModel:()=>Fo,HubertForCTC:()=>Yu,HubertForSequenceClassification:()=>Ju,HubertModel:()=>Xu,HubertPreTrainedModel:()=>Np,IJepaForImageClassification:()=>jl,IJepaModel:()=>Nl,IJepaPreTrainedModel:()=>yo,Idefics3ForConditionalGeneration:()=>Ui,Idefics3PreTrainedModel:()=>Ka,ImageMattingOutput:()=>Kn,JAISLMHeadModel:()=>il,JAISModel:()=>nl,JAISPreTrainedModel:()=>Hi,JinaCLIPModel:()=>oi,JinaCLIPPreTrainedModel:()=>ii,JinaCLIPTextModel:()=>Wi,JinaCLIPVisionModel:()=>yr,LlamaForCausalLM:()=>Uc,LlamaModel:()=>eo,LlamaPreTrainedModel:()=>Zi,LlavaForConditionalGeneration:()=>ni,LlavaOnevisionForConditionalGeneration:()=>Na,LlavaPreTrainedModel:()=>Kr,LongT5ForConditionalGeneration:()=>Se,LongT5Model:()=>be,LongT5PreTrainedModel:()=>ue,M2M100ForConditionalGeneration:()=>Un,M2M100Model:()=>gi,M2M100PreTrainedModel:()=>Du,MBartForCausalLM:()=>rr,MBartForConditionalGeneration:()=>Bt,MBartForSequenceClassification:()=>rs,MBartModel:()=>Fs,MBartPreTrainedModel:()=>us,MPNetForMaskedLM:()=>tn,MPNetForQuestionAnswering:()=>Mn,MPNetForSequenceClassification:()=>wn,MPNetForTokenClassification:()=>yn,MPNetModel:()=>gn,MPNetPreTrainedModel:()=>lr,MT5ForConditionalGeneration:()=>gt,MT5Model:()=>pt,MT5PreTrainedModel:()=>Qe,MarianMTModel:()=>Fu,MarianModel:()=>Ou,MarianPreTrainedModel:()=>Zo,MaskFormerForInstanceSegmentation:()=>fi,MaskFormerModel:()=>Mu,MaskFormerPreTrainedModel:()=>yu,MaskedLMOutput:()=>Xs,MgpstrForSceneTextRecognition:()=>Ad,MgpstrModelOutput:()=>up,MgpstrPreTrainedModel:()=>$d,MistralForCausalLM:()=>Lr,MistralModel:()=>Er,MistralPreTrainedModel:()=>ud,MobileBertForMaskedLM:()=>ri,MobileBertForQuestionAnswering:()=>_r,MobileBertForSequenceClassification:()=>Wr,MobileBertModel:()=>On,MobileBertPreTrainedModel:()=>Vr,MobileLLMForCausalLM:()=>Rn,MobileLLMModel:()=>fl,MobileLLMPreTrainedModel:()=>so,MobileNetV1ForImageClassification:()=>xd,MobileNetV1Model:()=>vd,MobileNetV1PreTrainedModel:()=>oa,MobileNetV2ForImageClassification:()=>la,MobileNetV2Model:()=>Td,MobileNetV2PreTrainedModel:()=>aa,MobileNetV3ForImageClassification:()=>da,MobileNetV3Model:()=>ap,MobileNetV3PreTrainedModel:()=>ua,MobileNetV4ForImageClassification:()=>Ed,MobileNetV4Model:()=>Pd,MobileNetV4PreTrainedModel:()=>ca,MobileViTForImageClassification:()=>Zl,MobileViTModel:()=>Jl,MobileViTPreTrainedModel:()=>fr,MobileViTV2ForImageClassification:()=>tu,MobileViTV2Model:()=>eu,MobileViTV2PreTrainedModel:()=>Po,ModelOutput:()=>Ke,ModernBertForMaskedLM:()=>ct,ModernBertForSequenceClassification:()=>lt,ModernBertForTokenClassification:()=>ht,ModernBertModel:()=>dt,ModernBertPreTrainedModel:()=>st,Moondream1ForConditionalGeneration:()=>ja,MoonshineForConditionalGeneration:()=>Ra,MoonshineModel:()=>hr,MoonshinePreTrainedModel:()=>Ni,MptForCausalLM:()=>Dl,MptModel:()=>Fl,MptPreTrainedModel:()=>_o,MultiModalityCausalLM:()=>Sd,MultiModalityPreTrainedModel:()=>kd,MusicgenForCausalLM:()=>op,MusicgenForConditionalGeneration:()=>Ti,MusicgenModel:()=>ip,MusicgenPreTrainedModel:()=>ia,NomicBertModel:()=>oe,NomicBertPreTrainedModel:()=>L,OPTForCausalLM:()=>zl,OPTModel:()=>Ll,OPTPreTrainedModel:()=>go,Olmo2ForCausalLM:()=>wl,Olmo2Model:()=>gl,Olmo2PreTrainedModel:()=>io,OlmoForCausalLM:()=>no,OlmoModel:()=>_l,OlmoPreTrainedModel:()=>ro,OpenELMForCausalLM:()=>Pl,OpenELMModel:()=>Tl,OpenELMPreTrainedModel:()=>co,OwlViTForObjectDetection:()=>ru,OwlViTModel:()=>su,OwlViTPreTrainedModel:()=>Eo,Owlv2ForObjectDetection:()=>Kc,Owlv2Model:()=>nu,Owlv2PreTrainedModel:()=>Co,PaliGemmaForConditionalGeneration:()=>Ga,PaliGemmaPreTrainedModel:()=>Wa,PatchTSMixerForPrediction:()=>Ld,PatchTSMixerModel:()=>Dd,PatchTSMixerPreTrainedModel:()=>pa,PatchTSTForPrediction:()=>Fd,PatchTSTModel:()=>Od,PatchTSTPreTrainedModel:()=>Id,Phi3ForCausalLM:()=>Al,Phi3Model:()=>ui,Phi3PreTrainedModel:()=>mo,Phi3VForCausalLM:()=>mr,Phi3VPreTrainedModel:()=>Ha,PhiForCausalLM:()=>Nn,PhiModel:()=>$l,PhiPreTrainedModel:()=>ho,PreTrainedModel:()=>se,PretrainedMixin:()=>ys,PvtForImageClassification:()=>Vl,PvtModel:()=>bo,PvtPreTrainedModel:()=>di,PyAnnoteForAudioFrameClassification:()=>ju,PyAnnoteModel:()=>Nu,PyAnnotePreTrainedModel:()=>wi,QuestionAnsweringModelOutput:()=>tr,Qwen2ForCausalLM:()=>Cl,Qwen2Model:()=>El,Qwen2PreTrainedModel:()=>po,Qwen2VLForConditionalGeneration:()=>Sl,Qwen2VLPreTrainedModel:()=>kl,RTDetrForObjectDetection:()=>on,RTDetrModel:()=>So,RTDetrObjectDetectionOutput:()=>Qs,RTDetrPreTrainedModel:()=>qr,ResNetForImageClassification:()=>Lo,ResNetModel:()=>pu,ResNetPreTrainedModel:()=>pi,RoFormerForMaskedLM:()=>$e,RoFormerForQuestionAnswering:()=>ut,RoFormerForSequenceClassification:()=>We,RoFormerForTokenClassification:()=>Je,RoFormerModel:()=>me,RoFormerPreTrainedModel:()=>H,RobertaForMaskedLM:()=>gr,RobertaForQuestionAnswering:()=>yt,RobertaForSequenceClassification:()=>ms,RobertaForTokenClassification:()=>$s,RobertaModel:()=>nr,RobertaPreTrainedModel:()=>Ot,SamImageSegmentationOutput:()=>Iu,SamModel:()=>Au,SamPreTrainedModel:()=>Jc,SapiensForDepthEstimation:()=>_u,SapiensForNormalEstimation:()=>Qc,SapiensForSemanticSegmentation:()=>fu,SapiensPreTrainedModel:()=>mi,SegformerForImageClassification:()=>gd,SegformerForSemanticSegmentation:()=>wd,SegformerModel:()=>ir,SegformerPreTrainedModel:()=>ra,Seq2SeqLMOutput:()=>bp,SequenceClassifierOutput:()=>Qt,SiglipModel:()=>Ya,SiglipPreTrainedModel:()=>Vi,SiglipTextModel:()=>Ja,SiglipVisionModel:()=>Za,SpeechT5ForSpeechToText:()=>np,SpeechT5ForTextToSpeech:()=>id,SpeechT5HifiGan:()=>od,SpeechT5Model:()=>rp,SpeechT5PreTrainedModel:()=>bi,SqueezeBertForMaskedLM:()=>Fn,SqueezeBertForQuestionAnswering:()=>Ln,SqueezeBertForSequenceClassification:()=>Dn,SqueezeBertModel:()=>bn,SqueezeBertPreTrainedModel:()=>zt,StableLmForCausalLM:()=>Gn,StableLmModel:()=>yd,StableLmPreTrainedModel:()=>xi,Starcoder2ForCausalLM:()=>dd,Starcoder2Model:()=>an,Starcoder2PreTrainedModel:()=>Qr,StyleTextToSpeech2Model:()=>nd,StyleTextToSpeech2PreTrainedModel:()=>rd,Swin2SRForImageSuperResolution:()=>qc,Swin2SRModel:()=>hu,Swin2SRPreTrainedModel:()=>Ro,SwinForImageClassification:()=>Bo,SwinModel:()=>hi,SwinPreTrainedModel:()=>zo,T5ForConditionalGeneration:()=>q,T5Model:()=>C,T5PreTrainedModel:()=>Pe,TableTransformerForObjectDetection:()=>du,TableTransformerModel:()=>Ao,TableTransformerObjectDetectionOutput:()=>Hc,TableTransformerPreTrainedModel:()=>$o,TokenClassifierOutput:()=>Ks,TrOCRForCausalLM:()=>ld,TrOCRPreTrainedModel:()=>ad,UniSpeechForCTC:()=>Vu,UniSpeechForSequenceClassification:()=>Wu,UniSpeechModel:()=>ea,UniSpeechPreTrainedModel:()=>yi,UniSpeechSatForAudioFrameClassification:()=>tp,UniSpeechSatForCTC:()=>Gu,UniSpeechSatForSequenceClassification:()=>Ku,UniSpeechSatModel:()=>ep,UniSpeechSatPreTrainedModel:()=>Vn,ViTForImageClassification:()=>Rl,ViTMAEModel:()=>Gl,ViTMAEPreTrainedModel:()=>Wl,ViTMSNForImageClassification:()=>Hl,ViTMSNModel:()=>Kl,ViTMSNPreTrainedModel:()=>vo,ViTModel:()=>Bl,ViTPreTrainedModel:()=>wo,VisionEncoderDecoderModel:()=>ji,VitMatteForImageMatting:()=>Yl,VitMattePreTrainedModel:()=>Xl,VitPoseForPoseEstimation:()=>Ul,VitPosePreTrainedModel:()=>Mo,VitsModel:()=>sa,VitsModelOutput:()=>Pc,VitsPreTrainedModel:()=>_d,Wav2Vec2BertForCTC:()=>qu,Wav2Vec2BertForSequenceClassification:()=>Qu,Wav2Vec2BertModel:()=>Hu,Wav2Vec2BertPreTrainedModel:()=>Mi,Wav2Vec2ForAudioFrameClassification:()=>Ru,Wav2Vec2ForCTC:()=>zu,Wav2Vec2ForSequenceClassification:()=>Bu,Wav2Vec2Model:()=>Lu,Wav2Vec2PreTrainedModel:()=>Dr,WavLMForAudioFrameClassification:()=>sp,WavLMForCTC:()=>ed,WavLMForSequenceClassification:()=>td,WavLMForXVector:()=>sd,WavLMModel:()=>Zu,WavLMPreTrainedModel:()=>Wn,WeSpeakerResNetModel:()=>Zc,WeSpeakerResNetPreTrainedModel:()=>Uu,WhisperForConditionalGeneration:()=>Ba,WhisperModel:()=>za,WhisperPreTrainedModel:()=>Ri,XLMForQuestionAnswering:()=>sn,XLMForSequenceClassification:()=>Gs,XLMForTokenClassification:()=>$t,XLMModel:()=>Ls,XLMPreTrainedModel:()=>qt,XLMRobertaForMaskedLM:()=>Oa,XLMRobertaForQuestionAnswering:()=>Da,XLMRobertaForSequenceClassification:()=>zi,XLMRobertaForTokenClassification:()=>Fa,XLMRobertaModel:()=>It,XLMRobertaPreTrainedModel:()=>qe,XLMWithLMHeadModel:()=>As,XVectorOutput:()=>vp,YolosForObjectDetection:()=>Su,YolosModel:()=>ku,YolosObjectDetectionOutput:()=>$u,YolosPreTrainedModel:()=>Cu});var _=r("./src/configs.js"),D=r("./src/backends/onnx.js"),j=r("./src/utils/dtypes.js"),Y=r("./src/utils/generic.js"),N=r("./src/utils/core.js"),g=r("./src/utils/hub.js"),v=r("./src/utils/constants.js"),y=r("./src/generation/logits_process.js"),M=r("./src/generation/configuration_utils.js"),b=r("./src/utils/tensor.js"),I=r("./src/utils/image.js"),K=r("./src/utils/maths.js"),te=r("./src/generation/stopping_criteria.js"),ne=r("./src/generation/logits_sampler.js"),W=r("./src/env.js"),U=r("./src/models/whisper/generation_whisper.js"),X=r("./src/models/whisper/common_whisper.js");const $={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9},S=new Map,w=new Map,x=new Map;async function O(f,T,R){var xs;const _e=((xs=R.config)==null?void 0:xs["transformers.js_config"])??{};let Ie=R.device??_e.device;Ie&&typeof Ie!="string"&&(Ie.hasOwnProperty(T)?Ie=Ie[T]:(console.warn(`device not specified for "${T}". Using the default device.`),Ie=null));const Oe=Ie??(W.apis.IS_NODE_ENV?"cpu":"wasm"),et=(0,D.deviceToExecutionProviders)(Oe);let rt=R.dtype??_e.dtype;if(typeof rt!="string"&&(rt&&rt.hasOwnProperty(T)?rt=rt[T]:(rt=j.DEFAULT_DEVICE_DTYPE_MAPPING[Oe]??j.DATA_TYPES.fp32,console.warn(`dtype not specified for "${T}". Using the default dtype (${rt}) for this device (${Oe}).`))),rt===j.DATA_TYPES.auto){let fs=_e.dtype;typeof fs!="string"&&(fs=fs[T]),fs&&fs!==j.DATA_TYPES.auto&&j.DATA_TYPES.hasOwnProperty(fs)?rt=fs:rt=j.DEFAULT_DEVICE_DTYPE_MAPPING[Oe]??j.DATA_TYPES.fp32}const _t=rt;if(j.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(_t)){if(_t===j.DATA_TYPES.fp16&&Oe==="webgpu"&&!await(0,j.isWebGpuFp16Supported)())throw new Error(`The device (${Oe}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${_t}. Should be one of: ${Object.keys(j.DATA_TYPES).join(", ")}`);const Mt=_e.kv_cache_dtype?typeof _e.kv_cache_dtype=="string"?_e.kv_cache_dtype:_e.kv_cache_dtype[_t]??"float32":void 0;if(Mt&&!["float32","float16"].includes(Mt))throw new Error(`Invalid kv_cache_dtype: ${Mt}. Should be one of: float32, float16`);const jt={dtype:_t,kv_cache_dtype:Mt},Vt=j.DEFAULT_DTYPE_SUFFIX_MAPPING[_t],Lt=`${R.subfolder??""}/${T}${Vt}.onnx`,Gt={...R.session_options};Gt.executionProviders??(Gt.executionProviders=et);const es=_e.free_dimension_overrides;es?Gt.freeDimensionOverrides??(Gt.freeDimensionOverrides=es):Oe.startsWith("webnn")&&!Gt.freeDimensionOverrides&&console.warn('WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.');const ns=(0,g.getModelFile)(f,Lt,!0,R),Jt=R.use_external_data_format??_e.use_external_data_format;let os=[];if(Jt&&(Jt===!0||typeof Jt=="object"&&Jt.hasOwnProperty(T)&&Jt[T]===!0)){if(W.apis.IS_NODE_ENV)throw new Error("External data format is not yet supported in Node.js");const fs=`${T}${Vt}.onnx_data`,Es=`${R.subfolder??""}/${fs}`;os.push(new Promise(async(Os,Zs)=>{const Ys=await(0,g.getModelFile)(f,Es,!0,R);Os({path:fs,data:Ys})}))}else Gt.externalData!==void 0&&(os=Gt.externalData.map(async fs=>{if(typeof fs.data=="string"){const Es=await(0,g.getModelFile)(f,fs.data,!0,R);return{...fs,data:Es}}return fs}));if(os.length>0&&(Gt.externalData=await Promise.all(os)),Oe==="webgpu"){const fs=(0,_.getKeyValueShapes)(R.config,{prefix:"present"});if(Object.keys(fs).length>0&&!(0,D.isONNXProxy)()){const Es={};for(const Os in fs)Es[Os]="gpu-buffer";Gt.preferredOutputLocation=Es}}return{buffer:await ns,session_options:Gt,session_config:jt}}async function ae(f,T,R){return Object.fromEntries(await Promise.all(Object.keys(T).map(async _e=>{const{buffer:Ie,session_options:Oe,session_config:et}=await O(f,T[_e],R),rt=await(0,D.createInferenceSession)(Ie,Oe,et);return[_e,rt]})))}async function ie(f,T,R){return Object.fromEntries(await Promise.all(Object.keys(T).map(async _e=>{const Ie=await(0,g.getModelJSON)(f,T[_e],!1,R);return[_e,Ie]})))}function ve(f,T){const R=Object.create(null),_e=[];for(const et of f.inputNames){const rt=T[et];if(!(rt instanceof b.Tensor)){_e.push(et);continue}R[et]=(0,D.isONNXProxy)()?rt.clone():rt}if(_e.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${_e.join(", ")}.`);const Ie=Object.keys(T).length,Oe=f.inputNames.length;if(Ie>Oe){let et=Object.keys(T).filter(rt=>!f.inputNames.includes(rt));console.warn(`WARNING: Too many inputs were provided (${Ie} > ${Oe}). The following inputs will be ignored: "${et.join(", ")}".`)}return R}async function we(f,T){const R=ve(f,T);try{const _e=Object.fromEntries(Object.entries(R).map(([Oe,et])=>[Oe,et.ort_tensor]));let Ie=await f.run(_e);return Ie=re(Ie),Ie}catch(_e){const Ie=Object.fromEntries(Object.entries(R).map(([Oe,{type:et,dims:rt,data:_t}])=>[Oe,{type:et,dims:rt,data:_t}]));throw console.error(`An error occurred during model execution: "${_e}".`),console.error("Inputs given to model:",Ie),_e}}function re(f){for(let T in f)(0,D.isONNXTensor)(f[T])?f[T]=new b.Tensor(f[T]):typeof f[T]=="object"&&re(f[T]);return f}function xe(f){if(f instanceof b.Tensor)return f;if(f.length===0)throw Error("items must be non-empty");if(Array.isArray(f[0])){if(f.some(T=>T.length!==f[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 b.Tensor("int64",BigInt64Array.from(f.flat().map(T=>BigInt(T))),[f.length,f[0].length])}else return new b.Tensor("int64",BigInt64Array.from(f.map(T=>BigInt(T))),[1,f.length])}function ce(f){return new b.Tensor("bool",[f],[1])}async function ke(f,T){let{encoder_outputs:R,input_ids:_e,decoder_input_ids:Ie,...Oe}=T;if(!R){const rt=(0,N.pick)(T,f.sessions.model.inputNames);R=(await Ae(f,rt)).last_hidden_state}return Oe.input_ids=Ie,Oe.encoder_hidden_states=R,f.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(Oe.encoder_attention_mask=T.attention_mask),await Ee(f,Oe,!0)}async function Ae(f,T){const R=f.sessions.model,_e=(0,N.pick)(T,R.inputNames);if(R.inputNames.includes("inputs_embeds")&&!_e.inputs_embeds){if(!T.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");_e.inputs_embeds=await f.encode_text({input_ids:T.input_ids})}if(R.inputNames.includes("token_type_ids")&&!_e.token_type_ids){if(!_e.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");_e.token_type_ids=(0,b.zeros_like)(_e.input_ids)}if(R.inputNames.includes("pixel_mask")&&!_e.pixel_mask){if(!_e.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const Ie=_e.pixel_values.dims;_e.pixel_mask=(0,b.ones)([Ie[0],Ie[2],Ie[3]])}return await we(R,_e)}async function Ee(f,T,R=!1){const _e=f.sessions[R?"decoder_model_merged":"model"],{past_key_values:Ie,...Oe}=T;if(_e.inputNames.includes("use_cache_branch")&&(Oe.use_cache_branch=ce(!!Ie)),_e.inputNames.includes("position_ids")&&Oe.attention_mask&&!Oe.position_ids){const rt=f.config.model_type==="paligemma"?1:0;Oe.position_ids=J(Oe,Ie,rt)}f.addPastKeyValues(Oe,Ie);const et=(0,N.pick)(Oe,_e.inputNames);return await we(_e,et)}function tt({image_token_id:f,inputs_embeds:T,image_features:R,input_ids:_e,attention_mask:Ie}){const Oe=_e.tolist().map(Mt=>Mt.reduce((jt,Vt,Lt)=>(Vt==f&&jt.push(Lt),jt),[])),et=Oe.reduce((Mt,jt)=>Mt+jt.length,0),rt=R.dims[0];if(et!==rt)throw new Error(`Image features and image tokens do not match: tokens: ${et}, features ${rt}`);let _t=0;for(let Mt=0;MtOe.dims[1])){if(Iert==f.config.image_token_index)){const rt=f.config.num_image_tokens;if(!rt)throw new Error("`num_image_tokens` is missing in the model configuration.");const _t=Oe.dims[1]-(Ie-rt);R.input_ids=Oe.slice(null,[-_t,null]),R.attention_mask=(0,b.ones)([1,Ie+_t])}}}return R}function Ce(f,T,R,_e){return R.past_key_values&&(T=T.map(Ie=>[Ie.at(-1)])),{...R,decoder_input_ids:xe(T)}}function Be(f,...T){return f.config.is_encoder_decoder?Ce(f,...T):de(f,...T)}function Ze(f,T,R,_e){const Ie=!!R.past_key_values;return _e.guidance_scale!==null&&_e.guidance_scale>1&&(Ie?R.input_ids=(0,b.cat)([R.input_ids,R.input_ids],0):(R.input_ids=(0,b.cat)([R.input_ids,(0,b.full_like)(R.input_ids,BigInt(_e.pad_token_id))],0),R.attention_mask=(0,b.cat)([R.attention_mask,(0,b.full_like)(R.attention_mask,0n)],0))),(Ie||!R.pixel_values)&&(R.pixel_values=(0,b.full)([0,0,3,384,384],1)),Ie&&(R.images_seq_mask=new b.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),R.images_emb_mask=new b.Tensor("bool",new Array(0).fill(!1),[1,1,0])),R}class se extends Y.Callable{constructor(R,_e,Ie){super();fe(this,"main_input_name","input_ids");fe(this,"forward_params",["input_ids","attention_mask"]);this.config=R,this.sessions=_e,this.configs=Ie;const Oe=x.get(this.constructor),et=S.get(Oe);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,et){case $.DecoderOnly:this.can_generate=!0,this._forward=Ee,this._prepare_inputs_for_generation=de;break;case $.Seq2Seq:case $.Vision2Seq:case $.Musicgen:this.can_generate=!0,this._forward=ke,this._prepare_inputs_for_generation=Ce;break;case $.EncoderDecoder:this._forward=ke;break;case $.ImageTextToText:this.can_generate=!0,this._forward=Ge,this._prepare_inputs_for_generation=Be;break;case $.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=Be;break;case $.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Ze;break;default:this._forward=Ae;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var _e;const R=[];for(const Ie of Object.values(this.sessions))(_e=Ie==null?void 0:Ie.handler)!=null&&_e.dispose&&R.push(Ie.handler.dispose());return await Promise.all(R)}static async from_pretrained(R,{progress_callback:_e=null,config:Ie=null,cache_dir:Oe=null,local_files_only:et=!1,revision:rt="main",model_file_name:_t=null,subfolder:Mt="onnx",device:jt=null,dtype:Vt=null,use_external_data_format:Lt=null,session_options:Gt={}}={}){let es={progress_callback:_e,config:Ie,cache_dir:Oe,local_files_only:et,revision:rt,model_file_name:_t,subfolder:Mt,device:jt,dtype:Vt,use_external_data_format:Lt,session_options:Gt};const ns=x.get(this),Jt=S.get(ns);Ie=es.config=await _.AutoConfig.from_pretrained(R,es);let os;if(Jt===$.DecoderOnly)os=await Promise.all([ae(R,{model:es.model_file_name??"model"},es),ie(R,{generation_config:"generation_config.json"},es)]);else if(Jt===$.Seq2Seq||Jt===$.Vision2Seq)os=await Promise.all([ae(R,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},es),ie(R,{generation_config:"generation_config.json"},es)]);else if(Jt===$.MaskGeneration)os=await Promise.all([ae(R,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},es)]);else if(Jt===$.EncoderDecoder)os=await Promise.all([ae(R,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},es)]);else if(Jt===$.ImageTextToText){const Cs={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Ie.is_encoder_decoder&&(Cs.model="encoder_model"),os=await Promise.all([ae(R,Cs,es),ie(R,{generation_config:"generation_config.json"},es)])}else if(Jt===$.Musicgen)os=await Promise.all([ae(R,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},es),ie(R,{generation_config:"generation_config.json"},es)]);else if(Jt===$.MultiModality)os=await Promise.all([ae(R,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},es),ie(R,{generation_config:"generation_config.json"},es)]);else if(Jt===$.Phi3V)os=await Promise.all([ae(R,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},es),ie(R,{generation_config:"generation_config.json"},es)]);else{if(Jt!==$.EncoderOnly){const Cs=ns??(Ie==null?void 0:Ie.model_type);Cs!=="custom"&&console.warn(`Model type for '${Cs}' not found, assuming encoder-only architecture. Please report this at ${v.GITHUB_ISSUE_URL}.`)}os=await Promise.all([ae(R,{model:es.model_file_name??"model"},es)])}return new this(Ie,...os)}async _call(R){return await this.forward(R)}async forward(R){return await this._forward(this,R)}get generation_config(){var R;return((R=this.configs)==null?void 0:R.generation_config)??null}_get_logits_warper(R){const _e=new y.LogitsProcessorList;return R.temperature!==null&&R.temperature!==1&&_e.push(new y.TemperatureLogitsWarper(R.temperature)),R.top_k!==null&&R.top_k!==0&&_e.push(new y.TopKLogitsWarper(R.top_k)),R.top_p!==null&&R.top_p<1&&_e.push(new y.TopPLogitsWarper(R.top_p)),_e}_get_logits_processor(R,_e,Ie=null){const Oe=new y.LogitsProcessorList;if(R.repetition_penalty!==null&&R.repetition_penalty!==1&&Oe.push(new y.RepetitionPenaltyLogitsProcessor(R.repetition_penalty)),R.no_repeat_ngram_size!==null&&R.no_repeat_ngram_size>0&&Oe.push(new y.NoRepeatNGramLogitsProcessor(R.no_repeat_ngram_size)),R.bad_words_ids!==null&&Oe.push(new y.NoBadWordsLogitsProcessor(R.bad_words_ids,R.eos_token_id)),R.min_length!==null&&R.eos_token_id!==null&&R.min_length>0&&Oe.push(new y.MinLengthLogitsProcessor(R.min_length,R.eos_token_id)),R.min_new_tokens!==null&&R.eos_token_id!==null&&R.min_new_tokens>0&&Oe.push(new y.MinNewTokensLengthLogitsProcessor(_e,R.min_new_tokens,R.eos_token_id)),R.forced_bos_token_id!==null&&Oe.push(new y.ForcedBOSTokenLogitsProcessor(R.forced_bos_token_id)),R.forced_eos_token_id!==null&&Oe.push(new y.ForcedEOSTokenLogitsProcessor(R.max_length,R.forced_eos_token_id)),R.begin_suppress_tokens!==null){const et=_e>1||R.forced_bos_token_id===null?_e:_e+1;Oe.push(new y.SuppressTokensAtBeginLogitsProcessor(R.begin_suppress_tokens,et))}return R.guidance_scale!==null&&R.guidance_scale>1&&Oe.push(new y.ClassifierFreeGuidanceLogitsProcessor(R.guidance_scale)),Ie!==null&&Oe.extend(Ie),Oe}_prepare_generation_config(R,_e,Ie=M.GenerationConfig){const Oe={...this.config};for(const rt of["decoder","generator","text_config"])rt in Oe&&Object.assign(Oe,Oe[rt]);const et=new Ie(Oe);return Object.assign(et,this.generation_config??{}),R&&Object.assign(et,R),_e&&Object.assign(et,(0,N.pick)(_e,Object.getOwnPropertyNames(et))),et}_get_stopping_criteria(R,_e=null){const Ie=new te.StoppingCriteriaList;return R.max_length!==null&&Ie.push(new te.MaxLengthCriteria(R.max_length,this.config.max_position_embeddings??null)),R.eos_token_id!==null&&Ie.push(new te.EosTokenCriteria(R.eos_token_id)),_e&&Ie.extend(_e),Ie}_validate_model_class(){if(!this.can_generate){const R=[jd,Ei,ma,ha],_e=x.get(this.constructor),Ie=new Set,Oe=this.config.model_type;for(const rt of R){const _t=rt.get(Oe);_t&&Ie.add(_t[0])}let et=`The current model class (${_e}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw Ie.size>0&&(et+=` Please use the following class instead: ${[...Ie].join(", ")}`),Error(et)}}prepare_inputs_for_generation(...R){return this._prepare_inputs_for_generation(this,...R)}_update_model_kwargs_for_generation({generated_input_ids:R,outputs:_e,model_inputs:Ie,is_encoder_decoder:Oe}){return Ie.past_key_values=this.getPastKeyValues(_e,Ie.past_key_values),Ie.input_ids=new b.Tensor("int64",R.flat(),[R.length,1]),Oe||(Ie.attention_mask=(0,b.cat)([Ie.attention_mask,(0,b.ones)([Ie.attention_mask.dims[0],1])],1)),Ie.position_ids=null,Ie}_prepare_model_inputs({inputs:R,bos_token_id:_e,model_kwargs:Ie}){const Oe=(0,N.pick)(Ie,this.forward_params),et=this.main_input_name;if(et in Oe){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 Oe[et]=R;return{inputs_tensor:Oe[et],model_inputs:Oe,model_input_name:et}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:R,model_inputs:_e,model_input_name:Ie,generation_config:Oe}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!_e.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:rt,pixel_values:_t,attention_mask:Mt,...jt}=_e,Vt=await this._prepare_inputs_embeds(_e);_e={...jt,...(0,N.pick)(Vt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:et}=await Ae(this,_e);if(Oe.guidance_scale!==null&&Oe.guidance_scale>1)et=(0,b.cat)([et,(0,b.full_like)(et,0)],0),"attention_mask"in _e&&(_e.attention_mask=(0,b.cat)([_e.attention_mask,(0,b.zeros_like)(_e.attention_mask)],0));else if(_e.decoder_input_ids){const rt=xe(_e.decoder_input_ids).dims[0];if(rt!==et.dims[0]){if(et.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${et.dims[0]}) than the decoder inputs (${rt}).`);et=(0,b.cat)(Array.from({length:rt},()=>et),0)}}return _e.encoder_outputs=et,_e}_prepare_decoder_input_ids_for_generation({batch_size:R,model_input_name:_e,model_kwargs:Ie,decoder_start_token_id:Oe,bos_token_id:et,generation_config:rt}){let{decoder_input_ids:_t,...Mt}=Ie;if(!(_t instanceof b.Tensor)){if(_t)Array.isArray(_t[0])||(_t=Array.from({length:R},()=>_t));else if(Oe??(Oe=et),this.config.model_type==="musicgen")_t=Array.from({length:R*this.config.decoder.num_codebooks},()=>[Oe]);else if(Array.isArray(Oe)){if(Oe.length!==R)throw new Error(`\`decoder_start_token_id\` expcted to have length ${R} but got ${Oe.length}`);_t=Oe}else _t=Array.from({length:R},()=>[Oe]);_t=xe(_t)}return Ie.decoder_attention_mask=(0,b.ones_like)(_t),{input_ids:_t,model_inputs:Mt}}async generate({inputs:R=null,generation_config:_e=null,logits_processor:Ie=null,stopping_criteria:Oe=null,streamer:et=null,...rt}){this._validate_model_class(),_e=this._prepare_generation_config(_e,rt);let{inputs_tensor:_t,model_inputs:Mt,model_input_name:jt}=this._prepare_model_inputs({inputs:R,model_kwargs:rt});const Vt=this.config.is_encoder_decoder;Vt&&("encoder_outputs"in Mt||(Mt=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:_t,model_inputs:Mt,model_input_name:jt,generation_config:_e})));let Lt;Vt?{input_ids:Lt,model_inputs:Mt}=this._prepare_decoder_input_ids_for_generation({batch_size:Mt[jt].dims.at(0),model_input_name:jt,model_kwargs:Mt,decoder_start_token_id:_e.decoder_start_token_id,bos_token_id:_e.bos_token_id,generation_config:_e}):Lt=Mt[jt];let Gt=Lt.dims.at(-1);_e.max_new_tokens!==null&&(_e.max_length=Gt+_e.max_new_tokens);const es=this._get_logits_processor(_e,Gt,Ie),ns=this._get_stopping_criteria(_e,Oe),Jt=Mt[jt].dims.at(0),os=ne.LogitsSampler.getSampler(_e),Cs=new Array(Jt).fill(0),xs=Lt.tolist();et&&et.put(xs);let fs,Es={};for(;;){if(Mt=this.prepare_inputs_for_generation(xs,Mt,_e),fs=await this.forward(Mt),_e.output_attentions&&_e.return_dict_in_generate){const ur=this.getAttentions(fs);for(const Cr in ur)Cr in Es||(Es[Cr]=[]),Es[Cr].push(ur[Cr])}const Ys=fs.logits.slice(null,-1,null),br=es(xs,Ys),Pn=[];for(let ur=0;urur))break;Mt=this._update_model_kwargs_for_generation({generated_input_ids:Pn,outputs:fs,model_inputs:Mt,is_encoder_decoder:Vt})}et&&et.end();const Os=this.getPastKeyValues(fs,Mt.past_key_values,!0),Zs=new b.Tensor("int64",xs.flat(),[xs.length,xs[0].length]);if(_e.return_dict_in_generate)return{sequences:Zs,past_key_values:Os,...Es};for(const Ys of Object.values(fs))Ys.location==="gpu-buffer"&&Ys.dispose();return Zs}getPastKeyValues(R,_e,Ie=!1){const Oe=Object.create(null);for(const et in R)if(et.startsWith("present")){const rt=et.replace("present","past_key_values"),_t=et.includes("encoder");if(_t&&_e?Oe[rt]=_e[rt]:Oe[rt]=R[et],_e&&(!_t||Ie)){const Mt=_e[rt];Mt.location==="gpu-buffer"&&Mt.dispose()}}return Oe}getAttentions(R){const _e={};for(const Ie of["cross_attentions","encoder_attentions","decoder_attentions"])for(const Oe in R)Oe.startsWith(Ie)&&(Ie in _e||(_e[Ie]=[]),_e[Ie].push(R[Oe]));return _e}addPastKeyValues(R,_e){var Ie,Oe,et;if(_e)Object.assign(R,_e);else{const rt=this.sessions.decoder_model_merged??this.sessions.model,_t=((Ie=rt==null?void 0:rt.config)==null?void 0:Ie.kv_cache_dtype)??"float32",Mt=_t==="float16"?new Uint16Array:[],jt=((et=(Oe=R[this.main_input_name]??R.attention_mask)==null?void 0:Oe.dims)==null?void 0:et[0])??1,Vt=(0,_.getKeyValueShapes)(this.config,{batch_size:jt});for(const Lt in Vt)R[Lt]=new b.Tensor(_t,Mt,Vt[Lt])}}async encode_image({pixel_values:R}){const _e=(await we(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 (${_e.dims[1]}).`),this.config.num_image_tokens=_e.dims[1]),_e}async encode_text({input_ids:R}){return(await we(this.sessions.embed_tokens,{input_ids:R})).inputs_embeds}}class Ke{}class je extends Ke{constructor({last_hidden_state:T,hidden_states:R=null,attentions:_e=null}){super(),this.last_hidden_state=T,this.hidden_states=R,this.attentions=_e}}class le extends se{}class Te extends le{}class Ue extends le{async _call(T){return new Xs(await super._call(T))}}class Ve extends le{async _call(T){return new Qt(await super._call(T))}}class Ne extends le{async _call(T){return new Ks(await super._call(T))}}class Re extends le{async _call(T){return new tr(await super._call(T))}}class st extends se{}class dt extends st{}class ct extends st{async _call(T){return new Xs(await super._call(T))}}class lt extends st{async _call(T){return new Qt(await super._call(T))}}class ht extends st{async _call(T){return new Ks(await super._call(T))}}class L extends se{}class oe extends L{}class H extends se{}class me extends H{}class $e extends H{async _call(T){return new Xs(await super._call(T))}}class We extends H{async _call(T){return new Qt(await super._call(T))}}class Je extends H{async _call(T){return new Ks(await super._call(T))}}class ut extends H{async _call(T){return new tr(await super._call(T))}}class mt extends se{}class vt extends mt{}class kt extends mt{async _call(T){return new Xs(await super._call(T))}}class At extends mt{async _call(T){return new Qt(await super._call(T))}}class is extends mt{async _call(T){return new Ks(await super._call(T))}}class ws extends mt{async _call(T){return new tr(await super._call(T))}}class ks extends se{}class Ds extends ks{}class sr extends ks{async _call(T){return new Xs(await super._call(T))}}class Sr extends ks{async _call(T){return new Qt(await super._call(T))}}class Yr extends ks{async _call(T){return new Ks(await super._call(T))}}class Us extends ks{async _call(T){return new tr(await super._call(T))}}class Tr extends se{}class Nt extends Tr{}class Jr extends Tr{async _call(T){return new Xs(await super._call(T))}}class $r extends Tr{async _call(T){return new Qt(await super._call(T))}}class Ar extends Tr{async _call(T){return new Ks(await super._call(T))}}class Zr extends Tr{async _call(T){return new tr(await super._call(T))}}class pr extends se{}class en extends pr{}class Ir extends pr{async _call(T){return new Xs(await super._call(T))}}class Rr extends pr{async _call(T){return new Qt(await super._call(T))}}class Nr extends pr{async _call(T){return new Ks(await super._call(T))}}class or extends pr{async _call(T){return new tr(await super._call(T))}}class it extends se{}class Tt extends it{}class Dt extends it{async _call(T){return new Xs(await super._call(T))}}class Vs extends it{async _call(T){return new Qt(await super._call(T))}}class jr extends it{async _call(T){return new Ks(await super._call(T))}}class Or extends it{async _call(T){return new tr(await super._call(T))}}class Ms extends se{}class ar extends Ms{}class Is extends Ms{async _call(T){return new Qt(await super._call(T))}}class Pr extends Ms{async _call(T){return new Ks(await super._call(T))}}class ts extends Ms{async _call(T){return new tr(await super._call(T))}}class _n extends Ms{async _call(T){return new Xs(await super._call(T))}}class Ur extends se{}class si extends Ur{}class $n extends Ur{async _call(T){return new Xs(await super._call(T))}}class An extends Ur{async _call(T){return new Qt(await super._call(T))}}class In extends Ur{async _call(T){return new Ks(await super._call(T))}}class Vr extends se{}class On extends Vr{}class ri extends Vr{async _call(T){return new Xs(await super._call(T))}}class Wr extends Vr{async _call(T){return new Qt(await super._call(T))}}class _r extends Vr{async _call(T){return new tr(await super._call(T))}}class lr extends se{}class gn extends lr{}class tn extends lr{async _call(T){return new Xs(await super._call(T))}}class wn extends lr{async _call(T){return new Qt(await super._call(T))}}class yn extends lr{async _call(T){return new Ks(await super._call(T))}}class Mn extends lr{async _call(T){return new tr(await super._call(T))}}class zt extends se{}class bn extends zt{}class Fn extends zt{async _call(T){return new Xs(await super._call(T))}}class Dn extends zt{async _call(T){return new Qt(await super._call(T))}}class Ln extends zt{async _call(T){return new tr(await super._call(T))}}class Gr extends se{}class zn extends Gr{}class vn extends Gr{async _call(T){return new Qt(await super._call(T))}}class Bn extends Gr{async _call(T){return new tr(await super._call(T))}}class as extends Gr{async _call(T){return new Xs(await super._call(T))}}class Pe extends se{constructor(){super(...arguments);fe(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class C extends Pe{}class q extends Pe{}class ue extends se{}class be extends ue{}class Se extends ue{}class Qe extends se{}class pt extends Qe{}class gt extends Qe{}class ft extends se{}class xt extends ft{}class Kt extends ft{}class hs extends ft{async _call(T){return new Qt(await super._call(T))}}class us extends se{}class Fs extends us{}class Bt extends us{}class rs extends us{async _call(T){return new Qt(await super._call(T))}}class rr extends us{}class Ws extends se{}class Le extends Ws{}class Js extends Ws{}class Fr extends se{}class Ss extends Fr{}class qs extends Fr{}class Ot extends se{}class nr extends Ot{}class gr extends Ot{async _call(T){return new Xs(await super._call(T))}}class ms extends Ot{async _call(T){return new Qt(await super._call(T))}}class $s extends Ot{async _call(T){return new Ks(await super._call(T))}}class yt extends Ot{async _call(T){return new tr(await super._call(T))}}class qt extends se{}class Ls extends qt{}class As extends qt{async _call(T){return new Xs(await super._call(T))}}class Gs extends qt{async _call(T){return new Qt(await super._call(T))}}class $t extends qt{async _call(T){return new Ks(await super._call(T))}}class sn extends qt{async _call(T){return new tr(await super._call(T))}}class qe extends se{}class It extends qe{}class Oa extends qe{async _call(T){return new Xs(await super._call(T))}}class zi extends qe{async _call(T){return new Qt(await super._call(T))}}class Fa extends qe{async _call(T){return new Ks(await super._call(T))}}class Da extends qe{async _call(T){return new tr(await super._call(T))}}class Yt extends se{}class La extends Yt{}class Bi extends Yt{}class Ri extends se{constructor(){super(...arguments);fe(this,"requires_attention_mask",!1);fe(this,"main_input_name","input_features");fe(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class za extends Ri{}class Ba extends Ri{_prepare_generation_config(T,R){return super._prepare_generation_config(T,R,U.WhisperGenerationConfig)}_retrieve_init_tokens(T){const R=[T.decoder_start_token_id];let _e=T.language;const Ie=T.task;if(T.is_multilingual){_e||(console.warn("No language specified - defaulting to English (en)."),_e="en");const et=`<|${(0,X.whisper_language_to_code)(_e)}|>`;R.push(T.lang_to_id[et]),R.push(T.task_to_id[Ie??"transcribe"])}else if(_e||Ie)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!T.return_timestamps&&T.no_timestamps_token_id&&R.at(-1)!==T.no_timestamps_token_id?R.push(T.no_timestamps_token_id):T.return_timestamps&&R.at(-1)===T.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),R.pop()),R.filter(Oe=>Oe!=null)}async generate({inputs:T=null,generation_config:R=null,logits_processor:_e=null,stopping_criteria:Ie=null,...Oe}){R=this._prepare_generation_config(R,Oe);const et=Oe.decoder_input_ids??this._retrieve_init_tokens(R);if(R.return_timestamps&&(_e??(_e=new y.LogitsProcessorList),_e.push(new y.WhisperTimeStampLogitsProcessor(R,et))),R.begin_suppress_tokens&&(_e??(_e=new y.LogitsProcessorList),_e.push(new y.SuppressTokensAtBeginLogitsProcessor(R.begin_suppress_tokens,et.length))),R.return_token_timestamps){if(!R.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.");R.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),R.output_attentions=!0,R.return_dict_in_generate=!0}const rt=await super.generate({inputs:T,generation_config:R,logits_processor:_e,decoder_input_ids:et,...Oe});return R.return_token_timestamps&&(rt.token_timestamps=this._extract_token_timestamps(rt,R.alignment_heads,R.num_frames)),rt}_extract_token_timestamps(T,R,_e=null,Ie=.02){if(!T.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`.");_e==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 Oe=this.config.median_filter_width;Oe===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),Oe=7);const et=T.cross_attentions,rt=Array.from({length:this.config.decoder_layers},(ns,Jt)=>(0,b.cat)(et.map(os=>os[Jt]),2)),_t=(0,b.stack)(R.map(([ns,Jt])=>{if(ns>=rt.length)throw new Error(`Layer index ${ns} is out of bounds for cross attentions (length ${rt.length}).`);return _e?rt[ns].slice(null,Jt,null,[0,_e]):rt[ns].slice(null,Jt)})).transpose(1,0,2,3),[Mt,jt]=(0,b.std_mean)(_t,-2,0,!0),Vt=_t.clone();for(let ns=0;nsos[Zs+1]-os[Zs]),fs=(0,N.mergeArrays)([1],xs).map(Os=>!!Os),Es=[];for(let Os=0;OsLt.findIndex(Gt=>Gt==Oe)),_t=rt.every(Lt=>Lt===-1),Mt=rt.every(Lt=>Lt!==-1);if(!_t&&!Mt)throw new Error("Every input should contain either 0 or 1 image token.");if(_t)return{inputs_embeds:T,attention_mask:Ie};const jt=[],Vt=[];for(let Lt=0;LtArray.from({length:T.dims[0]},xs=>Array.from({length:T.dims[1]},fs=>1))),es=R?R.tolist():[],ns=_e?_e.tolist():[];let Jt=0,os=0;for(let Cs=0;CsLt[Cs][zs]==1),Es=xs.reduce((Ts,zs,zr)=>(zs==_t&&Ts.push(zr),Ts),[]).map(Ts=>xs[Ts+1]),Os=Es.filter(Ts=>Ts==et).length,Zs=Es.filter(Ts=>Ts==rt).length;let Ys=[],br=0,Pn=Os,xa=Zs;for(let Ts=0;Tsdr>br&&dn==et),zr=xs.findIndex((dn,dr)=>dr>br&&dn==rt),ln=Pn>0&&zs!==-1?zs:xs.length+1,En=xa>0&&zr!==-1?zr:xs.length+1;let Ta,Si,Pa,Ea;ln0?(0,K.max)(Ys.at(-1))[0]+1:0;Ys.push(Array.from({length:3*ka},(dn,dr)=>Cc+dr%ka));const kc=ka+Cc,$i=jp*Ca*Cn,Sc=Array.from({length:$i},(dn,dr)=>kc+Math.floor(dr/(Ca*Cn))),$c=Array.from({length:$i},(dn,dr)=>kc+Math.floor(dr/Cn)%Ca),un=Array.from({length:$i},(dn,dr)=>kc+dr%Cn);Ys.push([Sc,$c,un].flat()),br=Ta+$i}if(br0?(0,K.max)(Ys.at(-1))[0]+1:0,zs=xs.length-br;Ys.push(Array.from({length:3*zs},(zr,ln)=>Ts+ln%zs))}const ur=Ys.reduce((Ts,zs)=>Ts+zs.length,0),Cr=new Array(ur);let Ec=0;for(let Ts=0;Ts<3;++Ts)for(let zs=0;zsVt[Jt%Vt.length]),es=Array.from({length:Lt[0]},(ns,Jt)=>(0,K.max)(Vt.subarray(Lt[1]*Jt,Lt[1]*(Jt+1)))[0]+1n+BigInt(Lt[1]));return[new b.Tensor("int64",Gt,[3,...Lt]),new b.Tensor("int64",es,[es.length,1])]}else{const[Vt,Lt]=T.dims,Gt=BigInt64Array.from({length:3*Vt*Lt},(es,ns)=>BigInt(Math.floor(ns%Lt/Vt)));return[new b.Tensor("int64",Gt,[3,...T.dims]),(0,b.zeros)([Vt,1])]}}async encode_image({pixel_values:T,image_grid_thw:R}){return(await we(this.sessions.vision_encoder,{pixel_values:T,grid_thw:R})).image_features}_merge_input_ids_with_image_features(T){return tt({image_token_id:this.config.image_token_id,...T})}prepare_inputs_for_generation(T,R,_e){if(R.attention_mask&&!R.position_ids)if(!R.past_key_values)[R.position_ids,R.rope_deltas]=this.get_rope_index(R.input_ids,R.image_grid_thw,R.video_grid_thw,R.attention_mask);else{R.pixel_values=null;const Ie=BigInt(Object.values(R.past_key_values)[0].dims.at(-2)),Oe=R.rope_deltas.map(et=>Ie+et);R.position_ids=(0,b.stack)([Oe,Oe,Oe],0)}return R}}class ho extends se{}class $l extends ho{}class Nn extends ho{}class mo extends se{}class ui extends mo{}class Al extends mo{}class fo extends se{}class Il extends fo{}class Ol extends fo{}class _o extends se{}class Fl extends _o{}class Dl extends _o{}class go extends se{}class Ll extends go{}class zl extends go{}class wo extends se{}class Bl extends wo{}class Rl extends wo{async _call(T){return new Qt(await super._call(T))}}class yo extends se{}class Nl extends yo{}class jl extends yo{async _call(T){return new Qt(await super._call(T))}}class Mo extends se{}class Ul extends Mo{}class di extends se{}class bo extends di{}class Vl extends di{async _call(T){return new Qt(await super._call(T))}}class Wl extends se{}class Gl extends Wl{}class vo extends se{}class Kl extends vo{}class Hl extends vo{async _call(T){return new Qt(await super._call(T))}}class xo extends se{}class ql extends xo{}class To extends se{}class Ql extends To{}class Gc extends To{async _call(T){return new Qt(await super._call(T))}}class Xl extends se{}class Yl extends Xl{async _call(T){return new Kn(await super._call(T))}}class fr extends se{}class Jl extends fr{}class Zl extends fr{async _call(T){return new Qt(await super._call(T))}}class Po extends se{}class eu extends Po{}class tu extends Po{async _call(T){return new Qt(await super._call(T))}}class Eo extends se{}class su extends Eo{}class ru extends Eo{}class Co extends se{}class nu extends Co{}class Kc extends Co{}class ko extends se{}class iu extends ko{}class ou extends ko{async _call(T){return new Qt(await super._call(T))}}class ci extends se{}class au extends ci{}class lu extends ci{async _call(T){return new Hr(await super._call(T))}}class uu extends ci{async _call(T){return new nn(await super._call(T))}}class Hr extends Ke{constructor({logits:T,pred_boxes:R}){super(),this.logits=T,this.pred_boxes=R}}class nn extends Ke{constructor({logits:T,pred_boxes:R,pred_masks:_e}){super(),this.logits=T,this.pred_boxes=R,this.pred_masks=_e}}class qr extends se{}class So extends qr{}class on extends qr{async _call(T){return new Qs(await super._call(T))}}class Qs extends Ke{constructor({logits:T,pred_boxes:R}){super(),this.logits=T,this.pred_boxes=R}}class $o extends se{}class Ao extends $o{}class du extends $o{async _call(T){return new Hc(await super._call(T))}}class Hc extends Hr{}class xn extends se{}class Io extends xn{}class Oo extends xn{async _call(T){return new Qt(await super._call(T))}}class Fo extends se{}class cu extends Fo{}class Do extends Fo{async _call(T){return new Qt(await super._call(T))}}class pi extends se{}class pu extends pi{}class Lo extends pi{async _call(T){return new Qt(await super._call(T))}}class zo extends se{}class hi extends zo{}class Bo extends zo{async _call(T){return new Qt(await super._call(T))}}class Ro extends se{}class hu extends Ro{}class qc extends Ro{}class No extends se{}class jo extends No{}class jn extends No{}class mu extends se{}class Uo extends mu{}class mi extends se{}class fu extends mi{}class _u extends mi{}class Qc extends mi{}class gu extends se{}class wu extends gu{}class yu extends se{}class Mu extends yu{}class fi extends yu{}class Vo extends se{}class _i extends Vo{}class Wo extends Vo{}class Go extends se{}class bu extends Go{}class Ko extends se{}class Ho extends Ko{}class Xc extends Ko{async _call(T){return new Qt(await super._call(T))}}class qo extends se{}class Yc extends qo{}class vu extends qo{async _call(T){return new Qt(await super._call(T))}}class Qo extends se{}class xu extends Qo{}class Xo extends Qo{async _call(T){return new Qt(await super._call(T))}}class Yo extends se{}class Tu extends Yo{}class Jo extends Yo{async _call(T){return new Qt(await super._call(T))}}class Pu extends se{}class Eu extends Pu{}class Cu extends se{}class ku extends Cu{}class Su extends Cu{async _call(T){return new $u(await super._call(T))}}class $u extends Ke{constructor({logits:T,pred_boxes:R}){super(),this.logits=T,this.pred_boxes=R}}class Jc extends se{}class Au extends Jc{async get_image_embeddings({pixel_values:T}){return await Ae(this,{pixel_values:T})}async forward(T){if((!T.image_embeddings||!T.image_positional_embeddings)&&(T={...T,...await this.get_image_embeddings(T)}),!T.input_labels&&T.input_points){const _e=T.input_points.dims.slice(0,-1),Ie=_e.reduce((Oe,et)=>Oe*et,1);T.input_labels=new b.Tensor("int64",new BigInt64Array(Ie).fill(1n),_e)}const R={image_embeddings:T.image_embeddings,image_positional_embeddings:T.image_positional_embeddings};return T.input_points&&(R.input_points=T.input_points),T.input_labels&&(R.input_labels=T.input_labels),T.input_boxes&&(R.input_boxes=T.input_boxes),await we(this.sessions.prompt_encoder_mask_decoder,R)}async _call(T){return new Iu(await super._call(T))}}class Iu extends Ke{constructor({iou_scores:T,pred_masks:R}){super(),this.iou_scores=T,this.pred_masks=R}}class Zo extends se{}class Ou extends Zo{}class Fu extends Zo{}class Du extends se{}class gi extends Du{}class Un extends Du{}class Dr extends se{}class Lu extends Dr{}class zu extends Dr{async _call(T){return new Tn(await super._call(T))}}class Bu extends Dr{async _call(T){return new Qt(await super._call(T))}}class Ru extends Dr{async _call(T){return new Ks(await super._call(T))}}class wi extends se{}class Nu extends wi{}class ju extends wi{async _call(T){return new Ks(await super._call(T))}}class Uu extends se{}class Zc extends Uu{}class yi extends se{}class ea extends yi{}class Vu extends yi{async _call(T){return new Tn(await super._call(T))}}class Wu extends yi{async _call(T){return new Qt(await super._call(T))}}class Vn extends se{}class ep extends Vn{}class Gu extends Vn{async _call(T){return new Tn(await super._call(T))}}class Ku extends Vn{async _call(T){return new Qt(await super._call(T))}}class tp extends Vn{async _call(T){return new Ks(await super._call(T))}}class Mi extends se{}class Hu extends Mi{}class qu extends Mi{async _call(T){return new Tn(await super._call(T))}}class Qu extends Mi{async _call(T){return new Qt(await super._call(T))}}class Np extends se{}class Xu extends Dr{}class Yu extends Dr{async _call(T){return new Tn(await super._call(T))}}class Ju extends Dr{async _call(T){return new Qt(await super._call(T))}}class Wn extends se{}class Zu extends Wn{}class ed extends Wn{async _call(T){return new Tn(await super._call(T))}}class td extends Wn{async _call(T){return new Qt(await super._call(T))}}class sd extends Wn{async _call(T){return new vp(await super._call(T))}}class sp extends Wn{async _call(T){return new Ks(await super._call(T))}}class rd extends se{}class nd extends rd{}class bi extends se{}class rp extends bi{}class np extends bi{}class id extends bi{async generate_speech(T,R,{threshold:_e=.5,minlenratio:Ie=0,maxlenratio:Oe=20,vocoder:et=null}={}){const rt={input_ids:T},{encoder_outputs:_t,encoder_attention_mask:Mt}=await Ae(this,rt),jt=_t.dims[1]/this.config.reduction_factor,Vt=Math.floor(jt*Oe),Lt=Math.floor(jt*Ie),Gt=this.config.num_mel_bins;let es=[],ns=null,Jt=null,os=0;for(;;){++os;const fs=ce(!!Jt);let Es;Jt?Es=Jt.output_sequence_out:Es=new b.Tensor("float32",new Float32Array(Gt),[1,1,Gt]);let Os={use_cache_branch:fs,output_sequence:Es,encoder_attention_mask:Mt,speaker_embeddings:R,encoder_hidden_states:_t};this.addPastKeyValues(Os,ns),Jt=await we(this.sessions.decoder_model_merged,Os),ns=this.getPastKeyValues(Jt,ns);const{prob:Zs,spectrum:Ys}=Jt;if(es.push(Ys),os>=Lt&&(Array.from(Zs.data).filter(br=>br>=_e).length>0||os>=Vt))break}const Cs=(0,b.cat)(es),{waveform:xs}=await we(et.sessions.model,{spectrogram:Cs});return{spectrogram:Cs,waveform:xs}}}class od extends se{constructor(){super(...arguments);fe(this,"main_input_name","spectrogram")}}class ad extends se{}class ld extends ad{}class ud extends se{}class Er extends ud{}class Lr extends ud{}class Qr extends se{}class an extends Qr{}class dd extends Qr{}class ta extends se{}class cd extends ta{}class pd extends ta{}class vi extends se{}class hd extends vi{}class md extends vi{static async from_pretrained(T,R={}){return super.from_pretrained(T,{...R,model_file_name:R.model_file_name??"text_model"})}}class fd extends vi{static async from_pretrained(T,R={}){return super.from_pretrained(T,{...R,model_file_name:R.model_file_name??"audio_model"})}}class _d extends se{}class sa extends _d{async _call(T){return new Pc(await super._call(T))}}class ra extends se{}class ir extends ra{}class gd extends ra{}class wd extends ra{}class xi extends se{}class yd extends xi{}class Gn extends xi{}class na extends se{}class Md extends na{}class bd extends na{async _call(T){return new Qt(await super._call(T))}}class ia extends se{}class ip extends ia{}class op extends ia{}class Ti extends se{constructor(){super(...arguments);fe(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(R){const[_e,Ie]=R.dims,Oe=this.config.decoder.num_codebooks,et=Ie-Oe;let rt=0;for(let jt=0;jt0&&Gt<=et&&(R.data[rt++]=R.data[jt])}const _t=Math.floor(_e/Oe),Mt=rt/(_t*Oe);return new b.Tensor(R.type,R.data.slice(0,rt),[_t,Oe,Mt])}prepare_inputs_for_generation(R,_e,Ie){let Oe=structuredClone(R);for(let rt=0;rt=_t&&(Oe[rt][_t]=BigInt(this.config.decoder.pad_token_id));return Ie.guidance_scale!==null&&Ie.guidance_scale>1&&(Oe=Oe.concat(Oe)),super.prepare_inputs_for_generation(Oe,_e,Ie)}async generate(R){const _e=await super.generate(R),Ie=this._apply_and_filter_by_delay_pattern_mask(_e).unsqueeze_(0),{audio_values:Oe}=await we(this.sessions.encodec_decode,{audio_codes:Ie});return Oe}}class oa extends se{}class vd extends oa{}class xd extends oa{async _call(T){return new Qt(await super._call(T))}}class aa extends se{}class Td extends aa{}class la extends aa{async _call(T){return new Qt(await super._call(T))}}class ua extends se{}class ap extends ua{}class da extends ua{async _call(T){return new Qt(await super._call(T))}}class ca extends se{}class Pd extends ca{}class Ed extends ca{async _call(T){return new Qt(await super._call(T))}}class lp extends se{}class Cd extends lp{}class kd extends se{}class Sd extends kd{constructor(...R){super(...R);fe(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(R){const _e=this._generation_mode??"text";let Ie;if(_e==="text"||!R.past_key_values){const Mt=this.sessions.prepare_inputs_embeds,jt=(0,N.pick)(R,Mt.inputNames);Ie=await we(Mt,jt)}else{const Mt=this.sessions.gen_img_embeds,jt=(0,N.pick)({image_ids:R.input_ids},Mt.inputNames);Ie=await we(Mt,jt)}const Oe={...R,...Ie},et=await Ee(this,Oe),rt=this.sessions[_e==="text"?"lm_head":"gen_head"];if(!rt)throw new Error(`Unable to find "${rt}" generation head`);const _t=await we(rt,(0,N.pick)(et,rt.inputNames));return{...Ie,...et,..._t}}async generate(R){return this._generation_mode="text",super.generate(R)}async generate_images(R){this._generation_mode="image";const _e=(R.inputs??R[this.main_input_name]).dims[1],Oe=(await super.generate(R)).slice(null,[_e,null]),et=this.sessions.image_decode,{decoded_image:rt}=await we(et,{generated_tokens:Oe}),_t=rt.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Mt=[];for(const jt of _t){const Vt=I.RawImage.fromTensor(jt);Mt.push(Vt)}return Mt}}class up extends Ke{constructor({char_logits:T,bpe_logits:R,wp_logits:_e}){super(),this.char_logits=T,this.bpe_logits=R,this.wp_logits=_e}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class $d extends se{}class Ad extends $d{async _call(T){return new up(await super._call(T))}}class Id extends se{}class Od extends Id{}class Fd extends Id{}class pa extends se{}class Dd extends pa{}class Ld extends pa{}class ys{static async from_pretrained(T,{progress_callback:R=null,config:_e=null,cache_dir:Ie=null,local_files_only:Oe=!1,revision:et="main",model_file_name:rt=null,subfolder:_t="onnx",device:Mt=null,dtype:jt=null,use_external_data_format:Vt=null,session_options:Lt={}}={}){const Gt={progress_callback:R,config:_e,cache_dir:Ie,local_files_only:Oe,revision:et,model_file_name:rt,subfolder:_t,device:Mt,dtype:jt,use_external_data_format:Vt,session_options:Lt};if(Gt.config=await _.AutoConfig.from_pretrained(T,Gt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);for(const es of this.MODEL_CLASS_MAPPINGS){const ns=es.get(Gt.config.model_type);if(ns)return await ns[1].from_pretrained(T,Gt)}if(this.BASE_IF_FAIL)return console.warn(`Unknown model class "${Gt.config.model_type}", attempting to construct from base class.`),await se.from_pretrained(T,Gt);throw Error(`Unsupported model type: ${Gt.config.model_type}`)}}fe(ys,"MODEL_CLASS_MAPPINGS",null),fe(ys,"BASE_IF_FAIL",!1);const dp=new Map([["bert",["BertModel",Te]],["modernbert",["ModernBertModel",dt]],["nomic_bert",["NomicBertModel",oe]],["roformer",["RoFormerModel",me]],["electra",["ElectraModel",Ds]],["esm",["EsmModel",si]],["convbert",["ConvBertModel",vt]],["camembert",["CamembertModel",Nt]],["deberta",["DebertaModel",en]],["deberta-v2",["DebertaV2Model",Tt]],["mpnet",["MPNetModel",gn]],["albert",["AlbertModel",zn]],["distilbert",["DistilBertModel",ar]],["roberta",["RobertaModel",nr]],["xlm",["XLMModel",Ls]],["xlm-roberta",["XLMRobertaModel",It]],["clap",["ClapModel",hd]],["clip",["CLIPModel",qa]],["clipseg",["CLIPSegModel",el]],["chinese_clip",["ChineseCLIPModel",wr]],["siglip",["SiglipModel",Ya]],["jina_clip",["JinaCLIPModel",oi]],["mobilebert",["MobileBertModel",On]],["squeezebert",["SqueezeBertModel",bn]],["wav2vec2",["Wav2Vec2Model",Lu]],["wav2vec2-bert",["Wav2Vec2BertModel",Hu]],["unispeech",["UniSpeechModel",ea]],["unispeech-sat",["UniSpeechSatModel",ep]],["hubert",["HubertModel",Xu]],["wavlm",["WavLMModel",Zu]],["audio-spectrogram-transformer",["ASTModel",La]],["vits",["VitsModel",sa]],["pyannote",["PyAnnoteModel",Nu]],["wespeaker-resnet",["WeSpeakerResNetModel",Zc]],["detr",["DetrModel",au]],["rt_detr",["RTDetrModel",So]],["table-transformer",["TableTransformerModel",Ao]],["vit",["ViTModel",Bl]],["ijepa",["IJepaModel",Nl]],["pvt",["PvtModel",bo]],["vit_msn",["ViTMSNModel",Kl]],["vit_mae",["ViTMAEModel",Gl]],["groupvit",["GroupViTModel",ql]],["fastvit",["FastViTModel",Ql]],["mobilevit",["MobileViTModel",Jl]],["mobilevitv2",["MobileViTV2Model",eu]],["owlvit",["OwlViTModel",su]],["owlv2",["Owlv2Model",nu]],["beit",["BeitModel",iu]],["deit",["DeiTModel",Io]],["hiera",["HieraModel",cu]],["convnext",["ConvNextModel",Ho]],["convnextv2",["ConvNextV2Model",Yc]],["dinov2",["Dinov2Model",xu]],["dinov2_with_registers",["Dinov2WithRegistersModel",Tu]],["resnet",["ResNetModel",pu]],["swin",["SwinModel",hi]],["swin2sr",["Swin2SRModel",hu]],["donut-swin",["DonutSwinModel",bu]],["yolos",["YolosModel",ku]],["dpt",["DPTModel",jo]],["glpn",["GLPNModel",_i]],["hifigan",["SpeechT5HifiGan",od]],["efficientnet",["EfficientNetModel",Md]],["decision_transformer",["DecisionTransformerModel",Cd]],["patchtst",["PatchTSTForPrediction",Od]],["patchtsmixer",["PatchTSMixerForPrediction",Dd]],["mobilenet_v1",["MobileNetV1Model",vd]],["mobilenet_v2",["MobileNetV2Model",Td]],["mobilenet_v3",["MobileNetV3Model",ap]],["mobilenet_v4",["MobileNetV4Model",Pd]],["maskformer",["MaskFormerModel",Mu]],["mgp-str",["MgpstrForSceneTextRecognition",Ad]],["style_text_to_speech_2",["StyleTextToSpeech2Model",nd]]]),cp=new Map([["t5",["T5Model",C]],["longt5",["LongT5Model",be]],["mt5",["MT5Model",pt]],["bart",["BartModel",xt]],["mbart",["MBartModel",Fs]],["marian",["MarianModel",Ou]],["whisper",["WhisperModel",za]],["m2m_100",["M2M100Model",gi]],["blenderbot",["BlenderbotModel",Le]],["blenderbot-small",["BlenderbotSmallModel",Ss]]]),pp=new Map([["bloom",["BloomModel",Il]],["jais",["JAISModel",nl]],["gpt2",["GPT2Model",sl]],["gptj",["GPTJModel",ul]],["gpt_bigcode",["GPTBigCodeModel",cl]],["gpt_neo",["GPTNeoModel",Mr]],["gpt_neox",["GPTNeoXModel",al]],["codegen",["CodeGenModel",Ji]],["llama",["LlamaModel",eo]],["exaone",["ExaoneModel",li]],["olmo",["OlmoModel",_l]],["olmo2",["Olmo2Model",gl]],["mobilellm",["MobileLLMModel",fl]],["granite",["GraniteModel",Vc]],["cohere",["CohereModel",Ml]],["gemma",["GemmaModel",ds]],["gemma2",["Gemma2Model",vl]],["openelm",["OpenELMModel",Tl]],["qwen2",["Qwen2Model",El]],["phi",["PhiModel",$l]],["phi3",["Phi3Model",ui]],["mpt",["MptModel",Fl]],["opt",["OPTModel",Ll]],["mistral",["MistralModel",Er]],["starcoder2",["Starcoder2Model",an]],["falcon",["FalconModel",cd]],["stablelm",["StableLmModel",yd]]]),ha=new Map([["speecht5",["SpeechT5ForSpeechToText",np]],["whisper",["WhisperForConditionalGeneration",Ba]],["moonshine",["MoonshineForConditionalGeneration",Ra]]]),zd=new Map([["speecht5",["SpeechT5ForTextToSpeech",id]]]),Bd=new Map([["vits",["VitsModel",sa]],["musicgen",["MusicgenForConditionalGeneration",Ti]]]),Rd=new Map([["bert",["BertForSequenceClassification",Ve]],["modernbert",["ModernBertForSequenceClassification",lt]],["roformer",["RoFormerForSequenceClassification",We]],["electra",["ElectraForSequenceClassification",Sr]],["esm",["EsmForSequenceClassification",An]],["convbert",["ConvBertForSequenceClassification",At]],["camembert",["CamembertForSequenceClassification",$r]],["deberta",["DebertaForSequenceClassification",Rr]],["deberta-v2",["DebertaV2ForSequenceClassification",Vs]],["mpnet",["MPNetForSequenceClassification",wn]],["albert",["AlbertForSequenceClassification",vn]],["distilbert",["DistilBertForSequenceClassification",Is]],["roberta",["RobertaForSequenceClassification",ms]],["xlm",["XLMForSequenceClassification",Gs]],["xlm-roberta",["XLMRobertaForSequenceClassification",zi]],["bart",["BartForSequenceClassification",hs]],["mbart",["MBartForSequenceClassification",rs]],["mobilebert",["MobileBertForSequenceClassification",Wr]],["squeezebert",["SqueezeBertForSequenceClassification",Dn]]]),Nd=new Map([["bert",["BertForTokenClassification",Ne]],["modernbert",["ModernBertForTokenClassification",ht]],["roformer",["RoFormerForTokenClassification",Je]],["electra",["ElectraForTokenClassification",Yr]],["esm",["EsmForTokenClassification",In]],["convbert",["ConvBertForTokenClassification",is]],["camembert",["CamembertForTokenClassification",Ar]],["deberta",["DebertaForTokenClassification",Nr]],["deberta-v2",["DebertaV2ForTokenClassification",jr]],["mpnet",["MPNetForTokenClassification",yn]],["distilbert",["DistilBertForTokenClassification",Pr]],["roberta",["RobertaForTokenClassification",$s]],["xlm",["XLMForTokenClassification",$t]],["xlm-roberta",["XLMRobertaForTokenClassification",Fa]]]),ma=new Map([["t5",["T5ForConditionalGeneration",q]],["longt5",["LongT5ForConditionalGeneration",Se]],["mt5",["MT5ForConditionalGeneration",gt]],["bart",["BartForConditionalGeneration",Kt]],["mbart",["MBartForConditionalGeneration",Bt]],["marian",["MarianMTModel",Fu]],["m2m_100",["M2M100ForConditionalGeneration",Un]],["blenderbot",["BlenderbotForConditionalGeneration",Js]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",qs]]]),jd=new Map([["bloom",["BloomForCausalLM",Ol]],["gpt2",["GPT2LMHeadModel",rl]],["jais",["JAISLMHeadModel",il]],["gptj",["GPTJForCausalLM",dl]],["gpt_bigcode",["GPTBigCodeForCausalLM",pl]],["gpt_neo",["GPTNeoForCausalLM",ol]],["gpt_neox",["GPTNeoXForCausalLM",ll]],["codegen",["CodeGenForCausalLM",hl]],["llama",["LlamaForCausalLM",Uc]],["exaone",["ExaoneForCausalLM",ml]],["olmo",["OlmoForCausalLM",no]],["olmo2",["Olmo2ForCausalLM",wl]],["mobilellm",["MobileLLMForCausalLM",Rn]],["granite",["GraniteForCausalLM",yl]],["cohere",["CohereForCausalLM",Wc]],["gemma",["GemmaForCausalLM",bl]],["gemma2",["Gemma2ForCausalLM",xl]],["openelm",["OpenELMForCausalLM",Pl]],["qwen2",["Qwen2ForCausalLM",Cl]],["phi",["PhiForCausalLM",Nn]],["phi3",["Phi3ForCausalLM",Al]],["mpt",["MptForCausalLM",Dl]],["opt",["OPTForCausalLM",zl]],["mbart",["MBartForCausalLM",rr]],["mistral",["MistralForCausalLM",Lr]],["starcoder2",["Starcoder2ForCausalLM",dd]],["falcon",["FalconForCausalLM",pd]],["trocr",["TrOCRForCausalLM",ld]],["stablelm",["StableLmForCausalLM",Gn]],["phi3_v",["Phi3VForCausalLM",mr]]]),Pi=new Map([["multi_modality",["MultiModalityCausalLM",Sd]]]),fa=new Map([["bert",["BertForMaskedLM",Ue]],["modernbert",["ModernBertForMaskedLM",ct]],["roformer",["RoFormerForMaskedLM",$e]],["electra",["ElectraForMaskedLM",sr]],["esm",["EsmForMaskedLM",$n]],["convbert",["ConvBertForMaskedLM",kt]],["camembert",["CamembertForMaskedLM",Jr]],["deberta",["DebertaForMaskedLM",Ir]],["deberta-v2",["DebertaV2ForMaskedLM",Dt]],["mpnet",["MPNetForMaskedLM",tn]],["albert",["AlbertForMaskedLM",as]],["distilbert",["DistilBertForMaskedLM",_n]],["roberta",["RobertaForMaskedLM",gr]],["xlm",["XLMWithLMHeadModel",As]],["xlm-roberta",["XLMRobertaForMaskedLM",Oa]],["mobilebert",["MobileBertForMaskedLM",ri]],["squeezebert",["SqueezeBertForMaskedLM",Fn]]]),_a=new Map([["bert",["BertForQuestionAnswering",Re]],["roformer",["RoFormerForQuestionAnswering",ut]],["electra",["ElectraForQuestionAnswering",Us]],["convbert",["ConvBertForQuestionAnswering",ws]],["camembert",["CamembertForQuestionAnswering",Zr]],["deberta",["DebertaForQuestionAnswering",or]],["deberta-v2",["DebertaV2ForQuestionAnswering",Or]],["mpnet",["MPNetForQuestionAnswering",Mn]],["albert",["AlbertForQuestionAnswering",Bn]],["distilbert",["DistilBertForQuestionAnswering",ts]],["roberta",["RobertaForQuestionAnswering",yt]],["xlm",["XLMForQuestionAnswering",sn]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Da]],["mobilebert",["MobileBertForQuestionAnswering",_r]],["squeezebert",["SqueezeBertForQuestionAnswering",Ln]]]),Ei=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",ji]],["idefics3",["Idefics3ForConditionalGeneration",Ui]]]),Ud=new Map([["llava",["LlavaForConditionalGeneration",ni]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",Na]],["moondream1",["Moondream1ForConditionalGeneration",ja]],["florence2",["Florence2ForConditionalGeneration",Va]],["qwen2-vl",["Qwen2VLForConditionalGeneration",Sl]],["idefics3",["Idefics3ForConditionalGeneration",Ui]],["paligemma",["PaliGemmaForConditionalGeneration",Ga]]]),hp=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",ji]]]),Vd=new Map([["vit",["ViTForImageClassification",Rl]],["ijepa",["IJepaForImageClassification",jl]],["pvt",["PvtForImageClassification",Vl]],["vit_msn",["ViTMSNForImageClassification",Hl]],["fastvit",["FastViTForImageClassification",Gc]],["mobilevit",["MobileViTForImageClassification",Zl]],["mobilevitv2",["MobileViTV2ForImageClassification",tu]],["beit",["BeitForImageClassification",ou]],["deit",["DeiTForImageClassification",Oo]],["hiera",["HieraForImageClassification",Do]],["convnext",["ConvNextForImageClassification",Xc]],["convnextv2",["ConvNextV2ForImageClassification",vu]],["dinov2",["Dinov2ForImageClassification",Xo]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",Jo]],["resnet",["ResNetForImageClassification",Lo]],["swin",["SwinForImageClassification",Bo]],["segformer",["SegformerForImageClassification",gd]],["efficientnet",["EfficientNetForImageClassification",bd]],["mobilenet_v1",["MobileNetV1ForImageClassification",xd]],["mobilenet_v2",["MobileNetV2ForImageClassification",la]],["mobilenet_v3",["MobileNetV3ForImageClassification",da]],["mobilenet_v4",["MobileNetV4ForImageClassification",Ed]]]),ga=new Map([["detr",["DetrForObjectDetection",lu]],["rt_detr",["RTDetrForObjectDetection",on]],["table-transformer",["TableTransformerForObjectDetection",du]],["yolos",["YolosForObjectDetection",Su]]]),wa=new Map([["owlvit",["OwlViTForObjectDetection",ru]],["owlv2",["Owlv2ForObjectDetection",Kc]],["grounding-dino",["GroundingDinoForObjectDetection",Eu]]]),Wd=new Map([["detr",["DetrForSegmentation",uu]],["clipseg",["CLIPSegForImageSegmentation",tl]]]),Gd=new Map([["segformer",["SegformerForSemanticSegmentation",wd]],["sapiens",["SapiensForSemanticSegmentation",fu]]]),ya=new Map([["detr",["DetrForSegmentation",uu]],["maskformer",["MaskFormerForInstanceSegmentation",fi]]]),Kd=new Map([["sam",["SamModel",Au]]]),Hd=new Map([["wav2vec2",["Wav2Vec2ForCTC",zu]],["wav2vec2-bert",["Wav2Vec2BertForCTC",qu]],["unispeech",["UniSpeechForCTC",Vu]],["unispeech-sat",["UniSpeechSatForCTC",Gu]],["wavlm",["WavLMForCTC",ed]],["hubert",["HubertForCTC",Yu]]]),Ma=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Bu]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Qu]],["unispeech",["UniSpeechForSequenceClassification",Wu]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Ku]],["wavlm",["WavLMForSequenceClassification",td]],["hubert",["HubertForSequenceClassification",Ju]],["audio-spectrogram-transformer",["ASTForAudioClassification",Bi]]]),qd=new Map([["wavlm",["WavLMForXVector",sd]]]),Qd=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",tp]],["wavlm",["WavLMForAudioFrameClassification",sp]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Ru]],["pyannote",["PyAnnoteForAudioFrameClassification",ju]]]),Xd=new Map([["vitmatte",["VitMatteForImageMatting",Yl]]]),mp=new Map([["patchtst",["PatchTSTForPrediction",Fd]],["patchtsmixer",["PatchTSMixerForPrediction",Ld]]]),fp=new Map([["swin2sr",["Swin2SRForImageSuperResolution",qc]]]),Yd=new Map([["dpt",["DPTForDepthEstimation",jn]],["depth_anything",["DepthAnythingForDepthEstimation",Uo]],["glpn",["GLPNForDepthEstimation",Wo]],["sapiens",["SapiensForDepthEstimation",_u]],["depth_pro",["DepthProForDepthEstimation",wu]]]),Jd=new Map([["sapiens",["SapiensForNormalEstimation",Qc]]]),Zd=new Map([["vitpose",["VitPoseForPoseEstimation",Ul]]]),ec=new Map([["clip",["CLIPVisionModelWithProjection",Xa]],["siglip",["SiglipVisionModel",Za]],["jina_clip",["JinaCLIPVisionModel",yr]]]),_p=[[dp,$.EncoderOnly],[cp,$.EncoderDecoder],[pp,$.DecoderOnly],[Rd,$.EncoderOnly],[Nd,$.EncoderOnly],[ma,$.Seq2Seq],[ha,$.Seq2Seq],[jd,$.DecoderOnly],[Pi,$.MultiModality],[fa,$.EncoderOnly],[_a,$.EncoderOnly],[Ei,$.Vision2Seq],[Ud,$.ImageTextToText],[Vd,$.EncoderOnly],[Wd,$.EncoderOnly],[ya,$.EncoderOnly],[Gd,$.EncoderOnly],[Xd,$.EncoderOnly],[mp,$.EncoderOnly],[fp,$.EncoderOnly],[Yd,$.EncoderOnly],[Jd,$.EncoderOnly],[Zd,$.EncoderOnly],[ga,$.EncoderOnly],[wa,$.EncoderOnly],[Kd,$.MaskGeneration],[Hd,$.EncoderOnly],[Ma,$.EncoderOnly],[zd,$.Seq2Seq],[Bd,$.EncoderOnly],[qd,$.EncoderOnly],[Qd,$.EncoderOnly],[ec,$.EncoderOnly]];for(const[f,T]of _p)for(const[R,_e]of f.values())S.set(R,T),x.set(_e,R),w.set(R,_e);const gp=[["MusicgenForConditionalGeneration",Ti,$.Musicgen],["Phi3VForCausalLM",mr,$.Phi3V],["CLIPTextModelWithProjection",Qa,$.EncoderOnly],["SiglipTextModel",Ja,$.EncoderOnly],["JinaCLIPTextModel",Wi,$.EncoderOnly],["ClapTextModelWithProjection",md,$.EncoderOnly],["ClapAudioModelWithProjection",fd,$.EncoderOnly]];for(const[f,T,R]of gp)S.set(f,R),x.set(T,f),w.set(f,T);class ba extends ys{}fe(ba,"MODEL_CLASS_MAPPINGS",_p.map(T=>T[0])),fe(ba,"BASE_IF_FAIL",!0);class tc extends ys{}fe(tc,"MODEL_CLASS_MAPPINGS",[Rd]);class wp extends ys{}fe(wp,"MODEL_CLASS_MAPPINGS",[Nd]);class sc extends ys{}fe(sc,"MODEL_CLASS_MAPPINGS",[ma]);class rc extends ys{}fe(rc,"MODEL_CLASS_MAPPINGS",[ha]);class nc extends ys{}fe(nc,"MODEL_CLASS_MAPPINGS",[zd]);class ic extends ys{}fe(ic,"MODEL_CLASS_MAPPINGS",[Bd]);class yp extends ys{}fe(yp,"MODEL_CLASS_MAPPINGS",[jd]);class oc extends ys{}fe(oc,"MODEL_CLASS_MAPPINGS",[fa]);class ac extends ys{}fe(ac,"MODEL_CLASS_MAPPINGS",[_a]);class lc extends ys{}fe(lc,"MODEL_CLASS_MAPPINGS",[Ei]);class uc extends ys{}fe(uc,"MODEL_CLASS_MAPPINGS",[Vd]);class dc extends ys{}fe(dc,"MODEL_CLASS_MAPPINGS",[Wd]);class cc extends ys{}fe(cc,"MODEL_CLASS_MAPPINGS",[Gd]);class pc extends ys{}fe(pc,"MODEL_CLASS_MAPPINGS",[ya]);class hc extends ys{}fe(hc,"MODEL_CLASS_MAPPINGS",[ga]);class mc extends ys{}fe(mc,"MODEL_CLASS_MAPPINGS",[wa]);class fc extends ys{}fe(fc,"MODEL_CLASS_MAPPINGS",[Kd]);class _c extends ys{}fe(_c,"MODEL_CLASS_MAPPINGS",[Hd]);class va extends ys{}fe(va,"MODEL_CLASS_MAPPINGS",[Ma]);class gc extends ys{}fe(gc,"MODEL_CLASS_MAPPINGS",[qd]);class wc extends ys{}fe(wc,"MODEL_CLASS_MAPPINGS",[Qd]);class yc extends ys{}fe(yc,"MODEL_CLASS_MAPPINGS",[hp]);class Mc extends ys{}fe(Mc,"MODEL_CLASS_MAPPINGS",[Xd]);class bc extends ys{}fe(bc,"MODEL_CLASS_MAPPINGS",[fp]);class vc extends ys{}fe(vc,"MODEL_CLASS_MAPPINGS",[Yd]);class xc extends ys{}fe(xc,"MODEL_CLASS_MAPPINGS",[Jd]);class Mp extends ys{}fe(Mp,"MODEL_CLASS_MAPPINGS",[Zd]);class Tc extends ys{}fe(Tc,"MODEL_CLASS_MAPPINGS",[ec]);class bp extends Ke{constructor({logits:T,past_key_values:R,encoder_outputs:_e,decoder_attentions:Ie=null,cross_attentions:Oe=null}){super(),this.logits=T,this.past_key_values=R,this.encoder_outputs=_e,this.decoder_attentions=Ie,this.cross_attentions=Oe}}class Qt extends Ke{constructor({logits:T,...R}){super(),this.logits=T;const _e=Object.values(R);_e.length>0&&(this.attentions=_e)}}class vp extends Ke{constructor({logits:T,embeddings:R}){super(),this.logits=T,this.embeddings=R}}class Ks extends Ke{constructor({logits:T}){super(),this.logits=T}}class Xs extends Ke{constructor({logits:T}){super(),this.logits=T}}class tr extends Ke{constructor({start_logits:T,end_logits:R}){super(),this.start_logits=T,this.end_logits=R}}class Tn extends Ke{constructor({logits:T}){super(),this.logits=T}}class xp extends Ke{constructor({logits:T,past_key_values:R}){super(),this.logits=T,this.past_key_values=R}}class Kn extends Ke{constructor({alphas:T}){super(),this.alphas=T}}class Pc extends Ke{constructor({waveform:T,spectrogram:R}){super(),this.waveform=T,this.spectrogram=R}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(ze,A,r)=>{r.r(A),r.d(A,{ASTFeatureExtractor:()=>j});var _=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var D=r("./src/utils/audio.js");class j extends _.FeatureExtractor{constructor(N){super(N);const g=this.config.sampling_rate,v=(0,D.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(g/2),g,null,"kaldi",!0);for(let y=0;y{r.r(A),r.d(A,{AutoFeatureExtractor:()=>Y});var _=r("./src/utils/constants.js"),D=r("./src/utils/hub.js");r("./src/base/feature_extraction_utils.js");var j=r("./src/models/feature_extractors.js");class Y{static async from_pretrained(g,v={}){const y=await(0,D.getModelJSON)(g,_.FEATURE_EXTRACTOR_NAME,!0,v),M=y.feature_extractor_type,b=j[M];if(!b)throw new Error(`Unknown feature_extractor_type: '${M}'. Please report this at ${_.GITHUB_ISSUE_URL}.`);return new b(y)}}},"./src/models/auto/image_processing_auto.js":(ze,A,r)=>{r.r(A),r.d(A,{AutoImageProcessor:()=>N});var _=r("./src/utils/constants.js"),D=r("./src/utils/hub.js"),j=r("./src/base/image_processors_utils.js"),Y=r("./src/models/image_processors.js");class N{static async from_pretrained(v,y={}){const M=await(0,D.getModelJSON)(v,_.IMAGE_PROCESSOR_NAME,!0,y),b=M.image_processor_type??M.feature_extractor_type;let I=Y[b];return I||(b!==void 0&&console.warn(`Image processor type '${b}' not found, assuming base ImageProcessor. Please report this at ${_.GITHUB_ISSUE_URL}.`),I=j.ImageProcessor),new I(M)}}},"./src/models/auto/processing_auto.js":(ze,A,r)=>{r.r(A),r.d(A,{AutoProcessor:()=>v});var _=r("./src/utils/constants.js"),D=r("./src/utils/hub.js"),j=r("./src/base/processing_utils.js"),Y=r("./src/models/processors.js"),N=r("./src/models/image_processors.js"),g=r("./src/models/feature_extractors.js");class v{static async from_pretrained(M,b={}){const I=await(0,D.getModelJSON)(M,_.IMAGE_PROCESSOR_NAME,!0,b),{image_processor_type:K,feature_extractor_type:te,processor_class:ne}=I;if(ne&&Y[ne])return Y[ne].from_pretrained(M,b);if(!K&&!te)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const W={};if(K){const X=N[K];if(!X)throw new Error(`Unknown image_processor_type: '${K}'.`);W.image_processor=new X(I)}if(te){const X=N[te];if(X)W.image_processor=new X(I);else{const $=g[te];if(!$)throw new Error(`Unknown feature_extractor_type: '${te}'.`);W.feature_extractor=new $(I)}}const U={};return new j.Processor(U,W)}}},"./src/models/beit/image_processing_beit.js":(ze,A,r)=>{r.r(A),r.d(A,{BeitFeatureExtractor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(ze,A,r)=>{r.r(A),r.d(A,{BitImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(ze,A,r)=>{r.r(A),r.d(A,{ChineseCLIPFeatureExtractor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(ze,A,r)=>{r.r(A),r.d(A,{ClapFeatureExtractor:()=>j});var _=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var D=r("./src/utils/audio.js");class j extends _.FeatureExtractor{constructor(N){super(N),this.mel_filters=(0,D.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,D.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,D.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(N,g,v,y){let M;const b=N.length-g;if(b>0)if(v==="rand_trunc"){const I=Math.floor(Math.random()*(b+1));N=N.subarray(I,I+g),M=await this._extract_fbank_features(N,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${v}" not implemented`);else{if(b<0){let I=new Float64Array(g);if(I.set(N),y==="repeat")for(let K=N.length;K{r.r(A),r.d(A,{CLIPFeatureExtractor:()=>j,CLIPImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{}class j extends D{}},"./src/models/convnext/image_processing_convnext.js":(ze,A,r)=>{r.r(A),r.d(A,{ConvNextFeatureExtractor:()=>j,ConvNextImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{constructor(N){super(N),this.crop_pct=this.config.crop_pct??.875}async resize(N){var v;const g=(v=this.size)==null?void 0:v.shortest_edge;if(g===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(g<384){const y=Math.floor(g/this.crop_pct),[M,b]=this.get_resize_output_image_size(N,{shortest_edge:y});N=await N.resize(M,b,{resample:this.resample}),N=await N.center_crop(g,g)}else N=await N.resize(g,g,{resample:this.resample});return N}}class j extends D{}},"./src/models/deit/image_processing_deit.js":(ze,A,r)=>{r.r(A),r.d(A,{DeiTFeatureExtractor:()=>j,DeiTImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{}class j extends D{}},"./src/models/detr/image_processing_detr.js":(ze,A,r)=>{r.r(A),r.d(A,{DetrFeatureExtractor:()=>Y,DetrImageProcessor:()=>j});var _=r("./src/base/image_processors_utils.js"),D=r("./src/utils/tensor.js");class j extends _.ImageProcessor{async _call(g){const v=await super._call(g),y=[v.pixel_values.dims[0],64,64],M=(0,D.full)(y,1n);return{...v,pixel_mask:M}}post_process_object_detection(...g){return(0,_.post_process_object_detection)(...g)}post_process_panoptic_segmentation(...g){return(0,_.post_process_panoptic_segmentation)(...g)}post_process_instance_segmentation(...g){return(0,_.post_process_instance_segmentation)(...g)}}class Y extends j{}},"./src/models/donut/image_processing_donut.js":(ze,A,r)=>{r.r(A),r.d(A,{DonutFeatureExtractor:()=>j,DonutImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{pad_image(N,g,v,y={}){const[M,b,I]=g;let K=this.image_mean;Array.isArray(this.image_mean)||(K=new Array(I).fill(K));let te=this.image_std;Array.isArray(te)||(te=new Array(I).fill(K));const ne=K.map((W,U)=>-W/te[U]);return super.pad_image(N,g,v,{center:!0,constant_values:ne,...y})}}class j extends D{}},"./src/models/dpt/image_processing_dpt.js":(ze,A,r)=>{r.r(A),r.d(A,{DPTFeatureExtractor:()=>j,DPTImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{}class j extends D{}},"./src/models/efficientnet/image_processing_efficientnet.js":(ze,A,r)=>{r.r(A),r.d(A,{EfficientNetImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{constructor(Y){super(Y),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(N=>N*N))}}},"./src/models/feature_extractors.js":(ze,A,r)=>{r.r(A),r.d(A,{ASTFeatureExtractor:()=>_.ASTFeatureExtractor,ClapFeatureExtractor:()=>D.ClapFeatureExtractor,ImageFeatureExtractor:()=>b.ImageProcessor,MoonshineFeatureExtractor:()=>j.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>Y.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>N.SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor:()=>g.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>v.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>y.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>M.WhisperFeatureExtractor});var _=r("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),D=r("./src/models/clap/feature_extraction_clap.js"),j=r("./src/models/moonshine/feature_extraction_moonshine.js"),Y=r("./src/models/pyannote/feature_extraction_pyannote.js"),N=r("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),g=r("./src/models/speecht5/feature_extraction_speecht5.js"),v=r("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),y=r("./src/models/wespeaker/feature_extraction_wespeaker.js"),M=r("./src/models/whisper/feature_extraction_whisper.js"),b=r("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(ze,A,r)=>{r.r(A),r.d(A,{Florence2Processor:()=>Y});var _=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");class Y extends _.Processor{constructor(g,v){super(g,v);const{tasks_answer_post_processing_type:y,task_prompts_without_inputs:M,task_prompts_with_input:b}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(y??{})),this.task_prompts_without_inputs=new Map(Object.entries(M??{})),this.task_prompts_with_input=new Map(Object.entries(b??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(g){typeof g=="string"&&(g=[g]);const v=[];for(const y of g)if(this.task_prompts_without_inputs.has(y))v.push(this.task_prompts_without_inputs.get(y));else{for(const[M,b]of this.task_prompts_with_input)if(y.includes(M)){v.push(b.replaceAll("{input}",y).replaceAll(M,""));break}v.length!==g.length&&v.push(y)}return v}post_process_generation(g,v,y){const M=this.tasks_answer_post_processing_type.get(v)??"pure_text";g=g.replaceAll("","").replaceAll("","");let b;switch(M){case"pure_text":b=g;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const I=M==="ocr"?"quad_boxes":"bboxes",K=g.matchAll(this.regexes[I]),te=[],ne=[];for(const[W,U,...X]of K)te.push(U?U.trim():te.at(-1)??""),ne.push(X.map(($,S)=>(Number($)+.5)/this.size_per_bin*y[S%2]));b={labels:te,[I]:ne};break;default:throw new Error(`Task "${v}" (of type "${M}") not yet implemented.`)}return{[v]:b}}async _call(g,v=null,y={}){if(!g&&!v)throw new Error("Either text or images must be provided");const M=await this.image_processor(g,y),b=v?this.tokenizer(v,y):{};return{...M,...b}}}fe(Y,"tokenizer_class",j.AutoTokenizer),fe(Y,"image_processor_class",D.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(ze,A,r)=>{r.r(A),r.d(A,{GLPNFeatureExtractor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{}},"./src/models/grounding_dino/image_processing_grounding_dino.js":(ze,A,r)=>{r.r(A),r.d(A,{GroundingDinoImageProcessor:()=>j});var _=r("./src/base/image_processors_utils.js"),D=r("./src/utils/tensor.js");class j extends _.ImageProcessor{async _call(N){const g=await super._call(N),v=g.pixel_values.dims,y=(0,D.ones)([v[0],v[2],v[3]]);return{...g,pixel_mask:y}}}},"./src/models/grounding_dino/processing_grounding_dino.js":(ze,A,r)=>{r.r(A),r.d(A,{GroundingDinoProcessor:()=>g});var _=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js"),Y=r("./src/base/image_processors_utils.js");function N(v,y){const b=v.dims.at(-1)-1,I=v.tolist();I.fill(!1,0,1),I.fill(!1,b);const K=y.tolist();return I.map((te,ne)=>te?ne:null).filter(te=>te!==null).map(te=>K[te])}class g extends _.Processor{async _call(y,M,b={}){const I=y?await this.image_processor(y,b):{};return{...M?this.tokenizer(M,b):{},...I}}post_process_grounded_object_detection(y,M,{box_threshold:b=.25,text_threshold:I=.25,target_sizes:K=null}={}){const{logits:te,pred_boxes:ne}=y,W=te.dims[0];if(K!==null&&K.length!==W)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const U=te.dims.at(1),X=te.sigmoid(),$=X.max(-1).tolist(),S=ne.tolist().map(x=>x.map(O=>(0,Y.center_to_corners_format)(O))),w=[];for(let x=0;xre.map((xe,ce)=>xe*O[(ce+1)%2])));const ae=$[x],ie=[],ve=[],we=[];for(let re=0;re{r.r(A),r.d(A,{Idefics3ImageProcessor:()=>j});var _=r("./src/base/image_processors_utils.js"),D=r("./src/utils/tensor.js");class j extends _.ImageProcessor{constructor(N){super(N),this.do_image_splitting=N.do_image_splitting??!0,this.max_image_size=N.max_image_size}get_resize_for_vision_encoder(N,g){let[v,y]=N.dims.slice(-2);const M=y/v;return y>=v?(y=Math.ceil(y/g)*g,v=Math.floor(y/M),v=Math.ceil(v/g)*g):(v=Math.ceil(v/g)*g,y=Math.floor(v*M),y=Math.ceil(y/g)*g),{height:v,width:y}}async _call(N,{do_image_splitting:g=null,return_row_col_info:v=!1}={}){let y;if(!Array.isArray(N))y=[[N]];else{if(N.length===0||!N[0])throw new Error("No images provided.");Array.isArray(N[0])?y=N:y=[N]}let M=[],b=[],I=[];const K=[],te=[];for(const x of y){let O=await Promise.all(x.map(ve=>this.preprocess(ve)));K.push(...O.map(ve=>ve.original_size)),te.push(...O.map(ve=>ve.reshaped_input_size)),O.forEach(ve=>ve.pixel_values.unsqueeze_(0));const{longest_edge:ae}=this.max_image_size;let ie;if(g??this.do_image_splitting){let ve=new Array(O.length),we=new Array(O.length);ie=await Promise.all(O.map(async(re,xe)=>{const ce=this.get_resize_for_vision_encoder(re.pixel_values,ae),ke=await(0,D.interpolate_4d)(re.pixel_values,{size:[ce.height,ce.width]}),{frames:Ae,num_splits_h:Ee,num_splits_w:tt}=await this.split_image(ke,this.max_image_size);return ve[xe]=Ee,we[xe]=tt,(0,D.cat)(Ae,0)})),b.push(ve),I.push(we)}else{const ve=[ae,ae];ie=await Promise.all(O.map(we=>(0,D.interpolate_4d)(we.pixel_values,{size:ve}))),b.push(new Array(O.length).fill(0)),I.push(new Array(O.length).fill(0))}M.push((0,D.cat)(ie,0))}const ne=M.length,[W,U,X,$]=M[0].dims;let S,w;if(ne===1)S=M[0].unsqueeze_(0),w=(0,D.full)([ne,W,X,$],!0);else{const x=Math.max(...M.map(ie=>ie.dims.at(0)));w=(0,D.full)([ne,x,X,$],!0);const O=w.data,ae=x*X*$;for(let ie=0;iev||I>y){K=Math.ceil(b/v),te=Math.ceil(I/y);const ne=Math.ceil(b/K),W=Math.ceil(I/te);for(let $=0;${r.r(A),r.d(A,{Idefics3Processor:()=>y});var _=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");r("./src/utils/image.js");var Y=r("./src/utils/core.js");function N(M,b,I,K,te,ne){let W="";for(let U=0;U`+te.repeat(M);W+=` +`}return W+=` +${K}${ne}`+te.repeat(M)+`${K}`,W}function g(M,b,I,K){return`${b}${K}`+I.repeat(M)+`${b}`}function v(M,b,I,K,te,ne){return M===0&&b===0?g(I,K,te,ne):N(I,M,b,K,te,ne)}class y extends _.Processor{constructor(){super(...arguments);fe(this,"fake_image_token","");fe(this,"image_token","");fe(this,"global_img_token","")}async _call(I,K=null,te={}){te.return_row_col_info??(te.return_row_col_info=!0);let ne;K&&(ne=await this.image_processor(K,te)),Array.isArray(I)||(I=[I]);const W=ne.rows??[new Array(I.length).fill(0)],U=ne.cols??[new Array(I.length).fill(0)],X=this.config.image_seq_len,$=[],S=[];for(let x=0;xv(xe,ie[ce],X,this.fake_image_token,this.image_token,this.global_img_token)),we=O.split(this.image_token);if(we.length===0)throw new Error("The image token should be present in the text.");let re=we[0];for(let xe=0;xe{r.r(A),r.d(A,{BeitFeatureExtractor:()=>_.BeitFeatureExtractor,BitImageProcessor:()=>D.BitImageProcessor,CLIPFeatureExtractor:()=>Y.CLIPFeatureExtractor,CLIPImageProcessor:()=>Y.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>j.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>N.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>N.ConvNextImageProcessor,DPTFeatureExtractor:()=>M.DPTFeatureExtractor,DPTImageProcessor:()=>M.DPTImageProcessor,DeiTFeatureExtractor:()=>g.DeiTFeatureExtractor,DeiTImageProcessor:()=>g.DeiTImageProcessor,DetrFeatureExtractor:()=>v.DetrFeatureExtractor,DetrImageProcessor:()=>v.DetrImageProcessor,DonutFeatureExtractor:()=>y.DonutFeatureExtractor,DonutImageProcessor:()=>y.DonutImageProcessor,EfficientNetImageProcessor:()=>b.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>I.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>K.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>te.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>W.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>U.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>X.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>$.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>$.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>S.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>S.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>w.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>w.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>x.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>x.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>O.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>O.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>ae.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>ae.MobileViTImageProcessor,NougatImageProcessor:()=>ie.NougatImageProcessor,OwlViTFeatureExtractor:()=>we.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>we.OwlViTImageProcessor,Owlv2ImageProcessor:()=>ve.Owlv2ImageProcessor,Phi3VImageProcessor:()=>re.Phi3VImageProcessor,PvtImageProcessor:()=>xe.PvtImageProcessor,Qwen2VLImageProcessor:()=>ce.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>ke.RTDetrImageProcessor,SamImageProcessor:()=>Ae.SamImageProcessor,SegformerFeatureExtractor:()=>Ee.SegformerFeatureExtractor,SegformerImageProcessor:()=>Ee.SegformerImageProcessor,SiglipImageProcessor:()=>tt.SiglipImageProcessor,Swin2SRImageProcessor:()=>Ge.Swin2SRImageProcessor,VLMImageProcessor:()=>ne.VLMImageProcessor,ViTFeatureExtractor:()=>ye.ViTFeatureExtractor,ViTImageProcessor:()=>ye.ViTImageProcessor,VitMatteImageProcessor:()=>J.VitMatteImageProcessor,VitPoseImageProcessor:()=>de.VitPoseImageProcessor,YolosFeatureExtractor:()=>Ce.YolosFeatureExtractor,YolosImageProcessor:()=>Ce.YolosImageProcessor});var _=r("./src/models/beit/image_processing_beit.js"),D=r("./src/models/bit/image_processing_bit.js"),j=r("./src/models/chinese_clip/image_processing_chinese_clip.js"),Y=r("./src/models/clip/image_processing_clip.js"),N=r("./src/models/convnext/image_processing_convnext.js"),g=r("./src/models/deit/image_processing_deit.js"),v=r("./src/models/detr/image_processing_detr.js"),y=r("./src/models/donut/image_processing_donut.js"),M=r("./src/models/dpt/image_processing_dpt.js"),b=r("./src/models/efficientnet/image_processing_efficientnet.js"),I=r("./src/models/glpn/image_processing_glpn.js"),K=r("./src/models/grounding_dino/image_processing_grounding_dino.js"),te=r("./src/models/idefics3/image_processing_idefics3.js"),ne=r("./src/models/janus/image_processing_janus.js"),W=r("./src/models/jina_clip/image_processing_jina_clip.js"),U=r("./src/models/llava_onevision/image_processing_llava_onevision.js"),X=r("./src/models/mask2former/image_processing_mask2former.js"),$=r("./src/models/maskformer/image_processing_maskformer.js"),S=r("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),w=r("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),x=r("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),O=r("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),ae=r("./src/models/mobilevit/image_processing_mobilevit.js"),ie=r("./src/models/nougat/image_processing_nougat.js"),ve=r("./src/models/owlv2/image_processing_owlv2.js"),we=r("./src/models/owlvit/image_processing_owlvit.js"),re=r("./src/models/phi3_v/image_processing_phi3_v.js"),xe=r("./src/models/pvt/image_processing_pvt.js"),ce=r("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),ke=r("./src/models/rt_detr/image_processing_rt_detr.js"),Ae=r("./src/models/sam/image_processing_sam.js"),Ee=r("./src/models/segformer/image_processing_segformer.js"),tt=r("./src/models/siglip/image_processing_siglip.js"),Ge=r("./src/models/swin2sr/image_processing_swin2sr.js"),ye=r("./src/models/vit/image_processing_vit.js"),J=r("./src/models/vitmatte/image_processing_vitmatte.js"),de=r("./src/models/vitpose/image_processing_vitpose.js"),Ce=r("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(ze,A,r)=>{r.r(A),r.d(A,{VLMImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{constructor(Y){super({do_pad:!0,pad_size:{width:Y.image_size,height:Y.image_size},...Y}),this.constant_values=this.config.background_color.map(N=>N*this.rescale_factor)}pad_image(Y,N,g,v){return super.pad_image(Y,N,g,{constant_values:this.constant_values,center:!0,...v})}}},"./src/models/janus/processing_janus.js":(ze,A,r)=>{r.r(A),r.d(A,{VLChatProcessor:()=>v});var _=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js"),Y=r("./src/utils/core.js"),N=r("./src/utils/tensor.js"),g=r("./src/utils/image.js");class v extends _.Processor{constructor(M,b){super(M,b),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(M,{images:b=null,chat_template:I="default"}={}){b?Array.isArray(b)||(b=[b]):b=await Promise.all(M.filter(ie=>ie.images).flatMap(ie=>ie.images).map(ie=>g.RawImage.read(ie)));const K=this.tokenizer,te=K.apply_chat_template(M,{tokenize:!1,add_generation_prompt:!0,chat_template:I}),ne=ie=>K.encode(ie,{add_special_tokens:!1}),W=te.split(this.image_tag),U=W.length-1;if(b.length!==U)throw new Error(`Number of images provided (${b.length}) does not match number of "${this.image_tag}" image tags (${U})`);const[X,$,S]=K.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let w=ne(W[0]),x=new Array(w.length).fill(!1);for(let ie=1;ie0){const ie=await this.image_processor(b);return ie.pixel_values.unsqueeze_(0),{...ae,...ie}}return ae}}fe(v,"image_processor_class",D.AutoImageProcessor),fe(v,"tokenizer_class",j.AutoTokenizer),fe(v,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(ze,A,r)=>{r.r(A),r.d(A,{JinaCLIPImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{constructor(Y){const{resize_mode:N,fill_color:g,interpolation:v,size:y,...M}=Y,b=N==="squash"?{width:y,height:y}:N==="shortest"?{shortest_edge:y}:{longest_edge:y},I=v==="bicubic"?3:2;super({...M,size:b,resample:I,do_center_crop:!0,crop_size:y,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(ze,A,r)=>{r.r(A),r.d(A,{JinaCLIPProcessor:()=>Y});var _=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");class Y extends _.Processor{async _call(g=null,v=null,y={}){if(!g&&!v)throw new Error("Either text or images must be provided");const M=g?this.tokenizer(g,y):{},b=v?await this.image_processor(v,y):{};return{...M,...b}}}fe(Y,"tokenizer_class",j.AutoTokenizer),fe(Y,"image_processor_class",D.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(ze,A,r)=>{r.r(A),r.d(A,{LlavaOnevisionImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(ze,A,r)=>{r.r(A),r.d(A,{Mask2FormerImageProcessor:()=>D});var _=r("./src/models/maskformer/image_processing_maskformer.js");class D extends _.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(ze,A,r)=>{r.r(A),r.d(A,{MaskFormerFeatureExtractor:()=>j,MaskFormerImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{post_process_panoptic_segmentation(...N){return(0,_.post_process_panoptic_segmentation)(...N)}post_process_instance_segmentation(...N){return(0,_.post_process_instance_segmentation)(...N)}}class j extends D{}},"./src/models/mgp_str/processing_mgp_str.js":(ze,A,r)=>{r.r(A),r.d(A,{MgpstrProcessor:()=>g});var _=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js"),Y=r("./src/utils/maths.js");const N={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class g extends _.Processor{get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(y,M){if(!N.hasOwnProperty(M))throw new Error(`Format ${M} is not supported.`);const[b,I]=N[M],K=this[b].bind(this),[te,ne]=y.dims,W=[],U=[],X=y.tolist();for(let S=0;S0?O.reduce((ie,ve)=>ie*ve,1):0;U.push(x),W.push(ae)}return[K(U),W]}char_decode(y){return this.char_tokenizer.batch_decode(y).map(M=>M.replaceAll(" ",""))}bpe_decode(y){return this.bpe_tokenizer.batch_decode(y)}wp_decode(y){return this.wp_tokenizer.batch_decode(y).map(M=>M.replaceAll(" ",""))}batch_decode([y,M,b]){const[I,K]=this._decode_helper(y,"char"),[te,ne]=this._decode_helper(M,"bpe"),[W,U]=this._decode_helper(b,"wp"),X=[],$=[];for(let S=0;S{r.r(A),r.d(A,{MobileNetV1FeatureExtractor:()=>j,MobileNetV1ImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{}class j extends D{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(ze,A,r)=>{r.r(A),r.d(A,{MobileNetV2FeatureExtractor:()=>j,MobileNetV2ImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{}class j extends D{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(ze,A,r)=>{r.r(A),r.d(A,{MobileNetV3FeatureExtractor:()=>j,MobileNetV3ImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{}class j extends D{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(ze,A,r)=>{r.r(A),r.d(A,{MobileNetV4FeatureExtractor:()=>j,MobileNetV4ImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{}class j extends D{}},"./src/models/mobilevit/image_processing_mobilevit.js":(ze,A,r)=>{r.r(A),r.d(A,{MobileViTFeatureExtractor:()=>j,MobileViTImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{}class j extends D{}},"./src/models/moonshine/feature_extraction_moonshine.js":(ze,A,r)=>{r.r(A),r.d(A,{MoonshineFeatureExtractor:()=>j});var _=r("./src/base/feature_extraction_utils.js"),D=r("./src/utils/tensor.js");class j extends _.FeatureExtractor{async _call(N){(0,_.validate_audio_inputs)(N,"MoonshineFeatureExtractor"),N instanceof Float64Array&&(N=new Float32Array(N));const g=[1,N.length];return{input_values:new D.Tensor("float32",N,g)}}}},"./src/models/moonshine/processing_moonshine.js":(ze,A,r)=>{r.r(A),r.d(A,{MoonshineProcessor:()=>Y});var _=r("./src/models/auto/feature_extraction_auto.js"),D=r("./src/tokenizers.js"),j=r("./src/base/processing_utils.js");class Y extends j.Processor{async _call(g){return await this.feature_extractor(g)}}fe(Y,"tokenizer_class",D.AutoTokenizer),fe(Y,"feature_extractor_class",_.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(ze,A,r)=>{r.r(A),r.d(A,{NougatImageProcessor:()=>D});var _=r("./src/models/donut/image_processing_donut.js");class D extends _.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(ze,A,r)=>{r.r(A),r.d(A,{Owlv2ImageProcessor:()=>D});var _=r("./src/models/owlvit/image_processing_owlvit.js");class D extends _.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(ze,A,r)=>{r.r(A),r.d(A,{OwlViTFeatureExtractor:()=>j,OwlViTImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{post_process_object_detection(...N){return(0,_.post_process_object_detection)(...N)}}class j extends D{}},"./src/models/owlvit/processing_owlvit.js":(ze,A,r)=>{r.r(A),r.d(A,{OwlViTProcessor:()=>Y});var _=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");class Y extends _.Processor{}fe(Y,"tokenizer_class",j.AutoTokenizer),fe(Y,"image_processor_class",D.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(ze,A,r)=>{r.r(A),r.d(A,{PaliGemmaProcessor:()=>g});var _=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");const Y="";function N(v,y,M,b,I){return`${b.repeat(M*I)}${y}${v} +`}class g extends _.Processor{async _call(y,M=null,b={}){M||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),M=""),Array.isArray(y)||(y=[y]),Array.isArray(M)||(M=[M]);const I=this.tokenizer.bos_token,K=this.image_processor.config.image_seq_length;let te;M.some(U=>U.includes(Y))?te=M.map(U=>{const X=U.replaceAll(Y,Y.repeat(K)),$=X.lastIndexOf(Y),S=$===-1?0:$+Y.length;return X.slice(0,S)+I+X.slice(S)+` +`}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),te=M.map(U=>N(U,I,K,Y,y.length)));const ne=this.tokenizer(te,b);return{...await this.image_processor(y,b),...ne}}}fe(g,"tokenizer_class",j.AutoTokenizer),fe(g,"image_processor_class",D.AutoImageProcessor),fe(g,"uses_processor_config",!1)},"./src/models/phi3_v/image_processing_phi3_v.js":(ze,A,r)=>{r.r(A),r.d(A,{Phi3VImageProcessor:()=>y});var _=r("./src/base/image_processors_utils.js"),D=r("./src/utils/tensor.js");const j=336,Y=[2,3],{ceil:N,floor:g,sqrt:v}=Math;class y extends _.ImageProcessor{constructor(b){super({...b,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=b.num_crops}calc_num_image_tokens_from_image_size(b,I){const{num_img_tokens:K}=this.config;return g((g(I/j)*g(b/j)+1)*K+1+(g(I/j)+1)*v(K))}get_resize_output_image_size(b,I){const K=this._num_crops,[te,ne]=b.size;let W=te/ne,U=1;for(;U*Math.ceil(U/W)<=K;)U+=1;U-=1;const X=Math.floor(U*336),$=Math.floor(X/W);return[X,$]}pad_image(b,I,K,te={}){const[ne,W]=I,U=j*N(ne/j),X=j*N(W/j),$=[1,1,1].map((S,w)=>(S-this.image_mean[w])/this.image_std[w]);return super.pad_image(b,I,{width:X,height:U},{center:!0,constant_values:$,...te})}async _call(b,{num_crops:I=null}={}){if(this._num_crops=I??(I=this.config.num_crops),I<4||v(I)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(b)||(b=[b]);const K=b.length,te=await Promise.all(b.map(x=>this.preprocess(x))),ne=te.map(x=>x.original_size),W=te.map(x=>x.reshaped_input_size),U=[];for(const{pixel_values:x}of te){x.unsqueeze_(0);const[O,ae]=x.dims.slice(-2),ie=await(0,D.interpolate_4d)(x,{size:[j,j],mode:"bicubic"});if(I>0){const ve=[],we=v(I),re=g(ae/we),xe=g(O/we);for(let ke=0;kex.map(O=>j*N(O/j))),S=new D.Tensor("int64",$.flat(),[K,2]),w=$.map(([x,O])=>this.calc_num_image_tokens_from_image_size(O,x));return{pixel_values:X,original_sizes:ne,reshaped_input_sizes:W,image_sizes:S,num_img_tokens:w}}}},"./src/models/phi3_v/processing_phi3_v.js":(ze,A,r)=>{r.r(A),r.d(A,{Phi3VProcessor:()=>g});var _=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");r("./src/utils/image.js");const Y="<|image|>",N=/<\|image_\d+\|>/g;class g extends _.Processor{async _call(y,M=null,{padding:b=!0,truncation:I=!0,num_crops:K=null}={}){Array.isArray(y)||(y=[y]);let te,ne;if(M){ne=await this.image_processor(M,{num_crops:K});const{num_img_tokens:W}=ne,U=y.map(($,S)=>$.split(N).join(Y.repeat(W[S])));te=this.tokenizer(U,{padding:b,truncation:I});const X=this.tokenizer.model.convert_tokens_to_ids([Y])[0];te.input_ids.map_($=>$==X?-$:$)}else te=this.tokenizer(y);return{...te,...ne}}}fe(g,"image_processor_class",D.AutoImageProcessor),fe(g,"tokenizer_class",j.AutoTokenizer)},"./src/models/processors.js":(ze,A,r)=>{r.r(A),r.d(A,{Florence2Processor:()=>_.Florence2Processor,GroundingDinoProcessor:()=>D.GroundingDinoProcessor,Idefics3Processor:()=>j.Idefics3Processor,JinaCLIPProcessor:()=>N.JinaCLIPProcessor,MgpstrProcessor:()=>g.MgpstrProcessor,MoonshineProcessor:()=>v.MoonshineProcessor,OwlViTProcessor:()=>y.OwlViTProcessor,PaliGemmaProcessor:()=>b.PaliGemmaProcessor,Phi3VProcessor:()=>M.Phi3VProcessor,PyAnnoteProcessor:()=>I.PyAnnoteProcessor,Qwen2VLProcessor:()=>K.Qwen2VLProcessor,SamProcessor:()=>te.SamProcessor,SpeechT5Processor:()=>ne.SpeechT5Processor,VLChatProcessor:()=>Y.VLChatProcessor,Wav2Vec2ProcessorWithLM:()=>W.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>U.WhisperProcessor});var _=r("./src/models/florence2/processing_florence2.js"),D=r("./src/models/grounding_dino/processing_grounding_dino.js"),j=r("./src/models/idefics3/processing_idefics3.js"),Y=r("./src/models/janus/processing_janus.js"),N=r("./src/models/jina_clip/processing_jina_clip.js"),g=r("./src/models/mgp_str/processing_mgp_str.js"),v=r("./src/models/moonshine/processing_moonshine.js"),y=r("./src/models/owlvit/processing_owlvit.js"),M=r("./src/models/phi3_v/processing_phi3_v.js"),b=r("./src/models/paligemma/processing_paligemma.js"),I=r("./src/models/pyannote/processing_pyannote.js"),K=r("./src/models/qwen2_vl/processing_qwen2_vl.js"),te=r("./src/models/sam/processing_sam.js"),ne=r("./src/models/speecht5/processing_speecht5.js"),W=r("./src/models/wav2vec2/processing_wav2vec2.js"),U=r("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(ze,A,r)=>{r.r(A),r.d(A,{PvtImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(ze,A,r)=>{r.r(A),r.d(A,{PyAnnoteFeatureExtractor:()=>Y});var _=r("./src/base/feature_extraction_utils.js"),D=r("./src/utils/tensor.js"),j=r("./src/utils/maths.js");class Y extends _.FeatureExtractor{async _call(g){(0,_.validate_audio_inputs)(g,"PyAnnoteFeatureExtractor"),g instanceof Float64Array&&(g=new Float32Array(g));const v=[1,1,g.length];return{input_values:new D.Tensor("float32",g,v)}}samples_to_frames(g){return(g-this.config.offset)/this.config.step}post_process_speaker_diarization(g,v){const y=v/this.samples_to_frames(v)/this.config.sampling_rate,M=[];for(const b of g.tolist()){const I=[];let K=-1;for(let te=0;te({id:te,start:ne*y,end:W*y,confidence:U/(W-ne)})))}return M}}},"./src/models/pyannote/processing_pyannote.js":(ze,A,r)=>{r.r(A),r.d(A,{PyAnnoteProcessor:()=>j});var _=r("./src/base/processing_utils.js"),D=r("./src/models/pyannote/feature_extraction_pyannote.js");class j extends _.Processor{async _call(N){return await this.feature_extractor(N)}post_process_speaker_diarization(...N){return this.feature_extractor.post_process_speaker_diarization(...N)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}fe(j,"feature_extractor_class",D.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(ze,A,r)=>{r.r(A),r.d(A,{Qwen2VLImageProcessor:()=>j});var _=r("./src/base/image_processors_utils.js"),D=r("./src/utils/tensor.js");class j extends _.ImageProcessor{async _call(N,...g){const{pixel_values:v,original_sizes:y,reshaped_input_sizes:M}=await super._call(N,...g);let b=v;const{temporal_patch_size:I,merge_size:K,patch_size:te}=this.config;b.dims[0]===1&&(b=(0,D.cat)(Array.from({length:I},()=>b),0));const ne=b.dims[0]/I,W=b.dims[1],U=Math.floor(b.dims[2]/te),X=Math.floor(b.dims[3]/te),$=b.view(ne,I,W,Math.floor(U/K),K,te,Math.floor(X/K),K,te).permute(0,3,6,4,7,2,1,5,8).view(ne*U*X,W*I*te*te),S=new D.Tensor("int64",[ne,U,X],[1,3]);return{pixel_values:$,image_grid_thw:S,original_sizes:y,reshaped_input_sizes:M}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(ze,A,r)=>{r.r(A),r.d(A,{Qwen2VLProcessor:()=>Y});var _=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js"),j=r("./src/tokenizers.js");r("./src/utils/image.js");class Y extends _.Processor{async _call(g,v=null,...y){Array.isArray(g)||(g=[g]);let M,b;if(v&&(M=await this.image_processor(v),b=M.image_grid_thw),b){let K=this.image_processor.config.merge_size**2,te=0;const ne=b.tolist();g=g.map(W=>{for(;W.includes("<|image_pad|>");){const U=Number(ne[te++].reduce((X,$)=>X*$,1n));W=W.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(U/K)))}return W.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(g),...M}}}fe(Y,"image_processor_class",D.AutoImageProcessor),fe(Y,"tokenizer_class",j.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(ze,A,r)=>{r.r(A),r.d(A,{RTDetrImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{post_process_object_detection(...Y){return(0,_.post_process_object_detection)(...Y)}}},"./src/models/sam/image_processing_sam.js":(ze,A,r)=>{r.r(A),r.d(A,{SamImageProcessor:()=>Y});var _=r("./src/base/image_processors_utils.js"),D=r("./src/utils/core.js"),j=r("./src/utils/tensor.js");class Y extends _.ImageProcessor{reshape_input_points(g,v,y,M=!1){g=structuredClone(g);let b=(0,D.calculateDimensions)(g);if(b.length===3)M||(b=[1,...b]),g=[g];else if(b.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let I=0;IM!==v.dims[b]))throw Error(`The first ${y.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new j.Tensor("int64",g.flat(1/0).map(BigInt),y)}async _call(g,{input_points:v=null,input_labels:y=null,input_boxes:M=null}={}){const b=await super._call(g);if(v&&(b.input_points=this.reshape_input_points(v,b.original_sizes,b.reshaped_input_sizes)),y){if(!b.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");b.input_labels=this.add_input_labels(y,b.input_points)}return M&&(b.input_boxes=this.reshape_input_points(M,b.original_sizes,b.reshaped_input_sizes,!0)),b}async post_process_masks(g,v,y,{mask_threshold:M=0,binarize:b=!0,pad_size:I=null}={}){const K=[];I=I??this.pad_size;const te=[I.height,I.width];for(let ne=0;neM&&(S[w]=1);X=new j.Tensor("bool",S,X.dims)}K.push(X)}return K}generate_crop_boxes(g,v,{crop_n_layers:y=0,overlap_ratio:M=.3413333333333333,points_per_crop:b=32,crop_n_points_downscale_factor:I=1}={}){}}},"./src/models/sam/processing_sam.js":(ze,A,r)=>{r.r(A),r.d(A,{SamProcessor:()=>j});var _=r("./src/base/processing_utils.js"),D=r("./src/models/auto/image_processing_auto.js");class j extends _.Processor{async _call(...N){return await this.image_processor(...N)}post_process_masks(...N){return this.image_processor.post_process_masks(...N)}reshape_input_points(...N){return this.image_processor.reshape_input_points(...N)}}fe(j,"image_processor_class",D.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(ze,A,r)=>{r.r(A),r.d(A,{SeamlessM4TFeatureExtractor:()=>Y});var _=r("./src/base/feature_extraction_utils.js"),D=r("./src/utils/tensor.js"),j=r("./src/utils/audio.js");class Y extends _.FeatureExtractor{constructor(g){super(g);const v=this.config.sampling_rate,y=(0,j.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(v/2),v,null,"kaldi",!0);for(let M=0;My*32768),(0,j.spectrogram)(g,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:v,transpose:!0})}async _call(g,{padding:v=!0,pad_to_multiple_of:y=2,do_normalize_per_mel_bins:M=!0,return_attention_mask:b=!0}={}){(0,_.validate_audio_inputs)(g,"SeamlessM4TFeatureExtractor");let I=await this._extract_fbank_features(g,this.config.max_length);if(M){const[S,w]=I.dims,x=I.data;for(let O=0;O0){const ae=new Float32Array(w*(S+O));ae.set(x),ae.fill(this.config.padding_value,x.length);const ie=S+O;I=new D.Tensor(I.type,ae,[ie,w]),b&&(K=new D.Tensor("int64",new BigInt64Array(ie),[1,ie]),K.data.fill(1n,0,S))}}const[te,ne]=I.dims,W=this.config.stride;if(te%W!==0)throw new Error(`The number of frames (${te}) must be a multiple of the stride (${W}).`);const X=I.view(1,Math.floor(te/W),ne*W),$={input_features:X};if(b){const S=X.dims[1],w=new BigInt64Array(S);if(K){const x=K.data;for(let O=1,ae=0;O{r.r(A),r.d(A,{SegformerFeatureExtractor:()=>j,SegformerImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{post_process_semantic_segmentation(...N){return(0,_.post_process_semantic_segmentation)(...N)}}class j extends D{}},"./src/models/siglip/image_processing_siglip.js":(ze,A,r)=>{r.r(A),r.d(A,{SiglipImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(ze,A,r)=>{r.r(A),r.d(A,{SpeechT5FeatureExtractor:()=>D});var _=r("./src/base/feature_extraction_utils.js");class D extends _.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(ze,A,r)=>{r.r(A),r.d(A,{SpeechT5Processor:()=>Y});var _=r("./src/base/processing_utils.js"),D=r("./src/tokenizers.js"),j=r("./src/models/auto/feature_extraction_auto.js");class Y extends _.Processor{async _call(g){return await this.feature_extractor(g)}}fe(Y,"tokenizer_class",D.AutoTokenizer),fe(Y,"feature_extractor_class",j.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(ze,A,r)=>{r.r(A),r.d(A,{Swin2SRImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{pad_image(Y,N,g,v={}){const[y,M,b]=N;return super.pad_image(Y,N,{width:M+(g-M%g)%g,height:y+(g-y%g)%g},{mode:"symmetric",center:!1,constant_values:-1,...v})}}},"./src/models/vit/image_processing_vit.js":(ze,A,r)=>{r.r(A),r.d(A,{ViTFeatureExtractor:()=>j,ViTImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{}class j extends D{}},"./src/models/vitmatte/image_processing_vitmatte.js":(ze,A,r)=>{r.r(A),r.d(A,{VitMatteImageProcessor:()=>j});var _=r("./src/base/image_processors_utils.js"),D=r("./src/utils/tensor.js");class j extends _.ImageProcessor{async _call(N,g){Array.isArray(N)||(N=[N]),Array.isArray(g)||(g=[g]);const v=await Promise.all(N.map(b=>this.preprocess(b))),y=await Promise.all(g.map(b=>this.preprocess(b,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,D.stack)(v.map((b,I)=>(0,D.cat)([b.pixel_values,y[I].pixel_values],0)),0),original_sizes:v.map(b=>b.original_size),reshaped_input_sizes:v.map(b=>b.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(ze,A,r)=>{r.r(A),r.d(A,{VitPoseImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{post_process_pose_estimation(Y,N,{threshold:g=null}={}){const v=Y.tolist(),[y,M,b,I]=Y.dims,K=[];for(let te=0;te{r.r(A),r.d(A,{Wav2Vec2FeatureExtractor:()=>j});var _=r("./src/base/feature_extraction_utils.js"),D=r("./src/utils/tensor.js");class j extends _.FeatureExtractor{_zero_mean_unit_var_norm(N){const v=N.reduce((M,b)=>M+b,0)/N.length,y=N.reduce((M,b)=>M+(b-v)**2,0)/N.length;return N.map(M=>(M-v)/Math.sqrt(y+1e-7))}async _call(N){(0,_.validate_audio_inputs)(N,"Wav2Vec2FeatureExtractor"),N instanceof Float64Array&&(N=new Float32Array(N));let g=N;this.config.do_normalize&&(g=this._zero_mean_unit_var_norm(g));const v=[1,g.length];return{input_values:new D.Tensor("float32",g,v),attention_mask:new D.Tensor("int64",new BigInt64Array(g.length).fill(1n),v)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(ze,A,r)=>{r.r(A),r.d(A,{Wav2Vec2ProcessorWithLM:()=>j});var _=r("./src/base/processing_utils.js"),D=r("./src/models/auto/feature_extraction_auto.js");class j extends _.Processor{async _call(N){return await this.feature_extractor(N)}}fe(j,"feature_extractor_class",D.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(ze,A,r)=>{r.r(A),r.d(A,{WeSpeakerFeatureExtractor:()=>j});var _=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var D=r("./src/utils/audio.js");class j extends _.FeatureExtractor{constructor(N){super(N);const g=this.config.sampling_rate,v=(0,D.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(g/2),g,null,"kaldi",!0);for(let y=0;yg*32768),(0,D.spectrogram)(N,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(N){(0,_.validate_audio_inputs)(N,"WeSpeakerFeatureExtractor");const g=(await this._extract_fbank_features(N)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const v=g.mean(1).data,y=g.data,[M,b,I]=g.dims;for(let K=0;K{r.r(A),r.d(A,{WHISPER_LANGUAGE_MAPPING:()=>D,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>j,whisper_language_to_code:()=>Y});const _=[["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"]],D=new Map(_),j=new Map([..._.map(([N,g])=>[g,N]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function Y(N){N=N.toLowerCase();let g=j.get(N);if(g===void 0)if(D.has(N))g=N;else{const y=N.length===2?D.keys():D.values();throw new Error(`Language "${N}" is not supported. Must be one of: ${JSON.stringify(y)}`)}return g}},"./src/models/whisper/feature_extraction_whisper.js":(ze,A,r)=>{r.r(A),r.d(A,{WhisperFeatureExtractor:()=>Y});var _=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var D=r("./src/utils/audio.js"),j=r("./src/utils/maths.js");class Y extends _.FeatureExtractor{constructor(g){var v;super(g),(v=this.config).mel_filters??(v.mel_filters=(0,D.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,D.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(g){const v=await(0,D.spectrogram)(g,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}),y=v.data,M=(0,j.max)(y)[0];for(let b=0;bthis.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`."),v=g.slice(0,this.config.n_samples)):(v=new Float32Array(this.config.n_samples),v.set(g)),{input_features:(await this._extract_fbank_features(v)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(ze,A,r)=>{r.r(A),r.d(A,{WhisperGenerationConfig:()=>D});var _=r("./src/generation/configuration_utils.js");class D extends _.GenerationConfig{constructor(){super(...arguments);fe(this,"return_timestamps",null);fe(this,"return_token_timestamps",null);fe(this,"num_frames",null);fe(this,"alignment_heads",null);fe(this,"task",null);fe(this,"language",null);fe(this,"no_timestamps_token_id",null);fe(this,"prompt_ids",null);fe(this,"is_multilingual",null);fe(this,"lang_to_id",null);fe(this,"task_to_id",null);fe(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(ze,A,r)=>{r.r(A),r.d(A,{WhisperProcessor:()=>Y});var _=r("./src/models/auto/feature_extraction_auto.js"),D=r("./src/tokenizers.js"),j=r("./src/base/processing_utils.js");class Y extends j.Processor{async _call(g){return await this.feature_extractor(g)}}fe(Y,"tokenizer_class",D.AutoTokenizer),fe(Y,"feature_extractor_class",_.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(ze,A,r)=>{r.r(A),r.d(A,{YolosFeatureExtractor:()=>j,YolosImageProcessor:()=>D});var _=r("./src/base/image_processors_utils.js");class D extends _.ImageProcessor{post_process_object_detection(...N){return(0,_.post_process_object_detection)(...N)}}class j extends D{}},"./src/ops/registry.js":(ze,A,r)=>{r.r(A),r.d(A,{TensorOpRegistry:()=>Y});var _=r("./src/backends/onnx.js"),D=r("./src/utils/tensor.js");const j=async(N,g,v)=>{const y=await(0,_.createInferenceSession)(new Uint8Array(N),g);return async M=>{const b=(0,_.isONNXProxy)(),I=Object.fromEntries(Object.entries(M).map(([te,ne])=>[te,(b?ne.clone():ne).ort_tensor])),K=await y.run(I);return Array.isArray(v)?v.map(te=>new D.Tensor(K[te])):new D.Tensor(K[v])}};class Y{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=j([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=j([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=j([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=j([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=j([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=j([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=j([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=j([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}fe(Y,"session_options",{})},"./src/pipelines.js":(ze,A,r)=>{r.r(A),r.d(A,{AudioClassificationPipeline:()=>we,AutomaticSpeechRecognitionPipeline:()=>xe,DepthEstimationPipeline:()=>Ce,DocumentQuestionAnsweringPipeline:()=>ye,FeatureExtractionPipeline:()=>ie,FillMaskPipeline:()=>X,ImageClassificationPipeline:()=>ke,ImageFeatureExtractionPipeline:()=>ve,ImageSegmentationPipeline:()=>Ae,ImageToImagePipeline:()=>de,ImageToTextPipeline:()=>ce,ObjectDetectionPipeline:()=>tt,Pipeline:()=>te,QuestionAnsweringPipeline:()=>U,SummarizationPipeline:()=>S,Text2TextGenerationPipeline:()=>$,TextClassificationPipeline:()=>ne,TextGenerationPipeline:()=>O,TextToAudioPipeline:()=>J,TokenClassificationPipeline:()=>W,TranslationPipeline:()=>w,ZeroShotAudioClassificationPipeline:()=>re,ZeroShotClassificationPipeline:()=>ae,ZeroShotImageClassificationPipeline:()=>Ee,ZeroShotObjectDetectionPipeline:()=>Ge,pipeline:()=>se});var _=r("./src/tokenizers.js"),D=r("./src/models.js"),j=r("./src/models/auto/processing_auto.js");r("./src/base/processing_utils.js");var Y=r("./src/utils/generic.js"),N=r("./src/utils/core.js"),g=r("./src/utils/maths.js"),v=r("./src/utils/audio.js"),y=r("./src/utils/tensor.js"),M=r("./src/utils/image.js");async function b(je){return Array.isArray(je)||(je=[je]),await Promise.all(je.map(le=>M.RawImage.read(le)))}async function I(je,le){return Array.isArray(je)||(je=[je]),await Promise.all(je.map(Te=>typeof Te=="string"||Te instanceof URL?(0,v.read_audio)(Te,le):Te instanceof Float64Array?new Float32Array(Te):Te))}function K(je,le){le&&(je=je.map(Re=>Re|0));const[Te,Ue,Ve,Ne]=je;return{xmin:Te,ymin:Ue,xmax:Ve,ymax:Ne}}class te extends Y.Callable{constructor({task:le,model:Te,tokenizer:Ue=null,processor:Ve=null}){super(),this.task=le,this.model=Te,this.tokenizer=Ue,this.processor=Ve}async dispose(){await this.model.dispose()}}class ne extends te{constructor(le){super(le)}async _call(le,{top_k:Te=1}={}){const Ue=this.tokenizer(le,{padding:!0,truncation:!0}),Ve=await this.model(Ue),Ne=this.model.config.problem_type==="multi_label_classification"?dt=>dt.sigmoid():dt=>new y.Tensor("float32",(0,g.softmax)(dt.data),dt.dims),Re=this.model.config.id2label,st=[];for(const dt of Ve.logits){const ct=Ne(dt),lt=await(0,y.topk)(ct,Te),ht=lt[0].tolist(),oe=lt[1].tolist().map((H,me)=>({label:Re?Re[H]:`LABEL_${H}`,score:ht[me]}));Te===1?st.push(...oe):st.push(oe)}return Array.isArray(le)||Te===1?st:st[0]}}class W extends te{constructor(le){super(le)}async _call(le,{ignore_labels:Te=["O"]}={}){const Ue=Array.isArray(le),Ve=this.tokenizer(Ue?le:[le],{padding:!0,truncation:!0}),Re=(await this.model(Ve)).logits,st=this.model.config.id2label,dt=[];for(let ct=0;ctut==this.tokenizer.sep_token_id);dt[ht].map((ut,mt)=>ut==1&&(mt===0||mt>oe&&ct.findIndex(vt=>vt==L[mt])===-1));const H=Ne[ht].tolist(),me=Re[ht].tolist();for(let ut=1;utmt==L[ut])!==-1)&&(H[ut]=-1/0,me[ut]=-1/0);const $e=(0,g.softmax)(H).map((ut,mt)=>[ut,mt]),We=(0,g.softmax)(me).map((ut,mt)=>[ut,mt]);$e[0][0]=0,We[0][0]=0;const Je=(0,N.product)($e,We).filter(ut=>ut[0][1]<=ut[1][1]).map(ut=>[ut[0][1],ut[1][1],ut[0][0]*ut[1][0]]).sort((ut,mt)=>mt[2]-ut[2]);for(let ut=0;utH==this.tokenizer.mask_token_id);if(ct===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const lt=Ve[st][ct],ht=await(0,y.topk)(new y.Tensor("float32",(0,g.softmax)(lt.data),lt.dims),Te),L=ht[0].tolist(),oe=ht[1].tolist();Ne.push(oe.map((H,me)=>{const $e=dt.slice();return $e[ct]=H,{score:L[me],token:Number(H),token_str:this.tokenizer.decode([H]),sequence:this.tokenizer.decode($e,{skip_special_tokens:!0})}}))}return Array.isArray(le)?Ne:Ne[0]}}class $ extends te{constructor(Te){super(Te);fe(this,"_key","generated_text")}async _call(Te,Ue={}){Array.isArray(Te)||(Te=[Te]),this.model.config.prefix&&(Te=Te.map(ct=>this.model.config.prefix+ct));const Ve=this.model.config.task_specific_params;Ve&&Ve[this.task]&&Ve[this.task].prefix&&(Te=Te.map(ct=>Ve[this.task].prefix+ct));const Ne=this.tokenizer,Re={padding:!0,truncation:!0};let st;this instanceof w&&"_build_translation_inputs"in Ne?st=Ne._build_translation_inputs(Te,Re,Ue):st=Ne(Te,Re);const dt=await this.model.generate({...st,...Ue});return Ne.batch_decode(dt,{skip_special_tokens:!0}).map(ct=>({[this._key]:ct}))}}class S extends ${constructor(Te){super(Te);fe(this,"_key","summary_text")}}class w extends ${constructor(Te){super(Te);fe(this,"_key","translation_text")}}function x(je){return Array.isArray(je)&&je.every(le=>"role"in le&&"content"in le)}class O extends te{constructor(le){super(le)}async _call(le,Te={}){let Ue=!1,Ve=!1,Ne;if(typeof le=="string")Ne=le=[le];else if(Array.isArray(le)&&le.every(oe=>typeof oe=="string"))Ue=!0,Ne=le;else{if(x(le))le=[le];else if(Array.isArray(le)&&le.every(x))Ue=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");Ve=!0,Ne=le.map(oe=>this.tokenizer.apply_chat_template(oe,{tokenize:!1,add_generation_prompt:!0}))}const Re=Te.add_special_tokens??!1,st=Ve?!1:Te.return_full_text??!0;this.tokenizer.padding_side="left";const dt=this.tokenizer(Ne,{add_special_tokens:Re,padding:!0,truncation:!0}),ct=await this.model.generate({...dt,...Te}),lt=this.tokenizer.batch_decode(ct,{skip_special_tokens:!0});let ht;!st&&dt.input_ids.dims.at(-1)>0&&(ht=this.tokenizer.batch_decode(dt.input_ids,{skip_special_tokens:!0}).map(oe=>oe.length));const L=Array.from({length:le.length},oe=>[]);for(let oe=0;oe[Te.toLowerCase(),Ue])),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(le,Te,{hypothesis_template:Ue="This example is {}.",multi_label:Ve=!1}={}){const Ne=Array.isArray(le);Ne||(le=[le]),Array.isArray(Te)||(Te=[Te]);const Re=Te.map(ct=>Ue.replace("{}",ct)),st=Ve||Te.length===1,dt=[];for(const ct of le){const lt=[];for(const oe of Re){const H=this.tokenizer(ct,{text_pair:oe,padding:!0,truncation:!0}),me=await this.model(H);st?lt.push([me.logits.data[this.contradiction_id],me.logits.data[this.entailment_id]]):lt.push(me.logits.data[this.entailment_id])}const L=(st?lt.map(oe=>(0,g.softmax)(oe)[1]):(0,g.softmax)(lt)).map((oe,H)=>[oe,H]).sort((oe,H)=>H[0]-oe[0]);dt.push({sequence:ct,labels:L.map(oe=>Te[oe[1]]),scores:L.map(oe=>oe[0])})}return Ne?dt:dt[0]}}class ie extends te{constructor(le){super(le)}async _call(le,{pooling:Te="none",normalize:Ue=!1,quantize:Ve=!1,precision:Ne="binary"}={}){const Re=this.tokenizer(le,{padding:!0,truncation:!0}),st=await this.model(Re);let dt=st.last_hidden_state??st.logits??st.token_embeddings;if(Te!=="none")if(Te==="mean")dt=(0,y.mean_pooling)(dt,Re.attention_mask);else if(Te==="cls")dt=dt.slice(null,0);else throw Error(`Pooling method '${Te}' not supported.`);return Ue&&(dt=dt.normalize(2,-1)),Ve&&(dt=(0,y.quantize_embeddings)(dt,Ne)),dt}}class ve extends te{constructor(le){super(le)}async _call(le,{pool:Te=null}={}){const Ue=await b(le),{pixel_values:Ve}=await this.processor(Ue),Ne=await this.model({pixel_values:Ve});let Re;if(Te){if(!("pooler_output"in Ne))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Re=Ne.pooler_output}else Re=Ne.last_hidden_state??Ne.logits??Ne.image_embeds;return Re}}class we extends te{constructor(le){super(le)}async _call(le,{top_k:Te=5}={}){const Ue=this.processor.feature_extractor.config.sampling_rate,Ve=await I(le,Ue),Ne=this.model.config.id2label,Re=[];for(const st of Ve){const dt=await this.processor(st),lt=(await this.model(dt)).logits[0],ht=await(0,y.topk)(new y.Tensor("float32",(0,g.softmax)(lt.data),lt.dims),Te),L=ht[0].tolist(),H=ht[1].tolist().map((me,$e)=>({label:Ne?Ne[me]:`LABEL_${me}`,score:L[$e]}));Re.push(H)}return Array.isArray(le)?Re:Re[0]}}class re extends te{constructor(le){super(le)}async _call(le,Te,{hypothesis_template:Ue="This is a sound of {}."}={}){const Ve=!Array.isArray(le);Ve&&(le=[le]);const Ne=Te.map(lt=>Ue.replace("{}",lt)),Re=this.tokenizer(Ne,{padding:!0,truncation:!0}),st=this.processor.feature_extractor.config.sampling_rate,dt=await I(le,st),ct=[];for(const lt of dt){const ht=await this.processor(lt),L=await this.model({...Re,...ht}),oe=(0,g.softmax)(L.logits_per_audio.data);ct.push([...oe].map((H,me)=>({score:H,label:Te[me]})))}return Ve?ct[0]:ct}}class xe extends te{constructor(le){super(le)}async _call(le,Te={}){switch(this.model.config.model_type){case"whisper":return this._call_whisper(le,Te);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(le,Te);case"moonshine":return this._call_moonshine(le,Te);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(le,Te){Te.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),Te.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const Ue=!Array.isArray(le);Ue&&(le=[le]);const Ve=this.processor.feature_extractor.config.sampling_rate,Ne=await I(le,Ve),Re=[];for(const st of Ne){const dt=await this.processor(st),lt=(await this.model(dt)).logits[0],ht=[];for(const oe of lt)ht.push((0,g.max)(oe.data)[1]);const L=this.tokenizer.decode(ht);Re.push({text:L})}return Ue?Re[0]:Re}async _call_whisper(le,Te){const Ue=Te.return_timestamps??!1,Ve=Te.chunk_length_s??0,Ne=Te.force_full_sequences??!1;let Re=Te.stride_length_s??null;const st={...Te};Ue==="word"&&(st.return_token_timestamps=!0,st.return_timestamps=!1);const dt=!Array.isArray(le);dt&&(le=[le]);const ct=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,lt=this.processor.feature_extractor.config.hop_length,ht=this.processor.feature_extractor.config.sampling_rate,L=await I(le,ht),oe=[];for(const H of L){let me=[];if(Ve>0){if(Re===null)Re=Ve/6;else if(Ve<=Re)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Je=ht*Ve,ut=ht*Re,mt=Je-2*ut;let vt=0;for(;;){const kt=vt+Je,At=H.subarray(vt,kt),is=await this.processor(At),ws=vt===0,ks=kt>=H.length;if(me.push({stride:[At.length,ws?0:ut,ks?0:ut],input_features:is.input_features,is_last:ks}),ks)break;vt+=mt}}else me=[{stride:[H.length,0,0],input_features:(await this.processor(H)).input_features,is_last:!0}];for(const Je of me){st.num_frames=Math.floor(Je.stride[0]/lt);const ut=await this.model.generate({inputs:Je.input_features,...st});Ue==="word"?(Je.tokens=ut.sequences.tolist()[0],Je.token_timestamps=ut.token_timestamps.tolist()[0].map(mt=>(0,g.round)(mt,2))):Je.tokens=ut[0].tolist(),Je.stride=Je.stride.map(mt=>mt/ht)}const[$e,We]=this.tokenizer._decode_asr(me,{time_precision:ct,return_timestamps:Ue,force_full_sequences:Ne});oe.push({text:$e,...We})}return dt?oe[0]:oe}async _call_moonshine(le,Te){const Ue=!Array.isArray(le);Ue&&(le=[le]);const Ve=this.processor.feature_extractor.config.sampling_rate,Ne=await I(le,Ve),Re=[];for(const st of Ne){const dt=await this.processor(st),ct=Math.floor(st.length/Ve)*6,lt=await this.model.generate({max_new_tokens:ct,...Te,...dt}),ht=this.processor.batch_decode(lt,{skip_special_tokens:!0})[0];Re.push({text:ht})}return Ue?Re[0]:Re}}class ce extends te{constructor(le){super(le)}async _call(le,Te={}){const Ue=Array.isArray(le),Ve=await b(le),{pixel_values:Ne}=await this.processor(Ve),Re=[];for(const st of Ne){st.dims=[1,...st.dims];const dt=await this.model.generate({inputs:st,...Te}),ct=this.tokenizer.batch_decode(dt,{skip_special_tokens:!0}).map(lt=>({generated_text:lt.trim()}));Re.push(ct)}return Ue?Re:Re[0]}}class ke extends te{constructor(le){super(le)}async _call(le,{top_k:Te=5}={}){const Ue=await b(le),{pixel_values:Ve}=await this.processor(Ue),Ne=await this.model({pixel_values:Ve}),Re=this.model.config.id2label,st=[];for(const dt of Ne.logits){const ct=await(0,y.topk)(new y.Tensor("float32",(0,g.softmax)(dt.data),dt.dims),Te),lt=ct[0].tolist(),L=ct[1].tolist().map((oe,H)=>({label:Re?Re[oe]:`LABEL_${oe}`,score:lt[H]}));st.push(L)}return Array.isArray(le)?st:st[0]}}class Ae extends te{constructor(le){super(le),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(le,{threshold:Te=.5,mask_threshold:Ue=.5,overlap_mask_area_threshold:Ve=.8,label_ids_to_fuse:Ne=null,target_sizes:Re=null,subtask:st=null}={}){if(Array.isArray(le)&&le.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const ct=await b(le),lt=ct.map(We=>[We.height,We.width]),{pixel_values:ht,pixel_mask:L}=await this.processor(ct),oe=await this.model({pixel_values:ht,pixel_mask:L});let H=null;if(st!==null)H=this.subtasks_mapping[st];else for(let[We,Je]of Object.entries(this.subtasks_mapping))if(Je in this.processor.image_processor){H=this.processor.image_processor[Je].bind(this.processor.image_processor),st=We;break}const me=this.model.config.id2label,$e=[];if(st==="panoptic"||st==="instance"){const We=H(oe,Te,Ue,Ve,Ne,Re??lt)[0],Je=We.segmentation;for(const ut of We.segments_info){const mt=new Uint8ClampedArray(Je.data.length);for(let kt=0;ktUe.replace("{}",L)),st=this.tokenizer(Re,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:dt}=await this.processor(Ne),ct=await this.model({...st,pixel_values:dt}),lt=this.model.config.model_type==="siglip"?L=>L.sigmoid().data:L=>(0,g.softmax)(L.data),ht=[];for(const L of ct.logits_per_image){const H=[...lt(L)].map((me,$e)=>({score:me,label:Te[$e]}));H.sort((me,$e)=>$e.score-me.score),ht.push(H)}return Ve?ht:ht[0]}}class tt extends te{constructor(le){super(le)}async _call(le,{threshold:Te=.9,percentage:Ue=!1}={}){const Ve=Array.isArray(le);if(Ve&&le.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ne=await b(le),Re=Ue?null:Ne.map(oe=>[oe.height,oe.width]),{pixel_values:st,pixel_mask:dt}=await this.processor(Ne),ct=await this.model({pixel_values:st,pixel_mask:dt}),lt=this.processor.image_processor.post_process_object_detection(ct,Te,Re),ht=this.model.config.id2label,L=lt.map(oe=>oe.boxes.map((H,me)=>({score:oe.scores[me],label:ht[oe.classes[me]],box:K(H,!Ue)})));return Ve?L:L[0]}}class Ge extends te{constructor(le){super(le)}async _call(le,Te,{threshold:Ue=.1,top_k:Ve=null,percentage:Ne=!1}={}){const Re=Array.isArray(le),st=await b(le),dt=this.tokenizer(Te,{padding:!0,truncation:!0}),ct=await this.processor(st),lt=[];for(let ht=0;ht({score:We.scores[ut],label:We.labels[ut],box:K(Je,!Ne)}))}else{const We=this.processor.image_processor.post_process_object_detection(me,Ue,oe,!0)[0];$e=We.boxes.map((Je,ut)=>({score:We.scores[ut],label:Te[We.classes[ut]],box:K(Je,!Ne)}))}$e.sort((We,Je)=>Je.score-We.score),Ve!==null&&($e=$e.slice(0,Ve)),lt.push($e)}return Re?lt:lt[0]}}class ye extends te{constructor(le){super(le)}async _call(le,Te,Ue={}){const Ve=(await b(le))[0],{pixel_values:Ne}=await this.processor(Ve),Re=`${Te}`,st=this.tokenizer(Re,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,dt=await this.model.generate({inputs:Ne,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:st,...Ue}),lt=this.tokenizer.batch_decode(dt)[0].match(/(.*?)<\/s_answer>/);let ht=null;return lt&<.length>=2&&(ht=lt[1].trim()),[{answer:ht}]}}class J extends te{constructor(Te){super(Te);fe(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=Te.vocoder??null}async _call(Te,{speaker_embeddings:Ue=null}={}){return this.processor?this._call_text_to_spectrogram(Te,{speaker_embeddings:Ue}):this._call_text_to_waveform(Te)}async _call_text_to_waveform(Te){const Ue=this.tokenizer(Te,{padding:!0,truncation:!0}),{waveform:Ve}=await this.model(Ue),Ne=this.model.config.sampling_rate;return new v.RawAudio(Ve.data,Ne)}async _call_text_to_spectrogram(Te,{speaker_embeddings:Ue}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await D.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof Ue=="string"||Ue instanceof URL)&&(Ue=new Float32Array(await(await fetch(Ue)).arrayBuffer())),Ue instanceof Float32Array)Ue=new y.Tensor("float32",Ue,[1,Ue.length]);else if(!(Ue instanceof y.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:Ve}=this.tokenizer(Te,{padding:!0,truncation:!0}),{waveform:Ne}=await this.model.generate_speech(Ve,Ue,{vocoder:this.vocoder}),Re=this.processor.feature_extractor.config.sampling_rate;return new v.RawAudio(Ne.data,Re)}}class de extends te{constructor(le){super(le)}async _call(le){const Te=await b(le),Ue=await this.processor(Te),Ve=await this.model(Ue),Ne=[];for(const Re of Ve.reconstruction){const st=Re.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ne.push(M.RawImage.fromTensor(st))}return Ne.length>1?Ne:Ne[0]}}class Ce extends te{constructor(le){super(le)}async _call(le){const Te=await b(le),Ue=await this.processor(Te),{predicted_depth:Ve}=await this.model(Ue),Ne=[];for(let Re=0;Re1?Ne:Ne[0]}}const Be=Object.freeze({"text-classification":{tokenizer:_.AutoTokenizer,pipeline:ne,model:D.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:_.AutoTokenizer,pipeline:W,model:D.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:_.AutoTokenizer,pipeline:U,model:D.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:_.AutoTokenizer,pipeline:X,model:D.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:_.AutoTokenizer,pipeline:S,model:D.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:_.AutoTokenizer,pipeline:w,model:D.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:_.AutoTokenizer,pipeline:$,model:D.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:_.AutoTokenizer,pipeline:O,model:D.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:_.AutoTokenizer,pipeline:ae,model:D.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:we,model:D.AutoModelForAudioClassification,processor:j.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:_.AutoTokenizer,pipeline:re,model:D.AutoModel,processor:j.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:_.AutoTokenizer,pipeline:xe,model:[D.AutoModelForSpeechSeq2Seq,D.AutoModelForCTC],processor:j.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:_.AutoTokenizer,pipeline:J,model:[D.AutoModelForTextToWaveform,D.AutoModelForTextToSpectrogram],processor:[j.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:_.AutoTokenizer,pipeline:ce,model:D.AutoModelForVision2Seq,processor:j.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:ke,model:D.AutoModelForImageClassification,processor:j.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Ae,model:[D.AutoModelForImageSegmentation,D.AutoModelForSemanticSegmentation,D.AutoModelForUniversalSegmentation],processor:j.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"zero-shot-image-classification":{tokenizer:_.AutoTokenizer,pipeline:Ee,model:D.AutoModel,processor:j.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:tt,model:D.AutoModelForObjectDetection,processor:j.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:_.AutoTokenizer,pipeline:Ge,model:D.AutoModelForZeroShotObjectDetection,processor:j.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:_.AutoTokenizer,pipeline:ye,model:D.AutoModelForDocumentQuestionAnswering,processor:j.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:de,model:D.AutoModelForImageToImage,processor:j.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Ce,model:D.AutoModelForDepthEstimation,processor:j.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:_.AutoTokenizer,pipeline:ie,model:D.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:j.AutoProcessor,pipeline:ve,model:[D.AutoModelForImageFeatureExtraction,D.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Ze=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function se(je,le=null,{progress_callback:Te=null,config:Ue=null,cache_dir:Ve=null,local_files_only:Ne=!1,revision:Re="main",device:st=null,dtype:dt=null,model_file_name:ct=null,session_options:lt={}}={}){je=Ze[je]??je;const ht=Be[je.split("_",1)[0]];if(!ht)throw Error(`Unsupported pipeline: ${je}. Must be one of [${Object.keys(Be)}]`);le||(le=ht.default.model,console.log(`No model specified. Using default model: "${le}".`));const L={progress_callback:Te,config:Ue,cache_dir:Ve,local_files_only:Ne,revision:Re,device:st,dtype:dt,model_file_name:ct,session_options:lt},oe=new Map([["tokenizer",ht.tokenizer],["model",ht.model],["processor",ht.processor]]),H=await Ke(oe,le,L);H.task=je,(0,N.dispatchCallback)(Te,{status:"ready",task:je,model:le});const me=ht.pipeline;return new me(H)}async function Ke(je,le,Te){const Ue=Object.create(null),Ve=[];for(const[Ne,Re]of je.entries()){if(!Re)continue;let st;Array.isArray(Re)?st=new Promise(async(dt,ct)=>{var ht,L;let lt;for(const oe of Re){if(oe===null){dt(null);return}try{dt(await oe.from_pretrained(le,Te));return}catch(H){if((ht=H.message)!=null&&ht.includes("Unsupported model type"))lt=H;else if((L=H.message)!=null&&L.includes("Could not locate file"))lt=H;else{ct(H);return}}}ct(lt)}):st=Re.from_pretrained(le,Te),Ue[Ne]=st,Ve.push(st)}await Promise.all(Ve);for(const[Ne,Re]of Object.entries(Ue))Ue[Ne]=await Re;return Ue}},"./src/tokenizers.js":(ze,A,r)=>{r.r(A),r.d(A,{AlbertTokenizer:()=>$r,AutoTokenizer:()=>as,BartTokenizer:()=>Or,BertTokenizer:()=>Jr,BlenderbotSmallTokenizer:()=>Dn,BlenderbotTokenizer:()=>Fn,BloomTokenizer:()=>Pr,CLIPTokenizer:()=>yn,CamembertTokenizer:()=>it,CodeGenTokenizer:()=>wn,CodeLlamaTokenizer:()=>Ur,CohereTokenizer:()=>vn,ConvBertTokenizer:()=>Rr,DebertaTokenizer:()=>pr,DebertaV2Tokenizer:()=>en,DistilBertTokenizer:()=>or,ElectraTokenizer:()=>Dt,EsmTokenizer:()=>Vr,FalconTokenizer:()=>An,GPT2Tokenizer:()=>jr,GPTNeoXTokenizer:()=>In,GemmaTokenizer:()=>ri,Grok1Tokenizer:()=>Wr,HerbertTokenizer:()=>Ir,LlamaTokenizer:()=>_n,M2M100Tokenizer:()=>gn,MBart50Tokenizer:()=>ar,MBartTokenizer:()=>Ms,MPNetTokenizer:()=>$n,MarianTokenizer:()=>zt,MgpstrTokenizer:()=>Bn,MobileBertTokenizer:()=>Ar,NllbTokenizer:()=>lr,NougatTokenizer:()=>Gr,PreTrainedTokenizer:()=>Nt,Qwen2Tokenizer:()=>On,RoFormerTokenizer:()=>Nr,RobertaTokenizer:()=>Is,SiglipTokenizer:()=>Mn,SpeechT5Tokenizer:()=>Ln,SqueezeBertTokenizer:()=>Zr,T5Tokenizer:()=>Vs,TokenizerModel:()=>ve,VitsTokenizer:()=>zn,Wav2Vec2CTCTokenizer:()=>bn,WhisperTokenizer:()=>tn,XLMRobertaTokenizer:()=>si,XLMTokenizer:()=>Tt,is_chinese_char:()=>X});var _=r("./src/utils/generic.js"),D=r("./src/utils/core.js"),j=r("./src/utils/hub.js"),Y=r("./src/utils/maths.js"),N=r("./src/utils/tensor.js"),g=r("./src/utils/data-structures.js"),v=r("./node_modules/@huggingface/jinja/dist/index.js"),y=r("./src/models/whisper/common_whisper.js");async function M(Pe,C){const q=await Promise.all([(0,j.getModelJSON)(Pe,"tokenizer.json",!0,C),(0,j.getModelJSON)(Pe,"tokenizer_config.json",!0,C)]);return C.legacy!==null&&(q[1].legacy=C.legacy),q}function b(Pe,C){const q=[];let ue=0;for(const be of Pe.matchAll(C)){const Se=be[0];ue0&&q.push(Se),ue=be.index+Se.length}return ue=19968&&Pe<=40959||Pe>=13312&&Pe<=19903||Pe>=131072&&Pe<=173791||Pe>=173824&&Pe<=177983||Pe>=177984&&Pe<=178207||Pe>=178208&&Pe<=183983||Pe>=63744&&Pe<=64255||Pe>=194560&&Pe<=195103}function $(Pe,C,q){const ue=[];let be=0;for(;bethis.tokens_to_ids.get(q)??this.unk_token_id)}convert_ids_to_tokens(C){return C.map(q=>this.vocab[q]??this.unk_token)}}class we extends ve{constructor(C){super(C),this.tokens_to_ids=K(C.vocab),this.unk_token_id=this.tokens_to_ids.get(C.unk_token),this.unk_token=C.unk_token,this.max_input_chars_per_word=C.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[q,ue]of this.tokens_to_ids)this.vocab[ue]=q}encode(C){const q=[];for(const ue of C){const be=[...ue];if(be.length>this.max_input_chars_per_word){q.push(this.unk_token);continue}let Se=!1,Qe=0;const pt=[];for(;Qe0&&(xt=this.config.continuing_subword_prefix+xt),this.tokens_to_ids.has(xt)){ft=xt;break}--gt}if(ft===null){Se=!0;break}pt.push(ft),Qe=gt}Se?q.push(this.unk_token):q.push(...pt)}return q}}class re extends ve{constructor(C,q){super(C);const ue=C.vocab.length;this.vocab=new Array(ue),this.scores=new Array(ue);for(let be=0;be[be,Se])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=q.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,Y.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new g.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(C){const q=C.chars,ue=1;let be=0;for(;be{const Pe=[...Array.from({length:94},(be,Se)=>Se+33),...Array.from({length:12},(be,Se)=>Se+161),...Array.from({length:82},(be,Se)=>Se+174)],C=Pe.slice();let q=0;for(let be=0;be<256;++be)Pe.includes(be)||(Pe.push(be),C.push(256+q),q+=1);const ue=C.map(be=>String.fromCharCode(be));return Object.fromEntries(Pe.map((be,Se)=>[be,ue[Se]]))})(),ce=(0,D.reverseDictionary)(xe);class ke extends ve{constructor(C){super(C),this.tokens_to_ids=K(C.vocab),this.unk_token_id=this.tokens_to_ids.get(C.unk_token),this.unk_token=C.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[ue,be]of this.tokens_to_ids)this.vocab[be]=ue;const q=Array.isArray(C.merges[0]);this.merges=q?C.merges:C.merges.map(ue=>ue.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((ue,be)=>[JSON.stringify(ue),be])),this.end_of_word_suffix=C.end_of_word_suffix,this.continuing_subword_suffix=C.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(C){if(C.length===0)return[];const q=this.cache.get(C);if(q!==void 0)return q;const ue=Array.from(C);this.end_of_word_suffix&&(ue[ue.length-1]+=this.end_of_word_suffix);let be=[];if(ue.length>1){const Se=new g.PriorityQueue((gt,ft)=>gt.score`<0x${pt.toString(16).toUpperCase().padStart(2,"0")}>`);Qe.every(pt=>this.tokens_to_ids.has(pt))?q.push(...Qe):q.push(this.unk_token)}else q.push(this.unk_token)}return q}}class Ae extends ve{constructor(C,q){super(C),this.tokens_to_ids=K(q.target_lang?C.vocab[q.target_lang]:C.vocab),this.bos_token=q.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=q.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=q.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=q.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[ue,be]of this.tokens_to_ids)this.vocab[be]=ue}encode(C){return C}}class Ee extends _.Callable{constructor(C){super(),this.config=C}static fromConfig(C){if(C===null)return null;switch(C.type){case"BertNormalizer":return new Ke(C);case"Precompiled":return new ws(C);case"Sequence":return new se(C);case"Replace":return new tt(C);case"NFC":return new Ge(C);case"NFKC":return new ye(C);case"NFKD":return new J(C);case"Strip":return new de(C);case"StripAccents":return new Ce(C);case"Lowercase":return new Be(C);case"Prepend":return new Ze(C);default:throw new Error(`Unknown Normalizer type: ${C.type}`)}}normalize(C){throw Error("normalize should be implemented in subclass.")}_call(C){return this.normalize(C)}}class tt extends Ee{normalize(C){const q=I(this.config.pattern);return q===null?C:C.replaceAll(q,this.config.content)}}class Ge extends Ee{normalize(C){return C=C.normalize("NFC"),C}}class ye extends Ee{normalize(C){return C=C.normalize("NFKC"),C}}class J extends Ee{normalize(C){return C=C.normalize("NFKD"),C}}class de extends Ee{normalize(C){return this.config.strip_left&&this.config.strip_right?C=C.trim():(this.config.strip_left&&(C=C.trimStart()),this.config.strip_right&&(C=C.trimEnd())),C}}class Ce extends Ee{normalize(C){return C=W(C),C}}class Be extends Ee{normalize(C){return C=C.toLowerCase(),C}}class Ze extends Ee{normalize(C){return C=this.config.prepend+C,C}}class se extends Ee{constructor(C){super(C),this.normalizers=C.normalizers.map(q=>Ee.fromConfig(q))}normalize(C){return this.normalizers.reduce((q,ue)=>ue.normalize(q),C)}}class Ke extends Ee{_tokenize_chinese_chars(C){const q=[];for(let ue=0;uethis.pre_tokenize_text(ue,q)):this.pre_tokenize_text(C,q)).flat()}_call(C,q){return this.pre_tokenize(C,q)}}class le extends je{constructor(C){super(),this.pattern=new RegExp(`[^\\s${w}]+|[${w}]`,"gu")}pre_tokenize_text(C,q){return C.trim().match(this.pattern)||[]}}class Te extends je{constructor(C){super(),this.config=C,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=xe,this.text_encoder=new TextEncoder}pre_tokenize_text(C,q){return this.add_prefix_space&&!C.startsWith(" ")&&(C=" "+C),(this.use_regex?C.match(this.pattern)||[]:[C]).map(be=>Array.from(this.text_encoder.encode(be),Se=>this.byte_encoder[Se]).join(""))}}class Ue extends je{constructor(C){super(),this.config=C,this.pattern=I(this.config.pattern,this.config.invert)}pre_tokenize_text(C,q){var ue;return this.pattern===null?[]:this.config.invert?C.match(this.pattern)||[]:((ue=this.config.behavior)==null?void 0:ue.toLowerCase())==="removed"?C.split(this.pattern).filter(be=>be):b(C,this.pattern)}}class Ve extends je{constructor(C){super(),this.config=C,this.pattern=new RegExp(`[^${w}]+|[${w}]+`,"gu")}pre_tokenize_text(C,q){return C.match(this.pattern)||[]}}class Ne extends je{constructor(C){super(),this.config=C;const q=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(q,"gu")}pre_tokenize_text(C,q){return C.match(this.pattern)||[]}}class Re extends _.Callable{constructor(C){super(),this.config=C}static fromConfig(C){if(C===null)return null;switch(C.type){case"TemplateProcessing":return new ct(C);case"ByteLevel":return new lt(C);case"RobertaProcessing":return new dt(C);case"BertProcessing":return new st(C);case"Sequence":return new ht(C);default:throw new Error(`Unknown PostProcessor type: ${C.type}`)}}post_process(C,...q){throw Error("post_process should be implemented in subclass.")}_call(C,...q){return this.post_process(C,...q)}}class st extends Re{constructor(C){super(C),this.cls=C.cls[0],this.sep=C.sep[0]}post_process(C,q=null,{add_special_tokens:ue=!0}={}){ue&&(C=(0,D.mergeArrays)([this.cls],C,[this.sep]));let be=new Array(C.length).fill(0);if(q!==null){const Se=ue&&this instanceof dt?[this.sep]:[],Qe=ue?[this.sep]:[];C=(0,D.mergeArrays)(C,Se,q,Qe),be=(0,D.mergeArrays)(be,new Array(q.length+Se.length+Qe.length).fill(1))}return{tokens:C,token_type_ids:be}}}class dt extends st{}class ct extends Re{constructor(C){super(C),this.single=C.single,this.pair=C.pair}post_process(C,q=null,{add_special_tokens:ue=!0}={}){const be=q===null?this.single:this.pair;let Se=[],Qe=[];for(const pt of be)"SpecialToken"in pt?ue&&(Se.push(pt.SpecialToken.id),Qe.push(pt.SpecialToken.type_id)):"Sequence"in pt&&(pt.Sequence.id==="A"?(Se=(0,D.mergeArrays)(Se,C),Qe=(0,D.mergeArrays)(Qe,new Array(C.length).fill(pt.Sequence.type_id))):pt.Sequence.id==="B"&&(Se=(0,D.mergeArrays)(Se,q),Qe=(0,D.mergeArrays)(Qe,new Array(q.length).fill(pt.Sequence.type_id))));return{tokens:Se,token_type_ids:Qe}}}class lt extends Re{post_process(C,q=null){return q&&(C=(0,D.mergeArrays)(C,q)),{tokens:C}}}class ht extends Re{constructor(C){super(C),this.processors=C.processors.map(q=>Re.fromConfig(q))}post_process(C,q=null,ue={}){let be;for(const Se of this.processors)if(Se instanceof lt)C=Se.post_process(C).tokens,q&&(q=Se.post_process(q).tokens);else{const Qe=Se.post_process(C,q,ue);C=Qe.tokens,be=Qe.token_type_ids}return{tokens:C,token_type_ids:be}}}class L extends _.Callable{constructor(C){super(),this.config=C,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=C.trim_offsets}static fromConfig(C){if(C===null)return null;switch(C.type){case"WordPiece":return new We(C);case"Metaspace":return new is(C);case"ByteLevel":return new Je(C);case"Replace":return new oe(C);case"ByteFallback":return new H(C);case"Fuse":return new me(C);case"Strip":return new $e(C);case"Sequence":return new mt(C);case"CTC":return new ut(C);case"BPEDecoder":return new vt(C);default:throw new Error(`Unknown Decoder type: ${C.type}`)}}_call(C){return this.decode(C)}decode(C){return this.decode_chain(C).join("")}decode_chain(C){throw Error("`decode_chain` should be implemented in subclass.")}}class oe extends L{decode_chain(C){const q=I(this.config.pattern);return q===null?C:C.map(ue=>ue.replaceAll(q,this.config.content))}}class H extends L{constructor(C){super(C),this.text_decoder=new TextDecoder}decode_chain(C){const q=[];let ue=[];for(const be of C){let Se=null;if(be.length===6&&be.startsWith("<0x")&&be.endsWith(">")){const Qe=parseInt(be.slice(3,5),16);isNaN(Qe)||(Se=Qe)}if(Se!==null)ue.push(Se);else{if(ue.length>0){const Qe=this.text_decoder.decode(Uint8Array.from(ue));q.push(Qe),ue=[]}q.push(be)}}if(ue.length>0){const be=this.text_decoder.decode(Uint8Array.from(ue));q.push(be),ue=[]}return q}}class me extends L{decode_chain(C){return[C.join("")]}}class $e extends L{constructor(C){super(C),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(C){return C.map(q=>{let ue=0;for(let Se=0;Se(ue!==0&&(q.startsWith(this.config.prefix)?q=q.replace(this.config.prefix,""):q=" "+q),this.cleanup&&(q=ne(q)),q))}}class Je extends L{constructor(C){super(C),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(C){const q=C.join(""),ue=new Uint8Array([...q].map(Se=>this.byte_decoder[Se]));return this.text_decoder.decode(ue)}decode_chain(C){const q=[];let ue=[];for(const be of C)this.added_tokens.find(Se=>Se.content===be)!==void 0?(ue.length>0&&(q.push(this.convert_tokens_to_string(ue)),ue=[]),q.push(be)):ue.push(be);return ue.length>0&&q.push(this.convert_tokens_to_string(ue)),q}}class ut extends L{constructor(C){super(C),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(C){if(C.length===0)return"";const q=[C[0]];for(let Se=1;SeSe!==this.pad_token).join("");return this.cleanup&&(be=ne(be).replaceAll(this.word_delimiter_token," ").trim()),be}decode_chain(C){return[this.convert_tokens_to_string(C)]}}class mt extends L{constructor(C){super(C),this.decoders=C.decoders.map(q=>L.fromConfig(q))}decode_chain(C){return this.decoders.reduce((q,ue)=>ue.decode_chain(q),C)}}class vt extends L{constructor(C){super(C),this.suffix=this.config.suffix}decode_chain(C){return C.map((q,ue)=>q.replaceAll(this.suffix,ue===C.length-1?"":" "))}}class kt extends L{decode_chain(C){let q="";for(let ue=1;ueue.normalize("NFKC")).join("~"):C=C.normalize("NFKC"),C}}class ks extends je{constructor(C){super(),this.tokenizers=C.pretokenizers.map(q=>je.fromConfig(q))}pre_tokenize_text(C,q){return this.tokenizers.reduce((ue,be)=>be.pre_tokenize(ue,q),[C])}}class Ds extends je{constructor(C){super()}pre_tokenize_text(C,q){return C.match(/\w+|[^\w\s]+/g)||[]}}class sr extends je{constructor(C){super()}pre_tokenize_text(C,q){return S(C)}}class Sr extends je{constructor(C){super(),this.config=C,this.pattern=I(this.config.pattern),this.content=this.config.content}pre_tokenize_text(C,q){return this.pattern===null?[C]:[C.replaceAll(this.pattern,this.config.content)]}}const Yr=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Us(Pe,C,q,ue){for(const be of Object.keys(Pe)){const Se=C-Pe[be].length,Qe=q(be),pt=new Array(Se).fill(Qe);Pe[be]=ue==="right"?(0,D.mergeArrays)(Pe[be],pt):(0,D.mergeArrays)(pt,Pe[be])}}function Tr(Pe,C){for(const q of Object.keys(Pe))Pe[q].length=C}class Nt extends _.Callable{constructor(q,ue){super();fe(this,"return_token_type_ids",!1);fe(this,"padding_side","right");this._tokenizer_config=ue,this.normalizer=Ee.fromConfig(q.normalizer),this.pre_tokenizer=je.fromConfig(q.pre_tokenizer),this.model=ve.fromConfig(q.model,ue),this.post_processor=Re.fromConfig(q.post_processor),this.decoder=L.fromConfig(q.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const be of q.added_tokens){const Se=new ie(be);this.added_tokens.push(Se),this.model.tokens_to_ids.set(Se.content,Se.id),this.model.vocab[Se.id]=Se.content,Se.special&&(this.special_tokens.push(Se.content),this.all_special_ids.push(Se.id))}if(this.additional_special_tokens=ue.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.slice().sort((be,Se)=>Se.content.length-be.content.length).map(be=>`${be.lstrip?"\\s*":""}(${(0,D.escapeRegExp)(be.content)})${be.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.bos_token=this.getToken("bos_token"),this.bos_token_id=this.model.tokens_to_ids.get(this.bos_token),this.eos_token=this.getToken("eos_token"),this.eos_token_id=this.model.tokens_to_ids.get(this.eos_token),this.model_max_length=ue.model_max_length,this.remove_space=ue.remove_space,this.clean_up_tokenization_spaces=ue.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=ue.do_lowercase_and_remove_accent??!1,ue.padding_side&&(this.padding_side=ue.padding_side),this.legacy=!1,this.chat_template=ue.chat_template??null,Array.isArray(this.chat_template)){const be=Object.create(null);for(const{name:Se,template:Qe}of this.chat_template){if(typeof Se!="string"||typeof Qe!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');be[Se]=Qe}this.chat_template=be}this._compiled_template_cache=new Map}getToken(...q){for(const ue of q){const be=this._tokenizer_config[ue];if(be)if(typeof be=="object"){if(be.__type==="AddedToken")return be.content;throw Error(`Unknown token: ${be}`)}else return be}return null}static async from_pretrained(q,{progress_callback:ue=null,config:be=null,cache_dir:Se=null,local_files_only:Qe=!1,revision:pt="main",legacy:gt=null}={}){const ft=await M(q,{progress_callback:ue,config:be,cache_dir:Se,local_files_only:Qe,revision:pt,legacy:gt});return new this(...ft)}_call(q,{text_pair:ue=null,add_special_tokens:be=!0,padding:Se=!1,truncation:Qe=null,max_length:pt=null,return_tensor:gt=!0,return_token_type_ids:ft=null}={}){const xt=Array.isArray(q);let Kt;if(xt){if(q.length===0)throw Error("text array must be non-empty");if(ue!==null){if(Array.isArray(ue)){if(q.length!==ue.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Kt=q.map((us,Fs)=>this._encode_plus(us,{text_pair:ue[Fs],add_special_tokens:be,return_token_type_ids:ft}))}else Kt=q.map(us=>this._encode_plus(us,{add_special_tokens:be,return_token_type_ids:ft}))}else{if(q==null)throw Error("text may not be null or undefined");if(Array.isArray(ue))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Kt=[this._encode_plus(q,{text_pair:ue,add_special_tokens:be,return_token_type_ids:ft})]}if(pt===null?Se==="max_length"?pt=this.model_max_length:pt=(0,Y.max)(Kt.map(us=>us.input_ids.length))[0]:Qe||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),Se||Qe)for(let us=0;uspt?Qe&&Tr(Kt[us],pt):Se&&Us(Kt[us],pt,Fs=>Fs==="input_ids"?this.pad_token_id:0,this.padding_side));const hs={};if(gt){if(!(Se&&Qe)&&Kt.some(Fs=>{var Bt;for(const rs of Object.keys(Fs))if(Fs[rs].length!==((Bt=Kt[0][rs])==null?void 0:Bt.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 us=[Kt.length,Kt[0].input_ids.length];for(const Fs of Object.keys(Kt[0]))hs[Fs]=new N.Tensor("int64",BigInt64Array.from(Kt.flatMap(Bt=>Bt[Fs]).map(BigInt)),us)}else{for(const us of Object.keys(Kt[0]))hs[us]=Kt.map(Fs=>Fs[us]);if(!xt)for(const us of Object.keys(hs))hs[us]=hs[us][0]}return hs}_encode_text(q){return q===null?null:(this.added_tokens_regex?q.split(this.added_tokens_regex).filter(Se=>Se):[q]).map((Se,Qe)=>{if(this.added_tokens.find(gt=>gt.content===Se)!==void 0)return Se;{if(this.remove_space===!0&&(Se=Se.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(Se=U(Se)),this.normalizer!==null&&(Se=this.normalizer(Se)),Se.length===0)return[];const gt=this.pre_tokenizer!==null?this.pre_tokenizer(Se,{section_index:Qe}):[Se];return this.model(gt)}}).flat()}_encode_plus(q,{text_pair:ue=null,add_special_tokens:be=!0,return_token_type_ids:Se=null}={}){const{tokens:Qe,token_type_ids:pt}=this._tokenize_helper(q,{pair:ue,add_special_tokens:be}),gt=this.model.convert_tokens_to_ids(Qe),ft={input_ids:gt,attention_mask:new Array(gt.length).fill(1)};return(Se??this.return_token_type_ids)&&pt&&(ft.token_type_ids=pt),ft}_tokenize_helper(q,{pair:ue=null,add_special_tokens:be=!1}={}){const Se=this._encode_text(q),Qe=this._encode_text(ue);return this.post_processor?this.post_processor(Se,Qe,{add_special_tokens:be}):{tokens:(0,D.mergeArrays)(Se??[],Qe??[])}}tokenize(q,{pair:ue=null,add_special_tokens:be=!1}={}){return this._tokenize_helper(q,{pair:ue,add_special_tokens:be}).tokens}encode(q,{text_pair:ue=null,add_special_tokens:be=!0,return_token_type_ids:Se=null}={}){return this._encode_plus(q,{text_pair:ue,add_special_tokens:be,return_token_type_ids:Se}).input_ids}batch_decode(q,ue={}){return q instanceof N.Tensor&&(q=q.tolist()),q.map(be=>this.decode(be,ue))}decode(q,ue={}){if(q instanceof N.Tensor&&(q=te(q)),!Array.isArray(q)||q.length===0||!(0,D.isIntegralNumber)(q[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(q,ue)}decode_single(q,{skip_special_tokens:ue=!1,clean_up_tokenization_spaces:be=null}){let Se=this.model.convert_ids_to_tokens(q);ue&&(Se=Se.filter(pt=>!this.special_tokens.includes(pt)));let Qe=this.decoder?this.decoder(Se):Se.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Qe=Qe.replaceAll(this.decoder.end_of_word_suffix," "),ue&&(Qe=Qe.trim())),(be??this.clean_up_tokenization_spaces)&&(Qe=ne(Qe)),Qe}get_chat_template({chat_template:q=null,tools:ue=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const be=this.chat_template;if(q!==null&&Object.hasOwn(be,q))q=be[q];else if(q===null)if(ue!==null&&"tool_use"in be)q=be.tool_use;else if("default"in be)q=be.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(be).sort()}.`)}else if(q===null)if(this.chat_template)q=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return q}apply_chat_template(q,{tools:ue=null,documents:be=null,chat_template:Se=null,add_generation_prompt:Qe=!1,tokenize:pt=!0,padding:gt=!1,truncation:ft=!1,max_length:xt=null,return_tensor:Kt=!0,return_dict:hs=!1,tokenizer_kwargs:us={},...Fs}={}){if(Se=this.get_chat_template({chat_template:Se,tools:ue}),typeof Se!="string")throw Error(`chat_template must be a string, but got ${typeof Se}`);let Bt=this._compiled_template_cache.get(Se);Bt===void 0&&(Bt=new v.Template(Se),this._compiled_template_cache.set(Se,Bt));const rs=Object.create(null);for(const Ws of Yr){const Le=this.getToken(Ws);Le&&(rs[Ws]=Le)}const rr=Bt.render({messages:q,add_generation_prompt:Qe,tools:ue,documents:be,...rs,...Fs});if(pt){const Ws=this._call(rr,{add_special_tokens:!1,padding:gt,truncation:ft,max_length:xt,return_tensor:Kt,...us});return hs?Ws:Ws.input_ids}return rr}}class Jr extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class $r extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class Ar extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class Zr extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class pr extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class en extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class Ir extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class Rr extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class Nr extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class or extends Nt{}class it extends Nt{}class Tt extends Nt{constructor(q,ue){super(q,ue);fe(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class Dt extends Nt{constructor(){super(...arguments);fe(this,"return_token_type_ids",!0)}}class Vs extends Nt{}class jr extends Nt{}class Or extends Nt{}class Ms extends Nt{constructor(C,q){super(C,q),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(ue=>this.languageRegex.test(ue)),this.lang_to_token=ue=>ue}_build_translation_inputs(C,q,ue){return _r(this,C,q,ue)}}class ar extends Ms{}class Is extends Nt{}class Pr extends Nt{}const ts="▁";class _n extends Nt{constructor(q,ue){super(q,ue);fe(this,"padding_side","left");this.legacy=ue.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new At({replacement:ts,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 ue=super._encode_text(ts+q.replaceAll(ts," "));return ue.length>1&&ue[0]===ts&&this.special_tokens.includes(ue[1])&&(ue=ue.slice(1)),ue}}class Ur extends Nt{}class si extends Nt{}class $n extends Nt{}class An extends Nt{}class In extends Nt{}class Vr extends Nt{}class On extends Nt{}class ri extends Nt{}class Wr extends Nt{}function _r(Pe,C,q,ue){if(!("language_codes"in Pe)||!Array.isArray(Pe.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in Pe)||!(Pe.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in Pe)||typeof Pe.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const be=ue.src_lang,Se=ue.tgt_lang;if(!Pe.language_codes.includes(Se))throw new Error(`Target language code "${Se}" is not valid. Must be one of: {${Pe.language_codes.join(", ")}}`);if(be!==void 0){if(!Pe.language_codes.includes(be))throw new Error(`Source language code "${be}" is not valid. Must be one of: {${Pe.language_codes.join(", ")}}`);for(const Qe of Pe.post_processor.config.single)if("SpecialToken"in Qe&&Pe.languageRegex.test(Qe.SpecialToken.id)){Qe.SpecialToken.id=Pe.lang_to_token(be);break}}return ue.forced_bos_token_id=Pe.model.convert_tokens_to_ids([Pe.lang_to_token(Se)])[0],Pe._call(C,q)}class lr extends Nt{constructor(C,q){super(C,q),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(ue=>this.languageRegex.test(ue)),this.lang_to_token=ue=>ue}_build_translation_inputs(C,q,ue){return _r(this,C,q,ue)}}class gn extends Nt{constructor(C,q){super(C,q),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(ue=>this.languageRegex.test(ue)).map(ue=>ue.slice(2,-2)),this.lang_to_token=ue=>`__${ue}__`}_build_translation_inputs(C,q,ue){return _r(this,C,q,ue)}}class tn extends Nt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(C,{return_timestamps:q=!1,return_language:ue=!1,time_precision:be=null,force_full_sequences:Se=!0}={}){if(be===null)throw Error("Must specify time_precision");let Qe=null;const pt=q==="word";function gt(){return{language:Qe,timestamp:[null,null],text:""}}const ft=[];let xt=gt(),Kt=0;const hs=this.timestamp_begin,Fs=hs+1500;let Bt=[],rs=[],rr=!1,Ws=null;const Le=new Set(this.all_special_ids);for(const Ss of C){const qs=Ss.tokens,Ot=pt?Ss.token_timestamps:null;let nr=null,gr=hs;if("stride"in Ss){const[yt,qt,Ls]=Ss.stride;if(Kt-=qt,Ws=yt-Ls,qt&&(gr=qt/be+hs),Ls)for(let As=qs.length-1;As>=0;--As){const Gs=Number(qs[As]);if(Gs>=hs){if(nr!==null&&(Gs-hs)*be=hs&&qt<=Fs){const Ls=(qt-hs)*be+Kt,As=(0,Y.round)(Ls,2);if(nr!==null&&qt>=nr)rr=!0;else if(rr||Bt.length>0&&qt0?(Bt.push(ms),pt&&rs.push($s)):Bt.every(yt=>yt.length===0)&&(xt=gt(),Bt=[],ms=[],rs=[],$s=[])}if(Bt.length>0){if(Se&&q)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[Ss,qs]=this.findLongestCommonSequence(Bt,rs),Ot=this.decode(Ss);xt.text=Ot,pt&&(xt.words=this.collateWordTimestamps(Ss,qs,Qe)),ft.push(xt)}let Js=Object.create(null);const Fr=ft.map(Ss=>Ss.text).join("");if(q||ue){for(let Ss=0;Ss0;let pt=Qe?[]:null,gt=Qe?q[0]:null;for(let ft=1;ftqt===gr[Ls]&>[Fr+Ls]<=q[ft][Ot+Ls]).length:ms=qs.filter((qt,Ls)=>qt===gr[Ls]).length;const $s=Js/1e4,yt=ms/Js+$s;ms>1&&yt>Kt&&(Kt=yt,hs=[Fr,Ss,Ot,nr])}const[Fs,Bt,rs,rr]=hs,Ws=Math.floor((Bt+Fs)/2),Le=Math.floor((rr+rs)/2);Se.push(...ue.slice(0,Ws)),ue=xt.slice(Le),be=ue.length,Qe&&(pt.push(...gt.slice(0,Ws)),gt=q[ft].slice(Le))}return Se.push(...ue),Qe?(pt.push(...gt),[Se,pt]):[Se,[]]}collateWordTimestamps(C,q,ue){const[be,Se,Qe]=this.combineTokensIntoWords(C,ue),pt=[];for(let gt=0;gt=be){const pt=((Qe-be)*ue).toFixed(2);Se.push(`<|${pt}|>`),Se.push([])}else Se[Se.length-1].push(Qe);return Se=Se.map(Qe=>typeof Qe=="string"?Qe:super.decode(Qe,q)),Se.join("")}splitTokensOnUnicode(C){const q=this.decode(C,{decode_with_timestamps:!0}),ue="�",be=[],Se=[],Qe=[];let pt=[],gt=[],ft=0;for(let xt=0;xt=this.model.tokens_to_ids.get("<|endoftext|>"),Fs=xt.startsWith(" "),Bt=xt.trim(),rs=gt.test(Bt);if(us||Fs||rs||Se.length===0)Se.push(xt),Qe.push(Kt),pt.push(hs);else{const rr=Se.length-1;Se[rr]+=xt,Qe[rr].push(...Kt),pt[rr].push(...hs)}}return[Se,Qe,pt]}mergePunctuations(C,q,ue,be,Se){const Qe=structuredClone(C),pt=structuredClone(q),gt=structuredClone(ue);let ft=Qe.length-2,xt=Qe.length-1;for(;ft>=0;)Qe[ft].startsWith(" ")&&be.includes(Qe[ft].trim())?(Qe[xt]=Qe[ft]+Qe[xt],pt[xt]=(0,D.mergeArrays)(pt[ft],pt[xt]),gt[xt]=(0,D.mergeArrays)(gt[ft],gt[xt]),Qe[ft]="",pt[ft]=[],gt[ft]=[]):xt=ft,--ft;for(ft=0,xt=1;xtKt),pt.filter(Kt=>Kt.length>0),gt.filter(Kt=>Kt.length>0)]}}class wn extends Nt{}class yn extends Nt{}class Mn extends Nt{}class zt extends Nt{constructor(C,q){super(C,q),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(ue=>this.languageRegex.test(ue)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(C){if(C===null)return null;const[q,...ue]=C.trim().split(this.languageRegex);if(ue.length===0)return super._encode_text(q);if(ue.length===2){const[be,Se]=ue;return this.supported_language_codes.includes(be)||console.warn(`Unsupported language code "${be}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,D.mergeArrays)([be],super._encode_text(Se))}}}class bn extends Nt{}class Fn extends Nt{}class Dn extends Nt{}class Ln extends Nt{}class Gr extends Nt{}class zn extends Nt{constructor(C,q){super(C,q),this.decoder=new kt({})}}class vn extends Nt{}class Bn extends Nt{}class as{static async from_pretrained(C,{progress_callback:q=null,config:ue=null,cache_dir:be=null,local_files_only:Se=!1,revision:Qe="main",legacy:pt=null}={}){var hs;const[gt,ft]=await M(C,{progress_callback:q,config:ue,cache_dir:be,local_files_only:Se,revision:Qe,legacy:pt}),xt=((hs=ft.tokenizer_class)==null?void 0:hs.replace(/Fast$/,""))??"PreTrainedTokenizer";let Kt=this.TOKENIZER_CLASS_MAPPING[xt];return Kt||(console.warn(`Unknown tokenizer class "${xt}", attempting to construct from base class.`),Kt=Nt),new Kt(gt,ft)}}fe(as,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Vs,DistilBertTokenizer:or,CamembertTokenizer:it,DebertaTokenizer:pr,DebertaV2Tokenizer:en,BertTokenizer:Jr,HerbertTokenizer:Ir,ConvBertTokenizer:Rr,RoFormerTokenizer:Nr,XLMTokenizer:Tt,ElectraTokenizer:Dt,MobileBertTokenizer:Ar,SqueezeBertTokenizer:Zr,AlbertTokenizer:$r,GPT2Tokenizer:jr,BartTokenizer:Or,MBartTokenizer:Ms,MBart50Tokenizer:ar,RobertaTokenizer:Is,WhisperTokenizer:tn,CodeGenTokenizer:wn,CLIPTokenizer:yn,SiglipTokenizer:Mn,MarianTokenizer:zt,BloomTokenizer:Pr,NllbTokenizer:lr,M2M100Tokenizer:gn,LlamaTokenizer:_n,CodeLlamaTokenizer:Ur,XLMRobertaTokenizer:si,MPNetTokenizer:$n,FalconTokenizer:An,GPTNeoXTokenizer:In,EsmTokenizer:Vr,Wav2Vec2CTCTokenizer:bn,BlenderbotTokenizer:Fn,BlenderbotSmallTokenizer:Dn,SpeechT5Tokenizer:Ln,NougatTokenizer:Gr,VitsTokenizer:zn,Qwen2Tokenizer:On,GemmaTokenizer:ri,Grok1Tokenizer:Wr,CohereTokenizer:vn,MgpstrTokenizer:Bn,PreTrainedTokenizer:Nt})},"./src/utils/audio.js":(ze,A,r)=>{r.r(A),r.d(A,{RawAudio:()=>we,hamming:()=>b,hanning:()=>M,mel_filter_bank:()=>X,read_audio:()=>v,spectrogram:()=>O,window_function:()=>ae});var _=r("./src/utils/hub.js"),D=r("./src/utils/maths.js"),j=r("./src/utils/core.js"),Y=r("./src/env.js"),N=r("?7a2c"),g=r("./src/utils/tensor.js");async function v(re,xe){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 ce=await(await(0,_.getFile)(re)).arrayBuffer(),ke=new AudioContext({sampleRate:xe});typeof xe>"u"&&console.warn(`No sampling rate provided, using default of ${ke.sampleRate}Hz.`);const Ae=await ke.decodeAudioData(ce);let Ee;if(Ae.numberOfChannels===2){const tt=Math.sqrt(2),Ge=Ae.getChannelData(0),ye=Ae.getChannelData(1);Ee=new Float32Array(Ge.length);for(let J=0;J2595*Math.log10(1+re/700),kaldi:re=>1127*Math.log(1+re/700),slaney:(re,xe=1e3,ce=15,ke=27/Math.log(6.4))=>re>=xe?ce+Math.log(re/xe)*ke:3*re/200};function K(re,xe="htk"){const ce=I[xe];if(!ce)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof re=="number"?ce(re):re.map(ke=>ce(ke))}const te={htk:re=>700*(10**(re/2595)-1),kaldi:re=>700*(Math.exp(re/1127)-1),slaney:(re,xe=1e3,ce=15,ke=Math.log(6.4)/27)=>re>=ce?xe*Math.exp(ke*(re-ce)):200*re/3};function ne(re,xe="htk"){const ce=te[xe];if(!ce)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof re=="number"?ce(re):re.map(ke=>ce(ke))}function W(re,xe){const ce=Float64Array.from({length:xe.length-1},(tt,Ge)=>xe[Ge+1]-xe[Ge]),ke=Array.from({length:re.length},()=>new Array(xe.length));for(let tt=0;ttnew Array(re.length));for(let tt=0;ttre+ke*Ee)}function X(re,xe,ce,ke,Ae,Ee=null,tt="htk",Ge=!1){if(Ee!==null&&Ee!=="slaney")throw new Error('norm must be one of null or "slaney"');const ye=K(ce,tt),J=K(ke,tt),de=U(ye,J,xe+2);let Ce=ne(de,tt),Be;if(Ge){const se=Ae/(re*2);Be=K(Float64Array.from({length:re},(Ke,je)=>je*se),tt),Ce=de}else Be=U(0,Math.floor(Ae/2),re);const Ze=W(Be,Ce);if(Ee!==null&&Ee==="slaney")for(let se=0;seAe)throw Error(`frame_length (${ce}) may not be larger than fft_length (${Ae})`);if(Ne!==ce)throw new Error(`Length of the window (${Ne}) must equal frame_length (${ce})`);if(ke<=0)throw new Error("hop_length must be greater than zero");if(Ee===null&&de!==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(tt){if(Ge!=="reflect")throw new Error(`pad_mode="${Ge}" not implemented yet.`);const We=Math.floor((Ae-1)/2)+1;re=$(re,We,We)}let Re=Math.floor(1+Math.floor((re.length-ce)/ke));le!==null&&ReRe?Ue&&(ct=Te):ct=dt=Te);const lt=new D.FFT(Ae),ht=new Float64Array(Ae),L=new Float64Array(lt.outputBufferSize),oe=new Float32Array(st*ct);for(let We=0;We=1;--mt)ht[mt]-=J*ht[mt-1];ht[0]*=1-J}for(let mt=0;mtMath.pow(Ge,.85));break;default:throw new Error(`Unknown window type ${xe}.`)}if(ce&&(tt=tt.subarray(0,re)),ke===null)return tt;if(re>ke)throw new Error(`Length of the window (${re}) may not be larger than frame_length (${ke})`);return tt}function ie(re,xe){let ce=44;const ke=new ArrayBuffer(ce+re.length*4),Ae=new DataView(ke);ve(Ae,0,"RIFF"),Ae.setUint32(4,36+re.length*4,!0),ve(Ae,8,"WAVE"),ve(Ae,12,"fmt "),Ae.setUint32(16,16,!0),Ae.setUint16(20,3,!0),Ae.setUint16(22,1,!0),Ae.setUint32(24,xe,!0),Ae.setUint32(28,xe*4,!0),Ae.setUint16(32,4,!0),Ae.setUint16(34,32,!0),ve(Ae,36,"data"),Ae.setUint32(40,re.length*4,!0);for(let Ee=0;Ee{let Ee=await Ae.arrayBuffer();N.writeFileSync(ke,Buffer.from(Ee))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await ce(xe,this.toBlob())}}},"./src/utils/constants.js":(ze,A,r)=>{r.r(A),r.d(A,{CHAT_TEMPLATE_NAME:()=>g,CONFIG_NAME:()=>D,FEATURE_EXTRACTOR_NAME:()=>j,GENERATION_CONFIG_NAME:()=>v,GITHUB_ISSUE_URL:()=>_,IMAGE_PROCESSOR_NAME:()=>Y,PROCESSOR_NAME:()=>N});const _="https://github.com/huggingface/transformers.js/issues/new/choose",D="config.json",j="preprocessor_config.json",Y=j,N="processor_config.json",g="chat_template.json",v="generation_config.json"},"./src/utils/core.js":(ze,A,r)=>{r.r(A),r.d(A,{calculateDimensions:()=>v,calculateReflectOffset:()=>I,count:()=>W,dispatchCallback:()=>_,escapeRegExp:()=>j,isIntegralNumber:()=>N,isNullishDimension:()=>g,isTypedArray:()=>Y,len:()=>ne,mergeArrays:()=>M,pick:()=>te,pop:()=>y,product:()=>b,reverseDictionary:()=>D,saveBlob:()=>K});function _(U,X){U&&U(X)}function D(U){return Object.fromEntries(Object.entries(U).map(([X,$])=>[$,X]))}function j(U){return U.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Y(U){var X,$,S;return((S=($=(X=U==null?void 0:U.prototype)==null?void 0:X.__proto__)==null?void 0:$.constructor)==null?void 0:S.name)==="TypedArray"}function N(U){return Number.isInteger(U)||typeof U=="bigint"}function g(U){return U==null||U===-1}function v(U){const X=[];let $=U;for(;Array.isArray($);)X.push($.length),$=$[0];return X}function y(U,X,$=void 0){const S=U[X];if(S!==void 0)return delete U[X],S;if($===void 0)throw Error(`Key ${X} does not exist in object.`);return $}function M(...U){return Array.prototype.concat.apply([],U)}function b(...U){return U.reduce((X,$)=>X.flatMap(S=>$.map(w=>[S,w])))}function I(U,X){return Math.abs((U+X)%(2*X)-X)}function K(U,X){const $=URL.createObjectURL(X),S=document.createElement("a");S.href=$,S.download=U,S.click(),S.remove(),URL.revokeObjectURL($)}function te(U,X){return Object.assign({},...X.map($=>{if(U[$]!==void 0)return{[$]:U[$]}}))}function ne(U){let X=0;for(const $ of U)++X;return X}function W(U,X){let $=0;for(const S of U)S===X&&++$;return $}},"./src/utils/data-structures.js":(ze,A,r)=>{r.r(A),r.d(A,{CharTrie:()=>D,PriorityQueue:()=>_,TokenLattice:()=>Y});class _{constructor(v=(M,b)=>M>b,y=1/0){this._heap=[],this._comparator=v,this._maxSize=y}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...v){return this.extend(v)}extend(v){for(const y of v)if(this.size0&&this._swap(0,y),this._heap.pop(),this._siftDown(),v}replace(v){const y=this.peek();return this._heap[0]=v,this._siftDown(),y}_parent(v){return(v+1>>>1)-1}_left(v){return(v<<1)+1}_right(v){return v+1<<1}_greater(v,y){return this._comparator(this._heap[v],this._heap[y])}_swap(v,y){const M=this._heap[v];this._heap[v]=this._heap[y],this._heap[y]=M}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(v){for(;v>0&&this._greater(v,this._parent(v));)this._swap(v,this._parent(v)),v=this._parent(v)}_siftDown(){let v=0;for(;this._left(v)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const b=new N(this.bosTokenId,0,0,0,0),I=new N(this.eosTokenId,1,this.len,0,0);this.nodes.push(b.clone()),this.nodes.push(I.clone()),this.beginNodes[this.len].push(I),this.endNodes[0].push(b)}insert(v,y,M,b){const I=this.nodes.length,K=new N(b,I,v,y,M);this.beginNodes[v].push(K),this.endNodes[v+y].push(K),this.nodes.push(K)}viterbi(){const v=this.len;let y=0;for(;y<=v;){if(this.beginNodes[y].length==0)return[];for(let te of this.beginNodes[y]){te.prev=null;let ne=0,W=null;for(let U of this.endNodes[y]){const X=U.backtraceScore+te.score;(W===null||X>ne)&&(W=U.clone(),ne=X)}if(W!==null)te.prev=W,te.backtraceScore=ne;else return[]}++y}const M=[],I=this.beginNodes[v][0].prev;if(I===null)return[];let K=I.clone();for(;K.prev!==null;)M.push(K.clone()),K=K.clone().prev.clone();return M.reverse(),M}piece(v){return this.chars.slice(v.pos,v.pos+v.length).join("")}tokens(){return this.viterbi().map(y=>this.piece(y))}tokenIds(){return this.viterbi().map(y=>y.tokenId)}}class N{constructor(v,y,M,b,I){this.tokenId=v,this.nodeId=y,this.pos=M,this.length=b,this.score=I,this.prev=null,this.backtraceScore=0}clone(){const v=new N(this.tokenId,this.nodeId,this.pos,this.length,this.score);return v.prev=this.prev,v.backtraceScore=this.backtraceScore,v}}},"./src/utils/devices.js":(ze,A,r)=>{r.r(A),r.d(A,{DEVICE_TYPES:()=>_});const _=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":(ze,A,r)=>{r.r(A),r.d(A,{DATA_TYPES:()=>Y,DEFAULT_DEVICE_DTYPE_MAPPING:()=>N,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>g,isWebGpuFp16Supported:()=>j});var _=r("./src/env.js"),D=r("./src/utils/devices.js");const j=function(){let v;return async function(){if(v===void 0)if(!_.apis.IS_WEBGPU_AVAILABLE)v=!1;else try{v=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{v=!1}return v}}(),Y=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),N=Object.freeze({[D.DEVICE_TYPES.wasm]:Y.q8}),g=Object.freeze({[Y.fp32]:"",[Y.fp16]:"_fp16",[Y.int8]:"_int8",[Y.uint8]:"_uint8",[Y.q8]:"_quantized",[Y.q4]:"_q4",[Y.q4f16]:"_q4f16",[Y.bnb4]:"_bnb4"})},"./src/utils/generic.js":(ze,A,r)=>{r.r(A),r.d(A,{Callable:()=>_});const _=class{constructor(){let D=function(...j){return D._call(...j)};return Object.setPrototypeOf(D,new.target.prototype)}_call(...D){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(ze,A,r)=>{r.r(A),r.d(A,{getFile:()=>y,getModelFile:()=>te,getModelJSON:()=>ne});var _=r("?7a2c"),D=r("?a42a"),j=r("./src/env.js"),Y=r("./src/utils/core.js");const N={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 g{constructor($){if(this.filePath=$,this.headers=new Headers,this.exists=_.existsSync($),this.exists){this.status=200,this.statusText="OK";let S=_.statSync($);this.headers.set("content-length",S.size.toString()),this.updateContentType();let w=this;this.body=new ReadableStream({start(x){w.arrayBuffer().then(O=>{x.enqueue(new Uint8Array(O)),x.close()})}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const $=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",N[$]??"application/octet-stream")}clone(){let $=new g(this.filePath);return $.exists=this.exists,$.status=this.status,$.statusText=this.statusText,$.headers=new Headers(this.headers),$}async arrayBuffer(){return(await _.promises.readFile(this.filePath)).buffer}async blob(){const $=await _.promises.readFile(this.filePath);return new Blob([$],{type:this.headers.get("content-type")})}async text(){return await _.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function v(X,$=null,S=null){let w;try{w=new URL(X)}catch{return!1}return!($&&!$.includes(w.protocol)||S&&!S.includes(w.hostname))}async function y(X){var $;if(j.env.useFS&&!v(X,["http:","https:","blob:"]))return new g(X);if(typeof process<"u"&&(($=process==null?void 0:process.release)==null?void 0:$.name)==="node"){const S=!!(cr!=null&&cr.TESTING_REMOTELY),w=j.env.version,x=new Headers;if(x.set("User-Agent",`transformers.js/${w}; is_ci/${S};`),v(X,["http:","https:"],["huggingface.co","hf.co"])){const ae=(cr==null?void 0:cr.HF_TOKEN)??(cr==null?void 0:cr.HF_ACCESS_TOKEN);ae&&x.set("Authorization",`Bearer ${ae}`)}return fetch(X,{headers:x})}else return fetch(X)}const M={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 b(X,$,S){if(!S)return null;const w=M[X]??`Error (${X}) occurred while trying to load file`;throw Error(`${w}: "${$}".`)}class I{constructor($){this.path=$}async match($){let S=D.join(this.path,$),w=new g(S);if(w.exists)return w}async put($,S){const w=Buffer.from(await S.arrayBuffer());let x=D.join(this.path,$);try{await _.promises.mkdir(D.dirname(x),{recursive:!0}),await _.promises.writeFile(x,w)}catch(O){console.warn("An error occurred while writing the file to cache:",O)}}}async function K(X,...$){for(let S of $)try{let w=await X.match(S);if(w)return w}catch{continue}}async function te(X,$,S=!0,w={}){if(!j.env.allowLocalModels){if(w.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(!j.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,Y.dispatchCallback)(w.progress_callback,{status:"initiate",name:X,file:$});let x;if(!x&&j.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{x=await caches.open("transformers-cache")}catch(tt){console.warn("An error occurred while opening the browser cache:",tt)}}if(!x&&j.env.useFSCache&&(x=new I(w.cache_dir??j.env.cacheDir)),!x&&j.env.useCustomCache){if(!j.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!j.env.customCache.match||!j.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");x=j.env.customCache}const O=w.revision??"main";let ae=U(X,$),ie=U(j.env.localModelPath,ae),ve=U(j.env.remoteHost,j.env.remotePathTemplate.replaceAll("{model}",X).replaceAll("{revision}",encodeURIComponent(O)),$),we=O==="main"?ae:U(X,O,$),re,xe=x instanceof I?we:ve,ce=!1,ke;x&&(ke=await K(x,ie,xe));const Ae=ke!==void 0;if(ke===void 0){if(j.env.allowLocalModels)if(v(ae,["http:","https:"])){if(w.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${ae}.`);if(!j.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${ae}.`)}else try{ke=await y(ie),re=ie}catch(Ge){console.warn(`Unable to load from local path "${ie}": "${Ge}"`)}if(ke===void 0||ke.status===404){if(w.local_files_only||!j.env.allowRemoteModels){if(S)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${ie}".`);return null}if(ke=await y(ve),ke.status!==200)return b(ke.status,ve,S);re=xe}ce=x&&typeof Response<"u"&&ke instanceof Response&&ke.status===200}(0,Y.dispatchCallback)(w.progress_callback,{status:"download",name:X,file:$});let Ee;return w.progress_callback?Ae&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(Ee=new Uint8Array(await ke.arrayBuffer()),(0,Y.dispatchCallback)(w.progress_callback,{status:"progress",name:X,file:$,progress:100,loaded:Ee.length,total:Ee.length})):Ee=await W(ke,tt=>{(0,Y.dispatchCallback)(w.progress_callback,{status:"progress",name:X,file:$,...tt})}):Ee=new Uint8Array(await ke.arrayBuffer()),ce&&re&&await x.match(re)===void 0&&await x.put(re,new Response(Ee,{headers:ke.headers})).catch(tt=>{console.warn(`Unable to add response to browser cache: ${tt}.`)}),(0,Y.dispatchCallback)(w.progress_callback,{status:"done",name:X,file:$}),Ee}async function ne(X,$,S=!0,w={}){let x=await te(X,$,S,w);if(x===null)return{};let ae=new TextDecoder("utf-8").decode(x);return JSON.parse(ae)}async function W(X,$){const S=X.headers.get("Content-Length");S===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let w=parseInt(S??"0"),x=new Uint8Array(w),O=0;const ae=X.body.getReader();async function ie(){const{done:ve,value:we}=await ae.read();if(ve)return;let re=O+we.length;if(re>w){w=re;let ce=new Uint8Array(w);ce.set(x),x=ce}x.set(we,O),O=re;const xe=O/w*100;return $({progress:xe,loaded:O,total:w}),ie()}return await ie(),x}function U(...X){return X=X.map(($,S)=>(S&&($=$.replace(new RegExp("^/"),"")),S!==X.length-1&&($=$.replace(new RegExp("/$"),"")),$)),X.join("/")}},"./src/utils/image.js":(ze,A,r)=>{r.r(A),r.d(A,{RawImage:()=>K,load_image:()=>te});var _=r("./src/utils/core.js"),D=r("./src/utils/hub.js"),j=r("./src/env.js"),Y=r("./src/utils/tensor.js"),N=r("?2b25");let g,v,y;const M=j.apis.IS_BROWSER_ENV||j.apis.IS_WEBWORKER_ENV;if(M)g=(ne,W)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ne,W)},y=self.createImageBitmap,v=self.ImageData;else if(N)y=async ne=>{const U=(await ne.metadata()).channels,{data:X,info:$}=await ne.rotate().raw().toBuffer({resolveWithObject:!0}),S=new K(new Uint8ClampedArray(X),$.width,$.height,$.channels);return U!==void 0&&U!==$.channels&&S.convert(U),S};else throw new Error("Unable to load image processing library.");const b={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},I=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class K{constructor(W,U,X,$){this.data=W,this.width=U,this.height=X,this.channels=$}get size(){return[this.width,this.height]}static async read(W){if(W instanceof K)return W;if(typeof W=="string"||W instanceof URL)return await this.fromURL(W);throw new Error(`Unsupported input type: ${typeof W}`)}static fromCanvas(W){if(!M)throw new Error("fromCanvas() is only supported in browser environments.");const X=W.getContext("2d").getImageData(0,0,W.width,W.height).data;return new K(X,W.width,W.height,4)}static async fromURL(W){const U=await(0,D.getFile)(W);if(U.status!==200)throw new Error(`Unable to read image from "${W}" (${U.status} ${U.statusText})`);const X=await U.blob();return this.fromBlob(X)}static async fromBlob(W){if(M){const U=await y(W),X=g(U.width,U.height).getContext("2d");return X.drawImage(U,0,0),new this(X.getImageData(0,0,U.width,U.height).data,U.width,U.height,4)}else{const U=N(await W.arrayBuffer());return await y(U)}}static fromTensor(W,U="CHW"){if(W.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${W.dims.length} dimensions.`);if(U==="CHW")W=W.transpose(1,2,0);else if(U!=="HWC")throw new Error(`Unsupported channel format: ${U}`);if(!(W.data instanceof Uint8ClampedArray||W.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${W.type}`);switch(W.dims[2]){case 1:case 2:case 3:case 4:return new K(W.data,W.dims[1],W.dims[0],W.dims[2]);default:throw new Error(`Unsupported number of channels: ${W.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const W=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let U=0,X=0;U=0?O=X:ie=-X,$>=0?ae=$:ve=-$,x.drawImage(w,O,ae,W,U,ie,ve,W,U),new K(x.getImageData(0,0,W,U).data,W,U,4).convert(S)}else{let S=this.toSharp();if(X>=0&&$>=0)S=S.extract({left:Math.floor(X),top:Math.floor($),width:W,height:U});else if(X<=0&&$<=0){const w=Math.floor(-$),x=Math.floor(-X);S=S.extend({top:w,left:x,right:W-this.width-x,bottom:U-this.height-w})}else{let w=[0,0],x=0;$<0?(w[0]=Math.floor(-$),w[1]=U-this.height-w[0]):x=Math.floor($);let O=[0,0],ae=0;X<0?(O[0]=Math.floor(-X),O[1]=W-this.width-O[0]):ae=Math.floor(X),S=S.extend({top:w[0],bottom:w[1],left:O[0],right:O[1]}).extract({left:ae,top:x,width:W,height:U})}return await y(S)}}async toBlob(W="image/png",U=1){if(!M)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:W,quality:U})}toTensor(W="CHW"){let U=new Y.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(W!=="HWC")if(W==="CHW")U=U.permute(2,0,1);else throw new Error(`Unsupported channel format: ${W}`);return U}toCanvas(){if(!M)throw new Error("toCanvas() is only supported in browser environments.");const W=this.clone().rgba(),U=g(W.width,W.height),X=new v(W.data,W.width,W.height);return U.getContext("2d").putImageData(X,0,0),U}split(){const{data:W,width:U,height:X,channels:$}=this,S=W.constructor,w=W.length/$,x=Array.from({length:$},()=>new S(w));for(let O=0;Onew K(O,U,X,1))}_update(W,U,X,$=null){return this.data=W,this.width=U,this.height=X,$!==null&&(this.channels=$),this}clone(){return new K(this.data.slice(),this.width,this.height,this.channels)}convert(W){if(this.channels===W)return this;switch(W){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(W){if(M){if(j.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const U=W.split(".").pop().toLowerCase(),X=I.get(U)??"image/png",$=await this.toBlob(X);(0,_.saveBlob)(W,$)}else{if(j.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(W);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(M)throw new Error("toSharp() is only supported in server-side environments.");return N(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const te=K.read.bind(K)},"./src/utils/maths.js":(ze,A,r)=>{r.r(A),r.d(A,{FFT:()=>te,bankers_round:()=>U,cos_sim:()=>g,dot:()=>N,dynamic_time_warping:()=>X,interpolate_data:()=>_,log_softmax:()=>Y,magnitude:()=>v,max:()=>M,medianFilter:()=>ne,min:()=>y,permute_data:()=>D,round:()=>W,softmax:()=>j});function _($,[S,w,x],[O,ae],ie="bilinear",ve=!1){const we=ae/x,re=O/w,xe=new $.constructor(O*ae*S),ce=w*x,ke=O*ae;for(let Ae=0;Ae=0;--ve)O[ve]=we,x[ve]=S[w[ve]],we*=x[ve];const ae=w.map((ve,we)=>O[w.indexOf(we)]),ie=new $.constructor($.length);for(let ve=0;ve<$.length;++ve){let we=0;for(let re=S.length-1,xe=ve;re>=0;--re)we+=xe%S[re]*ae[re],xe=Math.floor(xe/S[re]);ie[we]=$[ve]}return[ie,x]}function j($){const S=M($)[0],w=$.map(ae=>Math.exp(ae-S)),x=w.reduce((ae,ie)=>ae+ie,0);return w.map(ae=>ae/x)}function Y($){const S=M($)[0];let w=0;for(let ae=0;ae<$.length;++ae)w+=Math.exp($[ae]-S);const x=Math.log(w);return $.map(ae=>ae-S-x)}function N($,S){let w=0;for(let x=0;x<$.length;++x)w+=$[x]*S[x];return w}function g($,S){const w=N($,S),x=v($),O=v(S);return w/(x*O)}function v($){return Math.sqrt($.reduce((S,w)=>S+w*w,0))}function y($){if($.length===0)throw Error("Array must not be empty");let S=$[0],w=0;for(let x=1;x<$.length;++x)$[x]S&&(S=$[x],w=x);return[S,w]}function b($){return $>0&&($&$-1)===0}class I{constructor(S){if(this.size=S|0,this.size<=1||!b(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=S<<1,this.table=new Float64Array(this.size*2);for(let x=0;xx;x<<=1)++w;this._width=w%2===0?w-1:w,this._bitrev=new Int32Array(1<>>O&3)<>>1);for(let O=0;O>>1]=S[O];return x}toComplexArray(S,w){const x=w||this.createComplexArray();for(let O=0;O>>1],x[O+1]=0;return x}transform(S,w){if(S===w)throw new Error("Input and output buffers must be different");this._transform4(S,w,1)}realTransform(S,w){if(S===w)throw new Error("Input and output buffers must be different");this._realTransform4(S,w,1)}inverseTransform(S,w){if(S===w)throw new Error("Input and output buffers must be different");this._transform4(S,w,-1);for(let x=0;x>=2;ie>=2;ie>>=2){ve=O/ie<<1;const ke=ve>>>2;for(we=0;we>>1,ie>>>1)}else for(we=0,re=0;we>>1,ie>>>1,x)}const ce=this.table;for(ie>>=2;ie>=2;ie>>=2){ve=O/ie<<1;const Ae=ve>>>1,Ee=Ae>>>1,tt=Ee>>>1;for(we=0;we>>1;for(let Ae=2;Ae>1;++xe){const ce=(xe+1-S)**2/2,ke=Math.sqrt(we**2+re**2)**ce,Ae=ce*Math.atan2(re,we),Ee=2*xe;ae[Ee]=ke*Math.cos(Ae),ae[Ee+1]=ke*Math.sin(Ae),ie[Ee]=ae[Ee],ie[Ee+1]=-ae[Ee+1]}this._slicedChirpBuffer=ae.subarray(w,x),this._f=new I(O>>1),this._f.transform(this._chirpBuffer,ie)}_transform(S,w,x){const O=this._buffer1,ae=this._buffer2,ie=this._outBuffer1,ve=this._outBuffer2,we=this._chirpBuffer,re=this._slicedChirpBuffer,xe=this._a;if(x)for(let ce=0;ce>1,Ee=w[Ae];O[ce]=Ee*re[ce],O[ke]=Ee*re[ke]}else for(let ce=0;ce=$.length&&(we=2*($.length-1)-we),x[ie++]=$[we]}x.sort(),w[ae]=x[O]}return w}function W($,S){const w=Math.pow(10,S);return Math.round($*w)/w}function U($){const S=Math.round($);return Math.abs($)%1===.5?S%2===0?S:S-1:S}function X($){const S=$.length,w=$[0].length,x=[S+1,w+1],O=Array.from({length:x[0]},()=>Array(x[1]).fill(1/0));O[0][0]=0;const ae=Array.from({length:x[0]},()=>Array(x[1]).fill(-1));for(let xe=1;xe0||ve>0;)switch(we.push(ie-1),re.push(ve-1),ae[ie][ve]){case 0:--ie,--ve;break;case 1:--ie;break;case 2:--ve;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${ie}, ${ve}]. Please file a bug report.`)}return we.reverse(),re.reverse(),[we,re]}},"./src/utils/tensor.js":(ze,A,r)=>{r.r(A),r.d(A,{Tensor:()=>N,cat:()=>w,full:()=>re,full_like:()=>xe,interpolate:()=>y,interpolate_4d:()=>M,layer_norm:()=>U,matmul:()=>b,mean:()=>ie,mean_pooling:()=>W,ones:()=>ce,ones_like:()=>ke,permute:()=>v,quantize_embeddings:()=>Ge,rand:()=>tt,rfft:()=>I,slice:()=>ne,stack:()=>x,std_mean:()=>ae,topk:()=>K,zeros:()=>Ae,zeros_like:()=>Ee});var _=r("./src/utils/maths.js"),D=r("./src/backends/onnx.js"),j=r("./src/ops/registry.js");const Y=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,uint4:Uint8Array,int4:Int8Array});class N{constructor(...J){fe(this,"ort_tensor");return(0,D.isONNXTensor)(J[0])?this.ort_tensor=J[0]:this.ort_tensor=new D.Tensor(J[0],J[1],J[2]),new Proxy(this,{get:(de,Ce)=>{if(typeof Ce=="string"){let Be=Number(Ce);if(Number.isInteger(Be))return de._getitem(Be)}return de[Ce]},set:(de,Ce,Be)=>de[Ce]=Be})}get dims(){return this.ort_tensor.dims}set dims(J){this.ort_tensor.dims=J}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[J,...de]=this.dims;if(de.length>0){const Ce=de.reduce((Be,Ze)=>Be*Ze);for(let Be=0;Be0){const Be=Ce.reduce((Ze,se)=>Ze*se);return this._subarray(J,Be,Ce)}else return new N(this.type,[this.data[J]],Ce)}indexOf(J){const de=this.data;for(let Ce=0;CeVe)throw new Error(`Invalid slice: ${Te}`);const Ne=[Math.max(Ue,0),Math.min(Ve,this.dims[le])];Ce.push(Ne),de.push(Ne[1]-Ne[0])}else throw new Error(`Invalid slice: ${Te}`)}const Be=Ce.map(([le,Te])=>Te-le),Ze=Be.reduce((le,Te)=>le*Te),se=this.data,Ke=new se.constructor(Ze),je=this.stride();for(let le=0;le=0;--Ue){const Ne=Be[Ue];Te+=(Ve%Ne+Ce[Ue][0])*je[Ue],Ve=Math.floor(Ve/Ne)}Ke[le]=se[Te]}return new N(this.type,Ke,de)}permute(...J){return v(this,J)}transpose(...J){return this.permute(...J)}sum(J=null,de=!1){return this.norm(1,J,de)}norm(J="fro",de=null,Ce=!1){if(J==="fro")J=2;else if(typeof J=="string")throw Error(`Unsupported norm: ${J}`);const Be=this.data,Ze=(le,Te)=>le+Te**J;if(de===null){const le=Be.reduce(Ze,0)**(1/J);return new N(this.type,[le],[])}const[se,Ke,je]=O(Ze,this,de,Ce);if(J!==1)for(let le=0;le=0;--je){const Ue=this.dims[je];if(je!==de){const Ve=le%Ue;Ke+=Ve*Te,Te*=this.dims[je]}le=Math.floor(le/Ue)}Be[se]/=Ze[Ke]}return this}normalize(J=2,de=1){return this.clone().normalize_(J,de)}stride(){return ve(this.dims)}squeeze(J=null){return new N(this.type,this.data,X(this.dims,J))}squeeze_(J=null){return this.dims=X(this.dims,J),this}unsqueeze(J=null){return new N(this.type,this.data,$(this.dims,J))}unsqueeze_(J=null){return this.dims=$(this.dims,J),this}flatten_(J=0,de=-1){de=(de+this.dims.length)%this.dims.length;let Ce=this.dims.slice(0,J),Be=this.dims.slice(J,de+1),Ze=this.dims.slice(de+1);return this.dims=[...Ce,Be.reduce((se,Ke)=>se*Ke,1),...Ze],this}flatten(J=0,de=-1){return this.clone().flatten_(J,de)}view(...J){let de=-1;for(let Be=0;BeKe!==de?Ze*se:Ze,1);J[de]=Ce.length/Be}return new N(this.type,Ce,J)}neg_(){const J=this.data;for(let de=0;deJ?1:0;return new N("bool",de,this.dims)}lt(J){const de=new Uint8Array(this.data.length),Ce=this.data;for(let Be=0;BeMath.min(se,Ke),this,J,de,1/0);return new N(Ce,Be,Ze)}max(J=null,de=!1){if(J===null){const se=(0,_.max)(this.data)[0];return new N(this.type,[se],[])}const[Ce,Be,Ze]=O((se,Ke)=>Math.max(se,Ke),this,J,de,-1/0);return new N(Ce,Be,Ze)}argmin(J=null,de=!1){if(J!==null)throw new Error("`dim !== null` not yet implemented.");const Ce=(0,_.min)(this.data)[1];return new N("int64",[BigInt(Ce)],[])}argmax(J=null,de=!1){if(J!==null)throw new Error("`dim !== null` not yet implemented.");const Ce=(0,_.max)(this.data)[1];return new N("int64",[BigInt(Ce)],[])}to(J){if(this.type===J)return this;if(!Y.hasOwnProperty(J))throw new Error(`Unsupported type: ${J}`);let de;const Ce=["int64","uint64"].includes(this.type),Be=["int64","uint64"].includes(J);return Ce&&!Be?de=Number:!Ce&&Be&&(de=BigInt),new N(J,Y[J].from(this.data,de),this.dims)}}function g(ye,J){const de=ye.length,Ce=J.reduce((Ze,se)=>Ze*se);if(de!==Ce)throw Error(`cannot reshape array of size ${de} into shape (${J})`);let Be=ye;for(let Ze=J.length-1;Ze>=0;Ze--)Be=Be.reduce((se,Ke)=>{let je=se[se.length-1];return je.lengthnew N("int64",ye,[ye.length]);async function ne(ye,J,de,Ce,Be){return await(await j.TensorOpRegistry.slice)({x:ye,s:te(J),e:te(de),a:te(Ce),t:te(Be??new Array(Ce.length).fill(1))})}function W(ye,J){const de=ye.data,Ce=J.data,Be=[ye.dims[0],ye.dims[2]],Ze=new de.constructor(Be[0]*Be[1]),[se,Ke,je]=ye.dims;let le=0;for(let Te=0;Tede!==1):typeof J=="number"?ye[J]===1&&ye.splice(J,1):Array.isArray(J)&&(ye=ye.filter((de,Ce)=>de!==1||!J.includes(Ce))),ye}function $(ye,J){return J=S(J,ye.length+1),ye=ye.slice(),ye.splice(J,0,1),ye}function S(ye,J,de=null,Ce=!0){if(Ce&&(ye<-J||ye>=J))throw new Error(`IndexError: index ${ye} is out of bounds for dimension${de===null?"":" "+de} with size ${J}`);return ye<0&&(ye=(ye%J+J)%J),ye}function w(ye,J=0){J=S(J,ye[0].dims.length);const de=ye[0].dims.slice();de[J]=ye.reduce((se,Ke)=>se+Ke.dims[J],0);const Ce=de.reduce((se,Ke)=>se*Ke,1),Be=new ye[0].data.constructor(Ce),Ze=ye[0].type;if(J===0){let se=0;for(const Ke of ye){const je=Ke.data;Be.set(je,se),se+=je.length}}else{let se=0;for(let Ke=0;Ke=0;--Ve){const st=le[Ve];let dt=Ne%st;Ve===J&&(dt+=se),Ue+=dt*Re,Re*=de[Ve],Ne=Math.floor(Ne/st)}Be[Ue]=je[Te]}se+=le[J]}}return new N(Ze,Be,de)}function x(ye,J=0){return w(ye.map(de=>de.unsqueeze(J)),J)}function O(ye,J,de=null,Ce=!1,Be=null){const Ze=J.data,se=J.dims;de=S(de,se.length);const Ke=se.slice();Ke[de]=1;const je=new Ze.constructor(Ze.length/se[de]);Be!==null&&je.fill(Be);for(let le=0;le=0;--Ue){const Re=se[Ue];if(Ue!==de){const st=Ve%Re;Te+=st*Ne,Ne*=Ke[Ue]}Ve=Math.floor(Ve/Re)}je[Te]=ye(je[Te],Ze[le],le,Te)}return Ce||Ke.splice(de,1),[J.type,je,Ke]}function ae(ye,J=null,de=1,Ce=!1){const Be=ye.data,Ze=ye.dims;if(J===null){const Ne=Be.reduce((ct,lt)=>ct+lt,0)/Be.length,Re=Math.sqrt(Be.reduce((ct,lt)=>ct+(lt-Ne)**2,0)/(Be.length-de)),st=new N(ye.type,[Ne],[]);return[new N(ye.type,[Re],[]),st]}J=S(J,Ze.length);const se=ie(ye,J,Ce),Ke=se.data,[je,le,Te]=O((Ve,Ne,Re,st)=>Ve+(Ne-Ke[st])**2,ye,J,Ce);for(let Ve=0;Vele+Te,0);return new N(ye.type,[je/Be.length],[])}J=S(J,Ce.length);const[Ze,se,Ke]=O((je,le)=>je+le,ye,J,de);if(Ce[J]!==1)for(let je=0;je=0;--de)J[de]=Ce,Ce*=ye[de];return J}function we(ye,J,de,Ce){const Be=ye.reduce((Ze,se)=>Ze*se,1);return new N(de,new Ce(Be).fill(J),ye)}function re(ye,J){let de,Ce;if(typeof J=="number")de="float32",Ce=Float32Array;else if(typeof J=="bigint")de="int64",Ce=BigInt64Array;else if(typeof J=="boolean")de="bool",Ce=Uint8Array;else throw new Error(`Unsupported data type: ${typeof J}`);return we(ye,J,de,Ce)}function xe(ye,J){return re(ye.dims,J)}function ce(ye){return we(ye,1n,"int64",BigInt64Array)}function ke(ye){return ce(ye.dims)}function Ae(ye){return we(ye,0n,"int64",BigInt64Array)}function Ee(ye){return Ae(ye.dims)}function tt(ye){const J=ye.reduce((de,Ce)=>de*Ce,1);return new N("float32",Float32Array.from({length:J},()=>Math.random()),ye)}function Ge(ye,J){if(ye.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(ye.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(J))throw new Error("The precision must be either 'binary' or 'ubinary'");const de=J==="binary",Ce=de?"int8":"uint8",Be=de?Int8Array:Uint8Array,Ze=ye.data,se=new Be(Ze.length/8);for(let Ke=0;Ke0?1:0,le=Math.floor(Ke/8),Te=Ke%8;se[le]|=je<<7-Te,de&&Te===0&&(se[le]-=128)}return new N(Ce,se,[ye.dims[0],ye.dims[1]/8])}}},ti={};function gs(ze){var A=ti[ze];if(A!==void 0)return A.exports;var r=ti[ze]={exports:{}};return Xr[ze](r,r.exports,gs),r.exports}gs.m=Xr,(()=>{var ze=Object.getPrototypeOf?r=>Object.getPrototypeOf(r):r=>r.__proto__,A;gs.t=function(r,_){if(_&1&&(r=this(r)),_&8||typeof r=="object"&&r&&(_&4&&r.__esModule||_&16&&typeof r.then=="function"))return r;var D=Object.create(null);gs.r(D);var j={};A=A||[null,ze({}),ze([]),ze(ze)];for(var Y=_&2&&r;typeof Y=="object"&&!~A.indexOf(Y);Y=ze(Y))Object.getOwnPropertyNames(Y).forEach(N=>j[N]=()=>r[N]);return j.default=()=>r,gs.d(D,j),D}})(),gs.d=(ze,A)=>{for(var r in A)gs.o(A,r)&&!gs.o(ze,r)&&Object.defineProperty(ze,r,{enumerable:!0,get:A[r]})},gs.o=(ze,A)=>Object.prototype.hasOwnProperty.call(ze,A),gs.r=ze=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(ze,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(ze,"__esModule",{value:!0})},(()=>{var ze;if(typeof self.location.href=="string"&&(ze=self.location.href),!ze)throw new Error("Automatic publicPath is not supported in this browser");ze=ze.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),gs.p=ze})(),gs.b=new URL("./",self.location.href);var c={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/gs.r(c),gs.d(c,{ASTFeatureExtractor:()=>y.ASTFeatureExtractor,ASTForAudioClassification:()=>r.ASTForAudioClassification,ASTModel:()=>r.ASTModel,ASTPreTrainedModel:()=>r.ASTPreTrainedModel,AlbertForMaskedLM:()=>r.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>r.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>r.AlbertForSequenceClassification,AlbertModel:()=>r.AlbertModel,AlbertPreTrainedModel:()=>r.AlbertPreTrainedModel,AlbertTokenizer:()=>_.AlbertTokenizer,AudioClassificationPipeline:()=>A.AudioClassificationPipeline,AutoConfig:()=>D.AutoConfig,AutoFeatureExtractor:()=>M.AutoFeatureExtractor,AutoImageProcessor:()=>K.AutoImageProcessor,AutoModel:()=>r.AutoModel,AutoModelForAudioClassification:()=>r.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>r.AutoModelForAudioFrameClassification,AutoModelForCTC:()=>r.AutoModelForCTC,AutoModelForCausalLM:()=>r.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>r.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>r.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>r.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>r.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>r.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>r.AutoModelForImageSegmentation,AutoModelForImageToImage:()=>r.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>r.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>r.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>r.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>r.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>r.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>r.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>r.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>r.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>r.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>r.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>r.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>r.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>r.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>r.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>r.AutoModelForVision2Seq,AutoModelForXVector:()=>r.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>r.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>W.AutoProcessor,AutoTokenizer:()=>_.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>A.AutomaticSpeechRecognitionPipeline,BartForConditionalGeneration:()=>r.BartForConditionalGeneration,BartForSequenceClassification:()=>r.BartForSequenceClassification,BartModel:()=>r.BartModel,BartPretrainedModel:()=>r.BartPretrainedModel,BartTokenizer:()=>_.BartTokenizer,BaseModelOutput:()=>r.BaseModelOutput,BaseStreamer:()=>U.BaseStreamer,BeitFeatureExtractor:()=>I.BeitFeatureExtractor,BeitForImageClassification:()=>r.BeitForImageClassification,BeitModel:()=>r.BeitModel,BeitPreTrainedModel:()=>r.BeitPreTrainedModel,BertForMaskedLM:()=>r.BertForMaskedLM,BertForQuestionAnswering:()=>r.BertForQuestionAnswering,BertForSequenceClassification:()=>r.BertForSequenceClassification,BertForTokenClassification:()=>r.BertForTokenClassification,BertModel:()=>r.BertModel,BertPreTrainedModel:()=>r.BertPreTrainedModel,BertTokenizer:()=>_.BertTokenizer,BitImageProcessor:()=>I.BitImageProcessor,BlenderbotForConditionalGeneration:()=>r.BlenderbotForConditionalGeneration,BlenderbotModel:()=>r.BlenderbotModel,BlenderbotPreTrainedModel:()=>r.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>r.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>r.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>r.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>_.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>_.BlenderbotTokenizer,BloomForCausalLM:()=>r.BloomForCausalLM,BloomModel:()=>r.BloomModel,BloomPreTrainedModel:()=>r.BloomPreTrainedModel,BloomTokenizer:()=>_.BloomTokenizer,CLIPFeatureExtractor:()=>I.CLIPFeatureExtractor,CLIPImageProcessor:()=>I.CLIPImageProcessor,CLIPModel:()=>r.CLIPModel,CLIPPreTrainedModel:()=>r.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>r.CLIPSegForImageSegmentation,CLIPSegModel:()=>r.CLIPSegModel,CLIPSegPreTrainedModel:()=>r.CLIPSegPreTrainedModel,CLIPTextModel:()=>r.CLIPTextModel,CLIPTextModelWithProjection:()=>r.CLIPTextModelWithProjection,CLIPTokenizer:()=>_.CLIPTokenizer,CLIPVisionModel:()=>r.CLIPVisionModel,CLIPVisionModelWithProjection:()=>r.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>r.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>r.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>r.CamembertForSequenceClassification,CamembertForTokenClassification:()=>r.CamembertForTokenClassification,CamembertModel:()=>r.CamembertModel,CamembertPreTrainedModel:()=>r.CamembertPreTrainedModel,CamembertTokenizer:()=>_.CamembertTokenizer,CausalLMOutput:()=>r.CausalLMOutput,CausalLMOutputWithPast:()=>r.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>I.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>r.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>r.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>r.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>y.ClapFeatureExtractor,ClapModel:()=>r.ClapModel,ClapPreTrainedModel:()=>r.ClapPreTrainedModel,ClapTextModelWithProjection:()=>r.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>$.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>r.CodeGenForCausalLM,CodeGenModel:()=>r.CodeGenModel,CodeGenPreTrainedModel:()=>r.CodeGenPreTrainedModel,CodeGenTokenizer:()=>_.CodeGenTokenizer,CodeLlamaTokenizer:()=>_.CodeLlamaTokenizer,CohereForCausalLM:()=>r.CohereForCausalLM,CohereModel:()=>r.CohereModel,CoherePreTrainedModel:()=>r.CoherePreTrainedModel,CohereTokenizer:()=>_.CohereTokenizer,ConvBertForMaskedLM:()=>r.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>r.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>r.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>r.ConvBertForTokenClassification,ConvBertModel:()=>r.ConvBertModel,ConvBertPreTrainedModel:()=>r.ConvBertPreTrainedModel,ConvBertTokenizer:()=>_.ConvBertTokenizer,ConvNextFeatureExtractor:()=>I.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>r.ConvNextForImageClassification,ConvNextImageProcessor:()=>I.ConvNextImageProcessor,ConvNextModel:()=>r.ConvNextModel,ConvNextPreTrainedModel:()=>r.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>r.ConvNextV2ForImageClassification,ConvNextV2Model:()=>r.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>r.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>I.DPTFeatureExtractor,DPTForDepthEstimation:()=>r.DPTForDepthEstimation,DPTImageProcessor:()=>I.DPTImageProcessor,DPTModel:()=>r.DPTModel,DPTPreTrainedModel:()=>r.DPTPreTrainedModel,DebertaForMaskedLM:()=>r.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>r.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>r.DebertaForSequenceClassification,DebertaForTokenClassification:()=>r.DebertaForTokenClassification,DebertaModel:()=>r.DebertaModel,DebertaPreTrainedModel:()=>r.DebertaPreTrainedModel,DebertaTokenizer:()=>_.DebertaTokenizer,DebertaV2ForMaskedLM:()=>r.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>r.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>r.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>r.DebertaV2ForTokenClassification,DebertaV2Model:()=>r.DebertaV2Model,DebertaV2PreTrainedModel:()=>r.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>_.DebertaV2Tokenizer,DecisionTransformerModel:()=>r.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>r.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>I.DeiTFeatureExtractor,DeiTForImageClassification:()=>r.DeiTForImageClassification,DeiTImageProcessor:()=>I.DeiTImageProcessor,DeiTModel:()=>r.DeiTModel,DeiTPreTrainedModel:()=>r.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>r.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>r.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>A.DepthEstimationPipeline,DepthProForDepthEstimation:()=>r.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>r.DepthProPreTrainedModel,DetrFeatureExtractor:()=>I.DetrFeatureExtractor,DetrForObjectDetection:()=>r.DetrForObjectDetection,DetrForSegmentation:()=>r.DetrForSegmentation,DetrImageProcessor:()=>I.DetrImageProcessor,DetrModel:()=>r.DetrModel,DetrObjectDetectionOutput:()=>r.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>r.DetrPreTrainedModel,DetrSegmentationOutput:()=>r.DetrSegmentationOutput,Dinov2ForImageClassification:()=>r.Dinov2ForImageClassification,Dinov2Model:()=>r.Dinov2Model,Dinov2PreTrainedModel:()=>r.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>r.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>r.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>r.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>r.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>r.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>r.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>r.DistilBertForTokenClassification,DistilBertModel:()=>r.DistilBertModel,DistilBertPreTrainedModel:()=>r.DistilBertPreTrainedModel,DistilBertTokenizer:()=>_.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>A.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>I.DonutFeatureExtractor,DonutImageProcessor:()=>I.DonutImageProcessor,DonutSwinModel:()=>r.DonutSwinModel,DonutSwinPreTrainedModel:()=>r.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>r.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>I.EfficientNetImageProcessor,EfficientNetModel:()=>r.EfficientNetModel,EfficientNetPreTrainedModel:()=>r.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>r.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>r.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>r.ElectraForSequenceClassification,ElectraForTokenClassification:()=>r.ElectraForTokenClassification,ElectraModel:()=>r.ElectraModel,ElectraPreTrainedModel:()=>r.ElectraPreTrainedModel,ElectraTokenizer:()=>_.ElectraTokenizer,EosTokenCriteria:()=>X.EosTokenCriteria,EsmForMaskedLM:()=>r.EsmForMaskedLM,EsmForSequenceClassification:()=>r.EsmForSequenceClassification,EsmForTokenClassification:()=>r.EsmForTokenClassification,EsmModel:()=>r.EsmModel,EsmPreTrainedModel:()=>r.EsmPreTrainedModel,EsmTokenizer:()=>_.EsmTokenizer,ExaoneForCausalLM:()=>r.ExaoneForCausalLM,ExaoneModel:()=>r.ExaoneModel,ExaonePreTrainedModel:()=>r.ExaonePreTrainedModel,FFT:()=>g.FFT,FalconForCausalLM:()=>r.FalconForCausalLM,FalconModel:()=>r.FalconModel,FalconPreTrainedModel:()=>r.FalconPreTrainedModel,FalconTokenizer:()=>_.FalconTokenizer,FastViTForImageClassification:()=>r.FastViTForImageClassification,FastViTModel:()=>r.FastViTModel,FastViTPreTrainedModel:()=>r.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>A.FeatureExtractionPipeline,FeatureExtractor:()=>v.FeatureExtractor,FillMaskPipeline:()=>A.FillMaskPipeline,Florence2ForConditionalGeneration:()=>r.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>r.Florence2PreTrainedModel,Florence2Processor:()=>ne.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>$.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>$.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>I.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>r.GLPNForDepthEstimation,GLPNModel:()=>r.GLPNModel,GLPNPreTrainedModel:()=>r.GLPNPreTrainedModel,GPT2LMHeadModel:()=>r.GPT2LMHeadModel,GPT2Model:()=>r.GPT2Model,GPT2PreTrainedModel:()=>r.GPT2PreTrainedModel,GPT2Tokenizer:()=>_.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>r.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>r.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>r.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>r.GPTJForCausalLM,GPTJModel:()=>r.GPTJModel,GPTJPreTrainedModel:()=>r.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>r.GPTNeoForCausalLM,GPTNeoModel:()=>r.GPTNeoModel,GPTNeoPreTrainedModel:()=>r.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>r.GPTNeoXForCausalLM,GPTNeoXModel:()=>r.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>r.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>_.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>r.Gemma2ForCausalLM,Gemma2Model:()=>r.Gemma2Model,Gemma2PreTrainedModel:()=>r.Gemma2PreTrainedModel,GemmaForCausalLM:()=>r.GemmaForCausalLM,GemmaModel:()=>r.GemmaModel,GemmaPreTrainedModel:()=>r.GemmaPreTrainedModel,GemmaTokenizer:()=>_.GemmaTokenizer,GraniteForCausalLM:()=>r.GraniteForCausalLM,GraniteModel:()=>r.GraniteModel,GranitePreTrainedModel:()=>r.GranitePreTrainedModel,Grok1Tokenizer:()=>_.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>r.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>I.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>r.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>ne.GroundingDinoProcessor,GroupViTModel:()=>r.GroupViTModel,GroupViTPreTrainedModel:()=>r.GroupViTPreTrainedModel,HerbertTokenizer:()=>_.HerbertTokenizer,HieraForImageClassification:()=>r.HieraForImageClassification,HieraModel:()=>r.HieraModel,HieraPreTrainedModel:()=>r.HieraPreTrainedModel,HubertForCTC:()=>r.HubertForCTC,HubertForSequenceClassification:()=>r.HubertForSequenceClassification,HubertModel:()=>r.HubertModel,HubertPreTrainedModel:()=>r.HubertPreTrainedModel,IJepaForImageClassification:()=>r.IJepaForImageClassification,IJepaModel:()=>r.IJepaModel,IJepaPreTrainedModel:()=>r.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>r.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>I.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>r.Idefics3PreTrainedModel,Idefics3Processor:()=>ne.Idefics3Processor,ImageClassificationPipeline:()=>A.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>A.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>y.ImageFeatureExtractor,ImageMattingOutput:()=>r.ImageMattingOutput,ImageProcessor:()=>b.ImageProcessor,ImageSegmentationPipeline:()=>A.ImageSegmentationPipeline,ImageToImagePipeline:()=>A.ImageToImagePipeline,ImageToTextPipeline:()=>A.ImageToTextPipeline,InterruptableStoppingCriteria:()=>X.InterruptableStoppingCriteria,JAISLMHeadModel:()=>r.JAISLMHeadModel,JAISModel:()=>r.JAISModel,JAISPreTrainedModel:()=>r.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>I.JinaCLIPImageProcessor,JinaCLIPModel:()=>r.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>r.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>ne.JinaCLIPProcessor,JinaCLIPTextModel:()=>r.JinaCLIPTextModel,JinaCLIPVisionModel:()=>r.JinaCLIPVisionModel,LlamaForCausalLM:()=>r.LlamaForCausalLM,LlamaModel:()=>r.LlamaModel,LlamaPreTrainedModel:()=>r.LlamaPreTrainedModel,LlamaTokenizer:()=>_.LlamaTokenizer,LlavaForConditionalGeneration:()=>r.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>r.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>I.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>r.LlavaPreTrainedModel,LogitsProcessor:()=>$.LogitsProcessor,LogitsProcessorList:()=>$.LogitsProcessorList,LogitsWarper:()=>$.LogitsWarper,LongT5ForConditionalGeneration:()=>r.LongT5ForConditionalGeneration,LongT5Model:()=>r.LongT5Model,LongT5PreTrainedModel:()=>r.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>r.M2M100ForConditionalGeneration,M2M100Model:()=>r.M2M100Model,M2M100PreTrainedModel:()=>r.M2M100PreTrainedModel,M2M100Tokenizer:()=>_.M2M100Tokenizer,MBart50Tokenizer:()=>_.MBart50Tokenizer,MBartForCausalLM:()=>r.MBartForCausalLM,MBartForConditionalGeneration:()=>r.MBartForConditionalGeneration,MBartForSequenceClassification:()=>r.MBartForSequenceClassification,MBartModel:()=>r.MBartModel,MBartPreTrainedModel:()=>r.MBartPreTrainedModel,MBartTokenizer:()=>_.MBartTokenizer,MPNetForMaskedLM:()=>r.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>r.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>r.MPNetForSequenceClassification,MPNetForTokenClassification:()=>r.MPNetForTokenClassification,MPNetModel:()=>r.MPNetModel,MPNetPreTrainedModel:()=>r.MPNetPreTrainedModel,MPNetTokenizer:()=>_.MPNetTokenizer,MT5ForConditionalGeneration:()=>r.MT5ForConditionalGeneration,MT5Model:()=>r.MT5Model,MT5PreTrainedModel:()=>r.MT5PreTrainedModel,MarianMTModel:()=>r.MarianMTModel,MarianModel:()=>r.MarianModel,MarianPreTrainedModel:()=>r.MarianPreTrainedModel,MarianTokenizer:()=>_.MarianTokenizer,Mask2FormerImageProcessor:()=>I.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>I.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>r.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>I.MaskFormerImageProcessor,MaskFormerModel:()=>r.MaskFormerModel,MaskFormerPreTrainedModel:()=>r.MaskFormerPreTrainedModel,MaskedLMOutput:()=>r.MaskedLMOutput,MaxLengthCriteria:()=>X.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>r.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>r.MgpstrModelOutput,MgpstrPreTrainedModel:()=>r.MgpstrPreTrainedModel,MgpstrProcessor:()=>ne.MgpstrProcessor,MgpstrTokenizer:()=>_.MgpstrTokenizer,MinLengthLogitsProcessor:()=>$.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>$.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>r.MistralForCausalLM,MistralModel:()=>r.MistralModel,MistralPreTrainedModel:()=>r.MistralPreTrainedModel,MobileBertForMaskedLM:()=>r.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>r.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>r.MobileBertForSequenceClassification,MobileBertModel:()=>r.MobileBertModel,MobileBertPreTrainedModel:()=>r.MobileBertPreTrainedModel,MobileBertTokenizer:()=>_.MobileBertTokenizer,MobileLLMForCausalLM:()=>r.MobileLLMForCausalLM,MobileLLMModel:()=>r.MobileLLMModel,MobileLLMPreTrainedModel:()=>r.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>I.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>r.MobileNetV1ForImageClassification,MobileNetV1ImageProcessor:()=>I.MobileNetV1ImageProcessor,MobileNetV1Model:()=>r.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>r.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>I.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>r.MobileNetV2ForImageClassification,MobileNetV2ImageProcessor:()=>I.MobileNetV2ImageProcessor,MobileNetV2Model:()=>r.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>r.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>I.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>r.MobileNetV3ForImageClassification,MobileNetV3ImageProcessor:()=>I.MobileNetV3ImageProcessor,MobileNetV3Model:()=>r.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>r.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>I.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>r.MobileNetV4ForImageClassification,MobileNetV4ImageProcessor:()=>I.MobileNetV4ImageProcessor,MobileNetV4Model:()=>r.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>r.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>I.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>r.MobileViTForImageClassification,MobileViTImageProcessor:()=>I.MobileViTImageProcessor,MobileViTModel:()=>r.MobileViTModel,MobileViTPreTrainedModel:()=>r.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>r.MobileViTV2ForImageClassification,MobileViTV2Model:()=>r.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>r.MobileViTV2PreTrainedModel,ModelOutput:()=>r.ModelOutput,ModernBertForMaskedLM:()=>r.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>r.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>r.ModernBertForTokenClassification,ModernBertModel:()=>r.ModernBertModel,ModernBertPreTrainedModel:()=>r.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>r.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>y.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>r.MoonshineForConditionalGeneration,MoonshineModel:()=>r.MoonshineModel,MoonshinePreTrainedModel:()=>r.MoonshinePreTrainedModel,MoonshineProcessor:()=>ne.MoonshineProcessor,MptForCausalLM:()=>r.MptForCausalLM,MptModel:()=>r.MptModel,MptPreTrainedModel:()=>r.MptPreTrainedModel,MultiModalityCausalLM:()=>r.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>r.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>r.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>r.MusicgenForConditionalGeneration,MusicgenModel:()=>r.MusicgenModel,MusicgenPreTrainedModel:()=>r.MusicgenPreTrainedModel,NllbTokenizer:()=>_.NllbTokenizer,NoBadWordsLogitsProcessor:()=>$.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>$.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>r.NomicBertModel,NomicBertPreTrainedModel:()=>r.NomicBertPreTrainedModel,NougatImageProcessor:()=>I.NougatImageProcessor,NougatTokenizer:()=>_.NougatTokenizer,OPTForCausalLM:()=>r.OPTForCausalLM,OPTModel:()=>r.OPTModel,OPTPreTrainedModel:()=>r.OPTPreTrainedModel,ObjectDetectionPipeline:()=>A.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>r.Olmo2ForCausalLM,Olmo2Model:()=>r.Olmo2Model,Olmo2PreTrainedModel:()=>r.Olmo2PreTrainedModel,OlmoForCausalLM:()=>r.OlmoForCausalLM,OlmoModel:()=>r.OlmoModel,OlmoPreTrainedModel:()=>r.OlmoPreTrainedModel,OpenELMForCausalLM:()=>r.OpenELMForCausalLM,OpenELMModel:()=>r.OpenELMModel,OpenELMPreTrainedModel:()=>r.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>I.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>r.OwlViTForObjectDetection,OwlViTImageProcessor:()=>I.OwlViTImageProcessor,OwlViTModel:()=>r.OwlViTModel,OwlViTPreTrainedModel:()=>r.OwlViTPreTrainedModel,OwlViTProcessor:()=>ne.OwlViTProcessor,Owlv2ForObjectDetection:()=>r.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>I.Owlv2ImageProcessor,Owlv2Model:()=>r.Owlv2Model,Owlv2PreTrainedModel:()=>r.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>r.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>r.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>ne.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>r.PatchTSMixerForPrediction,PatchTSMixerModel:()=>r.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>r.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>r.PatchTSTForPrediction,PatchTSTModel:()=>r.PatchTSTModel,PatchTSTPreTrainedModel:()=>r.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>r.Phi3ForCausalLM,Phi3Model:()=>r.Phi3Model,Phi3PreTrainedModel:()=>r.Phi3PreTrainedModel,Phi3VForCausalLM:()=>r.Phi3VForCausalLM,Phi3VImageProcessor:()=>I.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>r.Phi3VPreTrainedModel,Phi3VProcessor:()=>ne.Phi3VProcessor,PhiForCausalLM:()=>r.PhiForCausalLM,PhiModel:()=>r.PhiModel,PhiPreTrainedModel:()=>r.PhiPreTrainedModel,Pipeline:()=>A.Pipeline,PreTrainedModel:()=>r.PreTrainedModel,PreTrainedTokenizer:()=>_.PreTrainedTokenizer,PretrainedConfig:()=>D.PretrainedConfig,PretrainedMixin:()=>r.PretrainedMixin,Processor:()=>te.Processor,PvtForImageClassification:()=>r.PvtForImageClassification,PvtImageProcessor:()=>I.PvtImageProcessor,PvtModel:()=>r.PvtModel,PvtPreTrainedModel:()=>r.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>y.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>r.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>r.PyAnnoteModel,PyAnnotePreTrainedModel:()=>r.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>ne.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>r.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>A.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>r.Qwen2ForCausalLM,Qwen2Model:()=>r.Qwen2Model,Qwen2PreTrainedModel:()=>r.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>_.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>r.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>I.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>r.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>ne.Qwen2VLProcessor,RTDetrForObjectDetection:()=>r.RTDetrForObjectDetection,RTDetrImageProcessor:()=>I.RTDetrImageProcessor,RTDetrModel:()=>r.RTDetrModel,RTDetrObjectDetectionOutput:()=>r.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>r.RTDetrPreTrainedModel,RawAudio:()=>j.RawAudio,RawImage:()=>Y.RawImage,RepetitionPenaltyLogitsProcessor:()=>$.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>r.ResNetForImageClassification,ResNetModel:()=>r.ResNetModel,ResNetPreTrainedModel:()=>r.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>r.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>r.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>r.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>r.RoFormerForTokenClassification,RoFormerModel:()=>r.RoFormerModel,RoFormerPreTrainedModel:()=>r.RoFormerPreTrainedModel,RoFormerTokenizer:()=>_.RoFormerTokenizer,RobertaForMaskedLM:()=>r.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>r.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>r.RobertaForSequenceClassification,RobertaForTokenClassification:()=>r.RobertaForTokenClassification,RobertaModel:()=>r.RobertaModel,RobertaPreTrainedModel:()=>r.RobertaPreTrainedModel,RobertaTokenizer:()=>_.RobertaTokenizer,SamImageProcessor:()=>I.SamImageProcessor,SamImageSegmentationOutput:()=>r.SamImageSegmentationOutput,SamModel:()=>r.SamModel,SamPreTrainedModel:()=>r.SamPreTrainedModel,SamProcessor:()=>ne.SamProcessor,SapiensForDepthEstimation:()=>r.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>r.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>r.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>r.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>y.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>I.SegformerFeatureExtractor,SegformerForImageClassification:()=>r.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>r.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>I.SegformerImageProcessor,SegformerModel:()=>r.SegformerModel,SegformerPreTrainedModel:()=>r.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>r.Seq2SeqLMOutput,SequenceClassifierOutput:()=>r.SequenceClassifierOutput,SiglipImageProcessor:()=>I.SiglipImageProcessor,SiglipModel:()=>r.SiglipModel,SiglipPreTrainedModel:()=>r.SiglipPreTrainedModel,SiglipTextModel:()=>r.SiglipTextModel,SiglipTokenizer:()=>_.SiglipTokenizer,SiglipVisionModel:()=>r.SiglipVisionModel,SpeechT5FeatureExtractor:()=>y.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>r.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>r.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>r.SpeechT5HifiGan,SpeechT5Model:()=>r.SpeechT5Model,SpeechT5PreTrainedModel:()=>r.SpeechT5PreTrainedModel,SpeechT5Processor:()=>ne.SpeechT5Processor,SpeechT5Tokenizer:()=>_.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>r.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>r.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>r.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>r.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>r.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>_.SqueezeBertTokenizer,StableLmForCausalLM:()=>r.StableLmForCausalLM,StableLmModel:()=>r.StableLmModel,StableLmPreTrainedModel:()=>r.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>r.Starcoder2ForCausalLM,Starcoder2Model:()=>r.Starcoder2Model,Starcoder2PreTrainedModel:()=>r.Starcoder2PreTrainedModel,StoppingCriteria:()=>X.StoppingCriteria,StoppingCriteriaList:()=>X.StoppingCriteriaList,StyleTextToSpeech2Model:()=>r.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>r.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>A.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>$.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>r.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>I.Swin2SRImageProcessor,Swin2SRModel:()=>r.Swin2SRModel,Swin2SRPreTrainedModel:()=>r.Swin2SRPreTrainedModel,SwinForImageClassification:()=>r.SwinForImageClassification,SwinModel:()=>r.SwinModel,SwinPreTrainedModel:()=>r.SwinPreTrainedModel,T5ForConditionalGeneration:()=>r.T5ForConditionalGeneration,T5Model:()=>r.T5Model,T5PreTrainedModel:()=>r.T5PreTrainedModel,T5Tokenizer:()=>_.T5Tokenizer,TableTransformerForObjectDetection:()=>r.TableTransformerForObjectDetection,TableTransformerModel:()=>r.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>r.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>r.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>$.TemperatureLogitsWarper,Tensor:()=>N.Tensor,Text2TextGenerationPipeline:()=>A.Text2TextGenerationPipeline,TextClassificationPipeline:()=>A.TextClassificationPipeline,TextGenerationPipeline:()=>A.TextGenerationPipeline,TextStreamer:()=>U.TextStreamer,TextToAudioPipeline:()=>A.TextToAudioPipeline,TokenClassificationPipeline:()=>A.TokenClassificationPipeline,TokenClassifierOutput:()=>r.TokenClassifierOutput,TokenizerModel:()=>_.TokenizerModel,TopKLogitsWarper:()=>$.TopKLogitsWarper,TopPLogitsWarper:()=>$.TopPLogitsWarper,TrOCRForCausalLM:()=>r.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>r.TrOCRPreTrainedModel,TranslationPipeline:()=>A.TranslationPipeline,UniSpeechForCTC:()=>r.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>r.UniSpeechForSequenceClassification,UniSpeechModel:()=>r.UniSpeechModel,UniSpeechPreTrainedModel:()=>r.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>r.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>r.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>r.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>r.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>r.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>ne.VLChatProcessor,VLMImageProcessor:()=>I.VLMImageProcessor,ViTFeatureExtractor:()=>I.ViTFeatureExtractor,ViTForImageClassification:()=>r.ViTForImageClassification,ViTImageProcessor:()=>I.ViTImageProcessor,ViTMAEModel:()=>r.ViTMAEModel,ViTMAEPreTrainedModel:()=>r.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>r.ViTMSNForImageClassification,ViTMSNModel:()=>r.ViTMSNModel,ViTMSNPreTrainedModel:()=>r.ViTMSNPreTrainedModel,ViTModel:()=>r.ViTModel,ViTPreTrainedModel:()=>r.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>r.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>r.VitMatteForImageMatting,VitMatteImageProcessor:()=>I.VitMatteImageProcessor,VitMattePreTrainedModel:()=>r.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>r.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>I.VitPoseImageProcessor,VitPosePreTrainedModel:()=>r.VitPosePreTrainedModel,VitsModel:()=>r.VitsModel,VitsModelOutput:()=>r.VitsModelOutput,VitsPreTrainedModel:()=>r.VitsPreTrainedModel,VitsTokenizer:()=>_.VitsTokenizer,Wav2Vec2BertForCTC:()=>r.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>r.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>r.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>r.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>_.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>y.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>r.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>r.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>r.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>r.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>r.Wav2Vec2PreTrainedModel,Wav2Vec2ProcessorWithLM:()=>ne.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>r.WavLMForAudioFrameClassification,WavLMForCTC:()=>r.WavLMForCTC,WavLMForSequenceClassification:()=>r.WavLMForSequenceClassification,WavLMForXVector:()=>r.WavLMForXVector,WavLMModel:()=>r.WavLMModel,WavLMPreTrainedModel:()=>r.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>y.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>r.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>r.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>y.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>r.WhisperForConditionalGeneration,WhisperModel:()=>r.WhisperModel,WhisperPreTrainedModel:()=>r.WhisperPreTrainedModel,WhisperProcessor:()=>ne.WhisperProcessor,WhisperTextStreamer:()=>U.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>$.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>_.WhisperTokenizer,XLMForQuestionAnswering:()=>r.XLMForQuestionAnswering,XLMForSequenceClassification:()=>r.XLMForSequenceClassification,XLMForTokenClassification:()=>r.XLMForTokenClassification,XLMModel:()=>r.XLMModel,XLMPreTrainedModel:()=>r.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>r.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>r.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>r.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>r.XLMRobertaForTokenClassification,XLMRobertaModel:()=>r.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>r.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>_.XLMRobertaTokenizer,XLMTokenizer:()=>_.XLMTokenizer,XLMWithLMHeadModel:()=>r.XLMWithLMHeadModel,XVectorOutput:()=>r.XVectorOutput,YolosFeatureExtractor:()=>I.YolosFeatureExtractor,YolosForObjectDetection:()=>r.YolosForObjectDetection,YolosImageProcessor:()=>I.YolosImageProcessor,YolosModel:()=>r.YolosModel,YolosObjectDetectionOutput:()=>r.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>r.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>A.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>A.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>A.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>A.ZeroShotObjectDetectionPipeline,bankers_round:()=>g.bankers_round,cat:()=>N.cat,cos_sim:()=>g.cos_sim,dot:()=>g.dot,dynamic_time_warping:()=>g.dynamic_time_warping,env:()=>ze.env,full:()=>N.full,full_like:()=>N.full_like,getKeyValueShapes:()=>D.getKeyValueShapes,hamming:()=>j.hamming,hanning:()=>j.hanning,interpolate:()=>N.interpolate,interpolate_4d:()=>N.interpolate_4d,interpolate_data:()=>g.interpolate_data,is_chinese_char:()=>_.is_chinese_char,layer_norm:()=>N.layer_norm,load_image:()=>Y.load_image,log_softmax:()=>g.log_softmax,magnitude:()=>g.magnitude,matmul:()=>N.matmul,max:()=>g.max,mean:()=>N.mean,mean_pooling:()=>N.mean_pooling,medianFilter:()=>g.medianFilter,mel_filter_bank:()=>j.mel_filter_bank,min:()=>g.min,ones:()=>N.ones,ones_like:()=>N.ones_like,permute:()=>N.permute,permute_data:()=>g.permute_data,pipeline:()=>A.pipeline,quantize_embeddings:()=>N.quantize_embeddings,rand:()=>N.rand,read_audio:()=>j.read_audio,rfft:()=>N.rfft,round:()=>g.round,slice:()=>N.slice,softmax:()=>g.softmax,spectrogram:()=>j.spectrogram,stack:()=>N.stack,std_mean:()=>N.std_mean,topk:()=>N.topk,window_function:()=>j.window_function,zeros:()=>N.zeros,zeros_like:()=>N.zeros_like});var ze=gs("./src/env.js"),A=gs("./src/pipelines.js"),r=gs("./src/models.js"),_=gs("./src/tokenizers.js"),D=gs("./src/configs.js"),j=gs("./src/utils/audio.js"),Y=gs("./src/utils/image.js"),N=gs("./src/utils/tensor.js"),g=gs("./src/utils/maths.js"),v=gs("./src/base/feature_extraction_utils.js"),y=gs("./src/models/feature_extractors.js"),M=gs("./src/models/auto/feature_extraction_auto.js"),b=gs("./src/base/image_processors_utils.js"),I=gs("./src/models/image_processors.js"),K=gs("./src/models/auto/image_processing_auto.js"),te=gs("./src/base/processing_utils.js"),ne=gs("./src/models/processors.js"),W=gs("./src/models/auto/processing_auto.js"),U=gs("./src/generation/streamers.js"),X=gs("./src/generation/stopping_criteria.js"),$=gs("./src/generation/logits_process.js")})(),c.ASTFeatureExtractor,c.ASTForAudioClassification,c.ASTModel,c.ASTPreTrainedModel,c.AlbertForMaskedLM,c.AlbertForQuestionAnswering,c.AlbertForSequenceClassification,c.AlbertModel,c.AlbertPreTrainedModel,c.AlbertTokenizer,c.AudioClassificationPipeline,c.AutoConfig,c.AutoFeatureExtractor,c.AutoImageProcessor,c.AutoModel,c.AutoModelForAudioClassification,c.AutoModelForAudioFrameClassification,c.AutoModelForCTC,c.AutoModelForCausalLM,c.AutoModelForDepthEstimation,c.AutoModelForDocumentQuestionAnswering,c.AutoModelForImageClassification,c.AutoModelForImageFeatureExtraction,c.AutoModelForImageMatting,c.AutoModelForImageSegmentation,c.AutoModelForImageToImage,c.AutoModelForMaskGeneration,c.AutoModelForMaskedLM,c.AutoModelForNormalEstimation,c.AutoModelForObjectDetection,c.AutoModelForPoseEstimation,c.AutoModelForQuestionAnswering,c.AutoModelForSemanticSegmentation,c.AutoModelForSeq2SeqLM,c.AutoModelForSequenceClassification,c.AutoModelForSpeechSeq2Seq,c.AutoModelForTextToSpectrogram,c.AutoModelForTextToWaveform,c.AutoModelForTokenClassification,c.AutoModelForUniversalSegmentation,c.AutoModelForVision2Seq,c.AutoModelForXVector,c.AutoModelForZeroShotObjectDetection,c.AutoProcessor,c.AutoTokenizer,c.AutomaticSpeechRecognitionPipeline,c.BartForConditionalGeneration,c.BartForSequenceClassification,c.BartModel,c.BartPretrainedModel,c.BartTokenizer,c.BaseModelOutput,c.BaseStreamer,c.BeitFeatureExtractor,c.BeitForImageClassification,c.BeitModel,c.BeitPreTrainedModel,c.BertForMaskedLM,c.BertForQuestionAnswering,c.BertForSequenceClassification,c.BertForTokenClassification,c.BertModel,c.BertPreTrainedModel,c.BertTokenizer,c.BitImageProcessor,c.BlenderbotForConditionalGeneration,c.BlenderbotModel,c.BlenderbotPreTrainedModel,c.BlenderbotSmallForConditionalGeneration,c.BlenderbotSmallModel,c.BlenderbotSmallPreTrainedModel,c.BlenderbotSmallTokenizer,c.BlenderbotTokenizer,c.BloomForCausalLM,c.BloomModel,c.BloomPreTrainedModel,c.BloomTokenizer,c.CLIPFeatureExtractor,c.CLIPImageProcessor,c.CLIPModel,c.CLIPPreTrainedModel,c.CLIPSegForImageSegmentation,c.CLIPSegModel,c.CLIPSegPreTrainedModel,c.CLIPTextModel,c.CLIPTextModelWithProjection,c.CLIPTokenizer,c.CLIPVisionModel,c.CLIPVisionModelWithProjection,c.CamembertForMaskedLM,c.CamembertForQuestionAnswering,c.CamembertForSequenceClassification,c.CamembertForTokenClassification,c.CamembertModel,c.CamembertPreTrainedModel,c.CamembertTokenizer,c.CausalLMOutput,c.CausalLMOutputWithPast,c.ChineseCLIPFeatureExtractor,c.ChineseCLIPModel,c.ChineseCLIPPreTrainedModel,c.ClapAudioModelWithProjection,c.ClapFeatureExtractor,c.ClapModel,c.ClapPreTrainedModel,c.ClapTextModelWithProjection,c.ClassifierFreeGuidanceLogitsProcessor,c.CodeGenForCausalLM,c.CodeGenModel,c.CodeGenPreTrainedModel,c.CodeGenTokenizer,c.CodeLlamaTokenizer,c.CohereForCausalLM,c.CohereModel,c.CoherePreTrainedModel,c.CohereTokenizer,c.ConvBertForMaskedLM,c.ConvBertForQuestionAnswering,c.ConvBertForSequenceClassification,c.ConvBertForTokenClassification,c.ConvBertModel,c.ConvBertPreTrainedModel,c.ConvBertTokenizer,c.ConvNextFeatureExtractor,c.ConvNextForImageClassification,c.ConvNextImageProcessor,c.ConvNextModel,c.ConvNextPreTrainedModel,c.ConvNextV2ForImageClassification,c.ConvNextV2Model,c.ConvNextV2PreTrainedModel,c.DPTFeatureExtractor,c.DPTForDepthEstimation,c.DPTImageProcessor,c.DPTModel,c.DPTPreTrainedModel,c.DebertaForMaskedLM,c.DebertaForQuestionAnswering,c.DebertaForSequenceClassification,c.DebertaForTokenClassification,c.DebertaModel,c.DebertaPreTrainedModel,c.DebertaTokenizer,c.DebertaV2ForMaskedLM,c.DebertaV2ForQuestionAnswering,c.DebertaV2ForSequenceClassification,c.DebertaV2ForTokenClassification,c.DebertaV2Model,c.DebertaV2PreTrainedModel,c.DebertaV2Tokenizer,c.DecisionTransformerModel,c.DecisionTransformerPreTrainedModel,c.DeiTFeatureExtractor,c.DeiTForImageClassification,c.DeiTImageProcessor,c.DeiTModel,c.DeiTPreTrainedModel,c.DepthAnythingForDepthEstimation,c.DepthAnythingPreTrainedModel,c.DepthEstimationPipeline,c.DepthProForDepthEstimation,c.DepthProPreTrainedModel,c.DetrFeatureExtractor,c.DetrForObjectDetection,c.DetrForSegmentation,c.DetrImageProcessor,c.DetrModel,c.DetrObjectDetectionOutput,c.DetrPreTrainedModel,c.DetrSegmentationOutput,c.Dinov2ForImageClassification,c.Dinov2Model,c.Dinov2PreTrainedModel,c.Dinov2WithRegistersForImageClassification,c.Dinov2WithRegistersModel,c.Dinov2WithRegistersPreTrainedModel,c.DistilBertForMaskedLM,c.DistilBertForQuestionAnswering,c.DistilBertForSequenceClassification,c.DistilBertForTokenClassification,c.DistilBertModel,c.DistilBertPreTrainedModel,c.DistilBertTokenizer,c.DocumentQuestionAnsweringPipeline,c.DonutFeatureExtractor,c.DonutImageProcessor,c.DonutSwinModel,c.DonutSwinPreTrainedModel,c.EfficientNetForImageClassification,c.EfficientNetImageProcessor,c.EfficientNetModel,c.EfficientNetPreTrainedModel,c.ElectraForMaskedLM,c.ElectraForQuestionAnswering,c.ElectraForSequenceClassification,c.ElectraForTokenClassification,c.ElectraModel,c.ElectraPreTrainedModel,c.ElectraTokenizer,c.EosTokenCriteria,c.EsmForMaskedLM,c.EsmForSequenceClassification,c.EsmForTokenClassification,c.EsmModel,c.EsmPreTrainedModel,c.EsmTokenizer,c.ExaoneForCausalLM,c.ExaoneModel,c.ExaonePreTrainedModel,c.FFT,c.FalconForCausalLM,c.FalconModel,c.FalconPreTrainedModel,c.FalconTokenizer,c.FastViTForImageClassification,c.FastViTModel,c.FastViTPreTrainedModel,c.FeatureExtractionPipeline,c.FeatureExtractor,c.FillMaskPipeline,c.Florence2ForConditionalGeneration,c.Florence2PreTrainedModel,c.Florence2Processor,c.ForcedBOSTokenLogitsProcessor,c.ForcedEOSTokenLogitsProcessor,c.GLPNFeatureExtractor,c.GLPNForDepthEstimation,c.GLPNModel,c.GLPNPreTrainedModel,c.GPT2LMHeadModel,c.GPT2Model,c.GPT2PreTrainedModel,c.GPT2Tokenizer,c.GPTBigCodeForCausalLM,c.GPTBigCodeModel,c.GPTBigCodePreTrainedModel,c.GPTJForCausalLM,c.GPTJModel,c.GPTJPreTrainedModel,c.GPTNeoForCausalLM,c.GPTNeoModel,c.GPTNeoPreTrainedModel,c.GPTNeoXForCausalLM,c.GPTNeoXModel,c.GPTNeoXPreTrainedModel,c.GPTNeoXTokenizer,c.Gemma2ForCausalLM,c.Gemma2Model,c.Gemma2PreTrainedModel,c.GemmaForCausalLM,c.GemmaModel,c.GemmaPreTrainedModel,c.GemmaTokenizer,c.GraniteForCausalLM,c.GraniteModel,c.GranitePreTrainedModel,c.Grok1Tokenizer,c.GroundingDinoForObjectDetection,c.GroundingDinoImageProcessor,c.GroundingDinoPreTrainedModel,c.GroundingDinoProcessor,c.GroupViTModel,c.GroupViTPreTrainedModel,c.HerbertTokenizer,c.HieraForImageClassification,c.HieraModel,c.HieraPreTrainedModel,c.HubertForCTC,c.HubertForSequenceClassification,c.HubertModel,c.HubertPreTrainedModel,c.IJepaForImageClassification,c.IJepaModel,c.IJepaPreTrainedModel,c.Idefics3ForConditionalGeneration,c.Idefics3ImageProcessor,c.Idefics3PreTrainedModel,c.Idefics3Processor,c.ImageClassificationPipeline,c.ImageFeatureExtractionPipeline,c.ImageFeatureExtractor,c.ImageMattingOutput,c.ImageProcessor,c.ImageSegmentationPipeline,c.ImageToImagePipeline,c.ImageToTextPipeline,c.InterruptableStoppingCriteria,c.JAISLMHeadModel,c.JAISModel,c.JAISPreTrainedModel,c.JinaCLIPImageProcessor,c.JinaCLIPModel,c.JinaCLIPPreTrainedModel,c.JinaCLIPProcessor,c.JinaCLIPTextModel,c.JinaCLIPVisionModel,c.LlamaForCausalLM,c.LlamaModel,c.LlamaPreTrainedModel,c.LlamaTokenizer,c.LlavaForConditionalGeneration,c.LlavaOnevisionForConditionalGeneration,c.LlavaOnevisionImageProcessor,c.LlavaPreTrainedModel,c.LogitsProcessor,c.LogitsProcessorList,c.LogitsWarper,c.LongT5ForConditionalGeneration,c.LongT5Model,c.LongT5PreTrainedModel,c.M2M100ForConditionalGeneration,c.M2M100Model,c.M2M100PreTrainedModel,c.M2M100Tokenizer,c.MBart50Tokenizer,c.MBartForCausalLM,c.MBartForConditionalGeneration,c.MBartForSequenceClassification,c.MBartModel,c.MBartPreTrainedModel,c.MBartTokenizer,c.MPNetForMaskedLM,c.MPNetForQuestionAnswering,c.MPNetForSequenceClassification,c.MPNetForTokenClassification,c.MPNetModel,c.MPNetPreTrainedModel,c.MPNetTokenizer,c.MT5ForConditionalGeneration,c.MT5Model,c.MT5PreTrainedModel,c.MarianMTModel,c.MarianModel,c.MarianPreTrainedModel,c.MarianTokenizer,c.Mask2FormerImageProcessor,c.MaskFormerFeatureExtractor,c.MaskFormerForInstanceSegmentation,c.MaskFormerImageProcessor,c.MaskFormerModel,c.MaskFormerPreTrainedModel,c.MaskedLMOutput,c.MaxLengthCriteria,c.MgpstrForSceneTextRecognition,c.MgpstrModelOutput,c.MgpstrPreTrainedModel,c.MgpstrProcessor,c.MgpstrTokenizer,c.MinLengthLogitsProcessor,c.MinNewTokensLengthLogitsProcessor,c.MistralForCausalLM,c.MistralModel,c.MistralPreTrainedModel,c.MobileBertForMaskedLM,c.MobileBertForQuestionAnswering,c.MobileBertForSequenceClassification,c.MobileBertModel,c.MobileBertPreTrainedModel,c.MobileBertTokenizer,c.MobileLLMForCausalLM,c.MobileLLMModel,c.MobileLLMPreTrainedModel,c.MobileNetV1FeatureExtractor,c.MobileNetV1ForImageClassification,c.MobileNetV1ImageProcessor,c.MobileNetV1Model,c.MobileNetV1PreTrainedModel,c.MobileNetV2FeatureExtractor,c.MobileNetV2ForImageClassification,c.MobileNetV2ImageProcessor,c.MobileNetV2Model,c.MobileNetV2PreTrainedModel,c.MobileNetV3FeatureExtractor,c.MobileNetV3ForImageClassification,c.MobileNetV3ImageProcessor,c.MobileNetV3Model,c.MobileNetV3PreTrainedModel,c.MobileNetV4FeatureExtractor,c.MobileNetV4ForImageClassification,c.MobileNetV4ImageProcessor,c.MobileNetV4Model,c.MobileNetV4PreTrainedModel,c.MobileViTFeatureExtractor,c.MobileViTForImageClassification,c.MobileViTImageProcessor,c.MobileViTModel,c.MobileViTPreTrainedModel,c.MobileViTV2ForImageClassification,c.MobileViTV2Model,c.MobileViTV2PreTrainedModel,c.ModelOutput,c.ModernBertForMaskedLM,c.ModernBertForSequenceClassification,c.ModernBertForTokenClassification,c.ModernBertModel,c.ModernBertPreTrainedModel,c.Moondream1ForConditionalGeneration,c.MoonshineFeatureExtractor,c.MoonshineForConditionalGeneration,c.MoonshineModel,c.MoonshinePreTrainedModel,c.MoonshineProcessor,c.MptForCausalLM,c.MptModel,c.MptPreTrainedModel,c.MultiModalityCausalLM,c.MultiModalityPreTrainedModel,c.MusicgenForCausalLM,c.MusicgenForConditionalGeneration,c.MusicgenModel,c.MusicgenPreTrainedModel,c.NllbTokenizer,c.NoBadWordsLogitsProcessor,c.NoRepeatNGramLogitsProcessor,c.NomicBertModel,c.NomicBertPreTrainedModel,c.NougatImageProcessor,c.NougatTokenizer,c.OPTForCausalLM,c.OPTModel,c.OPTPreTrainedModel,c.ObjectDetectionPipeline,c.Olmo2ForCausalLM,c.Olmo2Model,c.Olmo2PreTrainedModel,c.OlmoForCausalLM,c.OlmoModel,c.OlmoPreTrainedModel,c.OpenELMForCausalLM,c.OpenELMModel,c.OpenELMPreTrainedModel,c.OwlViTFeatureExtractor,c.OwlViTForObjectDetection,c.OwlViTImageProcessor,c.OwlViTModel,c.OwlViTPreTrainedModel,c.OwlViTProcessor,c.Owlv2ForObjectDetection,c.Owlv2ImageProcessor,c.Owlv2Model,c.Owlv2PreTrainedModel,c.PaliGemmaForConditionalGeneration,c.PaliGemmaPreTrainedModel,c.PaliGemmaProcessor,c.PatchTSMixerForPrediction,c.PatchTSMixerModel,c.PatchTSMixerPreTrainedModel,c.PatchTSTForPrediction,c.PatchTSTModel,c.PatchTSTPreTrainedModel,c.Phi3ForCausalLM,c.Phi3Model,c.Phi3PreTrainedModel,c.Phi3VForCausalLM,c.Phi3VImageProcessor,c.Phi3VPreTrainedModel,c.Phi3VProcessor,c.PhiForCausalLM,c.PhiModel,c.PhiPreTrainedModel,c.Pipeline,c.PreTrainedModel,c.PreTrainedTokenizer,c.PretrainedConfig,c.PretrainedMixin,c.Processor,c.PvtForImageClassification,c.PvtImageProcessor,c.PvtModel,c.PvtPreTrainedModel,c.PyAnnoteFeatureExtractor,c.PyAnnoteForAudioFrameClassification,c.PyAnnoteModel,c.PyAnnotePreTrainedModel,c.PyAnnoteProcessor,c.QuestionAnsweringModelOutput,c.QuestionAnsweringPipeline,c.Qwen2ForCausalLM,c.Qwen2Model,c.Qwen2PreTrainedModel,c.Qwen2Tokenizer,c.Qwen2VLForConditionalGeneration,c.Qwen2VLImageProcessor,c.Qwen2VLPreTrainedModel,c.Qwen2VLProcessor,c.RTDetrForObjectDetection,c.RTDetrImageProcessor,c.RTDetrModel,c.RTDetrObjectDetectionOutput,c.RTDetrPreTrainedModel,c.RawAudio,c.RawImage,c.RepetitionPenaltyLogitsProcessor,c.ResNetForImageClassification,c.ResNetModel,c.ResNetPreTrainedModel,c.RoFormerForMaskedLM,c.RoFormerForQuestionAnswering,c.RoFormerForSequenceClassification,c.RoFormerForTokenClassification,c.RoFormerModel,c.RoFormerPreTrainedModel,c.RoFormerTokenizer,c.RobertaForMaskedLM,c.RobertaForQuestionAnswering,c.RobertaForSequenceClassification,c.RobertaForTokenClassification,c.RobertaModel,c.RobertaPreTrainedModel,c.RobertaTokenizer,c.SamImageProcessor,c.SamImageSegmentationOutput,c.SamModel,c.SamPreTrainedModel,c.SamProcessor,c.SapiensForDepthEstimation,c.SapiensForNormalEstimation,c.SapiensForSemanticSegmentation,c.SapiensPreTrainedModel,c.SeamlessM4TFeatureExtractor,c.SegformerFeatureExtractor,c.SegformerForImageClassification,c.SegformerForSemanticSegmentation,c.SegformerImageProcessor,c.SegformerModel,c.SegformerPreTrainedModel,c.Seq2SeqLMOutput,c.SequenceClassifierOutput,c.SiglipImageProcessor,c.SiglipModel,c.SiglipPreTrainedModel,c.SiglipTextModel,c.SiglipTokenizer,c.SiglipVisionModel,c.SpeechT5FeatureExtractor,c.SpeechT5ForSpeechToText,c.SpeechT5ForTextToSpeech,c.SpeechT5HifiGan,c.SpeechT5Model,c.SpeechT5PreTrainedModel,c.SpeechT5Processor,c.SpeechT5Tokenizer,c.SqueezeBertForMaskedLM,c.SqueezeBertForQuestionAnswering,c.SqueezeBertForSequenceClassification,c.SqueezeBertModel,c.SqueezeBertPreTrainedModel,c.SqueezeBertTokenizer,c.StableLmForCausalLM,c.StableLmModel,c.StableLmPreTrainedModel,c.Starcoder2ForCausalLM,c.Starcoder2Model,c.Starcoder2PreTrainedModel,c.StoppingCriteria,c.StoppingCriteriaList,c.StyleTextToSpeech2Model,c.StyleTextToSpeech2PreTrainedModel,c.SummarizationPipeline,c.SuppressTokensAtBeginLogitsProcessor,c.Swin2SRForImageSuperResolution,c.Swin2SRImageProcessor,c.Swin2SRModel,c.Swin2SRPreTrainedModel,c.SwinForImageClassification,c.SwinModel,c.SwinPreTrainedModel,c.T5ForConditionalGeneration,c.T5Model,c.T5PreTrainedModel,c.T5Tokenizer,c.TableTransformerForObjectDetection,c.TableTransformerModel,c.TableTransformerObjectDetectionOutput,c.TableTransformerPreTrainedModel,c.TemperatureLogitsWarper,c.Tensor,c.Text2TextGenerationPipeline,c.TextClassificationPipeline,c.TextGenerationPipeline;var sf=c.TextStreamer;c.TextToAudioPipeline,c.TokenClassificationPipeline,c.TokenClassifierOutput,c.TokenizerModel,c.TopKLogitsWarper,c.TopPLogitsWarper,c.TrOCRForCausalLM,c.TrOCRPreTrainedModel,c.TranslationPipeline,c.UniSpeechForCTC,c.UniSpeechForSequenceClassification,c.UniSpeechModel,c.UniSpeechPreTrainedModel,c.UniSpeechSatForAudioFrameClassification,c.UniSpeechSatForCTC,c.UniSpeechSatForSequenceClassification,c.UniSpeechSatModel,c.UniSpeechSatPreTrainedModel,c.VLChatProcessor,c.VLMImageProcessor,c.ViTFeatureExtractor,c.ViTForImageClassification,c.ViTImageProcessor,c.ViTMAEModel,c.ViTMAEPreTrainedModel,c.ViTMSNForImageClassification,c.ViTMSNModel,c.ViTMSNPreTrainedModel,c.ViTModel,c.ViTPreTrainedModel,c.VisionEncoderDecoderModel,c.VitMatteForImageMatting,c.VitMatteImageProcessor,c.VitMattePreTrainedModel,c.VitPoseForPoseEstimation,c.VitPoseImageProcessor,c.VitPosePreTrainedModel,c.VitsModel,c.VitsModelOutput,c.VitsPreTrainedModel,c.VitsTokenizer,c.Wav2Vec2BertForCTC,c.Wav2Vec2BertForSequenceClassification,c.Wav2Vec2BertModel,c.Wav2Vec2BertPreTrainedModel,c.Wav2Vec2CTCTokenizer,c.Wav2Vec2FeatureExtractor,c.Wav2Vec2ForAudioFrameClassification,c.Wav2Vec2ForCTC,c.Wav2Vec2ForSequenceClassification,c.Wav2Vec2Model,c.Wav2Vec2PreTrainedModel,c.Wav2Vec2ProcessorWithLM,c.WavLMForAudioFrameClassification,c.WavLMForCTC,c.WavLMForSequenceClassification,c.WavLMForXVector,c.WavLMModel,c.WavLMPreTrainedModel,c.WeSpeakerFeatureExtractor,c.WeSpeakerResNetModel,c.WeSpeakerResNetPreTrainedModel,c.WhisperFeatureExtractor,c.WhisperForConditionalGeneration,c.WhisperModel,c.WhisperPreTrainedModel,c.WhisperProcessor,c.WhisperTextStreamer,c.WhisperTimeStampLogitsProcessor,c.WhisperTokenizer,c.XLMForQuestionAnswering,c.XLMForSequenceClassification,c.XLMForTokenClassification,c.XLMModel,c.XLMPreTrainedModel,c.XLMRobertaForMaskedLM,c.XLMRobertaForQuestionAnswering,c.XLMRobertaForSequenceClassification,c.XLMRobertaForTokenClassification,c.XLMRobertaModel,c.XLMRobertaPreTrainedModel,c.XLMRobertaTokenizer,c.XLMTokenizer,c.XLMWithLMHeadModel,c.XVectorOutput,c.YolosFeatureExtractor,c.YolosForObjectDetection,c.YolosImageProcessor,c.YolosModel,c.YolosObjectDetectionOutput,c.YolosPreTrainedModel,c.ZeroShotAudioClassificationPipeline,c.ZeroShotClassificationPipeline,c.ZeroShotImageClassificationPipeline,c.ZeroShotObjectDetectionPipeline,c.bankers_round,c.cat,c.cos_sim,c.dot,c.dynamic_time_warping,c.env,c.full,c.full_like,c.getKeyValueShapes,c.hamming,c.hanning,c.interpolate,c.interpolate_4d,c.interpolate_data,c.is_chinese_char,c.layer_norm,c.load_image,c.log_softmax,c.magnitude,c.matmul,c.max,c.mean,c.mean_pooling,c.medianFilter,c.mel_filter_bank,c.min,c.ones,c.ones_like,c.permute,c.permute_data;var rf=c.pipeline;c.quantize_embeddings,c.rand,c.read_audio,c.rfft,c.round,c.slice,c.softmax,c.spectrogram,c.stack,c.std_mean,c.topk,c.window_function,c.zeros,c.zeros_like;class Bc{static async getInstance(A=null){return this.instance??(this.instance=rf(this.task,this.model,{progress_callback:A})),this.instance}}fe(Bc,"task","translation"),fe(Bc,"model","Xenova/nllb-200-distilled-600M"),fe(Bc,"instance",null),self.addEventListener("message",async ze=>{const A=await Bc.getInstance(D=>{self.postMessage(D)}),r=new sf(A.tokenizer,{skip_prompt:!0,skip_special_tokens:!0,callback_function:function(D){self.postMessage({status:"update",output:D})}}),_=await A(ze.data.text,{tgt_lang:ze.data.tgt_lang,src_lang:ze.data.src_lang,streamer:r});self.postMessage({status:"complete",output:_})})})(); diff --git a/index.html b/index.html index b93f7aa3d580d92b8fe36fe759393b9b63d3b2a1..fe9064cc53f2f92bdac61fa784e9169c4762fcc2 100644 --- a/index.html +++ b/index.html @@ -4,11 +4,10 @@ Transformers.js - Sample react application - - + +
-