deepar 5.5.2 → 5.6.0-alpha-141
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/VERSION.txt +1 -1
- package/js/deepar.esm.js +1 -1
- package/js/deepar.js +1 -1
- package/js/dynamicModules/mediaPipe.js +1 -1
- package/js/dynamicModules/xzimg.js +1 -1
- package/js/types/DeepAR.d.ts +17 -0
- package/js/types/initParams.d.ts +6 -0
- package/js/types/version.d.ts +1 -1
- package/package.json +1 -1
- package/wasm/deepar.wasm +0 -0
- package/wasm/dyArcoreImageLoader.wasm +0 -0
- package/wasm/dyArcorePhysics.wasm +0 -0
- package/wasm/dyArcoreScripting.wasm +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/*! For license information please see xzimg.js.LICENSE.txt */
|
|
2
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.__deeparDynamicJsModule_xzimg__=t():e.__deeparDynamicJsModule_xzimg__=t()}(self,(()=>(()=>{var e={683:()=>{},345:()=>{}},t={};function n(r){var a=t[r];if(void 0!==a)return a.exports;var s=t[r]={exports:{}};return e[r](s,s.exports,n),s.exports}n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};return(()=>{"use strict";function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if("default"!==n&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}}))})),Object.freeze(e)}n.r(r),n.d(r,{Foot:()=>LN,Geometry:()=>HN,Segmentation:()=>gk,VideoManager:()=>i});var t=function(){return t=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n])Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},t.apply(this,arguments)};function a(e,t,n,r){return new(n||(n=Promise))((function(a,s){function o(e){try{u(r.next(e))}catch(e){s(e)}}function i(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?a(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,i)}u((r=r.apply(e,t||[])).next())}))}function s(e,t){var n,r,a,s,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,i[0]&&(o=0)),o;)try{if(n=1,r&&(a=2&i[0]?r.return:i[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[2&i[0],a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!((a=(a=o.trys).length>0&&a[a.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break}a[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],r=0}finally{n=a=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}}function o(e,t,n){if(n||2===arguments.length)for(var r,a=0,s=t.length;a<s;a++)!r&&a in t||(r||(r=Array.prototype.slice.call(t,0,a)),r[a]=t[a]);return e.concat(r||Array.prototype.slice.call(t))}var i=function(){function e(e,t,n){this.NB_BUFFERS=5,this._videoFrames=[],this._nbFramesDelay=0,this._videoElement=e,this._videoCanvas=document.createElement("canvas"),this._videoCanvas.style.display="none",this._videoCanvasContext=this._videoCanvas.getContext("2d",{willReadFrequently:!0}),null!=t&&(this._videoCanvas.width=t),null!=n&&(this._videoCanvas.height=n)}return e.prototype.getNbFramesDelay=function(){return this._nbFramesDelay},e.prototype.setNbFramesDelay=function(e){e>=0&&e<this.NB_BUFFERS?this._nbFramesDelay=e:console.error("Invalid frames delay, delay must be less than ",this.NB_BUFFERS)},e.prototype.getVideoCanvas=function(){return this._videoCanvas},e.prototype.preProcessWithBuffer=function(e){return this._videoFrames.length===this.NB_BUFFERS&&(this._videoFrames=this._videoFrames.slice(0,-1)),this._videoFrames=o([e],this._videoFrames,!0),!0},e.prototype.preProcess=function(){if(null==this._videoElement||0===this._videoElement.videoWidth||0===this._videoElement.videoHeight)return!1;this._videoCanvas.width===this._videoElement.videoWidth&&this._videoCanvas.height===this._videoElement.videoHeight||(this._videoFrames=[],this._videoCanvas.width=this._videoElement.videoWidth,this._videoCanvas.height=this._videoElement.videoHeight),this._videoCanvasContext.drawImage(this._videoElement,0,0,this._videoCanvas.width,this._videoCanvas.height);var e=this._videoCanvasContext.getImageData(0,0,this._videoCanvas.width,this._videoCanvas.height);return this._videoFrames.length===this.NB_BUFFERS&&(this._videoFrames=this._videoFrames.slice(0,-1)),this._videoFrames=o([e],this._videoFrames,!0),!0},e.prototype.postProcess=function(){if(this._nbFramesDelay>0&&this._videoFrames.length>0){var e=this._nbFramesDelay<this._videoFrames.length?this._videoFrames[this._nbFramesDelay]:this._videoFrames[this._videoFrames.length-1];this._videoCanvasContext.putImageData(e,0,0)}},e.prototype.getCameraFrame=function(){if(this._nbFramesDelay>0&&this._videoFrames.length>0)return this._nbFramesDelay<this._videoFrames.length?this._videoFrames[this._nbFramesDelay]:this._videoFrames[this._videoFrames.length-1]},e.prototype.updateDelay=function(e){e>=0&&e<this.NB_BUFFERS?this._nbFramesDelay=e:console.error("Invalid frames delay, delay must be less than ",this.NB_BUFFERS)},e.prototype.getLastBuffer=function(){return this._videoFrames.length>0?this._videoFrames[0]:null},e.prototype.setOverlapingImage=function(e){this._videoCanvasContext.putImageData(e,10,10)},e}(),u=function(e,t){return u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},u(e,t)};function l(e,t){function n(){this.constructor=e}u(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function c(e){return"function"==typeof e}var p=!1,h={Promise:void 0,set useDeprecatedSynchronousErrorHandling(e){e&&(new Error).stack,p=e},get useDeprecatedSynchronousErrorHandling(){return p}};function d(e){setTimeout((function(){throw e}),0)}var f={closed:!0,next:function(e){},error:function(e){if(h.useDeprecatedSynchronousErrorHandling)throw e;d(e)},complete:function(){}},m=Array.isArray||function(e){return e&&"number"==typeof e.length};function g(e){return null!==e&&"object"==typeof e}var y=function(){function e(e){return Error.call(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=e,this}return e.prototype=Object.create(Error.prototype),e}(),b=y,_=function(){function e(e){this.closed=!1,this._parentOrParents=null,this._subscriptions=null,e&&(this._ctorUnsubscribe=!0,this._unsubscribe=e)}return e.prototype.unsubscribe=function(){var t;if(!this.closed){var n=this,r=n._parentOrParents,a=n._ctorUnsubscribe,s=n._unsubscribe,o=n._subscriptions;if(this.closed=!0,this._parentOrParents=null,this._subscriptions=null,r instanceof e)r.remove(this);else if(null!==r)for(var i=0;i<r.length;++i)r[i].remove(this);if(c(s)){a&&(this._unsubscribe=void 0);try{s.call(this)}catch(e){t=e instanceof b?x(e.errors):[e]}}if(m(o)){i=-1;for(var u=o.length;++i<u;){var l=o[i];if(g(l))try{l.unsubscribe()}catch(e){t=t||[],e instanceof b?t=t.concat(x(e.errors)):t.push(e)}}}if(t)throw new b(t)}},e.prototype.add=function(t){var n=t;if(!t)return e.EMPTY;switch(typeof t){case"function":n=new e(t);case"object":if(n===this||n.closed||"function"!=typeof n.unsubscribe)return n;if(this.closed)return n.unsubscribe(),n;if(!(n instanceof e)){var r=n;(n=new e)._subscriptions=[r]}break;default:throw new Error("unrecognized teardown "+t+" added to Subscription.")}var a=n._parentOrParents;if(null===a)n._parentOrParents=this;else if(a instanceof e){if(a===this)return n;n._parentOrParents=[a,this]}else{if(-1!==a.indexOf(this))return n;a.push(this)}var s=this._subscriptions;return null===s?this._subscriptions=[n]:s.push(n),n},e.prototype.remove=function(e){var t=this._subscriptions;if(t){var n=t.indexOf(e);-1!==n&&t.splice(n,1)}},e.EMPTY=function(e){return e.closed=!0,e}(new e),e}();function x(e){return e.reduce((function(e,t){return e.concat(t instanceof b?t.errors:t)}),[])}var v="function"==typeof Symbol?Symbol("rxSubscriber"):"@@rxSubscriber_"+Math.random(),w=function(e){function t(n,r,a){var s=e.call(this)||this;switch(s.syncErrorValue=null,s.syncErrorThrown=!1,s.syncErrorThrowable=!1,s.isStopped=!1,arguments.length){case 0:s.destination=f;break;case 1:if(!n){s.destination=f;break}if("object"==typeof n){n instanceof t?(s.syncErrorThrowable=n.syncErrorThrowable,s.destination=n,n.add(s)):(s.syncErrorThrowable=!0,s.destination=new T(s,n));break}default:s.syncErrorThrowable=!0,s.destination=new T(s,n,r,a)}return s}return l(t,e),t.prototype[v]=function(){return this},t.create=function(e,n,r){var a=new t(e,n,r);return a.syncErrorThrowable=!1,a},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this))},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){this.destination.error(e),this.unsubscribe()},t.prototype._complete=function(){this.destination.complete(),this.unsubscribe()},t.prototype._unsubscribeAndRecycle=function(){var e=this._parentOrParents;return this._parentOrParents=null,this.unsubscribe(),this.closed=!1,this.isStopped=!1,this._parentOrParents=e,this},t}(_),T=function(e){function t(t,n,r,a){var s,o=e.call(this)||this;o._parentSubscriber=t;var i=o;return c(n)?s=n:n&&(s=n.next,r=n.error,a=n.complete,n!==f&&(c((i=Object.create(n)).unsubscribe)&&o.add(i.unsubscribe.bind(i)),i.unsubscribe=o.unsubscribe.bind(o))),o._context=i,o._next=s,o._error=r,o._complete=a,o}return l(t,e),t.prototype.next=function(e){if(!this.isStopped&&this._next){var t=this._parentSubscriber;h.useDeprecatedSynchronousErrorHandling&&t.syncErrorThrowable?this.__tryOrSetError(t,this._next,e)&&this.unsubscribe():this.__tryOrUnsub(this._next,e)}},t.prototype.error=function(e){if(!this.isStopped){var t=this._parentSubscriber,n=h.useDeprecatedSynchronousErrorHandling;if(this._error)n&&t.syncErrorThrowable?(this.__tryOrSetError(t,this._error,e),this.unsubscribe()):(this.__tryOrUnsub(this._error,e),this.unsubscribe());else if(t.syncErrorThrowable)n?(t.syncErrorValue=e,t.syncErrorThrown=!0):d(e),this.unsubscribe();else{if(this.unsubscribe(),n)throw e;d(e)}}},t.prototype.complete=function(){var e=this;if(!this.isStopped){var t=this._parentSubscriber;if(this._complete){var n=function(){return e._complete.call(e._context)};h.useDeprecatedSynchronousErrorHandling&&t.syncErrorThrowable?(this.__tryOrSetError(t,n),this.unsubscribe()):(this.__tryOrUnsub(n),this.unsubscribe())}else this.unsubscribe()}},t.prototype.__tryOrUnsub=function(e,t){try{e.call(this._context,t)}catch(e){if(this.unsubscribe(),h.useDeprecatedSynchronousErrorHandling)throw e;d(e)}},t.prototype.__tryOrSetError=function(e,t,n){if(!h.useDeprecatedSynchronousErrorHandling)throw new Error("bad call");try{t.call(this._context,n)}catch(t){return h.useDeprecatedSynchronousErrorHandling?(e.syncErrorValue=t,e.syncErrorThrown=!0,!0):(d(t),!0)}return!1},t.prototype._unsubscribe=function(){var e=this._parentSubscriber;this._context=null,this._parentSubscriber=null,e.unsubscribe()},t}(w),k="function"==typeof Symbol&&Symbol.observable||"@@observable";function I(e){return e}var S=function(){function e(e){this._isScalar=!1,e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var r=this.operator,a=function(e,t,n){if(e){if(e instanceof w)return e;if(e[v])return e[v]()}return e||t||n?new w(e,t,n):new w(f)}(e,t,n);if(r?a.add(r.call(a,this.source)):a.add(this.source||h.useDeprecatedSynchronousErrorHandling&&!a.syncErrorThrowable?this._subscribe(a):this._trySubscribe(a)),h.useDeprecatedSynchronousErrorHandling&&a.syncErrorThrowable&&(a.syncErrorThrowable=!1,a.syncErrorThrown))throw a.syncErrorValue;return a},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){h.useDeprecatedSynchronousErrorHandling&&(e.syncErrorThrown=!0,e.syncErrorValue=t),function(e){for(;e;){var t=e,n=t.closed,r=t.destination,a=t.isStopped;if(n||a)return!1;e=r&&r instanceof w?r:null}return!0}(e)?e.error(t):console.warn(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=E(t))((function(t,r){var a;a=n.subscribe((function(t){try{e(t)}catch(e){r(e),a&&a.unsubscribe()}}),r,t)}))},e.prototype._subscribe=function(e){var t=this.source;return t&&t.subscribe(e)},e.prototype[k]=function(){return this},e.prototype.pipe=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return 0===t.length?this:(0===(e=t).length?I:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)})(this)},e.prototype.toPromise=function(e){var t=this;return new(e=E(e))((function(e,n){var r;t.subscribe((function(e){return r=e}),(function(e){return n(e)}),(function(){return e(r)}))}))},e.create=function(t){return new e(t)},e}();function E(e){if(e||(e=h.Promise||Promise),!e)throw new Error("no Promise impl found");return e}var N=function(e){return function(t){for(var n=0,r=e.length;n<r&&!t.closed;n++)t.next(e[n]);t.complete()}},C="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator",A=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function R(e){return!!e&&"function"!=typeof e.subscribe&&"function"==typeof e.then}var $=function(e){if(e&&"function"==typeof e[k])return r=e,function(e){var t=r[k]();if("function"!=typeof t.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return t.subscribe(e)};if(A(e))return N(e);if(R(e))return n=e,function(e){return n.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,d),e};if(e&&"function"==typeof e[C])return t=e,function(e){for(var n=t[C]();;){var r=void 0;try{r=n.next()}catch(t){return e.error(t),e}if(r.done){e.complete();break}if(e.next(r.value),e.closed)break}return"function"==typeof n.return&&e.add((function(){n.return&&n.return()})),e};var t,n,r,a=g(e)?"an invalid object":"'"+e+"'";throw new TypeError("You provided "+a+" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.")},M=function(e){function t(t){var n=e.call(this)||this;return n.parent=t,n}return l(t,e),t.prototype._next=function(e){this.parent.notifyNext(e)},t.prototype._error=function(e){this.parent.notifyError(e),this.unsubscribe()},t.prototype._complete=function(){this.parent.notifyComplete(),this.unsubscribe()},t}(w),F=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l(t,e),t.prototype.notifyNext=function(e){this.destination.next(e)},t.prototype.notifyError=function(e){this.destination.error(e)},t.prototype.notifyComplete=function(){this.destination.complete()},t}(w);function O(e){return e&&"function"==typeof e.schedule}var D=function(e){function t(t,n,r){var a=e.call(this)||this;return a.parent=t,a.outerValue=n,a.outerIndex=r,a.index=0,a}return l(t,e),t.prototype._next=function(e){this.parent.notifyNext(this.outerValue,e,this.outerIndex,this.index++,this)},t.prototype._error=function(e){this.parent.notifyError(e,this),this.unsubscribe()},t.prototype._complete=function(){this.parent.notifyComplete(this),this.unsubscribe()},t}(w);function L(e,t,n,r,a){if(void 0===a&&(a=new D(e,n,r)),!a.closed)return t instanceof S?t.subscribe(a):$(t)(a)}var P=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l(t,e),t.prototype.notifyNext=function(e,t,n,r,a){this.destination.next(t)},t.prototype.notifyError=function(e,t){this.destination.error(e)},t.prototype.notifyComplete=function(e){this.destination.complete()},t}(w);function B(e,t){return new S((function(n){var r=new _,a=0;return r.add(t.schedule((function(){a!==e.length?(n.next(e[a++]),n.closed||r.add(this.schedule())):n.complete()}))),r}))}function U(e,t){return t?B(e,t):new S(N(e))}var z={};function V(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=void 0,r=void 0;return O(e[e.length-1])&&(r=e.pop()),"function"==typeof e[e.length-1]&&(n=e.pop()),1===e.length&&m(e[0])&&(e=e[0]),U(e,r).lift(new W(n))}var W=function(){function e(e){this.resultSelector=e}return e.prototype.call=function(e,t){return t.subscribe(new H(e,this.resultSelector))},e}(),H=function(e){function t(t,n){var r=e.call(this,t)||this;return r.resultSelector=n,r.active=0,r.values=[],r.observables=[],r}return l(t,e),t.prototype._next=function(e){this.values.push(z),this.observables.push(e)},t.prototype._complete=function(){var e=this.observables,t=e.length;if(0===t)this.destination.complete();else{this.active=t,this.toRespond=t;for(var n=0;n<t;n++){var r=e[n];this.add(L(this,r,void 0,n))}}},t.prototype.notifyComplete=function(e){0==(this.active-=1)&&this.destination.complete()},t.prototype.notifyNext=function(e,t,n){var r=this.values,a=r[n],s=this.toRespond?a===z?--this.toRespond:this.toRespond:0;r[n]=t,0===s&&(this.resultSelector?this._tryResultSelector(r):this.destination.next(r.slice()))},t.prototype._tryResultSelector=function(e){var t;try{t=this.resultSelector.apply(this,e)}catch(e){return void this.destination.error(e)}this.destination.next(t)},t}(P);function G(e,t){return t?function(e,t){if(null!=e){if(function(e){return e&&"function"==typeof e[k]}(e))return function(e,t){return new S((function(n){var r=new _;return r.add(t.schedule((function(){var a=e[k]();r.add(a.subscribe({next:function(e){r.add(t.schedule((function(){return n.next(e)})))},error:function(e){r.add(t.schedule((function(){return n.error(e)})))},complete:function(){r.add(t.schedule((function(){return n.complete()})))}}))}))),r}))}(e,t);if(R(e))return function(e,t){return new S((function(n){var r=new _;return r.add(t.schedule((function(){return e.then((function(e){r.add(t.schedule((function(){n.next(e),r.add(t.schedule((function(){return n.complete()})))})))}),(function(e){r.add(t.schedule((function(){return n.error(e)})))}))}))),r}))}(e,t);if(A(e))return B(e,t);if(function(e){return e&&"function"==typeof e[C]}(e)||"string"==typeof e)return function(e,t){if(!e)throw new Error("Iterable cannot be null");return new S((function(n){var r,a=new _;return a.add((function(){r&&"function"==typeof r.return&&r.return()})),a.add(t.schedule((function(){r=e[C](),a.add(t.schedule((function(){if(!n.closed){var e,t;try{var a=r.next();e=a.value,t=a.done}catch(e){return void n.error(e)}t?n.complete():(n.next(e),this.schedule())}})))}))),a}))}(e,t)}throw new TypeError((null!==e&&typeof e||e)+" is not observable")}(e,t):e instanceof S?e:new S($(e))}function j(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e[e.length-1];return O(n)?(e.pop(),B(e,n)):U(e)}function K(e,t){return function(n){if("function"!=typeof e)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return n.lift(new q(e,t))}}var q=function(){function e(e,t){this.project=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new X(e,this.project,this.thisArg))},e}(),X=function(e){function t(t,n,r){var a=e.call(this,t)||this;return a.project=n,a.count=0,a.thisArg=r||a,a}return l(t,e),t.prototype._next=function(e){var t;try{t=this.project.call(this.thisArg,e,this.count++)}catch(e){return void this.destination.error(e)}this.destination.next(t)},t}(w),Y=new S((function(e){return e.complete()}));function Q(e,t){return new S(t?function(n){return t.schedule(J,0,{error:e,subscriber:n})}:function(t){return t.error(e)})}function J(e){var t=e.error;e.subscriber.error(t)}function Z(e){return function(t){return t.lift(new ee(e))}}var ee=function(){function e(e){this.callback=e}return e.prototype.call=function(e,t){return t.subscribe(new te(e,this.callback))},e}(),te=function(e){function t(t,n){var r=e.call(this,t)||this;return r.add(new _(n)),r}return l(t,e),t}(w),ne=function(){function e(){return Error.call(this),this.message="object unsubscribed",this.name="ObjectUnsubscribedError",this}return e.prototype=Object.create(Error.prototype),e}(),re=function(e){function t(t,n){var r=e.call(this)||this;return r.subject=t,r.subscriber=n,r.closed=!1,r}return l(t,e),t.prototype.unsubscribe=function(){if(!this.closed){this.closed=!0;var e=this.subject,t=e.observers;if(this.subject=null,t&&0!==t.length&&!e.isStopped&&!e.closed){var n=t.indexOf(this.subscriber);-1!==n&&t.splice(n,1)}}},t}(_),ae=function(e){function t(t){var n=e.call(this,t)||this;return n.destination=t,n}return l(t,e),t}(w),se=function(e){function t(){var t=e.call(this)||this;return t.observers=[],t.closed=!1,t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return l(t,e),t.prototype[v]=function(){return new ae(this)},t.prototype.lift=function(e){var t=new oe(this,this);return t.operator=e,t},t.prototype.next=function(e){if(this.closed)throw new ne;if(!this.isStopped)for(var t=this.observers,n=t.length,r=t.slice(),a=0;a<n;a++)r[a].next(e)},t.prototype.error=function(e){if(this.closed)throw new ne;this.hasError=!0,this.thrownError=e,this.isStopped=!0;for(var t=this.observers,n=t.length,r=t.slice(),a=0;a<n;a++)r[a].error(e);this.observers.length=0},t.prototype.complete=function(){if(this.closed)throw new ne;this.isStopped=!0;for(var e=this.observers,t=e.length,n=e.slice(),r=0;r<t;r++)n[r].complete();this.observers.length=0},t.prototype.unsubscribe=function(){this.isStopped=!0,this.closed=!0,this.observers=null},t.prototype._trySubscribe=function(t){if(this.closed)throw new ne;return e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){if(this.closed)throw new ne;return this.hasError?(e.error(this.thrownError),_.EMPTY):this.isStopped?(e.complete(),_.EMPTY):(this.observers.push(e),new re(this,e))},t.prototype.asObservable=function(){var e=new S;return e.source=this,e},t.create=function(e,t){return new oe(e,t)},t}(S),oe=function(e){function t(t,n){var r=e.call(this)||this;return r.destination=t,r.source=n,r}return l(t,e),t.prototype.next=function(e){var t=this.destination;t&&t.next&&t.next(e)},t.prototype.error=function(e){var t=this.destination;t&&t.error&&this.destination.error(e)},t.prototype.complete=function(){var e=this.destination;e&&e.complete&&this.destination.complete()},t.prototype._subscribe=function(e){return this.source?this.source.subscribe(e):_.EMPTY},t}(se),ie=function(e){function t(t){var n=e.call(this)||this;return n._value=t,n}return l(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!0,configurable:!0}),t.prototype._subscribe=function(t){var n=e.prototype._subscribe.call(this,t);return n&&!n.closed&&t.next(this._value),n},t.prototype.getValue=function(){if(this.hasError)throw this.thrownError;if(this.closed)throw new ne;return this._value},t.prototype.next=function(t){e.prototype.next.call(this,this._value=t)},t}(se);function ue(e){return void 0===e&&(e=-1),function(t){return t.lift(new le(e,t))}}var le=function(){function e(e,t){this.count=e,this.source=t}return e.prototype.call=function(e,t){return t.subscribe(new ce(e,this.count,this.source))},e}(),ce=function(e){function t(t,n,r){var a=e.call(this,t)||this;return a.count=n,a.source=r,a}return l(t,e),t.prototype.error=function(t){if(!this.isStopped){var n=this.source,r=this.count;if(0===r)return e.prototype.error.call(this,t);r>-1&&(this.count=r-1),n.subscribe(this._unsubscribeAndRecycle())}},t}(w);function pe(e,t){return"function"==typeof t?function(n){return n.pipe(pe((function(n,r){return G(e(n,r)).pipe(K((function(e,a){return t(n,e,r,a)})))})))}:function(t){return t.lift(new he(e))}}var he=function(){function e(e){this.project=e}return e.prototype.call=function(e,t){return t.subscribe(new de(e,this.project))},e}(),de=function(e){function t(t,n){var r=e.call(this,t)||this;return r.project=n,r.index=0,r}return l(t,e),t.prototype._next=function(e){var t,n=this.index++;try{t=this.project(e,n)}catch(e){return void this.destination.error(e)}this._innerSub(t)},t.prototype._innerSub=function(e){var t=this.innerSubscription;t&&t.unsubscribe();var n=new M(this),r=this.destination;r.add(n),this.innerSubscription=function(e,t){if(!t.closed){if(e instanceof S)return e.subscribe(t);var n;try{n=$(e)(t)}catch(e){t.error(e)}return n}}(e,n),this.innerSubscription!==n&&r.add(this.innerSubscription)},t.prototype._complete=function(){var t=this.innerSubscription;t&&!t.closed||e.prototype._complete.call(this),this.unsubscribe()},t.prototype._unsubscribe=function(){this.innerSubscription=void 0},t.prototype.notifyComplete=function(){this.innerSubscription=void 0,this.isStopped&&e.prototype._complete.call(this)},t.prototype.notifyNext=function(e){this.destination.next(e)},t}(F);function fe(){}function me(e,t,n){return function(r){return r.lift(new ge(e,t,n))}}var ge=function(){function e(e,t,n){this.nextOrObserver=e,this.error=t,this.complete=n}return e.prototype.call=function(e,t){return t.subscribe(new ye(e,this.nextOrObserver,this.error,this.complete))},e}(),ye=function(e){function t(t,n,r,a){var s=e.call(this,t)||this;return s._tapNext=fe,s._tapError=fe,s._tapComplete=fe,s._tapError=r||fe,s._tapComplete=a||fe,c(n)?(s._context=s,s._tapNext=n):n&&(s._context=n,s._tapNext=n.next||fe,s._tapError=n.error||fe,s._tapComplete=n.complete||fe),s}return l(t,e),t.prototype._next=function(e){try{this._tapNext.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.next(e)},t.prototype._error=function(e){try{this._tapError.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.error(e)},t.prototype._complete=function(){try{this._tapComplete.call(this._context)}catch(e){return void this.destination.error(e)}return this.destination.complete()},t}(w);function be(e){return new S((function(t){var n;try{n=e()}catch(e){return void t.error(e)}return(n?G(n):Y).subscribe(t)}))}var _e=void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function xe(){throw new Error("setTimeout has not been defined")}function ve(){throw new Error("clearTimeout has not been defined")}var we=xe,Te=ve;function ke(e){if(we===setTimeout)return setTimeout(e,0);if((we===xe||!we)&&setTimeout)return we=setTimeout,setTimeout(e,0);try{return we(e,0)}catch(t){try{return we.call(null,e,0)}catch(t){return we.call(this,e,0)}}}"function"==typeof _e.setTimeout&&(we=setTimeout),"function"==typeof _e.clearTimeout&&(Te=clearTimeout);var Ie,Se=[],Ee=!1,Ne=-1;function Ce(){Ee&&Ie&&(Ee=!1,Ie.length?Se=Ie.concat(Se):Ne=-1,Se.length&&Ae())}function Ae(){if(!Ee){var e=ke(Ce);Ee=!0;for(var t=Se.length;t;){for(Ie=Se,Se=[];++Ne<t;)Ie&&Ie[Ne].run();Ne=-1,t=Se.length}Ie=null,Ee=!1,function(e){if(Te===clearTimeout)return clearTimeout(e);if((Te===ve||!Te)&&clearTimeout)return Te=clearTimeout,clearTimeout(e);try{return Te(e)}catch(t){try{return Te.call(null,e)}catch(t){return Te.call(this,e)}}}(e)}}function Re(e,t){this.fun=e,this.array=t}function $e(){}Re.prototype.run=function(){this.fun.apply(null,this.array)};var Me=$e,Fe=$e,Oe=$e,De=$e,Le=$e,Pe=$e,Be=$e,Ue=_e.performance||{},ze=Ue.now||Ue.mozNow||Ue.msNow||Ue.oNow||Ue.webkitNow||function(){return(new Date).getTime()},Ve=new Date,We={nextTick:function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];Se.push(new Re(e,t)),1!==Se.length||Ee||ke(Ae)},title:"browser",browser:!0,env:{},argv:[],version:"",versions:{},on:Me,addListener:Fe,once:Oe,off:De,removeListener:Le,removeAllListeners:Pe,emit:Be,binding:function(e){throw new Error("process.binding is not supported")},cwd:function(){return"/"},chdir:function(e){throw new Error("process.chdir is not supported")},umask:function(){return 0},hrtime:function(e){var t=.001*ze.call(Ue),n=Math.floor(t),r=Math.floor(t%1*1e9);return e&&(n-=e[0],(r-=e[1])<0&&(n--,r+=1e9)),[n,r]},platform:"browser",release:{},config:{},uptime:function(){return(new Date-Ve)/1e3}},He=We;class Ge{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class je{refCount(e){return Ke("refCount")}incRef(e){return Ke("incRef")}timerAvailable(){return!0}time(e){return Ke("time")}read(e){return Ke("read")}readSync(e){return Ke("readSync")}readToGPU(e,t){return Ke("readToGPU")}numDataIds(){return Ke("numDataIds")}disposeData(e,t){return Ke("disposeData")}write(e,t,n){return Ke("write")}move(e,t,n,r,a){return Ke("move")}createTensorFromGPUData(e,t,n){return Ke("createTensorFromGPUData")}memory(){return Ke("memory")}floatPrecision(){return Ke("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return Ke("dispose")}}function Ke(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function qe(e,t,n){return Math.max(e,Math.min(t,n))}function Xe(e){return e%2==0?e:e+1}function Ye(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function Qe(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function Je(e,t,n=""){Qe(tt(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function Ze(e){Qe(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function et(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function tt(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function nt(e){return e%1==0}function rt(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function at(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function st(e,t=(e=>0),n,r){return new Promise(((a,s)=>{let o=0;const i=()=>{if(e())return void a();o++;const u=t(o);null!=n&&o>=n?s():null!=r?r(i,u):setTimeout(i,u)};i()}))}function ot(e,t){let n=1,r=-1;for(let t=0;t<e.length;++t)if(e[t]>=0)n*=e[t];else if(-1===e[t]){if(-1!==r)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${t}`);r=t}else if(e[t]<0)throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`);if(-1===r){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const a=e.slice();return a[r]=t/n,a}function it(e,t){const n=t.length;return Qe((e=null==e?t.map(((e,t)=>t)):[].concat(e)).every((e=>e>=-n&&e<n)),(()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),Qe(e.every((e=>nt(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function ut(e,t){const n=[],r=[],a=null!=t&&Array.isArray(t)&&0===t.length,s=null==t||a?null:it(t,e).sort();let o=0;for(let t=0;t<e.length;++t){if(null!=s){if(s[o]===t&&1!==e[t])throw new Error(`Can't squeeze axis ${t} since its dim '${e[t]}' is not 1`);(null==s[o]||s[o]>t)&&1===e[t]&&(n.push(e[t]),r.push(t)),s[o]<=t&&o++}1!==e[t]&&(n.push(e[t]),r.push(t))}return{newShape:n,keptDims:r}}function lt(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else{if("bool"!==e)throw new Error(`Unknown data type ${e}`);n=new Uint8Array(t)}return n}function ct(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error(`Unknown data type ${e}`);n=new Array(t)}return n}function pt(e,t){return!("complex64"===t||"float32"===t&&"complex64"!==e||"int32"===t&&"float32"!==e&&"complex64"!==e||"bool"===t&&"bool"===e)}function ht(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error(`Unknown dtype ${e}`)}function dt(e){return"string"==typeof e||e instanceof String}function ft(e){return Array.isArray(e)?ft(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":"number"==typeof e?"float32":dt(e)?"string":function(e){return"boolean"==typeof e}(e)?"bool":"float32"}function mt(e){return!!(e&&e.constructor&&e.call&&e.apply)}function gt(e,t){for(let n=t;n<e;++n)if(e%n==0)return n;return e}function yt(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}function bt(e,t,n,r=!1){const a=new Array;if(1===t.length){const s=t[0]*(r?2:1);for(let t=0;t<s;t++)a[t]=n[e+t]}else{const s=t[0],o=t.slice(1),i=o.reduce(((e,t)=>e*t))*(r?2:1);for(let t=0;t<s;t++)a[t]=bt(e+t*i,o,n,r)}return a}function _t(e,t,n=!1){if(0===e.length)return t[0];const r=e.reduce(((e,t)=>e*t))*(n?2:1);if(0===r)return[];if(r!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return bt(0,e,t,n)}function xt(e,t){const n=vt(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}function vt(e,t){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t)return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function wt(e){e.forEach((t=>{Qe(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function Tt(e,t,n){if(0===t)return 0;if(1===t)return e[0];let r=e[e.length-1];for(let t=0;t<e.length-1;++t)r+=n[t]*e[t];return r}function kt(e,t,n){if(0===t)return[];if(1===t)return[e];const r=new Array(t);for(let t=0;t<r.length-1;++t)r[t]=Math.floor(e/n[t]),e-=r[t]*n[t];return r[r.length-1]=e,r}function It(e){return e&&e.then&&"function"==typeof e.then}const St="tfjsflags";class Et{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=Nt,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(Ct().getBool("IS_TEST")||Ct().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},null!=this.urlFlags[e]){const t=this.urlFlags[e];Ct().getBool("IS_TEST")||Ct().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${t}.`),this.set(e,t)}}async getAsync(e){return e in this.flags||(this.flags[e]=await this.evaluateFlag(e)),this.flags[e]}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(It(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(null==this.flagRegistry[e])throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(null==this.flagRegistry[e])throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(void 0===this.global||void 0===this.global.location||void 0===this.global.location.search)return;const e=this.getQueryParams(this.global.location.search);St in e&&e[St].split(",").forEach((e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){if("true"===(t=t.toLowerCase())||"false"===t)return"true"===t;if(""+ +t===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}(t,n)}))}}function Nt(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,((e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("=")))),t}function Ct(){return Rt}let At,Rt=null;function $t(){if(null==At){let e;if("undefined"!=typeof window)e=window;else if(void 0!==_e)e=_e;else if(void 0!==He)e=He;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}At=e}return At}function Mt(e,t){const n=function(){const e=$t();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const r=t();return n.set(e,r),n.get(e)}}const Ft="Add",Ot="AddN",Dt="All",Lt="Any",Pt="ArgMax",Bt="AvgPool",Ut="BatchMatMul",zt="BatchToSpaceND",Vt="Cast",Wt="Ceil",Ht="ClipByValue",Gt="Concat",jt="Conv2D",Kt="Conv2DBackpropInput",qt="Cosh",Xt="Cumprod",Yt="Cumsum",Qt="CropAndResize",Jt="DepthToSpace",Zt="DepthwiseConv2dNative",en="RealDiv",tn="Elu",nn="Equal",rn="Exp",an="ExpandDims",sn="Fill",on="FlipLeftRight",un="Floor",ln="FloorDiv",cn="FusedBatchNorm",pn="GatherV2",hn="GatherNd",dn="Greater",fn="GreaterEqual",mn="Identity",gn="IsNan",yn="LeakyRelu",bn="Less",_n="LessEqual",xn="LogicalAnd",vn="LogicalNot",wn="LogicalOr",Tn="Max",kn="Maximum",In="MaxPool",Sn="Mean",En="Min",Nn="Minimum",Cn="MirrorPad",An="Multiply",Rn="NotEqual",$n="NonMaxSuppressionV3",Mn="NonMaxSuppressionV4",Fn="NonMaxSuppressionV5",On="OnesLike",Dn="OneHot",Ln="Pack",Pn="PadV2",Bn="Prelu",Un="Prod",zn="Range",Vn="Reciprocal",Wn="Relu",Hn="Reshape",Gn="ResizeNearestNeighbor",jn="ResizeBilinear",Kn="Relu6",qn="Reverse",Xn="Round",Yn="Rsqrt",Qn="ScatterNd",Jn="Select",Zn="Slice",er="Sigmoid",tr="Sqrt",nr="Sum",rr="SpaceToBatchND",ar="SplitV",sr="Softmax",or="SparseFillEmptyRows",ir="SparseReshape",ur="SparseSegmentMean",lr="SparseSegmentSum",cr="SquaredDifference",pr="StridedSlice",hr="StringNGrams",dr="StringSplit",fr="StringToHashBucketFast",mr="Sub",gr="Tanh",yr="Tile",br="TopK",_r="Transform",xr="Transpose",vr="Unpack",wr="ZerosLike",Tr="Step",kr="FromPixels",Ir="RotateWithOffset",Sr="_FusedMatMul",Er="FusedConv2D",Nr="FusedDepthwiseConv2D";function Cr(...e){Ct().getBool("IS_TEST")||Ct().getBool("PROD")||console.warn(...e)}const Ar=Mt("kernelRegistry",(()=>new Map)),Rr=Mt("gradRegistry",(()=>new Map));function $r(e,t){const n=Dr(e,t);return Ar.get(n)}function Mr(e){return Rr.get(e)}function Fr(e){const t=Ar.entries(),n=[];for(;;){const{done:r,value:a}=t.next();if(r)break;const[s,o]=a,[i]=s.split("_");i===e&&n.push(o)}return n}function Or(e){const{kernelName:t,backendName:n}=e,r=Dr(t,n);Ar.has(r)&&Cr(`The kernel '${t}' for backend '${n}' is already registered`),Ar.set(r,e)}function Dr(e,t){return`${t}_${e}`}var Lr=Br,Pr=null;try{Pr=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(e){}function Br(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function Ur(e){return!0===(e&&e.__isLong__)}Br.prototype.__isLong__,Object.defineProperty(Br.prototype,"__isLong__",{value:!0}),Br.isLong=Ur;var zr={},Vr={};function Wr(e,t){var n,r,a;return t?(a=0<=(e>>>=0)&&e<256)&&(r=Vr[e])?r:(n=Gr(e,(0|e)<0?-1:0,!0),a&&(Vr[e]=n),n):(a=-128<=(e|=0)&&e<128)&&(r=zr[e])?r:(n=Gr(e,e<0?-1:0,!1),a&&(zr[e]=n),n)}function Hr(e,t){if(isNaN(e))return t?ea:Zr;if(t){if(e<0)return ea;if(e>=Yr)return sa}else{if(e<=-Qr)return oa;if(e+1>=Qr)return aa}return e<0?Hr(-e,t).neg():Gr(e%Xr|0,e/Xr|0,t)}function Gr(e,t,n){return new Br(e,t,n)}Br.fromInt=Wr,Br.fromNumber=Hr,Br.fromBits=Gr;var jr=Math.pow;function Kr(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return Zr;if("number"==typeof t?(n=t,t=!1):t=!!t,(n=n||10)<2||36<n)throw RangeError("radix");var r;if((r=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===r)return Kr(e.substring(1),t,n).neg();for(var a=Hr(jr(n,8)),s=Zr,o=0;o<e.length;o+=8){var i=Math.min(8,e.length-o),u=parseInt(e.substring(o,o+i),n);if(i<8){var l=Hr(jr(n,i));s=s.mul(l).add(Hr(u))}else s=(s=s.mul(a)).add(Hr(u))}return s.unsigned=t,s}function qr(e,t){return"number"==typeof e?Hr(e,t):"string"==typeof e?Kr(e,t):Gr(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}Br.fromString=Kr,Br.fromValue=qr;var Xr=4294967296,Yr=Xr*Xr,Qr=Yr/2,Jr=Wr(1<<24),Zr=Wr(0);Br.ZERO=Zr;var ea=Wr(0,!0);Br.UZERO=ea;var ta=Wr(1);Br.ONE=ta;var na=Wr(1,!0);Br.UONE=na;var ra=Wr(-1);Br.NEG_ONE=ra;var aa=Gr(-1,2147483647,!1);Br.MAX_VALUE=aa;var sa=Gr(-1,-1,!0);Br.MAX_UNSIGNED_VALUE=sa;var oa=Gr(0,-2147483648,!1);Br.MIN_VALUE=oa;var ia=Br.prototype;ia.toInt=function(){return this.unsigned?this.low>>>0:this.low},ia.toNumber=function(){return this.unsigned?(this.high>>>0)*Xr+(this.low>>>0):this.high*Xr+(this.low>>>0)},ia.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(oa)){var t=Hr(e),n=this.div(t),r=n.mul(t).sub(this);return n.toString(e)+r.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var a=Hr(jr(e,6),this.unsigned),s=this,o="";;){var i=s.div(a),u=(s.sub(i.mul(a)).toInt()>>>0).toString(e);if((s=i).isZero())return u+o;for(;u.length<6;)u="0"+u;o=""+u+o}},ia.getHighBits=function(){return this.high},ia.getHighBitsUnsigned=function(){return this.high>>>0},ia.getLowBits=function(){return this.low},ia.getLowBitsUnsigned=function(){return this.low>>>0},ia.getNumBitsAbs=function(){if(this.isNegative())return this.eq(oa)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<<t);t--);return 0!=this.high?t+33:t+1},ia.isZero=function(){return 0===this.high&&0===this.low},ia.eqz=ia.isZero,ia.isNegative=function(){return!this.unsigned&&this.high<0},ia.isPositive=function(){return this.unsigned||this.high>=0},ia.isOdd=function(){return 1==(1&this.low)},ia.isEven=function(){return 0==(1&this.low)},ia.equals=function(e){return Ur(e)||(e=qr(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low},ia.eq=ia.equals,ia.notEquals=function(e){return!this.eq(e)},ia.neq=ia.notEquals,ia.ne=ia.notEquals,ia.lessThan=function(e){return this.comp(e)<0},ia.lt=ia.lessThan,ia.lessThanOrEqual=function(e){return this.comp(e)<=0},ia.lte=ia.lessThanOrEqual,ia.le=ia.lessThanOrEqual,ia.greaterThan=function(e){return this.comp(e)>0},ia.gt=ia.greaterThan,ia.greaterThanOrEqual=function(e){return this.comp(e)>=0},ia.gte=ia.greaterThanOrEqual,ia.ge=ia.greaterThanOrEqual,ia.compare=function(e){if(Ur(e)||(e=qr(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},ia.comp=ia.compare,ia.negate=function(){return!this.unsigned&&this.eq(oa)?oa:this.not().add(ta)},ia.neg=ia.negate,ia.add=function(e){Ur(e)||(e=qr(e));var t=this.high>>>16,n=65535&this.high,r=this.low>>>16,a=65535&this.low,s=e.high>>>16,o=65535&e.high,i=e.low>>>16,u=0,l=0,c=0,p=0;return c+=(p+=a+(65535&e.low))>>>16,l+=(c+=r+i)>>>16,u+=(l+=n+o)>>>16,u+=t+s,Gr((c&=65535)<<16|(p&=65535),(u&=65535)<<16|(l&=65535),this.unsigned)},ia.subtract=function(e){return Ur(e)||(e=qr(e)),this.add(e.neg())},ia.sub=ia.subtract,ia.multiply=function(e){if(this.isZero())return Zr;if(Ur(e)||(e=qr(e)),Pr)return Gr(Pr.mul(this.low,this.high,e.low,e.high),Pr.get_high(),this.unsigned);if(e.isZero())return Zr;if(this.eq(oa))return e.isOdd()?oa:Zr;if(e.eq(oa))return this.isOdd()?oa:Zr;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Jr)&&e.lt(Jr))return Hr(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,n=65535&this.high,r=this.low>>>16,a=65535&this.low,s=e.high>>>16,o=65535&e.high,i=e.low>>>16,u=65535&e.low,l=0,c=0,p=0,h=0;return p+=(h+=a*u)>>>16,c+=(p+=r*u)>>>16,p&=65535,c+=(p+=a*i)>>>16,l+=(c+=n*u)>>>16,c&=65535,l+=(c+=r*i)>>>16,c&=65535,l+=(c+=a*o)>>>16,l+=t*u+n*i+r*o+a*s,Gr((p&=65535)<<16|(h&=65535),(l&=65535)<<16|(c&=65535),this.unsigned)},ia.mul=ia.multiply,ia.divide=function(e){if(Ur(e)||(e=qr(e)),e.isZero())throw Error("division by zero");var t,n,r;if(Pr)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?Gr((this.unsigned?Pr.div_u:Pr.div_s)(this.low,this.high,e.low,e.high),Pr.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?ea:Zr;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return ea;if(e.gt(this.shru(1)))return na;r=ea}else{if(this.eq(oa))return e.eq(ta)||e.eq(ra)?oa:e.eq(oa)?ta:(t=this.shr(1).div(e).shl(1)).eq(Zr)?e.isNegative()?ta:ra:(n=this.sub(e.mul(t)),r=t.add(n.div(e)));if(e.eq(oa))return this.unsigned?ea:Zr;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();r=Zr}for(n=this;n.gte(e);){t=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(t)/Math.LN2),s=a<=48?1:jr(2,a-48),o=Hr(t),i=o.mul(e);i.isNegative()||i.gt(n);)i=(o=Hr(t-=s,this.unsigned)).mul(e);o.isZero()&&(o=ta),r=r.add(o),n=n.sub(i)}return r},ia.div=ia.divide,ia.modulo=function(e){return Ur(e)||(e=qr(e)),Pr?Gr((this.unsigned?Pr.rem_u:Pr.rem_s)(this.low,this.high,e.low,e.high),Pr.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},ia.mod=ia.modulo,ia.rem=ia.modulo,ia.not=function(){return Gr(~this.low,~this.high,this.unsigned)},ia.and=function(e){return Ur(e)||(e=qr(e)),Gr(this.low&e.low,this.high&e.high,this.unsigned)},ia.or=function(e){return Ur(e)||(e=qr(e)),Gr(this.low|e.low,this.high|e.high,this.unsigned)},ia.xor=function(e){return Ur(e)||(e=qr(e)),Gr(this.low^e.low,this.high^e.high,this.unsigned)},ia.shiftLeft=function(e){return Ur(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Gr(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):Gr(0,this.low<<e-32,this.unsigned)},ia.shl=ia.shiftLeft,ia.shiftRight=function(e){return Ur(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Gr(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):Gr(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},ia.shr=ia.shiftRight,ia.shiftRightUnsigned=function(e){if(Ur(e)&&(e=e.toInt()),0==(e&=63))return this;var t=this.high;return e<32?Gr(this.low>>>e|t<<32-e,t>>>e,this.unsigned):Gr(32===e?t:t>>>e-32,0,this.unsigned)},ia.shru=ia.shiftRightUnsigned,ia.shr_u=ia.shiftRightUnsigned,ia.toSigned=function(){return this.unsigned?Gr(this.low,this.high,!1):this},ia.toUnsigned=function(){return this.unsigned?this:Gr(this.low,this.high,!0)},ia.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},ia.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},ia.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},Br.fromBytes=function(e,t,n){return n?Br.fromBytesLE(e,t):Br.fromBytesBE(e,t)},Br.fromBytesLE=function(e,t){return new Br(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},Br.fromBytesBE=function(e,t){return new Br(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};const ua=Lr||e({__proto__:null,default:Lr},[Lr]);function la(e){return ua.fromString(e,!0,16)}const ca=la("c3a5c85c97cb3127"),pa=la("b492b66fbe98f273"),ha=la("9ae16a3b2f90404f");function da(e){return e.xor(e.shru(47))}function fa(e,t,n){const r=e.slice(t,t+n);return ua.fromBytes(Array.from(r),!0,!0)}function ma(e,t){return fa(e,t,8)}function ga(e,t){return fa(e,t,4)}function ya(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function ba(e,t,n=la("9ddfea08eb382d69")){let r=e.xor(t).mul(n);r=r.xor(r.shru(47));let a=t.xor(r).mul(n);return a=a.xor(a.shru(47)),a=a.mul(n),a}function _a(e,t,n,r){return function(e,t,n,r,a,s){a=a.add(e),s=ya(s.add(a).add(r),21);const o=a;return a=(a=a.add(t)).add(n),s=s.add(ya(a,44)),[a.add(r),s.add(o)]}(ma(e,t),ma(e,t+8),ma(e,t+16),ma(e,t+24),n,r)}function xa(e,t=e.length){const n=ua.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=ha.add(2*t),r=ma(e,0).add(ha),a=ma(e,t-8);return ba(ya(a,37).mul(n).add(r),ya(r,25).add(a).mul(n),n)}if(t>=4){const n=ha.add(2*t);return ba(ga(e,0).shl(3).add(t),ga(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),r=t+(e[t-1]<<2);return da(ha.mul(n).xor(ca.mul(r))).mul(ha)}return ha}(e,t):function(e,t=e.length){const n=ha.add(2*t),r=ma(e,0).mul(pa),a=ma(e,8),s=ma(e,t-8).mul(n),o=ma(e,t-16).mul(ha);return ba(ya(r.add(a),43).add(ya(s,30)).add(o),r.add(ya(a.add(ha),18)).add(s),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=ha.add(2*t),r=ma(e,0).mul(ha),a=ma(e,8),s=ma(e,t-8).mul(n),o=ma(e,t-16).mul(ha),i=ya(r.add(a),43).add(ya(s,30)).add(o),u=ba(i,r.add(ya(a.add(ha),18)).add(s),n),l=ma(e,16).mul(n),c=ma(e,24),p=i.add(ma(e,t-32)).mul(n),h=u.add(ma(e,t-24)).mul(n);return ba(ya(l.add(c),43).add(ya(p,30)).add(h),l.add(ya(c.add(r),18)).add(p),n)}(e,t);let r=n,a=n.mul(pa).add(113),s=da(a.mul(ha).add(113)).mul(ha),o=[ua.UZERO,ua.UZERO],i=[ua.UZERO,ua.UZERO];r=r.mul(ha).add(ma(e,0));let u=0;const l=64*(t-1>>6),c=l+(t-1&63)-63;do{r=ya(r.add(a).add(o[0]).add(ma(e,u+8)),37).mul(pa),a=ya(a.add(o[1]).add(ma(e,u+48)),42).mul(pa),r=r.xor(i[1]),a=a.add(o[0]).add(ma(e,u+40)),s=ya(s.add(i[0]),33).mul(pa),o=_a(e,u,o[1].mul(pa),r.add(i[0])),i=_a(e,u+32,s.add(i[1]),a.add(ma(e,u+16))),[s,r]=[r,s],u+=64}while(u!==l);const p=pa.add(s.and(255).shl(1));return u=c,i[0]=i[0].add(t-1&63),o[0]=o[0].add(i[0]),i[0]=i[0].add(o[0]),r=ya(r.add(a).add(o[0]).add(ma(e,u+8)),37).mul(p),a=ya(a.add(o[1]).add(ma(e,u+48)),42).mul(p),r=r.xor(i[1].mul(9)),a=a.add(o[0].mul(9).add(ma(e,u+40))),s=ya(s.add(i[0]),33).mul(p),o=_a(e,u,o[1].mul(p),r.add(i[0])),i=_a(e,u+32,s.add(i[1]),a.add(ma(e,u+16))),[s,r]=[r,s],ba(ba(o[0],i[0],p).add(da(a).mul(ca)).add(s),ba(o[1],i[1],p).add(r),p)}function va(e,t){return"string"===t?ka(e):wa([e],t)}function wa(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Ea(e)),Ct().getBool("DEBUG")&&function(e,t){for(let n=0;n<e.length;n++){const r=e[n];if(isNaN(r)||!isFinite(r))throw Error(`A tensor of type ${t} being uploaded contains ${r}.`)}}(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){const t=new Uint8Array(e.length);for(let n=0;n<t.length;++n)0!==Math.round(e[n])&&(t[n]=1);return t}throw new Error(`Unknown data type ${t}`)}function Ta(){return Ct().platform.now()}function ka(e,t="utf-8"){return t=t||"utf-8",Ct().platform.encode(e,t)}function Ia(e,t="utf-8"){return t=t||"utf-8",Ct().platform.decode(e,t)}function Sa(e){return Ct().platform.isTypedArray(e)}function Ea(e,t=[],n=!1){if(null==t&&(t=[]),"boolean"==typeof e||"number"==typeof e||"string"==typeof e||It(e)||null==e||Sa(e)&&n)t.push(e);else if(Array.isArray(e)||Sa(e))for(let r=0;r<e.length;++r)Ea(e[r],t,n);else{let r=-1;for(const t of Object.keys(e))/^([1-9]+[0-9]*|0)$/.test(t)&&(r=Math.max(r,Number(t)));for(let a=0;a<=r;a++)Ea(e[a],t,n)}return t}class Na{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new Aa)}profileKernel(e,t,n){let r;const a=()=>{r=n()};let s;const o=Ta();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(a);else{a();for(const e of r)e.dataSync();s=Promise.resolve({kernelMs:Ta()-o})}if(Ct().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<r.length;t++){const n=r[t];n.data().then((t=>{Ca(t,n.dtype,e)}))}return{kernelName:e,outputs:r,inputs:t,timeMs:s.then((e=>e.kernelMs)),extraInfo:s.then((e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():""))}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:a,extraInfo:s}=e;n.forEach((e=>{Promise.all([e.data(),r,s]).then((n=>{this.logger.logKernelProfile(t,e,n[0],n[1],a,n[2])}))}))}}function Ca(e,t,n){if("float32"!==t)return!1;for(let t=0;t<e.length;t++){const r=e[t];if(isNaN(r)||!isFinite(r))return console.warn(`Found ${r} in the result of '${n}'`),!0}return!1}class Aa{logKernelProfile(e,t,n,r,a,s){const o="number"==typeof r?at(`${r}ms`,9):r.error,i=at(e,25),u=t.rank,l=t.size,c=at(t.shape.toString(),14);let p="";for(const e in a){const n=a[e];if(null!=n){const r=n.shape||t.shape,a=r.length;p+=`${e}: ${a}D ${a>0?r:""} `}}console.log(`%c${i}\t%c${o}\t%c${u}D ${c}\t%c${l}\t%c${p}\t%c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}const Ra=20,$a=3,Ma=7;function Fa(e,t,n,r){const a=yt(t),s=function(e,t,n,r){const a=et(t),s=r[r.length-1],o=new Array(s).fill(0),i=t.length,u="complex64"===n?Pa(e):e;if(i>1)for(let e=0;e<a/s;e++){const t=e*s;for(let e=0;e<s;e++)o[e]=Math.max(o[e],Oa(u[t+e],0,n).length)}return o}(e,t,n,a),o=t.length,i=La(e,t,n,a,s),u=["Tensor"];return r&&(u.push(` dtype: ${n}`),u.push(` rank: ${o}`),u.push(` shape: [${t}]`),u.push(" values:")),u.push(i.map((e=>" "+e)).join("\n")),u.join("\n")}function Oa(e,t,n){let r;return r=Array.isArray(e)?`${parseFloat(e[0].toFixed(Ma))} + ${parseFloat(e[1].toFixed(Ma))}j`:dt(e)?`'${e}'`:"bool"===n?Da(e):parseFloat(e.toFixed(Ma)).toString(),at(r,t)}function Da(e){return 0===e?"false":"true"}function La(e,t,n,r,a,s=!0){const o="complex64"===n?2:1,i=t[0],u=t.length;if(0===u)return"complex64"===n?[Oa(Pa(e)[0],0,n)]:"bool"===n?[Da(e[0])]:[e[0].toString()];if(1===u){if(i>Ra){const t=$a*o;let r=Array.from(e.slice(0,t)),s=Array.from(e.slice((i-$a)*o,i*o));return"complex64"===n&&(r=Pa(r),s=Pa(s)),["["+r.map(((e,t)=>Oa(e,a[t],n))).join(", ")+", ..., "+s.map(((e,t)=>Oa(e,a[i-$a+t],n))).join(", ")+"]"]}return["["+("complex64"===n?Pa(e):Array.from(e)).map(((e,t)=>Oa(e,a[t],n))).join(", ")+"]"]}const l=t.slice(1),c=r.slice(1),p=r[0]*o,h=[];if(i>Ra){for(let t=0;t<$a;t++){const r=t*p,s=r+p;h.push(...La(e.slice(r,s),l,n,c,a,!1))}h.push("...");for(let t=i-$a;t<i;t++){const r=t*p,s=r+p;h.push(...La(e.slice(r,s),l,n,c,a,t===i-1))}}else for(let t=0;t<i;t++){const r=t*p,s=r+p;h.push(...La(e.slice(r,s),l,n,c,a,t===i-1))}const d=2===u?",":"";h[0]="["+(i>0?h[0]+d:"");for(let e=1;e<h.length-1;e++)h[e]=" "+h[e]+d;let f=",\n";for(let e=2;e<u;e++)f+="\n";return h[h.length-1]=" "+h[h.length-1]+"]"+(s?"":f),h}function Pa(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class Ba{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=et(e),null!=n){const e=n.length;Qe(e===this.size,(()=>`Length of values '${e}' does not match the size inferred by the shape '${this.size}'.`))}if("complex64"===t)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||ct(t,this.size),this.strides=yt(e)}set(e,...t){0===t.length&&(t=[0]),Qe(t.length===this.rank,(()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`));const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const t=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(t)}t++}let n=e[e.length-1];for(let t=0;t<e.length-1;++t)n+=this.strides[t]*e[t];return this.values[n]}locToIndex(e){if(0===this.rank)return 0;if(1===this.rank)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(0===this.rank)return[];if(1===this.rank)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Ua().makeTensor(this.values,this.shape,this.dtype)}}let Ua=null,za=null;class Va{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=et(e),this.strides=yt(e),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return za.buffer(this.shape,this.dtype,e)}bufferSync(){return za.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return _t(this.shape,e,"complex64"===this.dtype)}arraySync(){return _t(this.shape,this.dataSync(),"complex64"===this.dtype)}async data(){this.throwIfDisposed();const e=Ua().read(this.dataId);if("string"===this.dtype){const t=await e;try{return t.map((e=>Ia(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),Ua().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=Ua().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>Ia(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await Ua().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Ua().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return za.print(this,e)}clone(){return this.throwIfDisposed(),za.clone(this)}toString(e=!1){return Fa(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),za.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Ua().makeVariable(this,e,t,n)}}Object.defineProperty(Va,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),Mt("Tensor",(()=>Va));class Wa extends Va{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!tt(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Ua().disposeTensor(this),this.dataId=e.dataId,Ua().incRef(this,null)}dispose(){Ua().disposeVariable(this),this.isDisposedInternal=!0}}var Ha,Ga,ja,Ka,qa;Object.defineProperty(Wa,Symbol.hasInstance,{value:e=>e instanceof Va&&null!=e.assign&&e.assign instanceof Function}),function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"}(Ha||(Ha={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(Ga||(Ga={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(ja||(ja={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(Ka||(Ka={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(qa||(qa={}));const Xa={float32:Ka,int32:Ga,bool:ja,complex64:qa};function Ya(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Xa[e][t]}function Qa(e,t){if(e.dtype===t.dtype)return[e,t];const n=Ya(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function Ja(e){const t=[];return Za(e,t,new Set),t}function Za(e,t,n){if(null==e)return;if(e instanceof Va)return void t.push(e);if(r=e,!Array.isArray(r)&&"object"!=typeof r)return;var r;const a=e;for(const e in a){const r=a[e];n.has(r)||(n.add(r),Za(r,t,n))}}function es(e){return null!=e.kernelName}class ts{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map((e=>e.name))))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class ns{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new ts}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then((()=>{}));if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t];if(await this.initializeBackend(n).success)return void await this.setBackend(n)}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(null!=this.pendingBackendInit)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(null==this.backendInstance){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry)){if(!(e in this.registryFactory))return null;{const{asyncInit:t}=this.initializeBackend(e);if(t)return null}}return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(Cr(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(null==this.registryFactory[e])throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,null==this.registry[e]){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new Na(this.backendInstance),!0}setupRegisteredKernels(){Fr(this.backendName).forEach((e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){Fr(e).forEach((t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])}))}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(!n||n instanceof je||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,r=n.then((n=>!(t<this.pendingBackendInitId||(this.registry[e]=n,this.pendingBackendInit=null,0)))).catch((n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,Cr(`Initialization of backend ${e} failed`),Cr(n.stack||n.message)),!1)));return this.pendingBackendInit=r,{success:r,asyncInit:!0}}}catch(t){return Cr(`Initialization of backend ${e} failed`),Cr(t.stack||t.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort(((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority))}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:r,asyncInit:a}=this.initializeBackend(n);if(a||r)return{name:n,asyncInit:a}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),r=n.backend,a=this.readSync(t),s=r.refCount(t);r.disposeData(t,!0),n.backend=e,e.move(t,a,n.shape,n.dtype,s),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n,r=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");r=e}return this.scopedRun((()=>this.startScope(r)),(()=>this.endScope(n)),(()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n)))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(e){throw t(),e}}nextTensorId(){return ns.nextTensorId++}nextVariableId(){return ns.nextVariableId++}clone(e){const t=as.runKernel(mn,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e};return as.runKernel(Vt,t,{dtype:"float32"})}})),[],{}),t}runKernel(e,t,n){if(null==this.backendName&&this.backend,null==$r(e,this.backendName))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const r=this.backend.numDataIds();let a=0;n.forEach((e=>{a+="complex64"===e.dtype?3:1}));const s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=r-t-a-s;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const r=this.isTapeOn(),a=this.state.numBytes,s=this.state.numTensors;let o,i;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const u=es(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(es(e)){const{kernelName:t,inputs:a,attrs:s}=e;null==this.backendName&&this.backend;const u=$r(t,this.backendName);Qe(null!=u,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),o=()=>{const e=this.backend.numDataIds();i=u.kernelFunc({inputs:a,attrs:s,backend:this.backend});const o=Array.isArray(i)?i:[i];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,o);const l=o.map((e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e)));if(r){const e=this.getTensorsForGradient(t,a,l);n=this.saveTensorsForBackwardMode(e)}return l}}else{const{forwardFunc:t}=e,a=e=>{r&&(n=e.map((e=>this.keep(this.clone(e)))))};o=()=>{const e=this.backend.numDataIds();i=this.tidy((()=>t(this.backend,a)));const n=Array.isArray(i)?i:[i];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(u,e,n),n}}const{inputs:l,attrs:c}=e,p=es(e)?null:e.backwardsFunc;let h;return this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(h=this.profiler.profileKernel(u,l,(()=>o())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(h),t=h.outputs):t=o()})),r&&this.addTapeNode(u,l,t,p,n,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:u,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(l).map((e=>null!=l[e]?l[e].shape:null)),outputShapes:t.map((e=>e.shape)),kernelTimeMs:h.timeMs,extraInfo:h.extraInfo}),Array.isArray(i)?t:t[0]}saveTensorsForBackwardMode(e){return e.map((e=>this.keep(this.clone(e))))}getTensorsForGradient(e,t,n){const r=Mr(e);if(null!=r){const e=r.inputsToSave||[],a=r.outputsToSave||[];let s;r.saveAllInputs?(Qe(Array.isArray(t),(()=>"saveAllInputs is true, expected inputs to be an array.")),s=Object.keys(t).map((e=>t[e]))):s=e.map((e=>t[e]));const o=n.filter(((e,t)=>a[t]));return s.concat(o)}return[]}makeTensor(e,t,n,r){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let a=e;"string"===n&&dt(e[0])&&(a=e.map((e=>ka(e))));const s=r.write(a,t,n),o=new Va(t,n,s,this.nextTensorId());if(this.trackTensor(o,r),"string"===n){const e=this.state.tensorInfo.get(s),t=function(e){if(null==e)return 0;let t=0;return e.forEach((e=>t+=e.length)),t}(a);this.state.numBytes+=t-e.bytes,e.bytes=t}return o}makeTensorFromDataId(e,t,n,r){const a={dataId:e,shape:t,dtype:n=n||"float32"};return this.makeTensorFromTensorInfo(a,r)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:r,dtype:a}=e,s=new Va(r,a,n,this.nextTensorId());return this.trackTensor(s,t),s}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),null!=r&&r!==e.dtype&&(e=e.cast(r));const a=new Wa(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[a.name])throw new Error(`Variable with name ${a.name} was already registered`);return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*ht(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof Wa||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*ht(e.dtype);this.state.numBytes-=t}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map((e=>e.totalBytesSnapshot))),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const e of this.state.activeProfile.kernels)e.kernelTimeMs=await e.kernelTimeMs,e.extraInfo=await e.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,r,a,s){const o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:a},i=Mr(e);null!=i&&(r=i.gradFunc),null!=r&&(o.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],r=vt(e.size,e.dtype);return this.makeTensor(r,e.shape,e.dtype)}return e})),r(e.length>1?e:e[0],a,s))),this.state.activeTape.push(o)}keep(e){return e.kept=!0,e}startTape(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=Ja(e),n=new Set(t.map((e=>e.id)));for(let e=0;e<this.state.activeScope.track.length;e++){const t=this.state.activeScope.track[e];t.kept||n.has(t.id)||t.dispose()}const r=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach((e=>{e.kept||e.scopeId!==r.id||this.track(e)}))}gradients(e,t,n,r=!1){if(Qe(t.length>0,(()=>"gradients() received an empty list of xs.")),null!=n&&"float32"!==n.dtype)throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const a=this.scopedRun((()=>this.startTape()),(()=>this.endTape()),(()=>this.tidy("forward",e)));Qe(a instanceof Va,(()=>"The result y returned by f() must be a tensor."));const s=function(e,t,n){const r={},a={};for(let e=0;e<t.length;e++)r[t[e].id]=!0;for(let n=0;n<e.length;n++){const s=e[n],o=s.inputs;for(const e in o){const n=o[e];let i=!1;for(let e=0;e<t.length;e++)if(r[n.id]){s.outputs.forEach((e=>r[e.id]=!0)),i=!0,a[s.id]=!0;break}if(i)break}}const s={};s[n.id]=!0;const o={};for(let t=e.length-1;t>=0;t--){const n=e[t],r=n.inputs;for(let e=0;e<n.outputs.length;e++)if(s[n.outputs[e].id]){for(const e in r)s[r[e].id]=!0,o[n.id]=!0;break}}const i=[];for(let t=0;t<e.length;t++){const n=e[t];if(a[n.id]&&o[n.id]){const e={};for(const t in n.inputs){const a=n.inputs[t];r[a.id]&&(e[t]=a)}const t=Object.assign({},n);t.inputs=e,t.outputs=n.outputs,i.push(t)}}return i}(this.state.activeTape,t,a);if(!r&&0===s.length&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",(()=>{const e={};e[a.id]=null==n?function(e){const t=xt(et(e),"float32");return as.makeTensor(t,e,"float32")}(a.shape):n,function(e,t,n,r){for(let a=t.length-1;a>=0;a--){const s=t[a],o=[];if(s.outputs.forEach((t=>{const n=e[t.id];null!=n?o.push(n):o.push(null)})),null==s.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);const i=s.gradient(o);for(const t in s.inputs){if(!(t in i))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(i)}.`);const a=n((()=>i[t]()));if("float32"!==a.dtype)throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${a.dtype}'`);const o=s.inputs[t];if(!tt(a.shape,o.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${t}' has shape '${a.shape}', which does not match the shape of the input '${o.shape}'`);if(null==e[o.id])e[o.id]=a;else{const t=e[o.id];e[o.id]=r(t,a),t.dispose()}}}}(e,s,(e=>this.tidy(e)),ss);const r=t.map((t=>e[t.id]));return 0===this.state.gradientDepth&&(this.state.activeTape.forEach((e=>{for(const t of e.saved)t.dispose()})),this.state.activeTape=null),{value:a,grads:r}}))}customGrad(e){return Qe(mt(e),(()=>"The f passed in customGrad(f) must be a function.")),(...t)=>{let n;Qe(t.every((e=>e instanceof Va)),(()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors"));const r={};return t.forEach(((e,t)=>{r[t]=e})),this.runKernelFunc({forwardFunc:(r,a)=>(n=e(...t,a),Qe(n.value instanceof Va,(()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor")),Qe(mt(n.gradFunc),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function.")),n.value),backwardsFunc:(e,r)=>{const a=n.gradFunc(e,r),s=Array.isArray(a)?a:[a];Qe(s.length===t.length,(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...).")),Qe(s.every((e=>e instanceof Va)),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."));const o={};return s.forEach(((e,t)=>{o[t]=()=>e})),o},inputs:r})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){const t=Ta(),n=await this.backend.time(e);return n.wallMs=Ta()-t,n}track(e){return null!=this.state.activeScope&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new ts;for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}function rs(){const e=$t();if(null==e._tfengine){const t=new Et(e);e._tfengine=new ns(t)}var t;return t=e._tfengine.ENV,Rt=t,Ua=()=>e._tfengine,e._tfengine}ns.nextTensorId=0,ns.nextVariableId=0;const as=rs();function ss(e,t){const n={a:e,b:t};return as.runKernel(Ft,n)}function os(e){if(e||"undefined"!=typeof navigator&&null!=navigator){if(e||(e=navigator),"ReactNative"===e.product)return!0;const t=e.userAgent||e.vendor||("undefined"!=typeof window?window.opera:"");if(!t){const t=e;return t.userAgentData&&t.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))}return!1}function is(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}const us=Ct();us.registerFlag("DEBUG",(()=>!1),(e=>{e&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")})),us.registerFlag("IS_BROWSER",(()=>is())),us.registerFlag("IS_NODE",(()=>void 0!==He&&void 0!==He.versions&&void 0!==He.versions.node)),us.registerFlag("IS_CHROME",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor))),us.registerFlag("PROD",(()=>!1)),us.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(()=>us.getBool("DEBUG"))),us.registerFlag("DEPRECATION_WARNINGS_ENABLED",(()=>!0)),us.registerFlag("IS_TEST",(()=>!1)),us.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",(()=>!0)),us.registerFlag("WRAP_TO_IMAGEBITMAP",(()=>!1)),us.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",(()=>!1)),us.registerFlag("USE_SETTIMEOUTCUSTOM",(()=>!1));var ls=[],cs=[],ps="undefined"!=typeof Uint8Array?Uint8Array:Array,hs=!1;function ds(){hs=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0;t<64;++t)ls[t]=e[t],cs[e.charCodeAt(t)]=t;cs["-".charCodeAt(0)]=62,cs["_".charCodeAt(0)]=63}function fs(e,t,n){for(var r,a,s=[],o=t;o<n;o+=3)r=(e[o]<<16)+(e[o+1]<<8)+e[o+2],s.push(ls[(a=r)>>18&63]+ls[a>>12&63]+ls[a>>6&63]+ls[63&a]);return s.join("")}function ms(e){var t;hs||ds();for(var n=e.length,r=n%3,a="",s=[],o=16383,i=0,u=n-r;i<u;i+=o)s.push(fs(e,i,i+o>u?u:i+o));return 1===r?(t=e[n-1],a+=ls[t>>2],a+=ls[t<<4&63],a+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],a+=ls[t>>10],a+=ls[t>>4&63],a+=ls[t<<2&63],a+="="),s.push(a),s.join("")}function gs(e,t,n,r,a){var s,o,i=8*a-r-1,u=(1<<i)-1,l=u>>1,c=-7,p=n?a-1:0,h=n?-1:1,d=e[t+p];for(p+=h,s=d&(1<<-c)-1,d>>=-c,c+=i;c>0;s=256*s+e[t+p],p+=h,c-=8);for(o=s&(1<<-c)-1,s>>=-c,c+=r;c>0;o=256*o+e[t+p],p+=h,c-=8);if(0===s)s=1-l;else{if(s===u)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,r),s-=l}return(d?-1:1)*o*Math.pow(2,s-r)}function ys(e,t,n,r,a,s){var o,i,u,l=8*s-a-1,c=(1<<l)-1,p=c>>1,h=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:s-1,f=r?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-o))<1&&(o--,u*=2),(t+=o+p>=1?h/u:h*Math.pow(2,1-p))*u>=2&&(o++,u/=2),o+p>=c?(i=0,o=c):o+p>=1?(i=(t*u-1)*Math.pow(2,a),o+=p):(i=t*Math.pow(2,p-1)*Math.pow(2,a),o=0));a>=8;e[n+d]=255&i,d+=f,i/=256,a-=8);for(o=o<<a|i,l+=a;l>0;e[n+d]=255&o,d+=f,o/=256,l-=8);e[n+d-f]|=128*m}var bs={}.toString,_s=Array.isArray||function(e){return"[object Array]"==bs.call(e)};function xs(){return ws.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function vs(e,t){if(xs()<t)throw new RangeError("Invalid typed array length");return ws.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=ws.prototype:(null===e&&(e=new ws(t)),e.length=t),e}function ws(e,t,n){if(!(ws.TYPED_ARRAY_SUPPORT||this instanceof ws))return new ws(e,t,n);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return Is(this,e)}return Ts(this,e,t,n)}function Ts(e,t,n,r){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?function(e,t,n,r){if(t.byteLength,n<0||t.byteLength<n)throw new RangeError("'offset' is out of bounds");if(t.byteLength<n+(r||0))throw new RangeError("'length' is out of bounds");return t=void 0===n&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,n):new Uint8Array(t,n,r),ws.TYPED_ARRAY_SUPPORT?(e=t).__proto__=ws.prototype:e=Ss(e,t),e}(e,t,n,r):"string"==typeof t?function(e,t,n){if("string"==typeof n&&""!==n||(n="utf8"),!ws.isEncoding(n))throw new TypeError('"encoding" must be a valid string encoding');var r=0|Cs(t,n),a=(e=vs(e,r)).write(t,n);return a!==r&&(e=e.slice(0,a)),e}(e,t,n):function(e,t){if(Ns(t)){var n=0|Es(t.length);return 0===(e=vs(e,n)).length||t.copy(e,0,0,n),e}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||(r=t.length)!=r?vs(e,0):Ss(e,t);if("Buffer"===t.type&&_s(t.data))return Ss(e,t.data)}var r;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function ks(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function Is(e,t){if(ks(t),e=vs(e,t<0?0:0|Es(t)),!ws.TYPED_ARRAY_SUPPORT)for(var n=0;n<t;++n)e[n]=0;return e}function Ss(e,t){var n=t.length<0?0:0|Es(t.length);e=vs(e,n);for(var r=0;r<n;r+=1)e[r]=255&t[r];return e}function Es(e){if(e>=xs())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+xs().toString(16)+" bytes");return 0|e}function Ns(e){return!(null==e||!e._isBuffer)}function Cs(e,t){if(Ns(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return no(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return ro(e).length;default:if(r)return no(e).length;t=(""+t).toLowerCase(),r=!0}}function As(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return Gs(this,t,n);case"utf8":case"utf-8":return zs(this,t,n);case"ascii":return Ws(this,t,n);case"latin1":case"binary":return Hs(this,t,n);case"base64":return Us(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return js(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function Rs(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function $s(e,t,n,r,a){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)return-1;n=0}if("string"==typeof t&&(t=ws.from(t,r)),Ns(t))return 0===t.length?-1:Ms(e,t,n,r,a);if("number"==typeof t)return t&=255,ws.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):Ms(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function Ms(e,t,n,r,a){var s,o=1,i=e.length,u=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,i/=2,u/=2,n/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(a){var c=-1;for(s=n;s<i;s++)if(l(e,s)===l(t,-1===c?0:s-c)){if(-1===c&&(c=s),s-c+1===u)return c*o}else-1!==c&&(s-=s-c),c=-1}else for(n+u>i&&(n=i-u),s=n;s>=0;s--){for(var p=!0,h=0;h<u;h++)if(l(e,s+h)!==l(t,h)){p=!1;break}if(p)return s}return-1}function Fs(e,t,n,r){n=Number(n)||0;var a=e.length-n;r?(r=Number(r))>a&&(r=a):r=a;var s=t.length;if(s%2!=0)throw new TypeError("Invalid hex string");r>s/2&&(r=s/2);for(var o=0;o<r;++o){var i=parseInt(t.substr(2*o,2),16);if(isNaN(i))return o;e[n+o]=i}return o}function Os(e,t,n,r){return ao(no(t,e.length-n),e,n,r)}function Ds(e,t,n,r){return ao(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function Ls(e,t,n,r){return Ds(e,t,n,r)}function Ps(e,t,n,r){return ao(ro(t),e,n,r)}function Bs(e,t,n,r){return ao(function(e,t){for(var n,r,a,s=[],o=0;o<e.length&&!((t-=2)<0);++o)r=(n=e.charCodeAt(o))>>8,a=n%256,s.push(a),s.push(r);return s}(t,e.length-n),e,n,r)}function Us(e,t,n){return 0===t&&n===e.length?ms(e):ms(e.slice(t,n))}function zs(e,t,n){n=Math.min(e.length,n);for(var r=[],a=t;a<n;){var s,o,i,u,l=e[a],c=null,p=l>239?4:l>223?3:l>191?2:1;if(a+p<=n)switch(p){case 1:l<128&&(c=l);break;case 2:128==(192&(s=e[a+1]))&&(u=(31&l)<<6|63&s)>127&&(c=u);break;case 3:s=e[a+1],o=e[a+2],128==(192&s)&&128==(192&o)&&(u=(15&l)<<12|(63&s)<<6|63&o)>2047&&(u<55296||u>57343)&&(c=u);break;case 4:s=e[a+1],o=e[a+2],i=e[a+3],128==(192&s)&&128==(192&o)&&128==(192&i)&&(u=(15&l)<<18|(63&s)<<12|(63&o)<<6|63&i)>65535&&u<1114112&&(c=u)}null===c?(c=65533,p=1):c>65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|1023&c),r.push(c),a+=p}return function(e){var t=e.length;if(t<=Vs)return String.fromCharCode.apply(String,e);for(var n="",r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=Vs));return n}(r)}ws.TYPED_ARRAY_SUPPORT=void 0===_e.TYPED_ARRAY_SUPPORT||_e.TYPED_ARRAY_SUPPORT,xs(),ws.poolSize=8192,ws._augment=function(e){return e.__proto__=ws.prototype,e},ws.from=function(e,t,n){return Ts(null,e,t,n)},ws.TYPED_ARRAY_SUPPORT&&(ws.prototype.__proto__=Uint8Array.prototype,ws.__proto__=Uint8Array),ws.alloc=function(e,t,n){return function(e,t,n,r){return ks(t),t<=0?vs(e,t):void 0!==n?"string"==typeof r?vs(e,t).fill(n,r):vs(e,t).fill(n):vs(e,t)}(null,e,t,n)},ws.allocUnsafe=function(e){return Is(null,e)},ws.allocUnsafeSlow=function(e){return Is(null,e)},ws.isBuffer=function(e){return null!=e&&(!!e._isBuffer||so(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&so(e.slice(0,0))}(e))},ws.compare=function(e,t){if(!Ns(e)||!Ns(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,a=0,s=Math.min(n,r);a<s;++a)if(e[a]!==t[a]){n=e[a],r=t[a];break}return n<r?-1:r<n?1:0},ws.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},ws.concat=function(e,t){if(!_s(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return ws.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=ws.allocUnsafe(t),a=0;for(n=0;n<e.length;++n){var s=e[n];if(!Ns(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(r,a),a+=s.length}return r},ws.byteLength=Cs,ws.prototype._isBuffer=!0,ws.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)Rs(this,t,t+1);return this},ws.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)Rs(this,t,t+3),Rs(this,t+1,t+2);return this},ws.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)Rs(this,t,t+7),Rs(this,t+1,t+6),Rs(this,t+2,t+5),Rs(this,t+3,t+4);return this},ws.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?zs(this,0,e):As.apply(this,arguments)},ws.prototype.equals=function(e){if(!Ns(e))throw new TypeError("Argument must be a Buffer");return this===e||0===ws.compare(this,e)},ws.prototype.inspect=function(){var e="";return this.length>0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),"<Buffer "+e+">"},ws.prototype.compare=function(e,t,n,r,a){if(!Ns(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;for(var s=(a>>>=0)-(r>>>=0),o=(n>>>=0)-(t>>>=0),i=Math.min(s,o),u=this.slice(r,a),l=e.slice(t,n),c=0;c<i;++c)if(u[c]!==l[c]){s=u[c],o=l[c];break}return s<o?-1:o<s?1:0},ws.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},ws.prototype.indexOf=function(e,t,n){return $s(this,e,t,n,!0)},ws.prototype.lastIndexOf=function(e,t,n){return $s(this,e,t,n,!1)},ws.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(n)?(n|=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var a=this.length-t;if((void 0===n||n>a)&&(n=a),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return Fs(this,e,t,n);case"utf8":case"utf-8":return Os(this,e,t,n);case"ascii":return Ds(this,e,t,n);case"latin1":case"binary":return Ls(this,e,t,n);case"base64":return Ps(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Bs(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},ws.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Vs=4096;function Ws(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(127&e[a]);return r}function Hs(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(e[a]);return r}function Gs(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var a="",s=t;s<n;++s)a+=to(e[s]);return a}function js(e,t,n){for(var r=e.slice(t,n),a="",s=0;s<r.length;s+=2)a+=String.fromCharCode(r[s]+256*r[s+1]);return a}function Ks(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function qs(e,t,n,r,a,s){if(!Ns(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||t<s)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function Xs(e,t,n,r){t<0&&(t=65535+t+1);for(var a=0,s=Math.min(e.length-n,2);a<s;++a)e[n+a]=(t&255<<8*(r?a:1-a))>>>8*(r?a:1-a)}function Ys(e,t,n,r){t<0&&(t=4294967295+t+1);for(var a=0,s=Math.min(e.length-n,4);a<s;++a)e[n+a]=t>>>8*(r?a:3-a)&255}function Qs(e,t,n,r,a,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function Js(e,t,n,r,a){return a||Qs(e,0,n,4),ys(e,t,n,r,23,4),n+4}function Zs(e,t,n,r,a){return a||Qs(e,0,n,8),ys(e,t,n,r,52,8),n+8}ws.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e),ws.TYPED_ARRAY_SUPPORT)(n=this.subarray(e,t)).__proto__=ws.prototype;else{var a=t-e;n=new ws(a,void 0);for(var s=0;s<a;++s)n[s]=this[s+e]}return n},ws.prototype.readUIntLE=function(e,t,n){e|=0,t|=0,n||Ks(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r},ws.prototype.readUIntBE=function(e,t,n){e|=0,t|=0,n||Ks(e,t,this.length);for(var r=this[e+--t],a=1;t>0&&(a*=256);)r+=this[e+--t]*a;return r},ws.prototype.readUInt8=function(e,t){return t||Ks(e,1,this.length),this[e]},ws.prototype.readUInt16LE=function(e,t){return t||Ks(e,2,this.length),this[e]|this[e+1]<<8},ws.prototype.readUInt16BE=function(e,t){return t||Ks(e,2,this.length),this[e]<<8|this[e+1]},ws.prototype.readUInt32LE=function(e,t){return t||Ks(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},ws.prototype.readUInt32BE=function(e,t){return t||Ks(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},ws.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||Ks(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r>=(a*=128)&&(r-=Math.pow(2,8*t)),r},ws.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||Ks(e,t,this.length);for(var r=t,a=1,s=this[e+--r];r>0&&(a*=256);)s+=this[e+--r]*a;return s>=(a*=128)&&(s-=Math.pow(2,8*t)),s},ws.prototype.readInt8=function(e,t){return t||Ks(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},ws.prototype.readInt16LE=function(e,t){t||Ks(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},ws.prototype.readInt16BE=function(e,t){t||Ks(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},ws.prototype.readInt32LE=function(e,t){return t||Ks(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},ws.prototype.readInt32BE=function(e,t){return t||Ks(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},ws.prototype.readFloatLE=function(e,t){return t||Ks(e,4,this.length),gs(this,e,!0,23,4)},ws.prototype.readFloatBE=function(e,t){return t||Ks(e,4,this.length),gs(this,e,!1,23,4)},ws.prototype.readDoubleLE=function(e,t){return t||Ks(e,8,this.length),gs(this,e,!0,52,8)},ws.prototype.readDoubleBE=function(e,t){return t||Ks(e,8,this.length),gs(this,e,!1,52,8)},ws.prototype.writeUIntLE=function(e,t,n,r){e=+e,t|=0,n|=0,r||qs(this,e,t,n,Math.pow(2,8*n)-1,0);var a=1,s=0;for(this[t]=255&e;++s<n&&(a*=256);)this[t+s]=e/a&255;return t+n},ws.prototype.writeUIntBE=function(e,t,n,r){e=+e,t|=0,n|=0,r||qs(this,e,t,n,Math.pow(2,8*n)-1,0);var a=n-1,s=1;for(this[t+a]=255&e;--a>=0&&(s*=256);)this[t+a]=e/s&255;return t+n},ws.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||qs(this,e,t,1,255,0),ws.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},ws.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||qs(this,e,t,2,65535,0),ws.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Xs(this,e,t,!0),t+2},ws.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||qs(this,e,t,2,65535,0),ws.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Xs(this,e,t,!1),t+2},ws.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||qs(this,e,t,4,4294967295,0),ws.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):Ys(this,e,t,!0),t+4},ws.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||qs(this,e,t,4,4294967295,0),ws.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Ys(this,e,t,!1),t+4},ws.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);qs(this,e,t,n,a-1,-a)}var s=0,o=1,i=0;for(this[t]=255&e;++s<n&&(o*=256);)e<0&&0===i&&0!==this[t+s-1]&&(i=1),this[t+s]=(e/o>>0)-i&255;return t+n},ws.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);qs(this,e,t,n,a-1,-a)}var s=n-1,o=1,i=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===i&&0!==this[t+s+1]&&(i=1),this[t+s]=(e/o>>0)-i&255;return t+n},ws.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||qs(this,e,t,1,127,-128),ws.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},ws.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||qs(this,e,t,2,32767,-32768),ws.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Xs(this,e,t,!0),t+2},ws.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||qs(this,e,t,2,32767,-32768),ws.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Xs(this,e,t,!1),t+2},ws.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||qs(this,e,t,4,2147483647,-2147483648),ws.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):Ys(this,e,t,!0),t+4},ws.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||qs(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),ws.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Ys(this,e,t,!1),t+4},ws.prototype.writeFloatLE=function(e,t,n){return Js(this,e,t,!0,n)},ws.prototype.writeFloatBE=function(e,t,n){return Js(this,e,t,!1,n)},ws.prototype.writeDoubleLE=function(e,t,n){return Zs(this,e,t,!0,n)},ws.prototype.writeDoubleBE=function(e,t,n){return Zs(this,e,t,!1,n)},ws.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var a,s=r-n;if(this===e&&n<t&&t<r)for(a=s-1;a>=0;--a)e[a+t]=this[a+n];else if(s<1e3||!ws.TYPED_ARRAY_SUPPORT)for(a=0;a<s;++a)e[a+t]=this[a+n];else Uint8Array.prototype.set.call(e,this.subarray(n,n+s),t);return s},ws.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),1===e.length){var a=e.charCodeAt(0);a<256&&(e=a)}if(void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!ws.isEncoding(r))throw new TypeError("Unknown encoding: "+r)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{var o=Ns(e)?e:no(new ws(e,r).toString()),i=o.length;for(s=0;s<n-t;++s)this[s+t]=o[s%i]}return this};var eo=/[^+\/0-9A-Za-z-_]/g;function to(e){return e<16?"0"+e.toString(16):e.toString(16)}function no(e,t){var n;t=t||1/0;for(var r=e.length,a=null,s=[],o=0;o<r;++o){if((n=e.charCodeAt(o))>55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&s.push(239,191,189);if(a=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function ro(e){return function(e){var t,n,r,a,s,o;hs||ds();var i=e.length;if(i%4>0)throw new Error("Invalid string. Length must be a multiple of 4");s="="===e[i-2]?2:"="===e[i-1]?1:0,o=new ps(3*i/4-s),r=s>0?i-4:i;var u=0;for(t=0,n=0;t<r;t+=4,n+=3)a=cs[e.charCodeAt(t)]<<18|cs[e.charCodeAt(t+1)]<<12|cs[e.charCodeAt(t+2)]<<6|cs[e.charCodeAt(t+3)],o[u++]=a>>16&255,o[u++]=a>>8&255,o[u++]=255&a;return 2===s?(a=cs[e.charCodeAt(t)]<<2|cs[e.charCodeAt(t+1)]>>4,o[u++]=255&a):1===s&&(a=cs[e.charCodeAt(t)]<<10|cs[e.charCodeAt(t+1)]<<4|cs[e.charCodeAt(t+2)]>>2,o[u++]=a>>8&255,o[u++]=255&a),o}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(eo,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function ao(e,t,n,r){for(var a=0;a<r&&!(a+n>=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function so(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function oo(e,t){let n=e;if(Sa(e))return"string"===t?[]:[e.length];if("object"==typeof e){if("texture"in e){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if("buffer"in e&&!(e.buffer instanceof ArrayBuffer))return[e.buffer.size/(null==t?4:ht(t))]}if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||Sa(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&Ct().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&io(e,r,[]),r}function io(e,t,n){if(n=n||[],!Array.isArray(e)&&!Sa(e))return void Qe(0===t.length,(()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`));Qe(t.length>0,(()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`)),Qe(e.length===t[0],(()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`));const r=t.slice(1);for(let t=0;t<e.length;++t)io(e[t],r,n.concat(t))}function uo(e,t,n,r){if("string_or_numeric"!==e){if(null==e)throw new Error("Expected dtype cannot be null.");if("numeric"!==e&&e!==t||"numeric"===e&&"string"===t)throw new Error(`Argument '${n}' passed to '${r}' must be ${e} tensor, but got ${t} tensor`)}}function lo(e,t,n,r="numeric"){if(e instanceof Va)return uo(r,e.dtype,t,n),e;let a=ft(e);if("string"!==a&&["bool","int32","float32"].indexOf(r)>=0&&(a=r),uo(r,a,t,n),null==e||!Sa(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){const r=null==e?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${r}'`)}const s=oo(e,a);Sa(e)||Array.isArray(e)||(e=[e]);const o="string"!==a?wa(e,a):Ea(e,[],!0);return as.makeTensor(o,s,a)}function co(e,t,n,r="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map(((e,a)=>lo(e,`${t}[${a}]`,n,r)))}const po="__op";function ho(e){const t=Object.keys(e);if(1!==t.length)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0];const r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n+=po;const a=(...e)=>{as.startScope(n);try{const t=r(...e);return It(t)&&console.error("Cannot return a Promise inside of tidy."),as.endScope(t),t}catch(e){throw as.endScope(null),e}};return Object.defineProperty(a,"name",{value:n,configurable:!0}),a}const fo=ho({complex_:function(e,t){const n=lo(e,"real","complex"),r=lo(t,"imag","complex");Je(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, must match in call to tf.complex().`);const a={real:n,imag:r};return as.runKernel("Complex",a)}});function mo(e,t,n,r){if(null==r)r=ft(e);else if("complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if("object"==typeof e&&("texture"in e||"buffer"in e&&!(e.buffer instanceof ArrayBuffer))){if("float32"!==r&&"int32"!==r)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${r}.`);return as.backend.createTensorFromGPUData(e,t||n,r)}if(!Sa(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=t){wt(t);const e=et(t),r=et(n);Qe(e===r,(()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${r}`));for(let e=0;e<n.length;++e){const r=n[e],a=e!==n.length-1||r!==et(t.slice(e));Qe(n[e]===t[e]||!a,(()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `))}}return Sa(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==r?wa(e,r):Ea(e,[],!0),as.makeTensor(e,t,r)}function go(e,t,n){return mo(e,t,oo(e,n),n)}const yo={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},bo=4;function _o(e,t){const n={};let r,a=0;for(const s of t){const t=s.name,o=s.dtype,i=s.shape,u=et(i);let l;if("quantization"in s){const n=s.quantization;if("uint8"===n.dtype||"uint16"===n.dtype){if(!("min"in n)||!("scale"in n))throw new Error(`Weight ${s.name} with quantization ${n.dtype} doesn't have corresponding metadata min and scale.`)}else{if("float16"!==n.dtype)throw new Error(`Weight ${s.name} has unknown quantization dtype ${n.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);if("float32"!==o)throw new Error(`Weight ${s.name} is quantized with ${n.dtype} which only supports weights of type float32 not ${o}.`)}const i=yo[n.dtype],c=e.slice(a,a+u*i),p="uint8"===n.dtype?new Uint8Array(c):new Uint16Array(c);if("float32"===o)if("uint8"===n.dtype||"uint16"===n.dtype){l=new Float32Array(p.length);for(let e=0;e<p.length;e++){const t=p[e];l[e]=t*n.scale+n.min}}else{if("float16"!==n.dtype)throw new Error(`Unsupported quantization type ${n.dtype} for weight type float32.`);void 0===r&&(r=Ao()),l=r(p)}else{if("int32"!==o)throw new Error(`Unsupported dtype in weight '${t}': ${o}`);if("uint8"!==n.dtype&&"uint16"!==n.dtype)throw new Error(`Unsupported quantization type ${n.dtype} for weight type int32.`);l=new Int32Array(p.length);for(let e=0;e<p.length;e++){const t=p[e];l[e]=Math.round(t*n.scale+n.min)}}a+=u*i}else if("string"===o){const t=et(s.shape);l=[];for(let n=0;n<t;n++){const t=new Uint32Array(e.slice(a,a+bo))[0];a+=bo;const n=new Uint8Array(e.slice(a,a+t));l.push(n),a+=t}}else{const r=yo[o],s=e.slice(a,a+u*r);if("float32"===o)l=new Float32Array(s);else if("int32"===o)l=new Int32Array(s);else if("bool"===o)l=new Uint8Array(s);else{if("complex64"!==o)throw new Error(`Unsupported dtype in weight '${t}': ${o}`);{l=new Float32Array(s);const e=new Float32Array(l.length/2),r=new Float32Array(l.length/2);for(let t=0;t<e.length;t++)e[t]=l[2*t],r[t]=l[2*t+1];const a=go(e,i,"float32"),o=go(r,i,"float32");n[t]=fo(a,o),a.dispose(),o.dispose()}}a+=u*r}"complex64"!==o&&(n[t]=go(l,i,o))}return n}function xo(e){if(null===e)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0;const n=[];e.forEach((e=>{if(t+=e.byteLength,n.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${e.constructor.name}`)}));const r=new Uint8Array(t);let a=0;return n.forEach((e=>{r.set(new Uint8Array(e.buffer),a),a+=e.byteLength})),r.buffer}const vo=void 0!==ws&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function wo(e){return vo?ws.byteLength(e):new Blob([e]).size}function To(e){if(1===e.length)return e[0];let t=0;e.forEach((e=>{t+=e.byteLength}));const n=new Uint8Array(t);let r=0;return e.forEach((e=>{n.set(new Uint8Array(e),r),r+=e.byteLength})),n.buffer}function ko(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function Io(e,t){const n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return null!=e.signature&&(n.signature=e.signature),null!=e.userDefinedMetadata&&(n.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(n.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(n.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(n.trainingConfig=e.trainingConfig),n}function So(e,t,n){const r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(null!=e.trainingConfig&&(r.trainingConfig=e.trainingConfig),null!=e.weightsManifest){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!n)throw new Error("modelJSON has weightsManifest but weightData is null");r.weightSpecs=t,r.weightData=n}return null!=e.signature&&(r.signature=e.signature),null!=e.userDefinedMetadata&&(r.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(r.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(r.initializerSignature=e.initializerSignature),r}async function Eo(e,t){let n,r;return null!=e.weightsManifest&&([n,r]=await t(e.weightsManifest)),So(e,n,r)}function No(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:wo(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:wo(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:e.weightData.byteLength}}function Co(e){const t=[];for(const n of e)t.push(...n.weights);return t}function Ao(){const e=function(){const e=e=>{let t=e<<13,n=0;for(;0==(8388608&t);)n-=8388608,t<<=1;return t&=-8388609,n+=947912704,t|n},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let e=1024;e<2048;e++)t[e]=939524096+(e-1024<<13);return t}(),t=function(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}(),n=function(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}();return r=>{const a=new ArrayBuffer(4*r.length),s=new Uint32Array(a);for(let a=0;a<r.length;a++){const o=r[a],i=e[n[o>>10]+(1023&o)]+t[o>>10];s[a]=i}return new Float32Array(a)}}class Ro{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==Ro.instance&&(Ro.instance=new Ro),Ro.instance}static registerSaveRouter(e){Ro.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Ro.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Ro.getHandlers(e,"save")}static getLoadHandlers(e,t){return Ro.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[];return("load"===t?Ro.getInstance().loadRouters:Ro.getInstance().saveRouters).forEach((t=>{const a=t(e,n);null!==a&&r.push(a)})),r}}const $o="tensorflowjs",Mo="models_store",Fo="model_info_store";function Oo(){if(!Ct().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e="undefined"==typeof window?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function Do(e){const t=e.result;t.createObjectStore(Mo,{keyPath:"modelPath"}),t.createObjectStore(Fo,{keyPath:"modelPath"})}class Lo{constructor(e){if(this.indexedDB=Oo(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise(((e,n)=>{const r=this.indexedDB.open($o,1);r.onupgradeneeded=()=>Do(r),r.onsuccess=()=>{const a=r.result;if(null==t){const t=a.transaction(Mo,"readonly"),r=t.objectStore(Mo).get(this.modelPath);r.onsuccess=()=>{if(null==r.result)return a.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(r.result.modelArtifacts)},r.onerror=e=>(a.close(),n(r.error)),t.oncomplete=()=>a.close()}else{const r=No(t),s=a.transaction(Fo,"readwrite");let o=s.objectStore(Fo);const i=o.put({modelPath:this.modelPath,modelArtifactsInfo:r});let u;i.onsuccess=()=>{u=a.transaction(Mo,"readwrite");const i=u.objectStore(Mo).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:r});i.onsuccess=()=>e({modelArtifactsInfo:r}),i.onerror=e=>{o=s.objectStore(Fo);const t=o.delete(this.modelPath);t.onsuccess=()=>(a.close(),n(i.error)),t.onerror=e=>(a.close(),n(i.error))}},i.onerror=e=>(a.close(),n(i.error)),s.oncomplete=()=>{null==u?a.close():u.oncomplete=()=>a.close()}}},r.onerror=e=>n(r.error)}))}}Lo.URL_SCHEME="indexeddb://";const Po=e=>{return Ct().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Lo.URL_SCHEME)?(t=e.slice(Lo.URL_SCHEME.length),new Lo(t)):null;var t};Ro.registerSaveRouter(Po),Ro.registerLoadRouter(Po);class Bo{constructor(){this.indexedDB=Oo()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open($o,1);n.onupgradeneeded=()=>Do(n),n.onsuccess=()=>{const r=n.result,a=r.transaction(Fo,"readonly"),s=a.objectStore(Fo).getAll();s.onsuccess=()=>{const t={};for(const e of s.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},s.onerror=e=>(r.close(),t(s.error)),a.oncomplete=()=>r.close()},n.onerror=e=>t(n.error)}))}async removeModel(e){var t;return e=(t=e).startsWith(Lo.URL_SCHEME)?t.slice(Lo.URL_SCHEME.length):t,new Promise(((t,n)=>{const r=this.indexedDB.open($o,1);r.onupgradeneeded=()=>Do(r),r.onsuccess=()=>{const a=r.result,s=a.transaction(Fo,"readwrite"),o=s.objectStore(Fo),i=o.get(e);let u;i.onsuccess=()=>{if(null==i.result)return a.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const r=o.delete(e),s=()=>{u=a.transaction(Mo,"readwrite");const r=u.objectStore(Mo).delete(e);r.onsuccess=()=>t(i.result.modelArtifactsInfo),r.onerror=e=>n(i.error)};r.onsuccess=s,r.onerror=e=>(s(),a.close(),n(i.error))}},i.onerror=e=>(a.close(),n(i.error)),s.oncomplete=()=>{null==u?a.close():u.oncomplete=()=>a.close()}},r.onerror=e=>n(r.error)}))}}const Uo="/",zo="tensorflowjs_models",Vo="info",Wo="model_topology",Ho="weight_specs",Go="weight_data",jo="model_metadata";function Ko(e){return{info:[zo,e,Vo].join(Uo),topology:[zo,e,Wo].join(Uo),weightSpecs:[zo,e,Ho].join(Uo),weightData:[zo,e,Go].join(Uo),modelMetadata:[zo,e,jo].join(Uo)}}function qo(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function Xo(e){const t=e.split(Uo);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Uo)}class Yo{constructor(e){if(!Ct().getBool("IS_BROWSER")||"undefined"==typeof window||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=Ko(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),r=No(e);try{this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(e){if(vo)return ws.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let e=0,r=t.length;e<r;e++)n+=String.fromCharCode(t[e]);return btoa(n)}(e.weightData));const a={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:null!=e.signature?e.signature:void 0,userDefinedMetadata:null!=e.userDefinedMetadata?e.userDefinedMetadata:void 0,modelInitializer:null!=e.modelInitializer?e.modelInitializer:void 0,initializerSignature:null!=e.initializerSignature?e.initializerSignature:void 0,trainingConfig:null!=e.trainingConfig?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(a)),{modelArtifactsInfo:r}}catch(e){throw qo(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${r.modelTopologyBytes}, weightSpecsBytes=${r.weightSpecsBytes}, weightDataBytes=${r.weightDataBytes}.`)}}}async load(){const e=JSON.parse(this.LS.getItem(this.keys.info));if(null==e)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if("JSON"!==e.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(null==n)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;const r=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(null==r)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=r;const a=this.LS.getItem(this.keys.modelMetadata);if(null!=a){const e=JSON.parse(a);t.format=e.format,t.generatedBy=e.generatedBy,t.convertedBy=e.convertedBy,null!=e.signature&&(t.signature=e.signature),null!=e.userDefinedMetadata&&(t.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(t.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(t.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(t.trainingConfig=e.trainingConfig)}const s=this.LS.getItem(this.keys.weightData);if(null==s)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=function(e){if(vo){const t=ws.from(e,"base64");return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n.set([t.charCodeAt(e)],e);return n.buffer}(s),t}}Yo.URL_SCHEME="localstorage://";const Qo=e=>{return Ct().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Yo.URL_SCHEME)?(t=e.slice(Yo.URL_SCHEME.length),new Yo(t)):null;var t};Ro.registerSaveRouter(Qo),Ro.registerLoadRouter(Qo);class Jo{constructor(){Qe(Ct().getBool("IS_BROWSER"),(()=>"Current environment is not a web browser")),Qe("undefined"==typeof window||void 0!==window.localStorage,(()=>"Current browser does not appear to support localStorage")),this.LS=window.localStorage}async listModels(){const e={},t=zo+Uo,n=Uo+Vo;for(let r=0;r<this.LS.length;++r){const a=this.LS.key(r);a.startsWith(t)&&a.endsWith(n)&&(e[Xo(a)]=JSON.parse(this.LS.getItem(a)))}return e}async removeModel(e){var t;const n=Ko(e=(t=e).startsWith(Yo.URL_SCHEME)?t.slice(Yo.URL_SCHEME.length):t);if(null==this.LS.getItem(n.info))throw new Error(`Cannot find model at path '${e}'`);const r=JSON.parse(this.LS.getItem(n.info));return qo(n),r}}function Zo(e){return new Promise((e=>setTimeout(e))).then(e)}class ei{constructor(e){if(!Ct().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(ei.URL_SCHEME)&&(e=e.slice(ei.URL_SCHEME.length)),null!=e&&0!==e.length||(e="model"),this.modelJsonFileName=e+".json",this.weightDataFileName=e+".weights.bin"}async save(e){if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const n=Io(e,[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}]),r=window.URL.createObjectURL(new Blob([JSON.stringify(n)],{type:"application/json"})),a=null==this.modelJsonAnchor?document.createElement("a"):this.modelJsonAnchor;if(a.download=this.modelJsonFileName,a.href=r,await Zo((()=>a.dispatchEvent(new MouseEvent("click")))),null!=e.weightData){const e=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor;e.download=this.weightDataFileName,e.href=t,await Zo((()=>e.dispatchEvent(new MouseEvent("click"))))}return{modelArtifactsInfo:No(e)}}}}ei.URL_SCHEME="downloads://";class ti{constructor(e){if(null==e||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise(((e,t)=>{const n=new FileReader;n.onload=n=>{const r=JSON.parse(n.target.result),a=r.modelTopology;if(null==a)return void t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));if(null==r.weightsManifest)return void t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));if(0===this.weightsFiles.length)return void e({modelTopology:a});const s=Eo(r,(e=>this.loadWeights(e)));e(s)},n.onerror=e=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),n.readAsText(this.jsonFile)}))}loadWeights(e){const t=[],n=[];for(const r of e)t.push(...r.weights),n.push(...r.paths);const r=this.checkManifestAndWeightFiles(e),a=n.map((e=>this.loadWeightsFile(e,r[e])));return Promise.all(a).then((e=>[t,To(e)]))}loadWeightsFile(e,t){return new Promise(((n,r)=>{const a=new FileReader;a.onload=e=>{const t=e.target.result;n(t)},a.onerror=t=>r(`Failed to weights data from file of path '${e}'.`),a.readAsArrayBuffer(t)}))}checkManifestAndWeightFiles(e){const t=[],n=this.weightsFiles.map((e=>ko(e.name))),r={};for(const a of e)a.paths.forEach((e=>{const a=ko(e);if(-1!==t.indexOf(a))throw new Error(`Duplicate file basename found in weights manifest: '${a}'`);if(t.push(a),-1===n.indexOf(a))throw new Error(`Weight file with basename '${a}' is not provided.`);r[e]=this.weightsFiles[n.indexOf(a)]}));if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return r}}function ni(e,t,n,r){!function(e){Qe(null!=e&&Array.isArray(e)&&e.length>0,(()=>"promises must be a none empty array"))}(e),function(e,t){Qe(e>=0&&e<=1,(()=>`Progress fraction must be in range [0, 1], but got startFraction ${e}`)),Qe(t>=0&&t<=1,(()=>`Progress fraction must be in range [0, 1], but got endFraction ${t}`)),Qe(t>=e,(()=>`startFraction must be no more than endFraction, but got startFraction ${e} and endFraction ${t}`))}(n=null==n?0:n,r=null==r?1:r);let a=0;return Promise.all(e.map((s=>(s.then((s=>{const o=n+ ++a/e.length*(r-n);return t(o),s})),s))))}async function ri(e,t){null==t&&(t={});const n=null==t.fetchFunc?Ct().platform.fetch:t.fetchFunc,r=e.map((e=>n(e,t.requestInit,{isBinary:!0}))),a=(null==t.onProgress?await Promise.all(r):await ni(r,t.onProgress,0,.5)).map((e=>e.arrayBuffer()));return null==t.onProgress?await Promise.all(a):await ni(a,t.onProgress,.5,1)}function ai(e){return async(t,n="",r)=>{const a=t.map((()=>!1)),s={},o=null!=r?r.map((()=>!1)):[],i=[];if(t.forEach(((e,t)=>{let n=0;e.weights.forEach((e=>{const u="quantization"in e?e.quantization.dtype:e.dtype,l=yo[u]*et(e.shape),c=()=>{a[t]=!0,null==s[t]&&(s[t]=[]),s[t].push({manifestEntry:e,groupOffset:n,sizeBytes:l})};null!=r?r.forEach(((t,n)=>{t===e.name&&(c(),o[n]=!0)})):c(),i.push(e.name),n+=l}))})),!o.every((e=>e))){const e=r.filter(((e,t)=>!o[t]));throw new Error(`Could not find weights in manifest with names: ${e.join(", ")}. \nManifest JSON has weights with names: ${i.join(", ")}.`)}const u=a.reduce(((e,t,n)=>(t&&e.push(n),e)),[]),l=[];u.forEach((e=>{t[e].paths.forEach((e=>{const t=n+(n.endsWith("/")?"":"/")+e;l.push(t)}))}));const c=await e(l),p={};let h=0;return u.forEach((e=>{const n=t[e].paths.length;let r=0;for(let e=0;e<n;e++)r+=c[h+e].byteLength;const a=new ArrayBuffer(r),o=new Uint8Array(a);let i=0;for(let e=0;e<n;e++){const t=new Uint8Array(c[h+e]);o.set(t,i),i+=t.byteLength}s[e].forEach((e=>{const t=_o(a.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(const e in t)p[e]=t[e]})),h+=n})),p}}Ro.registerSaveRouter((e=>Ct().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ei.URL_SCHEME)?function(e="model"){return new ei(e)}(e.slice(ei.URL_SCHEME.length)):null));class si{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?(Qe("function"==typeof t.fetchFunc,(()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)")),this.fetch=t.fetchFunc):this.fetch=Ct().platform.fetch,Qe(null!=e&&e.length>0,(()=>"URL path for http must not be null, undefined or empty.")),Array.isArray(e)&&Qe(2===e.length,(()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`)),this.path=e,null!=t.requestInit&&null!=t.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=Io(e,[{paths:["./model.weights.bin"],weights:e.weightSpecs}]);t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:"application/octet-stream"}),"model.weights.bin");const r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:No(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async load(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(e){let t=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?t+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":t+=" Please make sure the server is serving valid JSON for this request.",new Error(t)}const n=t.modelTopology,r=t.weightsManifest;if(null==n&&null==r)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return Eo(t,(e=>this.loadWeights(e)))}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=function(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?");return[e.substring(0,t)+"/",n>t?e.substring(n):""]}(t),a=this.weightPathPrefix||n,s=Co(e),o=[],i=[];for(const t of e)for(const e of t.paths)null!=this.weightUrlConverter?i.push(this.weightUrlConverter(e)):o.push(a+e+r);return this.weightUrlConverter&&o.push(...await Promise.all(i)),[s,To(await ri(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress}))]}}function oi(e){return null!=e.match(si.URL_SCHEME_REGEX)}si.URL_SCHEME_REGEX=/^https?:\/\//;const ii=(e,t)=>{if("undefined"==typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every((e=>oi(e))):oi(e),n)return ui(e,t)}return null};function ui(e,t){return new si(e,t)}Ro.registerSaveRouter(ii),Ro.registerLoadRouter(ii);class li{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class ci{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class pi{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function hi(e,t,n,r){return 1===arguments.length?null!=e.modelTopology||null!=e.weightSpecs?new li(e):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new li({modelTopology:e})):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new li({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r}))}const di="://";class fi{constructor(){this.managers={}}static getInstance(){return null==fi.instance&&(fi.instance=new fi),fi.instance}static registerManager(e,t){Qe(null!=e,(()=>"scheme must not be undefined or null.")),e.endsWith(di)&&(e=e.slice(0,e.indexOf(di))),Qe(e.length>0,(()=>"scheme must not be an empty string."));const n=fi.getInstance();Qe(null==n.managers[e],(()=>`A model store manager is already registered for scheme '${e}'.`)),n.managers[e]=t}static getManager(e){const t=fi.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(fi.getInstance().managers)}}function mi(e){if(-1===e.indexOf(di))throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${fi.getSchemes().join(",")}`);return{scheme:e.split(di)[0],path:e.split(di)[1]}}async function gi(e,t,n=!1){Qe(e!==t,(()=>`Old path and new path are the same: '${e}'`));const r=Ro.getLoadHandlers(e);Qe(r.length>0,(()=>`Copying failed because no load handler is found for source URL ${e}.`)),Qe(r.length<2,(()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${e}.`));const a=r[0],s=Ro.getSaveHandlers(t);Qe(s.length>0,(()=>`Copying failed because no save handler is found for destination URL ${t}.`)),Qe(s.length<2,(()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${t}.`));const o=s[0],i=mi(e).scheme,u=mi(e).path,l=i===mi(e).scheme,c=await a.load();n&&l&&await fi.getManager(i).removeModel(u);const p=await o.save(c);return n&&!l&&await fi.getManager(i).removeModel(u),p.modelArtifactsInfo}var yi=Object.freeze({__proto__:null,browserFiles:function(e){return new ti(e)},browserHTTPRequest:function(e,t){return ui(e,t)},concatenateArrayBuffers:To,decodeWeights:_o,encodeWeights:async function(e,t){const n=[],r=[],a=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);for(let s=0;s<a.length;++s){const o=a[s],i=Array.isArray(e)?e[s].tensor:e[o];if("float32"!==i.dtype&&"int32"!==i.dtype&&"bool"!==i.dtype&&"string"!==i.dtype&&"complex64"!==i.dtype)throw new Error(`Unsupported dtype in weight '${o}': ${i.dtype}`);const u={name:o,shape:i.shape,dtype:i.dtype};if("string"===i.dtype){const e=new Promise((async e=>{const t=await i.bytes(),n=t.reduce(((e,t)=>e+t.length),0)+bo*t.length,r=new Uint8Array(n);let a=0;for(let e=0;e<t.length;e++){const n=t[e],s=new Uint8Array(new Uint32Array([n.length]).buffer);r.set(s,a),a+=bo,r.set(n,a),a+=n.length}e(r)}));r.push(e)}else r.push(i.data());null!=t&&(u.group=t),n.push(u)}return{data:xo(await Promise.all(r)),specs:n}},fromMemory:function(e,t,n,r){return new pi(hi(...arguments))},fromMemorySync:hi,getLoadHandlers:(e,t)=>Ro.getLoadHandlers(e,t),getModelArtifactsForJSON:Eo,getModelArtifactsForJSONSync:So,getModelArtifactsInfoForJSON:No,getSaveHandlers:e=>Ro.getSaveHandlers(e),getWeightSpecs:Co,http:ui,isHTTPScheme:oi,loadWeights:async function(e,t="",n,r){return ai((e=>ri(e,{requestInit:r})))(e,t,n)},registerLoadRouter:e=>Ro.registerLoadRouter(e),registerSaveRouter:e=>Ro.registerSaveRouter(e),weightsLoaderFactory:ai,withSaveHandler:function(e){return new ci(e)},withSaveHandlerSync:function(e){return new ci(e)},copyModel:async function(e,t){return gi(e,t,!1)},listModels:async function(){const e=fi.getSchemes(),t={};for(const n of e){const e=await fi.getManager(n).listModels();for(const r in e)t[n+di+r]=e[r]}return t},moveModel:async function(e,t){return gi(e,t,!0)},removeModel:async function(e){const t=mi(e);return fi.getManager(t.scheme).removeModel(t.path)}});const bi=ho({cast_:function(e,t){const n=lo(e,"x","cast");if(!function(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if("string"===t&&"string"!==n.dtype||"string"!==t&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");const r={x:n},a={dtype:t};return as.runKernel(Vt,r,a)}}),_i=ho({matMul_:function(e,t,n=!1,r=!1){let a=lo(e,"a","matMul"),s=lo(t,"b","matMul");[a,s]=Qa(a,s);const o={a,b:s},i={transposeA:n,transposeB:r};return as.runKernel(Ut,o,i)}}),xi=ho({oneHot_:function(e,t,n=1,r=0,a="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const s={indices:lo(e,"indices","oneHot","int32")},o={dtype:a,depth:t,onValue:n,offValue:r};return as.runKernel(Dn,s,o)}});function vi(){return as}function wi(e,t){return as.tidy(e,t)}function Ti(e){Ja(e).forEach((e=>e.dispose()))}function ki(e){return as.keep(e)}function Ii(e){return as.setBackend(e)}function Si(){return as.backendName}function Ei(e,t,n=1){return as.registerBackend(e,t,n)}const Ni=ho({imag_:function(e){const t={input:lo(e,"input","imag")};return as.runKernel("Imag",t)}}),Ci=ho({neg_:function(e){const t={x:lo(e,"x","neg")};return as.runKernel("Neg",t)}}),Ai=ho({real_:function(e){const t={input:lo(e,"input","real")};return as.runKernel("Real",t)}}),Ri=ho({transpose_:function(e,t,n){const r=lo(e,"x","transpose");if(null==t&&(t=r.shape.map(((e,t)=>t)).reverse()),Qe(r.rank===t.length,(()=>`Error in transpose: rank of input ${r.rank} must match length of perm ${t}.`)),t.forEach((e=>{Qe(e>=0&&e<r.rank,(()=>"All entries in 'perm' must be between 0 and "+(r.rank-1)+` but got ${t}`))})),r.rank<=1)return r.clone();const a={x:r},s={perm:t};return"complex64"===r.dtype?wi((()=>{let e=Ai(r),t=Ni(r);return e=as.runKernel(xr,{x:e},s),t=as.runKernel(xr,{x:t},s),n&&(t=Ci(t)),fo(e,t)})):as.runKernel(xr,a,s)}});function $i(e,t){const n=e.length,r=[];for(let a=0;a<n;a++){const s=n-1-a,o=e[s]||1;(t[t.length-1-a]||1)>1&&1===o&&r.unshift(s)}return r}function Mi(e,t){const n=[];for(let r=0;r<t.length;r++){const a=e[e.length-r-1],s=t.length-r-1,o=t[s];(null==a||1===a&&o>1)&&n.unshift(s)}return n}function Fi(e,t){const n=[],r=Math.max(e.length,t.length);for(let a=0;a<r;a++){let r=e[e.length-a-1];null==r&&(r=1);let s=t[t.length-a-1];if(null==s&&(s=1),1===r)n.unshift(s);else if(1===s)n.unshift(r);else{if(r!==s)throw Error(`Operands could not be broadcast together with shapes ${e} and ${t}.`);n.unshift(r)}}return n}function Oi(e,t,n){if(Ze(e),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");const r=oo(e,n);if(3!==r.length&&1!==r.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return mo(e,t,r,n)}let Di;const Li=ho({fromPixels_:function(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,r=!1,a=!1,s=!1,o=!1,i=!1;if(e.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&e instanceof ImageData)r=!0;else if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)a=!0;else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)s=!0;else if(null!=e.getContext)o=!0;else{if(!("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap))throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);i=!0}if(null!=$r(kr,as.backendName)){const n={pixels:e},r={numChannels:t};return as.runKernel(kr,n,r)}const[u,l]=a?[e.videoWidth,e.videoHeight]:[e.width,e.height];let c,p;if(o)c=e.getContext("2d").getImageData(0,0,u,l).data;else if(r||n)c=e.data;else if(s||a||i){if(null==Di)if("undefined"==typeof document){if("undefined"==typeof OffscreenCanvas||"undefined"==typeof OffscreenCanvasRenderingContext2D)throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");Di=new OffscreenCanvas(1,1).getContext("2d")}else Di=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});Di.canvas.width=u,Di.canvas.height=l,Di.drawImage(e,0,0,u,l),c=Di.getImageData(0,0,u,l).data}if(4===t)p=new Int32Array(c);else{const e=u*l;p=new Int32Array(e*t);for(let n=0;n<e;n++)for(let e=0;e<t;++e)p[n*t+e]=c[4*n+e]}return Oi(p,[l,u,t],"int32")}});function Pi(e,t){const n=e.shape.length,r=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(r<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${r}.`);if("int32"!==t.dtype)throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[r-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[r-1]} vs. ${n}`);if(0===et(e.shape))throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const a=t.shape,s=a[a.length-1];let o=1;for(let e=0;e<a.length-1;++e)o*=a[e];const i=e.shape,u=a.slice();u.pop();let l=1;for(let e=s;e<n;++e)l*=i[e],u.push(i[e]);const c=[...yt(e.shape).map((e=>e/l)),1].slice(0,s);return[u,o,l,c]}function Bi(e,t,n){const r=t.rank>1?t.shape[t.rank-1]:1,a=t.rank>1?t.rank-1:1,s=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${r}, and batchDim: ${a}.`;if(n.rank<a)throw new Error(s+` update.rank < ${a}. `);if(e.length<r+(n.rank-a))throw new Error(s+` Output shape length < ${r+(n.rank-a)}`);if(n.rank!==a+e.length-r)throw new Error(s+" update.rank != "+(a+e.length-r));for(let e=0;e<a;++e)if(n.shape[e]!==t.shape[e])throw new Error(s+` updates.shape[${e}] (${n.shape[e]}) != indices.shape[${e}] (${t.shape[e]}).`);for(let t=0;t<n.rank-a;++t)if(n.shape[t+a]!==e[t+r])throw new Error(s+` updates.shape[${t+a}] (${n.shape[t+a]}) != shape[${t+a}] (${e[t+a]})`)}function Ui(e,t,n){if(t.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(e.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);if("int32"!==t.dtype)throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);if(n.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${n}`);if(0===n.length){if(0===t.size)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(0===e.size)throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`)}Bi(n,t,e)}function zi(e,t,n){const r=t.shape.length,a=r>1?t.shape[r-1]:1,s=n.length;let o=1;for(let e=a;e<s;++e)o*=n[e];const i=a<1?1:a;return{sliceRank:a,numUpdates:et(t.shape)/i,sliceSize:o,strides:[...yt(n.slice(0,a)),1],outputSize:et(n)}}function Vi(e,t,n){const r=e.shape.length;Qe(r===t.length,(()=>`Error in slice${r}D: Length of begin ${t} must match the rank of the array (${r}).`)),Qe(r===n.length,(()=>`Error in slice${r}D: Length of size ${n} must match the rank of the array (${r}).`));for(let a=0;a<r;++a)Qe(t[a]+n[a]<=e.shape[a],(()=>`Error in slice${r}D: begin[${a}] + size[${a}] (${t[a]+n[a]}) would overflow input.shape[${a}] (${e.shape[a]})`))}function Wi(e,t,n){const r=[];for(let a=0;a<e.length;a++)r[a]=Math.ceil((t[a]-e[a])/n[a]);return r}function Hi(e,t,n,r){const a=[...e];for(let e=a.length;e<r.length;e++)a.push(1);for(let e=0;e<n;e++)0===e?a[t]=1:(a.splice(t,0,1),a.pop());return a}function Gi(e,t,n){return n<=e?n:n-(t-1)}function ji(e,t){const n=[];for(let r=0;r<e;r++)n.push(t+r);return n}function Ki(e,t,n,r,a){const s=[...a],o=ji(n,t);for(let a=0;a<s.length;a++)if(o.indexOf(a)>-1)s[a]=0;else{const o=Gi(t,n,a);let i=r[o];e&1<<o&&(i=0),s[a]=i}return s}function qi(e,t,n,r,a){const s=[...a],o=ji(n,t);for(let a=0;a<s.length;a++)if(o.indexOf(a)>-1)s[a]=Number.MAX_SAFE_INTEGER;else{const o=Gi(t,n,a);let i=r[o];e&1<<o&&(i=Number.MAX_SAFE_INTEGER),s[a]=i}for(let e=0;e<s.length;e++){const t=a[e];s[e]<0&&(s[e]+=t),s[e]=qe(0,s[e],a[e])}return s}function Xi(e,t,n){let r=e[t];return(n&1<<t||null==r)&&(r=1),r}function Yi(e,t,n,r,a,s){let o=t[a];const i=n[a]||1;(e&1<<a||s&1<<a||null==o)&&(o=i>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);const u=r[a];return o<0&&(o+=u),o=qe(0,o,u-1),o}function Qi(e,t,n,r,a,s){let o=t[a];const i=n[a]||1;(e&1<<a||s&1<<a||null==o)&&(o=i>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);const u=r[a];return o<0&&(o+=u),o=i>0?qe(0,o,u):qe(-1,o,u-1),o}function Ji(e,t,n){let r=n.length;for(let e=0;e<n.length;e++)if(n[e]>1){r=e;break}for(let a=r+1;a<n.length;a++)if(t[a]>0||n[a]!==e[a])return!1;return!0}function Zi(e,t){let n=e.length>0?e[e.length-1]:1;for(let r=0;r<e.length-1;r++)n+=e[r]*t[r];return n}function eu(e,t,n){let r;const a=e.shape.length;let s;return r="number"==typeof t?[t,...new Array(a-1).fill(0)]:t.length<a?t.concat(new Array(a-t.length).fill(0)):t.slice(),r.forEach((e=>{Qe(-1!==e,(()=>"slice() does not support negative begin indexing."))})),s=null==n?new Array(a).fill(-1):"number"==typeof n?[n,...new Array(a-1).fill(-1)]:n.length<a?n.concat(new Array(a-n.length).fill(-1)):n,s=s.map(((t,n)=>t>=0?t:(Qe(-1===t,(()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`)),e.shape[n]-r[n]))),[r,s]}function tu(e,t,n,r,a,s,o,i,u){let l;if(null==r?(l=new Array(t.length),l.fill(1)):l=r,null!=o&&0!=(o&o-1))throw new Error("Multiple ellipses in slice is not allowed.");let c=!1;const p={dims:l.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:l.slice(),beginMask:a,endMask:s,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:u};for(let e=0;e<p.dims;e++)c&&0!=(1<<e&i)&&p.numAddAxisAfterEllipsis++,1<<e&o&&(c=!0);c||(p.ellipsisMask|=1<<p.dims,p.dims++);const h={dims:e.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};!function(e,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let n=0;t.beginValid=null!=e.begin,t.endValid=null!=e.end,t.begin=new Array(t.dims),t.end=new Array(t.dims),t.strides=new Array(t.dims),t.finalShapeGatherIndices=[],t.finalShapeGatherIndicesSparse=[],t.inputShapeGatherIndicesSparse=new Array(t.dims);for(let r=0;r<e.dims;r++)if(1<<r&e.ellipsisMask){const a=Math.min(t.dims-(e.dims-r)+1+e.numAddAxisAfterEllipsis,t.dims);for(;n<a;n++)t.begin[n]=0,t.end[n]=0,t.strides[n]=1,t.beginMask|=1<<n,t.endMask|=1<<n,t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(-1),t.inputShapeGatherIndicesSparse[n]=r}else if(1<<r&e.newAxisMask)t.finalShapeGatherIndices.push(-2),t.finalShapeGatherIndicesSparse.push(-1);else{if(n===t.begin.length)throw Error(`Index out of range using input dim ${n}; input has only ${t.dims} dims, ${t.begin.length}.`);null!=e.begin&&(t.begin[n]=e.begin[r]),null!=e.end&&(t.end[n]=e.end[r]),t.strides[n]=e.strides[r],e.beginMask&1<<r&&(t.beginMask|=1<<n),e.endMask&1<<r&&(t.endMask|=1<<n),e.shrinkAxisMask&1<<r?(t.finalShapeGatherIndices.push(-1),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<n):(t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(r)),t.inputShapeGatherIndicesSparse[n]=r,n++}}(p,h);let d=!0,f=!0,m=!0;const g=[],y=[];for(let t=0;t<e.length;++t){if(0===h.strides[t])throw Error(`strides[${t}] must be non-zero`);const n=!!(h.shrinkAxisMask&1<<t),r=e[t];if(-1===r){g.push(n?1:-1);continue}const a=[h.beginMask&1<<t,h.endMask&1<<t],s=[h.strides[t]>0?0:-1,h.strides[t]>0?r:r-1];if(n&&h.strides[t]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&1===h.strides[t];const o=!!(h.beginMask&1<<t&&h.endMask&1<<t);if(h.beginValid&&h.endValid){if(n){const e=h.begin[t]<0?r+h.begin[t]:h.begin[t];if(h.begin[t]=e,h.end[t]=h.begin[t]+1,e<0||e>=r)throw Error(`slice index ${h.begin[t]} of dimension ${t} out of bounds.`)}else h.begin[t]=nu(h.begin[t],0,h.strides[t],r,a,s),h.end[t]=nu(h.end[t],1,h.strides[t],r,a,s);const e=1===h.strides[t]&&0===h.begin[t]&&h.end[t]===r;d=d&&e,f=f&&(0===t&&1===h.strides[t]||e)}else d=d&&1===h.strides[t]&&o,f=f&&(0===t&&1===h.strides[t]||o);let i,u=!1;if(h.beginValid&&h.endValid?(i=h.end[t]-h.begin[t],u=!0):n?(i=1,u=!0):o&&r>=0&&(i=h.strides[t]<0?-r:r,u=!0),u){let e;e=0===i||i<0!=h.strides[t]<0?0:Math.trunc(i/h.strides[t])+(i%h.strides[t]!=0?1:0),g.push(e)}else g.push(-1)}for(let e=0;e<h.finalShapeGatherIndices.length;++e){const t=h.finalShapeGatherIndices[e];t>=0?y.push(g[t]):-2===t&&y.push(1)}const b=y.filter(((e,t)=>-2!==h.finalShapeGatherIndices[t]));return{finalShapeSparse:b,finalShape:y,isIdentity:d,sliceDim0:f,isSimpleSlice:m,begin:h.begin,end:h.end,strides:h.strides}}function nu(e,t,n,r,a,s){if(a[t])return n>0?s[t]:s[t+1&1];{const t=e<0?r+e:e;return t<s[0]?s[0]:t>s[1]?s[1]:t}}var ru=Object.freeze({__proto__:null,assertParamsValid:Vi,maskToAxes:function(e){const t=[];let n=0;for(;e>0;)1&e&&t.push(n),e/=2,n++;return t},computeOutShape:Wi,stridesWithElidedDims:Hi,getNormalizedAxes:function(e,t,n,r,a,s,o,i,u){const l=e.length;let c=new Array(l),p=new Array(l),h=new Array(l);if(t.length&&n>0){const u=t[0],l=n+1;c=Ki(o,u,l,r,e),p=qi(i,u,l,a,e),h=Hi(s,u,l,e)}else for(let t=0;t<l;t++)c[t]=Yi(o,r,s,e,t,u),p[t]=Qi(i,a,s,e,t,u),h[t]=Xi(s,t,u);return{begin:c,end:p,strides:h}},startIndicesWithElidedDims:Ki,stopIndicesWithElidedDims:qi,stridesForAxis:Xi,startForAxis:Yi,stopForAxis:Qi,isSliceContinous:Ji,computeFlatOffset:Zi,parseSliceParams:eu,sliceInfo:tu});const au=ho({add_:function(e,t){let n=lo(e,"a","add"),r=lo(t,"b","add");[n,r]=Qa(n,r);const a={a:n,b:r};return as.runKernel(Ft,a)}}),su=ho({floorDiv_:function(e,t){let n=lo(e,"a","floorDiv"),r=lo(t,"b","floorDiv");[n,r]=Qa(n,r);const a={a:n,b:r};return as.runKernel(ln,a)}}),ou=ho({div_:function(e,t){let n=lo(e,"a","div"),r=lo(t,"b","div");if([n,r]=Qa(n,r),"int32"===n.dtype&&"int32"===r.dtype)return su(n,r);const a={a:n,b:r};return as.runKernel(en,a,{})}}),iu=ho({mul_:function(e,t){let n=lo(e,"a","mul"),r=lo(t,"b","mul");[n,r]=Qa(n,r);const a={a:n,b:r};return as.runKernel(An,a)}}),uu=ho({abs_:function(e){const t=lo(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return as.runKernel("ComplexAbs",e)}{const e={x:t};return as.runKernel("Abs",e)}}}),lu=ho({acos_:function(e){const t={x:lo(e,"x","acos")};return as.runKernel("Acos",t)}}),cu=ho({acosh_:function(e){const t={x:lo(e,"x","acosh")};return as.runKernel("Acosh",t)}}),pu=ho({addN_:function(e){Qe(Array.isArray(e),(()=>"The argument passed to tf.addN() must be a list of tensors")),Qe(e.length>=1,(()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`));const t=e.map(((e,t)=>lo(e,`tensors${t}`,"addN"))),n=t[0];t.forEach((e=>{if(e.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")})),t.forEach((e=>{if(!tt(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));const r=t;return as.runKernel(Ot,r)}}),hu=ho({all_:function(e,t=null,n=!1){const r={x:lo(e,"x","all","bool")},a={axis:t,keepDims:n};return as.runKernel(Dt,r,a)}}),du=ho({any_:function(e,t=null,n=!1){const r={x:lo(e,"x","any","bool")},a={axis:t,keepDims:n};return as.runKernel(Lt,r,a)}}),fu=ho({argMax_:function(e,t=0){const n={x:lo(e,"x","argMax")},r={axis:t};return as.runKernel(Pt,n,r)}}),mu=ho({argMin_:function(e,t=0){const n={x:lo(e,"x","argMin")},r={axis:t};return as.runKernel("ArgMin",n,r)}}),gu=ho({asin_:function(e){const t={x:lo(e,"x","asin")};return as.runKernel("Asin",t)}}),yu=ho({asinh_:function(e){const t={x:lo(e,"x","asinh")};return as.runKernel("Asinh",t)}}),bu=ho({atan_:function(e){const t={x:lo(e,"x","atan")};return as.runKernel("Atan",t)}}),_u=ho({atan2_:function(e,t){let n=lo(e,"a","atan2"),r=lo(t,"b","atan2");[n,r]=Qa(n,r);const a={a:n,b:r};return as.runKernel("Atan2",a)}}),xu=ho({atanh_:function(e){const t={x:lo(e,"x","atanh")};return as.runKernel("Atanh",t)}});function vu(e,t,n,r,a,s,o="channelsLast"){const[i,u]=Iu(t);let l;if("channelsLast"===o)l=[i,u,e[3],e[3]];else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);l=[i,u,e[1],e[1]]}return wu(e,l,n,r,a,s,!1,o)}function wu(e,t,n,r,a,s,o=!1,i="channelsLast"){let[u,l,c,p]=[-1,-1,-1,-1];if("channelsLast"===i)[u,l,c,p]=e;else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);[u,p,l,c]=e}const[h,d,,f]=t,[m,g]=Iu(n),[y,b]=Iu(r),_=Eu(h,y),x=Eu(d,b),{padInfo:v,outHeight:w,outWidth:T}=function(e,t,n,r,a,s,o,i,u){let l,c,p;if("number"==typeof e){l={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const a=function(e,t,n,r,a){null==r&&(r=ku(e,t,n));const s=e[1];return[Nu((e[0]-t+2*r)/n+1,a),Nu((s-t+2*r)/n+1,a)]}([t,n],s,r,e,i);c=a[0],p=a[1]}else if("same"===e){c=Math.ceil(t/r),p=Math.ceil(n/a);const e=Math.max(0,(c-1)*r+s-t),i=Math.max(0,(p-1)*a+o-n),u=Math.floor(e/2),h=e-u,d=Math.floor(i/2);l={top:u,bottom:h,left:d,right:i-d,type:"SAME"}}else if("valid"===e)l={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-s+1)/r),p=Math.ceil((n-o+1)/a);else{if("object"!=typeof e)throw Error(`Unknown padding parameter: ${e}`);{const h="channelsLast"===u?e[1][0]:e[2][0],d="channelsLast"===u?e[1][1]:e[2][1],f="channelsLast"===u?e[2][0]:e[3][0],m="channelsLast"===u?e[2][1]:e[3][1];l={top:h,bottom:d,left:f,right:m,type:0===h&&0===d&&0===f&&0===m?"VALID":"EXPLICIT"},c=Nu((t-s+h+d)/r+1,i),p=Nu((n-o+f+m)/a+1,i)}}return{padInfo:l,outHeight:c,outWidth:p}}(a,l,c,m,g,_,x,s,i),k=o?f*p:f;let I;return"channelsFirst"===i?I=[u,k,w,T]:"channelsLast"===i&&(I=[u,w,T,k]),{batchSize:u,dataFormat:i,inHeight:l,inWidth:c,inChannels:p,outHeight:w,outWidth:T,outChannels:k,padInfo:v,strideHeight:m,strideWidth:g,filterHeight:h,filterWidth:d,effectiveFilterHeight:_,effectiveFilterWidth:x,dilationHeight:y,dilationWidth:b,inShape:e,outShape:I,filterShape:t}}function Tu(e,t,n,r,a,s=!1,o="channelsLast",i){let[u,l,c,p,h]=[-1,-1,-1,-1,-1];if("channelsLast"===o)[u,l,c,p,h]=e;else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);[u,h,l,c,p]=e}const[d,f,m,,g]=t,[y,b,_]=Su(n),[x,v,w]=Su(r),T=Eu(d,x),k=Eu(f,v),I=Eu(m,w),{padInfo:S,outDepth:E,outHeight:N,outWidth:C}=function(e,t,n,r,a,s,o,i,u,l,c){let p,h,d,f;if("valid"===e&&(e=0),"number"==typeof e){p={top:e,bottom:e,left:e,right:e,front:e,back:e,type:0===e?"VALID":"NUMBER"};const m=function(e,t,n,r,a,s){null==a&&(a=ku(e,t[0],r[0]));const o=[0,0,0,1];for(let n=0;n<3;n++)e[n]+2*a>=t[n]&&(o[n]=Nu((e[n]-t[n]+2*a)/r[n]+1,s));return o}([t,n,r,1],[i,u,l],0,[a,s,o],e,c);h=m[0],d=m[1],f=m[2]}else{if("same"!==e)throw Error(`Unknown padding parameter: ${e}`);{h=Math.ceil(t/a),d=Math.ceil(n/s),f=Math.ceil(r/o);const e=(h-1)*a+i-t,c=(d-1)*s+u-n,m=(f-1)*o+l-r,g=Math.floor(e/2),y=e-g,b=Math.floor(c/2),_=c-b,x=Math.floor(m/2);p={top:b,bottom:_,left:x,right:m-x,front:g,back:y,type:"SAME"}}}return{padInfo:p,outDepth:h,outHeight:d,outWidth:f}}(a,l,c,p,y,b,_,T,k,I,i),A=s?g*h:g;let R;return"channelsFirst"===o?R=[u,A,E,N,C]:"channelsLast"===o&&(R=[u,E,N,C,A]),{batchSize:u,dataFormat:o,inDepth:l,inHeight:c,inWidth:p,inChannels:h,outDepth:E,outHeight:N,outWidth:C,outChannels:A,padInfo:S,strideDepth:y,strideHeight:b,strideWidth:_,filterDepth:d,filterHeight:f,filterWidth:m,effectiveFilterDepth:T,effectiveFilterHeight:k,effectiveFilterWidth:I,dilationDepth:x,dilationHeight:v,dilationWidth:w,inShape:e,outShape:R,filterShape:t}}function ku(e,t,n,r=1){const a=Eu(t,r);return Math.floor((e[0]*(n-1)-n+a)/2)}function Iu(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function Su(e){return"number"==typeof e?[e,e,e]:e}function Eu(e,t){return t<=1?e:e+(e-1)*(t-1)}function Nu(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function Cu(e){const[t,n,r]=Iu(e);return 1===t&&1===n&&1===r}function Au(e,t){return Cu(e)||Cu(t)}function Ru(e){return Iu(e).every((e=>e>0))}function $u(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function Mu(e,t,n){if(null!=n){if("string"==typeof t)throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if("number"==typeof t)Qe(nt(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`));else{if("object"!=typeof t)throw Error(`Error in ${e}: Unknown padding parameter: ${t}`);t.forEach((t=>{t.forEach((t=>{Qe(nt(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`))}))}))}}}const Fu=ho({reshape_:function(e,t){const n={x:lo(e,"x","reshape","string_or_numeric")},r={shape:t};return as.runKernel(Hn,n,r)}}),Ou=ho({avgPool_:function(e,t,n,r,a){const s=lo(e,"x","avgPool","float32");Qe(Au(n,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`));let o=s,i=!1;3===s.rank&&(i=!0,o=Fu(s,[1,s.shape[0],s.shape[1],s.shape[2]])),Qe(4===o.rank,(()=>`Error in avgPool: x must be rank 4 but got rank ${o.rank}.`)),Mu("avgPool",r,a);const u={x:o},l={filterSize:t,strides:n,pad:r,dimRoundingMode:a};let c=as.runKernel(Bt,u,l);return c=bi(c,s.dtype),i?Fu(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),Du=ho({avgPool3d_:function(e,t,n,r,a,s="NDHWC"){const o=lo(e,"x","avgPool3d","float32");let i=o,u=!1;4===o.rank&&(u=!0,i=Fu(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),Qe(5===i.rank,(()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`)),Qe("NDHWC"===s,(()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`)),Qe("number"==typeof n&&n>0||Array.isArray(n)&&n[0]>0&&n[1]>0&&n[2]>0,(()=>`Error in avgPool3d: Stride must be > 0, but got '${n}'`)),Mu("avgPool3d",r,a);const l={x:i},c={filterSize:t,strides:n,pad:r,dimRoundingMode:a,dataFormat:s};let p=as.runKernel("AvgPool3D",l,c);return p=bi(p,i.dtype),u?Fu(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}}),Lu=ho({clone_:function(e){const t={x:lo(e,"x","clone","string_or_numeric")};return as.runKernel(mn,t)}}),Pu=ho({concat_:function(e,t=0){Qe(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=co(e,"tensors","concat","string_or_numeric");if("complex64"===n[0].dtype&&n.forEach((e=>{if("complex64"!==e.dtype)throw new Error(`Cannot concatenate complex64 tensors with a tensor\n with dtype ${e.dtype}. `)})),1===n.length)return Lu(n[0]);const r=n,a={axis:t};return as.runKernel(Gt,r,a)}}),Bu=ho({sigmoid_:function(e){const t={x:lo(e,"x","sigmoid","float32")};return as.runKernel(er,t)}}),Uu=ho({slice_:function(e,t,n){const r=lo(e,"x","slice","string_or_numeric");if(0===r.rank)throw new Error("Slicing scalar is not possible");const a={x:r},s={begin:t,size:n};return as.runKernel(Zn,a,s)}}),zu=ho({tanh_:function(e){const t={x:lo(e,"x","tanh","float32")};return as.runKernel(gr,t)}}),Vu=ho({basicLSTMCell_:function(e,t,n,r,a,s){const o=lo(e,"forgetBias","basicLSTMCell"),i=lo(t,"lstmKernel","basicLSTMCell"),u=lo(n,"lstmBias","basicLSTMCell"),l=lo(r,"data","basicLSTMCell"),c=lo(a,"c","basicLSTMCell"),p=lo(s,"h","basicLSTMCell"),h=Pu([l,p],1),d=_i(h,i),f=au(d,u),m=f.shape[0],g=f.shape[1]/4,y=[m,g],b=Uu(f,[0,0],y),_=Uu(f,[0,g],y),x=Uu(f,[0,2*g],y),v=Uu(f,[0,3*g],y),w=au(iu(Bu(b),zu(_)),iu(c,Bu(au(o,x))));return[w,iu(zu(w),Bu(v))]}}),Wu=ho({batchToSpaceND_:function(e,t,n){const r=lo(e,"x","batchToSpaceND"),a=t.reduce(((e,t)=>e*t));Qe(r.rank>=1+t.length,(()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`)),Qe(n.length===t.length,(()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`)),Qe(r.shape[0]%a==0,(()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${a}`));const s={x:r},o={blockShape:t,crops:n};return as.runKernel(zt,s,o)}}),Hu=ho({batchNorm_:function(e,t,n,r,a,s){null==s&&(s=.001);const o=lo(e,"x","batchNorm"),i=lo(t,"mean","batchNorm"),u=lo(n,"variance","batchNorm");let l,c;null!=a&&(l=lo(a,"scale","batchNorm")),null!=r&&(c=lo(r,"offset","batchNorm")),Qe(i.rank===u.rank,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),Qe(null==c||i.rank===c.rank,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),Qe(null==l||i.rank===l.rank,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));const p=function(e){let t;return t=0===e.rank||1===e.rank?Fu(e,[1,1,1,e.size]):2===e.rank?Fu(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?Fu(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(o),h={x:p,scale:l,offset:c,mean:i,variance:u},d={varianceEpsilon:s},f=as.runKernel(cn,h,d);return Fu(f,o.shape)}}),Gu=ho({batchNorm2d_:function(e,t,n,r,a,s){const o=lo(e,"x","batchNorm"),i=lo(t,"mean","batchNorm"),u=lo(n,"variance","batchNorm");let l,c;return null!=a&&(l=lo(a,"scale","batchNorm")),null!=r&&(c=lo(r,"offset","batchNorm")),Qe(2===o.rank,(()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`)),Qe(2===i.rank||1===i.rank,(()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`)),Qe(2===u.rank||1===u.rank,(()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${u.rank}.`)),null!=l&&Qe(2===l.rank||1===l.rank,(()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${l.rank}.`)),null!=c&&Qe(2===c.rank||1===c.rank,(()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`)),Hu(o,i,u,c,l,s)}}),ju=ho({batchNorm3d_:function(e,t,n,r,a,s){const o=lo(e,"x","batchNorm"),i=lo(t,"mean","batchNorm"),u=lo(n,"variance","batchNorm");let l,c;return null!=a&&(l=lo(a,"scale","batchNorm")),null!=r&&(c=lo(r,"offset","batchNorm")),Qe(3===o.rank,(()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`)),Qe(3===i.rank||1===i.rank,(()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`)),Qe(3===u.rank||1===u.rank,(()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${u.rank}.`)),null!=l&&Qe(3===l.rank||1===l.rank,(()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${l.rank}.`)),null!=c&&Qe(3===c.rank||1===c.rank,(()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`)),Hu(o,i,u,c,l,s)}}),Ku=ho({batchNorm4d_:function(e,t,n,r,a,s){const o=lo(e,"x","batchNorm"),i=lo(t,"mean","batchNorm"),u=lo(n,"variance","batchNorm");let l,c;return null!=a&&(l=lo(a,"scale","batchNorm")),null!=r&&(c=lo(r,"offset","batchNorm")),Qe(4===o.rank,(()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`)),Qe(4===i.rank||1===i.rank,(()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`)),Qe(4===u.rank||1===u.rank,(()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${u.rank}.`)),null!=l&&Qe(4===l.rank||1===l.rank,(()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${l.rank}.`)),null!=c&&Qe(4===c.rank||1===c.rank,(()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`)),Hu(o,i,u,c,l,s)}}),qu=ho({bincount_:function(e,t,n){const r=lo(e,"x","bincount"),a=lo(t,"weights","bincount");Qe("int32"===r.dtype,(()=>`Error in bincount: input dtype must be int32, but got ${r.dtype}`)),Qe(n>=0,(()=>`size must be non-negative, but got ${n}.`)),Qe(a.size===r.size||0===a.size,(()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${r.shape}, weights shape: ${a.shape}.`));const s={x:r,weights:a},o={size:n};return as.runKernel("Bincount",s,o)}}),Xu=ho({broadcastArgs_:function(e,t){const n=lo(e,"s0","broadcastArgs","int32"),r=lo(t,"s1","broadcastArgs","int32");if(1!==n.rank)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(1!==r.rank)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${r.rank}`);const a={s0:n,s1:r};return as.runKernel("BroadcastArgs",a)}}),Yu=ho({broadcastTo_:function(e,t){let n=lo(e,"broadcastTo","x");const r=n.shape;if(wt(t),t.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){const e=n.shape.slice();for(;e.length<t.length;)e.unshift(1);n=Fu(n,e)}const a=n.shape,s=Array.from(t);for(let e=t.length-1;e>=0;e--)if(a[e]===t[e])s[e]=1;else if(1!==n.shape[e])throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${t}].`);const o=s.map(((e,t)=>e>1?t:-1)).filter((e=>e>=0));if(0===o.length)return Lu(n);const i={x:n},u={reps:s};return as.runKernel(yr,i,u)}});function Qu(e,t="float32",n){return t=t||"float32",wt(e),new Ba(e,t,n)}const Ju=ho({ceil_:function(e){const t={x:lo(e,"x","ceil","float32")};return as.runKernel(Wt,t)}});function Zu(e,t,n){wt(e);const r={shape:e,value:t,dtype:n};return as.runKernel(sn,{},r)}const el=ho({clipByValue_:function(e,t,n){const r=lo(e,"x","clipByValue");if(Qe(t<=n,(()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`)),t===n)return Zu(r.shape,t,r.dtype);const a={x:r},s={clipValueMin:t,clipValueMax:n};return as.runKernel(Ht,a,s)}}),tl=ho({concat1d_:function(e){return Pu(e,0)}}),nl=ho({concat2d_:function(e,t){return Pu(e,t)}}),rl=ho({concat3d_:function(e,t){return Pu(e,t)}}),al=ho({concat4d_:function(e,t){return Pu(e,t)}}),sl=ho({conv2d_:function(e,t,n,r,a="NHWC",s=[1,1],o){const i=lo(e,"x","conv2d","float32"),u=lo(t,"filter","conv2d","float32");let l=i,c=!1;3===i.rank&&(c=!0,l=Fu(i,[1,i.shape[0],i.shape[1],i.shape[2]])),Qe(4===l.rank,(()=>`Error in conv2d: input must be rank 4, but got rank ${l.rank}.`)),Qe(4===u.rank,(()=>`Error in conv2d: filter must be rank 4, but got rank ${u.rank}.`)),Mu("conv2d",r,o);const p="NHWC"===a?l.shape[3]:l.shape[1];Qe(p===u.shape[2],(()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${u.shape[2]}.`)),Qe(Au(n,s),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`)),Qe(Ru(s),(()=>"Error in conv2D: Dilated rates should be larger than 0.")),Qe(Ru(n),(()=>"Error in conv2D: Strides should be larger than 0."));const h={x:l,filter:u},d={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o},f=as.runKernel(jt,h,d);return c?Fu(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),ol=ho({conv1d_:function(e,t,n,r,a="NWC",s=1,o){const i=lo(e,"x","conv1d"),u=lo(t,"filter","conv1d");let l=i,c=!1;2===i.rank&&(c=!0,l=Fu(i,[1,i.shape[0],i.shape[1]])),Qe(3===l.rank,(()=>`Error in conv1d: input must be rank 3, but got rank ${l.rank}.`)),Qe(3===u.rank,(()=>`Error in conv1d: filter must be rank 3, but got rank ${u.rank}.`)),Mu("conv1d",r,o),Qe(l.shape[2]===u.shape[1],(()=>`Error in conv1d: depth of input (${l.shape[2]}) must match input depth for filter ${u.shape[1]}.`)),Qe(Au(n,s),(()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${s}'`)),Qe(Ru(s),(()=>"Error in conv1D: Dilated rates should be larger than 0.")),Qe(Ru(n),(()=>"Error in conv1D: Stride should be larger than 0.")),Qe("NWC"===a,(()=>`Error in conv1d: got dataFormat of ${a} but only NWC is currently supported.`));const p=Fu(u,[1,u.shape[0],u.shape[1],u.shape[2]]),h=Fu(l,[l.shape[0],1,l.shape[1],l.shape[2]]),d=sl(h,p,[1,n],r,"NHWC",[1,s],o);return Fu(d,c?[d.shape[2],d.shape[3]]:[d.shape[0],d.shape[2],d.shape[3]])}}),il=ho({conv2DBackpropInput_:function(e,t,n,r,a,s="NHWC",o){Qe(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let i=e,u=t,l=!1;3===t.rank&&(l=!0,u=Fu(t,[1,t.shape[0],t.shape[1],t.shape[2]]),i=[1,e[0],e[1],e[2]]),Qe(4===i.length,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`)),Qe(4===u.rank,(()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${u.rank}`)),Qe(4===n.rank,(()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`));const c="NHWC"===s?i[3]:i[1],p="NHWC"===s?u.shape[3]:u.shape[1];Qe(c===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${n.shape[2]}.`)),Qe(p===n.shape[3],(()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[3]}.`)),Mu("conv2dDerInput",a,o);const h={dy:u,filter:n},d={strides:r,pad:a,dataFormat:s,dimRoundingMode:o,inputShape:i},f=as.runKernel(Kt,h,d);return l?Fu(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),ul=ho({conv2dTranspose_:function(e,t,n,r,a,s){const o=lo(e,"x","conv2dTranspose"),i=lo(t,"filter","conv2dTranspose");return il(n,o,i,r,a,"NHWC",s)}}),ll=ho({conv3d_:function(e,t,n,r,a="NDHWC",s=[1,1,1]){const o=lo(e,"x","conv3d"),i=lo(t,"filter","conv3d");let u=o,l=!1;4===o.rank&&(l=!0,u=Fu(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),Qe(5===u.rank,(()=>`Error in conv3d: input must be rank 5, but got rank ${u.rank}.`)),Qe(5===i.rank,(()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`)),Qe(u.shape[4]===i.shape[3],(()=>`Error in conv3d: depth of input (${u.shape[4]}) must match input depth for filter ${i.shape[3]}.`)),Qe(Au(n,s),(()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`)),Qe("NDHWC"===a,(()=>`Error in conv3d: got dataFormat of ${a} but only NDHWC is currently supported.`)),Qe(Ru(s),(()=>"Error in conv3D: Dilated rates should be larger than 0.")),Qe(Ru(n),(()=>"Error in conv3D: Strides should be larger than 0."));const c={x:u,filter:i},p={strides:n,pad:r,dataFormat:a,dilations:s},h=as.runKernel("Conv3D",c,p);return l?Fu(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}}),cl=ho({conv3DBackpropInput_:function(e,t,n,r,a){Qe(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let s=e,o=t,i=!1;4===t.rank&&(i=!0,o=Fu(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),s=[1,e[0],e[1],e[2],e[3]]);const u=s[4],l=o.shape[4];Qe(5===s.length,(()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`)),Qe(5===o.rank,(()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`)),Qe(5===n.rank,(()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`)),Qe(u===n.shape[3],(()=>`Error in conv3dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[3]}.`)),Qe(l===n.shape[4],(()=>`Error in conv3dDerInput: depth of output (${l}) must match output depth for filter ${n.shape[4]}.`));const c={dy:o,filter:n},p={pad:a,strides:r,inputShape:s},h=as.runKernel("Conv3DBackpropInputV2",c,p);return i?Fu(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}}),pl=ho({conv3dTranspose_:function(e,t,n,r,a){const s=lo(e,"x","conv3dTranspose"),o=lo(t,"filter","conv3dTranspose");return cl(n,s,o,r,a)}}),hl=ho({cos_:function(e){const t={x:lo(e,"x","cos","float32")};return as.runKernel("Cos",t)}}),dl=ho({cosh_:function(e){const t={x:lo(e,"x","cosh","float32")};return as.runKernel(qt,t)}}),fl=ho({cumprod_:function(e,t=0,n=!1,r=!1){const a={x:lo(e,"x","cumprod")},s={axis:t,exclusive:n,reverse:r};return as.runKernel(Xt,a,s)}}),ml=ho({cumsum_:function(e,t=0,n=!1,r=!1){const a={x:lo(e,"x","cumsum")},s={axis:t,exclusive:n,reverse:r};return as.runKernel(Yt,a,s)}}),gl=ho({denseBincount_:function(e,t,n,r=!1){const a=lo(e,"x","denseBincount"),s=lo(t,"weights","denseBincount");Qe("int32"===a.dtype,(()=>`Error in denseBincount: input dtype must be int32, but got ${a.dtype}`)),Qe(a.rank<=2,(()=>`Error in denseBincount: input must be at most rank 2, but got rank ${a.rank}.`)),Qe(n>=0,(()=>`size must be non-negative, but got ${n}.`)),Qe(s.size===a.size||0===s.size,(()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${a.shape}, weights shape: ${s.shape}.`));const o={x:a,weights:s},i={size:n,binaryOutput:r};return as.runKernel("DenseBincount",o,i)}}),yl=ho({depthToSpace_:function(e,t,n="NHWC"){const r=lo(e,"x","depthToSpace","float32"),a="NHWC"===n?r.shape[1]:r.shape[2],s="NHWC"===n?r.shape[2]:r.shape[3],o="NHWC"===n?r.shape[3]:r.shape[1];Qe(t>1,(()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`)),Qe(a*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${a} and ${t} for depthToSpace with input shape\n ${r.shape}`)),Qe(s*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${s} and ${t} for depthToSpace with input shape\n ${r.shape}`)),Qe(o%(t*t)==0,(()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${r.shape}`));const i={x:r},u={blockSize:t,dataFormat:n};return as.runKernel(Jt,i,u)}}),bl=ho({depthwiseConv2d_:function(e,t,n,r,a="NHWC",s=[1,1],o){const i=lo(e,"x","depthwiseConv2d","float32"),u=lo(t,"filter","depthwiseConv2d","float32");let l=i,c=!1;3===i.rank&&(c=!0,l=Fu(i,[1,i.shape[0],i.shape[1],i.shape[2]])),Qe(4===l.rank,(()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${l.rank}.`)),Qe(4===u.rank,(()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${u.rank}.`));const p="NHWC"===a?l.shape[3]:l.shape[1];Qe(p===u.shape[2],(()=>`Error in depthwiseConv2d: number of input channels (${p}) must match the inChannels dimension in filter ${u.shape[2]}.`)),Mu("depthwiseConv2d",r,o);const h={x:l,filter:u},d={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o},f=as.runKernel(Zt,h,d);return c?Fu(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),_l=ho({diag_:function(e){const t={x:lo(e,"x","diag")};return as.runKernel("Diag",t)}}),xl=ho({dilation2d_:function(e,t,n,r,a=[1,1],s="NHWC"){const o=lo(e,"x","dilation2d"),i=lo(t,"filter","dilation2d");Qe(3===o.rank||4===o.rank,(()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`)),Qe(3===i.rank,(()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`)),Qe("NHWC"===s,(()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`));let u=o,l=!1;3===o.rank&&(u=Fu(o,[1,o.shape[0],o.shape[1],o.shape[2]]),l=!0),Qe(u.shape[3]===i.shape[2],(()=>`Error in dilation2d: input and filter must have the same depth: ${u.shape[3]} vs ${i.shape[2]}`));const c={x:u,filter:i},p={strides:n,pad:r,dilations:a},h=as.runKernel("Dilation2D",c,p);return l?Fu(h,[h.shape[1],h.shape[2],h.shape[3]]):h}}),vl=ho({equal_:function(e,t){let n=lo(e,"a","equal","string_or_numeric"),r=lo(t,"b","equal","string_or_numeric");[n,r]=Qa(n,r),Fi(n.shape,r.shape);const a={a:n,b:r};return as.runKernel(nn,a)}}),wl=ho({where_:function(e,t,n){const r=lo(t,"a","where"),a=lo(n,"b","where"),s=lo(e,"condition","where","bool"),o=Fi(Fi(s.shape,r.shape),a.shape),i={condition:Yu(s,o),t:Yu(r,o),e:Yu(a,o)};return as.runKernel(Jn,i)}}),Tl=ho({zerosLike_:function(e){const t={x:lo(e,"x","zerosLike")};return as.runKernel(wr,t)}}),kl=ho({divNoNan_:function(e,t){let n=lo(e,"a","div"),r=lo(t,"b","div");[n,r]=Qa(n,r);const a=ou(n,r),s=Tl(a),o=vl(r,s);return wl(o,s,a)}}),Il=ho({dot_:function(e,t){const n=lo(e,"t1","dot"),r=lo(t,"t2","dot");Qe(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),(()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${r.rank}.`));const a=1===n.rank?n.size:n.shape[1],s=1===r.rank?r.size:r.shape[0];if(Qe(a===s,(()=>`Error in dot: inner dimensions of inputs must match, but got ${a} and ${s}.`)),1===n.rank&&1===r.rank){const e=Fu(n,[1,-1]),t=Fu(r,[-1,1]),a=_i(e,t);return Fu(a,[])}if(1===n.rank&&2===r.rank){const e=Fu(n,[1,-1]),t=Fu(r,[r.shape[0],r.shape[1]]),a=_i(e,t);return Fu(a,[a.size])}if(2===n.rank&&1===r.rank){const e=Fu(r,[-1,1]),t=_i(n,e);return Fu(t,[t.size])}{const e=Fu(r,[r.shape[0],r.shape[1]]);return _i(n,e)}}}),Sl=ho({einsum_:function(e,...t){const n=t.map(((e,t)=>lo(e,`tensors${t}`,"einsum"))),r={equation:e};return as.runKernel("Einsum",n,r)}}),El=ho({elu_:function(e){const t={x:lo(e,"x","elu","float32")};return as.runKernel(tn,t)}}),Nl=ho({erf_:function(e){let t=lo(e,"x","erf");Qe("int32"===t.dtype||"float32"===t.dtype,(()=>"Input dtype must be `int32` or `float32`.")),"int32"===t.dtype&&(t=bi(t,"float32"));const n={x:t};return as.runKernel("Erf",n)}});function Cl(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function Al(e,t,n){const r=e.length+t.length,a=[];let s=0,o=0;for(let i=0;i<r;i++)-1===n.indexOf(i)?a.push(e[s++]):a.push(t[o++]);return a}function Rl(e,t){const n=[],r=e.length;for(let a=0;a<r;a++)-1===t.indexOf(a)&&n.push(e[a]);return[n,t.map((t=>e[t]))]}function $l(e,t){return Al(e,t.map((e=>1)),t)}function Ml(e,t,n){Qe(Cl(t,n),(()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`))}function Fl(e,t){if(Cl(e,t))return null;const n=[];for(let r=0;r<t;++r)-1===e.indexOf(r)&&n.push(r);return e.forEach((e=>n.push(e))),n}function Ol(e){return e.map(((e,t)=>[t,e])).sort(((e,t)=>e[1]-t[1])).map((e=>e[0]))}function Dl(e,t){const n=[];for(let r=t-e;r<t;++r)n.push(r);return n}const Ll=ho({max_:function(e,t=null,n=!1){const r={x:lo(e,"x","max")},a={reductionIndices:t,keepDims:n};return as.runKernel(Tn,r,a)}}),Pl=ho({min_:function(e,t=null,n=!1){const r={x:lo(e,"x","min")},a={axis:t,keepDims:n};return as.runKernel(En,r,a)}}),Bl=ho({pow_:function(e,t){let n=lo(e,"base","pow"),r=lo(t,"exp","pow");[n,r]=Qa(n,r);const a={a:n,b:r};return as.runKernel("Pow",a)}});function Ul(e,t){if((Sa(e)&&"string"!==t||Array.isArray(e))&&"complex64"!==t)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===t&&Sa(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return mo(e,[],[],t)}const zl=ho({sqrt_:function(e){const t={x:lo(e,"x","sqrt","float32")};return as.runKernel(tr,t)}}),Vl=ho({square_:function(e){const t=lo(e,"x","square");return as.runKernel("Square",{x:t},{})}}),Wl=ho({sum_:function(e,t=null,n=!1){let r=lo(e,"x","sum");"bool"===r.dtype&&(r=bi(r,"int32"));const a={x:r},s={axis:t,keepDims:n};return as.runKernel(nr,a,s)}});function Hl(e,t,n=null){if(0===e.rank)return uu(e);if(1!==e.rank&&null===n)return Hl(Fu(e,[-1]),t,n);if(1===e.rank||"number"==typeof n||Array.isArray(n)&&1===n.length){if(1===t)return Wl(uu(e),n);if(t===1/0)return Ll(uu(e),n);if(t===-1/0)return Pl(uu(e),n);if("euclidean"===t||2===t)return zl(Wl(Bl(uu(e),Ul(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&2===n.length){if(1===t)return Ll(Wl(uu(e),n[0]),n[1]-1);if(t===1/0)return Ll(Wl(uu(e),n[1]),n[0]);if(t===-1/0)return Pl(Wl(uu(e),n[1]),n[0]);if("fro"===t||"euclidean"===t)return zl(Wl(Vl(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const Gl=ho({norm_:function(e,t="euclidean",n=null,r=!1){const a=Hl(e=lo(e,"x","norm"),t,n);let s=a.shape;if(r){const t=it(n,e.shape);s=$l(a.shape,t)}return Fu(a,s)}}),jl=ho({euclideanNorm_:function(e,t=null,n=!1){return Gl(e,"euclidean",t,n)}}),Kl=ho({exp_:function(e){const t={x:lo(e,"x","exp")};return as.runKernel(rn,t)}}),ql=ho({expandDims_:function(e,t=0){const n=lo(e,"x","expandDims","string_or_numeric");Qe(t<=n.rank,(()=>"Axis must be <= rank of the tensor"));const r={input:n},a={dim:t};return as.runKernel(an,r,a)}}),Xl=ho({expm1_:function(e){const t={x:lo(e,"x","expm1")};return as.runKernel("Expm1",t)}}),Yl=ho({tile_:function(e,t){const n=lo(e,"x","tile","string_or_numeric");Qe(n.rank===t.length,(()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`));const r={x:n},a={reps:t};return as.runKernel(yr,r,a)}}),Ql=ho({eye_:function(e,t,n,r="float32"){null==t&&(t=e);const a=Qu([e,t],r),s=e<=t?e:t;for(let e=0;e<s;++e)a.set(1,e,e);const o=Fu(a.toTensor(),[e,t]);if(null==n)return o;if(1===n.length)return Yl(ql(o,0),[n[0],1,1]);if(2===n.length)return Yl(ql(ql(o,0),0),[n[0],n[1],1,1]);if(3===n.length)return Yl(ql(ql(ql(o,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${n.length}D.`)}}),Jl=ho({floor_:function(e){const t={x:lo(e,"x","floor","float32")};return as.runKernel(un,t)}}),Zl=ho({gather_:function(e,t,n=0,r=0){const a={x:lo(e,"x","gather"),indices:lo(t,"indices","gather","int32")},s={axis:n,batchDims:r};return as.runKernel(pn,a,s)}}),ec=ho({greater_:function(e,t){let n=lo(e,"a","greater","string_or_numeric"),r=lo(t,"b","greater","string_or_numeric");[n,r]=Qa(n,r),Fi(n.shape,r.shape);const a={a:n,b:r};return as.runKernel(dn,a)}}),tc=ho({greaterEqual_:function(e,t){let n=lo(e,"a","greaterEqual","string_or_numeric"),r=lo(t,"b","greaterEqual","string_or_numeric");[n,r]=Qa(n,r),Fi(n.shape,r.shape);const a={a:n,b:r};return as.runKernel(fn,a)}}),nc=ho({isFinite_:function(e){const t={x:lo(e,"x","isFinite")};return as.runKernel("IsFinite",t)}}),rc=ho({isInf_:function(e){const t={x:lo(e,"x","isInf")};return as.runKernel("IsInf",t)}}),ac=ho({isNaN_:function(e){const t={x:lo(e,"x","isNaN")};return as.runKernel(gn,t)}}),sc=ho({leakyRelu_:function(e,t=.2){const n={x:lo(e,"x","leakyRelu")},r={alpha:t};return as.runKernel(yn,n,r)}}),oc=ho({less_:function(e,t){let n=lo(e,"a","less","string_or_numeric"),r=lo(t,"b","less","string_or_numeric");[n,r]=Qa(n,r),Fi(n.shape,r.shape);const a={a:n,b:r};return as.runKernel(bn,a)}}),ic=ho({lessEqual_:function(e,t){let n=lo(e,"a","lessEqual","string_or_numeric"),r=lo(t,"b","lessEqual","string_or_numeric");[n,r]=Qa(n,r),Fi(n.shape,r.shape);const a={a:n,b:r};return as.runKernel(_n,a)}}),uc=ho({localResponseNormalization_:function(e,t=5,n=1,r=1,a=.5){const s=lo(e,"x","localResponseNormalization");Qe(4===s.rank||3===s.rank,(()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank ${s.rank}.`)),Qe(nt(t),(()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`));let o=s,i=!1;3===s.rank&&(i=!0,o=Fu(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const u={x:o},l={depthRadius:t,bias:n,alpha:r,beta:a},c=as.runKernel("LRN",u,l);return i?Fu(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),lc=ho({log_:function(e){const t={x:lo(e,"x","log","float32")};return as.runKernel("Log",t)}}),cc=ho({log1p_:function(e){const t={x:lo(e,"x","log1p")};return as.runKernel("Log1p",t)}});function pc(e){return as.customGrad(e)}const hc=ho({softplus_:function(e){const t={x:lo(e,"x","softplus")};return as.runKernel("Softplus",t)}}),dc=ho({logSigmoid_:function(e){const t=lo(e,"x","logSigmoid"),n=pc((e=>({value:Ci(hc(Ci(e))),gradFunc:t=>iu(t,Bu(Ci(e)))})));return n(t)}}),fc=ho({sub_:function(e,t){let n=lo(e,"a","sub"),r=lo(t,"b","sub");[n,r]=Qa(n,r);const a={a:n,b:r};return as.runKernel(mr,a)}}),mc=ho({logSoftmax_:function(e,t=-1){const n=lo(e,"logits","logSoftmax");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);const r=pc(((e,n)=>{const r=Ll(e,t,!0),a=fc(e,r),s=fc(bi(a,"float32"),lc(Wl(Kl(a),t,!0)));return n([s]),{value:s,gradFunc:(e,n)=>{const[r]=n,a=Kl(r);return fc(e,iu(Wl(e,t,!0),a))}}}));return r(n)}}),gc=ho({logSumExp_:function(e,t=null,n=!1){const r=lo(e,"x","logSumExp"),a=it(t,r.shape),s=Ll(r,a,!0),o=fc(r,s),i=Kl(o),u=Wl(i,a),l=lc(u),c=au(Fu(s,l.shape),l);if(n){const e=$l(c.shape,a);return Fu(c,e)}return c}}),yc=ho({logicalAnd_:function(e,t){const n=lo(e,"a","logicalAnd","bool"),r=lo(t,"b","logicalAnd","bool");Fi(n.shape,r.shape);const a={a:n,b:r};return as.runKernel(xn,a)}}),bc=ho({logicalNot_:function(e){const t={x:lo(e,"x","logicalNot","bool")};return as.runKernel(vn,t)}}),_c=ho({logicalOr_:function(e,t){const n=lo(e,"a","logicalOr","bool"),r=lo(t,"b","logicalOr","bool");Fi(n.shape,r.shape);const a={a:n,b:r};return as.runKernel(wn,a)}}),xc=ho({logicalXor_:function(e,t){const n=lo(e,"a","logicalXor","bool"),r=lo(t,"b","logicalXor","bool");return Fi(n.shape,r.shape),yc(_c(e,t),bc(yc(e,t)))}}),vc=2147483648,wc=ho({searchSorted_:function(e,t,n="left"){const r=lo(e,"sortedSequence","searchSorted"),a=lo(t,"values","searchSorted"),s=r.shape[r.shape.length-1],o=a.shape[a.shape.length-1],i=Fu(r,[-1,s]),u=Fu(a,[-1,o]);if(i.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(i.shape[0]!==u.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(et(u.shape)>=vc)throw new Error("values tensor size must less than 2147483648");if(i.shape[1]>=vc)throw new Error(`trailing dim_size must less than 2147483648 for int32 output type, was ${i.shape[1]}`);const l={sortedSequence:i,values:u},c={side:n};return as.runKernel("SearchSorted",l,c)}}),Tc=ho({maxPool_:function(e,t,n,r,a){const s=lo(e,"x","maxPool");let o=s,i=!1;3===s.rank&&(i=!0,o=Fu(s,[1,s.shape[0],s.shape[1],s.shape[2]])),Qe(4===o.rank,(()=>`Error in maxPool: input must be rank 4 but got rank ${o.rank}.`)),Qe(Au(n,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`)),Mu("maxPool",r,a);const u={x:o},l={filterSize:t,strides:n,pad:r,dimRoundingMode:a},c=as.runKernel(In,u,l);return i?Fu(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),kc=ho({maxPool3d_:function(e,t=[1,1,1],n,r,a,s="NDHWC"){const o=lo(e,"x","maxPool3d");let i=o,u=!1;4===o.rank&&(u=!0,i=Fu(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),Qe(5===i.rank,(()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`)),Qe("NDHWC"===s,(()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`)),Mu("maxPool3d",r,a);const l={x:i},c={filterSize:t,strides:n,pad:r,dimRoundingMode:a,dataFormat:s},p=as.runKernel("MaxPool3D",l,c);return u?Fu(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}}),Ic=ho({maxPoolWithArgmax_:function(e,t,n,r,a=!1){const s={x:lo(e,"x","maxPoolWithArgmax")},o={filterSize:t,strides:n,pad:r,includeBatchInIndex:a},i=as.runKernel("MaxPoolWithArgmax",s,o);return{result:i[0],indexes:i[1]}}}),Sc=ho({maximum_:function(e,t){let n=lo(e,"a","maximum"),r=lo(t,"b","maximum");[n,r]=Qa(n,r),"bool"===n.dtype&&(n=bi(n,"int32"),r=bi(r,"int32")),Fi(n.shape,r.shape);const a={a:n,b:r};return as.runKernel(kn,a)}}),Ec=ho({mean_:function(e,t=null,n=!1){const r={x:lo(e,"x","mean")},a={axis:t,keepDims:n};return as.runKernel(Sn,r,a)}});function Nc(e,t="float32"){if(wt(e),"complex64"===t){const t=Nc(e,"float32"),n=Nc(e,"float32");return fo(t,n)}const n=vt(et(e),t);return as.makeTensor(n,e,t)}function Cc(e,t="float32"){if(wt(e),"complex64"===t){const t=Cc(e,"float32"),n=Nc(e,"float32");return fo(t,n)}const n=xt(et(e),t);return as.makeTensor(n,e,t)}const Ac=ho({minimum_:function(e,t){let n=lo(e,"a","minimum"),r=lo(t,"b","minimum");[n,r]=Qa(n,r),"bool"===n.dtype&&(n=bi(n,"int32"),r=bi(r,"int32")),Fi(n.shape,r.shape);const a={a:n,b:r};return as.runKernel(Nn,a)}}),Rc=ho({mirrorPad_:function(e,t,n){Qe("reflect"===n||"symmetric"===n,(()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`));const r=lo(e,"x","mirrorPad");if(0===r.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");Qe(t.length===r.rank,(()=>`Padding doesn't match input. Must be ${r.rank}. Got ${t.length}.`));const a="reflect"===n?1:0;for(let e=0;e<r.rank;e++)Qe(2===t[e].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),Qe(t[e][0]>=0&&t[e][0]<=r.shape[e]-a&&t[e][1]>=0&&t[e][1]<=r.shape[e]-a,(()=>`Padding in dimension ${e} cannot be greater than or equal to ${r.shape[e]-a} or less than 0 for input of shape ${r.shape}`));const s={paddings:t,mode:n},o={x:r};return as.runKernel(Cn,o,s)}}),$c=ho({mod_:function(e,t){let n=lo(e,"a","mod"),r=lo(t,"b","mod");[n,r]=Qa(n,r);const a={a:n,b:r};return as.runKernel("Mod",a)}}),Mc=ho({moments_:function(e,t=null,n=!1){const r=it(t,(e=lo(e,"x","moments")).shape),a=Ec(e,r,n);let s=a.shape;n||(s=$l(a.shape,r));const o=Vl(fc(bi(e,"float32"),Fu(a,s)));return{mean:a,variance:Ec(o,r,n)}}}),Fc=ho({multiRNNCell_:function(e,t,n,r){const a=lo(t,"data","multiRNNCell"),s=co(n,"c","multiRNNCell"),o=co(r,"h","multiRNNCell");let i=a;const u=[];for(let t=0;t<e.length;t++){const n=e[t](i,s[t],o[t]);u.push(n[0]),u.push(n[1]),i=n[1]}const l=[],c=[];for(let e=0;e<u.length;e+=2)l.push(u[e]),c.push(u[e+1]);return[l,c]}}),Oc=ho({multinomial_:function(e,t,n,r=!1){const a=lo(e,"logits","multinomial"),s=a.size,o=a.rank;if(s<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${s}.`);if(o>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${o}`);n=n||Math.random();const i={logits:1===o?Fu(a,[1,-1]):a},u={numSamples:t,seed:n,normalized:r},l=as.runKernel("Multinomial",i,u);return 1===o?Fu(l,[l.size]):l}}),Dc=ho({notEqual_:function(e,t){let n=lo(e,"a","notEqual","string_or_numeric"),r=lo(t,"b","notEqual","string_or_numeric");[n,r]=Qa(n,r),Fi(n.shape,r.shape);const a={a:n,b:r};return as.runKernel(Rn,a)}}),Lc=ho({onesLike_:function(e){const t={x:lo(e,"x","onesLike")};return as.runKernel(On,t)}}),Pc=ho({outerProduct_:function(e,t){const n=lo(e,"v1","outerProduct"),r=lo(t,"v2","outerProduct");Qe(1===n.rank&&1===r.rank,(()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${r.rank}.`));const a=Fu(n,[-1,1]),s=Fu(r,[1,-1]);return _i(a,s)}}),Bc=ho({pad_:function(e,t,n=0){const r=lo(e,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const a={paddings:t,constantValue:n},s={x:r};return as.runKernel(Pn,s,a)}}),Uc=ho({pad1d_:function(e,t,n=0){return Qe(2===t.length,(()=>"Invalid number of paddings. Must be length of 2.")),Bc(e,[t],n)}}),zc=ho({pad2d_:function(e,t,n=0){return Qe(2===t.length&&2===t[0].length&&2===t[1].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),Bc(e,t,n)}}),Vc=ho({pad3d_:function(e,t,n=0){return Qe(3===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),Bc(e,t,n)}}),Wc=ho({pad4d_:function(e,t,n=0){return Qe(4===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length&&2===t[3].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),Bc(e,t,n)}}),Hc=ho({spaceToBatchND_:function(e,t,n){const r=lo(e,"x","spaceToBatchND");Qe(r.rank>=1+t.length,(()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`)),Qe(n.length===t.length,(()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`)),Qe(r.shape.reduce(((e,r,a)=>a>0&&a<=t.length?e&&(r+n[a-1][0]+n[a-1][1])%t[a-1]==0:e),!0),(()=>`input spatial dimensions ${r.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`));const a={x:r},s={blockShape:t,paddings:n};return as.runKernel(rr,a,s)}}),Gc=ho({pool_:function(e,t,n,r,a,s,o){null==a&&(a=[1,1]),null==s&&(s=1),0===r&&(r="valid");const i=lo(e,"x","maxPool");let u=i,l=!1;3===i.rank&&(l=!0,u=Fu(i,[1,i.shape[0],i.shape[1],i.shape[2]])),Qe(Au(s,a),(()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${a}'`));const c=vu(u.shape,t,s,a,r),p=[c.dilationHeight,c.dilationWidth];let h;h="same"===r?function(e,t){const n=e.map(((e,n)=>e+(e-1)*(t[n]-1))).map((e=>e-1)),r=n.map((e=>Math.floor(e/2))),a=n.map(((e,t)=>e-r[t]));return n.map(((e,t)=>[r[t],a[t]]))}([c.filterHeight,c.filterWidth],p):[[0,0],[0,0]];const d=1===p[0]&&1===p[1],[f,m]=function(e,t,n){const r=n.map((e=>e[0])),a=n.map((e=>e[1])),s=e.concat(r,a),o=t.map(((e,t)=>(e-s[t]%e)%e)),i=a.map(((e,t)=>e+o[t]));return[t.map(((e,t)=>[r[t],i[t]])),t.map(((e,t)=>[0,o[t]]))]}([c.inHeight,c.inWidth],p,h),g=d?r:"valid",y=d?u:Hc(u,p,f),b=("avg"===n?()=>Ou(y,t,s,g,o):()=>Tc(y,t,s,g,o))(),_=d?b:Wu(b,p,m);return l?Fu(_,[_.shape[1],_.shape[2],_.shape[3]]):_}}),jc=ho({prelu_:function(e,t){const n={x:lo(e,"x","prelu"),alpha:lo(t,"alpha","prelu")};return as.runKernel(Bn,n)}});function Kc(e,t=!1){console.log(e.toString(t))}const qc=ho({prod_:function(e,t=null,n=!1){let r=lo(e,"x","prod");"bool"===r.dtype&&(r=bi(r,"int32"));const a={x:r},s={axis:t,keepDims:n};return as.runKernel(Un,a,s)}}),Xc=ho({raggedGather_:function(e,t,n,r){const a=e.map(((e,t)=>lo(e,`tensors${t}`,"raggedGather","int32"))),s={paramsNestedSplits:a,paramsDenseValues:lo(t,"paramsDenseValues","raggedGather"),indices:lo(n,"indices","raggedGather","int32")},o={outputRaggedRank:r},i=as.runKernel("RaggedGather",s,o);return{outputNestedSplits:i.slice(0,i.length-1),outputDenseValues:i[i.length-1]}}}),Yc=ho({raggedRange_:function(e,t,n){const r=lo(e,"starts","raggedRange"),a={starts:r,limits:lo(t,"limits","raggedRange",r.dtype),deltas:lo(n,"deltas","raggedRange",r.dtype)},s=as.runKernel("RaggedRange",a);return{rtNestedSplits:s[0],rtDenseValues:s[1]}}}),Qc=ho({raggedTensorToTensor_:function(e,t,n,r,a){const s=lo(e,"shape","raggedTensorToTensor","int32"),o=lo(t,"values","raggedTensorToTensor"),i=lo(n,"defaultValue","raggedTensorToTensor",o.dtype),u=r.map(((e,t)=>lo(e,`tensors${t}`,"raggedTensorToTensor","int32"))),l={shape:s,values:o,defaultValue:i,rowPartitionTensors:u},c={rowPartitionTypes:a};return as.runKernel("RaggedTensorToTensor",l,c)}}),Jc=ho({rand_:function(e,t,n){wt(e);const r=et(e);let a=null;if(null==n||"float32"===n)a=new Float32Array(r);else if("int32"===n)a=new Int32Array(r);else{if("bool"!==n)throw new Error(`Unknown data type ${n}`);a=new Uint8Array(r)}for(let e=0;e<r;e++)a[e]=t();return as.makeTensor(a,e,n)}});var Zc="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==n.g?n.g:"undefined"!=typeof self?self:{};function ep(e){var t={exports:{}};return e(t,t.exports),t.exports}var tp=ep((function(e){!function(e,t,n){function r(e){var t=this,n=function(){var e=4022871197;return function(t){t=String(t);for(var n=0;n<t.length;n++){var r=.02519603282416938*(e+=t.charCodeAt(n));r-=e=r>>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)}}();t.next=function(){var e=2091639*t.s0+2.3283064365386963e-10*t.c;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=0|e)},t.c=1,t.s0=n(" "),t.s1=n(" "),t.s2=n(" "),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function a(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function s(e,t){var n=new r(e),s=t&&t.state,o=n.next;return o.int32=function(){return 4294967296*n.next()|0},o.double=function(){return o()+11102230246251565e-32*(2097152*o()|0)},o.quick=o,s&&("object"==typeof s&&a(s,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=s:this.alea=s}(0,e)})),np=ep((function(e){!function(e,t,n){function r(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=0|n.charCodeAt(r),t.next()}function a(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function s(e,t){var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,s&&("object"==typeof s&&a(s,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=s:this.xor128=s}(0,e)})),rp=ep((function(e){!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=0|n.charCodeAt(r),r==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function a(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function s(e,t){var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,s&&("object"==typeof s&&a(s,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=s:this.xorwow=s}(0,e)})),ap=ep((function(e){!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.x,a=t.i;return e=r[a],n=(e^=e>>>7)^e<<24,n^=(e=r[a+1&7])^e>>>10,n^=(e=r[a+3&7])^e>>>3,n^=(e=r[a+4&7])^e<<7,e=r[a+7&7],n^=(e^=e<<13)^e<<9,r[a]=n,t.i=a+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,n=0;n<t.length;++n)r[7&n]=r[7&n]<<15^t.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],e.x=r,e.i=0,n=256;n>0;--n)e.next()}(t,e)}function a(e,t){return t.x=e.x.slice(),t.i=e.i,t}function s(e,t){null==e&&(e=+new Date);var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,s&&(s.x&&a(s,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=s:this.xorshift7=s}(0,e)})),sp=ep((function(e){!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.w,a=t.X,s=t.i;return t.w=r=r+1640531527|0,n=a[s+34&127],e=a[s=s+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=a[s]=n^e,t.i=s,n+(r^r>>>16)|0},function(e,t){var n,r,a,s,o,i=[],u=128;for(t===(0|t)?(r=t,t=null):(t+="\0",r=0,u=Math.max(u,t.length)),a=0,s=-32;s<u;++s)t&&(r^=t.charCodeAt((s+32)%t.length)),0===s&&(o=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,s>=0&&(o=o+1640531527|0,a=0==(n=i[127&s]^=r+o)?a+1:0);for(a>=128&&(i[127&(t&&t.length||0)]=-1),a=127,s=512;s>0;--s)r=i[a+34&127],n=i[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,i[a]=r^n;e.w=o,e.X=i,e.i=a}(t,e)}function a(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function s(e,t){null==e&&(e=+new Date);var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,s&&(s.X&&a(s,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=s:this.xor4096=s}(0,e)})),op=ep((function(e){!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,a=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^a,a=a-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^a,t.a=a-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r<n.length+20;r++)t.b^=0|n.charCodeAt(r),t.next()}function a(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function s(e,t){var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,s&&("object"==typeof s&&a(s,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=s:this.tychei=s}(0,e)})),ip=function(e){if(e.__esModule)return e;var t=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(e).forEach((function(n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})})),t}(Object.freeze({__proto__:null,default:{}})),up=ep((function(e){!function(t,n,r){var a,s=256,o="random",i=r.pow(s,6),u=r.pow(2,52),l=2*u,c=s-1;function p(e,c,p){var y=[],b=m(f((c=1==c?{entropy:!0}:c||{}).entropy?[e,g(n)]:null==e?function(){try{var e;return a&&(e=a.randomBytes)?e=e(s):(e=new Uint8Array(s),(t.crypto||t.msCrypto).getRandomValues(e)),g(e)}catch(e){var r=t.navigator,o=r&&r.plugins;return[+new Date,t,o,t.screen,g(n)]}}():e,3),y),_=new h(y),x=function(){for(var e=_.g(6),t=i,n=0;e<u;)e=(e+n)*s,t*=s,n=_.g(1);for(;e>=l;)e/=2,t/=2,n>>>=1;return(e+n)/t};return x.int32=function(){return 0|_.g(4)},x.quick=function(){return _.g(4)/4294967296},x.double=x,m(g(_.S),n),(c.pass||p||function(e,t,n,a){return a&&(a.S&&d(a,_),e.state=function(){return d(_,{})}),n?(r[o]=e,t):e})(x,b,"global"in c?c.global:this==r,c.state)}function h(e){var t,n=e.length,r=this,a=0,o=r.i=r.j=0,i=r.S=[];for(n||(e=[n++]);a<s;)i[a]=a++;for(a=0;a<s;a++)i[a]=i[o=c&o+e[a%n]+(t=i[a])],i[o]=t;(r.g=function(e){for(var t,n=0,a=r.i,o=r.j,i=r.S;e--;)t=i[a=c&a+1],n=n*s+i[c&(i[a]=i[o=c&o+t])+(i[o]=t)];return r.i=a,r.j=o,n})(s)}function d(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function f(e,t){var n,r=[],a=typeof e;if(t&&"object"==a)for(n in e)try{r.push(f(e[n],t-1))}catch(e){}return r.length?r:"string"==a?e:e+"\0"}function m(e,t){for(var n,r=e+"",a=0;a<r.length;)t[c&a]=c&(n^=19*t[c&a])+r.charCodeAt(a++);return g(t)}function g(e){return String.fromCharCode.apply(0,e)}if(m(r.random(),n),e.exports){e.exports=p;try{a=ip}catch(e){}}else r["seed"+o]=p}("undefined"!=typeof self?self:Zc,[],Math)}));up.alea=tp,up.xor128=np,up.xorwow=rp,up.xorshift7=ap,up.xor4096=sp,up.tychei=op;var lp=up;class cp{constructor(e,t,n,r,a){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);const s=a||Math.random();this.random=lp.alea(s.toString())}nextValue(){if(!isNaN(this.nextVal)){const e=this.nextVal;return this.nextVal=NaN,e}let e,t,n=!1;for(;!n;){let r,a,s;do{r=2*this.random()-1,a=2*this.random()-1,s=r*r+a*a}while(s>=1||0===s);const o=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*r*o,t=this.mean+this.stdDev*a*o,this.truncated&&!this.isValidTruncated(e)||(n=!0)}return this.truncated&&!this.isValidTruncated(t)||(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class pp{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const a=r||Math.random();this.randu=lp.alea(a.toString()),this.randn=new cp(0,1,n,!1,this.randu()),this.d=e<1?e+2/3:e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,r,a,s;for(;;){do{r=this.randn.nextValue(),s=1+this.c*r}while(s<=0);if(s*=s*s,e=r*r,t=1-.331*e*e,n=.5*e+this.d*(1-s+Math.log(s)),a=this.randu(),a<t||Math.log(a)<n)break}return s=1/this.beta*this.d*s,this.alpha<1&&(s*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(s)}convertValue(e){return"float32"===this.dtype?e:Math.round(e)}}class hp{constructor(e=0,t=1,n,r){if(this.canReturnFloat=()=>null==this.dtype||"float32"===this.dtype,this.min=e,this.range=t-e,this.dtype=n,null==r&&(r=Math.random()),"number"==typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=lp.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const dp=ho({randomGamma_:function(e,t,n=1,r="float32",a){if(wt(e),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error(`Unsupported data type ${r}`);const s=new pp(t,n,r,a),o=Qu(e,r);for(let e=0;e<o.values.length;e++)o.values[e]=s.nextValue();return o.toTensor()}}),fp=ho({randomNormal_:function(e,t=0,n=1,r,a){if(wt(e),null!=r&&"bool"===r)throw new Error(`Unsupported data type ${r}`);const s=new cp(t,n,r,!1,a),o=Qu(e,r);for(let e=0;e<o.values.length;e++)o.values[e]=s.nextValue();return o.toTensor()}}),mp=ho({randomStandardNormal_:function(e,t,n){if(null!=t&&"bool"===t)throw new Error(`Unsupported data type ${t}`);return fp(e,0,1,t,n)}}),gp=ho({randomUniform_:function(e,t=0,n=1,r="float32",a){wt(e);const s=Qu(e,r),o=new hp(t,n,null,a);for(let e=0;e<s.values.length;e++)s.values[e]=o.nextValue();return s.toTensor()}});function yp(e,t,n=1,r="float32"){if(0===n)throw new Error("Cannot have a step of zero");const a={start:e,stop:t,step:n,dtype:r};return as.runKernel(zn,{},a)}const bp=ho({reciprocal_:function(e){const t={x:lo(e,"x","reciprocal")};return as.runKernel(Vn,t)}}),_p=ho({relu_:function(e){const t={x:lo(e,"x","relu")};return as.runKernel(Wn,t)}}),xp=ho({relu6_:function(e){const t={x:lo(e,"x","relu6")};return as.runKernel(Kn,t)}}),vp=ho({reverse_:function(e,t){const n={x:lo(e,"x","reverse")},r={dims:t};return as.runKernel(qn,n,r)}}),wp=ho({reverse1d_:function(e){const t=lo(e,"x","reverse");return Qe(1===t.rank,(()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`)),vp(t,0)}}),Tp=ho({reverse2d_:function(e,t){const n=lo(e,"x","reverse");return Qe(2===n.rank,(()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`)),vp(n,t)}}),kp=ho({reverse3d_:function(e,t){const n=lo(e,"x","reverse");return Qe(3===n.rank,(()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`)),vp(n,t)}}),Ip=ho({reverse4d_:function(e,t){const n=lo(e,"x","reverse");return Qe(4===n.rank,(()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`)),vp(n,t)}}),Sp=ho({round_:function(e){const t={x:lo(e,"x","round")};return as.runKernel(Xn,t)}}),Ep=ho({rsqrt_:function(e){const t={x:lo(e,"x","rsqrt","float32")};return as.runKernel(Yn,t)}}),Np=ho({selu_:function(e){const t={x:lo(e,"x","selu")};return as.runKernel("Selu",t)}}),Cp=ho({separableConv2d_:function(e,t,n,r,a,s=[1,1],o="NHWC"){const i=lo(e,"x","separableConv2d"),u=lo(t,"depthwiseFilter","separableConv2d"),l=lo(n,"pointwiseFilter","separableConv2d");let c=i,p=!1;if(3===i.rank&&(p=!0,c=Fu(i,[1,i.shape[0],i.shape[1],i.shape[2]])),"NCHW"===o)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");Qe(4===c.rank,(()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`)),Qe(4===u.rank,(()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${u.rank}.`)),Qe(4===l.rank,(()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${u.rank}.`)),Qe(1===l.shape[0],(()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${l.shape[0]}.`)),Qe(1===l.shape[1],(()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${l.shape[1]}.`));const h=u.shape[2],d=u.shape[3];Qe(l.shape[2]===h*d,(()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${h*d}, but got ${l.shape[2]}.`));const f=bl(c,u,r,a,o,s),m=sl(f,l,1,"valid",o);return p?Fu(m,[m.shape[1],m.shape[2],m.shape[3]]):m}}),Ap=ho({sign_:function(e){const t={x:lo(e,"x","sign")};return as.runKernel("Sign",t)}}),Rp=ho({sin_:function(e){const t={x:lo(e,"x","sin","float32")};return as.runKernel("Sin",t)}}),$p=ho({sinh_:function(e){const t={x:lo(e,"x","sinh")};return as.runKernel("Sinh",t)}}),Mp=ho({slice1d_:function(e,t,n){const r=lo(e,"x","slice1d");return Qe(1===r.rank,(()=>`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`)),Uu(r,[t],[n])}}),Fp=ho({slice2d_:function(e,t,n){const r=lo(e,"x","slice2d");return Qe(2===r.rank,(()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`)),Uu(r,t,n)}}),Op=ho({slice3d_:function(e,t,n){const r=lo(e,"x","slice3d");return Qe(3===r.rank,(()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`)),Uu(r,t,n)}}),Dp=ho({slice4d_:function(e,t,n){const r=lo(e,"x","slice4d");return Qe(4===r.rank,(()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`)),Uu(r,t,n)}}),Lp=ho({softmax_:function(e,t=-1){const n=lo(e,"logits","softmax","float32");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);const r={logits:n},a={dim:t};return as.runKernel(sr,r,a)}}),Pp=ho({fft_:function(e){Qe("complex64"===e.dtype,(()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`));const t={input:e};return as.runKernel("FFT",t)}}),Bp=ho({ifft_:function(e){Qe("complex64"===e.dtype,(()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`));const t={input:e};return as.runKernel("IFFT",t)}}),Up=ho({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let r;if(t<=2){const a=Fu(e,[n,t]);r=Bp(a)}else{const a=[n,2*(t-1)],s=Fu(Ai(e),[n,t]),o=Fu(Ni(e),[n,t]),i=vp(Uu(s,[0,1],[n,t-2]),1),u=iu(vp(Uu(o,[0,1],[n,t-2]),1),Ul(-1)),l=Pu([s,i],1),c=Pu([o,u],1),p=Fu(fo(l,c),[a[0],a[1]]);r=Bp(p)}if(r=Ai(r),3===e.rank&&0!==e.shape[0]){const t=r,n=e.shape[0];r=Fu(r,[n,r.shape[0]/n,r.shape[1]]),t.dispose()}return r}}),zp=ho({split_:function(e,t,n=0){const r={x:lo(e,"x","split")},a={numOrSizeSplits:t,axis:n};return as.runKernel(ar,r,a)}}),Vp=ho({rfft_:function(e,t){Qe("float32"===e.dtype,(()=>`The dtype for rfft() must be real value but got ${e.dtype}`));let n=e.shape[e.shape.length-1];const r=e.size/n;let a;if(null!=t&&t<n){const r=e.shape.map((e=>0)),s=e.shape.map((e=>e));s[e.shape.length-1]=t,a=Uu(e,r,s),n=t}else if(null!=t&&t>n){const r=e.shape.map((e=>e));r[e.shape.length-1]=t-n,a=Pu([e,Nc(r)],e.shape.length-1),n=t}else a=e;const s=Tl(a),o=Fu(fo(a,s),[r,n]),i=Pp(o),u=Math.floor(n/2)+1,l=Ai(i),c=Ni(i),p=zp(l,[u,n-u],l.shape.length-1),h=zp(c,[u,n-u],c.shape.length-1),d=a.shape.slice();return d[a.shape.length-1]=u,Fu(fo(p[0],h[0]),d)}}),Wp=ho({squaredDifference_:function(e,t){let n=lo(e,"a","squaredDifference"),r=lo(t,"b","squaredDifference");[n,r]=Qa(n,r),Fi(n.shape,r.shape);const a={a:n,b:r};return as.runKernel(cr,a,{})}}),Hp=ho({squeeze_:function(e,t){const n=lo(e,"x","squeeze","string_or_numeric");return Fu(n,ut(n.shape,t).newShape)}}),Gp=ho({stack_:function(e,t=0){const n=co(e,"tensors","stack","string_or_numeric");Qe(n.length>=1,(()=>"Pass at least one tensor to tf.stack")),n.length>0&&Qe(t<=n[0].rank,(()=>"Axis must be <= rank of the tensor"));const r=n,a={axis:t};return as.runKernel(Ln,r,a)}}),jp=ho({step_:function(e,t=0){const n={x:lo(e,"x","step")},r={alpha:t};return as.runKernel(Tr,n,r)}}),Kp=ho({stridedSlice_:function(e,t,n,r,a=0,s=0,o=0,i=0,u=0){const l={x:lo(e,"x","stridedSlice","string_or_numeric")},c={begin:t,end:n,strides:r,beginMask:a,endMask:s,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:u};return as.runKernel(pr,l,c)}}),qp=ho({tan_:function(e){const t={x:lo(e,"x","tan","float32")};return as.runKernel("Tan",t)}});function Xp(e,t){Ze(e);const n=oo(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return mo(e,null,n,t)}function Yp(e,t,n){if(Ze(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const r=oo(e,n);if(2!==r.length&&1!==r.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return mo(e,t,r,n)}const Qp=ho({topk_:function(e,t=1,n=!0){const r=lo(e,"x","topk");if(0===r.rank)throw new Error("topk() expects the input to be of rank 1 or higher");const a=r.shape[r.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>a)throw new Error(`'k' passed to topk() must be <= the last dimension (${a}) but got ${t}`);const s={x:r},o={k:t,sorted:n},[i,u]=as.runKernel(br,s,o);return{values:i,indices:u}}}),Jp=ho({truncatedNormal_:function(e,t=0,n=1,r,a){if(wt(e),null!=r&&"bool"===r)throw new Error("Unsupported data type $ { dtype }");const s=new cp(t,n,r,!0,a),o=Qu(e,r);for(let e=0;e<o.values.length;e++)o.values[e]=s.nextValue();return o.toTensor()}}),Zp=ho({unique_:function(e,t=0){const n=lo(e,"x","unique","string_or_numeric");Qe(n.rank>0,(()=>"The input tensor must be at least 1D"));const r={x:n},a={axis:t},[s,o]=as.runKernel("Unique",r,a);return{values:s,indices:o}}}),eh=ho({unsortedSegmentSum_:function(e,t,n){const r=lo(e,"x","unsortedSegmentSum"),a=lo(t,"segmentIds","unsortedSegmentSum","int32");Qe(nt(n),(()=>"numSegments must be of dtype int"));const s={x:r,segmentIds:a},o={numSegments:n};return as.runKernel("UnsortedSegmentSum",s,o)}}),th=ho({unstack_:function(e,t=0){const n=lo(e,"x","unstack","string_or_numeric");Qe(t>=-n.shape.length&&t<n.shape.length,(()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`));const r={value:n},a={axis:t};return as.runKernel(vr,r,a)}});function nh(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const r=Qu(e,"int32"),a=Qu([n.length,e.length],"int32");for(let t=0;t<n.length;t++){const s=r.indexToLoc(n[t]),o=t*e.length;a.values.set(s,o)}return a.toTensor()}const rh=async function(e){const t=lo(e,"condition","whereAsync","bool"),n=await t.data(),r=nh(t.shape,n);return e!==t&&t.dispose(),r},ah=ho({movingAverage_:function(e,t,n,r,a=!0){const s=lo(e,"v","movingAverage"),o=lo(t,"x","movingAverage"),i=lo(n,"decay","movingAverage");var u,l;l=o,Qe((u=s).dtype===l.dtype,(()=>`The dtypes of the first(${u.dtype}) and second(${l.dtype}) input must match`)),Qe(tt(s.shape,o.shape),(()=>"Shape mismatch in v and x"));const c=Ul(1),p=fc(c,i);let h=iu(fc(o,s),p);if(a){Qe(null!=r,(()=>"When using zeroDebias: true, step is required."));const e=lo(r,"step","movingAverage");h=ou(h,fc(c,Bl(i,e)))}return au(s,h)}}),sh=ho({scatterND_:function(e,t,n){wt(n);const r=lo(e,"indices","scatterND","int32"),a=lo(t,"updates","scatterND");Ui(a,r,n);const s={indices:r,updates:a},o={shape:n};return as.runKernel(Qn,s,o)}}),oh=ho({sparseToDense_:function(e,t,n,r=0){wt(n);const a=lo(e,"sparseIndices","sparseToDense","int32"),s=lo(t,"sparseValues","sparseToDense","string_or_numeric"),o=lo(r,"defaultValue","sparseToDense",s.dtype);!function(e,t,n,r){if("int32"!==e.dtype)throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);const a=e.rank>0?e.shape[0]:1,s=e.rank>1?e.shape[1]:1;if(n.length!==s)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${s}.`);const o=t.size;if(0!==t.rank&&(1!==t.rank||o!==a))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${a}]`);if(t.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(a,s,n,o);const i={sparseIndices:a,sparseValues:s,defaultValue:o},u={outputShape:n};return as.runKernel("SparseToDense",i,u)}}),ih=ho({gatherND_:function(e,t){const n=lo(t,"indices","gatherND","int32"),r={params:lo(e,"x","gatherND","string_or_numeric"),indices:n};return as.runKernel(hn,r)}}),uh=ho({dropout_:function(e,t,n,r){const a=lo(e,"x","dropout");if(Qe("float32"===a.dtype,(()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${a.dtype} tensor instead.`)),Qe(t>=0&&t<1,(()=>`rate must be a float in the range [0, 1), but got ${t}.`)),0===t)return e instanceof Va?a.clone():a;const s=function(e,t){if(null==t)return e.shape.slice();if(tt(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let r=0;r<e.shape.length;r++)null==t[r]&&null!=e.shape[r]?n.push(e.shape[r]):n.push(t[r]);return n}return t}(a,n),o=1-t,i=ou(Jl(au(gp(s,0,1,"float32",r),o)),o);return iu(a,i)}});function lh(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function ch(e,t,n){const r=1-e%2,a=new Float32Array(e);for(let s=0;s<e;++s){const o=2*Math.PI*s/(e+r-1);a[s]=t-n*Math.cos(o)}return Xp(a,"float32")}const ph=ho({conv2DBackpropFilter_:function(e,t,n,r,a,s="NHWC",o){let i=e;3===e.rank&&(i=Fu(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u=t;3===u.rank&&(u=Fu(t,[1,t.shape[0],t.shape[1],t.shape[2]])),Qe(4===i.rank,(()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`)),Qe(4===u.rank,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${u.shape}.`)),Qe(4===n.length,(()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`));const l="NHWC"===s?i.shape[3]:i.shape[1],c="NHWC"===s?u.shape[3]:u.shape[1];Qe(l===n[2],(()=>`Error in conv2dDerFilter: depth of input ${l}) must match input depth in filter (${n[2]}.`)),Qe(c===n[3],(()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${n[3]}).`)),Mu("conv2dDerFilter",a,o);const p={x:i,dy:u},h={strides:r,pad:a,dataFormat:s,dimRoundingMode:o,filterShape:n};return as.runKernel("Conv2DBackpropFilter",p,h)}});function hh(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return iu(e,jp(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function dh(e,t){let n=t;const r=Mi(e.shape,t.shape);return r.length>0&&(n=Wl(n,r)),Fu(n,e.shape)}function fh(e,t,n,r){if("linear"===t)return e;if("relu"===t)return _p(e);if("elu"===t)return El(e);if("relu6"===t)return xp(e);if("prelu"===t)return jc(e,n);if("leakyrelu"===t)return sc(e,r);if("sigmoid"===t)return Bu(e);throw new Error(`Unknown fused activation ${t}.`)}const mh=(e,t)=>!(e>0)||"linear"===t,gh=ho({fusedConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:o,bias:i,activation:u="linear",preluActivationWeights:l,leakyreluAlpha:c}){if(u=u||"linear",!1===mh(as.state.gradientDepth,u)){Qe("NHWC"===a,(()=>`Error in fused conv2d: got dataFormat of ${a} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`));let p=sl(e,t,n,r,a,s,o);return null!=i&&(p=au(p,i)),fh(p,u,l,c)}const p=lo(e,"x","conv2d","float32"),h=lo(t,"filter","conv2d","float32");let d=p,f=!1;3===p.rank&&(f=!0,d=Fu(p,[1,p.shape[0],p.shape[1],p.shape[2]])),Qe(4===d.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${d.rank}.`)),Qe(4===h.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${h.rank}.`)),Mu("fused conv2d",r,o);const m="NHWC"===a?d.shape[3]:d.shape[1];Qe(h.shape[2]===m,(()=>`Error in conv2d: depth of input (${m}) must match input depth for filter ${h.shape[2]}.`)),Qe(Au(n,s),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`));const g=wu(d.shape,h.shape,n,s,r,o);let y,b;if(null!=i&&(y=lo(i,"bias","fused conv2d"),[y]=Qa(y,p),"NHWC"===a?Fi(g.outShape,y.shape):(Qe(y.shape.length<=1,(()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${y.shape.length}.`)),Qe(0===y.shape.length||y.shape[0]===g.outChannels||1===y.shape[0],(()=>`Error in fused conv2d: bias shape (${y.shape}) is not compatible with the number of output channels (${g.outChannels})`)))),null!=l){const e=l.shape;if(Qe(e.length<=1||3===e.length,(()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${e.length}.`)),1===e.length)Qe(1===e[0]||e[0]===g.outChannels,(()=>`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the number of output channels (${g.outChannels}).`));else if(3===e.length)try{Fi(e,g.outShape)}catch(t){const n=`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(n)}b=lo(l,"prelu weights","fused conv2d")}const _=(e,t)=>{Qe("NHWC"===a,(()=>`Error in gradient of fused conv2D: got dataFormat of ${a} but only NHWC is currently supported.`));const[o,i,l,c]=t,p=hh(e,l,u);Qe(Cu(s),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`));const h=[il(i.shape,p,o,n,r),ph(i,p,o.shape,n,r)];if(null!=c){const e=dh(c,p);h.push(e)}return h},x={x:d,filter:h,bias:y,preluActivationWeights:b},v={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o,activation:u,leakyreluAlpha:c};if(null==i){const e=pc(((e,t,n)=>{let r=as.runKernel(Er,x,v);return n([t,e,r]),f&&(r=Fu(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:_}}));return e(d,h)}{const e=pc(((e,t,n,r)=>{let a=as.runKernel(Er,x,v);return r([t,e,a,n]),f&&(a=Fu(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:_}}));return e(d,h,y)}}}),yh=ho({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,r,a,s=[1,1],o){let i=e;3===e.rank&&(i=Fu(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u=t;3===u.rank&&(u=Fu(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={x:i,dy:u},c={strides:r,pad:a,dimRoundingMode:o,dilations:s,filterShape:n};return as.runKernel("DepthwiseConv2dNativeBackpropFilter",l,c)}}),bh=ho({depthwiseConv2dNativeBackpropInput_:function(e,t,n,r,a,s=[1,1],o){let i=t,u=!1;3===t.rank&&(u=!0,i=Fu(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={dy:i,filter:n},c={strides:r,pad:a,dimRoundingMode:o,dilations:s,inputShape:e},p=as.runKernel("DepthwiseConv2dNativeBackpropInput",l,c);return u?Fu(p,[p.shape[1],p.shape[2],p.shape[3]]):p}}),_h=ho({fusedDepthwiseConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:o,bias:i,activation:u="linear",preluActivationWeights:l,leakyreluAlpha:c}){if(!1===mh(as.state.gradientDepth,u)){let p=bl(e,t,n,r,a,s,o);return null!=i&&(p=au(p,i)),fh(p,u,l,c)}const p=lo(e,"x","depthwiseConv2d","float32"),h=lo(t,"filter","depthwiseConv2d","float32");let d=p,f=!1;3===p.rank&&(f=!0,d=Fu(p,[1,p.shape[0],p.shape[1],p.shape[2]])),Qe(4===d.rank,(()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${d.rank}.`)),Qe(4===h.rank,(()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`)),Qe(d.shape[3]===h.shape[2],(()=>`Error in fused depthwiseConv2d: number of input channels (${d.shape[3]}) must match the inChannels dimension in filter ${h.shape[2]}.`)),null==s&&(s=[1,1]),Qe(Au(n,s),(()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`)),Mu("fused depthwiseConv2d",r,o);const m=wu(d.shape,h.shape,n,s,r,o,!0);let g,y;null!=i&&(g=lo(i,"bias","fused conv2d"),[g]=Qa(g,p),Fi(m.outShape,g.shape)),null!=l&&(y=lo(l,"prelu weights","fused depthwiseConv2d"));const b=(e,t)=>{Qe(Cu(s),(()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`));const[a,i,l,c]=t,p=hh(e,l,u),h=bh(i.shape,p,a,n,r,s,o),d=yh(i,p,a.shape,n,r,s,o);return null!=c?[h,d,dh(g,p)]:[h,d]},_={x:d,filter:h,bias:g,preluActivationWeights:y},x={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o,activation:u,leakyreluAlpha:c};if(null==i){const e=pc(((e,t,n)=>{let r=as.runKernel(Nr,_,x);return n([t,e,r]),f&&(r=Fu(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:b}}));return e(d,h)}{const e=pc(((e,t,n,r)=>{let a=as.runKernel(Nr,_,x);return r([t,e,a,n]),f&&(a=Fu(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:b}}));return e(d,h,g)}}}),xh=ho({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:a,activation:s="linear",preluActivationWeights:o,leakyreluAlpha:i=.2}){if(!1===mh(as.state.gradientDepth,s)){let u=_i(e,t,n,r);return null!=a&&(u=au(u,a)),fh(u,s,o,i)}let u=lo(e,"a","fused matMul"),l=lo(t,"b","fused matMul");[u,l]=Qa(u,l);const c=n?u.shape[u.rank-2]:u.shape[u.rank-1],p=r?l.shape[l.rank-1]:l.shape[l.rank-2],h=n?u.shape[u.rank-1]:u.shape[u.rank-2],d=r?l.shape[l.rank-2]:l.shape[l.rank-1],f=u.shape.slice(0,-2),m=l.shape.slice(0,-2),g=et(f),y=et(m);Qe(c===p,(()=>`Error in fused matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${u.shape} and ${l.shape} and transposeA=${n} and transposeB=${r} must match.`));const b=Fi(u.shape.slice(0,-2),l.shape.slice(0,-2)).concat([h,d]),_=Fu(u,n?[g,c,h]:[g,h,c]),x=Fu(l,r?[y,d,p]:[y,p,d]);let v,w;null!=a&&(v=lo(a,"bias","fused matMul"),[v]=Qa(v,u),Fi(b,v.shape)),null!=o&&(w=lo(o,"prelu weights","fused matMul"));const T=(e,t)=>{const[o,i,u,l]=t,c=hh(Fu(e,u.shape),u,s);let p,h;return n||r?!n&&r?(p=_i(c,i,!1,!1),h=_i(c,o,!0,!1)):n&&!r?(p=_i(i,c,!1,!0),h=_i(o,c,!1,!1)):(p=_i(i,c,!0,!0),h=_i(c,o,!0,!0)):(p=_i(c,i,!1,!0),h=_i(o,c,!0,!1)),null!=a?[p,h,dh(l,c)]:[p,h]},k={a:_,b:x,bias:v,preluActivationWeights:w},I={transposeA:n,transposeB:r,activation:s,leakyreluAlpha:i};if(null==a){const e=pc(((e,t,n)=>{const r=as.runKernel(Sr,k,I);return n([e,t,r]),{value:Fu(r,b),gradFunc:T}}));return e(_,x)}{const e=pc(((e,t,n,r)=>{const a=as.runKernel(Sr,k,I);return r([e,t,a,n]),{value:Fu(a,b),gradFunc:T}}));return e(_,x,v)}}});var vh=Object.freeze({__proto__:null,conv2d:gh,depthwiseConv2d:_h,matMul:xh});const wh=ho({hammingWindow_:function(e){return ch(e,.54,.46)}}),Th=ho({hannWindow_:function(e){return ch(e,.5,.5)}}),kh=ho({frame_:function(e,t,n,r=!1,a=0){let s=0;const o=[];for(;s+t<=e.size;)o.push(Uu(e,s,t)),s+=n;if(r)for(;s<e.size;){const r=s+t-e.size,i=Pu([Uu(e,s,t-r),Zu([r],a)]);o.push(i),s+=n}return 0===o.length?Yp([],[0,t]):Fu(Pu(o),[o.length,t])}}),Ih=ho({stft_:function(e,t,n,r,a=Th){null==r&&(r=lh(t));const s=kh(e,t,n),o=iu(s,a(t));return Vp(o,r)}}),Sh=ho({cropAndResize_:function(e,t,n,r,a="bilinear",s=0){const o=lo(e,"image","cropAndResize"),i=lo(t,"boxes","cropAndResize","float32"),u=lo(n,"boxInd","cropAndResize","int32"),l=i.shape[0];Qe(4===o.rank,(()=>`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`)),Qe(2===i.rank&&4===i.shape[1],(()=>`Error in cropAndResize: boxes must be have size [${l},4] but had shape ${i.shape}.`)),Qe(1===u.rank&&u.shape[0]===l,(()=>`Error in cropAndResize: boxInd must be have size [${l}] but had shape ${i.shape}.`)),Qe(2===r.length,(()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`)),Qe(r[0]>=1&&r[1]>=1,(()=>`cropSize must be atleast [1,1], but was ${r}`)),Qe("bilinear"===a||"nearest"===a,(()=>`method must be bilinear or nearest, but was ${a}`));const c={image:o,boxes:i,boxInd:u},p={method:a,extrapolationValue:s,cropSize:r};return as.runKernel(Qt,c,p)}}),Eh=ho({flipLeftRight_:function(e){const t=lo(e,"image","flipLeftRight","float32");Qe(4===t.rank,(()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`));const n={image:t};return as.runKernel(on,n,{})}}),Nh=ho({grayscaleToRGB_:function(e){const t=lo(e,"image","grayscaleToRGB"),n=t.rank-1,r=t.shape[n];Qe(t.rank>=2,(()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`)),Qe(1===r,(()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${r}.`));const a=new Array(t.rank);return a.fill(1,0,n),a[n]=3,Yl(t,a)}}),Ch=ho({rotateWithOffset_:function(e,t,n=0,r=.5){const a=lo(e,"image","rotateWithOffset","float32");Qe(4===a.rank,(()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${a.rank}.`));const s={image:a},o={radians:t,fillValue:n,center:r};return as.runKernel(Ir,s,o)}});function Ah(e,t,n,r,a,s){null==r&&(r=.5),null==a&&(a=Number.NEGATIVE_INFINITY),null==s&&(s=0);const o=e.shape[0];return n=Math.min(n,o),Qe(0<=r&&r<=1,(()=>`iouThreshold must be in [0, 1], but was '${r}'`)),Qe(2===e.rank,(()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`)),Qe(4===e.shape[1],(()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`)),Qe(1===t.rank,(()=>"scores must be a 1D tensor")),Qe(t.shape[0]===o,(()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`)),Qe(0<=s&&s<=1,(()=>`softNmsSigma must be in [0, 1], but was '${s}'`)),{maxOutputSize:n,iouThreshold:r,scoreThreshold:a,softNmsSigma:s}}const Rh=ho({nonMaxSuppression_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY){const s=lo(e,"boxes","nonMaxSuppression","float32"),o=lo(t,"scores","nonMaxSuppression","float32"),i=Ah(s,o,n,r,a),u={maxOutputSize:n=i.maxOutputSize,iouThreshold:r=i.iouThreshold,scoreThreshold:a=i.scoreThreshold};return as.runKernel($n,{boxes:s,scores:o},u)}});function $h(e,t,n){const r=function(e,t,n){return function(e,t,n){let r=0,a=e.length,s=0,o=!1;for(;r<a;){s=r+(a-r>>>1);const i=n(t,e[s]);i>0?r=s+1:(a=s,o=!i)}return o?r:-r-1}(e,t,n||Mh)}(e,t,n),a=r<0?-(r+1):r;e.splice(a,0,t)}function Mh(e,t){return e>t?1:e<t?-1:0}function Fh(e,t,n,r,a,s,o=!1,i=!1,u=!1){const l=[];for(let e=0;e<t.length;e++)t[e]>a&&l.push({score:t[e],boxIndex:e,suppressBeginIndex:0});l.sort(Lh);const c=s>0?-.5/s:0,p=[],h=[];for(;p.length<n&&l.length>0;){const t=l.pop(),{score:n,boxIndex:s,suppressBeginIndex:o}=t;if(n<a)break;let i=!1;for(let n=p.length-1;n>=o;--n){const o=Oh(e,s,p[n]);if(o>=r){i=!0;break}if(t.score=t.score*Dh(r,c,o),t.score<=a)break}t.suppressBeginIndex=p.length,i||(t.score===n?(p.push(s),h.push(t.score)):t.score>a&&$h(l,t,Lh))}const d=p.length,f=n-d;i&&f>0&&(p.push(...new Array(f).fill(0)),h.push(...new Array(f).fill(0)));const m={selectedIndices:p};return o&&(m.selectedScores=h),u&&(m.validOutputs=d),m}function Oh(e,t,n){const r=e.subarray(4*t,4*t+4),a=e.subarray(4*n,4*n+4),s=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),i=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(a[0],a[2]),c=Math.min(a[1],a[3]),p=Math.max(a[0],a[2]),h=Math.max(a[1],a[3]),d=(i-s)*(u-o),f=(p-l)*(h-c);if(d<=0||f<=0)return 0;const m=Math.max(s,l),g=Math.max(o,c),y=Math.min(i,p),b=Math.min(u,h),_=Math.max(y-m,0)*Math.max(b-g,0);return _/(d+f-_)}function Dh(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function Lh(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const Ph=ho({nonMaxSuppressionWithScore_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=0){const o=lo(e,"boxes","nonMaxSuppression"),i=lo(t,"scores","nonMaxSuppression"),u=Ah(o,i,n,r,a,s),l={boxes:o,scores:i},c={maxOutputSize:n=u.maxOutputSize,iouThreshold:r=u.iouThreshold,scoreThreshold:a=u.scoreThreshold,softNmsSigma:s=u.softNmsSigma},p=as.runKernel(Fn,l,c);return{selectedIndices:p[0],selectedScores:p[1]}}}),Bh=ho({nonMaxSuppressionPadded_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=!1){const o=lo(e,"boxes","nonMaxSuppression"),i=lo(t,"scores","nonMaxSuppression"),u=Ah(o,i,n,r,a,null),l={boxes:o,scores:i},c={maxOutputSize:u.maxOutputSize,iouThreshold:u.iouThreshold,scoreThreshold:u.scoreThreshold,padToMaxOutputSize:s},p=as.runKernel(Mn,l,c);return{selectedIndices:p[0],validOutputs:p[1]}}}),Uh=ho({resizeBilinear_:function(e,t,n=!1,r=!1){const a=lo(e,"images","resizeBilinear");Qe(3===a.rank||4===a.rank,(()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${a.rank}.`)),Qe(2===t.length,(()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`)),Qe(!1===r||!1===n,(()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false."));let s=a,o=!1;3===a.rank&&(o=!0,s=Fu(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const i={images:s},u={alignCorners:n,halfPixelCenters:r,size:t},l=as.runKernel(jn,i,u);return o?Fu(l,[l.shape[1],l.shape[2],l.shape[3]]):l}}),zh=ho({resizeNearestNeighbor_:function(e,t,n=!1,r=!1){const a=lo(e,"images","resizeNearestNeighbor");Qe(3===a.rank||4===a.rank,(()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${a.rank}.`)),Qe(2===t.length,(()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`)),Qe("float32"===a.dtype||"int32"===a.dtype,(()=>"`images` must have `int32` or `float32` as dtype")),Qe(!1===r||!1===n,(()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false."));let s=a,o=!1;3===a.rank&&(o=!0,s=Fu(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const i={images:s},u={alignCorners:n,halfPixelCenters:r,size:t},l=as.runKernel(Gn,i,u);return o?Fu(l,[l.shape[1],l.shape[2],l.shape[3]]):l}}),Vh=ho({threshold_:function(e,t="binary",n=!1,r=.5){const a=lo(e,"image","threshold"),s=a.shape[0]*a.shape[1];let o,i,u,l,c=iu(Xp([r]),255);if(Qe(3===a.rank,(()=>`Error in threshold: image must be rank 3,but got rank ${a.rank}.`)),Qe(3===a.shape[2]||1===a.shape[2],(()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${a.shape[2]}.`)),Qe("int32"===a.dtype||"float32"===a.dtype,(()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${a.dtype}.`)),Qe("otsu"===t||"binary"===t,(()=>`Method must be binary or otsu, but was ${t}`)),3===a.shape[2]){[o,i,u]=zp(a,[1,1,1],-1);const e=iu(o,.2989),t=iu(i,.587),n=iu(u,.114);l=au(au(e,t),n)}else l=e;"otsu"===t&&(c=function(e,t){let n,r,a,s,o,i,u=Xp([-1]),l=Xp([0]),c=Xp([0]);for(let p=0;p<e.size-1;p++){n=Uu(e,0,p+1),r=Uu(e,p+1),o=ou(Wl(n),t),i=ou(Wl(r),t);const h=Wl(iu(n,yp(0,n.size)));a=ou(h,Wl(n));const d=Zu(r.shape,n.size),f=au(yp(0,r.size),d),m=iu(r,f);s=ou(Wl(m),Wl(r));const g=fc(a,s),y=fc(a,s),b=iu(o,i);c=iu(iu(b,g),y);const _=ec(c,l);l=wl(_,c,l),u=wl(_,Xp([p]),u)}return u}(qu(bi(Sp(l),"int32"),go([]),256),s));const p=n?ic(l,c):ec(l,c);return bi(iu(p,255),"int32")}}),Wh=ho({transform_:function(e,t,n="nearest",r="constant",a=0,s){const o=lo(e,"image","transform","float32"),i=lo(t,"transforms","transform","float32");Qe(4===o.rank,(()=>`Error in transform: image must be rank 4,but got rank ${o.rank}.`)),Qe(2===i.rank&&(i.shape[0]===o.shape[0]||1===i.shape[0])&&8===i.shape[1],(()=>"Error in transform: Input transform should be batch x 8 or 1 x 8")),Qe(null==s||2===s.length,(()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`));const u={image:o,transforms:i},l={interpolation:n,fillMode:r,fillValue:a,outputShape:s};return as.runKernel(_r,u,l)}}),Hh=ho({bandPart_:function(e,t,n){Qe(t%1==0,(()=>`bandPart(): numLower must be an integer, got ${t}.`)),Qe(n%1==0,(()=>`bandPart(): numUpper must be an integer, got ${n}.`));const r=lo(e,"a","bandPart");Qe(r.rank>=2,(()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`));const a=r.shape,[s,o]=r.shape.slice(-2);if(!(t<=s))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`);if(!(n<=o))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${o}).`);t<0&&(t=s),n<0&&(n=o);const i=Fu(yp(0,s,1,"int32"),[-1,1]),u=yp(0,o,1,"int32"),l=fc(i,u),c=yc(ic(l,Ul(+t,"int32")),tc(l,Ul(-n,"int32"))),p=Nc([s,o],r.dtype);return Fu(Gp(th(Fu(r,[-1,s,o])).map((e=>wl(c,e,p)))),a)}}),Gh=ho({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,Qe(null!=e&&e.length>0,(()=>"Gram-Schmidt process: input must not be null, undefined, or empty"));const n=e[0].shape[0];for(let t=1;t<e.length;++t)Qe(e[t].shape[0]===n,(()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[t].shape[0]} vs. ${n})`))}else t=!0,e=zp(e,e.shape[0],0).map((e=>Hp(e,[0])));Qe(e.length<=e[0].shape[0],(()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`));const n=[],r=e;for(let t=0;t<e.length;++t)n.push(as.tidy((()=>{let e=r[t];if(t>0)for(let r=0;r<t;++r){const t=iu(Wl(iu(n[r],e)),n[r]);e=fc(e,t)}return ou(e,Gl(e,"euclidean"))})));return t?Gp(n,0):n}});function jh(e,t=!1){return as.tidy((()=>{Qe(2===e.shape.length,(()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`));const n=e.shape[0],r=e.shape[1];let a=Ql(n),s=Lu(e);const o=Yp([[1]],[1,1]);let i=Lu(o);const u=n>=r?r:n;for(let e=0;e<u;++e){const t=s,u=i,l=a;[i,s,a]=as.tidy((()=>{const t=Uu(s,[e,e],[n-e,1]),u=Gl(t),l=Uu(s,[e,e],[1,1]),c=wl(ec(l,0),Yp([[-1]]),Yp([[1]])),p=fc(l,iu(c,u)),h=ou(t,p);i=1===h.shape[0]?Lu(o):Pu([o,Uu(h,[1,0],[h.shape[0]-1,h.shape[1]])],0);const d=Ci(ou(_i(c,p),u)),f=Uu(s,[e,0],[n-e,r]),m=iu(d,i),g=Ri(i);if(0===e)s=fc(f,_i(m,_i(g,f)));else{const t=fc(f,_i(m,_i(g,f)));s=Pu([Uu(s,[0,0],[e,r]),t],0)}const y=Ri(m),b=Uu(a,[0,e],[n,a.shape[1]-e]);if(0===e)a=fc(b,_i(_i(b,i),y));else{const t=fc(b,_i(_i(b,i),y));a=Pu([Uu(a,[0,0],[n,e]),t],1)}return[i,s,a]})),Ti([t,u,l])}return!t&&n>r&&(a=Uu(a,[0,0],[n,r]),s=Uu(s,[0,0],[r,r])),[a,s]}))}const Kh=ho({qr_:function(e,t=!1){if(Qe(e.rank>=2,(()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`)),2===e.rank)return jh(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),r=th(Fu(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),a=[],s=[];return r.forEach((e=>{const[n,r]=jh(e,t);a.push(n),s.push(r)})),[Fu(Gp(a,0),e.shape),Fu(Gp(s,0),e.shape)]}}});var qh;!function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(qh||(qh={}));const Xh=ho({computeWeightedLoss_:function(e,t,n=qh.SUM_BY_NONZERO_WEIGHTS){const r=lo(e,"losses","computeWeightedLoss");let a=null;null!=t&&(a=lo(t,"weights","computeWeightedLoss"));const s=null==a?r:iu(r,a);if(n===qh.NONE)return s;if(n===qh.SUM)return Wl(s);if(n===qh.MEAN){if(null==a)return Ec(s);{const e=r.size/a.size,t=ou(Wl(s),Wl(a));return e>1?ou(t,Ul(e)):t}}if(n===qh.SUM_BY_NONZERO_WEIGHTS){if(null==a)return ou(Wl(s),Ul(r.size));{const e=iu(a,Cc(r.shape)),t=bi(Wl(Dc(e,Ul(0))),"float32");return ou(Wl(s),t)}}throw Error(`Unknown reduction: ${n}`)}}),Yh=ho({absoluteDifference_:function(e,t,n,r=qh.SUM_BY_NONZERO_WEIGHTS){const a=lo(e,"labels","absoluteDifference"),s=lo(t,"predictions","absoluteDifference");let o=null;null!=n&&(o=lo(n,"weights","absoluteDifference")),Je(a.shape,s.shape,"Error in absoluteDifference: ");const i=uu(fc(a,s));return Xh(i,o,r)}}),Qh=ho({cosineDistance_:function(e,t,n,r,a=qh.SUM_BY_NONZERO_WEIGHTS){const s=lo(e,"labels","cosineDistance"),o=lo(t,"predictions","cosineDistance");let i=null;null!=r&&(i=lo(r,"weights","cosineDistance")),Je(s.shape,o.shape,"Error in cosineDistance: ");const u=Ul(1),l=fc(u,Wl(iu(s,o),n,!0));return Xh(l,i,a)}}),Jh=ho({hingeLoss_:function(e,t,n,r=qh.SUM_BY_NONZERO_WEIGHTS){let a=lo(e,"labels","hingeLoss");const s=lo(t,"predictions","hingeLoss");let o=null;null!=n&&(o=lo(n,"weights","hingeLoss")),Je(a.shape,s.shape,"Error in hingeLoss: ");const i=Ul(1);a=fc(iu(Ul(2),a),i);const u=_p(fc(i,iu(a,s)));return Xh(u,o,r)}}),Zh=ho({huberLoss_:function(e,t,n,r=1,a=qh.SUM_BY_NONZERO_WEIGHTS){const s=lo(e,"labels","huberLoss"),o=lo(t,"predictions","huberLoss");let i=null;null!=n&&(i=lo(n,"weights","huberLoss")),Je(s.shape,o.shape,"Error in huberLoss: ");const u=Ul(r),l=uu(fc(o,s)),c=Ac(l,u),p=fc(l,c),h=au(iu(Ul(.5),Vl(c)),iu(u,p));return Xh(h,i,a)}}),ed=ho({logLoss_:function(e,t,n,r=1e-7,a=qh.SUM_BY_NONZERO_WEIGHTS){const s=lo(e,"labels","logLoss"),o=lo(t,"predictions","logLoss");let i=null;null!=n&&(i=lo(n,"weights","logLoss")),Je(s.shape,o.shape,"Error in logLoss: ");const u=Ul(1),l=Ul(r),c=Ci(iu(s,lc(au(o,l)))),p=iu(fc(u,s),lc(au(fc(u,o),l))),h=fc(c,p);return Xh(h,i,a)}}),td=ho({meanSquaredError_:function(e,t,n,r=qh.SUM_BY_NONZERO_WEIGHTS){const a=lo(e,"labels","meanSquaredError"),s=lo(t,"predictions","meanSquaredError");let o=null;null!=n&&(o=lo(n,"weights","meanSquaredError")),Je(a.shape,s.shape,"Error in meanSquaredError: ");const i=Wp(a,s);return Xh(i,o,r)}}),nd=ho({sigmoidCrossEntropy_:function(e,t,n,r=0,a=qh.SUM_BY_NONZERO_WEIGHTS){let s=lo(e,"multiClassLabels","sigmoidCrossEntropy");const o=lo(t,"logits","sigmoidCrossEntropy");let i=null;if(null!=n&&(i=lo(n,"weights","sigmoidCrossEntropy")),Je(s.shape,o.shape,"Error in sigmoidCrossEntropy: "),r>0){const e=Ul(r),t=Ul(1),n=Ul(.5);s=au(iu(s,fc(t,e)),iu(n,e))}const u=function(e,t){const n=lo(e,"labels","sigmoidCrossEntropyWithLogits"),r=lo(t,"logits","sigmoidCrossEntropyWithLogits");Je(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const a=_p(r),s=iu(r,n),o=cc(Kl(Ci(uu(r))));return au(fc(a,s),o)}(s,o);return Xh(u,i,a)}}),rd=ho({softmaxCrossEntropy_:function(e,t,n,r=0,a=qh.SUM_BY_NONZERO_WEIGHTS){let s=lo(e,"onehotLabels","softmaxCrossEntropy");const o=lo(t,"logits","softmaxCrossEntropy");let i=null;if(null!=n&&(i=lo(n,"weights","softmaxCrossEntropy")),Je(s.shape,o.shape,"Error in softmaxCrossEntropy: "),r>0){const e=Ul(r),t=Ul(1),n=Ul(s.shape[1]);s=au(iu(s,fc(t,e)),ou(e,n))}const u=function(e,t,n=-1){if(-1===n&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);const r=pc(((e,t,r)=>{const a=gc(t,[n],!0),s=fc(bi(t,"float32"),a);r([e,s]);const o=Ci(iu(s,e));return{value:Wl(o,[n]),gradFunc:(e,t)=>{const[r,a]=t,s=$l(e.shape,[n]);return[iu(Fu(e,s),fc(bi(r,"float32"),Kl(a))),iu(Fu(e,s),fc(Kl(a),bi(r,"float32")))]}}}));return r(e,t)}(s,o);return Xh(u,i,a)}}),ad=ho({sparseFillEmptyRows_:function(e,t,n,r){const a=lo(e,"indices","sparseFillEmptyRows","int32"),s=lo(t,"values","sparseFillEmptyRows"),o=lo(n,"denseShape","sparseFillEmptyRows","int32"),i=lo(r,"defaultValue","sparseFillEmptyRows",s.dtype);if(2!==a.rank)throw new Error(`Indices should be Tensor2D but received shape\n ${a.shape}`);if(1!==s.rank)throw new Error(`Values should be Tensor1D but received shape ${s.shape}`);if(1!==o.rank)throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);if(0!==i.rank)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);const u={indices:a,values:s,denseShape:o,defaultValue:i},l=as.runKernel(or,u);return{outputIndices:l[0],outputValues:l[1],emptyRowIndicator:l[2],reverseIndexMap:l[3]}}}),sd=ho({sparseReshape_:function(e,t,n){const r=lo(e,"inputIndices","sparseReshape","int32"),a=lo(t,"inputShape","sparseReshape","int32"),s=lo(n,"newShape","sparseReshape","int32");if(2!==r.rank)throw new Error(`Input indices should be Tensor2D but received shape\n ${r.shape}`);if(1!==a.rank)throw new Error(`Input shape should be Tensor1D but received shape ${a.shape}`);if(1!==s.rank)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);const o={inputIndices:r,inputShape:a,newShape:s},i=as.runKernel(ir,o);return{outputIndices:i[0],outputShape:i[1]}}}),od=ho({sparseSegmentMean_:function(e,t,n){const r=lo(e,"data","sparseSegmentMean"),a=lo(t,"indices","sparseSegmentMean","int32"),s=lo(n,"segmentIds","sparseSegmentMean","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${a.shape}`);if(1!==s.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${s.shape}`);const o={data:r,indices:a,segmentIds:s};return as.runKernel(ur,o)}}),id=ho({sparseSegmentSum_:function(e,t,n){const r=lo(e,"data","sparseSegmentSum"),a=lo(t,"indices","sparseSegmentSum","int32"),s=lo(n,"segmentIds","sparseSegmentSum","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${a.shape}`);if(1!==s.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${s.shape}`);const o={data:r,indices:a,segmentIds:s};return as.runKernel(lr,o)}}),ud=ho({stringNGrams_:function(e,t,n,r,a,s,o,i){const u=lo(e,"data","stringNGrams","string");if("string"!==u.dtype)throw new Error("Data must be of datatype string");if(1!==u.shape.length)throw new Error(`Data must be a vector, saw: ${u.shape}`);const l=lo(t,"dataSplits","stringNGrams");if("int32"!==l.dtype)throw new Error("Data splits must be of datatype int32");const c={separator:n,nGramWidths:r,leftPad:a,rightPad:s,padWidth:o,preserveShortSequences:i},p={data:u,dataSplits:l},h=as.runKernel(hr,p,c);return{nGrams:h[0],nGramsSplits:h[1]}}}),ld={fft:Pp,ifft:Bp,rfft:Vp,irfft:Up},cd={hammingWindow:wh,hannWindow:Th,frame:kh,stft:Ih},pd={flipLeftRight:Eh,grayscaleToRGB:Nh,resizeNearestNeighbor:zh,resizeBilinear:Uh,rotateWithOffset:Ch,cropAndResize:Sh,nonMaxSuppression:Rh,nonMaxSuppressionAsync:async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY){const s=lo(e,"boxes","nonMaxSuppressionAsync"),o=lo(t,"scores","nonMaxSuppressionAsync"),i=Ah(s,o,n,r,a);n=i.maxOutputSize,r=i.iouThreshold,a=i.scoreThreshold;const u=await Promise.all([s.data(),o.data()]),l=u[0],c=u[1],{selectedIndices:p}=function(e,t,n,r,a){return Fh(e,t,n,r,a,0)}(l,c,n,r,a);return s!==e&&s.dispose(),o!==t&&o.dispose(),Xp(p,"int32")},nonMaxSuppressionWithScore:Ph,nonMaxSuppressionWithScoreAsync:async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=0){const o=lo(e,"boxes","nonMaxSuppressionAsync"),i=lo(t,"scores","nonMaxSuppressionAsync"),u=Ah(o,i,n,r,a,s);n=u.maxOutputSize,r=u.iouThreshold,a=u.scoreThreshold,s=u.softNmsSigma;const l=await Promise.all([o.data(),i.data()]),c=l[0],p=l[1],{selectedIndices:h,selectedScores:d}=function(e,t,n,r,a,s){return Fh(e,t,n,r,a,s,!0)}(c,p,n,r,a,s);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Xp(h,"int32"),selectedScores:Xp(d)}},nonMaxSuppressionPadded:Bh,nonMaxSuppressionPaddedAsync:async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=!1){const o=lo(e,"boxes","nonMaxSuppressionAsync"),i=lo(t,"scores","nonMaxSuppressionAsync"),u=Ah(o,i,n,r,a,null),l=u.maxOutputSize,c=u.iouThreshold,p=u.scoreThreshold,[h,d]=await Promise.all([o.data(),i.data()]),{selectedIndices:f,validOutputs:m}=function(e,t,n,r,a,s){return Fh(e,t,n,r,a,0,!1,s,!0)}(h,d,l,c,p,s);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Xp(f,"int32"),validOutputs:Ul(m,"int32")}},threshold:Vh,transform:Wh},hd={bandPart:Hh,gramSchmidt:Gh,qr:Kh},dd={absoluteDifference:Yh,computeWeightedLoss:Xh,cosineDistance:Qh,hingeLoss:Jh,huberLoss:Zh,logLoss:ed,meanSquaredError:td,sigmoidCrossEntropy:nd,softmaxCrossEntropy:rd},fd={sparseFillEmptyRows:ad,sparseReshape:sd,sparseSegmentMean:od,sparseSegmentSum:id},md={stringNGrams:ud,stringSplit:ho({stringSplit_:function(e,t,n=!0){const r=lo(e,"input","stringSplit","string"),a=lo(t,"delimiter","stringSplit","string");if(1!==r.rank)throw new Error(`Input should be Tensor1D but received shape ${r.shape}`);if(0!==a.rank)throw new Error(`Delimiter should be a scalar but received shape ${a.shape}`);const s={skipEmpty:n},o={input:r,delimiter:a},i=as.runKernel(dr,o,s);return{indices:i[0],values:i[1],shape:i[2]}}}),stringToHashBucketFast:ho({stringToHashBucketFast_:function(e,t){const n=lo(e,"input","stringToHashBucketFast","string"),r={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");const a={input:n};return as.runKernel(fr,a,r)}})},gd="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:e=>e();function yd(e,t){const n=e[0].length;e.forEach(((e,t)=>{Qe(e.length===n,(()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`))})),Qe(t>=0&&t<n,(()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`));const r=e[0];e.forEach(((e,a)=>{for(let s=0;s<n;s++)Qe(s===t||e[s]===r[s],(()=>`Error in concat${n}D: Shape of tensors[${a}] (${e}) does not match the shape of the rest (${r}) along the non-concatenated axis ${a}.`))}))}function bd(e,t){const n=e[0].slice();for(let r=1;r<e.length;r++)n[t]+=e[r][t];return n}var _d;function xd(e,t,n){let r=new Array;if(null==n&&null==t)return r;if(null==t)for(;r.length<e+n.length;)r.push(-1);else r=t.slice();if(null==n)return r;if(e+n.length!==r.length)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.rank = ${e+n.length}, but shape.rank = ${r.length}`);for(let a=1;a<n.length;++a){const s=n[a],o=r[r.length-n.length+a],i=r[o];if(s>=0)if(i>=0){if(i!==s)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${a+e}] = ${s} but shape[${a+e}] = ${i}`)}else r[o]=s}return r}function vd(e){const t={FIRST_DIM_SIZE:_d.FIRST_DIM_SIZE,VALUE_ROWIDS:_d.VALUE_ROWIDS,ROW_LENGTHS:_d.ROW_LENGTHS,ROW_SPLITS:_d.ROW_SPLITS,ROW_LIMITS:_d.ROW_LIMITS,ROW_STARTS:_d.ROW_STARTS},n=[];for(const r of e){if(!(r in t))break;n.push(t[r])}return n}function wd(e){return 0===e.length?0:e[0]===_d.FIRST_DIM_SIZE?e.length-1:e.length}function Td(e,t){if(null==e||null==t)return;const n=e.length,r=t.length;if(n>=r)throw new Error(`defaultValue.shape=${e} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${n} must be less than ragged tensor input flatValues.rank = ${r})`);for(let a=0;a<Math.min(n,r-1);++a){const n=e[a],r=t[a+1];if(n>=0&&r>=0&&1!==n&&n!==r)throw new Error(`defaultValue.shape=${e}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${a-e.length}] = ${n} but ragged tensor input.flatValues.shape[${a-e.length}] = ${r}`)}}!function(e){e[e.FIRST_DIM_SIZE=0]="FIRST_DIM_SIZE",e[e.VALUE_ROWIDS=1]="VALUE_ROWIDS",e[e.ROW_LENGTHS=2]="ROW_LENGTHS",e[e.ROW_SPLITS=3]="ROW_SPLITS",e[e.ROW_LIMITS=4]="ROW_LIMITS",e[e.ROW_STARTS=5]="ROW_STARTS"}(_d||(_d={}));const kd=30;function Id(e){return e<=kd?e:gt(e,Math.floor(Math.sqrt(e)))}function Sd(e,t,n){return[n*("number"==typeof e?e:e[0]),t*("number"==typeof e?e:e[1])]}function Ed(e,t,n,r=!0){let a=[];if(r)a=a.concat(t.slice(0)),a.push(e[0]/n),a=a.concat(e.slice(1));else{a=a.concat(e[0]);const n=t.length;for(let r=0;r<n;++r)a=a.concat([e[r+1]/t[r],t[r]]);a=a.concat(e.slice(n+1))}return a}function Nd(e,t,n=!0){const r=[];if(n){r.push(t);for(let n=t+1;n<e;++n)n<=2*t?(r.push(n),r.push(n-(t+1))):r.push(n)}else{const n=[],a=[];for(let r=1;r<e;++r)r>=2*t+1||r%2==1?a.push(r):n.push(r);r.push(...n),r.push(0),r.push(...a)}return r}function Cd(e,t,n,r=!0){const a=[];r?a.push(e[0]/n):a.push(e[0]*n);for(let n=1;n<e.length;++n)n<=t.length?r?a.push(t[n-1]*e[n]):a.push(e[n]/t[n-1]):a.push(e[n]);return a}function Ad(e,t){const n=[0];for(let r=0;r<t;++r)n.push(e[r][0]);return n}function Rd(e,t,n){const r=e.slice(0,1);for(let a=0;a<n;++a)r.push(e[a+1]-t[a][0]-t[a][1]);return r}function $d(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);const n=new Float32Array(2*e.length);for(let r=0;r<n.length;r+=2)n[r]=e[r/2],n[r+1]=t[r/2];return n}const Md=/->/g;function Fd(e,t){const n=[];for(let r=0;r<e.length;++r)0!==e[r].length&&-1===e[r].indexOf(t)&&-1!==t||n.push(r);return n}function Od(e,t,n=0){let r=[];if("number"==typeof t)Qe(e.shape[n]%t==0,(()=>"Number of splits must evenly divide the axis.")),r=new Array(t).fill(e.shape[n]/t);else{Qe(t.reduce(((e,t)=>(-1===t&&(e+=1),e)),0)<=1,(()=>"There should be only one negative value in split array."));const a=t.indexOf(-1);if(-1!==a){const r=t.reduce(((e,t)=>t>0?e+t:e));t[a]=e.shape[n]-r}Qe(e.shape[n]===t.reduce(((e,t)=>e+t)),(()=>"The sum of sizes must match the size of the axis dimension.")),r=t}return r}function Dd(e){return`Received SparseTensor with denseShape[0] = 0 but\n indices.shape[0] = ${e}`}function Ld(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function Pd(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function Bd(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function Ud(e,t){return`size ${e} must be non-negative, not ${t}`}function zd(e,t){return`Input to reshape is a SparseTensor with ${et(e)}\n dense values, but the requested shape requires a multiple of ${et(t)}. inputShape=${e} outputShape= ${t}`}function Vd(e,t){return`Input to reshape is a tensor with ${et(e)} dense values, but the requested shape has ${et(t)}. inputShape=${e} outputShape=${t}`}function Wd(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function Hd(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}function Gd(e,t,n,r){const a=t.shape.length,s=e.shape.length;if(0!==r&&(r<-a||r>a))throw new Error(`Expect batchDims in the range of [-${a}, ${a}], but got ${r}`);if(r<0&&(r+=a),r>s)throw new Error(`batchDims (${r}) must be less than rank(x) (\n ${s}).`);if(n<r)throw new Error(`batchDims (${r}) must be less than or equal to axis (${n}).`);for(let n=0;n<r;++n)if(e.shape[n]!==t.shape[n])throw new Error(`x.shape[${n}]: ${e.shape[n]} should be equal to indices.shape[${n}]: ${t.shape[n]}.`);const o=e.shape[n],i=[];let u=1,l=1,c=1;for(let t=0;t<r;++t)i.push(e.shape[t]),u*=e.shape[t];for(let t=r;t<n;t++)i.push(e.shape[t]),l*=e.shape[t];for(let e=r;e<a;e++)i.push(t.shape[e]);for(let t=n+1;t<s;t++)i.push(e.shape[t]),c*=e.shape[t];return{batchSize:u,sliceSize:c,outerSize:l,dimSize:o,outputShape:i}}var jd=Object.freeze({__proto__:null,segOpComputeOptimalWindowSize:function(e,t){let n,r=!1;for(e<=kd?(n=e,r=!0):n=gt(e,Math.floor(Math.sqrt(e)));!r;)n>t||n===e?r=!0:n=gt(e,n+1);return n},computeOutShape:function(e,t,n){const r=[],a=e.length;for(let s=0;s<a;s++)s!==t?r.push(e[s]):r.push(n);return r},collectGatherOpShapeInfo:Gd});function Kd(e){try{return e.map((e=>Ia(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function qd(e){return e.map((e=>ka(e)))}var Xd=Object.freeze({__proto__:null,slice_util:ru,segment_util:jd,fromUint8ToStringArray:Kd,fromStringArrayToUint8:qd,upcastType:Ya,axesAreInnerMostDims:Cl,combineLocations:Al,computeOutAndReduceShapes:Rl,expandShapeToKeepDim:$l,assertAxesAreInnerMostDims:Ml,getAxesPermutation:Fl,getUndoAxesPermutation:Ol,getInnerMostAxes:Dl,getBroadcastDims:$i,getReductionAxes:Mi,assertAndGetBroadcastShape:Fi,assertParamsConsistent:yd,computeOutShape:bd,computeDilation2DInfo:function(e,t,n,r,a="NHWC",s){return wu(e,[...t,e[3]],n,s,r,null,null,$u(a))},computePool2DInfo:vu,computePool3DInfo:function(e,t,n,r,a,s,o="NDHWC"){const[i,u,l]=Su(t);let c,p;if("NDHWC"===o)p="channelsLast",c=[i,u,l,e[4],e[4]];else{if("NCDHW"!==o)throw new Error(`Unknown dataFormat ${o}`);p="channelsFirst",c=[i,u,l,e[1],e[1]]}return Tu(e,c,n,r,a,!1,p,s)},computeConv2DInfo:wu,computeConv3DInfo:Tu,computeDefaultPad:ku,tupleValuesAreOne:Cu,eitherStridesOrDilationsAreOne:Au,stridesOrDilationsArePositive:Ru,convertConv2DDataFormat:$u,checkPadOnDimRoundingMode:Mu,getFusedDyActivation:hh,getFusedBiasGradient:dh,applyActivation:fh,shouldFuse:mh,get RowPartitionType(){return _d},combineRaggedTensorToTensorShapes:xd,getRowPartitionTypesHelper:vd,getRaggedRank:wd,validateDefaultValueShape:Td,PARALLELIZE_THRESHOLD:kd,computeOptimalWindowSize:Id,getImageCenter:Sd,getReshaped:Ed,getPermuted:Nd,getReshapedPermuted:Cd,getSliceBeginCoords:Ad,getSliceSize:Rd,prepareAndValidate:Pi,validateUpdateShape:Bi,validateInput:Ui,calculateShapes:zi,SELU_SCALEALPHA:1.7580993408473768,SELU_SCALE:1.0507009873554805,ERF_P:.3275911,ERF_A1:.254829592,ERF_A2:-.284496736,ERF_A3:1.421413741,ERF_A4:-1.453152027,ERF_A5:1.061405429,warn:Cr,log:function(...e){Ct().getBool("IS_TEST")||Ct().getBool("PROD")||console.log(...e)},mergeRealAndImagArrays:$d,splitRealAndImagArrays:function(e){const t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=e[r],n[r/2]=e[r+1];return{real:t,imag:n}},complexWithEvenIndex:function(e){const t=Math.ceil(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let t=0;t<e.length;t+=4)n[Math.floor(t/4)]=e[t],r[Math.floor(t/4)]=e[t+1];return{real:n,imag:r}},complexWithOddIndex:function(e){const t=Math.floor(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let t=2;t<e.length;t+=4)n[Math.floor(t/4)]=e[t],r[Math.floor(t/4)]=e[t+1];return{real:n,imag:r}},getComplexWithIndex:function(e,t){return{real:e[2*t],imag:e[2*t+1]}},assignToTypedArray:function(e,t,n,r){e[2*r]=t,e[2*r+1]=n},exponents:function(e,t){const n=new Float32Array(e/2),r=new Float32Array(e/2);for(let a=0;a<Math.ceil(e/2);a++){const s=(t?2:-2)*Math.PI*(a/e);n[a]=Math.cos(s),r[a]=Math.sin(s)}return{real:n,imag:r}},exponent:function(e,t,n){const r=(n?2:-2)*Math.PI*(e/t);return{real:Math.cos(r),imag:Math.sin(r)}},decodeEinsumEquation:function(e,t){const n=((e=e.replace(/\s/g,"")).length-e.replace(Md,"").length)/2;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error('Equation must contain exactly one arrow ("->").');const[r,a]=e.split("->");Qe(-1===r.indexOf("..."),(()=>'The ellipsis notation ("...") is not supported yet.'));const s=r.split(","),o=s.length;if(t!==o)throw new Error(`Expected ${o} input tensors, received ${t}`);if(o>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");const i=[];for(let e=0;e<a.length;++e){const t=a[e];if(!s.some((e=>-1!==e.indexOf(t))))throw new Error(`Output subscripts contain the label ${t} not present in the input subscripts.`);-1===i.indexOf(t)&&i.push(t)}for(let e=0;e<r.length;++e){const t=r[e];-1===i.indexOf(t)&&","!==t&&i.push(t)}const u=new Array(s.length);for(let e=0;e<o;++e){if(new Set(s[e].split("")).size!==s[e].length)throw new Error(`Found duplicate axes in input component ${s[e]}. Support for duplicate axes in input is not implemented yet.`);u[e]=[];for(let t=0;t<s[e].length;++t)u[e].push(i.indexOf(s[e][t]))}const l=i.length,c=[];for(let e=a.length;e<l;++e)c.push(e);return{allDims:i,summedDims:c,idDims:u}},getEinsumPermutation:function(e,t){let n=new Array(e);n.fill(-1);for(let e=0;e<t.length;++e)n[t[e]]=e;const r=[];for(let t=0;t<e;++t)-1===n[t]&&r.push(t);return n=n.filter((e=>-1!==e)),{permutationIndices:n,expandDims:r}},checkEinsumDimSizes:function(e,t,n){const r=new Array(e);for(let e=0;e<n.length;++e){const a=n[e].shape;for(let n=0;n<t[e].length;++n)void 0===r[t[e][n]]?r[t[e][n]]=a[n]:Qe(r[t[e][n]]===a[n],(()=>`Expected dimension ${r[t[e][n]]} at axis ${n} of input shaped ${JSON.stringify(a)}, but got dimension ${a[n]}`))}},getEinsumComputePath:function(e,t){const n=e,r=[];let a=0;0===e.length&&n.push(-1),a=e.length+1;for(let e=0;e<a;++e)r.push([]);const s=[];for(let e=0;e<n.length;++e){const a=Fd(t,n[e]);for(const t of a)-1===s.indexOf(t)&&(r[e].push(t),s.push(t))}return{path:n,steps:r}},isIdentityPermutation:function(e){return e.every(((e,t)=>e===t))},prepareSplitSize:Od,getSparseFillEmptyRowsIndicesDenseShapeMismatch:Dd,getSparseFillEmptyRowsNegativeIndexErrorMessage:Ld,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:Pd,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:Bd,getSparseReshapeNegativeOutputDimErrorMessage:Ud,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:function(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"},getSparseReshapeInputOutputMultipleErrorMessage:zd,getSparseReshapeInputOutputMismatchErrorMessage:Vd,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:function(){return"segment ids must be >= 0"},getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:function(){return"segment ids are not increasing"},getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:Wd,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:Hd});class Yd{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}setTimeoutCustom(e,t){"undefined"!=typeof window&&Ct().getBool("USE_SETTIMEOUTCUSTOM")?(this.functionRefs.push(e),setTimeout((()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")}),t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",(e=>{e.source===window&&e.data.name===this.messageName&&(e.stopPropagation(),(0,this.functionRefs[e.data.index])(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0))}),!0))):setTimeout(e,t)}isTypedArray(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}}if(Ct().get("IS_BROWSER")){Ct().setPlatform("browser",new Yd);try{fi.registerManager(Yo.URL_SCHEME,new Jo)}catch(e){}try{fi.registerManager(Lo.URL_SCHEME,new Bo)}catch(e){}}let Qd;var Jd,Zd;Ct().get("IS_NODE")&&!Ct().get("IS_BROWSER")&&Ct().setPlatform("node",new class{constructor(){this.util=n(345),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=Ct().global.fetch?Ct().global.fetch(e,t):(null==Qd&&(Qd=n(683)),Qd(e,t))}now(){const e=He.hrtime();return 1e3*e[0]+e[1]/1e6}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return 0===e.length?"":new this.util.TextDecoder(t).decode(e)}isTypedArray(e){return this.util.types.isFloat32Array(e)||this.util.types.isInt32Array(e)||this.util.types.isUint8Array(e)||this.util.types.isUint8ClampedArray(e)}}),rs(),za={buffer:Qu,cast:bi,clone:Lu,print:Kc},Ct().registerFlag("KEEP_INTERMEDIATE_TENSORS",(()=>!1),(e=>{e&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")})),function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_QINT16=15]="DT_QINT16",e[e.DT_QUINT16=16]="DT_QUINT16",e[e.DT_UINT16=17]="DT_UINT16",e[e.DT_COMPLEX128=18]="DT_COMPLEX128",e[e.DT_HALF=19]="DT_HALF",e[e.DT_RESOURCE=20]="DT_RESOURCE",e[e.DT_VARIANT=21]="DT_VARIANT",e[e.DT_UINT32=22]="DT_UINT32",e[e.DT_UINT64=23]="DT_UINT64",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",e[e.DT_QINT16_REF=115]="DT_QINT16_REF",e[e.DT_QUINT16_REF=116]="DT_QUINT16_REF",e[e.DT_UINT16_REF=117]="DT_UINT16_REF",e[e.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",e[e.DT_HALF_REF=119]="DT_HALF_REF",e[e.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",e[e.DT_VARIANT_REF=121]="DT_VARIANT_REF",e[e.DT_UINT32_REF=122]="DT_UINT32_REF",e[e.DT_UINT64_REF=123]="DT_UINT64_REF"}(Jd||(Jd={})),function(e){var t;(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"}(Zd||(Zd={}));const ef={};function tf(e){return ef[e]}function nf(e,t,n,r,a){const s=t.inputParams[e];if(s&&void 0!==s.inputIndexStart){const e=s.inputIndexStart,o=0===s.inputIndexEnd?void 0:void 0===s.inputIndexEnd?e+1:s.inputIndexEnd;if("tensor"===s.type)return rf(t.inputNames[s.inputIndexStart],n,r,a);if("tensors"===s.type)return t.inputNames.slice(e,o).map((e=>rf(e,n,r,a)));const i=rf(t.inputNames.slice(e)[0],n,r,a),u=i.dataSync();return"number"===s.type?u[0]:_t(i.shape,u)}const o=t.attrParams[e];return o&&o.value}function rf(e,t,n,r){const[a,s]=of(e);if(null!=r){const e=r.getHashTableHandleByName(a);if(null!=e)return e}const o=n.currentContextIds.find((e=>!!t[sf(a,e)]));return void 0!==o?t[sf(a,o)][s]:void 0}function af(e,t){const[n,r,a]=of(e);return[sf(n,t&&t.currentContextId),r,a]}function sf(e,t){return t?`${e}-${t}`:e}function of(e){const t=e.split(":");if(1===t.length)return[e,0,void 0];const n=t[0],r=3===t.length?t[1]:void 0;return[n,Number(t[t.length-1]),r]}function uf(e,t,n){let r=nf("pad",e,t,n);if("explicit"===r){r=nf("explicitPaddings",e,t,n);const a=[[0,0],[0,0],[0,0],[0,0]];for(let e=0;e<4;e++)a[e][0]=r[2*e],a[e][1]=r[2*e+1];return a}return r}function lf(e){return e.kept?e:Lu(e)}var cf=Object.freeze({__proto__:null,json:[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),pf=Object.freeze({__proto__:null,json:[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),hf=Object.freeze({__proto__:null,json:[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcatV2",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListLength",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}]},{tfOpName:"TensorListResize",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"size",type:"number"}]}]}),df=Object.freeze({__proto__:null,json:[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}]}),ff=Object.freeze({__proto__:null,json:[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomStandardNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}]}),mf=Object.freeze({__proto__:null,json:[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),gf=Object.freeze({__proto__:null,json:[{tfOpName:"LowerBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"UpperBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}]}),yf=Object.freeze({__proto__:null,json:[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}]}),bf=Object.freeze({__proto__:null,json:[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"InitializeTable",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]},{tfOpName:"InitializeTableV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]}]}),_f=Object.freeze({__proto__:null,json:[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]},{tfOpName:"ImageProjectiveTransformV3",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"transforms",type:"tensor"},{start:2,name:"outputShape",type:"number[]"},{start:3,name:"fillValue",type:"number"}],attrs:[{tfName:"interpolation",name:"interpolation",type:"string"},{tfName:"fill_mode",name:"fillMode",type:"string"}]}]}),xf=Object.freeze({__proto__:null,json:[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),vf=Object.freeze({__proto__:null,json:[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]}]}),wf=Object.freeze({__proto__:null,json:[{tfOpName:"EuclideanNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",defaultValue:!1}]},{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}]}),Tf=Object.freeze({__proto__:null,json:[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Cumprod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}]}),kf=Object.freeze({__proto__:null,json:[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}]}),If=Object.freeze({__proto__:null,json:[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}]}),Sf=Object.freeze({__proto__:null,json:[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}]}),Ef=Object.freeze({__proto__:null,json:[{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}]}),Nf=Object.freeze({__proto__:null,json:[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}]});class Cf{constructor(){const e=[].concat(...[cf,pf,hf,df,ff,mf,gf,yf,bf,_f,xf,vf,wf,Tf,kf,If,Sf,Ef,Nf].map((e=>e.json)));this.opMappers=e.reduce(((e,t)=>(e[t.tfOpName]=t,e)),{})}static get Instance(){return this._instance||(this._instance=new this)}transformGraph(e,t={}){const n=e.node,r=[],a=[],s=[],o=n.reduce(((e,t)=>(e[t.name]=this.mapNode(t),t.op.startsWith("Placeholder")?r.push(e[t.name]):"Const"===t.op?a.push(e[t.name]):null!=t.input&&0!==t.input.length||s.push(e[t.name]),e)),{});let i=[];const u=[];let l={},c={};null!=t&&(l=this.mapSignatureEntries(t.inputs),c=this.mapSignatureEntries(t.outputs));const p=Object.keys(o);p.forEach((e=>{const t=o[e];t.inputNames.forEach(((e,n)=>{const[r,,a]=af(e),s=o[r];if(null!=s.outputs){const e=s.outputs.indexOf(a);if(-1!==e){const a=`${r}:${e}`;t.inputNames[n]=a}}t.inputs.push(s),s.children.push(t)}))})),0===Object.keys(c).length?p.forEach((e=>{const t=o[e];0===t.children.length&&u.push(t)})):Object.keys(c).forEach((e=>{const[t]=af(e),n=o[t];null!=n&&(n.signatureKey=c[e],u.push(n))})),Object.keys(l).length>0?Object.keys(l).forEach((e=>{const[t]=af(e),n=o[t];n&&(n.signatureKey=l[e],i.push(n))})):i=r;let h={};null!=e.library&&null!=e.library.function&&(h=e.library.function.reduce(((e,t)=>(e[t.signature.name]=this.mapFunction(t),e)),{}));const d={nodes:o,inputs:i,outputs:u,weights:a,placeholders:r,signature:t,functions:h};return s.length>0&&(d.initNodes=s),d}mapSignatureEntries(e){return Object.keys(e||{}).reduce(((t,n)=>(t[e[n].name]=n,t)),{})}mapNode(e){const t=tf(e.op)||this.opMappers[e.op]||{};null==e.attr&&(e.attr={});const n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map((e=>e.startsWith("^")?e.slice(1):e)),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return null!=t.inputs&&(n.inputParams=t.inputs.reduce(((e,t)=>(e[t.name]={type:t.type,inputIndexStart:t.start,inputIndexEnd:t.end},e)),{})),null!=t.attrs&&(n.attrParams=t.attrs.reduce(((t,n)=>{const r=n.type;let a;switch(n.type){case"string":a=Rf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Rf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":a=zf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=zf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":a=Mf(e.attr,n.tfName,n.defaultValue||0),void 0===a&&n.tfDeprecatedName&&(a=Mf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":a=Uf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Uf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":a=$f(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=$f(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":a=Wf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Wf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":a=Bf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Bf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":a=Vf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Vf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":a=Df(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Df(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":a=Lf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Lf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":a=Of(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Of(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${n.type} for op: ${e.op}`)}return t[n.name]={value:a,type:r},t}),{})),n}mapFunction(e){const t=e.nodeDef,n=[];let r={};null!=t&&(r=t.reduce(((e,t)=>(e[t.name]=this.mapNode(t),"Const"===t.op&&n.push(e[t.name]),e)),{}));const a=[],s=[];e.signature.inputArg.forEach((e=>{const[t]=af(e.name),n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Ff(e.type),type:"dtype"}},children:[]};n.signatureKey=e.name,a.push(n),r[t]=n})),Object.keys(r).forEach((e=>{const t=r[e];t.inputNames.forEach(((e,n)=>{const[a,,s]=af(e),o=r[a];if(null!=o.outputs){const e=o.outputs.indexOf(s);if(-1!==e){const r=`${a}:${e}`;t.inputNames[n]=r}}t.inputs.push(o),o.children.push(t)}))}));const o=e.ret;e.signature.outputArg.forEach((e=>{const[t,n]=af(o[e.name]),a=r[t];null!=a&&(a.defaultOutput=n,s.push(a))}));const i=this.mapArgsToSignature(e);return{nodes:r,inputs:a,outputs:s,weights:n,placeholders:[],signature:i}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce(((e,t)=>(e[t.name]=this.mapArgToTensorInfo(t),e)),{}),outputs:e.signature.outputArg.reduce(((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t)),{})}}mapArgToTensorInfo(e,t){let n=e.name;return null!=t&&(n=t[n]),{name:n,dtype:e.type}}}function Af(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){const t=Ct().global;if(void 0!==t.atob)return t.atob(e);if(void 0!==ws)return new ws(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}(e);return t?n:n.toLowerCase()}function Rf(e,t,n,r=!1){const a=e[t];return null!=a?Af(a.s,r):n}function $f(e,t,n){const r=e[t];return r?r.b:n}function Mf(e,t,n){const r=e[t]||{},a=null!=r.i?r.i:null!=r.f?r.f:n;return"number"==typeof a?a:parseInt(a,10)}function Ff(e){switch("string"==typeof e&&(e=Jd[e]),e){case Jd.DT_FLOAT:case Jd.DT_HALF:return"float32";case Jd.DT_INT32:case Jd.DT_INT64:case Jd.DT_INT8:case Jd.DT_UINT8:return"int32";case Jd.DT_BOOL:return"bool";case Jd.DT_DOUBLE:return"float32";case Jd.DT_STRING:return"string";default:return null}}function Of(e,t,n){const r=e[t];return r&&r.func?r.func.name:n}function Df(e,t,n){const r=e[t];return r&&r.type?Ff(r.type):n}function Lf(e,t,n){const r=e[t];return r&&r.list&&r.list.type?r.list.type.map((e=>Ff(e))):n}function Pf(e){if(!e.unknownRank)return null!=e.dim?e.dim.map((e=>"number"==typeof e.size?e.size:parseInt(e.size,10))):[]}function Bf(e,t,n){const r=e[t];return r&&r.shape?Pf(r.shape):n}function Uf(e,t,n){const r=e[t];return r?((r.list.f&&r.list.f.length?r.list.f:r.list.i)||[]).map((e=>"number"==typeof e?e:parseInt(e,10))):n}function zf(e,t,n,r=!1){const a=e[t];return a&&a.list&&a.list.s?a.list.s.map((e=>Af(e,r))):n}function Vf(e,t,n){const r=e[t];return r&&r.list&&r.list.shape?r.list.shape.map((e=>Pf(e))):n}function Wf(e,t,n){const r=e[t];return r&&r.list&&r.list.b?r.list.b:n}class Hf{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map((e=>this.getInput(e))),null!=e.rawAttrs&&(this.attrs=Object.keys(e.rawAttrs).reduce(((e,t)=>(e[t]=this.getAttr(t),e)),{}))}getInput(e){return rf(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(null!=n.tensor)return rf(e,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return Mf(this.node.rawAttrs,e,t);if(null!=n.s)return Rf(this.node.rawAttrs,e,t);if(null!=n.b)return $f(this.node.rawAttrs,e,t);if(null!=n.shape)return Bf(this.node.rawAttrs,e,t);if(null!=n.type)return Df(this.node.rawAttrs,e,t);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return Uf(this.node.rawAttrs,e,t);if(null!=n.list.s)return zf(this.node.rawAttrs,e,t);if(null!=n.list.shape)return Vf(this.node.rawAttrs,e,t);if(null!=n.list.b)return Wf(this.node.rawAttrs,e,t);if(null!=n.list.type)return Lf(this.node.rawAttrs,e,t)}return t}}var Gf=Object.freeze({__proto__:null,abs:uu,acos:lu,acosh:cu,add:au,addN:pu,all:hu,any:du,argMax:fu,argMin:mu,asin:gu,asinh:yu,atan:bu,atan2:_u,atanh:xu,avgPool:Ou,avgPool3d:Du,basicLSTMCell:Vu,batchToSpaceND:Wu,batchNorm:Hu,batchNorm2d:Gu,batchNorm3d:ju,batchNorm4d:Ku,bincount:qu,broadcastArgs:Xu,broadcastTo:Yu,buffer:Qu,cast:bi,ceil:Ju,clipByValue:el,clone:Lu,complex:fo,concat:Pu,concat1d:tl,concat2d:nl,concat3d:rl,concat4d:al,conv1d:ol,conv2d:sl,conv2dTranspose:ul,conv3d:ll,conv3dTranspose:pl,cos:hl,cosh:dl,cumprod:fl,cumsum:ml,denseBincount:gl,depthToSpace:yl,depthwiseConv2d:bl,diag:_l,dilation2d:xl,div:ou,divNoNan:kl,dot:Il,einsum:Sl,elu:El,equal:vl,erf:Nl,euclideanNorm:jl,exp:Kl,expandDims:ql,expm1:Xl,eye:Ql,fill:Zu,floor:Jl,floorDiv:su,gather:Zl,greater:ec,greaterEqual:tc,imag:Ni,isFinite:nc,isInf:rc,isNaN:ac,leakyRelu:sc,less:oc,lessEqual:ic,linspace:function(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");const r={start:e,stop:t,num:n};return as.runKernel("LinSpace",{},r)},localResponseNormalization:uc,log:lc,log1p:cc,logSigmoid:dc,logSoftmax:mc,logSumExp:gc,logicalAnd:yc,logicalNot:bc,logicalOr:_c,logicalXor:xc,lowerBound:function(e,t){return wc(e,t,"left")},matMul:_i,max:Ll,maxPool:Tc,maxPool3d:kc,maxPoolWithArgmax:Ic,maximum:Sc,mean:Ec,meshgrid:function(e,t,{indexing:n="xy"}={}){if("xy"!==n&&"ij"!==n)throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(void 0===e)return[];let r=lo(e,"x","meshgrid",e instanceof Va?e.dtype:"float32");if(void 0===t)return[r];let a=lo(t,"y","meshgrid",t instanceof Va?t.dtype:"float32");const s=et(r.shape),o=et(a.shape);return"xy"===n?(r=Fu(r,[1,-1]),a=Fu(a,[-1,1]),[_i(Cc([o,1],r.dtype),r),_i(a,Cc([1,s],a.dtype))]):(r=Fu(r,[-1,1]),a=Fu(a,[1,-1]),[_i(r,Cc([1,o],r.dtype)),_i(Cc([s,1],a.dtype),a)])},min:Pl,minimum:Ac,mirrorPad:Rc,mod:$c,moments:Mc,mul:iu,multiRNNCell:Fc,multinomial:Oc,neg:Ci,notEqual:Dc,oneHot:xi,ones:Cc,onesLike:Lc,outerProduct:Pc,pad:Bc,pad1d:Uc,pad2d:zc,pad3d:Vc,pad4d:Wc,pool:Gc,pow:Bl,prelu:jc,print:Kc,prod:qc,raggedGather:Xc,raggedRange:Yc,raggedTensorToTensor:Qc,rand:Jc,randomGamma:dp,randomNormal:fp,randomStandardNormal:mp,randomUniform:gp,range:yp,real:Ai,reciprocal:bp,relu:_p,relu6:xp,reshape:Fu,reverse:vp,reverse1d:wp,reverse2d:Tp,reverse3d:kp,reverse4d:Ip,round:Sp,rsqrt:Ep,scalar:Ul,selu:Np,separableConv2d:Cp,setdiff1dAsync:async function(e,t){const n=lo(e,"x","setdiff1d"),r=lo(t,"y","setdiff1d");Qe(n.dtype===r.dtype,(()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`)),Qe(1===n.rank,(()=>`x should be 1D tensor, but got x (${n.shape}).`)),Qe(1===r.rank,(()=>`y should be 1D tensor, but got y (${r.shape}).`));const a=await n.data(),s=await r.data(),o=new Set(s);let i=0;for(let e=0;e<a.length;e++)o.has(a[e])||i++;const u=new Ba([i],n.dtype),l=new Ba([i],"int32");for(let e=0,t=0;e<a.length;e++)o.has(a[e])||(u.values[t]=a[e],l.values[t]=e,t++);return[u.toTensor(),l.toTensor()]},sigmoid:Bu,sign:Ap,sin:Rp,sinh:$p,slice:Uu,slice1d:Mp,slice2d:Fp,slice3d:Op,slice4d:Dp,softmax:Lp,softplus:hc,spaceToBatchND:Hc,fft:Pp,ifft:Bp,irfft:Up,rfft:Vp,split:zp,sqrt:zl,square:Vl,squaredDifference:Wp,squeeze:Hp,stack:Gp,step:jp,stridedSlice:Kp,sub:fc,sum:Wl,tan:qp,tanh:zu,tensor:go,tensor1d:Xp,tensor2d:Yp,tensor3d:Oi,tensor4d:function(e,t,n){if(Ze(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");const r=oo(e,n);if(4!==r.length&&1!==r.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return mo(e,t,r,n)},tensor5d:function(e,t,n){if(Ze(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");const r=oo(e,n);if(5!==r.length&&1!==r.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return mo(e,t,r,n)},tensor6d:function(e,t,n){if(Ze(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");const r=oo(e,n);if(6!==r.length&&1!==r.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return mo(e,t=t||r,r,n)},tile:Yl,topk:Qp,truncatedNormal:Jp,unique:Zp,unsortedSegmentSum:eh,unstack:th,upperBound:function(e,t){return wc(e,t,"right")},variable:function(e,t=!0,n,r){return as.makeVariable(e,t,n,r)},where:wl,whereAsync:rh,zeros:Nc,zerosLike:Tl,op:ho,OP_SCOPE_SUFFIX:po,booleanMaskAsync:async function(e,t,n){const r=lo(e,"tensor","boolMask"),a=lo(t,"mask","boolMask","bool"),s=null==n?0:n,o=a.rank,i=r.shape;Qe(o>0,(()=>"mask cannot be scalar")),Je(i.slice(s,s+o),a.shape,"mask's shape must match the first K dimensions of tensor's shape,");let u=1;for(let e=s;e<s+o;e++)u*=i[e];const l=i.slice(0,s).concat([u],i.slice(s+o)),c=Fu(r,l),p=Fu(a,[-1]),h=await rh(p),d=Hp(h,[1]),f=Zl(c,d,s);return e!==r&&r.dispose(),t!==a&&a.dispose(),d.dispose(),c.dispose(),p.dispose(),h.dispose(),f},transpose:Ri,norm:Gl,movingAverage:ah,scatterND:sh,searchSorted:wc,sparseToDense:oh,gatherND:ih,dropout:uh,enclosingPowerOfTwo:lh,cosineWindow:ch,inTopKAsync:async function(e,t,n=1){const r=lo(e,"predictions","inTopK"),a=lo(t,"targets","inTopK");Qe(r.rank>1,(()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`)),Qe(r.rank-1===a.rank,(()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${r.rank} and targets rank ${a.rank}`)),Je(r.shape.slice(0,r.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const s=r.shape[r.shape.length-1];Qe(n>0&&n<=s,(()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${n}`));const o=await r.data(),i=await a.data(),[u,l]=[o.length/s,s],c=lt("bool",u);for(let e=0;e<u;e++){const t=e*l,r=o.subarray(t,t+l),a=[];for(let e=0;e<r.length;e++)a.push({value:r[e],index:e});a.sort(((e,t)=>t.value-e.value)),c[e]=0;for(let t=0;t<n;t++)if(a[t].index===i[e]){c[e]=1;break}}return e!==r&&r.dispose(),t!==a&&a.dispose(),go(c,a.shape,"bool")},image:pd,linalg:hd,losses:dd,spectral:ld,fused:vh,signal:cd,sparse:fd,string:md});function jf(e,t,n=""){if("number"!=typeof e&&"number"!=typeof t){Qe(e.length===t.length,(()=>n+` Shapes ${e} and ${t} must match`));for(let r=0;r<e.length;r++){const a=e[r],s=t[r];Qe(a<0||s<0||a===s,(()=>n+` Shapes ${e} and ${t} must match`))}}}function Kf(e){return"number"!=typeof e&&!e.some((e=>e<0))}function qf(e,t,n){let r=Xf(e,n);const a=!Kf(r);if(a&&0===t.length)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${r}`);if(a&&t.forEach((e=>{r=Xf(e.shape,r)})),!Kf(r))throw new Error(`Non-fully-defined elementShape: ${r}`);return r}function Xf(e,t){if("number"==typeof e)return t;if("number"==typeof t)return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);const n=[];for(let r=0;r<e.length;++r){const a=e[r],s=t[r];if(a>=0&&s>=0&&a!==s)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[r]=a>=0?a:s}return n}class Yf{constructor(e,t,n,r,a,s,o){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=r,this.identicalElementShapes=a,this.dynamicSize=s,this.clearAfterRead=o,this.tensors=[],this.closed_=!1,this.idTensor=Ul(0),ki(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach((t=>{null!=e&&e.has(t.tensor.id)||t.tensor.dispose()})),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);const t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map((e=>this.read(e)))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);const n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},\n because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=t.shape),jf(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,ki(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach(((e,n)=>this.write(e,t[n])))}gather(e,t){if(t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let t=0;t<this.size();t++)e.push(t)}if(0===e.length)return go([],[0].concat(this.elementShape));const n=this.readMany(e);return jf(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),Gp(n,0)}concat(e){if(e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(0===this.size())return go([],[0].concat(this.elementShape));const t=[];for(let e=0;e<this.size();e++)t.push(e);const n=this.readMany(t);return jf(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Pu(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);const n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,th(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0;const r=e.map((e=>(n+=e,n)));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);const a=0===n?0:t.size/n,s=[];wi((()=>{t=Fu(t,[1,n,a]);for(let n=0;n<e.length;++n){const o=[0,0===n?0:r[n-1],0],i=[1,e[n],a];s[n]=Fu(Uu(t,o,i),this.elementShape)}return s}));const o=[];for(let t=0;t<e.length;t++)o[t]=t;this.writeMany(o,s)}}class Qf{constructor(e,t,n,r=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,null!=e&&e.forEach((e=>{if(n!==e.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${e.dtype}`);jf(t,e.shape,"TensorList shape mismatch: "),ki(e)})),this.idTensor=Ul(0),this.maxNumElements=r,ki(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Qf([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach((t=>{null!=e&&e.has(t.id)||t.dispose()})),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(-1!==n&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);jf(e,this.elementShape,"TensorList shape mismatch: ");const r=qf(this.elementShape,this.tensors,e);return wi((()=>{const e=this.tensors.map((e=>Fu(e,r)));return Gp(e,0)}))}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(0===this.size())throw new Error("Trying to pop from an empty list.");const n=qf(this.elementShape,this.tensors,e),r=this.tensors.pop();return r.kept=!1,jf(r.shape,e,"TensorList shape mismatch: "),Fu(r,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(jf(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");ki(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(-1!==this.maxNumElements&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);const t=new Qf([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let n=0;n<Math.min(this.tensors.length,e);++n)t.tensors[n]=this.tensors[n];return t}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(null==this.tensors[e])throw new Error(`element at index ${e} is null.`);jf(this.tensors[e].shape,t,"TensorList shape mismatch: ");const r=qf(this.elementShape,this.tensors,t);return Fu(this.tensors[e],r)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||-1!==this.maxNumElements&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);jf(this.elementShape,t.shape,"TensorList shape mismatch: "),ki(t),null!=this.tensors[e]&&(this.tensors[e].kept=!1),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);jf(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());const r=qf(this.elementShape,this.tensors,n);return 0===e.length?go([],[0].concat(r)):wi((()=>{const t=e.map((e=>Fu(this.tensors[e],r)));return Gp(t,0)}))}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);jf(this.elementShape,t,"TensorList shape mismatch: ");const n=qf(this.elementShape,this.tensors,t);return 0===this.size()?go([],[0].concat(n)):wi((()=>{const e=this.tensors.map((e=>Fu(e,n)));return Pu(e,0)}))}}function Jf(e,t,n){const[r,a]=nf("fusedOps",e,t,n),s="biasadd"===r,o=!s,i="prelu"===a,u="fusedbatchnorm"===r,l=nf("numArgs",e,t,n);if(s){if(i&&2!==l)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&s&&1!==l)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(u)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");const c=nf("strides",e,t,n),p=uf(e,t,n),h=nf("dataFormat",e,t,n).toUpperCase(),d=nf("dilations",e,t,n);let[f,m]=nf("args",e,t,n);return o&&(m=f,f=void 0),{stride:c,pad:p,dataFormat:h,dilations:d,biasArg:f,preluArg:m,activationFunc:a,leakyreluAlpha:nf("leakyreluAlpha",e,t,n)}}function Zf(e,t,n){return{boxes:nf("boxes",e,t,n),scores:nf("scores",e,t,n),maxOutputSize:nf("maxOutputSize",e,t,n),iouThreshold:nf("iouThreshold",e,t,n),scoreThreshold:nf("scoreThreshold",e,t,n),softNmsSigma:nf("softNmsSigma",e,t,n)}}class em{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=Ul(0),this.tensorMap=new Map,ki(this.handle)}get id(){return this.handle.id}clearAndClose(){this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Ul(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),wi((()=>{const e=th(t),r=n.length,a=e.length;Qe(r===a,(()=>`The number of elements doesn't match, keys has ${r} elements, the values has ${a} elements.`));for(let t=0;t<r;t++){const r=n[t],a=e[t];ki(a),this.tensorMap.set(r,a)}return this.handle}))}async find(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return wi((()=>{const e=[];for(let r=0;r<n.length;r++){const a=n[r],s=this.findWithDefault(a,t);e.push(s)}return Gp(e)}))}findWithDefault(e,t){const n=this.tensorMap.get(e);return null!=n?n:t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);if(t.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`)}}function tm(e,t,n,r,a=wi){const s=((e,t,n)=>{switch(e.category){case"arithmetic":return a((()=>((e,t,n,r=Gf)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[r.add(nf("a",e,t,n),nf("b",e,t,n))];case"AddN":return[r.addN(nf("tensors",e,t,n))];case"FloorMod":case"Mod":return[r.mod(nf("a",e,t,n),nf("b",e,t,n))];case"Mul":return[r.mul(nf("a",e,t,n),nf("b",e,t,n))];case"RealDiv":case"Div":return[r.div(nf("a",e,t,n),nf("b",e,t,n))];case"DivNoNan":return[r.divNoNan(nf("a",e,t,n),nf("b",e,t,n))];case"FloorDiv":return[r.floorDiv(nf("a",e,t,n),nf("b",e,t,n))];case"Sub":return[r.sub(nf("a",e,t,n),nf("b",e,t,n))];case"Minimum":return[r.minimum(nf("a",e,t,n),nf("b",e,t,n))];case"Maximum":return[r.maximum(nf("a",e,t,n),nf("b",e,t,n))];case"Pow":return[r.pow(nf("a",e,t,n),nf("b",e,t,n))];case"SquaredDifference":return[r.squaredDifference(nf("a",e,t,n),nf("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"basic_math":return a((()=>((e,t,n,r=Gf)=>{switch(e.op){case"Abs":case"ComplexAbs":return[r.abs(nf("x",e,t,n))];case"Acos":return[r.acos(nf("x",e,t,n))];case"Acosh":return[r.acosh(nf("x",e,t,n))];case"Asin":return[r.asin(nf("x",e,t,n))];case"Asinh":return[r.asinh(nf("x",e,t,n))];case"Atan":return[r.atan(nf("x",e,t,n))];case"Atan2":return[r.atan2(nf("x",e,t,n),nf("y",e,t,n))];case"Atanh":return[r.atanh(nf("x",e,t,n))];case"Ceil":return[r.ceil(nf("x",e,t,n))];case"Complex":return[r.complex(nf("real",e,t,n),nf("imag",e,t,n))];case"Cos":return[r.cos(nf("x",e,t,n))];case"Cosh":return[r.cosh(nf("x",e,t,n))];case"Elu":return[r.elu(nf("x",e,t,n))];case"Erf":return[r.erf(nf("x",e,t,n))];case"Exp":return[r.exp(nf("x",e,t,n))];case"Expm1":return[r.expm1(nf("x",e,t,n))];case"Floor":return[r.floor(nf("x",e,t,n))];case"Log":return[r.log(nf("x",e,t,n))];case"Log1p":return[r.log1p(nf("x",e,t,n))];case"Imag":return[r.imag(nf("x",e,t,n))];case"Neg":return[r.neg(nf("x",e,t,n))];case"Reciprocal":return[r.reciprocal(nf("x",e,t,n))];case"Real":return[r.real(nf("x",e,t,n))];case"Relu":return[r.relu(nf("x",e,t,n))];case"Round":return[r.round(nf("x",e,t,n))];case"Selu":return[r.selu(nf("x",e,t,n))];case"Sigmoid":return[r.sigmoid(nf("x",e,t,n))];case"Sin":return[r.sin(nf("x",e,t,n))];case"Sign":return[r.sign(nf("x",e,t,n))];case"Sinh":return[r.sinh(nf("x",e,t,n))];case"Softplus":return[r.softplus(nf("x",e,t,n))];case"Sqrt":return[r.sqrt(nf("x",e,t,n))];case"Square":return[r.square(nf("x",e,t,n))];case"Tanh":return[r.tanh(nf("x",e,t,n))];case"Tan":return[r.tan(nf("x",e,t,n))];case"ClipByValue":return[r.clipByValue(nf("x",e,t,n),nf("clipValueMin",e,t,n),nf("clipValueMax",e,t,n))];case"Relu6":return[r.relu6(nf("x",e,t,n))];case"Rsqrt":return[r.rsqrt(rf(e.inputNames[0],t,n))];case"Prod":return[r.prod(nf("x",e,t,n),nf("axes",e,t,n))];case"LeakyRelu":return[r.leakyRelu(nf("x",e,t,n),nf("alpha",e,t,n))];case"Prelu":return[r.prelu(nf("x",e,t,n),nf("alpha",e,t,n))];case"IsNan":return[r.isNaN(rf(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"control":return(async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const r=nf("thenBranch",e,t,n),a=nf("elseBranch",e,t,n),s=nf("cond",e,t,n),o=nf("args",e,t,n);return(await s.data())[0]?n.functionMap[r].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap):n.functionMap[a].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{const r=nf("body",e,t,n),a=nf("cond",e,t,n),s=nf("args",e,t,n),o=await n.functionMap[a].executeFunctionAsync(s,n.tensorArrayMap,n.tensorListMap),i=s.map((e=>e.id));let u=await o[0].data();o.forEach((e=>{e.kept||-1!==i.indexOf(e.id)||e.dispose()}));let l=s;for(;u[0];){const e=l;l=await n.functionMap[r].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);const t=l.map((e=>e.id));e.forEach((e=>{e.kept||-1!==i.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()}));const s=await n.functionMap[a].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);u=await s[0].data(),s.forEach((e=>{e.kept||-1!==i.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()}))}return l}case"LoopCond":return[lf(nf("pred",e,t,n))];case"Switch":{const r=nf("pred",e,t,n);let a=nf("data",e,t,n);return a.kept||(a=lf(a)),(await r.data())[0]?[void 0,a]:[a,void 0]}case"Merge":{const r=e.inputNames.find((e=>void 0!==rf(e,t,n)));return r?[lf(rf(r,t,n))]:void 0}case"Enter":{const r=nf("frameName",e,t,n),a=nf("tensor",e,t,n);return n.enterFrame(r),[lf(a)]}case"Exit":{const r=nf("tensor",e,t,n);return n.exitFrame(),[lf(r)]}case"NextIteration":{const r=nf("tensor",e,t,n);return n.nextIteration(),[lf(r)]}case"TensorArrayV3":{const r=nf("size",e,t,n),a=nf("dtype",e,t,n),s=nf("elementShape",e,t,n),o=nf("dynamicSize",e,t,n),i=nf("clearAfterRead",e,t,n),u=nf("identicalElementShapes",e,t,n),l=nf("name",e,t,n),c=new Yf(l,a,r,s,u,o,i);return n.addTensorArray(c),[c.idTensor,Ul(1)]}case"TensorArrayWriteV3":{const r=nf("tensorArrayId",e,t,n),a=nf("index",e,t,n),s=nf("tensor",e,t,n),o=n.getTensorArray(r.id);return o.write(a,s),[o.idTensor]}case"TensorArrayReadV3":{const r=nf("tensorArrayId",e,t,n),a=nf("index",e,t,n);return[n.getTensorArray(r.id).read(a)]}case"TensorArrayGatherV3":{const r=nf("tensorArrayId",e,t,n),a=nf("indices",e,t,n),s=nf("dtype",e,t,n);return[n.getTensorArray(r.id).gather(a,s)]}case"TensorArrayScatterV3":{const r=nf("tensorArrayId",e,t,n),a=nf("indices",e,t,n),s=nf("tensor",e,t,n),o=n.getTensorArray(r.id);return o.scatter(a,s),[o.idTensor]}case"TensorArrayConcatV3":{const r=nf("tensorArrayId",e,t,n),a=n.getTensorArray(r.id),s=nf("dtype",e,t,n);return[a.concat(s)]}case"TensorArraySplitV3":{const r=nf("tensorArrayId",e,t,n),a=nf("tensor",e,t,n),s=nf("lengths",e,t,n),o=n.getTensorArray(r.id);return o.split(s,a),[o.idTensor]}case"TensorArraySizeV3":{const r=nf("tensorArrayId",e,t,n);return[Ul(n.getTensorArray(r.id).size(),"int32")]}case"TensorArrayCloseV3":{const r=nf("tensorArrayId",e,t,n),a=n.getTensorArray(r.id);return a.clearAndClose(),[a.idTensor]}case"TensorListSetItem":{const r=nf("tensorListId",e,t,n),a=nf("index",e,t,n),s=nf("tensor",e,t,n),o=n.getTensorList(r.id);return o.setItem(a,s),[o.idTensor]}case"TensorListGetItem":{const r=nf("tensorListId",e,t,n),a=nf("index",e,t,n),s=nf("elementShape",e,t,n),o=nf("elementDType",e,t,n);return[n.getTensorList(r.id).getItem(a,s,o)]}case"TensorListScatterV2":case"TensorListScatter":{const r=nf("indices",e,t,n),a=function(e,t,n,r){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);const a=Math.max(...t);if(null!=r&&-1!==r&&a>=r)throw new Error(`Max index must be < array size (${a} vs. ${r})`);const s=new Qf([],n,e.dtype,r),o=th(e,0);return t.forEach(((e,t)=>{s.setItem(e,o[t])})),s}(nf("tensor",e,t,n),r,nf("elementShape",e,t,n),nf("numElements",e,t,n));return n.addTensorList(a),[a.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const r=nf("elementShape",e,t,n),a=nf("elementDType",e,t,n);let s;s="TensorListReserve"===e.op?"numElements":"maxNumElements";const o=nf(s,e,t,n),i=function(e,t,n,r){return new Qf([],e,t,r)}(r,a,0,"TensorListReserve"===e.op?-1:o);return n.addTensorList(i),[i.idTensor]}case"TensorListGather":{const r=nf("tensorListId",e,t,n),a=nf("indices",e,t,n),s=nf("elementShape",e,t,n),o=nf("elementDType",e,t,n);return[n.getTensorList(r.id).gather(a,o,s)]}case"TensorListStack":{const r=nf("tensorListId",e,t,n),a=nf("elementShape",e,t,n),s=nf("elementDType",e,t,n),o=nf("numElements",e,t,n);return[n.getTensorList(r.id).stack(a,s,o)]}case"TensorListFromTensor":{const r=function(e,t,n){const r=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);jf(e.shape.slice(1),t,"TensorList shape mismatch: ");const a=th(e);return new Qf(a,t,r)}(nf("tensor",e,t,n),nf("elementShape",e,t,n),nf("elementDType",e,t,n));return n.addTensorList(r),[r.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const r=nf("tensorListId",e,t,n),a=n.getTensorList(r.id),s=nf("dtype",e,t,n),o=nf("elementShape",e,t,n);return[a.concat(s,o)]}case"TensorListPushBack":{const r=nf("tensorListId",e,t,n),a=nf("tensor",e,t,n),s=n.getTensorList(r.id);return s.pushBack(a),[s.idTensor]}case"TensorListPopBack":{const r=nf("tensorListId",e,t,n),a=nf("elementShape",e,t,n),s=nf("elementDType",e,t,n);return[n.getTensorList(r.id).popBack(a,s)]}case"TensorListSplit":{const r=nf("tensor",e,t,n),a=nf("elementShape",e,t,n),s=function(e,t,n){let r=0;const a=t.map((e=>(r+=e,r)));if(r!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${r}, and tensor's shape is: ${e.shape}`);const s=Xf(e.shape.slice(1),n),o=0===r?0:e.size/r,i=wi((()=>{const n=[];e=Fu(e,[1,r,o]);for(let r=0;r<t.length;++r){const i=[0,0===r?0:a[r-1],0],u=[1,t[r],o];n[r]=Fu(Uu(e,i,u),s)}return e.dispose(),n})),u=new Qf([],n,e.dtype,t.length);for(let e=0;e<i.length;e++)u.setItem(e,i[e]);return u}(r,nf("lengths",e,t,n),a);return n.addTensorList(s),[s.idTensor]}case"TensorListLength":{const r=nf("tensorListId",e,t,n);return[Ul(n.getTensorList(r.id).size(),"int32")]}case"TensorListResize":{const r=nf("tensorListId",e,t,n),a=nf("size",e,t,n),s=n.getTensorList(r.id).resize(a);return n.addTensorList(s),[s.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n);case"convolution":return a((()=>((e,t,n,r=Gf)=>{switch(e.op){case"Conv1D":{const a=nf("stride",e,t,n),s=nf("pad",e,t,n),o=nf("dataFormat",e,t,n).toUpperCase(),i=nf("dilation",e,t,n);return[r.conv1d(nf("x",e,t,n),nf("filter",e,t,n),a,s,o,i)]}case"Conv2D":{const a=nf("strides",e,t,n),s=uf(e,t,n),o=nf("dataFormat",e,t,n).toUpperCase(),i=nf("dilations",e,t,n);return[r.conv2d(nf("x",e,t,n),nf("filter",e,t,n),[a[1],a[2]],s,o,[i[1],i[2]])]}case"_FusedConv2D":{const{stride:a,pad:s,dataFormat:o,dilations:i,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:p}=Jf(e,t,n);return[r.fused.conv2d({x:nf("x",e,t,n),filter:nf("filter",e,t,n),strides:[a[1],a[2]],pad:s,dataFormat:o,dilations:[i[1],i[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:p})]}case"FusedDepthwiseConv2dNative":{const{stride:a,pad:s,dataFormat:o,dilations:i,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:p}=Jf(e,t,n);return[r.fused.depthwiseConv2d({x:nf("x",e,t,n),filter:nf("filter",e,t,n),strides:[a[1],a[2]],pad:s,dataFormat:o,dilations:[i[1],i[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:p})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const a=nf("outputShape",e,t,n),s=nf("strides",e,t,n),o=uf(e,t,n);return[r.conv2dTranspose(nf("x",e,t,n),nf("filter",e,t,n),a,[s[1],s[2]],o)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const a=nf("strides",e,t,n),s=uf(e,t,n),o=nf("dilations",e,t,n),i=nf("dataFormat",e,t,n).toUpperCase();return[r.depthwiseConv2d(nf("input",e,t,n),nf("filter",e,t,n),[a[1],a[2]],s,i,[o[1],o[2]])]}case"Conv3D":{const a=nf("strides",e,t,n),s=nf("pad",e,t,n),o=nf("dataFormat",e,t,n).toUpperCase(),i=nf("dilations",e,t,n);return[r.conv3d(nf("x",e,t,n),nf("filter",e,t,n),[a[1],a[2],a[3]],s,o,[i[1],i[2],i[3]])]}case"AvgPool":{const a=nf("strides",e,t,n),s=nf("pad",e,t,n),o=nf("kernelSize",e,t,n);return[r.avgPool(nf("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s)]}case"MaxPool":{const a=nf("strides",e,t,n),s=nf("pad",e,t,n),o=nf("kernelSize",e,t,n);return[r.maxPool(nf("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s)]}case"MaxPoolWithArgmax":{const a=nf("strides",e,t,n),s=nf("pad",e,t,n),o=nf("kernelSize",e,t,n),i=nf("includeBatchInIndex",e,t,n),{result:u,indexes:l}=r.maxPoolWithArgmax(nf("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s,i);return[u,l]}case"AvgPool3D":{const a=nf("strides",e,t,n),s=nf("pad",e,t,n),o=nf("kernelSize",e,t,n);return[r.avgPool3d(nf("x",e,t,n),[o[1],o[2],o[3]],[a[1],a[2],a[3]],s)]}case"MaxPool3D":{const a=nf("strides",e,t,n),s=nf("pad",e,t,n),o=nf("kernelSize",e,t,n);return[r.maxPool3d(nf("x",e,t,n),[o[1],o[2],o[3]],[a[1],a[2],a[3]],s)]}case"Dilation2D":{const a=nf("strides",e,t,n),s=nf("pad",e,t,n),o=nf("dilations",e,t,n),i=a[1],u=a[2],l=o[1],c=o[2];return[r.dilation2d(nf("x",e,t,n),nf("filter",e,t,n),[i,u],s,[l,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"creation":return a((()=>((e,t,n,r=Gf)=>{switch(e.op){case"Fill":{const a=nf("shape",e,t,n),s=nf("dtype",e,t,n),o=nf("value",e,t,n);return[r.fill(a,o,s)]}case"LinSpace":{const a=nf("start",e,t,n),s=nf("stop",e,t,n),o=nf("num",e,t,n);return[r.linspace(a,s,o)]}case"Multinomial":{const a=nf("logits",e,t,n),s=nf("numSamples",e,t,n),o=nf("seed",e,t,n);return[r.multinomial(a,s,o)]}case"OneHot":{const a=nf("indices",e,t,n),s=nf("depth",e,t,n),o=nf("onValue",e,t,n),i=nf("offValue",e,t,n),u=nf("dtype",e,t,n);return[r.oneHot(a,s,o,i,u)]}case"Ones":return[r.ones(nf("shape",e,t,n),nf("dtype",e,t,n))];case"OnesLike":return[r.onesLike(nf("x",e,t,n))];case"RandomStandardNormal":return[r.randomStandardNormal(nf("shape",e,t,n),nf("dtype",e,t,n),nf("seed",e,t,n))];case"RandomUniform":return[r.randomUniform(nf("shape",e,t,n),nf("minval",e,t,n),nf("maxval",e,t,n),nf("dtype",e,t,n))];case"Range":{const a=nf("start",e,t,n),s=nf("stop",e,t,n),o=nf("step",e,t,n);return[r.range(a,s,o,nf("dtype",e,t,n))]}case"TruncatedNormal":{const a=nf("shape",e,t,n),s=nf("mean",e,t,n),o=nf("stdDev",e,t,n),i=nf("seed",e,t,n);return[r.truncatedNormal(a,s,o,nf("dtype",e,t,n),i)]}case"Zeros":return[r.zeros(nf("shape",e,t,n),nf("dtype",e,t,n))];case"ZerosLike":return[r.zerosLike(nf("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"dynamic":return(async(e,t,n,r,a=Gf)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u,softNmsSigma:l}=Zf(e,t,n),c=await a.image.nonMaxSuppressionWithScoreAsync(r,s,o,i,u,l);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u}=Zf(e,t,n),l=nf("padToMaxOutputSize",e,t,n),c=await a.image.nonMaxSuppressionPaddedAsync(r,s,o,i,u,l);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u}=Zf(e,t,n);return[await a.image.nonMaxSuppressionAsync(r,s,o,i,u)]}case"Where":{const r=a.cast(nf("condition",e,t,n),"bool"),s=[await a.whereAsync(r)];return r.dispose(),s}case"ListDiff":return a.setdiff1dAsync(nf("x",e,t,n),nf("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n);case"evaluation":return a((()=>((e,t,n,r=Gf)=>{switch(e.op){case"LowerBound":{const a=nf("sortedSequence",e,t,n),s=nf("values",e,t,n);return[r.lowerBound(a,s)]}case"TopKV2":{const a=nf("x",e,t,n),s=nf("k",e,t,n),o=nf("sorted",e,t,n),i=r.topk(a,s,o);return[i.values,i.indices]}case"UpperBound":{const a=nf("sortedSequence",e,t,n),s=nf("values",e,t,n);return[r.upperBound(a,s)]}case"Unique":{const a=nf("x",e,t,n),s=r.unique(a);return[s.values,s.indices]}case"UniqueV2":{const a=nf("x",e,t,n),s=nf("axis",e,t,n),o=r.unique(a,s);return[o.values,o.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"image":return a((()=>((e,t,n,r=Gf)=>{switch(e.op){case"ResizeBilinear":{const a=nf("images",e,t,n),s=nf("size",e,t,n),o=nf("alignCorners",e,t,n),i=nf("halfPixelCenters",e,t,n);return[r.image.resizeBilinear(a,[s[0],s[1]],o,i)]}case"ResizeNearestNeighbor":{const a=nf("images",e,t,n),s=nf("size",e,t,n),o=nf("alignCorners",e,t,n),i=nf("halfPixelCenters",e,t,n);return[r.image.resizeNearestNeighbor(a,[s[0],s[1]],o,i)]}case"CropAndResize":{const a=nf("image",e,t,n),s=nf("boxes",e,t,n),o=nf("boxInd",e,t,n),i=nf("cropSize",e,t,n),u=nf("method",e,t,n),l=nf("extrapolationValue",e,t,n);return[r.image.cropAndResize(a,s,o,i,u,l)]}case"ImageProjectiveTransformV3":{const a=nf("images",e,t,n),s=nf("transforms",e,t,n),o=nf("outputShape",e,t,n),i=nf("fillValue",e,t,n),u=nf("interpolation",e,t,n),l=nf("fillMode",e,t,n);return[r.image.transform(a,s,u.toLowerCase(),l.toLowerCase(),i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"graph":return a((()=>((e,t,n,r=Gf)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const a=nf("default",e,t,n);return[rf(e.name,t,n)||a];case"Placeholder":return[rf(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":case"Snapshot":return[lf(nf("x",e,t,n))];case"IdentityN":return nf("x",e,t,n).map((e=>lf(e)));case"Shape":return[r.tensor1d(nf("x",e,t,n).shape,"int32")];case"ShapeN":return nf("x",e,t,n).map((e=>r.tensor1d(e.shape)));case"Size":return[r.scalar(nf("x",e,t,n).size,"int32")];case"Rank":return[r.scalar(nf("x",e,t,n).rank,"int32")];case"NoOp":return[r.scalar(1)];case"Print":const s=nf("x",e,t,n),o=nf("data",e,t,n),i=nf("message",e,t,n),u=nf("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(i);for(let e=0;e<o.length;e++)console.log(Array.prototype.slice.call(o[e].dataSync()).slice(0,u));return[s];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"logical":return a((()=>((e,t,n,r=Gf)=>{switch(e.op){case"Equal":return[r.equal(nf("a",e,t,n),nf("b",e,t,n))];case"NotEqual":return[r.notEqual(nf("a",e,t,n),nf("b",e,t,n))];case"Greater":return[r.greater(nf("a",e,t,n),nf("b",e,t,n))];case"GreaterEqual":return[r.greaterEqual(nf("a",e,t,n),nf("b",e,t,n))];case"Less":return[r.less(nf("a",e,t,n),nf("b",e,t,n))];case"LessEqual":return[r.lessEqual(nf("a",e,t,n),nf("b",e,t,n))];case"LogicalAnd":return[r.logicalAnd(nf("a",e,t,n),nf("b",e,t,n))];case"LogicalNot":return[r.logicalNot(nf("a",e,t,n))];case"LogicalOr":return[r.logicalOr(nf("a",e,t,n),nf("b",e,t,n))];case"Select":case"SelectV2":return[r.where(nf("condition",e,t,n),nf("a",e,t,n),nf("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"matrices":return a((()=>((e,t,n,r=Gf)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[r.matMul(nf("a",e,t,n),nf("b",e,t,n),nf("transposeA",e,t,n),nf("transposeB",e,t,n))];case"Einsum":return[r.einsum(nf("equation",e,t,n),...nf("tensors",e,t,n))];case"Transpose":return[r.transpose(nf("x",e,t,n),nf("perm",e,t,n))];case"_FusedMatMul":const[a,s]=nf("fusedOps",e,t,n),o="biasadd"===a,i="prelu"===s,u=nf("numArgs",e,t,n),l=nf("leakyreluAlpha",e,t,n);if(o){if(i&&2!==u)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&1!==u)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[c,p]=nf("args",e,t,n);return[r.fused.matMul({a:nf("a",e,t,n),b:nf("b",e,t,n),transposeA:nf("transposeA",e,t,n),transposeB:nf("transposeB",e,t,n),bias:c,activation:s,preluActivationWeights:p,leakyreluAlpha:l})];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"normalization":return a((()=>((e,t,n,r=Gf)=>{switch(e.op){case"EuclideanNorm":return[r.euclideanNorm(nf("x",e,t,n),nf("axis",e,t,n),nf("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[r.batchNorm(nf("x",e,t,n),nf("mean",e,t,n),nf("variance",e,t,n),nf("offset",e,t,n),nf("scale",e,t,n),nf("epsilon",e,t,n))];case"LRN":return[r.localResponseNormalization(nf("x",e,t,n),nf("radius",e,t,n),nf("bias",e,t,n),nf("alpha",e,t,n),nf("beta",e,t,n))];case"Softmax":return[r.softmax(nf("x",e,t,n))];case"LogSoftmax":return[r.logSoftmax(nf("x",e,t,n))];case"SparseToDense":return[r.sparseToDense(nf("sparseIndices",e,t,n),nf("outputShape",e,t,n),nf("sparseValues",e,t,n),nf("defaultValue",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"ragged":return a((()=>((e,t,n,r=Gf)=>{switch(e.op){case"RaggedGather":{const{outputNestedSplits:a,outputDenseValues:s}=r.raggedGather(nf("paramsNestedSplits",e,t,n),nf("paramsDenseValues",e,t,n),nf("indices",e,t,n),nf("outputRaggedRank",e,t,n));return a.concat(s)}case"RaggedRange":{const{rtNestedSplits:a,rtDenseValues:s}=r.raggedRange(nf("starts",e,t,n),nf("limits",e,t,n),nf("splits",e,t,n));return[a,s]}case"RaggedTensorToTensor":return[r.raggedTensorToTensor(nf("shape",e,t,n),nf("values",e,t,n),nf("defaultValue",e,t,n),nf("rowPartitionTensors",e,t,n),nf("rowPartitionTypes",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"reduction":return a((()=>((e,t,n,r=Gf)=>{switch(e.op){case"Max":{const a=nf("axis",e,t,n),s=nf("keepDims",e,t,n);return[r.max(nf("x",e,t,n),a,s)]}case"Mean":{const a=nf("axis",e,t,n),s=nf("keepDims",e,t,n);return[r.mean(nf("x",e,t,n),a,s)]}case"Min":{const a=nf("axis",e,t,n),s=nf("keepDims",e,t,n);return[r.min(nf("x",e,t,n),a,s)]}case"Sum":{const a=nf("axis",e,t,n),s=nf("keepDims",e,t,n);return[r.sum(nf("x",e,t,n),a,s)]}case"All":{const a=nf("axis",e,t,n),s=nf("keepDims",e,t,n);return[r.all(nf("x",e,t,n),a,s)]}case"Any":{const a=nf("axis",e,t,n),s=nf("keepDims",e,t,n);return[r.any(nf("x",e,t,n),a,s)]}case"ArgMax":{const a=nf("axis",e,t,n);return[r.argMax(nf("x",e,t,n),a)]}case"ArgMin":{const a=nf("axis",e,t,n);return[r.argMin(nf("x",e,t,n),a)]}case"Prod":{const a=nf("axis",e,t,n),s=nf("keepDims",e,t,n);return[r.prod(nf("x",e,t,n),a,s)]}case"Cumprod":{const a=nf("axis",e,t,n),s=nf("exclusive",e,t,n),o=nf("reverse",e,t,n);return[r.cumprod(nf("x",e,t,n),a,s,o)]}case"Cumsum":{const a=nf("axis",e,t,n),s=nf("exclusive",e,t,n),o=nf("reverse",e,t,n);return[r.cumsum(nf("x",e,t,n),a,s,o)]}case"Bincount":const a=nf("x",e,t,n),s=nf("weights",e,t,n),o=nf("size",e,t,n);return[r.bincount(a,s,o)];case"DenseBincount":{const a=nf("x",e,t,n),s=nf("weights",e,t,n),o=nf("size",e,t,n),i=nf("binaryOutput",e,t,n);return[r.denseBincount(a,s,o,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"slice_join":return a((()=>((e,t,n,r=Gf)=>{switch(e.op){case"ConcatV2":case"Concat":{const a=nf("n",e,t,n),s=nf("axis",e,t,n);let o=nf("tensors",e,t,n);return o=o.slice(0,a),[r.concat(o,s)]}case"Gather":{const a=nf("x",e,t,n),s=nf("indices",e,t,n);return[r.gather(a,r.cast(s,"int32"),0)]}case"GatherV2":{const a=nf("axis",e,t,n),s=nf("batchDims",e,t,n),o=nf("x",e,t,n),i=nf("indices",e,t,n);return[r.gather(o,r.cast(i,"int32"),a,s)]}case"Reverse":{const a=nf("dims",e,t,n),s=[];for(let e=0;e<a.length;e++)a[e]&&s.push(e);const o=nf("x",e,t,n);return[r.reverse(o,s)]}case"ReverseV2":{const a=nf("axis",e,t,n),s=nf("x",e,t,n);return[r.reverse(s,a)]}case"Slice":{const a=nf("begin",e,t,n),s=nf("size",e,t,n);return[r.slice(nf("x",e,t,n),a,s)]}case"StridedSlice":{const a=nf("begin",e,t,n),s=nf("end",e,t,n),o=nf("strides",e,t,n),i=nf("beginMask",e,t,n),u=nf("endMask",e,t,n),l=nf("ellipsisMask",e,t,n),c=nf("newAxisMask",e,t,n),p=nf("shrinkAxisMask",e,t,n),h=nf("x",e,t,n);return[r.stridedSlice(h,a,s,o,i,u,l,c,p)]}case"Pack":return wi((()=>{const a=nf("axis",e,t,n),s=nf("tensors",e,t,n),o=s[0].shape,i=r.squeeze(s[0]).shape,u=s.map((e=>{const t=tt(e.shape,o);if(!t&&!tt(r.squeeze(e).shape,i))throw new Error("the input tensors shape does not match");return t?e:r.reshape(e,o)}));return[r.stack(u,a)]}));case"Unpack":{const a=nf("axis",e,t,n),s=nf("tensor",e,t,n);return r.unstack(s,a)}case"Tile":{const a=nf("reps",e,t,n);return[r.tile(nf("x",e,t,n),a)]}case"Split":case"SplitV":{const a=nf("axis",e,t,n),s=nf("numOrSizeSplits",e,t,n),o=nf("x",e,t,n);return r.split(o,s,a)}case"ScatterNd":{const a=nf("indices",e,t,n),s=nf("values",e,t,n),o=nf("shape",e,t,n);return[r.scatterND(a,s,o)]}case"GatherNd":{const a=nf("x",e,t,n),s=nf("indices",e,t,n);return[r.gatherND(a,s)]}case"SparseToDense":{const a=nf("sparseIndices",e,t,n),s=nf("outputShape",e,t,n),o=nf("sparseValues",e,t,n),i=nf("defaultValue",e,t,n);return[r.sparseToDense(a,o,s,o.dtype===i.dtype?i:r.cast(i,o.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"sparse":return a((()=>((e,t,n,r=Gf)=>{switch(e.op){case"SparseFillEmptyRows":{const{outputIndices:a,outputValues:s,emptyRowIndicator:o,reverseIndexMap:i}=r.sparse.sparseFillEmptyRows(nf("indices",e,t,n),nf("values",e,t,n),nf("denseShape",e,t,n),nf("defaultValue",e,t,n));return[a,s,o,i]}case"SparseReshape":{const{outputIndices:a,outputShape:s}=r.sparse.sparseReshape(nf("inputIndices",e,t,n),nf("inputShape",e,t,n),nf("newShape",e,t,n));return[a,s]}case"SparseSegmentMean":return[r.sparse.sparseSegmentMean(nf("data",e,t,n),nf("indices",e,t,n),nf("segmentIds",e,t,n))];case"SparseSegmentSum":return[r.sparse.sparseSegmentSum(nf("data",e,t,n),nf("indices",e,t,n),nf("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"spectral":return a((()=>((e,t,n,r=Gf)=>{switch(e.op){case"FFT":return[r.fft(nf("x",e,t,n))];case"IFFT":return[r.ifft(nf("x",e,t,n))];case"RFFT":return[r.rfft(nf("x",e,t,n))];case"IRFFT":return[r.irfft(nf("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"string":return a((()=>((e,t,n,r=Gf)=>{switch(e.op){case"StringNGrams":{const{nGrams:a,nGramsSplits:s}=r.string.stringNGrams(nf("data",e,t,n),nf("dataSplits",e,t,n),nf("separator",e,t,n),nf("nGramWidths",e,t,n),nf("leftPad",e,t,n),nf("rightPad",e,t,n),nf("padWidth",e,t,n),nf("preserveShortSequences",e,t,n));return[a,s]}case"StringSplit":{const{indices:a,values:s,shape:o}=r.string.stringSplit(nf("input",e,t,n),nf("delimiter",e,t,n),nf("skipEmpty",e,t,n));return[a,s,o]}case"StringToHashBucketFast":return[r.string.stringToHashBucketFast(nf("input",e,t,n),nf("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"transformation":return a((()=>((e,t,n,r=Gf)=>{switch(e.op){case"Cast":return[r.cast(nf("x",e,t,n),nf("dtype",e,t,n))];case"ExpandDims":{const a=nf("axis",e,t,n);return[r.expandDims(nf("x",e,t,n),a)]}case"Squeeze":{const a=nf("axis",e,t,n);return[r.squeeze(nf("x",e,t,n),a)]}case"Reshape":return[r.reshape(nf("x",e,t,n),nf("shape",e,t,n))];case"MirrorPad":return[r.mirrorPad(nf("x",e,t,n),nf("padding",e,t,n),nf("mode",e,t,n))];case"PadV2":case"Pad":return[r.pad(nf("x",e,t,n),nf("padding",e,t,n),nf("constantValue",e,t,n))];case"SpaceToBatchND":{const a=nf("blockShape",e,t,n),s=nf("paddings",e,t,n);return[r.spaceToBatchND(nf("x",e,t,n),a,s)]}case"BatchToSpaceND":{const a=nf("blockShape",e,t,n),s=nf("crops",e,t,n);return[r.batchToSpaceND(nf("x",e,t,n),a,s)]}case"DepthToSpace":{const a=nf("blockSize",e,t,n),s=nf("dataFormat",e,t,n).toUpperCase();return[r.depthToSpace(nf("x",e,t,n),a,s)]}case"BroadcastTo":return[r.broadcastTo(nf("x",e,t,n),nf("shape",e,t,n))];case"BroadcastArgs":return[r.broadcastArgs(nf("s0",e,t,n),nf("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"hash_table":return(async(e,t,n,r)=>{switch(e.op){case"HashTable":case"HashTableV2":{const a=r.getHashTableHandleByName(e.name);if(null!=a)return[a];{const a=nf("keyDType",e,t,n),s=nf("valueDType",e,t,n),o=new em(a,s);return r.addHashTable(e.name,o),[o.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{const a=nf("tableHandle",e,t,n,r),s=nf("keys",e,t,n),o=nf("values",e,t,n),i=r.getHashTableById(a.id);return[await i.import(s,o)]}case"LookupTableFind":case"LookupTableFindV2":{const a=nf("tableHandle",e,t,n,r),s=nf("keys",e,t,n),o=nf("defaultValue",e,t,n),i=r.getHashTableById(a.id);return[await i.find(s,o)]}case"LookupTableSize":case"LookupTableSizeV2":{const a=nf("tableHandle",e,t,n,r);return[r.getHashTableById(a.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n,r);case"custom":const s=tf(e.op);if(s&&s.customExecutor)return s.customExecutor(new Hf(e,t,n));throw TypeError(`Custom op ${e.op} is not registered.`);default:throw TypeError(`Unknown op '${e.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return It(s)?s.then((e=>[].concat(e))):[].concat(s)}class nm{constructor(e={},t={},n={},r={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=r,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){const e=[];for(let t=0;t<this.contexts.length-1;t++){const n=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(n))}e.push(""),this._currentContextIds=e}contextIdforContexts(e){return e?e.map((e=>0===e.id&&0===e.iterationId?"":`${e.frameName}-${e.iterationId}`)).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(!(this.contexts&&this.contexts.length>1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()}nextIteration(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");{this.contexts=this.contexts.slice(),this.lastId++;const e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(const t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(const t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}}function rm(e,t,n,r){const a=new Set,s=[];let o=null,i=null;const u=new Set,l=Object.keys(e).map((e=>of(e)[0]));let c=[];null!=r&&(c=r.map((e=>of(e.name)[0])));const p=[...t];for(;p.length>0;){const e=p.pop();(im(e)||um(e)||lm(e))&&null==o&&(o=e,i=o.children.map((e=>e.name)).filter((e=>a.has(e)))),a.add(e.name),null==n[e.name]&&-1===l.indexOf(e.name)&&-1===c.indexOf(e.name)&&(0!==e.inputs.length?e.inputs.forEach((e=>{u.has(e.name)||(u.add(e.name),p.push(e))})):s.push(e.name))}return{inputs:e,outputs:t,usedNodes:a,missingInputs:s,dynamicNode:o,syncInputs:i}}const am=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],sm=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],om=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function im(e){return am.indexOf(e.op)>=0}function um(e){return sm.indexOf(e.op)>=0}function lm(e){return om.indexOf(e.op)>=0}class cm{constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._functions={},this._functionExecutorMap={},this.keepIntermediateTensors=!1,this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,null!=e.functions&&Object.keys(e.functions).forEach((t=>{this._functionExecutorMap[t]=new cm(e.functions[t],this)}))}get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){const t=Object.keys(e).map((t=>e[t].map((e=>e.id))));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map((e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0})))}get outputs(){return this._outputs.map((e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0})))}get inputNodes(){return this._inputs.map((e=>e.signatureKey||e.name))}get outputNodes(){return this._outputs.map((e=>{const t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t}))}get functions(){return Object.keys(this._functions).reduce(((e,t)=>(e[t]=this._functions[t].signature,e)),{})}getCompilationKey(e,t){const n=e.map((e=>e.name)).sort(),r=t.map((e=>e.name)).sort();return n.join(this.SEPERATOR)+"--"+r.join(this.SEPERATOR)}compile(e,t){const n=rm(e,t,this.weightMap,this._initNodes),{missingInputs:r,dynamicNode:a,syncInputs:s}=n;if(null!=a)throw new Error(`This execution contains the node '${a.name}', which has the dynamic op '${a.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${s}]`);if(r.length>0){const n=t.map((e=>e.name)),a=Object.keys(e);throw new Error(`Cannot compute the outputs [${n}] from the provided inputs [${a}]. Missing the following inputs: [${r}]`)}return function(e,t,n){const{usedNodes:r,inputs:a}=n,s=[],o=Object.keys(a).map((e=>of(e)[0])).map((t=>e.nodes[t])),i=e.initNodes;o.forEach((e=>{r.has(e.name)&&s.push(e)})),e.weights.forEach((e=>{r.has(e.name)&&s.push(e)})),null!=i&&i.forEach((e=>{r.has(e.name)&&s.push(e)}));const u=new Set,l=[];for(;s.length>0;){const e=s.pop();u.add(e.name),t[e.name]||l.push(e),e.children.forEach((e=>{!u.has(e.name)&&r.has(e.name)&&e.inputs.every((e=>u.has(e.name)))&&s.push(e)}))}return l}(this.graph,this.weightMap,n)}cloneAndKeepTensor(e){if(null==e)return null;const t=e.clone();return ki(t),t}cloneTensorList(e){return e?e.map((e=>this.cloneAndKeepTensor(e))):null}cloneTensorMap(e){return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,this.cloneTensorList(t)])))}execute(e,t){this.disposeIntermediateTensors(),e=this.mapInputs(e);const n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);const r=n.map((e=>this.graph.nodes[of(e)[0]])),a=t.map((e=>of(e)[0]));let s=a.map((e=>this.graph.nodes[e]));0===s.length&&(s=this._outputs);const o=this.getCompilationKey(r,s);let i=this.compiledMap.get(o);null==i&&(i=this.compile(e,s),this.compiledMap.set(o,i));try{this.keepIntermediateTensors=Ct().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const u={},l={};return wi((()=>{const n=new nm(this.weightMap,u,l,this.functionExecutorMap),r=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(e).forEach((t=>{const[n,a]=of(t),s=[];s[a]=e[t],r[n]=s,this.keepIntermediateTensors&&(this.clonedTensorsMap[n]=this.cloneTensorList(s))}));const s=this.getFrozenTensorIds(r),o={};for(let e=0;e<i.length;e++){const t=i[e];if(!r[t.name]){const e=tm(t,r,n,this._resourceManager);if(It(e))throw new Error(`The execution of the op '${t.op}' returned a promise. Please use model.executeAsync() instead.`);r[t.name]=e,this.keepIntermediateTensors&&(this.clonedTensorsMap[t.name]=this.cloneTensorList(e)),this.checkTensorForDisposal(t.name,t,r,n,s,a,o)}}return null==this.parent&&n.dispose(s),t.map((e=>rf(e,r,n)))}))}getFrozenTensorIds(e){const t=[].concat.apply([],Object.keys(e).map((t=>e[t])).map((e=>e.map((e=>e.id)))));return new Set(t)}checkTensorForDisposal(e,t,n,r,a,s,o){"control"!==t.category&&-1===s.indexOf(e)&&(n[e].forEach((e=>{null!=e&&(o[e.id]=(o[e.id]||0)+t.children.length)})),t.inputs.forEach((e=>{if("control"!==e.category){const t=function(e,t,n){return t[sf(e,n.currentContextId)]}(e.name,n,r);null!=t&&t.forEach((e=>{if(e&&!e.kept&&!a.has(e.id)){const t=o[e.id];1===t?(e.dispose(),delete o[e.id]):null!=t&&o[e.id]--}}))}})))}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){this.clonedTensorsMap&&(Object.values(this.clonedTensorsMap).forEach((e=>{for(const t of e)t&&!t.isDisposed&&t.dispose()})),this.clonedTensorsMap=null)}getIntermediateTensors(){return this.clonedTensorsMap}async _executeAsync(e,t,n=!1,r={},a={}){this.disposeIntermediateTensors(),n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepIntermediateTensors=Ct().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const s=new nm(this.weightMap,r,a,this.functionExecutorMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));const o=await this.executeWithControlFlow(e,s,t,n),i=t.map((e=>rf(e,o,s))),u=i.map((e=>e.id)),l=Object.keys(e).map((t=>e[t].id)),c=new Set([...u,...l,...this.weightIds]);return Object.values(o).forEach((e=>{e.forEach((e=>{!e||e.isDisposed||c.has(e.id)||e.dispose()}))})),null==this.parent&&s.dispose(c),i}async executeFunctionAsync(e,t,n){const r=e.reduce(((e,t,n)=>(e[this.inputs[n].name]=t,e)),{});return this._executeAsync(r,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,r){const a=Object.keys(e),s=a.map((e=>this.graph.nodes[of(e)[0]])),o=n.map((e=>of(e)[0]));let i=o.map((e=>this.graph.nodes[e]));0===i.length&&(i=this._outputs);const{usedNodes:u,missingInputs:l,dynamicNode:c,syncInputs:p}=rm(e,i,this.weightMap,this._initNodes),h=[...s,...this.graph.weights,...this._initNodes||[]].map((e=>({node:e,contexts:t.currentContext}))),d=Object.assign({},this.weightMap);Object.keys(e).forEach((t=>{const[n,r]=of(t),a=[];a[r]=e[t],d[n]=a}));const f={},m=this.getFrozenTensorIds(d),g={};for(;h.length>0;){const e=this.processStack(s,h,t,d,g,m,o,f,u);await Promise.all(e)}null!=c||r||console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");const y=i.filter((e=>!im(e)&&!rf(e.name,d,t))).map((e=>e.name));if(y.length>0){let e="";throw null!=c&&(e=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${p}]`),new Error(`Cannot compute the outputs [${y}] from the provided inputs [${a}]. Consider providing the following inputs: [${l}]. ${e}`)}return d}processStack(e,t,n,r,a,s,o,i,u){const l=[];for(;t.length>0;){const e=t.pop();n.currentContext=e.contexts;let c="";if("Enter"===e.node.op&&nf("isConstant",e.node,r,n)&&([c]=af(e.node.name,n)),null==r[e.node.name]){const p=tm(e.node,r,n,this._resourceManager);c||([c]=af(e.node.name,n));const h=n.currentContext;It(p)?l.push(p.then((l=>(r[c]=l,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(l)),n.currentContext=h,this.checkTensorForDisposal(c,e.node,r,n,s,o,i),this.processChildNodes(e.node,t,n,r,a,u),l)))):(r[c]=p,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(p)),this.checkTensorForDisposal(c,e.node,r,n,s,o,i),this.processChildNodes(e.node,t,n,r,a,u))}else this.processChildNodes(e.node,t,n,r,a,u)}return l}processChildNodes(e,t,n,r,a,s){e.children.forEach((e=>{const[o]=af(e.name,n);!a[o]&&s.has(e.name)&&("Merge"===e.op?e.inputNames.some((e=>!!rf(e,r,n)))&&(a[o]=!0,t.push({contexts:n.currentContext,node:e})):e.inputNames.every((e=>!!rf(e,r,n)))&&(a[o]=!0,t.push({contexts:n.currentContext,node:e})))}))}dispose(){Object.keys(this.weightMap).forEach((e=>this.weightMap[e].forEach((e=>e.dispose()))))}checkInputShapeAndType(e){Object.keys(e).forEach((t=>{const n=e[t],[r]=of(t),a=this.graph.nodes[r];if(a.attrParams.shape&&a.attrParams.shape.value){const e=a.attrParams.shape.value;Qe(e.length===n.shape.length&&n.shape.every(((t,n)=>-1===e[n]||e[n]===t)),(()=>`The shape of dict['${a.name}'] provided in model.execute(dict) must be [${e}], but was [${n.shape}]`))}a.attrParams.dtype&&a.attrParams.dtype.value&&Qe(n.dtype===a.attrParams.dtype.value,(()=>`The dtype of dict['${a.name}'] provided in model.execute(dict) must be ${a.attrParams.dtype.value}, but was ${n.dtype}`))}))}mapInputs(e){var t,n;const r={};for(const a in e){const s=null===(n=null===(t=this._signature)||void 0===t?void 0:t.inputs)||void 0===n?void 0:n[a];null!=s?r[s.name]=e[a]:r[a]=e[a]}return r}checkInputs(e){const t=Object.keys(e).filter((e=>{const[t]=of(e);return null==this.graph.nodes[t]}));if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map((e=>{var t,n;const r=null===(n=null===(t=this._signature)||void 0===t?void 0:t.outputs)||void 0===n?void 0:n[e];return null!=r?r.name:e}),{})}checkOutputs(e){e.forEach((e=>{const[t]=of(e);if(!this.graph.nodes[t])throw new Error(`The output '${e}' is not found in the graph`)}))}}class pm{constructor(e={},t={}){this.hashTableNameToHandle=e,this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(const e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(const e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}}const hm="?tfjs-format=file",dm="model.json";class fm{constructor(e,t={},n=yi){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=n,null==t&&(this.loadOptions={}),this.resourceManager=new pm}get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}get modelStructuredOutputKeys(){return this.structuredOutputKeys}findIOHandler(){const e=this.modelUrl;if(null!=e.load)this.handler=e;else if(null!=this.loadOptions.requestInit)this.handler=this.io.browserHTTPRequest(e,this.loadOptions);else{const t=this.io.getLoadHandlers(e,this.loadOptions);if(0===t.length)t.push(this.io.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}load(){if(this.findIOHandler(),null==this.handler.load)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const e=this.handler.load();return It(e)?e.then((e=>this.loadSync(e))):this.loadSync(e)}loadSync(e){this.artifacts=e;const t=this.artifacts.modelTopology;let n=this.artifacts.signature;if(null!=this.artifacts.userDefinedMetadata){const e=this.artifacts.userDefinedMetadata;null!=e.signature&&(n=e.signature),null!=e.structuredOutputKeys&&(this.structuredOutputKeys=e.structuredOutputKeys)}this.signature=n,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;const r=this.io.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new cm(Cf.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(r),this.executor.resourceManager=this.resourceManager,null!=e.modelInitializer&&null!=e.modelInitializer.node){const t=Cf.Instance.transformGraph(e.modelInitializer);this.initializer=new cm(t),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializerSignature=e.initializerSignature}return!0}async save(e,t){if("string"==typeof e){const t=this.io.getSaveHandlers(e);if(0===t.length)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Error(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}if(null==e.save)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}addStructuredOutputNames(e){if(this.structuredOutputKeys){const t={};return(e instanceof Va?[e]:e).forEach(((e,n)=>t[this.structuredOutputKeys[n]]=e)),t}return e}predict(e,t){const n=this.execute(e,this.outputNodes);return this.addStructuredOutputNames(n)}async predictAsync(e,t){const n=await this.executeAsync(e,this.outputNodes);return this.addStructuredOutputNames(n)}normalizeInputs(e){var t;if(!(e instanceof Va||Array.isArray(e))){const n=null===(t=this.signature)||void 0===t?void 0:t.inputs;if(null!=n)for(const t in n){const r=n[t];null!=r.resourceId&&(e[t]=this.resourceIdToCapturedInput[r.resourceId])}return e}e=Array.isArray(e)?e:[e];const n=Object.keys(this.resourceIdToCapturedInput).length;if(e.length+n!==this.inputNodes.length)throw new Error(`Input tensor count mismatch, the graph model has ${this.inputNodes.length-n} non-resource placeholders, while there are ${e.length} input tensors provided.`);let r=0;return this.inputNodes.reduce(((t,n)=>{var a,s,o;const i=null===(o=null===(s=null===(a=this.signature)||void 0===a?void 0:a.inputs)||void 0===s?void 0:s[n])||void 0===o?void 0:o.resourceId;return t[n]=null!=i?this.resourceIdToCapturedInput[i]:e[r++],t}),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}executeInitializerGraph(){return null==this.initializer?[]:null==this.initializerSignature?this.initializer.execute({},[]):this.initializer.execute({},Object.keys(this.initializerSignature.outputs))}async executeInitializerGraphAsync(){return null==this.initializer?[]:null==this.initializerSignature?this.initializer.executeAsync({},[]):this.initializer.executeAsync({},Object.keys(this.initializerSignature.outputs))}setResourceIdToCapturedInput(e){if(this.resourceIdToCapturedInput={},this.initializerSignature){const t=this.initializerSignature.outputs,n=Object.keys(t);for(let r=0;r<n.length;r++){const a=t[n[r]];this.resourceIdToCapturedInput[a.resourceId]=e[r]}}}execute(e,t){null==this.resourceIdToCapturedInput&&this.setResourceIdToCapturedInput(this.executeInitializerGraph()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){null==this.resourceIdToCapturedInput&&this.setResourceIdToCapturedInput(await this.executeInitializerGraphAsync()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce(((t,n)=>(t[n]=[e[n]],t)),{})}dispose(){this.executor.dispose(),this.initializer&&(this.initializer.dispose(),this.resourceIdToCapturedInput&&Ti(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}}async function mm(e,t={},n=yi){if(null==e)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");null==t&&(t={}),t.fromTFHub&&"string"==typeof e&&(e=function(e){return e.endsWith("/")||(e+="/"),`${e}${dm}${hm}`}(e));const r=new fm(e,t,n);return await r.load(),r}function gm(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&Qe("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the CPU backend.`))}))}const ym=nh;class bm extends je{constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new Ge(this,vi())}nextDataId(){return bm.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,Ct().get("IS_NODE")&&Cr("\n============================\nHi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details. \n============================"));const r={id:this.nextDataId()};return this.data.set(r,{values:e,dtype:n,refCount:1}),r}makeTensorInfo(e,t,n){let r;if("string"===t&&null!=n&&n.length>0&&dt(n[0])){const a=n.map((e=>ka(e)));r=this.write(a,e,t)}else r=this.write(n,e,t);return{dataId:r,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){this.data.get(e).refCount++}decRef(e){this.data.has(e)&&this.data.get(e).refCount--}move(e,t,n,r,a){this.data.set(e,{values:t,dtype:r,refCount:a})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);return"complex64"===t?$d(this.readSync(n.real.dataId),this.readSync(n.imag.dataId)):function(e,t){if(Array.isArray(e))return e;if("float32"===t)return e instanceof Float32Array?e:new Float32Array(e);if("int32"===t)return e instanceof Int32Array?e:new Int32Array(e);if("bool"===t||"string"===t)return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}(this.data.get(e).values,t)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map((e=>Ia(e)));return Qu(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Qu(e.shape,e.dtype,t)}makeOutput(e,t,n){return vi().makeTensorFromTensorInfo(this.makeTensorInfo(t,n,e),this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;const{complexTensorInfos:n}=this.data.get(e);null!=n&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){const t=Ta();return e(),{kernelMs:Ta()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){gm([e],"where");const t=this.readSync(e.dataId);return ym(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}function _m(e){return(t,n,r,a,s)=>{const o=Fi(t,n),i=o.length,u=yt(o),l=lt(s,et(o)),c=t.length,p=n.length,h=yt(t),d=yt(n),f=$i(t,o),m=$i(n,o);if(f.length+m.length===0)for(let t=0;t<l.length;++t)l[t]=e(r[t%r.length],a[t%a.length]);else for(let t=0;t<l.length;++t){const n=kt(t,i,u),s=n.slice(-c);f.forEach((e=>s[e]=0));const o=Tt(s,c,h),g=n.slice(-p);m.forEach((e=>g[e]=0));const y=Tt(g,p,d);l[t]=e(r[o],a[y])}return[l,o]}}function xm(e){const{inputs:t,backend:n}=e,{real:r,imag:a}=t,s=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values,i=n.makeTensorInfo(r.shape,"complex64");return n.data.get(i.dataId).complexTensorInfos={real:n.makeTensorInfo(r.shape,"float32",s),imag:n.makeTensorInfo(a.shape,"float32",o)},i}function vm(e,t,n="float32"){if("complex64"===n)return xm({inputs:{real:vm(e,t,"float32"),imag:vm(e,t,"float32")},backend:e});const r=vt(et(t),n);return e.makeTensorInfo(t,n,r)}function wm(e){const{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}bm.nextDataId=0;const Tm={kernelName:mn,backendName:"cpu",kernelFunc:wm};function km(e){const{inputs:t,backend:n}=e,{input:r}=t,a=n.data.get(r.dataId).complexTensorInfos.real,s=n.data.get(a.dataId).values;return n.makeTensorInfo(a.shape,a.dtype,s)}function Im(e,t,n,r){if("int32"===r)return[t,"int32",Int32Array.from(e)];if("bool"===r){const r=wa([0],n),[a,s]=_m(((e,t)=>e!==t?1:0))(t,[],e,r,"bool");return[s,"bool",a]}throw new Error(`Error in Cast: failed to cast ${n} to ${r}`)}function Sm(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dtype:s}=r;if("complex64"===s){if("complex64"===a.dtype)return wm({inputs:{x:a},backend:n});const e=vm(n,a.shape,a.dtype),t=Sm({inputs:{x:a},backend:n,attrs:{dtype:"float32"}}),r=xm({inputs:{real:t,imag:e},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),r}if("complex64"===a.dtype){const e=km({inputs:{input:a},backend:n}),t=Sm({inputs:{x:e},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(e),t}if(!pt(a.dtype,s)){const e=wm({inputs:{x:a},backend:n});return{dataId:e.dataId,shape:e.shape,dtype:s}}const o=n.data.get(a.dataId).values,[i,u,l]=Im(o,a.shape,a.dtype,s);return n.makeTensorInfo(i,u,l)}const Em={kernelName:Vt,backendName:"cpu",kernelFunc:Sm};function Nm(e,t,n,r){return null==n?({inputs:n,backend:a})=>{const{a:s,b:o}=n,i=a;gm([s,o],e);const u=i.data.get(s.dataId).values,l=i.data.get(o.dataId).values,c="string"===s.dtype?Kd(u):u,p="string"===s.dtype?Kd(l):l,h=r||s.dtype,[d,f]=t(s.shape,o.shape,c,p,h);return i.makeTensorInfo(f,h,d)}:({inputs:e,backend:a})=>{const{a:s,b:o}=e,i=a;if("complex64"===s.dtype||"complex64"===o.dtype){const e=Sm({inputs:{x:s},backend:i,attrs:{dtype:"complex64"}}),t=i.data.get(e.dataId),r=t.complexTensorInfos.real,a=t.complexTensorInfos.imag,u=i.data.get(r.dataId).values,l=i.data.get(a.dataId).values,c=Sm({inputs:{x:o},backend:i,attrs:{dtype:"complex64"}}),p=i.data.get(c.dataId),h=p.complexTensorInfos.real,d=p.complexTensorInfos.imag,f=i.data.get(h.dataId).values,m=i.data.get(d.dataId).values,[g,y,b]=n(s.shape,o.shape,u,l,f,m),_=i.makeTensorInfo(b,"float32",g),x=i.makeTensorInfo(b,"float32",y),v=xm({inputs:{real:_,imag:x},backend:i});return i.disposeIntermediateTensorInfo(e),i.disposeIntermediateTensorInfo(c),i.disposeIntermediateTensorInfo(_),i.disposeIntermediateTensorInfo(x),v}{const e=i.data.get(s.dataId).values,n=i.data.get(o.dataId).values,a=r||s.dtype,[u,l]=t(s.shape,o.shape,e,n,a);return i.makeTensorInfo(l,a,u)}}}function Cm(e){return(t,n,r,a,s,o)=>{const i=Fi(t,n),u=et(i),l=i.length,c=yt(i),p=lt("float32",u),h=lt("float32",u),d=$i(t,i),f=$i(n,i),m=$d(r,a),g=$d(s,o),y=t.length,b=yt(t),_=n.length,x=yt(n);if(d.length+f.length===0)for(let t=0;t<p.length;t++){const n=t%m.length,r=t%g.length,a=e(m[2*n],m[2*n+1],g[2*r],g[2*r+1]);p[t]=a.real,h[t]=a.imag}else for(let t=0;t<p.length;t++){const n=kt(t,l,c),r=n.slice(-y);d.forEach((e=>r[e]=0));const a=Tt(r,y,b),s=n.slice(-_);f.forEach((e=>s[e]=0));const o=Tt(s,_,x),i=e(m[2*a],m[2*a+1],g[2*o],g[2*o+1]);p[t]=i.real,h[t]=i.imag}return[p,h,i]}}const Am=_m(((e,t)=>e+t)),Rm=Cm(((e,t,n,r)=>({real:e+n,imag:t+r}))),$m=Nm(Ft,Am,Rm),Mm={kernelName:Ft,backendName:"cpu",kernelFunc:$m};function Fm(e){return(t,n,r)=>{const a=lt(n,t.length);for(let n=0;n<t.length;++n)a[n]=e(t[n],r);return a}}function Om(e,t,n){return({inputs:r,attrs:a,backend:s})=>{const{x:o}=r;if(gm(o,e),"string"===o.dtype||"string"===n)throw new Error("unaryKernelFunc does not support string input/output");const i=s,u=i.data.get(o.dataId).values,l=et(o.shape),c=n||o.dtype,p=ct(c,l);for(let e=0;e<l;++e)p[e]=t(u[e],a);return i.makeTensorInfo(o.shape,c,p)}}const Dm=Fm((e=>Math.ceil(e)));function Lm(e,t,n,r){const a=ct(n,et(t));if(r&&"string"!==n){let t=0;e.forEach((e=>{const n=et(e.shape);a.set(e.vals,t),t+=n}))}else{let r=0;e.forEach((e=>{const s="string"===n?Kd(e.vals):e.vals;let o=0;for(let n=0;n<e.shape[0];++n){const i=n*t[1]+r;for(let t=0;t<e.shape[1];++t)a[i+t]=s[o++]}r+=e.shape[1]}))}return a}const Pm=_m(((e,t)=>e===t?1:0)),Bm=Fm((e=>Math.exp(e))),Um=(zm=rn,Vm=Bm,"float32",({inputs:e,attrs:t,backend:n})=>{const{x:r}=e;if(gm(r,zm),"string"===r.dtype)throw new Error("unaryKernelFunc does not support string input/output");const a=n,s=a.data.get(r.dataId).values,o="float32",i=Vm(s,o,t);return a.makeTensorInfo(r.shape,o,i)});var zm,Vm;const Wm=Fm((e=>Math.expm1(e))),Hm=Fm((e=>Math.floor(e))),Gm=_m(((e,t)=>e>t?1:0)),jm=_m(((e,t)=>e>=t?1:0)),Km=_m(((e,t)=>e<t?1:0)),qm=_m(((e,t)=>e<=t?1:0)),Xm=Fm((e=>Math.log(e)));function Ym(e,t,n,r){const a=lt(r,et(n));for(let n=0;n<a.length;++n){const r=n*t;let s=e[r];for(let n=0;n<t;++n){const t=e[r+n];(Number.isNaN(t)||t>s)&&(s=t)}a[n]=s}return a}const Qm=_m(((e,t)=>Math.max(e,t))),Jm=_m(((e,t)=>Math.min(e,t))),Zm=_m(((e,t)=>e*t)),eg=Cm(((e,t,n,r)=>({real:e*n-t*r,imag:e*r+t*n}))),tg=Nm(An,Zm,eg),ng={kernelName:An,backendName:"cpu",kernelFunc:tg},rg=_m(((e,t)=>e!==t?1:0));function ag(e,t,n,r,a){const s=t.length,o=et(t),i=yt(t),u=yt(a),l=lt(n,et(a));for(let t=0;t<o;++t){const n=kt(t,s,i),a=new Array(n.length);for(let e=0;e<a.length;e++)a[e]=n[r[e]];l[Tt(a,s,u)]=e[t]}return l}function sg(e){const{inputs:t,attrs:n,backend:r}=e,{x:a}=t,{perm:s}=n;gm(a,"transpose");const o=a.shape.length,i=new Array(o);for(let e=0;e<i.length;e++)i[e]=a.shape[s[e]];const u=ag(r.data.get(a.dataId).values,a.shape,a.dtype,s,i);return{dataId:r.write(u,i,a.dtype),shape:i,dtype:a.dtype}}function og(e,t){const n=e.slice(0,t);for(;n.length<t;)n.push(1);for(let r=t;r<e.length;r++)n[t-1]*=e[r];return n}var ig=_d;class ug{constructor(e,t,n,r,a,s,o,i,u,l){this.shape=e,this.shapeShape=t,this.values=n,this.valuesShape=r,this.valuesDType=a,this.defaultValue=s,this.defaultValueShape=o,this.rowPartitionValues=i,this.rowPartitionValuesShapes=u,this.rowPartitionTypes=vd(l),this.raggedRank=wd(this.rowPartitionTypes)}getRowPartitionTypeByDimension(e){return this.rowPartitionTypes[0]===ig.FIRST_DIM_SIZE?this.rowPartitionTypes[e+1]:this.rowPartitionTypes[e]}getRowPartitionTensor(e){return this.rowPartitionTypes[0]===ig.FIRST_DIM_SIZE?this.rowPartitionValues[e+1]:this.rowPartitionValues[e]}getMaxWidth(e){const t=this.getRowPartitionTensor(e-1);switch(this.getRowPartitionTypeByDimension(e-1)){case ig.VALUE_ROWIDS:return ug.getMaxWidthValueRowID(t);case ig.ROW_SPLITS:return ug.getMaxWidthRowSplit(t);default:throw new Error(`Cannot handle partition type ${ig[this.getRowPartitionTypeByDimension(e-1)]}`)}}static getMaxWidthRowSplit(e){const t=e.length;if(0===t||1===t)return 0;let n=0;for(let r=0;r<t-1;++r){const t=e[r+1]-e[r];t>n&&(n=t)}return n}static getMaxWidthValueRowID(e){const t=e.length;if(0===t)return 0;let n=0,r=e[0],a=0;for(let s=1;s<t;++s){const t=e[s];t!==r&&(r=t,a=Math.max(s-n,a),n=s)}return Math.max(t-n,a)}tensorShapeFromTensor(e,t,n=!0){if(0===t.length){if(-1===e[0])return[];throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.")}return cg(e,n)}calculateOutputSize(e){const t=this.valuesShape;Td(this.defaultValueShape,t);const n=this.tensorShapeFromTensor(this.shape,this.shapeShape),r=xd(this.raggedRank,n,t);r[0]<0&&(r[0]=e);for(let e=1;e<=this.raggedRank;++e)r[e]<0&&(r[e]=this.getMaxWidth(e));return r}calculateFirstParentOutputIndex(e,t,n){const r=Math.min(e,n),a=[];let s=0;for(let e=0;e<r;++e,s+=t)a.push(s);for(let t=r;t<e;++t)a.push(-1);return Qe(a.length===e,(()=>"Final length of result must be equal to firstDimension.")),a}calculateOutputIndexRowSplit(e,t,n,r){const a=e.length,s=[];for(let o=0;o<a-1;++o){const a=e[o+1]-e[o];let i=Math.min(r,a),u=t[o];-1===u&&(i=0);for(let e=0;e<i;++e)s.push(u),u+=n;for(let e=0;e<a-i;++e)s.push(-1)}if(a>0&&s.length!==e[a-1])throw new Error("Invalid row split size.");return s}calculateOutputIndexValueRowID(e,t,n,r){const a=e.length,s=[];if(0===a)return[];let o=0,i=e[0];if(i>=t.length)throw new Error(`Got currentValueRowId=${i}, which is not less than ${t.length}`);let u=t[i];s.push(u);for(let l=1;l<a;++l){const a=e[l];if(a===i)u>=0&&(++o,o<r?u+=n:u=-1);else{if(o=0,i=a,a>=t.length)throw new Error(`Got nextValueRowId=${a} which is not less than ${t.length}`);u=t[a]}s.push(u)}if(s.length!==e.length)throw new Error("Invalid row ids.");return s}calculateOutputIndex(e,t,n,r){const a=this.getRowPartitionTensor(e),s=this.getRowPartitionTypeByDimension(e);switch(s){case ig.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(a,t,n,r);case ig.ROW_SPLITS:if(a.length-1>t.length)throw new Error(`Row partition size is greater than output size: ${a.length-1} > ${t.length}`);return this.calculateOutputIndexRowSplit(a,t,n,r);default:throw new Error(`Unsupported partition type: ${ig[s]}`)}}getFirstDimensionSize(){const e=this.rowPartitionValues[0];if(0===this.rowPartitionTypes.length)throw new Error("No row_partition_types given.");const t=this.rowPartitionTypes[0];switch(t){case ig.FIRST_DIM_SIZE:return e[0];case ig.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case ig.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${ig[t]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");const e=this.getFirstDimensionSize(),t=this.calculateOutputSize(e),n=new Array(this.raggedRank+1);n[n.length-1]=1;for(let e=n.length-2;e>=0;--e)n[e]=n[e+1]*t[e+1];const r=cg(t,!1),a=ct(this.valuesDType,et(r));if(n[0]*t[0]>0){let s=this.calculateFirstParentOutputIndex(e,n[0],t[0]);for(let e=1;e<=this.raggedRank;++e)s=this.calculateOutputIndex(e-1,s,n[e],t[e]);this.setOutput(this.raggedRank,s,a,r)}return[r,a]}setOutput(e,t,n,r){if(0===n.length)return;const a=this.values,s=n;let o=r.slice();o=o.slice(e+1);const i=et(o),u=t.length;let l=this.defaultValue;if(l.length!==i&&1!==l.length){const e=this.defaultValueShape;wi((()=>{const t=Fu(l,e),n=Yu(t,o);l=n.dataSync()}))}let c=0,p=0,h=0;for(let e=0;e<=u;++e){let r=e<u?t[e]:-1;if(r!==h){if(p<h){const e=a.subarray(c*i);lg(s.subarray(p*i),e,(h-p)*i)}if(e>=u){const e=n.length;r=Math.floor(e/i)}if(r>h)if(1===this.defaultValue.length)s.subarray(h*i,r*i).fill(this.defaultValue[0]),h=r;else for(;r>h;)lg(s.slice(h*i),l,i),++h;r<0?(c=e+1,p=h):(c=e,p=h,h=p+1)}else++h}}}function lg(e,t,n){for(let r=0;r<n;r++)e[r]=t[r]}function cg(e,t){const n=[];for(let r of e){if(r<0){if(!t)throw new Error(`Dimension ${r} must be >= 0`);if(r<-1)throw new Error(`Dimension ${r} must be >= -1`);r=-1}n.push(r)}return n}function pg(e,t,n,r){if(e===t||e<t&&n<0||t<e&&n>1)return vt(0,r);const a=vt(Math.abs(Math.ceil((t-e)/n)),r);t<e&&1===n&&(n=-1),a[0]=e;for(let e=1;e<a.length;e++)a[e]=a[e-1]+n;return a}const hg=Fm((e=>1/Math.sqrt(e))),dg=Fm((e=>1/(1+Math.exp(-e)))),fg=Om(er,(e=>1/(1+Math.exp(-e)))),mg={kernelName:er,backendName:"cpu",kernelFunc:fg};function gg(e,t,n,r,a){const s=Ji(r,t,n),o=et(n),i=yt(r);if(s){const n=Zi(t,i);return"string"===a?e.slice(n,n+o):e.subarray(n,n+o)}const u=Qu(r,a,"string"===a?Kd(e):e),l=Qu(n,a);for(let e=0;e<l.size;++e){const n=l.indexToLoc(e),r=n.map(((e,n)=>e+t[n]));l.set(u.get(...r),...n)}return"string"===a?qd(l.values):l.values}function yg(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,size:o}=r;gm(a,"slice");const[i,u]=eu(a,s,o);Vi(a,i,u);const l=gg(n.data.get(a.dataId).values,i,u,a.shape,a.dtype);return n.makeTensorInfo(u,a.dtype,l)}const bg={kernelName:Zn,backendName:"cpu",kernelFunc:yg},_g=Fm((e=>Math.sqrt(e))),xg=_m(((e,t)=>{const n=e-t;return n*n}));function vg(e,t,n,r){const a=Qu(e,t.dtype);for(let e=0;e<a.size;e++){const s=a.indexToLoc(e),o=new Array(s.length);for(let e=0;e<o.length;e++)o[e]=s[e]*n[e]+r[e];a.set(t.get(...o),...s)}return a}class wg{constructor(e,t,n,r,a,s){this.separator=ka(e),this.nGramWidths=t,this.leftPad=ka(n),this.rightPad=ka(r),this.padWidth=a,this.preserveShort=s}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){const n=this.getPadWidth(t);return Math.max(0,e+2*n-t+1)}createNGrams(e,t,n,r,a,s){for(let o=0;o<a;++o){const i=this.getPadWidth(s),u=Math.max(0,i-o),l=Math.max(0,i-(a-(o+1))),c=s-(u+l),p=t+(u>0?0:o-i);let h=0;h+=u*this.leftPad.length;for(let t=0;t<c;++t)h+=e[p+t].length;h+=l*this.rightPad.length,h+=(u+l+c-1)*this.separator.length,n[r+o]=new Uint8Array(h);const d=n[r+o];let f=0;const m=e=>e.forEach((e=>d[f++]=e));for(let e=0;e<u;++e)m(this.leftPad),m(this.separator);for(let t=0;t<c-1;++t)m(e[p+t]),m(this.separator);if(c>0){m(e[p+c-1]);for(let e=0;e<l;++e)m(this.separator),m(this.rightPad)}else{for(let e=0;e<l-1;++e)m(this.rightPad),m(this.separator);m(this.rightPad)}}}compute(e,t){const n=e.length,r=t.length;if(r>0){let e=t[0];if(0!==e)throw new Error(`First split value must be 0, got ${e}`);for(let a=1;a<r;++a){let r=t[a]>=e;if(r=r&&t[a]<=n,!r)throw new Error(`Invalid split value ${t[a]}, must be in [${e}, ${n}]`);e=t[a]}if(e!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${e}`)}const a=r-1,s=ct("int32",r);if(0===n||0===r){const e=new Array(n);for(let e=0;e<=a;++e)s[e]=0;return[e,s]}s[0]=0;for(let e=1;e<=a;++e){const n=t[e]-t[e-1];let r=0;this.nGramWidths.forEach((e=>{r+=this.getNumNGrams(n,e)})),this.preserveShort&&n>0&&0===r&&(r=1),s[e]=s[e-1]+r}const o=new Array(s[a]);for(let n=0;n<a;++n){const r=t[n];let a=s[n];if(this.nGramWidths.forEach((s=>{const i=t[n+1]-t[n],u=this.getNumNGrams(i,s);this.createNGrams(e,r,o,a,u,s),a+=u})),this.preserveShort&&a===s[n]){const s=t[n+1]-t[n];if(0===s)continue;const i=s+2*this.padWidth,u=1;this.createNGrams(e,r,o,a,u,i)}}return[o,s]}}function Tg(e,t,n,r,a,s,o,i){return new wg(n,r,a,s,o,i).compute(e,t)}function kg(e,t,n,r){if(!e.length)return;if(0===t.length){for(let t=0;t<e.length;++t)r.push(e.subarray(t,t+1));return}if(1===t.length){const a=t[0];let s=e.indexOf(a);for(;-1!==s;){const t=e.subarray(0,s);n&&0===t.length||r.push(t),s=(e=e.subarray(s+1)).indexOf(a)}return void(n&&0===e.length||r.push(e))}let a=0;for(let s=0;s<e.length+1;s++)if(s===e.length||-1!==t.indexOf(e[s])){const t=e.subarray(a,s);n&&0===t.length||r.push(t),a=s+1}}function Ig(e,t,n){const r=e.length,a=[];let s=0,o=0;const i=new Array(r);for(let u=0;u<r;++u){const r=a.length;kg(e[u],t,n,a);const l=a.length-r;i[u]=l,s+=l,o=Math.max(o,l)}const u=ct("int32",2*s),l=new Array(s),c=[r,o];let p=0;for(let e=0;e<r;++e)for(let t=0;t<i[e];++t)u[2*p]=e,u[2*p+1]=t,l[p]=a[p],++p;return[u,l,c]}function Sg(e,t){const n=ct("int32",e.length);for(let r=0;r<e.length;++r)n[r]=xa(e[r]).modulo(t).getLowBitsUnsigned();return n}const Eg=_m(((e,t)=>e-t)),Ng=Cm(((e,t,n,r)=>({real:e-n,imag:t-r}))),Cg=Nm(mr,Eg,Ng),Ag={kernelName:mr,backendName:"cpu",kernelFunc:Cg},Rg=(e,t)=>{const n=t.value-e.value;return 0===n?e.index-t.index:n};function $g(e,t,n=0,r=e.length-1){for(;r>n;){if(r-n>600){const a=r-n+1,s=t-n+1,o=Math.log(a),i=.5*Math.exp(2*o/3),u=.5*Math.sqrt(o*i*(a-i)/a)*Math.sign(s-a/2);$g(e,t,Math.max(n,Math.floor(t-s*i/a+u)),Math.min(r,Math.floor(t+(a-s)*i/a+u)))}const a=e[t];let s=n,o=r;for(Ye(e,n,t),Rg(e[r],a)>0&&Ye(e,n,r);s<o;){for(Ye(e,s,o),s++,o--;Rg(e[s],a)<0;)s+=1;for(;Rg(e[o],a)>0;)o-=1}0===Rg(e[n],a)?Ye(e,n,o):(o+=1,Ye(e,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}}var Mg=Object.freeze({__proto__:null,simpleAbsImpl:function(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t},addImpl:Am,bincountImpl:function(e,t,n,r,a){const s=et(r),o=vt(a,n);for(let n=0;n<e.length;n++){const r=e[n];if(r<0)throw new Error("Input x must be non-negative!");r>=a||(o[r]+=s>0?t[n]:1)}return o},bincountReduceImpl:function(e,t,n,r=!1){const a=e.shape[0],s=e.shape[1],o=Qu([a,n],t.dtype);for(let i=0;i<a;i++)for(let a=0;a<s;a++){const s=e.get(i,a);if(s<0)throw new Error("Input x must be non-negative!");s>=n||(r?o.set(1,i,s):t.size>0?o.set(o.get(i,s)+t.get(i,a),i,s):o.set(o.get(i,s)+1,i,s))}return o},castImpl:Im,ceilImpl:Dm,concatImpl:Lm,equalImpl:Pm,expImpl:Bm,expm1Impl:Wm,floorImpl:Hm,gatherNdImpl:function(e,t,n,r,a,s,o,i,u){const l=Qu([r,s],n);for(let n=0;n<r;n++){const r=[];let c=0;for(let t=0;t<a;t++){const s=e[n*a+t];c+=s*o[t],r.push(s)}if(c<0||c>=u/s)throw new Error(`Invalid indices: ${r} does not index into ${i}`);for(let e=0;e<s;e++)l.values[n*s+e]=t.get(...t.indexToLoc(c*s+e))}return l},gatherV2Impl:function(e,t,n){const r=Qu(n,e.dtype);for(let n=0;n<r.size;++n){const a=r.indexToLoc(n).slice(),s=a[0],o=a[2],i=t.locToIndex([s,o]);a[2]=t.values[i];const u=e.locToIndex(a);0<=u&&u<e.values.length&&(r.values[n]=e.values[u])}return r},greaterImpl:Gm,greaterEqualImpl:jm,lessImpl:Km,lessEqualImpl:qm,linSpaceImpl:function(e,t,n){const r=(t-e)/(n-1),a=vt(n,"float32");a[0]=e;for(let e=1;e<a.length;e++)a[e]=a[e-1]+r;return a},logImpl:Xm,maxImpl:Ym,maximumImpl:Qm,minimumImpl:Jm,multiplyImpl:Zm,negImpl:function(e,t,n){const r=va(-1,n);return Zm([],t,r,e,n)},notEqualImpl:rg,prodImpl:function(e,t,n,r){const[a,s]=Rl(e,r),o=Ya(t,"int32"),i=vt(et(a),o),u=et(s);for(let e=0;e<i.length;++e){const t=e*u;let r=1;for(let e=0;e<u;++e)r*=n[t+e];i[e]=r}return{outVals:i,outShape:a,outDtype:o}},raggedGatherImpl:function(e,t,n,r,a,s,o,i){if(0===e.length)throw new Error("paramsNestedSplits must be non empty");if(0===t[0].length)throw new Error("Split tensors must not be scalars");if(function(e,t,n){e.forEach(((e,r)=>{if(e<0||e>=n){const a=kt(r,t.length,yt(t)).join(",");throw new Error(`indices[${a}] = ${e} is not in [0, ${n})`)}}))}(s,o,t[0][0]-1),0===r.length)throw new Error("params.rank must be nonzero");const u=r[0],{outSplits:l,valueSlices:c,numValues:p}=function(e,t,n,r){const a=[];let s=0;const o=t.length-1+n.length,i=new Array(o).fill(null).map((()=>[0]));!function(e,t){for(let n=0;n<e.length;++n){const r=e[n],a=n===e.length-1?t:e[n+1].length;if(0===r.length)throw new Error("Ragged splits may not be empty");if(r[0]<0)throw new Error("Ragged splits must be non-negative");if(r[r.length-1]>a)throw new Error("Ragged splits must not point past values");for(let e=1;e<r.length;++e)if(r[e-1]>r[e])throw new Error("Ragged splits must be sorted in ascending order")}}(n,r);let u=1;for(let e=0;e<t.length-1;++e){u*=t[e];const n=t[e+1];for(let t=1;t<u+1;++t)i[e].push(t*n)}for(let r=0;r<e.length;++r){let o=e[r],u=e[r]+1;for(let e=0;e<n.length;++e){const r=n[e],a=e+t.length-1;if(a>=0){const e=i[a],t=e[e.length-1]-r[o];for(let e=o;e<u;++e)i[a].push(r[e+1]+t)}o=r[o],u=r[u]}u!==o&&(a.push([o,u]),s+=u-o)}return{outSplits:i,valueSlices:a,numValues:s}}(s,o,e,u),h=function(e){const t=[];for(let n=0;n<e.length;++n){const r=ct("int32",e[n].length);t.push(r),e[n].forEach(((e,t)=>r[t]=e))}return t}(l),d=function(e,t,n,r,a){const s=t.slice();s[0]=a;const o=ct(n,et(s)),i=e.length;return function(e,t,n,r,a,s){const o=og(t,2)[1],i=og(s,2)[1];let u=0;for(const t of n)for(let n=t[0];n<t[1];++n){for(let t=0;t<r;++t)a[u*i+t]=e[n*o+t];++u}}(e,t,r,0===i?0:i/t[0],o,s),[o,s]}(n,r,a,c,p);return[h,d[0],d[1]]},raggedRangeImpl:function(e,t,n,r,a,s,o){if(t.length>1)throw new Error("starts must be a scalar or vector");if(a.length>1)throw new Error("limits must be a scalar or vector");if(o.length>1)throw new Error("deltas must be a scalar or vector");const i=0===t.length,u=0===a.length,l=0===o.length,c=[];i||c.push(t[0]),u||c.push(a[0]),l||c.push(o[0]);for(let e=1;e<c.length;++e)if(c[e]!==c[e-1])throw new Error("starts, limits, and deltas must have the same shape");const p=0===c.length?1:c[0],h=ct("int32",p+1);h[0]=0;for(let t=0;t<p;++t){const n=i?e[0]:e[t],a=u?r[0]:r[t],o=l?s[0]:s[t];if(0===o)throw new Error("Requires delta != 0");let c;if(o>0&&a<n||o<0&&a>n)c=0;else if(c=Math.ceil(Math.abs((a-n)/o)),c>2147483647)throw new Error("Requires ((limit - start) / delta) <= 2147483647");h[t+1]=h[t]+c}const d=ct(n,h[p]);let f=0;for(let t=0;t<p;++t){const n=h[t+1]-h[t];let r=i?e[0]:e[t];const a=l?s[0]:s[t];for(let e=0;e<n;++e)d[f++]=r,r+=a}return[h,d]},raggedTensorToTensorImpl:function(e,t,n,r,a,s,o,i,u,l){return new ug(e,t,n,r,a,s,o,i,u,l).compute()},rangeImpl:pg,rsqrtImpl:hg,scatterImpl:function(e,t,n,r,a,s,o,i,u,l){const c=[r/a,a],p=e.values,h=t.values;if(0===r)return Qu(n,t.dtype);const d=Qu(c,t.dtype);"string"==typeof u||"number"==typeof u?d.values.fill(u):"boolean"==typeof u&&d.values.fill(+u);for(let e=0;e<s;e++){const s=[];let u=0;for(let t=0;t<o;t++){const n=p[e*o+t];s.push(n),u+=n*i[t]}if(u<0||u>=r/a)throw new Error(`Invalid indices: ${s} does not index into ${n}`);for(let n=0;n<a;n++)l?d.values[u*a+n]+=h[e*a+n]:d.values[u*a+n]=0===t.rank?h[0]:h[e*a+n]}return d},sigmoidImpl:dg,sliceImpl:gg,sparseFillEmptyRowsImpl:function(e,t,n,r,a,s,o){const i=t[0],u=s[0],l=new Array(u),c=new Array(i),p=t[1];if(0===u){if(0!==i)throw new Error(Dd(i));return[ct(n,0),[0,p],ct(a,0),l,c]}let h=!0,d=0;const f=new Array(u).fill(0);for(let t=0;t<i;++t){const n=e[t*p];if(n<0)throw new Error(Ld(t,n));if(n>=u)throw new Error(Pd(t,n,u));++f[n],h=h&&n>=d,d=n}let m=!0;for(let e=0;e<u;++e){const t=0===f[e];l[e]=t,m=m&&!t,f[e]=Math.max(f[e],1),e>0&&(f[e]+=f[e-1])}if(m&&h){const t=e,n=r;for(let e=0;e<i;++e)c[e]=e;return[t,[i,p],n,l,c]}{const t=f[u-1],s=ct(n,t*p),h=ct(a,t),d=new Array(u).fill(0);for(let t=0;t<i;++t){const n=e[t*p],a=d[n],o=(0===n?0:f[n-1])+a;d[n]++;for(let n=0;n<p;++n)s[o*p+n]=e[t*p+n];h[o]=r[t],c[t]=o}for(let e=0;e<u;++e)if(0===d[e]){const t=0===e?0:f[e-1];s[t*p+0]=e;for(let e=1;e<p;++e)s[t*p+e]=0;h[t]=o}return[s,[t,p],h,l,c]}},sparseReshapeImpl:function(e,t,n,r,a){const s=et(r),o=t[0],i=a.length,u=[];let l=1,c=-1;for(let e=0;e<i;++e){const t=a[e];if(-1===t){if(-1!==c)throw new Error(Bd(c,e));c=e,u.push(1)}else{if(t<0)throw new Error(Ud(e,t));l*=t,u.push(t)}}if(-1!==c){if(l<=0)throw new Error("reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero");const e=Math.trunc(s/l);if(l*e!==s)throw new Error(zd(r,u));u[c]=e}if(et(u)!==s)throw new Error(Vd(r,u));const p=r.length,h=[];if(p>0){h[p-1]=1;for(let e=p-2;e>=0;--e)h[e]=h[e+1]*r[e+1]}const d=[];if(i>0){d[i-1]=1;for(let e=i-2;e>=0;--e)d[e]=d[e+1]*u[e+1]}const f=ct(n,o*i);for(let t=0;t<o;++t){let n=0;for(let r=0;r<p;++r)n+=e[t*p+r]*h[r];for(let e=0;e<i;++e)f[t*i+e]=Math.trunc(n/d[e]),n%=d[e]}return[f,[o,i],u]},sparseSegmentReductionImpl:function(e,t,n,r,a,s=!1,o=0){const i=r.length,u=[t[0],e.length/t[0]],l=u[1],c=i>0?a[i-1]+1:0;if(c<0)throw new Error("segment ids must be >= 0");const p=t.slice();p[0]=c;const h=ct(n,p.reduce(((e,t)=>e*t),1));if(0===i)return c>0&&h.fill(o),[h,p];if(c<=0)throw new Error("segment ids must be >= 0");let d=0,f=1,m=0,g=a[d];for(;;){let t=0;if(f<i){if(t=a[f],g===t){++f;continue}if(g>=t)throw new Error("segment ids are not increasing")}if(g<0||g>=c)throw new Error(Wd(g,c));g>m&&h.fill(o,m*l,g*l);for(let t=d;t<f;++t){const n=r[t];if(n<0||n>=u[0])throw new Error(Hd(t,r[t],u[0]));for(let t=0;t<l;t++)h[g*l+t]+=e[n*l+t]}if(s)for(let e=0;e<l;e++)h[g*l+e]/=f-d;if(d=f,++f,m=g+1,g=t,f>i)break}return m<c&&h.fill(o,m*l,c*l),[h,p]},sqrtImpl:_g,squaredDifferenceImpl:xg,stridedSliceImpl:vg,stringNGramsImpl:Tg,stringSplitImpl:Ig,stringToHashBucketFastImpl:Sg,subImpl:Eg,tileImpl:function(e,t){const n=new Array(e.rank);for(let r=0;r<n.length;r++)n[r]=e.shape[r]*t[r];const r=Qu(n,e.dtype);for(let t=0;t<r.values.length;++t){const n=r.indexToLoc(t),a=new Array(e.rank);for(let t=0;t<a.length;t++)a[t]=n[t]%e.shape[t];const s=e.locToIndex(a);r.values[t]=e.values[s]}return r},topKImpl:function(e,t,n,r,a){const s=t[t.length-1],[o,i]=[e.length/s,s],u=lt(n,o*r),l=lt("int32",o*r);for(let t=0;t<o;t++){const n=t*i,s=e.subarray(n,n+i);let o=new Array(s.length);s.forEach(((e,t)=>o[t]={value:e,index:t})),r<o.length&&($g(o,r),o=o.slice(0,r)),a&&o.sort(Rg);const c=t*r,p=u.subarray(c,c+r),h=l.subarray(c,c+r);for(let e=0;e<r;e++)p[e]=o[e].value,h[e]=o[e].index}const c=t.slice();return c[c.length-1]=r,[Qu(c,n,u),Qu(c,"int32",l)]},transposeImpl:ag,uniqueImpl:function(e,t,n,r){const a=it(t,n)[0],s=[1,n[0],1];for(let e=0;e<a;e++)s[0]*=n[e];s[1]=n[a];for(let e=a+1;e<n.length;e++)s[2]*=n[e];const o={},i=new Int32Array(n[a]),u=new Ba(s,r,e),l=[],c=1===s[0]&&1===s[2];for(let t=0;t<n[a];t++){let n;if(c)n=e[t].toString();else{const e=[];for(let n=0;n<s[0];n++)for(let r=0;r<s[2];r++)e.push(u.get(n,t,r));n=e.join(",")}if(void 0!==o[n])i[t]=o[n];else{const e=Object.keys(o).length;o[n]=e,i[t]=e,l.push(t)}}const p=s.slice();p[1]=Object.keys(o).length;const h=new Ba(p,r);l.forEach(((e,t)=>{for(let n=0;n<s[0];n++)for(let r=0;r<s[2];r++)h.set(u.get(n,e,r),n,t,r)}));const d=n.slice();return d[a]=p[1],{outputValues:h.values,outputShape:d,indices:i}}});function Fg(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{shape:s}=r,o=et(a.shape),i=ot(s,o),u=et(i);Qe(o===u,(()=>`The new shape (${i}) has ${u} elements and the old shape (${a.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`)),n.incRef(a.dataId);const l=n.data.get(a.dataId);if(null!=l.complexTensorInfos){const e=l.complexTensorInfos.real,t=l.complexTensorInfos.imag;e.shape=i,t.shape=i}return{dataId:a.dataId,shape:i,dtype:a.dtype}}Ei("cpu",(()=>new bm),1);const Og={kernelName:Hn,backendName:"cpu",kernelFunc:Fg},Dg={kernelName:jn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:o,size:i}=r;gm(a,"resizeBilinear");const u=yt(a.shape),[l,c]=i,[p,h,d,f]=a.shape,m=n.data.get(a.dataId).values,g=new Float32Array(et([p,l,c,f])),y=[s&&l>1?h-1:h,s&&c>1?d-1:d],b=[s&&l>1?l-1:l,s&&c>1?c-1:c];let _=0;const x=y[0]/b[0],v=y[1]/b[1];for(let e=0;e<p;e++)for(let t=0;t<l;t++){let n;n=o?x*(t+.5)-.5:x*t;const r=Math.max(0,Math.floor(n)),a=n-r,s=Math.min(h-1,Math.ceil(n)),i=e*u[0]+r*u[1],l=e*u[0]+s*u[1];for(let e=0;e<c;e++){let t;t=o?v*(e+.5)-.5:v*e;const n=Math.max(0,Math.floor(t)),r=t-n,s=Math.min(d-1,Math.ceil(t)),c=i+n*u[2],p=l+n*u[2],h=i+s*u[2],y=l+s*u[2];for(let e=0;e<f;e++){const t=m[c+e],n=m[p+e],s=t+(m[h+e]-t)*r,o=s+(n+(m[y+e]-n)*r-s)*a;g[_++]=o}}}return n.makeTensorInfo([p,l,c,f],"float32",g)}},Lg=_m(((e,t)=>e/t)),Pg=Nm(en,Lg),Bg={kernelName:en,backendName:"cpu",kernelFunc:Pg},Ug={kernelName:Pn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{paddings:s,constantValue:o}=r;gm(a,"pad");const i=s.map(((e,t)=>e[0]+a.shape[t]+e[1])),u=s.map((e=>e[0])),l=n.data.get(a.dataId).values,c=et(a.shape),p=a.shape.length,h=yt(a.shape),d=et(i),f=i.length,m=yt(i),g=lt(a.dtype,d);0!==o&&g.fill(o);for(let e=0;e<c;e++)g[Tt(kt(e,p,h).map(((e,t)=>e+u[t])),f,m)]=l[e];return{dataId:n.write(g,i,a.dtype),shape:i,dtype:a.dtype}}};function zg(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dataFormat:u,dilations:l,dimRoundingMode:c}=r;gm([a,s],"conv2d");const p=$u(u),h=wu(a.shape,s.shape,o,l,i,c,!1,p),d=h.filterHeight,f=h.filterWidth,m=h.dilationHeight,g=h.dilationWidth,y=h.padInfo.left,b=h.padInfo.top,_="channelsLast"===h.dataFormat,x=new Ba(h.outShape,a.dtype),v=yt(a.shape),w=yt(s.shape),T=v[0],k=_?v[1]:v[2],I=_?v[2]:1,S=_?1:v[1],E=x.strides[0],N=_?x.strides[1]:x.strides[2],C=_?x.strides[2]:1,A=_?1:x.strides[1],R=n.data.get(a.dataId).values,$=n.data.get(s.dataId).values,M=x.values;for(let e=0;e<h.batchSize;++e){const t=e*T,n=e*E;for(let e=0;e<h.outHeight;++e){const r=n+e*N,a=e*h.strideHeight-b;for(let e=0;e<d;++e){const n=a+e*m;if(n<0||n>=h.inHeight)continue;const s=e*w[0],o=t+n*k;for(let e=0;e<h.outWidth;++e){const t=r+e*C,n=e*h.strideWidth-y;for(let e=0;e<f;++e){const r=n+e*g;if(r<0||r>=h.inWidth)continue;const a=o+r*I;let i=s+e*w[1];for(let e=0;e<h.inChannels;++e){const n=R[a+e*S];for(let e=0;e<h.outChannels;++e)M[t+e*A]+=n*$[i+e];i+=h.outChannels}}}}}}return n.makeTensorInfo(x.shape,x.dtype,M)}const Vg={kernelName:jt,backendName:"cpu",kernelFunc:zg},Wg=Om(tn,(e=>e>=0?e:Math.exp(e)-1)),Hg=_m(((e,t)=>e<0?t*e:e)),Gg=Om(Wn,(e=>Math.max(0,e))),jg={kernelName:Wn,backendName:"cpu",kernelFunc:Gg},Kg=Om(Kn,(e=>Math.min(Math.max(0,e),6))),qg={kernelName:Kn,backendName:"cpu",kernelFunc:Kg};function Xg(e,t,n,r,a){if("linear"===n)return wm({inputs:{x:t},backend:e});if("relu"===n)return Gg({inputs:{x:t},backend:e});if("elu"===n)return Wg({inputs:{x:t},backend:e});if("relu6"===n)return Kg({inputs:{x:t},backend:e});if("prelu"===n)return function(e){const{inputs:t,backend:n}=e,{x:r,alpha:a}=t;gm([r,a],"prelu");const s=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values,[i,u]=Hg(r.shape,a.shape,s,o,"float32");return n.makeTensorInfo(u,"float32",i)}({inputs:{x:t,alpha:r},backend:e});if("leakyrelu"===n)return function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{alpha:s}=r;gm([a],"leakyRelu");const o=et(a.shape),i=n.data.get(a.dataId).values,u=lt("float32",o);for(let e=0;e<i.length;e++)u[e]=i[e]<0?s*i[e]:i[e];return n.makeTensorInfo(a.shape,"float32",u)}({inputs:{x:t},backend:e,attrs:{alpha:a}});if("sigmoid"===n)return fg({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}const Yg={kernelName:Er,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dataFormat:c,dilations:p,dimRoundingMode:h,activation:d,leakyreluAlpha:f}=r;let m=zg({inputs:{x:a,filter:s},backend:n,attrs:{strides:u,pad:l,dataFormat:c,dilations:p,dimRoundingMode:h}});if(o){const e=m;if("NCHW"===c&&1===o.shape.length&&1!==o.shape[0]){const e=Fg({inputs:{x:o},backend:n,attrs:{shape:[o.shape[0],1,1]}});m=$m({inputs:{a:m,b:e},backend:n}),n.disposeIntermediateTensorInfo(e)}else m=$m({inputs:{a:m,b:o},backend:n});n.disposeIntermediateTensorInfo(e)}if(d){const e=m;if("NCHW"===c&&"prelu"===d&&1===i.shape.length&&1!==i.shape[0]){const e=Fg({inputs:{x:i},backend:n,attrs:{shape:[i.shape[0],1,1]}});m=Xg(n,m,d,e,f),n.disposeIntermediateTensorInfo(e)}else m=Xg(n,m,d,i,f);n.disposeIntermediateTensorInfo(e)}return m}};function Qg(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dilations:u,dimRoundingMode:l}=r;gm([a,s],"depthwiseConv2DNative");const c=yt(a.shape),p=yt(s.shape);let h=u;null==h&&(h=[1,1]),Qe(Au(o,h),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${h}'`));const d=wu(a.shape,s.shape,o,h,i,l,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:y,padInfo:b}=d,_=b.left,x=b.top,v=d.outChannels/d.inChannels,w=new Ba(d.outShape,a.dtype),T=n.data.get(a.dataId).values,k=n.data.get(s.dataId).values,I=w.values;for(let e=0;e<d.batchSize;++e){const t=e*c[0],n=e*w.strides[0];for(let e=0;e<d.outHeight;++e){const r=n+e*w.strides[1],a=e*d.strideHeight-x;for(let e=0;e<f;++e){const n=a+e*g;if(n<0||n>=d.inHeight)continue;const s=e*p[0],o=t+n*c[1];for(let e=0;e<d.outWidth;++e){const t=r+e*w.strides[2],n=e*d.strideWidth-_;for(let e=0;e<m;++e){const r=n+e*y;if(r<0||r>=d.inWidth)continue;const a=s+e*p[1],i=o+r*d.inChannels;let u=t,l=a;for(let e=0;e<d.inChannels;++e){const t=T[i+e];for(let e=0;e<v;++e)I[u+e]+=t*k[l+e];u+=v,l+=v}}}}}}return n.makeTensorInfo(w.shape,w.dtype,w.values)}const Jg={kernelName:Zt,backendName:"cpu",kernelFunc:Qg},Zg={kernelName:Nr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dataFormat:c,dilations:p,dimRoundingMode:h,activation:d,leakyreluAlpha:f}=r;let m=Qg({inputs:{x:a,filter:s},backend:n,attrs:{strides:u,pad:l,dataFormat:c,dilations:p,dimRoundingMode:h}});if(o){const e=m;m=$m({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(e)}if(d){const e=m;m=Xg(n,m,d,i,f),n.disposeIntermediateTensorInfo(e)}return m}},ey={kernelName:rr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,paddings:o}=r;gm([a],"spaceToBatchND");const i=et(s),u=[[0,0]];u.push(...o);for(let e=1+s.length;e<a.shape.length;++e)u.push([0,0]);const l=Ug.kernelFunc({inputs:{x:a},backend:n,attrs:{paddings:u,constantValue:0}}),c=Ed(l.shape,s,i,!1),p=Nd(c.length,s.length,!1),h=Cd(l.shape,s,i,!1),d=Fg({inputs:{x:l},backend:n,attrs:{shape:c}}),f=sg({inputs:{x:d},backend:n,attrs:{perm:p}}),m=Fg({inputs:{x:f},backend:n,attrs:{shape:h}});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),m}},ty={kernelName:zt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,crops:o}=r;gm([a],"batchToSpaceND");const i=s.reduce(((e,t)=>e*t)),u=Ed(a.shape,s,i),l=Nd(u.length,s.length),c=Cd(a.shape,s,i),p=Ad(o,s.length),h=Rd(c,o,s.length),d=Fg({inputs:{x:a},backend:n,attrs:{shape:u}}),f=sg({inputs:{x:d},backend:n,attrs:{perm:l}}),m=Fg({inputs:{x:f},backend:n,attrs:{shape:c}}),g=yg({inputs:{x:m},backend:n,attrs:{begin:p,size:h}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}},ny={kernelName:pr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,end:o,strides:i,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:h}=r;gm(a,"stridedSlice");const{finalShapeSparse:d,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:_,strides:x}=tu(a.shape,s,o,i,u,l,c,p,h);let v;if(m)v=Fg({inputs:{x:a},backend:n,attrs:{shape:f}});else if(g||y){Qe(a.shape.length>=1,(()=>`Input must have rank at least 1, got: ${a.shape.length}`));const e=Wi(b,_,x),t=yg({inputs:{x:a},backend:n,attrs:{begin:b,size:e}});v=Fg({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else{const e=vg(d,n.bufferSync(a),x,b);v=n.makeTensorInfo(f,e.dtype,e.values)}return v}};function ry(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r,s=it(a,t[0].shape)[0];yd(t.map((e=>e.shape)),s);let o=bd(t.map((e=>e.shape)),s);if(0===et(o))return n.makeTensorInfo(o,t[0].dtype,[]);const i=t.filter((e=>et(e.shape)>0));if(1===i.length)return wm({inputs:{x:i[0]},backend:n});if("complex64"===i[0].dtype){const e=i.map((e=>km({inputs:{input:e},backend:n}))),t=i.map((e=>function(e){const{inputs:t,backend:n}=e,{input:r}=t,a=n.data.get(r.dataId).complexTensorInfos.imag,s=n.data.get(a.dataId).values;return n.makeTensorInfo(a.shape,a.dtype,s)}({inputs:{input:e},backend:n}))),r=ry({inputs:e,backend:n,attrs:{axis:s}}),a=ry({inputs:t,backend:n,attrs:{axis:s}}),o=xm({inputs:{real:r,imag:a},backend:n});return e.forEach((e=>n.disposeIntermediateTensorInfo(e))),t.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),o}const u=i.map((e=>{const t=et(e.shape.slice(s));return Fg({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),l=u.map((e=>({vals:n.data.get(e.dataId).values,shape:e.shape})));o=bd(u.map((e=>e.shape)),1);const c=1===u[0].shape[0],p=Lm(l,o,t[0].dtype,c),h=bd(i.map((e=>e.shape)),s),d=n.makeTensorInfo(h,t[0].dtype,p);return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}const ay={kernelName:Gt,backendName:"cpu",kernelFunc:ry};function sy(e){const{inputs:t,backend:n,attrs:r}=e,{input:a}=t,{dim:s}=r,o=a.shape.length,i=a.shape.slice();let u=s;return s<0&&(Qe(-(o+1)<=s,(()=>`Axis must be in the interval [${-(o+1)}, ${o}]`)),u=o+s+1),i.splice(u,0,1),Fg({inputs:{x:a},backend:n,attrs:{shape:i}})}const oy={kernelName:Ln,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return sy({inputs:{input:t[0]},backend:n,attrs:{dim:a}});const s=t[0].shape,o=t[0].dtype;t.forEach((e=>{Je(s,e.shape,"All tensors passed to stack must have matching shapes"),Qe(o===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const i=[],u=ry({inputs:t.map((e=>{const t=sy({inputs:{input:e},backend:n,attrs:{dim:a}});return i.push(t),t})),backend:n,attrs:{axis:a}});return i.forEach((e=>n.disposeIntermediateTensorInfo(e))),u}},iy={kernelName:Kt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{inputShape:o,strides:i,pad:u,dataFormat:l,dimRoundingMode:c}=r;gm([a,s],"conv2dBackpropInput");const p=yt(s.shape),h=yt(a.shape);let d=$u(l);const f=wu(o,s.shape,i,1,u,c,!1,d),m=new Ba(f.inShape,"float32"),g=m.values,y=n.data.get(a.dataId).values,b=n.data.get(s.dataId).values,[_,x,v]=p,{batchSize:w,filterHeight:T,filterWidth:k,inChannels:I,inHeight:S,inWidth:E,outChannels:N,outHeight:C,outWidth:A,strideHeight:R,strideWidth:$}=f;d=f.dataFormat;const M=T-1-f.padInfo.top,F=k-1-f.padInfo.left,O="channelsLast"===d,D=m.strides[0],L=O?m.strides[1]:m.strides[2],P=O?m.strides[2]:1,B=O?1:m.strides[1],U=h[0],z=O?h[1]:h[2],V=O?h[2]:1,W=O?1:h[1];for(let e=0;e<w;++e)for(let t=0;t<I;++t)for(let n=0;n<S;++n){const r=n-M,a=Math.max(0,Math.ceil(r/R)),s=Math.min(C,(T+r)/R);for(let o=0;o<E;++o){const i=o-F,u=Math.max(0,Math.ceil(i/$)),l=Math.min(A,(k+i)/$);let c=0;for(let n=a;n<s;++n){const a=n*R-r;for(let r=u;r<l;++r){const s=U*e+z*n+V*r,o=_*(T-1-a)+x*(k-1-(r*$-i))+v*t;for(let e=0;e<N;++e)c+=y[s+W*e]*b[o+e]}}g[D*e+L*n+P*o+B*t]=c}}return n.makeTensorInfo(m.shape,m.dtype,m.values)}},uy={kernelName:Qt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:a,boxes:s,boxInd:o}=t,{cropSize:i,method:u,extrapolationValue:l}=r,[c,p,h,d]=a.shape,f=s.shape[0],[m,g]=i,y=Qu([f,m,g,d],"float32"),b=n.data.get(s.dataId).values,_=n.data.get(o.dataId).values,x=n.data.get(a.dataId).values,v=yt(a.shape),w=yt(y.shape);for(let e=0;e<f;e++){const t=4*e,n=b[t],r=b[t+1],a=b[t+2],s=b[t+3],o=_[e];if(o>=c)continue;const i=m>1?(a-n)*(p-1)/(m-1):0,f=g>1?(s-r)*(h-1)/(g-1):0;for(let t=0;t<m;t++){const c=m>1?n*(p-1)+t*i:.5*(n+a)*(p-1);if(c<0||c>p-1)for(let n=0;n<g;n++)for(let r=0;r<d;r++){const a=r+n*w[2]+t*w[1]+e*w[0];y.values[a]=l}else if("bilinear"===u){const n=Math.floor(c),a=Math.ceil(c),i=c-n;for(let u=0;u<g;u++){const c=g>1?r*(h-1)+u*f:.5*(r+s)*(h-1);if(c<0||c>h-1){for(let n=0;n<d;n++){const r=n+u*w[2]+t*w[1]+e*w[0];y.values[r]=l}continue}const p=Math.floor(c),m=Math.ceil(c),b=c-p;for(let r=0;r<d;r++){let s=r+p*v[2]+n*v[1]+o*v[0];const l=x[s];s=r+m*v[2]+n*v[1]+o*v[0];const c=x[s];s=r+p*v[2]+a*v[1]+o*v[0];const h=x[s];s=r+m*v[2]+a*v[1]+o*v[0];const d=l+(c-l)*b,f=h+(x[s]-h)*b;s=r+u*w[2]+t*w[1]+e*w[0],y.values[s]=d+(f-d)*i}}}else for(let n=0;n<g;++n){const a=g>1?r*(h-1)+n*f:.5*(r+s)*(h-1);if(a<0||a>h-1){for(let r=0;r<d;r++){const a=r+n*w[2]+t*w[1]+e*w[0];y.values[a]=l}continue}const i=Math.round(a),u=Math.round(c);for(let r=0;r<d;r++){const a=r+i*v[2]+u*v[1]+o*v[0],s=r+n*w[2]+t*w[1]+e*w[0];y.values[s]=x[a]}}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}},ly={kernelName:qn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dims:s}=r;gm(a,"reverse");const o=a.shape.length,i=it(s,a.shape);if(0===o)return wm({inputs:{x:a},backend:n});const u=new Ba(a.shape,a.dtype),l=n.bufferSync(a);for(let e=0;e<u.size;e++){const t=u.indexToLoc(e),n=t.slice();i.forEach((e=>n[e]=a.shape[e]-1-n[e])),u.set(l.get(...n),...t)}return n.makeTensorInfo(u.shape,u.dtype,u.values)}},cy={kernelName:vr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{value:a}=t;let{axis:s}=r;s<0&&(s+=a.shape.length);const o=a.shape.length,i=a.shape[s],u=new Array(o-1);let l=0;for(let e=0;e<o;e++)e!==s&&(u[l++]=a.shape[e]);const c=new Array(o).fill(0),p=a.shape.slice();p[s]=1;const h=new Array(i);for(let e=0;e<h.length;e++){c[s]=e;const t=yg({inputs:{x:a},backend:n,attrs:{begin:c,size:p}});h[e]=Fg({inputs:{x:t},backend:n,attrs:{shape:u}}),n.disposeIntermediateTensorInfo(t)}return h}},py={kernelName:Pt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;gm(a,"argMax");let o=it(s,a.shape);const i=Fl(o,a.shape.length);let u=a;const l=[];null!=i&&(u=sg({inputs:{x:a},backend:n,attrs:{perm:i}}),l.push(u),o=Dl(o.length,u.shape.length)),o=[o[0]],Ml("argMax",o,u.shape.length);const[c,p]=Rl(u.shape,o),h=vt(et(c),"int32"),d=et(p),f=n.data.get(u.dataId).values;for(let e=0;e<h.length;++e){const t=e*d;let n=f[t],r=0;for(let e=0;e<d;++e){const a=f[t+e];a>n&&(n=a,r=e)}h[e]=r}return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(c,"int32",h)}};function hy(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r;let i;gm(a,"sum"),i="bool"===a.dtype?Sm({inputs:{x:a},backend:n,attrs:{dtype:"int32"}}):wm({inputs:{x:a},backend:n});const u=i.shape.length,l=it(s,i.shape),c=Fl(l,u);let p=l,h=i;null!=c&&(h=sg({inputs:{x:i},backend:n,attrs:{perm:c}}),p=Dl(p.length,u)),Ml("sum",p,h.shape.length);const[d,f]=Rl(h.shape,p);let m=vm(n,d,Ya(h.dtype,"int32"));const g=et(f),y=n.data.get(m.dataId).values,b=n.data.get(h.dataId).values;for(let e=0;e<y.length;++e){const t=e*g;let n=0;for(let e=0;e<g;++e)n+=b[t+e];y[e]=n}if(o){const e=m;m=Fg({inputs:{x:m},backend:n,attrs:{shape:$l(m.shape,l)}}),n.disposeIntermediateTensorInfo(e)}return n.disposeIntermediateTensorInfo(i),null!=c&&n.disposeIntermediateTensorInfo(h),m}const dy={kernelName:Sn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r,i=it(s,a.shape),u=et(Rl(a.shape,i)[1]),l=[],c=n.makeTensorInfo([],"float32",new Float32Array([u]));l.push(c);const p=Sm({inputs:{x:a},backend:n,attrs:{dtype:"float32"}});l.push(p);const h=Pg({inputs:{a:p,b:c},backend:n});l.push(h);const d=hy({inputs:{x:h},backend:n,attrs:{axis:s,keepDims:o}});return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}},fy={kernelName:sr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{dim:s}=r,o=a.shape.length;let i=s;if(-1===i&&(i=o-1),i!==o-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${o} and dim was ${i}`);const u=it([i],a.shape),l=function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{reductionIndices:s,keepDims:o}=r,i=n;let u=a.shape;const l=u.length,c=it(s,u);let p=c;const h=Fl(p,l);let d=i.data.get(a.dataId).values;if(null!=h){const e=new Array(l);for(let t=0;t<e.length;t++)e[t]=u[h[t]];d=ag(d,u,a.dtype,h,e),p=Dl(p.length,l),u=e}gm(a,"max"),Ml("max",p,l);const[f,m]=Rl(u,p),g=Ym(d,et(m),f,a.dtype),y=i.write(g,f,a.dtype);let b=f;return o&&(b=$l(f,c)),{dataId:y,shape:b,dtype:a.dtype}}({inputs:{x:a},backend:n,attrs:{reductionIndices:u,keepDims:!1}}),c=$l(l.shape,u),p=Fg({inputs:{x:l},backend:n,attrs:{shape:c}}),h=Cg({inputs:{a,b:p},backend:n}),d=Um({inputs:{x:h},backend:n}),f=hy({inputs:{x:d},backend:n,attrs:{axis:u,keepDims:!1}}),m=Fg({inputs:{x:f},backend:n,attrs:{shape:c}}),g=Pg({inputs:{a:d,b:m},backend:n});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}},my=Om(Ht,((e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e})),gy={kernelName:Ht,backendName:"cpu",kernelFunc:my},yy={kernelName:Bt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;gm(a,"avgPool");const{filterSize:s,strides:o,pad:i,dimRoundingMode:u}=r;Qe(Au(o,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '1'`));const l=vu(a.shape,s,o,1,i,u);let c;if(1===l.filterWidth&&1===l.filterHeight&&tt(l.inShape,l.outShape))c=wm({inputs:{x:a},backend:n});else{const e=n.data.get(a.dataId).values,t=yt(a.shape),r=function(e,t,n,r,a,s){const o=a.strideHeight,i=a.strideWidth,u=a.dilationHeight,l=a.dilationWidth,c=a.effectiveFilterHeight,p=a.effectiveFilterWidth,h=a.padInfo.top,d=a.padInfo.left,f=Number.POSITIVE_INFINITY,m=Qu(a.outShape,n),g=m.values,y=a.outShape[1]*a.outShape[2]*a.outShape[3],b=a.outShape[2]*a.outShape[3],_=a.outShape[3];for(let t=0;t<a.batchSize;++t){const n=t*y,s=t*r[0];for(let t=0;t<a.inChannels;++t)for(let m=0;m<a.outHeight;++m){const y=m*o-h,x=Math.max(0,y),v=Math.min(a.inHeight,c+y),w=n+m*b;for(let n=0;n<a.outWidth;++n){const o=n*i-d,c=Math.max(0,o),h=Math.min(a.inWidth,p+o);let m=f,y=0,b=0;for(let n=x;n<v;n+=u){const a=s+n*r[1];for(let n=c;n<h;n+=l){const s=e[a+n*r[2]+t];y+=s,b++}if(isNaN(m))break}g[w+n*_+t]=y/b}}}return m}(e,a.shape,a.dtype,t,l);c=n.makeTensorInfo(l.outShape,a.dtype,r.values)}return c}},by={kernelName:Ut,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a,b:s}=t,{transposeA:o,transposeB:i}=r;gm([a,s],"matMul");const u=a.shape.length,l=s.shape.length,c=o?a.shape[u-2]:a.shape[u-1],p=i?s.shape[l-1]:s.shape[l-2],h=o?a.shape[u-1]:a.shape[u-2],d=i?s.shape[l-2]:s.shape[l-1],f=a.shape.slice(0,-2),m=s.shape.slice(0,-2),g=et(f),y=et(m),b=Fi(a.shape.slice(0,-2),s.shape.slice(0,-2)).concat([h,d]);Qe(c===p,(()=>`Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${a.shape} and ${s.shape} and transposeA=${o} and transposeB=${i} must match.`));const _=i?[y,d,p]:[y,p,d],x=Fg({inputs:{x:a},backend:n,attrs:{shape:o?[g,c,h]:[g,h,c]}}),v=Fg({inputs:{x:s},backend:n,attrs:{shape:_}}),w=o?x.shape[1]:x.shape[2],T=o?x.shape[2]:x.shape[1],k=i?v.shape[1]:v.shape[2],I=Math.max(g,y),S=n.data.get(x.dataId).values,E=n.data.get(v.dataId).values,N=yt(x.shape),C=yt(v.shape),[A,R,$]=o?[N[0],1,N[1]]:[N[0],N[1],1],[M,F,O]=i?[1,C[1],C[0]]:[C[1],1,C[0]],D=T*k,L=Qu([I,T,k],x.dtype),P=L.values,B=n.blockSize;for(let e=0;e<I;e++){const t=e%g,n=e%y;for(let r=0;r<T;r+=B){const a=Math.min(r+B,T);for(let s=0;s<k;s+=B){const o=Math.min(s+B,k);for(let i=0;i<w;i+=B){const u=Math.min(i+B,w);for(let l=r;l<a;l++)for(let r=s;r<o;r++){let a=0;for(let e=i;e<u;e++)a+=S[t*A+l*R+e*$]*E[e*M+r*F+n*O];P[e*D+(l*k+r)]+=a}}}}}return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(v),n.makeTensorInfo(b,L.dtype,L.values)}},_y={},xy={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function vy(e,t){if(!(e in _y)||null!=t){const n=function(e,t){if(1!==e&&2!==e)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const n=null==t?function(e){if("undefined"!=typeof OffscreenCanvas&&2===e)return new OffscreenCanvas(300,150);if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}(e):t;return n.addEventListener("webglcontextlost",(t=>{t.preventDefault(),delete _y[e]}),!1),Ct().getBool("SOFTWARE_WEBGL_ENABLED")&&(xy.failIfMajorPerformanceCaveat=!1),1===e?n.getContext("webgl",xy)||n.getContext("experimental-webgl",xy):n.getContext("webgl2",xy)}(e,t);if(null===n)return console.log("Could not get context for WebGL version",e),null;_y[e]=n}const n=_y[e];return null==n||n.isContextLost()?(delete _y[e],vy(e)):(n.disable(n.DEPTH_TEST),n.disable(n.STENCIL_TEST),n.disable(n.BLEND),n.disable(n.DITHER),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SAMPLE_COVERAGE),n.enable(n.SCISSOR_TEST),n.enable(n.CULL_FACE),n.cullFace(n.BACK),_y[e])}var wy,Ty,ky;function Iy(e,t){return[t,e]}function Sy(e){const t=et(e);return rt(Math.ceil(t/4))}function Ey(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function Ny(e,t){const n=e;let r,a,s,o,i,u,l,c,p,h;return 2===Ct().getNumber("WEBGL_VERSION")?(r=n.R32F,a=n.R16F,s=n.RGBA16F,o=n.RGBA32F,i=n.RED,l=4,c=1,p=n.HALF_FLOAT,h=n.FLOAT,u=n.RGBA8):(r=e.RGBA,a=e.RGBA,s=e.RGBA,o=n.RGBA,i=e.RGBA,l=4,c=4,p=null!=t?t.HALF_FLOAT_OES:null,h=e.FLOAT,u=e.RGBA),{internalFormatFloat:r,internalFormatHalfFloat:a,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:o,textureFormatFloat:i,downloadTextureFormat:u,downloadUnpackNumChannels:l,defaultNumChannels:c,textureTypeHalfFloat:p,textureTypeFloat:h}}function Cy(e,t){const n=t();return Ct().getBool("DEBUG")&&function(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+function(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}(e,t))}(e),n}function Ay(e){return!!(Ct().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||5.96e-8<Math.abs(e)&&Math.abs(e)<65504)}function Ry(e,t){return By(e,(()=>e.getExtension(t)),'Extension "'+t+'" not supported on this browser.')}!function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"}(wy||(wy={})),function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"}(Ty||(Ty={})),function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(ky||(ky={}));const $y=/ERROR: [0-9]+:([0-9]+):/g;function My(e,t){const n=$y.exec(t);if(null==n)return console.log(`Couldn't parse line number in error: ${t}`),void console.log(e);const r=+n[1],a=e.split("\n"),s=a.length.toString().length+2,o=a.map(((e,t)=>at((t+1).toString(),s)+e));let i=0;for(let e=0;e<o.length;e++)i=Math.max(o[e].length,i);const u=o.slice(0,r-1),l=o.slice(r-1,r),c=o.slice(r);console.log(u.join("\n")),console.log(t.split("\n")[0]),console.log(`%c ${at(l[0],i)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(c.join("\n"))}function Fy(e,t){if(Cy(e,(()=>e.validateProgram(t))),!1===e.getProgramParameter(t,e.VALIDATE_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function Oy(e,t,n,r,a,s,o){const i=e.getAttribLocation(t,n);return-1!==i&&(Cy(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,r))),Cy(e,(()=>e.vertexAttribPointer(i,a,e.FLOAT,!1,s,o))),Cy(e,(()=>e.enableVertexAttribArray(i))),!0)}function Dy(e,t,n){Cy(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,n))),Cy(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)))}function Ly(e,t){Cy(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,t))),Cy(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)))}function Py(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+function(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}(e,t))}function By(e,t,n){const r=Cy(e,(()=>t()));if(null==r)throw new Error(n);return r}function Uy(e,t=2){return et(e.slice(0,e.length-t))}function zy(e){if(0===e.length)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function Vy(e){let t=[1,1,1];return 0===e.length||1===e.length&&1===e[0]||(t=[Uy(e),...zy(e)]),t}function Wy(e){return e%2==0}function Hy(e,t){if(tt(e=e.slice(-2),t=t.slice(-2)))return!0;if(!e.length||!t.length)return!0;if(0===e[0]||0===e[1]||0===t[0]||0===t[1])return!0;if(e.length!==t.length){const n=e.slice(-1)[0],r=t.slice(-1)[0];if(n===r)return!0;if(Wy(n)&&Wy(r)&&(1===e[0]||1===t[0]))return!0}return e[1]===t[1]&&Wy(e[0])&&Wy(t[0])}let Gy,jy;function Ky(e,t){return null!=e.getExtension(t)}function qy(e){try{if(null!=vy(e))return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function Xy(e){const t=Ny(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);const a=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(r),a}const Yy=Ct();function Qy(){let e,t,n,r,a,s,o,i,u,l;return 2===Ct().getNumber("WEBGL_VERSION")?(e="#version 300 es",t="in",n="out",r="in",a="texture",s="outputColor",o="out vec4 outputColor;",i=Ct().getBool("WEBGL2_ISNAN_CUSTOM")?"\n bool isnan_custom(float val) {\n uint floatToUint = floatBitsToUint(val);\n return (floatToUint & 0x7fffffffu) > 0x7f800000u;\n }\n\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan_custom(val.x),\n isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n }\n\n #define isnan(value) isnan_custom(value)\n ":"",u="",l="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(e="",t="attribute",n="varying",r="varying",a="texture2D",s="gl_FragColor",o="",i="\n #define isnan(value) isnan_custom(value)\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n ",u="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",l="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:a,output:s,defineOutput:o,defineSpecialNaN:i,defineSpecialInf:u,defineRound:l}}function Jy(e,t,n="index"){const r=yt(t);return r.map(((t,a)=>`int ${e[a]} = ${n} / ${t}; ${a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * ${t}`:`index -= ${e[a]} * ${t}`};`)).join("")}function Zy(e,t,n="index"){const r=yt(t);return r.map(((t,a)=>`int ${e[a]} = ${n} / outShapeStrides[${a}]; ${a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * outShapeStrides[${a}]`:`index -= ${e[a]} * outShapeStrides[${a}]`};`)).join("")}function eb(e){const t=yt(e).map((e=>e.toString()));return`\n int getFlatIndex(ivec3 coords) {\n return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;\n }\n`}Yy.registerFlag("HAS_WEBGL",(()=>Yy.getNumber("WEBGL_VERSION")>0)),Yy.registerFlag("WEBGL_VERSION",(()=>qy(2)?2:qy(1)?1:0)),Yy.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",(()=>!1)),Yy.registerFlag("WEBGL_BUFFER_SUPPORTED",(()=>2===Yy.get("WEBGL_VERSION"))),Yy.registerFlag("WEBGL_CPU_FORWARD",(()=>!0)),Yy.registerFlag("WEBGL_FORCE_F16_TEXTURES",(()=>!1)),Yy.registerFlag("WEBGL_PACK",(()=>Yy.getBool("HAS_WEBGL"))),Yy.registerFlag("WEBGL_PACK_NORMALIZATION",(()=>Yy.getBool("WEBGL_PACK"))),Yy.registerFlag("WEBGL_PACK_CLIP",(()=>Yy.getBool("WEBGL_PACK"))),Yy.registerFlag("WEBGL_PACK_DEPTHWISECONV",(()=>Yy.getBool("WEBGL_PACK"))),Yy.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(()=>Yy.getBool("WEBGL_PACK"))),Yy.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(()=>Yy.getBool("WEBGL_PACK"))),Yy.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(()=>Yy.getBool("WEBGL_PACK"))),Yy.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(()=>Yy.getBool("WEBGL_PACK"))),Yy.registerFlag("WEBGL_PACK_REDUCE",(()=>Yy.getBool("WEBGL_PACK"))),Yy.registerFlag("WEBGL_LAZILY_UNPACK",(()=>Yy.getBool("WEBGL_PACK"))),Yy.registerFlag("WEBGL_CONV_IM2COL",(()=>Yy.getBool("WEBGL_PACK"))),Yy.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(()=>function(e){if(null==Gy){const t=vy(e);Gy=t.getParameter(t.MAX_TEXTURE_SIZE)}return Gy}(Yy.getNumber("WEBGL_VERSION")))),Yy.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(()=>function(e){if(null==jy){const t=vy(e);jy=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,jy)}(Yy.getNumber("WEBGL_VERSION")))),Yy.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(()=>{const e=Yy.getNumber("WEBGL_VERSION");return 0===e?0:function(e){if(0===e)return 0;let t;const n=vy(e);return t=Ky(n,"EXT_disjoint_timer_query_webgl2")&&2===e?2:Ky(n,"EXT_disjoint_timer_query")?1:0,t}(e)})),Yy.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(()=>Yy.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!os())),Yy.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(()=>function(e){if(0===e)return!1;const t=vy(e);if(1===e){if(!Ky(t,"OES_texture_float"))return!1}else if(!Ky(t,"EXT_color_buffer_float"))return!1;return Xy(t)}(Yy.getNumber("WEBGL_VERSION")))),Yy.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(()=>!Yy.getBool("WEBGL_FORCE_F16_TEXTURES")&&Yy.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))),Yy.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(()=>function(e){if(0===e)return!1;const t=vy(e);if(1!==e){if(Ky(t,"EXT_color_buffer_float"))return Xy(t);const e="EXT_color_buffer_half_float";if(Ky(t,e)){const n=t.getExtension(e);return function(e,t){const n=Ny(e,t),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);const a=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,a),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const s=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(r),e.deleteFramebuffer(a),s}(t,n)}return!1}return!!Ky(t,"OES_texture_float")&&!!Ky(t,"WEBGL_color_buffer_float")&&Xy(t)}(Yy.getNumber("WEBGL_VERSION")))),Yy.registerFlag("WEBGL_FENCE_API_ENABLED",(()=>{return 2===(e=Yy.getNumber("WEBGL_VERSION"))&&null!=vy(e).fenceSync;var e})),Yy.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(()=>Yy.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0)),Yy.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",(()=>-1),(e=>{if(e<0&&-1!==e)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`)})),Yy.registerFlag("WEBGL_FLUSH_THRESHOLD",(()=>os()?1:-1),(e=>{if(e<0&&-1!==e)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${e}.`)})),Yy.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",(()=>128)),Yy.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",(()=>!1)),Yy.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",(()=>1e5)),Yy.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",(()=>128)),Yy.registerFlag("WEBGL_EXP_CONV",(()=>!1)),Yy.registerFlag("SOFTWARE_WEBGL_ENABLED",(()=>Yy.getBool("IS_TEST"))),Yy.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",(()=>1/0)),Yy.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",(()=>!1)),Yy.registerFlag("WEBGL2_ISNAN_CUSTOM",(()=>!1)),Yy.registerFlag("ENGINE_COMPILE_ONLY",(()=>!1));const tb="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isnan(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n",{getBroadcastDims:nb}=Xd;function rb(e,t,n){const r=[];if(e.forEach((e=>{const t=et(e.shapeInfo.logicalShape);if(e.shapeInfo.isUniform?r.push(`uniform float ${e.name}${t>1?`[${t}]`:""};`):(r.push(`uniform sampler2D ${e.name};`),r.push(`uniform int offset${e.name};`)),n.enableShapeUniforms){const{uniformShape:t}=db(n.packedInputs,e.shapeInfo.logicalShape,e.shapeInfo.texShape);switch(t.length){case 1:r.push(`uniform int ${e.name}Shape;`);break;case 2:r.push(`uniform ivec2 ${e.name}Shape;`);break;case 3:r.push(`uniform ivec3 ${e.name}Shape;`);break;case 4:r.push(`uniform ivec4 ${e.name}Shape;`)}r.push(`uniform ivec2 ${e.name}TexShape;`)}})),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:r.push("uniform int outShape;");break;case 2:r.push("uniform ivec2 outShape;"),r.push("uniform int outShapeStrides;");break;case 3:r.push("uniform ivec3 outShape;"),r.push("uniform ivec2 outShapeStrides;");break;case 4:r.push("uniform ivec4 outShape;"),r.push("uniform ivec3 outShapeStrides;")}r.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach((e=>{r.push(`uniform ${e.type} ${e.name}${e.arrayIndex?`[${e.arrayIndex}]`:""};`)}));const a=r.join("\n"),s=e.map((e=>function(e,t,n=!1,r){let a="";a+=n?sb(e,r):ab(e,r);const s=e.shapeInfo.logicalShape,o=t.logicalShape;return s.length<=o.length&&(a+=n?function(e,t){const n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),a="get"+r+"AtOutCoords",s=e.shapeInfo.logicalShape.length,o=t.logicalShape.length,i=nb(e.shapeInfo.logicalShape,t.logicalShape),u=hb(o),l=o-s;let c;const p=["x","y","z","w","u","v"];c=0===s?"":o<2&&i.length>=1?"coords = 0;":i.map((e=>`coords.${p[e+l]} = 0;`)).join("\n");let h="";h=o<2&&s>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${p[t+l]}`)).join(", ");let d="return outputValue;";const f=1===et(e.shapeInfo.logicalShape),m=1===et(t.logicalShape);if(1!==s||f||m){if(f&&!m)d=1===o?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(i.length){const e=s-2,t=s-1;i.indexOf(e)>-1&&i.indexOf(t)>-1?d="return vec4(outputValue.x);":i.indexOf(e)>-1?d="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(t)>-1&&(d="return vec4(outputValue.xx, outputValue.zz);")}}else d="\n return vec4(outputValue.xy, outputValue.xy);\n ";return`\n vec4 ${a}() {\n ${u} coords = getOutputCoords();\n ${c}\n vec4 outputValue = get${r}(${h});\n ${d}\n }\n `}(e,t):function(e,t){const n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),a="get"+r+"AtOutCoords",s=t.texShape,o=e.shapeInfo.texShape,i=e.shapeInfo.logicalShape.length,u=t.logicalShape.length;if(!e.shapeInfo.isUniform&&i===u&&null==e.shapeInfo.flatOffset&&tt(o,s))return`\n float ${a}() {\n return sampleTexture(${n}, resultUV);\n }\n `;const l=hb(u),c=nb(e.shapeInfo.logicalShape,t.logicalShape),p=u-i;let h;const d=["x","y","z","w","u","v"];h=0===i?"":u<2&&c.length>=1?"coords = 0;":c.map((e=>`coords.${d[e+p]} = 0;`)).join("\n");let f="";return f=u<2&&i>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${d[t+p]}`)).join(", "),`\n float ${a}() {\n ${l} coords = getOutputCoords();\n ${h}\n return get${r}(${f});\n }\n `}(e,t)),a}(e,t,n.packedInputs,n.enableShapeUniforms))).join("\n"),o=t.texShape,i=Qy(),u=function(e){return`\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return ${e.texture2D}(textureSampler, uv).r;\n }\n `}(i);let l,c,p=function(e){return`${e.version}\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n ${e.varyingFs} vec2 resultUV;\n ${e.defineOutput}\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n ${e.defineSpecialNaN}\n ${e.defineSpecialInf}\n ${e.defineRound}\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n ${ob}\n ${ib}\n ${ub}\n `}(i);return t.isPacked?(l=function(e,t,n){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(e,t,n){const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return 1===r[0]?n?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));\n }\n ":`\n int getOutputCoords() {\n return 2 * int(resultUV.x * ${r[1]}.0);\n }\n `:1===r[1]?n?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));\n }\n ":`\n int getOutputCoords() {\n return 2 * int(resultUV.y * ${r[0]}.0);\n }\n `:n?"\n int getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);\n }\n ":`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n return 2 * (resTexRC.x * ${r[1]} + resTexRC.y);\n }\n `}(0,t,n);case 2:return function(e,t,n){const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(tt(e,t))return n?"\n ivec2 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));\n }\n ":`\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2(${r[0]}, ${r[1]}));\n }\n `;const a=Math.ceil(e[1]/2);return n?"\n ivec2 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec2(r, c);\n }\n ":`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n\n int index = resTexRC.x * ${r[1]} + resTexRC.y;\n int r = 2 * (index / ${a});\n int c = imod(index, ${a}) * 2;\n\n return ivec2(r, c);\n }\n `}(e,t,n);case 3:return function(e,t,n){if(n)return"\n ivec3 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));\n int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n\n int b = index / texelsInBatch;\n index -= b * texelsInBatch;\n\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec3(b, r, c);\n }\n ";const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],a=Math.ceil(e[2]/2),s=a*Math.ceil(e[1]/2);return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n int index = resTexRC.x * ${r[1]} + resTexRC.y;\n\n int b = index / ${s};\n index -= b * ${s};\n\n int r = 2 * (index / ${a});\n int c = imod(index, ${a}) * 2;\n\n return ivec3(b, r, c);\n }\n `}(e,t,n);default:return function(e,t,n){if(n)return"\n ivec4 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n\n int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));\n int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));\n int texelsInBatchN = texelsInBatch * outShape[1];\n\n int b2 = index / texelsInBatchN;\n index -= b2 * texelsInBatchN;\n\n int b = index / texelsInBatch;\n index -= b * texelsInBatch;\n\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec4(b2, b, r, c);\n }\n ";const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],a=Math.ceil(e[e.length-1]/2),s=a*Math.ceil(e[e.length-2]/2);let o=s,i="",u="b, r, c";for(let t=2;t<e.length-1;t++)o*=e[e.length-t-1],i=`\n int b${t} = index / ${o};\n index -= b${t} * ${o};\n `+i,u=`b${t}, `+u;return`\n ivec${e.length} getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n int index = resTexRC.x * ${r[1]} + resTexRC.y;\n\n ${i}\n\n int b = index / ${s};\n index -= b * ${s};\n\n int r = 2 * (index / ${a});\n int c = imod(index, ${a}) * 2;\n\n return ivec${e.length}(${u});\n }\n `}(e,t,n)}}(t.logicalShape,o,n.enableShapeUniforms),c=function(e){return`\n void setOutput(vec4 val) {\n ${e.output} = val;\n }\n `}(i)):(l=function(e,t,n){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(e,t,n){return 1===t[0]?n?"\n int getOutputCoords() {\n return int(resultUV.x * float(outTexShape[1]));\n }\n ":`\n int getOutputCoords() {\n return int(resultUV.x * ${t[1]}.0);\n }\n `:1===t[1]?n?"\n int getOutputCoords() {\n return int(resultUV.y * float(outTexShape[0]));\n }\n ":`\n int getOutputCoords() {\n return int(resultUV.y * ${t[0]}.0);\n }\n `:n?"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n return resTexRC.x * outTexShape[1] + resTexRC.y;\n }\n ":`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n return resTexRC.x * ${t[1]} + resTexRC.y;\n }\n `}(0,t,n);case 2:return function(e,t,n){return tt(e,t)?n?"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));\n }\n ":`\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));\n }\n `:1===e[1]?n?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n return ivec2(index, 0);\n }\n ":`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n return ivec2(index, 0);\n }\n `:1===e[0]?n?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n return ivec2(0, index);\n }\n ":`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n return ivec2(0, index);\n }\n `:n?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n int r = index / outShape[1];\n int c = index - r * outShape[1];\n return ivec2(r, c);\n }\n ":`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n int r = index / ${e[1]};\n int c = index - r * ${e[1]};\n return ivec2(r, c);\n }\n `}(e,t,n);case 3:return function(e,t,n){if(n)return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n ${Zy(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n`;const r=Jy(["r","c","d"],e);return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n ${r}\n return ivec3(r, c, d);\n }\n `}(e,t,n);case 4:return function(e,t,n){if(n)return`\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n ${Zy(["r","c","d","d2"],e)}\n return ivec4(r, c, d, d2);\n }\n `;const r=Jy(["r","c","d","d2"],e);return`\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n ${r}\n return ivec4(r, c, d, d2);\n }\n `}(e,t,n);case 5:return function(e,t){const n=Jy(["r","c","d","d2","d3"],e);return`\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},\n ${t[1]}));\n\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n\n ${n}\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n `}(e,t);case 6:return function(e,t){const n=Jy(["r","c","d","d2","d3","d4"],e);return`\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n\n ${n}\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n `}(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}(t.logicalShape,o,n.enableShapeUniforms),c=function(e){return`\n void setOutput(float val) {\n ${e.output} = vec4(val, 0, 0, 0);\n }\n `}(i)),n.packedInputs&&(p+=lb),[p,u,c,a,l,s,n.userCode].join("\n")}function ab(e,t=!1){const n=e.shapeInfo.logicalShape;switch(n.length){case 0:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`float ${r}() {return ${n};}`;const[a,s]=e.shapeInfo.texShape;if(1===a&&1===s)return`\n float ${r}() {\n return sampleTexture(${n}, halfCR);\n }\n `;const o=cb(n);if(t)return`\n float ${r}() {\n vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], ${o});\n return sampleTexture(${n}, uv);\n }\n `;const[i,u]=e.shapeInfo.texShape;return`\n float ${r}() {\n vec2 uv = uvFromFlat(${i}, ${u}, ${o});\n return sampleTexture(${n}, uv);\n }\n `}(e,t);case 1:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`\n float ${r}(int index) {\n ${pb(e)}\n }\n `;const a=e.shapeInfo.texShape,s=a[0],o=a[1];if(1===o&&1===s)return`\n float ${r}(int index) {\n return sampleTexture(${n}, halfCR);\n }\n `;const i=cb(n);return 1===o?t?`\n float ${r}(int index) {\n vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / float(${n}TexShape[0]));\n return sampleTexture(${n}, uv);\n }\n `:`\n float ${r}(int index) {\n vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / ${s}.0);\n return sampleTexture(${n}, uv);\n }\n `:1===s?t?`\n float ${r}(int index) {\n vec2 uv = vec2((float(index + ${i}) + 0.5) / float(${n}TexShape[1]), 0.5);\n return sampleTexture(${n}, uv);\n }\n `:`\n float ${r}(int index) {\n vec2 uv = vec2((float(index + ${i}) + 0.5) / ${o}.0, 0.5);\n return sampleTexture(${n}, uv);\n }\n `:t?`\n float ${r}(int index) {\n vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${i});\n return sampleTexture(${n}, uv);\n }\n `:`\n float ${r}(int index) {\n vec2 uv = uvFromFlat(${s}, ${o}, index + ${i});\n return sampleTexture(${n}, uv);\n }\n `}(e,t);case 2:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),s=e.shapeInfo.texShape;if(null!=s&&tt(n,s)){if(t)return`\n float ${a}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `;const e=s[0];return`\n float ${a}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${s[1]}.0, ${e}.0);\n return sampleTexture(${r}, uv);\n }\n `}const{newShape:o,keptDims:i}=ut(n),u=o;if(u.length<n.length){const n=["row","col"];return`\n ${ab(fb(e,u),t)}\n float ${a}(int row, int col) {\n return ${a}(${mb(n,i)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${a}(int row, int col) {\n int index = round(dot(vec2(row, col), vec2(${n[1]}, 1)));\n ${pb(e)}\n }\n `;const l=s[0],c=s[1],p=cb(r);return 1===c?t?`\n float ${a}(int row, int col) {\n float index = dot(vec3(row, col, ${p}), vec3(${r}Shape[1], 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / float(${r}TexShape[0]));\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col) {\n float index = dot(vec3(row, col, ${p}), vec3(${n[1]}, 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);\n return sampleTexture(${r}, uv);\n }\n `:1===l?t?`\n float ${a}(int row, int col) {\n float index = dot(vec3(row, col, ${p}), vec3(${r}Shape[1], 1, 1));\n vec2 uv = vec2((index + 0.5) / float(${r}TexShape[1]), 0.5);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col) {\n float index = dot(vec3(row, col, ${p}), vec3(${n[1]}, 1, 1));\n vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);\n return sampleTexture(${r}, uv);\n }\n `:t?`\n float ${a}(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${r}Shape[1] + col + ${p};\n vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${n[1]} + col + ${p};\n vec2 uv = uvFromFlat(${l}, ${c}, index);\n return sampleTexture(${r}, uv);\n }\n`}(e,t);case 3:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),s=n[1]*n[2],o=n[2],{newShape:i,keptDims:u}=ut(n),l=i;if(l.length<n.length){const n=["row","col","depth"];return`\n ${ab(fb(e,l),t)}\n float ${a}(int row, int col, int depth) {\n return ${a}(${mb(n,u)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${a}(int row, int col, int depth) {\n int index = round(dot(vec3(row, col, depth),\n vec3(${s}, ${o}, 1)));\n ${pb(e)}\n }\n `;const c=e.shapeInfo.texShape,p=c[0],h=c[1],d=e.shapeInfo.flatOffset;if(h===s&&null==d)return t?`\n float ${a}(int row, int col, int depth) {\n int stride1 = ${r}Shape[2];\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2(stride1, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col, int depth) {\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2(${o}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${h}.0, ${p}.0);\n return sampleTexture(${r}, uv);\n }\n `;if(h===o&&null==d)return t?`\n float ${a}(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2(${r}Shape[1], 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2(${n[1]}, 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${h}.0, ${p}.0);\n return sampleTexture(${r}, uv);\n }\n `;const f=cb(r);return t?`\n float ${a}(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int stride0 = ${r}Shape[1] * ${r}Shape[2];\n int stride1 = ${r}Shape[2];\n int index = row * stride0 + col * stride1 + depth + ${f};\n vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${s} + col * ${o} + depth + ${f};\n vec2 uv = uvFromFlat(${p}, ${h}, index);\n return sampleTexture(${r}, uv);\n }\n `}(e,t);case 4:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),s=n[3],o=n[2]*s,i=n[1]*o,{newShape:u,keptDims:l}=ut(n);if(u.length<n.length){const n=["row","col","depth","depth2"];return`\n ${ab(fb(e,u),t)}\n float ${a}(int row, int col, int depth, int depth2) {\n return ${a}(${mb(n,l)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${a}(int row, int col, int depth, int depth2) {\n int index = round(dot(vec4(row, col, depth, depth2),\n vec4(${i}, ${o}, ${s}, 1)));\n ${pb(e)}\n }\n `;const c=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,h=p[0],d=p[1],f=`int stride2 = ${r}Shape[3];`,m=`int stride1 = ${r}Shape[2] * stride2;`,g=`int stride0 = ${r}Shape[1] * stride1;`;if(d===i&&null==c)return t?`\n float ${a}(int row, int col, int depth, int depth2) {\n ${f}\n ${m}\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3(stride1, stride2, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col, int depth, int depth2) {\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3(${o}, ${s}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${d}.0, ${h}.0);\n return sampleTexture(${r}, uv);\n }\n `;if(d===s&&null==c)return t?`\n float ${a}(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3(${r}Shape[1] * ${r}Shape[2], ${r}Shape[2], 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3(${n[1]*n[2]}, ${n[2]}, 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${d}.0, ${h}.0);\n return sampleTexture(${r}, uv);\n }\n `;const y=cb(r);return t?`\n float ${a}(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n ${f}\n ${m}\n ${g}\n int index = row * stride0 + col * stride1 +\n depth * stride2 + depth2;\n vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index + ${y});\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${i} + col * ${o} +\n depth * ${s} + depth2;\n vec2 uv = uvFromFlat(${h}, ${d}, index + ${y});\n return sampleTexture(${r}, uv);\n }\n `}(e,t);case 5:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=t[4],s=t[3]*a,o=t[2]*s,i=t[1]*o,{newShape:u,keptDims:l}=ut(t);if(u.length<t.length){const t=["row","col","depth","depth2","depth3"];return`\n ${ab(fb(e,u))}\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n return ${r}(${mb(t,l)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n float index = dot(\n vec4(row, col, depth, depth2),\n vec4(${i}, ${o}, ${s}, ${a})) +\n depth3;\n ${pb(e)}\n }\n `;const c=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,h=p[0],d=p[1];return d===i&&null==c?`\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4(${o}, ${s}, ${a}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${d}.0, ${h}.0);\n return sampleTexture(${n}, uv);\n }\n `:d===a&&null==c?`\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n float texR = dot(\n vec4(row, col, depth, depth2),\n vec4(${t[1]*t[2]*t[3]},\n ${t[2]*t[3]}, ${t[3]}, 1));\n int texC = depth3;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${d}.0, ${h}.0);\n return sampleTexture(${n}, uv);\n }\n `:`\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${i} + col * ${o} + depth * ${s} +\n depth2 * ${a} + depth3 + ${cb(n)};\n vec2 uv = uvFromFlat(${h}, ${d}, index);\n return sampleTexture(${n}, uv);\n }\n `}(e);case 6:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:a,keptDims:s}=ut(t);if(a.length<t.length){const t=["row","col","depth","depth2","depth3","depth4"];return`\n ${ab(fb(e,a))}\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return ${r}(${mb(t,s)});\n }\n `}const o=t[5],i=t[4]*o,u=t[3]*i,l=t[2]*u,c=t[1]*l;if(e.shapeInfo.isUniform)return`\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int index = round(dot(\n vec4(row, col, depth, depth2),\n vec4(${c}, ${l}, ${u}, ${i})) +\n dot(\n vec2(depth3, depth4),\n vec2(${o}, 1)));\n ${pb(e)}\n }\n `;const p=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,d=h[0],f=h[1];return f===c&&null==p?`\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4(${l}, ${u}, ${i}, ${o})) +\n float(depth4);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${f}.0, ${d}.0);\n return sampleTexture(${n}, uv);\n }\n `:f===o&&null==p?`\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n float texR = dot(vec4(row, col, depth, depth2),\n vec4(${t[1]*t[2]*t[3]*t[4]},\n ${t[2]*t[3]*t[4]},\n ${t[3]*t[4]},\n ${t[4]})) + float(depth3);\n int texC = depth4;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${f}.0, ${d}.0);\n return sampleTexture(${n}, uv);\n }\n `:`\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${c} + col * ${l} + depth * ${u} +\n depth2 * ${i} + depth3 * ${o} + depth4 + ${cb(n)};\n vec2 uv = uvFromFlat(${d}, ${f}, index);\n return sampleTexture(${n}, uv);\n }\n `}(e);default:throw new Error(`${n.length}-D input sampling is not yet supported`)}}function sb(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return function(e){const t=e.name;return`\n vec4 ${"get"+t.charAt(0).toUpperCase()+t.slice(1)}() {\n return ${Qy().texture2D}(${t}, halfCR);\n }\n `}(e);case 1:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=e.shapeInfo.texShape,s=Qy();if(t)return`\n vec4 ${r}(int index) {\n ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));\n vec2 uv = packedUVfrom1D(\n packedTexShape[0], packedTexShape[1], index);\n return ${s.texture2D}(${n}, uv);\n }\n `;const o=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];return`\n vec4 ${r}(int index) {\n vec2 uv = packedUVfrom1D(\n ${o[0]}, ${o[1]}, index);\n return ${s.texture2D}(${n}, uv);\n }\n `}(e,t);case 2:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),s=e.shapeInfo.texShape,o=s[0],i=s[1],u=Qy();if(null!=s&&tt(n,s))return t?`\n vec4 ${a}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);\n\n return ${u.texture2D}(${r}, uv);\n }\n `:`\n vec4 ${a}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${i}.0, ${o}.0);\n\n return ${u.texture2D}(${r}, uv);\n }\n `;if(t)return`\n vec4 ${a}(int row, int col) {\n ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));\n int valuesPerRow = int(ceil(float(${r}Shape[1]) / 2.0));\n vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);\n return ${u.texture2D}(${r}, uv);\n }\n `;const l=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];return`\n vec4 ${a}(int row, int col) {\n vec2 uv = packedUVfrom2D(${Math.ceil(n[1]/2)}, ${l[0]}, ${l[1]}, row, col);\n return ${u.texture2D}(${r}, uv);\n }\n `}(e,t);case 3:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),s=e.shapeInfo.texShape,o=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];if(1===n[0]){const r=[1,2],s=["b","row","col"];return`\n ${sb(fb(e,n.slice(1)),t)}\n vec4 ${a}(int b, int row, int col) {\n return ${a}(${mb(s,r)});\n }\n `}const i=Qy();if(t)return`\n vec4 ${a}(int b, int row, int col) {\n ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));\n int valuesPerRow = int(ceil(float(${r}Shape[2]) / 2.0));\n int texelsInBatch = valuesPerRow * int(ceil(float(${r}Shape[1]) / 2.0));\n vec2 uv = packedUVfrom3D(\n packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);\n return ${i.texture2D}(${r}, uv);\n }\n `;const u=o[0],l=o[1],c=Math.ceil(n[2]/2);return`\n vec4 ${a}(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n ${u}, ${l}, ${c*Math.ceil(n[1]/2)}, ${c}, b, row, col);\n return ${i.texture2D}(${r}, uv);\n }\n `}(e,t);default:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=Qy();if(t)return`\n vec4 ${r}(int b2, int b, int row, int col) {\n int valuesPerRow = int(ceil(float(${n}Shape[3]) / 2.0));\n int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[2]) / 2.0));\n int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);\n texelsInBatch *= ${n}Shape[1];\n index = b2 * texelsInBatch + index;\n ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));\n int texR = index / packedTexShape[1];\n int texC = index - texR * packedTexShape[1];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${a.texture2D}(${n}, uv);\n }\n `;const s=e.shapeInfo.logicalShape,o=s.length,i=e.shapeInfo.texShape,u=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],l=u[0],c=u[1],p=Math.ceil(s[o-1]/2);let h=p*Math.ceil(s[o-2]/2),d="int b, int row, int col",f=`b * ${h} + (row / 2) * ${p} + (col / 2)`;for(let e=2;e<o-1;e++)d=`int b${e}, `+d,h*=s[o-e-1],f=`b${e} * ${h} + `+f;return`\n vec4 ${r}(${d}) {\n int index = ${f};\n int texR = index / ${c};\n int texC = index - texR * ${c};\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${c}, ${l});\n return ${a.texture2D}(${n}, uv);\n }\n `}(e,t)}}const ob="\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",ib="\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n int texNumC, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",ub="\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",lb="\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n float getChannel(vec4 frag, int dim) {\n float modCoord = mod(float(dim), 2.);\n return modCoord == 0. ? frag.r : frag.g;\n }\n";function cb(e){return`offset${e}`}function pb(e){const t=e.name,n=et(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`\n for (int i = 0; i < ${n}; i++) {\n if (i == index) {\n return ${t}[i];\n }\n }\n `}function hb(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function db(e,t,n){const{newShape:r,keptDims:a}=ut(t),s=t.length,o=e&&3===s&&1===t[0],i=o?t.slice(1):r,u=!e&&s>1&&!tt(t,n)&&r.length<s||o;return{useSqueezeShape:u,uniformShape:u?i:t,keptDims:a}}function fb(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function mb(e,t){return t.map((t=>e[t])).join(", ")}function gb(e,t,n){const r={},a={},s={},o=[];let i,u,l,c=null,p=null;p=e.getUniformLocation(n,"NAN",!1),1===Ct().getNumber("WEBGL_VERSION")&&(c=e.getUniformLocation(n,"INFINITY",!1));const h=!1;for(let o=0;o<t.variableNames.length;o++){const i=t.variableNames[o];r[i]=e.getUniformLocation(n,i,h),r[`offset${i}`]=e.getUniformLocation(n,`offset${i}`,h),t.enableShapeUniforms&&(a[`${i}Shape`]=e.getUniformLocation(n,`${i}Shape`,h),s[`${i}TexShape`]=e.getUniformLocation(n,`${i}TexShape`,h))}return t.enableShapeUniforms&&(i=e.getUniformLocation(n,"outShape",h),l=e.getUniformLocation(n,"outShapeStrides",h),u=e.getUniformLocation(n,"outTexShape",h)),t.customUniforms&&t.customUniforms.forEach(((t,r)=>{o[r]=e.getUniformLocation(n,t.name,h)})),{uniformLocations:r,customUniformLocations:o,infLoc:c,nanLoc:p,inShapesLocations:a,inTexShapesLocations:s,outShapeLocation:i,outShapeStridesLocation:l,outTexShapeLocation:u}}function yb(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach(((e,n)=>{const r=e.logicalShape,a=t[n],s=a.shape;if(!tt(r,s))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${r} and ${s} must match`);if(e.isUniform&&a.isUniform)return;const o=e.texShape,i=a.isUniform?null:a.texData.texShape;if(!tt(o,i))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${o} and ${i} must match`)}))}function bb(e){return Ct().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}class _b{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=wy.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=Qy();this.outputShape=e,this.enableShapeUniforms=bb(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?Zy(["r","c","d"],e):Jy(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));\n int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n ${t.output} = result;\n }\n `}}class xb{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=wy.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=Qy();this.outputShape=e,this.enableShapeUniforms=bb(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?Zy(["r","c","d"],e):Jy(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));\n int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n ${t.output} = result;\n }\n `}}class vb{constructor(e){this.variableNames=["A"],this.outTexUsage=Ty.DOWNLOAD;const t=Qy();this.outputShape=e,this.userCode=`\n ${tb}\n\n void main() {\n float x = getAAtOutCoords();\n ${t.output} = encode_float(x);\n }\n `}}class wb{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Ty.DOWNLOAD;const t=Qy();this.outputShape=e,this.userCode=`\n ${tb}\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n ${t.output} = encode_float(x);\n }\n `}}const Tb={R:0,G:1,B:2,A:3};class kb{constructor(e,t=!1,n="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const r=Qy();this.outputShape=e,this.enableShapeUniforms=bb(this.outputShape.length);let a="result";t&&(a="floor(result * 255. + 0.5)");let s="";for(let e=0;e<n.length;e++){const t=n[e];s+=`\n if(offset == ${e}) {\n result = values[${Tb[t]}];\n }`}this.userCode=`\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":eb(e)}\n\n void main() {\n ivec3 coords = getOutputCoords();\n int flatIndex = getFlatIndex(coords);\n float result = 0.;\n int offset = imod(flatIndex, ${n.length});\n\n flatIndex = idiv(flatIndex, ${n.length}, 1.);\n\n int r = flatIndex / texShape[1];\n if (r < texShape[0]) {\n int c = imod(flatIndex, texShape[1]);\n vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\n vec4 values = ${r.texture2D}(A, uv);\n ${s}\n }\n ${r.output} = vec4(${a}, 0., 0., 0.);\n }\n `}}class Ib{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=Qy();this.outputShape=e,this.enableShapeUniforms=bb(this.outputShape.length);let r="",a="result";t&&(a="floor(result * 255. + 0.5)");for(let t=0;t<=1;t++)for(let a=0;a<=1;a++){const s=2*t+a;r+=`\n localCoords = coords;\n if(localCoords[2] + ${a} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {\n localCoords[2] += ${a};\n if (localCoords[1] + ${t} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {\n localCoords[1] += ${t};\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n int r = flatIndex / texShape[1];\n int c = imod(flatIndex, texShape[1]);\n vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\n values = ${n.texture2D}(A, uv);\n\n if (offset == 0) {\n result[${s}] = values[0];\n } else if (offset == 1) {\n result[${s}] = values[1];\n } else if (offset == 2) {\n result[${s}] = values[2];\n } else {\n result[${s}] = values[3];\n }\n }\n }\n `}this.userCode=`\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":eb(e)}\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n\n ${r}\n\n ${n.output} = ${a};\n }\n `}}function Sb(e,t,n,r,a,s){!function(e,t){const n=Ct().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0)throw new Error(`Requested texture size [${e}x${t}] is invalid.`);if(e>n||t>n)throw new Error(`Requested texture size [${e}x${t}] greater than WebGL maximum on this browser / GPU [${n}x${n}].`)}(t,n);const o=function(e){return By(e,(()=>e.createTexture()),"Unable to create WebGLTexture.")}(e),i=e.TEXTURE_2D;return Cy(e,(()=>e.bindTexture(i,o))),Cy(e,(()=>e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE))),Cy(e,(()=>e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE))),Cy(e,(()=>e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST))),Cy(e,(()=>e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST))),1===Ct().getNumber("WEBGL_VERSION")?Cy(e,(()=>e.texImage2D(i,0,r,t,n,0,a,s,null))):Cy(e,(()=>e.texStorage2D(i,1,r,t,n))),Cy(e,(()=>e.bindTexture(e.TEXTURE_2D,null))),{texture:o,texShape:[n,t]}}function Eb(e){return e.internalFormatFloat}function Nb(e){return e.internalFormatHalfFloat}function Cb(e){return e.downloadTextureFormat}function Ab(e){return e.internalFormatPackedFloat}function Rb(e){return e.internalFormatPackedHalfFloat}class $b{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];const t=Ct().getNumber("WEBGL_VERSION");if(null!=e?(this.gl=e,function(e,t){_y[e]=t}(t,e)):this.gl=vy(t),e=this.gl,2===Ct().getNumber("WEBGL_VERSION")){const t=e;this.createVertexArray=()=>Cy(t,(()=>t.createVertexArray())),this.bindVertexArray=e=>Cy(t,(()=>t.bindVertexArray(e))),this.deleteVertexArray=e=>Cy(t,(()=>t.deleteVertexArray(e))),this.getVertexArray=()=>Cy(t,(()=>t.getParameter(t.VERTEX_ARRAY_BINDING)))}else if(null!=e){const t=e.getExtension("OES_vertex_array_object");if(null==t)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>Cy(e,(()=>t.createVertexArrayOES())),this.bindVertexArray=n=>Cy(e,(()=>t.bindVertexArrayOES(n))),this.deleteVertexArray=n=>Cy(e,(()=>t.deleteVertexArrayOES(n))),this.getVertexArray=()=>Cy(e,(()=>e.getParameter(t.VERTEX_ARRAY_BINDING_OES)))}let n="WEBGL_color_buffer_float";const r="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),1===Ct().getNumber("WEBGL_VERSION")){const e="OES_texture_float",t="OES_texture_half_float";if(this.textureFloatExtension=Ry(this.gl,e),Ky(this.gl,t))this.textureHalfFloatExtension=Ry(this.gl,t);else if(Ct().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Ky(this.gl,r))this.colorBufferHalfFloatExtension=Ry(this.gl,r);else if(Ct().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Ky(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!Ky(this.gl,r))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension(r)}this.vertexBuffer=function(e){return function(e,t){const n=By(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return Cy(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),Cy(e,(()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW))),n}(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}(this.gl),this.indexBuffer=function(e){return function(e,t){const n=By(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return Cy(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n))),Cy(e,(()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW))),n}(e,new Uint16Array([0,1,2,2,1,3]))}(this.gl),this.framebuffer=function(e){return By(e,(()=>e.createFramebuffer()),"Unable to create WebGLFramebuffer.")}(this.gl),this.textureConfig=Ny(this.gl,this.textureHalfFloatExtension)}get debug(){return Ct().getBool("DEBUG")}dispose(){if(this.disposed)return;null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");const e=this.gl;Cy(e,(()=>e.finish())),Cy(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,null))),Cy(e,(()=>e.deleteFramebuffer(this.framebuffer))),Cy(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,null))),Cy(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null))),Cy(e,(()=>e.deleteBuffer(this.indexBuffer))),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=Iy(t,n);return Sb(e,a,s,Eb(r),r.textureFormatFloat,e.FLOAT)}(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=Iy(t,n);return Sb(e,a,s,Nb(r),r.textureFormatFloat,r.textureTypeHalfFloat)}(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=Iy(t,n);return Sb(e,a,s,Cb(r),e.RGBA,e.UNSIGNED_BYTE)}(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),function(e,t,n){Cy(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),n.data instanceof Uint8Array?2===Ct().getNumber("WEBGL_VERSION")?Cy(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data))):Cy(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data))):2===Ct().getNumber("WEBGL_VERSION")?Cy(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n))):Cy(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n))),Cy(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,r){this.throwIfDisposed(),function(e,t,n,r,a,s){let o,i,u;Cy(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),a instanceof Uint8Array?(o=new Uint8Array(n*r*4),i=e.UNSIGNED_BYTE,u=e.RGBA):(o=new Float32Array(n*r*4),i=e.FLOAT,u=s.internalFormatPackedFloat),o.set(a),2===Ct().getNumber("WEBGL_VERSION")?Cy(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGBA,i,o))):Cy(e,(()=>e.texImage2D(e.TEXTURE_2D,0,u,n,r,0,e.RGBA,i,o))),Cy(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}(this.gl,e,t,n,r,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=Ey(t,n);return Sb(e,a,s,Rb(r),e.RGBA,r.textureTypeHalfFloat)}(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=Ey(t,n);return Sb(e,a,s,Ab(r),e.RGBA,e.FLOAT)}(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Ly(this.gl,this.framebuffer),this.outputTexture=null),Cy(this.gl,(()=>this.gl.deleteTexture(e)))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>function(e,t,n,r){const[a,s]=Iy(t,n),o=new Uint8Array(t*n*4);return Cy(e,(()=>e.readPixels(0,0,a,s,r.downloadTextureFormat,e.UNSIGNED_BYTE,o))),new Float32Array(o.buffer)}(this.gl,t,n,this.textureConfig)))}downloadPackedMatrixFromBuffer(e,t,n,r,a,s){return function(e,t,n,r,a,s,o,i){const u=e,l=new Float32Array(function(e,t){const[n,r]=Ey(e,t);return n*r*4}(s,o));return u.bindBuffer(u.PIXEL_PACK_BUFFER,t),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,l),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),l}(this.gl,e,0,0,0,a,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return function(e,t,n){const r=e,a=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,t),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,a),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),a}(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const r=function(e,t,n,r){const a=e.createBuffer();Cy(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,a)));const s=16*t*n;return Cy(e,(()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ))),Cy(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0))),Cy(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null))),a}(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(Ct().getBool("WEBGL_FENCE_API_ENABLED")){const r=e,a=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{const e=r.clientWaitSync(a,0,0);return e===r.ALREADY_SIGNALED||e===r.CONDITION_SATISFIED},t=a}else Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>function(e,t,n){const r=new Float32Array(t*n*4);return Cy(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,r))),r}(this.gl,t,n)))}createProgram(e){this.throwIfDisposed();const t=this.gl;null==this.vertexShader&&(this.vertexShader=function(e){const t=Qy();return function(e,t){const n=By(e,(()=>e.createShader(e.VERTEX_SHADER)),"Unable to create vertex WebGLShader.");if(Cy(e,(()=>e.shaderSource(n,t))),Cy(e,(()=>e.compileShader(n))),!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw console.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}(e,`${t.version}\n precision highp float;\n ${t.attribute} vec3 clipSpacePos;\n ${t.attribute} vec2 uv;\n ${t.varyingVs} vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }`)}(t));const n=function(e){return By(e,(()=>e.createProgram()),"Unable to create WebGLProgram.")}(t);let r;return Cy(t,(()=>t.attachShader(n,this.vertexShader))),Cy(t,(()=>t.attachShader(n,e))),function(e,t){if(Cy(e,(()=>e.linkProgram(t))),!Ct().get("ENGINE_COMPILE_ONLY")&&!1===e.getProgramParameter(t,e.LINK_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}(t,n),r=Object.assign(n,{vao:this.createVertexArray()}),this.bindVertexArray(r.vao),Cy(t,(()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer))),console.assert(function(e,t,n){return Cy(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),Oy(e,t,"clipSpacePos",n,3,20,0)&&Oy(e,t,"uv",n,2,20,12)}(t,r,this.vertexBuffer),"gpgpu_util.bindVertexProgramAttributeStreams not fully successful."),this.debug&&Fy(t,r),this.setProgram(r),r}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&(Cy(this.gl,(()=>this.gl.deleteProgram(e))),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,null!=this.program&&(this.bindVertexArray(this.program.vao),this.debug&&Fy(this.gl,this.program)),Cy(this.gl,(()=>this.gl.useProgram(e)))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?function(e,t,n){return By(e,(()=>e.getUniformLocation(t,n)),'uniform "'+n+'" not present in program.')}(this.gl,e,t):function(e,t,n){return e.getUniformLocation(t,n)}(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),Cy(this.gl,(()=>this.gl.getAttribLocation(e,t)))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),function(e,t,n,r){Cy(e,(()=>function(e,t,n){!function(e,t){const n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+e.TEXTURE0;if(r<e.TEXTURE0||r>n)throw new Error(`textureUnit must be in [gl.TEXTURE0, gl.TEXTURE${n}].`)}(e,n),Cy(e,(()=>e.activeTexture(e.TEXTURE0+n))),Cy(e,(()=>e.bindTexture(e.TEXTURE_2D,t)))}(e,t,r))),Cy(e,(()=>e.uniform1i(n,r)))}(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[r,a]=Ey(t,n);this.setOutputMatrixTextureDriver(e,r,a)}setOutputMatrixWriteRegion(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t)}setOutputPackedMatrixWriteRegion(e,t,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){null!=this.program&&Fy(this.gl,this.program),Py(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;if(this.debug){const e=this.getVertexArray();console.assert(e===this.program.vao,"VAO changed between setProgram and executeProgram!"),this.debugValidate()}Cy(e,(()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),Cy(this.gl,(()=>this.gl.finish()))}getQueryTimerExtension(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=Ry(this.gl,2===Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(2===Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}const e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(2===Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2();return void e.endQuery(t.TIME_ELAPSED_EXT)}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await st((()=>this.disposed||this.isQueryAvailable(e,Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")))),this.getQueryTime(e,Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(0===t)return null;if(2===t){const t=this.gl;return t.getQueryParameter(e,t.QUERY_RESULT)/1e6}{const t=this.getQueryTimerExtensionWebGL1();return t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(0===t)return!0;if(2===t){const t=this.gl,n=this.getQueryTimerExtensionWebGL2(),r=t.getQueryParameter(e,t.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),r&&!this.disjoint}{const t=this.getQueryTimerExtensionWebGL1(),n=t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(t.GPU_DISJOINT_EXT)),n&&!this.disjoint}}pollFence(e){return new Promise((t=>{this.addItemToPoll((()=>e.isFencePassed()),(()=>t()))}))}pollItems(){const e=function(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}(this.itemsToPoll.map((e=>e.isDoneFn)));for(let t=0;t<=e;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;let n;"setTimeoutCustom"in Ct().platform&&(n=Ct().platform.setTimeoutCustom.bind(Ct().platform)),st((()=>(this.pollItems(),0===this.itemsToPoll.length)),(()=>0),null,n)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),Dy(this.gl,e,this.framebuffer),this.debug&&Py(this.gl)}unbindTextureToFrameBuffer(){null!=this.outputTexture?(Dy(this.gl,this.outputTexture,this.framebuffer),this.debug&&Py(this.gl)):Ly(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();const r=this.gl;Dy(r,e,this.framebuffer),this.debug&&Py(r),this.outputTexture=e,Cy(r,(()=>r.viewport(0,0,t,n))),Cy(r,(()=>r.scissor(0,0,t,n)))}setOutputMatrixWriteRegionDriver(e,t,n,r){this.throwIfDisposed(),Cy(this.gl,(()=>this.gl.scissor(e,t,n,r)))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(null==this.program)throw new Error("No GPU program is currently set.")}}const{addImpl:Mb,bincountImpl:Fb,bincountReduceImpl:Ob,castImpl:Db,ceilImpl:Lb,concatImpl:Pb,equalImpl:Bb,expImpl:Ub,expm1Impl:zb,floorImpl:Vb,gatherNdImpl:Wb,gatherV2Impl:Hb,greaterImpl:Gb,greaterEqualImpl:jb,lessImpl:Kb,lessEqualImpl:qb,linSpaceImpl:Xb,logImpl:Yb,maxImpl:Qb,maximumImpl:Jb,minimumImpl:Zb,multiplyImpl:e_,negImpl:t_,notEqualImpl:n_,prodImpl:r_,raggedGatherImpl:a_,raggedRangeImpl:s_,raggedTensorToTensorImpl:o_,rangeImpl:i_,rsqrtImpl:u_,scatterImpl:l_,sigmoidImpl:c_,simpleAbsImpl:p_,sliceImpl:h_,sparseFillEmptyRowsImpl:d_,sparseReshapeImpl:f_,sparseSegmentReductionImpl:m_,sqrtImpl:g_,stridedSliceImpl:y_,stringNGramsImpl:b_,stringSplitImpl:__,stringToHashBucketFastImpl:x_,subImpl:v_,tileImpl:w_,topKImpl:T_,transposeImpl:k_,uniqueImpl:I_}=Mg;function S_(e,t){return["x","y","z","w","u","v"].slice(0,t).map((t=>`${e}.${t}`))}function E_(e,t){return 1===t?[e]:S_(e,t)}class N_{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=bb(this.outputShape.length),0===this.rank)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{const e=E_("rc",this.rank),t=hb(this.rank),n=this.getOutOfBoundsCondition(e),r=this.getSetup(e),a=this.getOutput(e);this.userCode=`\n void main() {\n ${t} rc = getOutputCoords();\n\n if(${n}) {\n setOutput(vec4(0));\n } else {\n ${r}\n\n setOutput(vec4(${a}));\n }\n }\n `}}getSourceCoordsArr(e){const t=[];for(let n=0;n<=1;n++)for(let r=0;r<=1;r++){let a=`${0===n?"r":"rp1"}, ${0===r?"c":"cp1"}`;for(let t=2;t<this.rank;t++)a=`${e[e.length-1-t]},`+a;t.push(a)}return t}getOutOfBoundsCondition(e){if(1===this.rank)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let n=this.rank-2;n<this.rank;n++)t+=`${e[n]} >= ${this.enableShapeUniforms?`outShape[${n}]`:this.outputShape[n]}`,n<this.rank-1&&(t+="||");return t}getSetup(e){if(1===this.rank)return"";const t=e.slice(-2),n=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],r=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`\n int r = ${t[0]};\n int c = ${t[1]};\n int rp1 = r + 1;\n int cp1 = c + 1;\n\n bool cEdge = cp1 >= ${n};\n bool rEdge = rp1 >= ${r};\n `}getOutput(e){const t=this.getSourceCoordsArr(e);return 1===this.rank?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${t[0]}),\n cEdge ? 0. : getA(${t[1]}),\n rEdge ? 0. : getA(${t[2]}),\n rEdge || cEdge ? 0. : getA(${t[3]})`}}class C_{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=bb(this.outputShape.length);let n="";for(let e=0;e<4;e++){let t="thisRC = rc;";e%2==1&&(t+="thisRC.z += 1;"),e>1&&(t+="thisRC.y += 1;"),n+=`\n ${t}\n ${e>0?"if(thisRC.y < rows && thisRC.z < cols){":""}\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result[${e}] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n ${e>0?"}":""}\n `}var r,a;this.userCode=`\n ${r=t,a=this.enableShapeUniforms,`\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n ${a?function(e,t,n="index"){const r=e.map(((e,t)=>t)),a=function(e,t){const n=e.length,r=e.map((e=>`${t}[${e}]`)),a=new Array(n-1);a[n-2]=r[n-1];for(let e=n-3;e>=0;--e)a[e]=`(${a[e+1]} * ${r[e+1]})`;return a}(r,t);return a.map(((t,r)=>`int ${e[r]} = ${n} / ${a[r]}; ${r===a.length-1?`int ${e[r+1]} = ${n} - ${e[r]} * ${a[r]}`:`index -= ${e[r]} * ${a[r]}`};`)).join("")}(["r","c","d"],"inputShape"):Jy(["r","c","d"],r)}\n return ivec3(r, c, d);\n }\n `}\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":eb(e)}\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]};\n int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]};\n\n ${n}\n\n setOutput(result);\n }\n `}}class A_{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,n){const r=$_(t,n),a=M_(e,r,n);a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]);const s=R_(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=s,this.log();const e=this.freeTextures[a].shift();return this.usedTextures[a].push(e),e}let o;return r===ky.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===ky.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===ky.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===ky.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===ky.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[a].push(o),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),o}releaseTexture(e,t,n,r){if(null==this.freeTextures)return;const a=$_(n,r),s=M_(t,a,r);s in this.freeTextures||(this.freeTextures[s]=[]);const o=R_(t,a,this.gpgpu.gl,this.gpgpu.textureConfig,r),i=Ct().get("WEBGL_DELETE_TEXTURE_THRESHOLD");-1!==i&&this._numBytesAllocated>i?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=o):(this.freeTextures[s].push(e),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;const u=this.usedTextures[s],l=u.indexOf(e);if(l<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u.splice(l,1),this.log()}log(){if(!this.logEnabled)return;const e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(null!=this.freeTextures){for(const e in this.freeTextures)this.freeTextures[e].forEach((e=>{this.gpgpu.deleteMatrixTexture(e.texture)}));for(const e in this.usedTextures)this.usedTextures[e].forEach((e=>{this.gpgpu.deleteMatrixTexture(e.texture)}));this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}}function R_(e,t,n,r,a){const s=function(e,t){switch(e){case ky.PACKED_2X2_FLOAT32:return Ab(t);case ky.PACKED_2X2_FLOAT16:return Rb(t);case ky.UNPACKED_FLOAT32:return Eb(t);case ky.UNPACKED_FLOAT16:return Nb(t);case ky.PACKED_4X1_UNSIGNED_BYTE:return Cb(t);default:throw new Error(`Unknown physical texture type ${e}`)}}(t,r);let o;if(a){const[t,n]=Ey(e[0],e[1]);o=t*n}else{const[t,n]=Iy(e[0],e[1]);o=t*n}const i=function(e,t){const n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;if(t===n.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}(n,s);return o*i}function $_(e,t){if(e===Ty.UPLOAD)return ky.PACKED_2X2_FLOAT32;if(e===Ty.RENDER||null==e)return function(e){return Ct().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?ky.PACKED_2X2_FLOAT32:ky.UNPACKED_FLOAT32:e?ky.PACKED_2X2_FLOAT16:ky.UNPACKED_FLOAT16}(t);if(e===Ty.DOWNLOAD||e===Ty.PIXELS)return ky.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function M_(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class F_{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=bb(this.outputShape.length),this.userCode=`\n float unaryOperation(float x) {\n ${t}\n }\n\n void main() {\n float x = getAAtOutCoords();\n float y = unaryOperation(x);\n\n setOutput(y);\n }\n `}}const O_="if (isnan(x)) return x;",D_="return x;",L_="return abs(x);",P_="return (x >= 0.0) ? x : (exp(x) - 1.0);",B_=O_+"\n return (x < 0.0) ? 0.0 : x;\n",U_=O_+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",z_="return x;",V_="return 1.0 / (1.0 + exp(-1.0 * x));",W_="return x;",H_="\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n",G_="\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",j_="\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",K_="return 1.0 / (1.0 + exp(-1.0 * x));";class q_{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=bb(this.outputShape.length),this.userCode=`\n vec4 unaryOperation(vec4 x) {\n ${t}\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n `}}class X_{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=bb(this.outputShape.length);const t=e.length,n=E_("rc",t),r=hb(t),a=function(e,t){if(1===e)return"rc";let n="";for(let r=0;r<e;r++)n+=t[r],r<e-1&&(n+=",");return n}(t,n),s=n.slice(-2),o=t<=1?"rc":`vec2(${s.join(",")})`;this.userCode=`\n void main() {\n ${r} rc = getOutputCoords();\n vec4 packedInput = getA(${a});\n\n setOutput(getChannel(packedInput, ${o}));\n }\n `}}const Y_=nh,Q_={},J_=Ct().getNumber("CPU_HANDOFF_SIZE_THRESHOLD");class Z_ extends je{constructor(e){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!Ct().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(null!=e){if(e instanceof $b)t=e;else{const n=vy(Ct().getNumber("WEBGL_VERSION"),e);t=new $b(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{const e=vy(Ct().getNumber("WEBGL_VERSION"));t=new $b(e),this.binaryCache=((n=Ct().getNumber("WEBGL_VERSION"))in Q_||(Q_[n]={}),Q_[n]),this.gpgpuCreatedLocally=!0}var n;this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new A_(this.gpgpu),this.numMBBeforeWarning=null==Ct().global.screen?1024:Ct().global.screen.height*Ct().global.screen.width*window.devicePixelRatio*600/1024/1024,this.texData=new Ge(this,vi())}nextDataId(){return Z_.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(e,t,n,r,a,s){const o=this.makeTensorInfo(t,n),i=this.texData.get(o.dataId);i.isPacked=!1,i.texture={texture:e,texShape:[r,a]},i.texShape=[r,a];const u=Vy(t),l=new kb(u,!1,s),c=this.runWebGLProgram(l,[o],n,[[r,a]]);return c.shape=t,i.texture=null,this.disposeIntermediateTensorInfo(o),c.dataId}write(e,t,n){if((Ct().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||Ct().getBool("DEBUG"))&&this.checkNumericalProblems(e),"complex64"===n&&null!=e)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const r={id:this.nextDataId()};return this.texData.set(r,{shape:t,dtype:n,values:e,usage:Ty.UPLOAD,refCount:1}),r}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){this.texData.get(e).refCount++}decRef(e){this.texData.has(e)&&this.texData.get(e).refCount--}move(e,t,n,r,a){if(Ct().getBool("DEBUG")&&this.checkNumericalProblems(t),"complex64"===r)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:r,values:t,usage:Ty.UPLOAD,refCount:a})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){const t=this.texData.get(e),{values:n,dtype:r,complexTensorInfos:a,slice:s,shape:o,isPacked:i}=t;if(null!=s){let t;t=i?new q_(o,z_):new F_(o,z_);const n=this.runWebGLProgram(t,[{dataId:e,shape:o,dtype:r}],r),a=this.readSync(n.dataId);return this.disposeIntermediateTensorInfo(n),a}if(null!=n)return this.convertAndCacheOnCPU(e);if("string"===r)return n;const u=null!=this.activeTimers;let l,c;return u&&(l=Ta()),c="complex64"===r?$d(this.readSync(a.real.dataId),this.readSync(a.imag.dataId)):this.getValuesFromTexture(e),u&&(this.downloadWaitMs+=Ta()-l),this.convertAndCacheOnCPU(e,c)}async read(e){if(this.pendingRead.has(e)){const t=this.pendingRead.get(e);return new Promise((e=>t.push(e)))}const t=this.texData.get(e),{values:n,shape:r,slice:a,dtype:s,complexTensorInfos:o,isPacked:i}=t;if(null!=a){let t;t=i?new q_(r,z_):new F_(r,z_);const n=this.runWebGLProgram(t,[{dataId:e,shape:r,dtype:s}],s),a=this.read(n.dataId);return this.disposeIntermediateTensorInfo(n),a}if(null!=n)return this.convertAndCacheOnCPU(e);if(Ct().getBool("DEBUG")&&!Ct().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===Ct().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let u,l,c=null;if("complex64"!==s&&Ct().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);const t=this.texData.get(u.dataId);c=this.gpgpu.createBufferFromTexture(t.texture.texture,...Sy(r))}if(this.pendingRead.set(e,[]),"complex64"!==s&&await this.gpgpu.createAndWaitForFence(),"complex64"===s){const e=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]);l=$d(e[0],e[1])}else if(null==c)l=this.getValuesFromTexture(e);else{const e=et(r);l=this.gpgpu.downloadFloat32MatrixFromBuffer(c,e)}if(null!=u&&this.disposeIntermediateTensorInfo(u),null!=c){const e=this.gpgpu.gl;Cy(e,(()=>e.deleteBuffer(c)))}const p=this.convertAndCacheOnCPU(e,l),h=this.pendingRead.get(e);return this.pendingRead.delete(e),h.forEach((e=>e(p))),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&vi().removeDataId(e,this),this.pendingDeletes--),p}readToGPU(e,t={}){const n=this.texData.get(e),{values:r,shape:a,slice:s,dtype:o,isPacked:i,texture:u}=n;if("complex64"===o)throw new Error("Does not support reading texture for complex64 dtype.");if(null!=s){let n;n=i?new q_(a,z_):new F_(a,z_);const r=this.runWebGLProgram(n,[{dataId:e,shape:a,dtype:o}],o),s=this.readToGPU(r,t);return this.disposeIntermediateTensorInfo(r),s}if(null==u)throw null!=r?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");const l=this.decode(e,t.customTexShape),c=vi().makeTensorFromTensorInfo(l),p=this.texData.get(l.dataId);return Object.assign({tensorRef:c},p.texture)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map((e=>Ia(e)));return Qu(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Qu(e.shape,e.dtype,t)}checkNumericalProblems(e){if(null!=e)for(let t=0;t<e.length;t++){const n=e[t];if(!Ay(n)){if(Ct().getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))throw Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`);throw Error(`The value ${n} cannot be represented on this device.`)}}}getValuesFromTexture(e){const{shape:t,dtype:n,isPacked:r}=this.texData.get(e),a=et(t);if(Ct().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const n=this.decode(e),r=this.texData.get(n.dataId),s=this.gpgpu.downloadMatrixFromPackedTexture(r.texture.texture,...Sy(t)).subarray(0,a);return this.disposeIntermediateTensorInfo(n),s}const s=Ct().getBool("WEBGL_PACK")&&!0===r,o=s?Vy(t):t,i=s?new wb(o):new vb(o),u=this.runWebGLProgram(i,[{shape:o,dtype:n,dataId:e}],"float32"),l=this.texData.get(u.dataId),c=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(l.texture.texture,l.texShape[0],l.texShape[1]).subarray(0,a);return this.disposeIntermediateTensorInfo(u),c}timerAvailable(){return Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(e){const t=this.activeTimers,n=[];let r=!1;null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e();const a=Ea(this.activeTimers.map((e=>e.query))).filter((e=>null!=e)),s=Ea(this.activeTimers.map((e=>e.name))).filter((e=>null!=e));this.activeTimers=t,r&&(this.programTimersStack=null);const o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const e=await Promise.all(a);o.kernelMs=function(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}(e),o.getExtraProfileInfo=()=>e.map(((e,t)=>({name:s[t],ms:e}))).map((e=>`${e.name}: ${e.ms}`)).join(", ")}else o.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,o})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:Ta(),endMs:null}}endTimer(e){return Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=Ta(),e)}async getQueryTime(e){if(Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);const t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);const{complexTensorInfos:n}=this.texData.get(e);return null!=n&&(this.disposeData(n.real.dataId,t),this.disposeData(n.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){const{texture:t,dtype:n,texShape:r,usage:a,isPacked:s,slice:o}=this.texData.get(e),i=o&&o.origDataId||e,u=this.dataRefCount.get(i);u>1?this.dataRefCount.set(i,u-1):(this.dataRefCount.delete(i),null!=t&&(this.numBytesInGPU-=this.computeBytes(r,n),this.textureManager.releaseTexture(t,r,a,s)));const l=this.texData.get(e);l.texture=null,l.texShape=null,l.isPacked=!1,l.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=J_){return Ct().getBool("WEBGL_CPU_FORWARD")&&e.every((e=>null==this.texData.get(e.dataId).texture&&et(e.shape)<t))}getGPGPUContext(){return this.gpgpu}where(e){Cr("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return Y_(e.shape,t)}packedUnaryOp(e,t,n){const r=new q_(e.shape,t),a=this.compileAndRun(r,[e],n);return vi().makeTensorFromTensorInfo(a)}abs(e){if(this.shouldExecuteOnCPU([e])&&"complex64"!==e.dtype){const t=p_(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,t)}if(Ct().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,L_,e.dtype);const t=new F_(e.shape,L_),n=this.compileAndRun(t,[e]);return vi().makeTensorFromTensorInfo(n)}makeTensorInfo(e,t,n){let r;if("string"===t&&null!=n&&n.length>0&&dt(n[0])){const a=n.map((e=>ka(e)));r=this.write(a,e,t)}else r=this.write(n,e,t);return this.texData.get(r).usage=null,{dataId:r,shape:e,dtype:t}}makeOutput(e,t,n){return vi().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,n),this)}unpackTensor(e){const t=new X_(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new N_(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const n=[Uy(e.shape),...zy(e.shape)],r={dtype:e.dtype,shape:n,dataId:e.dataId},a=[Uy(t),...zy(t)],s=new C_(a,n),o=[n],i=this.runWebGLProgram(s,[r],e.dtype,o,!0);return{dataId:i.dataId,shape:t,dtype:i.dtype}}decode(e,t){const n=this.texData.get(e),{isPacked:r,shape:a,dtype:s}=n;null!=t&&Qe(et(a)<=t[0]*t[1]*4,(()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data."));const o=Vy(a);let i;i=r?new xb(o):new _b(o);const u=[null!=t?t:Sy(o)];return{dtype:s,shape:a,dataId:this.runWebGLProgram(i,[{shape:o,dtype:s,dataId:e}],s,u,!0,t).dataId}}runWebGLProgram(e,t,n,r,a=!1,s){const o=this.makeTensorInfo(e.outputShape,n),i=this.texData.get(o.dataId);if(e.packedOutput&&(i.isPacked=!0),e.outPackingScheme===wy.DENSE){const t=null!=s?s:Sy(e.outputShape);i.texShape=t.map((e=>2*e))}if(null!=e.outTexUsage&&(i.usage=e.outTexUsage),0===et(o.shape))return i.values=lt(o.dtype,0),o;const u=[],l=t.map((t=>{if("complex64"===t.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let n=this.texData.get(t.dataId);if(null==n.texture){if(!e.packedInputs&&et(t.shape)<=Ct().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:t.shape,texData:null,isUniform:!0,uniformValues:n.values};e.packedInputs&&(n.isPacked=!0,n.shape=t.shape)}if(this.uploadToGPU(t.dataId),!!n.isPacked!=!!e.packedInputs)t=n.isPacked?this.unpackTensor(t):this.packTensor(t),u.push(t),n=this.texData.get(t.dataId);else if(n.isPacked&&!Hy(n.shape,t.shape)){const e=t,r=t.shape;t.shape=n.shape,t=this.packedReshape(t,r),u.push(t),n=this.texData.get(t.dataId),e.shape=r}return{shape:t.shape,texData:n,isUniform:!1}}));this.uploadToGPU(o.dataId);const c={shape:o.shape,texData:i,isUniform:!1},p=function(e,t,n){let r="";t.concat(n).forEach((t=>{const a=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!t.isUniform){const s=t.texData.texShape,{useSqueezeShape:o,uniformShape:i,keptDims:u}=db(e.packedInputs,t.shape,s);let l="",c="",p="";if(1===i.length&&e.packedInputs){const e=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];l=`${e[0]>1}_${e[1]>1}`}else if(2!==i.length||e.packedInputs){if(i.length>2&&!e.packedInputs){const e=yt(i);p=`${e[0]===s[1]}_${e[e.length-1]===s[1]}`}}else c=`${i[0]>1}_${i[1]>1}`;const h=t.shape.length,d=2===i.length&&tt(t.shape,s),f=1===et(t.shape),m=$i(t.shape,n.shape),g=!e.packedInputs&&h===n.shape.length&&tt(s,n.texData.texShape),y=e.packedInputs||i.length>2?"":`${s[0]>1}_${s[1]>1}`;r+=`${h}_${g}_${o?u:""}_${i.length}_${f}_${m}_${d}_${l}_${c}_${p}_${y}_${a}`}else{const e=t.isUniform?"uniform":t.texData.texShape;r+=`${t.shape}_${e}_${a}`}}));const a=e.userCode;let s=e.constructor.name;return s+="_"+r+"_"+a+`${Ct().getNumber("WEBGL_VERSION")}`,s}(e,l,c),h=this.getAndSaveBinary(p,(()=>function(e,t,n,r){const a=n.map(((e,n)=>{const r={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.isPacked,flatOffset:null};return null!=e.texData&&null!=e.texData.slice&&e.texData.slice.flatOffset>0&&(r.flatOffset=e.texData.slice.flatOffset),{name:t.variableNames[n],shapeInfo:r}})),s=a.map((e=>e.shapeInfo)),o={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},i=rb(a,o,t),u=function(e,t){const n=By(e,(()=>e.createShader(e.FRAGMENT_SHADER)),"Unable to create fragment WebGLShader.");if(Cy(e,(()=>e.shaderSource(n,t))),Cy(e,(()=>e.compileShader(n))),Ct().get("ENGINE_COMPILE_ONLY"))return n;if(!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw My(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}(e.gl,i),l=e.createProgram(u);return Ct().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:u,source:i,webGLProgram:l,inShapeInfos:s,outShapeInfo:o,uniformLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,inShapesLocations:null,inTexShapesLocations:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:Object.assign({program:t,fragmentShader:u,source:i,webGLProgram:l,inShapeInfos:s,outShapeInfo:o},gb(e,t,l))}(this.gpgpu,e,l,c))),d=null!=this.activeTimers;let f;d&&(f=this.startTimer()),Ct().get("ENGINE_COMPILE_ONLY")||function(e,t,n,r,a){t.program.enableShapeUniforms||(yb(t.inShapeInfos,n),yb([t.outShapeInfo],[r]));const s=r.texData.texture,o=r.texData.texShape;r.texData.isPacked?e.setOutputPackedMatrixTexture(s.texture,o[0],o[1]):e.setOutputMatrixTexture(s.texture,o[0],o[1]),e.setProgram(t.webGLProgram),1===Ct().getNumber("WEBGL_VERSION")&&null!==t.infLoc&&e.gl.uniform1f(t.infLoc,1/0),null!==t.nanLoc&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach(((n,r)=>{const a=t.program.variableNames[r],s=t.uniformLocations[a],o=t.uniformLocations[`offset${a}`],i=t.inShapesLocations[`${a}Shape`],u=t.inTexShapesLocations[`${a}TexShape`];if(i){const{uniformShape:r}=db(t.program.packedInputs,n.shape,n.texData.texShape);switch(r.length){case 1:e.gl.uniform1iv(i,new Int32Array(r));break;case 2:e.gl.uniform2iv(i,new Int32Array(r));break;case 3:e.gl.uniform3iv(i,new Int32Array(r));break;case 4:e.gl.uniform4iv(i,new Int32Array(r))}}if(u&&e.gl.uniform2i(u,n.texData.texShape[0],n.texData.texShape[1]),null!=s)if(n.isUniform)if(et(n.shape)<2)e.gl.uniform1f(s,n.uniformValues[0]);else{let t=n.uniformValues;t instanceof Float32Array||(t=new Float32Array(t)),e.gl.uniform1fv(s,t)}else null!=n.texData.slice&&null!=o&&e.gl.uniform1i(o,n.texData.slice.flatOffset),e.setInputMatrixTexture(n.texData.texture.texture,s,r)}));const i=t.outShapeLocation;if(i)switch(r.shape.length){case 1:e.gl.uniform1iv(i,new Int32Array(r.shape));break;case 2:e.gl.uniform2iv(i,new Int32Array(r.shape));break;case 3:e.gl.uniform3iv(i,new Int32Array(r.shape));break;case 4:e.gl.uniform4iv(i,new Int32Array(r.shape))}if(t.outShapeStridesLocation){const n=yt(r.shape);switch(r.shape.length){case 2:e.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(n));break;case 3:e.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(n));break;case 4:e.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(n))}}t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,r.texData.texShape[0],r.texData.texShape[1]),t.program.customUniforms&&a&&t.program.customUniforms.forEach(((n,r)=>{const s=t.customUniformLocations[r],o=a[r];if("float"===n.type)e.gl.uniform1fv(s,o);else if("vec2"===n.type)e.gl.uniform2fv(s,o);else if("vec3"===n.type)e.gl.uniform3fv(s,o);else if("vec4"===n.type)e.gl.uniform4fv(s,o);else if("int"===n.type)e.gl.uniform1iv(s,o);else if("ivec2"===n.type)e.gl.uniform2iv(s,o);else if("ivec3"===n.type)e.gl.uniform3iv(s,o);else{if("ivec4"!==n.type)throw Error(`uniform type ${n.type} is not supported yet.`);e.gl.uniform4iv(s,o)}})),e.executeProgram()}(this.gpgpu,h,l,c,r),u.forEach((e=>this.disposeIntermediateTensorInfo(e))),d&&(f=this.endTimer(f),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(f)}));const m=Ct().get("WEBGL_FLUSH_THRESHOLD");if(m>0){const e=Ta();e-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=e)}if(!Ct().getBool("WEBGL_LAZILY_UNPACK")&&i.isPacked&&!1===a){const e=this.unpackTensor(o);return this.disposeIntermediateTensorInfo(o),e}return o}compileAndRun(e,t,n,r,a=!1){return n=n||t[0].dtype,this.runWebGLProgram(e,t,n,r,a)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(Ct().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach((e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]})),this.textureManager.dispose(),null!=this.canvas&&"undefined"!=typeof HTMLCanvasElement&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return null==this.floatPrecisionValue&&(this.floatPrecisionValue=wi((()=>{if(!Ct().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=Ct().getBool("DEBUG");Ct().set("DEBUG",!1);const t=this.abs(Ul(1e-8)).dataSync()[0];if(Ct().set("DEBUG",e),t>0)return 32}return 16}))),this.floatPrecisionValue}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}uploadToGPU(e){const t=this.texData.get(e),{shape:n,dtype:r,values:a,texture:s,usage:o,isPacked:i}=t;if(null!=s)return;const u=null!=this.activeTimers;let l;u&&(l=Ta());let c=t.texShape;if(null==c&&(c=function(e,t=!1){let n=Ct().getNumber("WEBGL_MAX_TEXTURE_SIZE"),r=Ct().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");if(r===1/0&&Ct().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(r=n/2),t&&(n*=2,r*=2,e=e.map(((t,n)=>n>=e.length-2?Xe(e[n]):e[n])),1===e.length&&(e=[2,e[0]])),2!==e.length){const t=ut(e);e=t.newShape}let a=et(e),s=null;e.length<=1&&a<=n?s=[1,a]:2===e.length&&e[0]<=n&&e[1]<=n?s=e:3===e.length&&e[0]*e[1]<=n&&e[2]<=n?s=[e[0]*e[1],e[2]]:3===e.length&&e[0]<=n&&e[1]*e[2]<=n?s=[e[0],e[1]*e[2]]:4===e.length&&e[0]*e[1]*e[2]<=n&&e[3]<=n?s=[e[0]*e[1]*e[2],e[3]]:4===e.length&&e[0]<=n&&e[1]*e[2]*e[3]<=n&&(s=[e[0],e[1]*e[2]*e[3]]);const o=null!=s&&Math.max(...s)>r&&Math.min(...s)<=(t?2:1)&&Math.min(...s)>0;if(null==s||o)if(t){const t=Uy(e);let n=2,r=2;e.length&&([n,r]=zy(e)),a=t*(n/2)*(r/2),s=rt(a).map((e=>2*e))}else s=rt(a);return s}(n,i),t.texShape=c),null!=a){const e=Vy(n);let s,o=c[1],p=c[0];const h=a instanceof Uint8Array||a instanceof Uint8ClampedArray;!i&&h||([o,p]=Ey(c[0],c[1])),s=i?new Ib(e,h):new kb(e,h);const d=h?[p,o]:c,f=this.makeTensorInfo(d,r),m=this.texData.get(f.dataId);m.usage=h?Ty.PIXELS:Ty.UPLOAD,m.texShape=d,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(f.dataId),o,p,a);const g=[[p,o]],y=!0,b=this.runWebGLProgram(s,[f],r,g,y),_=this.texData.get(b.dataId);t.texShape=_.texShape,t.isPacked=_.isPacked,t.usage=_.usage,Ct().get("ENGINE_COMPILE_ONLY")?this.disposeData(b.dataId):(t.texture=_.texture,t.values=null,this.texData.delete(b.dataId)),this.disposeIntermediateTensorInfo(f),u&&(this.uploadWaitMs+=Ta()-l)}else{const e=this.acquireTexture(c,o,r,i);t.texture=e}}convertAndCacheOnCPU(e,t){const n=this.texData.get(e),{dtype:r}=n;return null!=t&&(n.values=function(e,t){if("float32"===t||"complex64"===t)return e;if("int32"===t||"bool"===t){const n="int32"===t?new Int32Array(e.length):new Uint8Array(e.length);for(let t=0;t<n.length;++t)n[t]=Math.round(e[t]);return n}throw new Error(`Unknown dtype ${t}`)}(t,r)),n.values}acquireTexture(e,t,n,r){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){const e=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${e} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,r)}computeBytes(e,t){return e[0]*e[1]*ht(t)}checkCompileCompletion(){for(const[,e]of Object.entries(this.binaryCache))this.checkCompletion_(e)}async checkCompileCompletionAsync(){const e=[];if(this.gpgpu.parallelCompilationExtension){for(const[,t]of Object.entries(this.binaryCache))e.push(this.checkCompletionAsync_(t));return Promise.all(e)}for(const[,t]of Object.entries(this.binaryCache)){const n=new Promise((e=>{try{this.checkCompletion_(t),e(!0)}catch(e){throw e}}));e.push(n)}return Promise.all(e)}async checkCompletionAsync_(e){return this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(e):(await new Promise((e=>gd((()=>e())))),this.checkCompletionAsync_(e))}checkCompletion_(e){if(!1===this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.gl.LINK_STATUS)){if(console.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram)),!1===this.gpgpu.gl.getShaderParameter(e.fragmentShader,this.gpgpu.gl.COMPILE_STATUS))throw My(e.source,this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)),new Error("Failed to compile fragment shader.");throw new Error("Failed to link vertex and fragment shaders.")}return!0}getUniformLocations(){for(const[,e]of Object.entries(this.binaryCache)){const{uniformLocations:t,customUniformLocations:n,infLoc:r,nanLoc:a,inShapesLocations:s,inTexShapesLocations:o,outShapeLocation:i,outShapeStridesLocation:u,outTexShapeLocation:l}=gb(this.gpgpu,e.program,e.webGLProgram);e.uniformLocations=t,e.customUniformLocations=n,e.infLoc=r,e.nanLoc=a,e.inShapesLocations=s,e.inTexShapesLocations=o,e.outShapeLocation=i,e.outShapeStridesLocation=u,e.outTexShapeLocation=l}}createTensorFromGPUData(e,t,n){e.channels=e.channels||"RGBA";const{texture:r,height:a,width:s,channels:o}=e,i=vi().backend;if(!i.gpgpu.gl.isTexture(r))throw new Error("The texture is invalid. Also, please make sure the texture and the TFJS WebGL backend are using the same canvas. If you want to use your own custom canvas, you have to create and use the custom TFJS WebGL backend created from the canvas through 'new tf.MathBackendWebGL(customCanvas)'.");const u=i.writeTexture(r,t,n,a,s,o);return vi().makeTensorFromDataId(u,t,n,i)}}Z_.nextDataId=0,is()&&Ei("webgl",(()=>new Z_),2);class ex{constructor(e){this.variableNames=["A"];const t=Qy(),[n,r]=e;this.outputShape=e,this.userCode=`\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}.0, ${n}.0);\n\n vec4 values = ${t.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n `}}class tx{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=Qy(),[n,r]=e;this.outputShape=e,this.userCode=`\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${r}.0, ${n}.0);\n vec4 values = ${t.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n ${t.output} = result;\n }\n `}}const nx={kernelName:kr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e;let{pixels:a}=t;const{numChannels:s}=r,o="undefined"!=typeof HTMLVideoElement&&a instanceof HTMLVideoElement,i="undefined"!=typeof HTMLImageElement&&a instanceof HTMLImageElement,[u,l]=o?[a.videoWidth,a.videoHeight]:[a.width,a.height],c=[l,u],p=[l,u,s];if(i||o){const e=Ct().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");null!=rx&&e===ax||(ax=e,rx=document.createElement("canvas").getContext("2d",{willReadFrequently:ax})),rx.canvas.width=u,rx.canvas.height=l,rx.drawImage(a,0,0,u,l),a=rx.canvas}const h=n.makeTensorInfo(c,"int32");n.texData.get(h.dataId).usage=Ty.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(h.dataId),a);const d=Ct().getBool("WEBGL_PACK")?new tx(p):new ex(p),f=n.runWebGLProgram(d,[h],"int32");return n.disposeData(h.dataId),f}};let rx,ax=Ct().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function sx(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{shape:s}=r,o=n,i=et(a.shape),u=ot(s,i),l=et(u);Qe(i===l,(()=>`The new shape (${u}) has ${l} elements and the old shape (${a.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`));const c=o.texData.get(a.dataId);return!c.isPacked||Hy(a.shape,u)||null!==c.texture&&Hy(c.shape,u)?(o.incRef(a.dataId),{dataId:a.dataId,shape:u,dtype:a.dtype}):function(e,t,n){const r=[Uy(e.shape),...zy(e.shape)],a={dtype:e.dtype,shape:r,dataId:e.dataId},s=[Uy(t),...zy(t)],o=new C_(s,r),i=[r],u=n.runWebGLProgram(o,[a],e.dtype,i,!0);return{dataId:u.dataId,shape:t,dtype:u.dtype}}(a,u,o)}const ox={kernelName:Hn,backendName:"webgl",kernelFunc:sx};function ix(e){const{inputs:t,attrs:n,backend:r}=e,{dim:a}=n,{input:s}=t,o=s.shape.length,i=s.shape.slice();let u=a;return a<0&&(Qe(-(o+1)<=a,(()=>`Axis must be in the interval [${-(o+1)}, ${o}]`)),u=o+a+1),i.splice(u,0,1),sx({inputs:{x:s},backend:r,attrs:{shape:i}})}const ux={kernelName:an,backendName:"webgl",kernelFunc:ix};class lx{constructor(e,t,n,r,a){this.variableNames=["A"],this.outputShape=[];const[s,o,i,u]=e;this.outputShape=[s,t,n,u];const l=[r&&t>1?o-1:o,r&&n>1?i-1:i],c=[r&&t>1?t-1:t,r&&n>1?n-1:n];let p;p=a?"(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${l[0]/c[0]},\n ${l[1]/c[1]});\n const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = ${p};\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n `}}class cx{constructor(e,t,n,r,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[s,o,i,u]=e;this.outputShape=[s,t,n,u];const l=[r&&t>1?o-1:o,r&&n>1?i-1:i],c=[r&&t>1?t-1:t,r&&n>1?n-1:n];let p;p=a?"(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${l[0]/c[0]},\n ${l[1]/c[1]},\n ${l[1]/c[1]});\n const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,\n ${i}.0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = ${p};\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < ${u-1};\n bool hasNextRow = coords.z < ${n-1};\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n `}}const px={kernelName:jn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:o,size:i}=r,[u,l]=i,c=Ct().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new cx(a.shape,u,l,s,o):new lx(a.shape,u,l,s,o);return n.runWebGLProgram(c,[a],"float32")}};function hx(e){const{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}const dx={kernelName:mn,backendName:"webgl",kernelFunc:hx};function fx(e){const{inputs:t,backend:n}=e,{real:r,imag:a}=t,s=n.makeTensorInfo(r.shape,"complex64"),o=n.texData.get(s.dataId),i=hx({inputs:{x:r},backend:n}),u=hx({inputs:{x:a},backend:n});return o.complexTensorInfos={real:i,imag:u},s}class mx{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=Fi(t,n),this.enableShapeUniforms=bb(this.outputShape.length),this.userCode=`\n float binaryOperation(float a, float b) {\n ${e}\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n `}}class gx{constructor(e,t,n,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=Fi(t,n);const a=this.outputShape.length;this.enableShapeUniforms=bb(a);let s="";if(r)if(0===a||1===et(this.outputShape))s="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(s=`\n ${hb(a)} coords = getOutputCoords();\n `,1===a)this.enableShapeUniforms?s+="\n result.y = (coords + 1) >= outShape ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ":s+=`\n result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n `;else{const e=E_("coords",a);this.enableShapeUniforms?s+=`\n bool nextRowOutOfBounds =\n (${e[a-2]} + 1) >= outShape[${a} - 2];\n bool nextColOutOfBounds =\n (${e[a-1]} + 1) >= outShape[${a} - 1];\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `:s+=`\n bool nextRowOutOfBounds =\n (${e[a-2]} + 1) >= ${this.outputShape[a-2]};\n bool nextColOutOfBounds =\n (${e[a-1]} + 1) >= ${this.outputShape[a-1]};\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `}this.userCode=`\n vec4 binaryOperation(vec4 a, vec4 b) {\n ${e}\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n ${s}\n\n setOutput(result);\n }\n `}}const yx="return (a < 0.) ? b * a : a;",bx="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",_x="return (a < 0.) ? b * a : a;",xx="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",vx="if (isnan(x)) return x;";function wx({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:r}){return({inputs:a,backend:s})=>{const{x:o}=a,i=s,u=r||o.dtype;if(i.shouldExecuteOnCPU([o])&&null!=n){const e=i.texData.get(o.dataId),t=n(e.values,u);return i.makeTensorInfo(o.shape,u,t)}let l;return l=Ct().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&null!=t?new q_(o.shape,t):new F_(o.shape,e),i.runWebGLProgram(l,[o],u)}}function Tx({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:r=!1,cpuKernelImpl:a,dtype:s}){return({inputs:o,backend:i})=>{const{a:u,b:l}=o,c=i;if(r&&"complex64"===u.dtype){const t=c.texData.get(u.dataId),n=c.texData.get(l.dataId),[r,a]=[[t.complexTensorInfos.real,n.complexTensorInfos.real],[t.complexTensorInfos.imag,n.complexTensorInfos.imag]].map((t=>{const[n,r]=t,a={dataId:n.dataId,dtype:n.dtype,shape:u.shape},s={dataId:r.dataId,dtype:r.dtype,shape:l.shape},o=new mx(e,u.shape,l.shape);return c.runWebGLProgram(o,[a,s],Ya(n.dtype,r.dtype))})),s=fx({inputs:{real:r,imag:a},backend:c});return c.disposeIntermediateTensorInfo(r),c.disposeIntermediateTensorInfo(a),s}const p=s||Ya(u.dtype,l.dtype);if(("string"===u.dtype||"string"===l.dtype||c.shouldExecuteOnCPU([u,l]))&&null!=a){const e=c.texData.get(u.dataId).values,t=c.texData.get(l.dataId).values,n="string"===u.dtype?Kd(e):e,r="string"===u.dtype?Kd(t):t,[s,o]=a(u.shape,l.shape,n,r,p),i=c.makeTensorInfo(o,p);return c.texData.get(i.dataId).values=s,i}let h;return h=Ct().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&null!=t?new gx(t,u.shape,l.shape,n):new mx(e,u.shape,l.shape),c.runWebGLProgram(h,[u,l],p)}}function kx(e,t=!1){if("linear"===e)return t?W_:D_;if("relu"===e)return t?G_:B_;if("elu"===e)return t?H_:P_;if("relu6"===e)return t?j_:U_;if("prelu"===e)return t?xx:_x;if("leakyrelu"===e)return t?bx:yx;if("sigmoid"===e)return t?K_:V_;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}const Ix=Tx({opSnippet:"return float(a != b);",cpuKernelImpl:n_,dtype:"bool"});function Sx(e){const{inputs:t,backend:n}=e,{input:r}=t;return hx({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.real},backend:n})}const Ex={kernelName:Vt,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r,attrs:a}=t,{x:s}=n,{dtype:o}=a;if("complex64"===o){if("complex64"===s.dtype)return hx({inputs:{x:s},backend:r});const t=Nc(s.shape),n=e({inputs:{x:s},backend:r,attrs:{dtype:"float32"}}),a=fx({inputs:{real:n,imag:t},backend:r});return t.dispose(),r.disposeIntermediateTensorInfo(n),a}if("complex64"===s.dtype){const t=Sx({inputs:{input:s},backend:r}),n=e({inputs:{x:t},backend:r,attrs:{dtype:o}});return r.disposeIntermediateTensorInfo(t),n}if(!pt(s.dtype,o)){const e=hx({inputs:{x:s},backend:r});return{dataId:e.dataId,shape:e.shape,dtype:o}}if(r.shouldExecuteOnCPU([s])){const e=r.texData.get(s.dataId).values,[t,n,a]=Db(e,s.shape,s.dtype,o);return r.makeTensorInfo(t,n,a)}if("int32"===o)return function(e,t){const n=new F_(e.shape,"return float(int(x));"),r=t.runWebGLProgram(n,[e],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}(s,r);if("bool"===o){const e=r.makeTensorInfo([],"bool",lt("bool",1)),t=Ix({inputs:{a:s,b:e},backend:r});return r.disposeIntermediateTensorInfo(e),t}throw new Error(`Error in Cast: failed to cast ${s.dtype} to ${o}`)}},Nx=Tx({opSnippet:"\nif (a == b) {\n return 1.0;\n};\nreturn a / b;",packedOpSnippet:"\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(a.x == b.x) {\n result.x = 1.;\n }\n if(a.y == b.y) {\n result.y = 1.;\n }\n if(a.z == b.z) {\n result.z = 1.;\n }\n if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n",checkOutOfBounds:!0}),Cx={kernelName:en,backendName:"webgl",kernelFunc:Nx};class Ax{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const r=e.length,a=hb(r),s=t.map((e=>e[0])).join(","),o=t.map(((t,n)=>t[0]+e[n])).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?`\n ${a} start = ${a}(${s});\n ${a} end = ${a}(${o});\n\n void main() {\n ${a} outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(value);\n } else {\n ${a} coords = outC - start;\n setOutput(getX(${i}));\n }\n }\n `:`\n int start = ${s};\n int end = ${o};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(value);\n } else {\n setOutput(getX(outC - start));\n }\n }\n `}}class Rx{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const r=e.length,a=hb(r),s=t.map((e=>e[0])).join(","),o=t.map(((t,n)=>t[0]+e[n])).join(","),i=E_("rc",r),u=E_("source",r),l=`${i[r-1]} < ${this.outputShape[r-1]}`,c=1===r?"source":`vec2(${u.slice(-2).join()})`,p=[`${a} rc = outputLoc;`,`${i[r-1]} += 1;\n if(${l}) {\n `,1===r?"":`}\n rc = outputLoc;\n ${i[r-2]} += 1;\n if(${i[r-2]} < ${this.outputShape[r-2]}) {`,1===r?"":` ${i[r-1]} += 1;\n if(${l}) {`],h=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let d="";for(let e=0,t=1===r?2:4;e<t;e++)d+=`\n ${p[e]}\n if (${h}) {\n result[${e}] = float(value);\n } else {\n ${a} source = rc - start;\n result[${e}] = getChannel(getX(${u.join()}), ${c});\n }\n `;d+=1===r?"} ":"}}",this.userCode=`\n const ${a} start = ${a}(${s});\n const ${a} end = ${a}(${o});\n\n void main() {\n ${a} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${d}\n setOutput(result);\n }\n `}}class $x{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode="\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}}const Mx=e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{paddings:s,constantValue:o}=r;if(0===et(a.shape)){const e=s.map(((e,t)=>e[0]+a.shape[t]+e[1]));return function(e){const{backend:t,attrs:n}=e,{shape:r,value:a}=n;let{dtype:s}=n;if(s=s||ft(a),"string"===s){const e=ct(s,et(r));return e.fill(a),t.makeTensorInfo(r,s,e)}{const e=new $x(r,a),n=[[a]];return t.runWebGLProgram(e,[],s,n)}}({backend:n,attrs:{shape:e,value:o,dtype:a.dtype}})}const i=Ct().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Rx(a.shape,s,o):new Ax(a.shape,s,o),u=[[o]];return n.runWebGLProgram(i,[a],a.dtype,u)},Fx={kernelName:Pn,backendName:"webgl",kernelFunc:Mx};class Ox{constructor(e,t=!1,n=null,r=!1,a=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const s=e.padInfo.top,o=e.padInfo.left,i=e.strideHeight,u=e.strideWidth,l=e.dilationHeight,c=e.dilationWidth,p=e.filterHeight,h=e.filterWidth,d=4*Math.floor(e.inChannels/4),f=e.inChannels%4,m="channelsLast"===e.dataFormat,g=m?1:2,y=m?2:3,b=m?3:1;let _="",x="";n&&(_=r?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:a?`float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`\n float activation(float x) {\n ${n}\n }\n `,x="result = activation(result);");const v=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${_}\n\n const ivec2 strides = ivec2(${i}, ${u});\n const ivec2 pads = ivec2(${s}, ${o});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[${b}];\n\n ivec2 xRCCorner =\n ivec2(coords[${g}], coords[${y}]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${p}; wR++) {\n int xR = xRCorner + wR * ${l};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${h}; wC++) {\n int xC = xCCorner + wC * ${c};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${d}; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if (${m}) {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if (${1===f}) {\n\n if (${m}) {\n dotProd +=\n getX(batch, xR, xC, ${d}) *\n getW(wR, wC, ${d}, d2);\n } else {\n dotProd +=\n getX(batch, ${d}, xR, xC) *\n getW(wR, wC, ${d}, d2);\n }\n\n } else if (${2===f}) {\n vec2 wValues = vec2(\n getW(wR, wC, ${d}, d2),\n getW(wR, wC, ${d} + 1, d2)\n );\n\n if (${m}) {\n vec2 xValues = vec2(\n getX(batch, xR, xC, ${d}),\n getX(batch, xR, xC, ${d} + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, ${d}, xR, xC),\n getX(batch, ${d} + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if (${3===f}) {\n vec3 wValues = vec3(\n getW(wR, wC, ${d}, d2),\n getW(wR, wC, ${d} + 1, d2),\n getW(wR, wC, ${d} + 2, d2)\n );\n\n if (${m}) {\n vec3 xValues = vec3(\n getX(batch, xR, xC, ${d}),\n getX(batch, xR, xC, ${d} + 1),\n getX(batch, xR, xC, ${d} + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, ${d}, xR, xC),\n getX(batch, ${d} + 1, xR, xC),\n getX(batch, ${d} + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n ${v}\n ${x}\n setOutput(result);\n }\n `}}class Dx{constructor(e,t=!1,n=null,r=!1,a=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=bb(this.outputShape.length);const s=e.padInfo.left,o=e.strideWidth,i=e.dilationWidth,u=e.filterHeight,l=e.filterWidth,c=l;let p="\n int xR; int xC; int xCOffset;\n vec4 wTexel; vec4 previous; vec4 final;";for(let e=0;e<l;e++)p+=`\n vec4 xTexelC${2*e};\n int xTexelC${2*e}Ready;\n vec4 xTexelC${2*e+1};\n int xTexelC${2*e+1}Ready;\n vec4 xC${e};`;p+=`\n for (int r = 0; r < ${u}; r++) {\n for (int d1 = 0; d1 < ${e.inChannels}; d1 += 2) {\n `;for(let e=0;e<l;e++)p+=`\n xTexelC${2*e} = vec4(0.0);\n xTexelC${2*e}Ready = 0;\n xTexelC${2*e+1} = vec4(0.0);\n xTexelC${2*e+1}Ready = 0;\n xC${e} = vec4(0.0);`;p+="\n xR = xRCorner + r * dilations[0];\n if (xR >=0 && xR < inDims[0]) {\n ";for(let t=0;t<(c+1)/2;t++){const n=2*t;if(p+=`\n xC = xCCorner + ${n*i};\n `,1===o){if(n<l&&(s%2==1?(p+=`\n xCOffset = xC + 1;\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n `,p+=1===i&&n>0?`\n xC${n} = vec4(xTexelC${n-2}.zw, xTexelC${n}.xy);\n `:`\n xCOffset = xC + 1 - 2;\n\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n previous.zw = vec2(0.0);\n }\n\n xC${n} = vec4(previous.zw, xTexelC${n}.xy);\n } else {\n xC${n} = vec4(0.0, 0.0, xTexelC${n}.xy);\n }\n `):p+=`\n if (xC >= 0 && xC < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n\n xC${n} = xTexelC${n};\n `,n+1<l)){const e=s%2==0?Xe(i):i;i%2==0&&s%2==1||i%2!=0&&s%2!=1?(p+=`\n xCOffset = xC + imod(pads[1], 2) + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n+1}.zw = vec2(0.0);\n }\n xTexelC${n+1}Ready = 1;\n }\n `,p+=i>1?`\n xCOffset -= 2;\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n xC${n+1} = vec4(previous.zw, xTexelC${n+1}.xy);\n } else {\n xC${n+1} = vec4(0.0, 0.0, xTexelC${n+1}.xy);\n }\n `:`\n xC${n+1} = vec4(xTexelC${n}.zw, xTexelC${n+1}.xy);\n `):p+=1===e?`\n xC${n+1} = xTexelC${n};\n `:`\n xCOffset = xC + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n+1}.zw = vec2(0.0);\n }\n xTexelC${n+1}Ready = 1;\n }\n\n xC${n+1} = xTexelC${n+1};\n `}}else n<l&&(s%2==1?(p+=`\n xCOffset = xC + 1 - strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = getX(batch, xR, xCOffset, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+1} = getX(batch, xR, xC + 1, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xC + 2 >= inDims[1]) {\n xTexelC${n+1}.zw = vec2(0.0);\n }\n xTexelC${n+1}Ready = 1;\n }\n\n xC${n} = vec4(xTexelC${n}.zw, xTexelC${n+1}.zw);\n `,n+1<l&&(p+=`\n final = vec4(0.0);\n xCOffset = xC + 1 + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1]) {\n final = getX(batch, xR, xCOffset, d1);\n }\n xC${n+1} = vec4(xTexelC${n+1}.xy, final.xy);\n `)):(p+=`\n if(xC >= 0 && xC < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n\n xCOffset = xC + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n+1}.zw = vec2(0.);\n }\n xTexelC${n+1}Ready = 1;\n }\n\n xC${n} = vec4(\n xTexelC${n}.xy, xTexelC${n+1}.xy);\n `,n+1<l&&(p+=`\n xC${n+1} = vec4(xTexelC${n}.zw, xTexelC${n+1}.zw);\n `)));n<l&&(p+=`\n wTexel = getW(r, ${n}, d1, d2);\n dotProd += xC${n}.xxzz * vec4(wTexel.xy, wTexel.xy);\n if(d1 + 1 < ${e.inChannels}) {\n dotProd += xC${n}.yyww * vec4(wTexel.zw, wTexel.zw);\n }\n `,n+1<l&&(p+=`\n wTexel = getW(r, ${n+1}, d1, d2);\n dotProd += xC${n+1}.xxzz * vec4(wTexel.xy, wTexel.xy);\n if(d1 + 1 < ${e.inChannels}) {\n dotProd += xC${n+1}.yyww * vec4(wTexel.zw, wTexel.zw);\n }\n `))}p+="\n }\n ",p+="\n }\n ",p+="\n }\n ";let h="",d="";n&&(h=r?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:a?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`vec4 activation(vec4 x) {\n ${n}\n }`,d="result = activation(result);");const f=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${h}\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.\n vec4 dotProd = vec4(0.000000000000001);\n\n ${p}\n\n vec4 result = dotProd - vec4(0.000000000000001);\n ${f}\n ${d}\n setOutput(result);\n }\n `}}class Lx{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec4"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=e,this.enableShapeUniforms=bb(this.outputShape.length);const{dataFormat:n}=t,r=Qy(),a="channelsLast"===n,s=a?1:2,o=a?2:3,i=this.enableShapeUniforms?"if(blockIndex < outShape[2] && pos < outShape[1]) {":`if(blockIndex < ${e[2]} && pos < ${e[1]}) {`;let u="";for(let e=0;e<=1;e++)for(let t=0;t<=1;t++)u+=`\n blockIndex = rc.z + ${t};\n pos = rc.y + ${e};\n\n ${i}\n offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];\n d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);\n\n if(d0 < inputShape[${s}] && d0 >= 0) {\n // Use custom imod instead mod. On Intel GPU, mod may generate\n // unexpected value.\n // https://github.com/tensorflow/tfjs/issues/5447\n offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];\n d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /\n inChannels);\n\n if(d1 < inputShape[${o}] && d1 >= 0) {\n\n ch = imod(pos, inChannels);\n\n if (${a}) {\n innerDims = vec2(d1, ch);\n result[${2*e+t}] = getChannel(\n getA(rc.x, d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result[${2*e+t}] = getChannel(\n getA(rc.x, ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n `;this.userCode=`\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n ${u}\n\n ${r.output} = result;\n }\n `}}class Px{constructor(e,t,n,r=!1,a=!1,s=!1,o=null,i=!1,u=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=bb(this.outputShape.length);const l=r?e[1]:e[2],c=Math.ceil(l/2),p=r?"i * 2, rc.y":"rc.y, i * 2",h=a?"rc.z, i * 2":"i * 2, rc.z",d=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=a?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let m="",g="";o&&(m=i?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${o}\n }`:u?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${o}\n }`:`vec4 activation(vec4 x) {\n ${o}\n }`,g="result = activation(result);");const y=s?"result += getBiasAtOutCoords();":"";s&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),u&&this.variableNames.push("leakyreluAlpha");let b="rc.x",_="rc.x";e[0]<t[0]?b=`imod(rc.x, ${e[0]})`:t[0]<e[0]&&(_=`imod(rc.x, ${t[0]})`),this.userCode=`\n ${m}\n // Don't use uniform for sharedDimensionPacked for performance.\n const float sharedDimension = ${c}.0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n int batchA = ${b};\n int batchB = ${_};\n for (int i = 0; i < ${c}; i++) {\n vec4 a = getMatrixA(batchA, ${p});\n vec4 b = getMatrixB(batchB, ${h});\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += (${d[0]} * ${f[0]});\n result += (${d[1]} * ${f[1]});\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n ${y}\n\n ${g}\n\n setOutput(result);\n }\n `}}const Bx={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class Ux{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Fi(t,n),this.userCode=`\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n ${e}\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n `}}const zx="return a * b;";function Vx(e){const{inputs:t,backend:n}=e,{a:r,b:a}=t,s=Ya(r.dtype,a.dtype);if("complex64"===r.dtype){const e=n.texData.get(r.dataId),t=n.texData.get(a.dataId),s=new Ux(Bx.REAL,r.shape,a.shape),o=new Ux(Bx.IMAG,r.shape,a.shape),i=[{dataId:e.complexTensorInfos.real.dataId,dtype:e.complexTensorInfos.real.dtype,shape:r.shape},{dataId:e.complexTensorInfos.imag.dataId,dtype:e.complexTensorInfos.imag.dtype,shape:r.shape},{dataId:t.complexTensorInfos.real.dataId,dtype:t.complexTensorInfos.real.dtype,shape:a.shape},{dataId:t.complexTensorInfos.imag.dataId,dtype:t.complexTensorInfos.imag.dtype,shape:a.shape}],u=n.runWebGLProgram(s,i,"float32"),l=n.runWebGLProgram(o,i,"float32"),c=fx({inputs:{real:u,imag:l},backend:n});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(l),c}if(n.shouldExecuteOnCPU([r,a])){const e=n.texData.get(r.dataId),t=n.texData.get(a.dataId),[o,i]=e_(r.shape,a.shape,e.values,t.values,s),u=n.makeTensorInfo(i,s);return n.texData.get(u.dataId).values=o,u}let o;return o=Ct().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new gx(zx,r.shape,a.shape):new mx(zx,r.shape,a.shape),n.runWebGLProgram(o,[r,a],s)}const Wx={kernelName:An,backendName:"webgl",kernelFunc:Vx};class Hx{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:a,outSize:s}=e;this.outputShape=[r,s];const o=4*Math.floor(n/4),i=n%4;let u="sumValue += dot(values, ones);";if(null!=t){const e=1/t;u=`sumValue += dot(values * ${nt(e)?e.toPrecision(2):e}, ones);`}let l="";a%n>0&&(l=`\n if (inIdx < 0 || inIdx >= ${a}) {\n return 0.0;\n }\n `),this.userCode=`\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${l}\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${n};\n\n float sumValue = 0.0;\n\n for (int i = 0; i < ${o}; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n ${u}\n }\n\n int inIdx = inOffset + ${o};\n if (${1===i}) {\n vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\n\n ${u}\n } else if (${2===i}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1), 0.0, 0.0);\n\n ${u}\n } else if (${3===i}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2), 0.0);\n\n ${u}\n }\n setOutput(sumValue);\n }\n `}}class Gx{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:a,outSize:s}=e;this.outputShape=[r,s];let o="0.0",i="";"prod"===t?o="1.0":"min"===t?(o="1.0 / 1e-20",i="min"):"max"===t&&(o="-1.0 / 1e-20",i="max");let u=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"sum"===t?u="sumValue":"prod"===t?u="prodValue":"all"===t?u="allValue":"any"===t&&(u="anyValue");const l=4*Math.floor(n/4),c=n%4;let p=`\n if (${"sum"===t}) {\n sumValue += dot(values, ones);\n } else if (${"prod"===t}) {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = ${i}(values, minMaxValue);\n if (${"min"===t} || ${"max"===t}) {\n minMaxValue = ${i}(values, minMaxValue);\n bvec4 isNaN = isnan(values);\n if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {\n minMaxValue = vec4(NAN);\n }\n }\n }\n `,h="vec4";"all"===t?(o="1.0",p="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",h="bvec4"):"any"===t&&(o="0.0",p="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",h="bvec4");let d="";a%n>0&&(d=`\n if (inIdx < 0 || inIdx >= ${a}) {\n return initializationValue;\n }\n `),this.userCode=`\n const float initializationValue = ${o};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${d}\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${n};\n\n vec4 minMaxValue = vec4(${o});\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < ${l}; i += 4) {\n int inIdx = inOffset + i;\n ${h} values = ${h}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n ${p}\n }\n\n int inIdx = inOffset + ${l};\n if (${1===c}) {\n ${h} values = ${h}(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${p}\n } else if (${2===c}) {\n ${h} values = ${h}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n ${p}\n } else if (${3===c}) {\n ${h} values = ${h}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n ${p}\n }\n setOutput(${u});\n }\n `}}function jx(e,t,n,r){const a=function(e){const t=[];for(;0===t.length||1!==t[t.length-1].outSize;){const n=t.length?t[t.length-1].outSize:e[1],r=Id(n);t.push({inSize:n,windowSize:r,outSize:Math.ceil(n/r)})}return t}(e.shape);let s=e;for(let o=0;o<a.length;o++){const{inSize:i,windowSize:u,outSize:l}=a[o];let c,p;c="mean"===n?0===o?new Hx({windowSize:u,inSize:i,batchSize:e.shape[0],outSize:l},i):new Hx({windowSize:u,inSize:i,batchSize:e.shape[0],outSize:l}):new Gx({windowSize:u,inSize:i,batchSize:e.shape[0],outSize:l},n),p=s,s=r.runWebGLProgram(c,[s],t),p.dataId!==e.dataId&&r.disposeIntermediateTensorInfo(p)}return s}class Kx{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[t[r]];this.outputShape=n,this.rank=n.length;const r=hb(this.rank),a=function(e){const t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t);for(let t=0;t<e.length;t++)r[e[t]]=n[t];return r.join()}(t);this.userCode=`\n void main() {\n ${r} resRC = getOutputCoords();\n setOutput(getA(${a}));\n }\n `}}class qx{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[t[r]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const r=hb(this.rank),a=S_("rc",this.rank),s=new Array(this.rank);for(let e=0;e<t.length;e++)s[t[e]]=a[e];const o=`vec2(${s.slice(-2).join()})`,i=`++${a[this.rank-1]} < ${n[this.rank-1]}`,u=`getChannel(getA(${s.join()}), ${o})`;this.userCode=`\n void main() {\n ${r} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result[0] = ${u};\n if(${i}) {\n result[1] = ${u};\n }\n --${a[this.rank-1]};\n if(++${a[this.rank-2]} < ${n[this.rank-2]}) {\n result[2] = ${u};\n if(${i}) {\n result[3] = ${u};\n }\n }\n setOutput(result);\n }\n `}}function Xx(e,t,n){const r=Ct().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new qx(e.shape,t):new Kx(e.shape,t);return n.runWebGLProgram(r,[e],e.dtype)}function Yx(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r;return function(e,t,n,r){const a=t,s=e.shape.length,o=it(a,e.shape);let i=o;const u=Fl(i,s),l=null!=u;let c=e;l&&(c=Xx(e,u,r),i=Dl(i.length,s)),Ml("sum",i,s);const[p,h]=Rl(c.shape,i);let d=p;n&&(d=$l(p,o));const f=et(h),m=sx({inputs:{x:c},attrs:{shape:[et(e.shape)/f,f]},backend:r}),g=jx(m,Ya(e.dtype,"int32"),"sum",r),y=sx({inputs:{x:g},attrs:{shape:d},backend:r});return r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(g),l&&r.disposeIntermediateTensorInfo(c),y}(a,s,o,n)}function Qx(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{perm:s}=r,o=n,i=a.shape.length,u=new Array(i);for(let e=0;e<u.length;e++)u[e]=a.shape[s[e]];let l;if(o.shouldExecuteOnCPU([a])){const e=o.texData.get(a.dataId).values,t=k_(e,a.shape,a.dtype,s,u);l=o.makeTensorInfo(u,a.dtype),o.texData.get(l.dataId).values=t}else l=Xx(a,s,o);return l}const Jx=1e3;function Zx({a:e,b:t,transposeA:n,transposeB:r,backend:a,bias:s=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:u=null}){const l=e.shape.length,c=t.shape.length,p=n?e.shape[l-2]:e.shape[l-1],h=r?t.shape[c-1]:t.shape[c-2],d=n?e.shape[l-1]:e.shape[l-2],f=r?t.shape[c-2]:t.shape[c-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=et(m),b=et(g),_=Fi(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([d,f]);Qe(p===h,(()=>`Error in matMul: inner shapes (${p}) and (${h}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${r} must match.`));const x=n?[y,p,d]:[y,d,p],v=r?[b,f,h]:[b,h,f],w=sx({inputs:{x:e},backend:a,attrs:{shape:x}}),T=sx({inputs:{x:t},backend:a,attrs:{shape:v}}),k=[w,T],I=Math.max(y,b),S=n?w.shape[1]:w.shape[2],E=null!=s,N=null!=o,C="leakyrelu"===u,A=null!=u?kx(u,!0):null;let R;if((1===d||1===f)&&S>Jx&&!1===(E||N||C||null!=A)){let e=w,t=T;n&&(e=Qx({inputs:{x:w},backend:a,attrs:{perm:[0,2,1]}}),k.push(e)),r&&(t=Qx({inputs:{x:T},backend:a,attrs:{perm:[0,2,1]}}),k.push(t));const s=1===f;let o=e;1!==f&&(o=sx({inputs:{x:e},backend:a,attrs:{shape:[I,S,1]}}),k.push(o));const i=1===f?2:1;let u=t;s&&(u=sx({inputs:{x:t},backend:a,attrs:{shape:[I,1,S]}}),k.push(u));const l=Vx({inputs:{a:o,b:u},backend:a});R=Yx({inputs:{x:l},backend:a,attrs:{axis:i,keepDims:!0}}),k.push(l)}else{const u=Ya(e.dtype,t.dtype),l=new Px(x,v,[I,d,f],n,r,E,A,N,C),c=[w,T];if(null!=s&&c.push(s),N&&c.push(o),C){const e=a.makeTensorInfo([],"float32",va(i,"float32"));c.push(e),k.push(e)}R=a.runWebGLProgram(l,c,u)}const $=sx({inputs:{x:R},backend:a,attrs:{shape:_}});k.push(R);for(const e of k)a.disposeIntermediateTensorInfo(e);return $}function ev(e,t){const n=e.length;return n>=3?t?[...e.slice(0,-3),e[n-3]*e[n-2],e[n-1]]:[...e.slice(0,-3),e[n-3],e[n-2]*e[n-1]]:!t&&1===n&&e[0]>1?[e[0],1]:null}function tv({x:e,filter:t,convInfo:n,backend:r,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:o=0,activation:i=null}){const u=e.shape,l=r.texData.get(e.dataId),c=n.inChannels,p=u[0]*u[1]*u[2],h=n.outChannels,d="channelsLast"===n.dataFormat;let f;const m=[];if(null!=s){const e=ev(s.shape,d);null!=e&&(s=sx({inputs:{x:s},backend:r,attrs:{shape:e}}),m.push(s))}if(null!=a){const e=ev(a.shape,d);null!=e&&(a=sx({inputs:{x:a},backend:r,attrs:{shape:e}}),m.push(a))}if((1!==p&&1!==h||!(c>Jx))&&l.isPacked&&d&&null!=l.texture&&u[2]%2!=0&&tt(l.shape.slice(-3),u.slice(-3))){const c=u[0]*u[1]*(u[2]+1),p={dataId:e.dataId,shape:[1,c,n.inChannels],dtype:e.dtype},h=l.shape;l.shape=l.shape.slice(),l.shape[l.shape.length-2]++,Qe(Hy(l.shape,p.shape),(()=>`packed reshape ${l.shape} to ${p.shape} isn't free`));const d=sx({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}});m.push(d);const g=Zx({a:p,b:d,backend:r,transposeA:!1,transposeB:!1,bias:a,activation:i,preluActivationWeights:s,leakyreluAlpha:o}),y=r.texData.get(g.dataId);Qe(y.isPacked,(()=>"batchMatMul result is expected to be packed")),l.shape=h,y.shape=n.outShape,f=hx({inputs:{x:g},backend:r}),f.shape=n.outShape,m.push(g)}else{const u=n.outHeight*n.outWidth,l=sx({inputs:{x:e},backend:r,attrs:{shape:d?[n.batchSize,u,n.inChannels]:[n.batchSize,n.inChannels,u]}}),c=sx({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}}),p=Zx({a:d?l:c,b:d?c:l,transposeA:!d,transposeB:!1,backend:r,bias:a,activation:i,preluActivationWeights:s,leakyreluAlpha:o});f=sx({inputs:{x:p},backend:r,attrs:{shape:n.outShape}}),m.push(l),m.push(c),m.push(p)}for(const e of m)r.disposeIntermediateTensorInfo(e);return f}function nv({x:e,filter:t,convInfo:n,backend:r,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:o=0,activation:i=null}){const{filterWidth:u,filterHeight:l,inChannels:c,outWidth:p,outHeight:h,dataFormat:d}=n,f="channelsLast"===d,m=u*l*c,g=h*p,y=[n.batchSize,m,g],b=[];if(null!=s){const e=ev(s.shape,f);null!=e&&(s=sx({inputs:{x:s},backend:r,attrs:{shape:e}}),b.push(s))}if(null!=a){const e=ev(a.shape,f);null!=e&&(a=sx({inputs:{x:a},backend:r,attrs:{shape:e}}),b.push(a))}const _=sx({inputs:{x:t},backend:r,attrs:{shape:[1,m,et(t.shape)/m]}});b.push(_);const x=new Lx(y,n),v=[e.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],w=r.runWebGLProgram(x,[e],"float32",v),T=sx({inputs:{x:w},backend:r,attrs:{shape:y}});b.push(w),b.push(T);const k=null!=a,I=null!=s,S="leakyrelu"===i,E=i?kx(i,!0):null,N=new Px(f?T.shape:_.shape,f?_.shape:T.shape,f?[n.batchSize,g,n.outChannels]:[n.batchSize,n.outChannels,g],!0,!1,k,E,I,S),C=f?[T,_]:[_,T];if(a&&C.push(a),I&&C.push(s),S){const e=r.makeTensorInfo([],"float32",va(o,"float32"));C.push(e),b.push(e)}const A=r.runWebGLProgram(N,C,"float32"),R=sx({inputs:{x:A},backend:r,attrs:{shape:n.outShape}});b.push(A);for(const e of b)r.disposeIntermediateTensorInfo(e);return R}const rv={kernelName:jt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dataFormat:u,dilations:l,dimRoundingMode:c}=r,p=$u(u),h=wu(a.shape,s.shape,o,l,i,c,!1,p);let d;if(1!==h.filterHeight||1!==h.filterWidth||1!==h.dilationHeight||1!==h.dilationWidth||1!==h.strideHeight||1!==h.strideWidth||"SAME"!==h.padInfo.type&&"VALID"!==h.padInfo.type)if(h.strideWidth<=2&&"channelsLast"===p&&Ct().getBool("WEBGL_EXP_CONV")){const e=new Dx(h),t=[[h.padInfo.top,h.padInfo.left],[h.strideHeight,h.strideWidth],[h.dilationHeight,h.dilationWidth],[h.inHeight,h.inWidth]];d=n.runWebGLProgram(e,[a,s],"float32",t)}else if(Ct().getBool("WEBGL_CONV_IM2COL"))d=nv({x:a,filter:s,convInfo:h,backend:n});else{const e=new Ox(h);d=n.runWebGLProgram(e,[a,s],"float32")}else d=tv({x:a,filter:s,convInfo:h,backend:n});const f=sx({inputs:{x:d},backend:n,attrs:{shape:h.outShape}});return n.disposeIntermediateTensorInfo(d),f}},av={kernelName:Er,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dataFormat:c,dilations:p,dimRoundingMode:h,activation:d,leakyreluAlpha:f}=r,m=$u(c),g=wu(a.shape,s.shape,u,p,l,h,!1,m);let y;const b=[],_=null!=o,x=null!=i,v="leakyrelu"===d,w=()=>{const e=[a,s],t=(e,t)=>{if("NCHW"===t&&1===e.shape.length&&1!==e.shape[0]){const t=sx({inputs:{x:e},backend:n,attrs:{shape:[e.shape[0],1,1]}});return b.push(t),t}return e};if(_&&e.push(t(o,c)),x&&e.push(t(i,c)),v){const t=n.makeTensorInfo([],"float32",va(f,"float32"));e.push(t),b.push(t)}return e};if(1!==g.filterHeight||1!==g.filterWidth||1!==g.dilationHeight||1!==g.dilationWidth||1!==g.strideHeight||1!==g.strideWidth||"SAME"!==g.padInfo.type&&"VALID"!==g.padInfo.type)if(g.strideWidth<=2&&"channelsLast"===m&&Ct().getBool("WEBGL_EXP_CONV")){const e=d?kx(d,!0):null,t=new Dx(g,_,e,x,v),r=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],a=w();y=n.runWebGLProgram(t,a,"float32",r)}else if(Ct().getBool("WEBGL_CONV_IM2COL"))y=nv({x:a,filter:s,convInfo:g,backend:n,bias:o,activation:d,preluActivationWeights:i,leakyreluAlpha:f});else{const e=d?kx(d,!1):null,t=new Ox(g,_,e,x,v),r=w();y=n.runWebGLProgram(t,r,"float32")}else y=tv({x:a,filter:s,convInfo:g,backend:n,bias:o,activation:d,preluActivationWeights:i,leakyreluAlpha:f});const T=sx({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach((e=>n.disposeIntermediateTensorInfo(e))),T}};class sv{constructor(e,t=!1,n=null,r=!1,a=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=bb(this.outputShape.length);const s=e.filterHeight,o=e.filterWidth,i=e.outChannels/e.inChannels;let u="",l="";n&&(u=r?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:a?`float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`\n float activation(float x) {\n ${n}\n }\n `,l="result = activation(result);");const c=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${u}\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / ${i};\n int q = d2 - d1 * ${i};\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < ${s}; wR++) {\n int xR = xRCorner + wR * dilations[0];\n\n if (xR < 0 || xR >= inDims[0]) {\n continue;\n }\n\n for (int wC = 0; wC < ${o}; wC++) {\n int xC = xCCorner + wC * dilations[1];\n\n if (xC < 0 || xC >= inDims[1]) {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n\n float result = dotProd;\n ${c}\n ${l}\n setOutput(result);\n }\n `}}class ov{constructor(e,t=!1,n=null,r=!1,a=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=bb(this.outputShape.length);const s=e.outChannels/e.inChannels,o=e.padInfo.left,i=e.strideWidth,u=e.dilationWidth,l=e.filterHeight,c=e.filterWidth,p=c;let h="\n int xR; int xC; int xCOffset;\n vec4 wTexel; vec4 previous; vec4 final;";for(let e=0;e<c;e++)h+=`\n vec4 xTexelC${2*e};\n int xTexelC${2*e}Ready;\n vec4 xTexelC${2*e+1};\n int xTexelC${2*e+1}Ready;\n vec4 xC${e};`;h+=`\n for (int r = 0; r < ${l}; r++) {\n `;for(let e=0;e<c;e++)h+=`\n xTexelC${2*e} = vec4(0.0);\n xTexelC${2*e}Ready = 0;\n xTexelC${2*e+1} = vec4(0.0);\n xTexelC${2*e+1}Ready = 0;\n xC${e} = vec4(0.0);`;h+="\n xR = xRCorner + r * dilations[0];\n if (xR >=0 && xR < inDims[0]) {\n ";for(let e=0;e<(p+1)/2;e++){const t=2*e;if(h+=`\n xC = xCCorner + ${t*u};\n `,1===i){if(t<c&&(o%2==1?(h+=`\n xCOffset = xC + 1;\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n `,h+=1===u&&t>0?`\n xC${t} = vec4(xTexelC${t-2}.zw, xTexelC${t}.xy);\n `:`\n xCOffset = xC + 1 - 2;\n\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n previous.zw = vec2(0.0);\n }\n\n xC${t} = vec4(previous.zw, xTexelC${t}.xy);\n } else {\n xC${t} = vec4(0.0, 0.0, xTexelC${t}.xy);\n }\n `):h+=`\n if (xC >= 0 && xC < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n\n xC${t} = xTexelC${t};\n `,t+1<c)){const e=o%2==0?Xe(u):u;u%2==0&&o%2==1||u%2!=0&&o%2!=1?(h+=`\n xCOffset = xC + imod(pads[1], 2) + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.0);\n }\n xTexelC${t+1}Ready = 1;\n }\n `,h+=u>1?`\n xCOffset -= 2;\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n xC${t+1} = vec4(previous.zw, xTexelC${t+1}.xy);\n } else {\n xC${t+1} = vec4(0.0, 0.0, xTexelC${t+1}.xy);\n }\n `:`\n xC${t+1} = vec4(xTexelC${t}.zw, xTexelC${t+1}.xy);\n `):h+=1===e?`\n xC${t+1} = xTexelC${t};\n `:`\n xCOffset = xC + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.0);\n }\n xTexelC${t+1}Ready = 1;\n }\n\n xC${t+1} = xTexelC${t+1};\n `}}else t<c&&(o%2==1?(h+=`\n xCOffset = xC + 1 - strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xCOffset, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xC + 1, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xC + 2 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.0);\n }\n xTexelC${t+1}Ready = 1;\n }\n\n xC${t} = vec4(xTexelC${t}.zw, xTexelC${t+1}.zw);\n `,t+1<c&&(h+=`\n final = vec4(0.0);\n xCOffset = xC + 1 + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1]) {\n final = getX(batch, xR, xCOffset, d1);\n }\n xC${t+1} = vec4(xTexelC${t+1}.xy, final.xy);\n `)):(h+=`\n if(xC >= 0 && xC < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n\n xCOffset = xC + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.);\n }\n xTexelC${t+1}Ready = 1;\n }\n\n xC${t} = vec4(\n xTexelC${t}.xy, xTexelC${t+1}.xy);\n `,t+1<c&&(h+=`\n xC${t+1} = vec4(xTexelC${t}.zw, xTexelC${t+1}.zw);\n `)));t<c&&(h+=`\n wTexel = getW(r, ${t}, d1, q);\n dotProd += xC${t} * vec4(wTexel.xz, wTexel.xz);\n `,t+1<c&&(h+=`\n wTexel = getW(r, ${t+1}, d1, q);\n dotProd += xC${t+1} * vec4(wTexel.xz, wTexel.xz);\n `))}h+="\n }\n ",h+="\n }\n ";let d="",f="";n&&(d=r?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:a?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`vec4 activation(vec4 x) {\n ${n}\n }`,f="result = activation(result);");const m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${d}\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / ${s};\n int q = d2 - d1 * ${s};\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.\n vec4 dotProd = vec4(0.000000000000001);\n\n ${h}\n\n vec4 result = dotProd - vec4(0.000000000000001);\n ${m}\n ${f}\n setOutput(result);\n }\n `}}const iv={kernelName:Nr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dilations:c,dimRoundingMode:p,activation:h,leakyreluAlpha:d}=r,f=[];let m=c;null==m&&(m=[1,1]),Qe(Au(u,m),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${u} and dilations '${m}'`));const g=wu(a.shape,s.shape,u,m,l,p,!0),y=Ct().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,b=h?kx(h,y):null,_=[a,s],x=null!=o,v=null!=i,w="leakyrelu"===h;if(x&&_.push(o),v&&_.push(i),w){const e=n.makeTensorInfo([],"float32",va(d,"float32"));_.push(e),f.push(e)}let T;T=y?new ov(g,x,b,v,w):new sv(g,x,b,v,w);const k=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],I=n.runWebGLProgram(T,_,"float32",k);return f.forEach((e=>n.disposeIntermediateTensorInfo(e))),I}},uv="return a + b;",lv=Tx({opSnippet:uv,packedOpSnippet:uv,supportsComplex:!0,cpuKernelImpl:Mb}),cv={kernelName:Ft,backendName:"webgl",kernelFunc:lv},pv={kernelName:rr,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,paddings:o}=r;Qe(a.shape.length<=4,(()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"));const i=s.reduce(((e,t)=>e*t)),u=[[0,0]];u.push(...o);for(let e=1+s.length;e<a.shape.length;++e)u.push([0,0]);const l=[],c=Mx({inputs:{x:a},backend:n,attrs:{paddings:u,constantValue:0}}),p=Ed(c.shape,s,i,!1),h=Nd(p.length,s.length,!1),d=Cd(c.shape,s,i,!1),f=sx({inputs:{x:c},backend:n,attrs:{shape:p}}),m=Qx({inputs:{x:f},backend:n,attrs:{perm:h}}),g=sx({inputs:{x:m},backend:n,attrs:{shape:d}});return l.push(c),l.push(f),l.push(m),l.forEach((e=>n.disposeIntermediateTensorInfo(e))),g}},hv={kernelName:Zt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dilations:u,dimRoundingMode:l}=r;let c=u;null==c&&(c=[1,1]),Qe(Au(o,c),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`));const p=wu(a.shape,s.shape,o,c,i,l,!0);let h;h=Ct().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels==1?new ov(p):new sv(p);const d=[[p.padInfo.top,p.padInfo.left],[p.strideHeight,p.strideWidth],[p.dilationHeight,p.dilationWidth],[p.inHeight,p.inWidth]];return n.runWebGLProgram(h,[a,s],"float32",d)}};class dv{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=hb(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const n=function(e){if(1===e)return"sourceLoc";if(e<=6)return fv.slice(0,e).map((e=>"sourceLoc."+e)).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}(this.rank);let r;const a=e.map(((e,t)=>`sourceLoc.${fv[t]} = start[${t}] + coords.${fv[t]};`));r=`\n ${t} sourceLoc;\n ${t} coords = getOutputCoords();\n ${a.join("\n")}\n `,this.userCode=`\n void main() {\n ${r}\n setOutput(getSource(${n}));\n }\n `}}const fv=["x","y","z","w","u","v"];class mv{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const t=hb(this.rank),n=E_("coords",this.rank),r=E_("sourceLoc",this.rank),a=1===this.rank?"sourceLoc":`vec2(${r.slice(-2).join()})`,s=`getChannel(getSource(${r.join()}), ${a})`,o=`\n result.x = ${s};\n if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n ++${r[this.rank-1]};\n result.y = ${s};\n --${r[this.rank-1]};\n }\n `,i=1===this.rank?"":`\n --${n[this.rank-1]};\n if (++${n[this.rank-2]} < ${e[this.rank-2]}) {\n ++${r[this.rank-2]};\n result.z = ${s};\n if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n ++${r[this.rank-1]};\n result.w = ${s};\n }\n }\n `,u=this.rank<=4?`sourceLoc = coords +\n ${t}(${e.map(((e,t)=>`start[${t}]`)).join()});`:e.map(((e,t)=>`${r[t]} = ${n[t]} + start[${t}];`)).join("\n");this.userCode=`\n void main() {\n ${t} coords = getOutputCoords();\n ${t} sourceLoc;\n ${u}\n vec4 result = vec4(0.);\n ${o}\n ${i}\n setOutput(result);\n }\n `}}function gv(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,size:o}=r,[i,u]=eu(a,s,o);if(Vi(a,i,u),0===et(u))return n.makeTensorInfo(u,a.dtype,[]);if(n.shouldExecuteOnCPU([a])||"string"===a.dtype){const e=n.texData.get(a.dataId),t=h_(e.values,i,u,a.shape,a.dtype);return n.makeTensorInfo(u,a.dtype,t)}const{isPacked:l}=n.texData.get(a.dataId),c=Ji(a.shape,i,u);if(l||!c){const e=Ct().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new mv(u):new dv(u),t=[i];return n.runWebGLProgram(e,[a],a.dtype,t)}return n.uploadToGPU(a.dataId),function(e,t,n,r){const a=r.texData.get(e.dataId),s=r.makeTensorInfo(n,e.dtype),o=r.texData.get(s.dataId);Object.assign(o,a),o.refCount=1,o.shape=n,o.dtype=e.dtype;let i=Zi(t,yt(e.shape));a.slice&&(i+=a.slice.flatOffset),o.slice={flatOffset:i,origDataId:a.slice&&a.slice.origDataId||e.dataId};const u=r.dataRefCount.get(o.slice.origDataId)||1;return r.dataRefCount.set(o.slice.origDataId,u+1),s}(a,i,u,n)}const yv={kernelName:Zn,backendName:"webgl",kernelFunc:gv},bv={kernelName:zt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,crops:o}=r;Qe(a.shape.length<=4,(()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"));const i=s.reduce(((e,t)=>e*t)),u=Ed(a.shape,s,i),l=Nd(u.length,s.length),c=Cd(a.shape,s,i),p=Ad(o,s.length),h=Rd(c,o,s.length),d=[],f=sx({inputs:{x:a},backend:n,attrs:{shape:u}}),m=Qx({inputs:{x:f},backend:n,attrs:{perm:l}}),g=sx({inputs:{x:m},backend:n,attrs:{shape:c}}),y=gv({inputs:{x:g},backend:n,attrs:{begin:p,size:h}});return d.push(f),d.push(m),d.push(g),d.forEach((e=>n.disposeIntermediateTensorInfo(e))),y}},_v=wx({opSnippet:O_+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",packedOpSnippet:"\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n"}),xv={kernelName:Kn,backendName:"webgl",kernelFunc:_v};class vv{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const r=n.length,a=hb(n.length),s=hb(n.length);let o="";if(1===r)o="coords * strides + begin";else{let e=0;o=n.map(((t,r)=>(e++,1===n.length?`coords * strides[${r}] + begin[${r}]`:`coords[${e-1}] * strides[${r}] + begin[${r}]`))).join(",")}this.userCode=`\n ${a} begin = ${a}(${e});\n ${a} strides = ${a}(${t});\n\n void main() {\n ${s} coords = getOutputCoords();\n setOutput(getX(${o}));\n }\n `}}const wv={kernelName:pr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,end:o,strides:i,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:h}=r,{finalShapeSparse:d,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:_,strides:x}=tu(a.shape,s,o,i,u,l,c,p,h);let v;if(m)v=sx({inputs:{x:a},backend:n,attrs:{shape:f}});else if(g||y){Qe(a.shape.length>=1,(()=>`Input must have rank at least 1, got: ${a.shape.length}`));const e=Wi(b,_,x),t=gv({inputs:{x:a},backend:n,attrs:{begin:b,size:e}});v=sx({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else if(n.shouldExecuteOnCPU([a])){const e=n.readSync(a.dataId),t=Qu(a.shape,a.dtype,e),r=y_(d,t,x,b);v=n.makeTensorInfo(f,a.dtype,r.values)}else{const e=new vv(b,x,d);v=n.runWebGLProgram(e,[a],a.dtype)}const w=sx({inputs:{x:v},backend:n,attrs:{shape:f}});return n.disposeIntermediateTensorInfo(v),w}};class Tv{constructor(e){this.outputShape=[],this.outputShape=bd(e,1),this.variableNames=e.map(((e,t)=>`T${t}`));const t=new Array(e.length-1);t[0]=e[0][1];for(let n=1;n<t.length;n++)t[n]=t[n-1]+e[n][1];const n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let e=1;e<t.length;e++){const r=t[e-1];n.push(`else if (yC < ${t[e]}) setOutput(getT${e}(yR, yC-${r}));`)}const r=t.length,a=t[t.length-1];n.push(`else setOutput(getT${r}(yR, yC-${a}));`),this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n ${n.join("\n ")}\n }\n `}}class kv{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=bd(e,t);const n=this.outputShape,r=n.length,a=hb(r),s=E_("coords",r),o=["x","y","z","w","u","v"].slice(0,r);this.variableNames=e.map(((e,t)=>`T${t}`));const i=new Array(e.length-1);i[0]=e[0][t];for(let n=1;n<i.length;n++)i[n]=i[n-1]+e[n][t];const u=o[t],l=o.slice(-2),c=o.join();let p=`if (${u} < ${i[0]}) {\n return getChannel(\n getT0(${c}), vec2(${l.join()}));\n }`;for(let e=1;e<i.length;e++){const t=i[e-1];p+=`\n if (${u} < ${i[e]} && ${u} >= ${i[e-1]}) {\n return getChannel(\n getT${e}(${Iv(o,u,t)}),\n vec2(${Iv(l,u,t)}));\n }`}const h=i.length,d=i[i.length-1];p+=`\n return getChannel(\n getT${h}(${Iv(o,u,d)}),\n vec2(${Iv(l,u,d)}));`,this.userCode=`\n float getValue(${o.map((e=>"int "+e))}) {\n ${p}\n }\n\n void main() {\n ${a} coords = getOutputCoords();\n vec4 result = vec4(getValue(${s}), 0., 0., 0.);\n\n ${s[r-1]} = ${s[r-1]} + 1;\n if (${s[r-1]} < ${n[r-1]}) {\n result.g = getValue(${s});\n }\n\n ${s[r-2]} = ${s[r-2]} + 1;\n if (${s[r-2]} < ${n[r-2]}) {\n result.a = getValue(${s});\n }\n\n ${s[r-1]} = ${s[r-1]} - 1;\n if (${s[r-2]} < ${n[r-2]} &&\n ${s[r-1]} < ${n[r-1]}) {\n result.b = getValue(${s});\n }\n setOutput(result);\n }\n `}}function Iv(e,t,n){const r=e.indexOf(t);return e.map(((e,t)=>t===r?`${e} - ${n}`:e)).join()}function Sv(e,t,n){const r=e[0].dtype;if("complex64"===r){const r=e.map((e=>Sx({inputs:{input:e},backend:n}))),a=e.map((e=>function(e){const{inputs:t,backend:n}=e,{input:r}=t;return hx({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.imag},backend:n})}({inputs:{input:e},backend:n}))),s=Sv(r,t,n),o=Sv(a,t,n),i=fx({inputs:{real:s,imag:o},backend:n});return r.forEach((e=>n.disposeIntermediateTensorInfo(e))),a.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(o),i}let a=n.shouldExecuteOnCPU(e);if("string"===r&&(a=!0),a){const a=e.map((e=>{const r=et(e.shape.slice(t));return sx({inputs:{x:e},backend:n,attrs:{shape:[-1,r]}})})),s=a.map((e=>({vals:n.readSync(e.dataId),shape:e.shape}))),o=bd(a.map((e=>e.shape)),1),i=1===a[0].shape[0],u=Pb(s,o,r,i),l=bd(e.map((e=>e.shape)),t),c=n.makeTensorInfo(l,r,u);return a.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}const s=e.filter((e=>et(e.shape)>0)),o=Ct().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&s[0].shape.length>1;if(1===s.length){const t=o?new F_(e[0].shape,z_):new q_(e[0].shape,z_);return n.runWebGLProgram(t,e,r)}const i=Ct().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(s.length>i){const e=[];for(let r=0;r<s.length;r+=i){const a=s.slice(r,r+i);e.push(Sv(a,t,n))}const r=Sv(e,t,n);for(const t of e)n.disposeIntermediateTensorInfo(t);return r}if(o){const e=new kv(s.map((e=>e.shape)),t);return n.runWebGLProgram(e,s,r)}const{tensors2D:u,outShape:l}=function(e,t,n){const r=bd(e.map((e=>e.shape)),t),a=e.map((e=>sx({inputs:{x:e},attrs:{shape:[-1,et(e.shape.slice(t))]},backend:n})));return{tensors2D:a,outShape:r}}(s,t,n),c=new Tv(u.map((e=>e.shape))),p=n.runWebGLProgram(c,u,r);u.forEach((e=>n.disposeIntermediateTensorInfo(e)));const h=sx({inputs:{x:p},attrs:{shape:l},backend:n});return n.disposeIntermediateTensorInfo(p),h}function Ev(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r,s=it(a,t[0].shape)[0];yd(t.map((e=>e.shape)),s);const o=bd(t.map((e=>e.shape)),s);if(0===et(o))return n.makeTensorInfo(o,t[0].dtype,[]);const i=t.filter((e=>et(e.shape)>0));return 1===i.length?hx({inputs:{x:i[0]},backend:n}):Sv(i,s,n)}const Nv={kernelName:Gt,backendName:"webgl",kernelFunc:Ev},Cv={kernelName:Ln,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return ix({inputs:{input:t[0]},backend:n,attrs:{dim:a}});const s=t[0].shape,o=t[0].dtype;t.forEach((e=>{Je(s,e.shape,"All tensors passed to stack must have matching shapes"),Qe(o===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const i=[],u=Ev({inputs:t.map((e=>{const t=ix({inputs:{input:e},backend:n,attrs:{dim:a}});return i.push(t),t})),backend:n,attrs:{axis:a}});return i.forEach((e=>n.disposeIntermediateTensorInfo(e))),u}};class Av{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,s="channelsLast"===e.dataFormat,o=t-1-e.padInfo.top,i=n-1-e.padInfo.left,u=s?1:2,l=s?2:3,c=s?3:1;this.userCode=`\n const ivec2 pads = ivec2(${o}, ${i});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[${c}];\n\n ivec2 dyCorner = ivec2(coords[${u}], coords[${l}]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${t}; wR++) {\n float dyR = float(dyRCorner + wR) / ${r}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${t} - 1 - wR;\n\n for (int wC = 0; wC < ${n}; wC++) {\n float dyC = float(dyCCorner + wC) / ${a}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${n} - 1 - wC;\n\n for (int d2 = 0; d2 < ${e.outChannels}; d2++) {\n\n if (${s}) {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const Rv={kernelName:Kt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{inputShape:o,strides:i,pad:u,dataFormat:l,dimRoundingMode:c}=r,p=$u(l),h=wu(o,s.shape,i,1,u,c,!1,p),d=new Av(h);return n.runWebGLProgram(d,[a,s],"float32")}},$v=wx({opSnippet:O_+"\n return (x < 0.0) ? 0.0 : x;\n",packedOpSnippet:"\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n"}),Mv={kernelName:Wn,backendName:"webgl",kernelFunc:$v},Fv=wx({opSnippet:vx+"\n return 1.0 / (1.0 + exp(-1.0 * x));\n",packedOpSnippet:"\n vec4 result = 1.0 / (1.0 + exp(-1.0 * x));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",cpuKernelImpl:c_}),Ov={kernelName:er,backendName:"webgl",kernelFunc:Fv};class Dv{constructor(e,t,n,r,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[s,o,i,u]=e,[l]=t,[c,p]=n;this.outputShape=[l,c,p,u];const h="bilinear"===r?1:0,[d,f]=[o-1+".0",i-1+".0"],[m,g,y]=c>1?[""+(o-1)/(c-1),"(y2-y1) * height_ratio",`y1*${d} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${d}`],[b,_,x]=p>1?[""+(i-1)/(p-1),"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${f}`];this.userCode=`\n const float height_ratio = float(${m});\n const float width_ratio = float(${b});\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= ${s}) {\n return;\n }\n\n float height_scale = ${g};\n float width_scale = ${_};\n\n float in_y = ${y};\n if( in_y < 0.0 || in_y > ${d} ) {\n setOutput(float(${a}));\n return;\n }\n float in_x = ${x};\n if( in_x < 0.0 || in_x > ${f} ) {\n setOutput(float(${a}));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if(${h} == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n `}}const Lv={kernelName:Qt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{image:a,boxes:s,boxInd:o}=t,{cropSize:i,method:u,extrapolationValue:l}=r,c=new Dv(a.shape,s.shape,i,u,l);return n.runWebGLProgram(c,[a,s,o],"float32")}};class Pv{constructor(e,t){this.variableNames=["x"];const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,1===n)return void(this.userCode=`\n void main() {\n int coord = getOutputCoords();\n setOutput(getX(${e[0]} - coord - 1));\n }\n `);const r=e.map(((n,r)=>(n=>-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - coords[${n}] - 1`:`coords[${n}]`)(r))).join(","),a=hb(n);this.userCode=`\n void main() {\n ${a} coords = getOutputCoords();\n setOutput(getX(${r}));\n }\n `}}class Bv{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;const r=E_("rc",n),a=`${r[n-1]} + 1 < ${this.outputShape[n-1]}`,s=`${r[n-2]} + 1 < ${this.outputShape[n-2]}`,o=hb(n);function i(n){const r=e.map(((r,a)=>function(n,r){return-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - ${r[n]} - 1`:`${r[n]}`}(a,n)));return`getChannel(getX(${r.join(",")}), vec2(${r.slice(-2).join(",")}))`}this.userCode=1===n?`\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX(${e[0]} - rc - 1),\n ${e[0]} - rc - 1);\n if(${a}){\n result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),\n ${e[0]} - (rc + 1) - 1);\n }\n setOutput(result);\n }\n `:`\n void main() {\n ${o} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = ${function(e){return i(e)}(r.slice())};\n if(${a}){\n result.g = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",i(e)}(r.slice())};\n }\n if(${s}) {\n result.b = ${function(e){return e[n-2]="("+e[n-2]+" + 1)",i(e)}(r.slice())};\n if(${a}) {\n result.a = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",e[n-2]="("+e[n-2]+" + 1)",i(e)}(r.slice())};\n }\n }\n setOutput(result);\n }\n `}}const Uv={kernelName:qn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dims:s}=r,o=a.shape.length,i=it(s,a.shape);if(0===o)return hx({inputs:{x:a},backend:n});const u=Ct().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Bv(a.shape,i):new Pv(a.shape,i);return n.runWebGLProgram(u,[a],a.dtype)}},zv="return a - b;",Vv=Tx({opSnippet:zv,packedOpSnippet:zv,supportsComplex:!0,cpuKernelImpl:v_}),Wv={kernelName:mr,backendName:"webgl",kernelFunc:Vv},Hv={kernelName:vr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{value:a}=t;let{axis:s}=r;s<0&&(s+=a.shape.length);const o=a,i=o.shape.length,u=a.shape[s],l=new Array(i-1);let c=0;for(let e=0;e<i;e++)e!==s&&(l[c++]=o.shape[e]);const p=[],h=new Array(i).fill(0),d=o.shape.slice();d[s]=1;const f=new Array(u);for(let e=0;e<f.length;e++){h[s]=e;const t=gv({inputs:{x:o},backend:n,attrs:{begin:h,size:d}}),r=sx({inputs:{x:t},backend:n,attrs:{shape:l}});f[e]=r,p.push(t)}return p.forEach((e=>n.disposeIntermediateTensorInfo(e))),f}};class Gv{constructor(e,t,n){this.variableNames=["A"];const{windowSize:r,batchSize:a,outSize:s}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[a,s];const o="max"===t?">":"<",i=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${r};\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < ${r}; i++) {\n int inIdx = ${i};\n float candidate = getA(batch, inIdx);\n if (candidate ${o} bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n `}}class jv{constructor(e,t,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,Qe(e.length>2,(()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`));const a=e[e.length-1],s=Math.ceil(a/t);this.outputShape=e.slice(0,-1),s>1&&this.outputShape.push(s),r||this.variableNames.push("bestIndicesA");const o=this.outputShape,i=o.length,u=hb(i),l=E_("coords",i);let c,p;if(1===s){p=i+1;const e=hb(p);c=`\n ${e} sourceLocR = ${e}(${l.join()}, 0);\n ++${l[i-1]};\n ${e} sourceLocG = ${e}(${l.join()}, 0);\n ++${l[i-2]};\n ${e} sourceLocA = ${e}(${l.join()}, 0);\n --${l[i-1]};\n ${e} sourceLocB = ${e}(${l.join()}, 0);\n --${l[i-2]};`}else p=i,c=`\n ${u} sourceLocR = coords;\n ++${l[i-1]};\n ${u} sourceLocG = coords;\n ++${l[i-2]};\n ${u} sourceLocA = coords;\n --${l[i-1]};\n ${u} sourceLocB = coords;\n --${l[i-2]};`;const h=["x","y","z","w","u","v"].slice(0,p),d="."+h[p-1],f=h.map((e=>"int "+e)),m=E_("sourceLocR",p-1).concat("inIdx.r"),g=E_("sourceLocG",p-1).concat("inIdx.g"),y=E_("sourceLocB",p-1).concat("inIdx.b"),b=E_("sourceLocA",p-1).concat("inIdx.a"),_="max"===n?"greaterThan":"lessThan",x=r?"":`\n inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),\n getBestIndicesAChannel(${g.join()}),\n getBestIndicesAChannel(${y.join()}),\n getBestIndicesAChannel(${b.join()})));`,v=`vec4(\n getAChannel(${m.join()}),\n hasNextCol ? getAChannel(${g.join()}) : 0.,\n hasNextRow ? getAChannel(${y.join()}) : 0.,\n hasNextRow && hasNextCol ? getAChannel(${b.join()}) : 0.)`,w=r?"":`\n float getBestIndicesAChannel(${f.join()}) {\n return getChannel(getBestIndicesA(${h.join()}),\n vec2(${h.slice(-2).join()}));\n }`;this.userCode=`\n float getAChannel(${f.join()}) {\n return getChannel(getA(${h.join()}),\n vec2(${h.slice(-2).join()}));\n }\n ${w}\n void main() {\n ${u} coords = getOutputCoords();\n bool hasNextCol = ${l[i-1]} < ${o[i-1]-1};\n bool hasNextRow = ${l[i-2]} < ${o[i-2]-1};\n ${c}\n ivec4 srcIdx = ivec4(sourceLocR${d}, sourceLocG${d},\n sourceLocB${d}, sourceLocA${d}) * ${t};\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = ${v};\n\n for (int i = 0; i < ${t}; i++) {\n inIdx = srcIdx;\n ${x}\n vec4 candidate = ${v};\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4(${_}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n `}}function Kv(e,t,n,r=null){let a=t.shape[0],s=t.shape[1];null!=r&&(a=r.shape[0],s=r.shape[1]);const o=Id(s),i={windowSize:o,inSize:s,batchSize:a,outSize:Math.ceil(s/o)},u=new Gv(i,n,null==r),l=[t];null!=r&&l.push(r);const c=e.runWebGLProgram(u,l,"int32");if(1===c.shape[1])return c;const p=Kv(e,t,n,c);return e.disposeIntermediateTensorInfo(c),p}function qv(e,t,n,r=null){const a=null!=r?r.shape:t.shape,s=Id(a[a.length-1]),o=new jv(a,s,n,null==r),i=null==r?[t]:[t,r],u=e.runWebGLProgram(o,i,"int32");if(u.shape.length===t.shape.length){const r=qv(e,t,n,u);return e.disposeIntermediateTensorInfo(u),r}return u}function Xv(e,t,n,r){const a=[n];if(Ml("arg"+r.charAt(0).toUpperCase()+r.slice(1),a,t.shape.length),!Ct().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){const n=[],s=e.texData.get(t.dataId);let o=t;null!==s&&s.isPacked&&(o=e.unpackTensor(t),n.push(o));const[i,u]=Rl(o.shape,a),l=et(u),c=sx({inputs:{x:o},backend:e,attrs:{shape:[-1,l]}});n.push(c);const p=Kv(e,c,r);n.push(p);const h=sx({inputs:{x:p},backend:e,attrs:{shape:i}});return n.forEach((t=>e.disposeIntermediateTensorInfo(t))),h}return qv(e,t,r)}const Yv={kernelName:Pt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;let o=it(s,a.shape);const i=Fl(o,a.shape.length);let u=a;const l=[];null!=i&&(u=Qx({inputs:{x:a},backend:n,attrs:{perm:i}}),l.push(u),o=Dl(o.length,u.shape.length)),Ml("argMax",[o[0]],u.shape.length);const c=Xv(n,u,o[0],"max");return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}},Qv={kernelName:Sn,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{keepDims:a,axis:s}=t,o=n,i=r.shape.length,u=it(s,r.shape);let l=u;const c=Fl(l,i),p=null!=c,h=o.shouldExecuteOnCPU([r]),d=[];let f=r;if(p){if(h){const e=o.texData.get(f.dataId).values,t=new Array(i);for(let e=0;e<t.length;e++)t[e]=r.shape[c[e]];const n=k_(e,r.shape,r.dtype,c,t);f=o.makeTensorInfo(t,r.dtype),o.texData.get(f.dataId).values=n}else f=Xx(r,c,o);d.push(f),l=Dl(l.length,i)}Ml("sum",l,i);const[m,g]=Rl(f.shape,l);let y=m;a&&(y=$l(m,u));const b=function(e,t,n,r){const a=et(t),s=sx({inputs:{x:e},attrs:{shape:[et(e.shape)/a,a]},backend:r}),o=jx(s,"float32","mean",r),i=sx({inputs:{x:o},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(o),i}(f,g,y,o);for(const e of d)o.disposeIntermediateTensorInfo(e);return b}},Jv=wx({opSnippet:vx+"\n return exp(x);\n",packedOpSnippet:"\n vec4 result = exp(x);\n bvec4 isNaN = isnan(x);\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",cpuKernelImpl:Ub,dtype:"float32"}),Zv={kernelName:sr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{dim:s}=r,o=it([s],a.shape),i=function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{reductionIndices:s,keepDims:o}=r,i=a.shape.length,u=it(s,a.shape);let l=u;const c=Fl(l,i),p=null!=c,h=n.shouldExecuteOnCPU([a]);let d=a;if(p){if(h){const e=n.texData.get(d.dataId).values,t=new Array(i);for(let e=0;e<t.length;e++)t[e]=a.shape[c[e]];const r=k_(e,a.shape,a.dtype,c,t);d=n.makeTensorInfo(t,a.dtype),n.texData.get(d.dataId).values=r}else d=Xx(a,c,n);l=Dl(l.length,i)}Ml("max",l,i);const[f,m]=Rl(d.shape,l);let g,y=f;if(o&&(y=$l(f,u)),h){const e=n.texData.get(d.dataId).values,t=Qb(e,et(m),y,a.dtype);g=n.makeTensorInfo(y,a.dtype),n.texData.get(g.dataId).values=t}else g=function(e,t,n,r){const a=et(t),s=sx({inputs:{x:e},attrs:{shape:[et(e.shape)/a,a]},backend:r}),o=jx(s,e.dtype,"max",r),i=sx({inputs:{x:o},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(o),i}(d,m,y,n);return p&&n.disposeIntermediateTensorInfo(d),g}({inputs:{x:a},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),u=$l(i.shape,o),l=sx({inputs:{x:i},backend:n,attrs:{shape:u}}),c=Vv({inputs:{a,b:l},backend:n}),p=Jv({inputs:{x:c},backend:n}),h=Yx({inputs:{x:p},backend:n,attrs:{axis:o,keepDims:!1}}),d=sx({inputs:{x:h},backend:n,attrs:{shape:u}}),f=Nx({inputs:{a:p,b:d},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(d),f}};class ew{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode="\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}}class tw{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode="\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n }\n "}}const nw={kernelName:Ht,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{clipValueMin:s,clipValueMax:o}=r;let i;i=Ct().getBool("WEBGL_PACK_CLIP")?new tw(a.shape):new ew(a.shape);const u=[[s],[o]];return n.runWebGLProgram(i,[a],a.dtype,u)}};class rw{constructor(e,t,n,r=!1,a=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const s=e.filterWidth,o=e.strideHeight,i=e.strideWidth,u=e.dilationHeight,l=e.dilationWidth,c=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=e.padInfo.top,d=e.padInfo.left;this.outputShape=e.outShape;const f="avg"===t,m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let y="0.0";if(f||(y="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\n const ivec2 strides = ivec2(${o}, ${i});\n const ivec2 pads = ivec2(${h}, ${d});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < ${c};\n wR += ${u}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${p};\n wC += ${l}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value ${t} currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${r?a?m:g:`wR * ${p} + wC`};\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `)}let b=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(b="avgValue / max(count, 1.0)");const _=4*Math.floor(s/4),x=s%4,v=`\n if (${f}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n `;this.userCode=`\n const ivec2 strides = ivec2(${o}, ${i});\n const ivec2 pads = ivec2(${h}, ${d});\n const float initializationValue = ${y};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= ${e.inWidth}) {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4(${y});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < ${c};\n wR += ${u}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${_}; wC += 4) {\n int xC = xCCorner + wC * ${l};\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${l}, d),\n getValue(batch, xR, xC + 2 * ${l}, d),\n getValue(batch, xR, xC + 3 * ${l}, d)\n );\n\n ${v}\n }\n\n int xC = xCCorner + ${_};\n if (${1===x}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${v}\n } else if (${2===x}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${l}, d),\n initializationValue,\n initializationValue\n );\n\n ${v}\n } else if (${3===x}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${l}, d),\n getValue(batch, xR, xC + 2 * ${l}, d),\n initializationValue\n );\n\n ${v}\n }\n }\n setOutput(${b});\n }\n `}}const aw={kernelName:Bt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;!function(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&Qe("complex64"!==e.dtype,(()=>"avgPool does not support complex64 tensors in the WebGL backend."))}))}(a);const{filterSize:s,strides:o,pad:i,dimRoundingMode:u}=r;Qe(Au(o,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '1'`));const l=vu(a.shape,s,o,1,i,u);if(1===l.filterWidth&&1===l.filterHeight&&tt(l.inShape,l.outShape))return hx({inputs:{x:a},backend:n});const c=new rw(l,"avg",!1);return n.runWebGLProgram(c,[a],"float32")}},sw={kernelName:Ut,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a,b:s}=t,{transposeA:o,transposeB:i}=r;return Zx({a,b:s,transposeA:o,transposeB:i,backend:n})}},ow={kernelName:Sr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a,b:s,bias:o,preluActivationWeights:i}=t,{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:p}=r;return Zx({a,b:s,transposeA:u,transposeB:l,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:p,activation:c})}};Or(Og),Or(Dg),Or(Em),Or(Bg),Or(Ug),Or(Vg),Or(Yg),Or(Zg),Or(Mm),Or(ey),Or(Jg),Or(ty),Or(ng),Or(qg),Or(ny),Or(oy),Or(iy),Or(jg),Or(mg),Or(Tm),Or(uy),Or(ly),Or(ay),Or(Ag),Or(cy),Or(py),Or(dy),Or(bg),Or(fy),Or(gy),Or(yy),Or(by),Or(nx),Or(ox),Or(ux),Or(px),Or(Ex),Or(Cx),Or(Fx),Or(rv),Or(av),Or(iv),Or(cv),Or(pv),Or(hv),Or(bv),Or(Wx),Or(xv),Or(wv),Or(Cv),Or(Rv),Or(Mv),Or(Ov),Or(dx),Or(Lv),Or(Uv),Or(Nv),Or(Wv),Or(Hv),Or(Yv),Or(Qv),Or(yv),Or(Zv),Or(nw),Or(aw),Or(sw),Or(ow);var iw={filename:""};function uw(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(1===e.length){var n=e[0];if(m(n))return lw(n,null);if(g(n)&&Object.getPrototypeOf(n)===Object.prototype){var r=Object.keys(n);return lw(r.map((function(e){return n[e]})),r)}}if("function"==typeof e[e.length-1]){var a=e.pop();return lw(e=1===e.length&&m(e[0])?e[0]:e,null).pipe(K((function(e){return a.apply(void 0,e)})))}return lw(e,null)}function lw(e,t){return new S((function(n){var r=e.length;if(0!==r)for(var a=new Array(r),s=0,o=0,i=function(i){var u=G(e[i]),l=!1;n.add(u.subscribe({next:function(e){l||(l=!0,o++),a[i]=e},error:function(e){return n.error(e)},complete:function(){++s!==r&&l||(o===r&&n.next(t?t.reduce((function(e,t,n){return e[t]=a[n],e}),{}):a),n.complete())}}))},u=0;u<r;u++)i(u);else n.complete()}))}var cw="undefined"!=typeof window&&window,pw="undefined"!=typeof self&&"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&self,hw=cw||void 0!==_e&&_e||pw;function dw(e,t){return void 0===t&&(t=null),new xw({method:"GET",url:e,headers:t})}function fw(e,t,n){return new xw({method:"POST",url:e,body:t,headers:n})}function mw(e,t){return new xw({method:"DELETE",url:e,headers:t})}function gw(e,t,n){return new xw({method:"PUT",url:e,body:t,headers:n})}function yw(e,t,n){return new xw({method:"PATCH",url:e,body:t,headers:n})}var bw=K((function(e,t){return e.response}));function _w(e,t){return bw(new xw({method:"GET",url:e,responseType:"json",headers:t}))}var xw=function(e){function t(t){var n=e.call(this)||this,r={async:!0,createXHR:function(){return this.crossDomain?function(){if(hw.XMLHttpRequest)return new hw.XMLHttpRequest;if(hw.XDomainRequest)return new hw.XDomainRequest;throw new Error("CORS is not supported by your browser")}():function(){if(hw.XMLHttpRequest)return new hw.XMLHttpRequest;var e=void 0;try{for(var t=["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP.4.0"],n=0;n<3;n++)try{if(e=t[n],new hw.ActiveXObject(e))break}catch(e){}return new hw.ActiveXObject(e)}catch(e){throw new Error("XMLHttpRequest is not supported by your browser")}}()},crossDomain:!0,withCredentials:!1,headers:{},method:"GET",responseType:"json",timeout:0};if("string"==typeof t)r.url=t;else for(var a in t)t.hasOwnProperty(a)&&(r[a]=t[a]);return n.request=r,n}var n;return l(t,e),t.prototype._subscribe=function(e){return new vw(e,this.request)},t.create=((n=function(e){return new t(e)}).get=dw,n.post=fw,n.delete=mw,n.put=gw,n.patch=yw,n.getJSON=_w,n),t}(S),vw=function(e){function t(t,n){var r=e.call(this,t)||this;r.request=n,r.done=!1;var a=n.headers=n.headers||{};return n.crossDomain||r.getHeader(a,"X-Requested-With")||(a["X-Requested-With"]="XMLHttpRequest"),r.getHeader(a,"Content-Type")||hw.FormData&&n.body instanceof hw.FormData||void 0===n.body||(a["Content-Type"]="application/x-www-form-urlencoded; charset=UTF-8"),n.body=r.serializeBody(n.body,r.getHeader(n.headers,"Content-Type")),r.send(),r}return l(t,e),t.prototype.next=function(e){this.done=!0;var t,n=this,r=n.xhr,a=n.request,s=n.destination;try{t=new ww(e,r,a)}catch(e){return s.error(e)}s.next(t)},t.prototype.send=function(){var e=this.request,t=this.request,n=t.user,r=t.method,a=t.url,s=t.async,o=t.password,i=t.headers,u=t.body;try{var l=this.xhr=e.createXHR();this.setupEvents(l,e),n?l.open(r,a,s,n,o):l.open(r,a,s),s&&(l.timeout=e.timeout,l.responseType=e.responseType),"withCredentials"in l&&(l.withCredentials=!!e.withCredentials),this.setHeaders(l,i),u?l.send(u):l.send()}catch(e){this.error(e)}},t.prototype.serializeBody=function(e,t){if(!e||"string"==typeof e)return e;if(hw.FormData&&e instanceof hw.FormData)return e;if(t){var n=t.indexOf(";");-1!==n&&(t=t.substring(0,n))}switch(t){case"application/x-www-form-urlencoded":return Object.keys(e).map((function(t){return encodeURIComponent(t)+"="+encodeURIComponent(e[t])})).join("&");case"application/json":return JSON.stringify(e);default:return e}},t.prototype.setHeaders=function(e,t){for(var n in t)t.hasOwnProperty(n)&&e.setRequestHeader(n,t[n])},t.prototype.getHeader=function(e,t){for(var n in e)if(n.toLowerCase()===t.toLowerCase())return e[n]},t.prototype.setupEvents=function(e,t){var n,r,a=t.progressSubscriber;function s(e){var t,n=s,r=n.subscriber,a=n.progressSubscriber,o=n.request;a&&a.error(e);try{t=new Iw(this,o)}catch(e){t=e}r.error(t)}function o(e){}function i(e){var t=i,n=t.subscriber,r=t.progressSubscriber,a=t.request;if(4===this.readyState){var s=1223===this.status?204:this.status,o="text"===this.responseType?this.response||this.responseText:this.response;if(0===s&&(s=o?200:0),s<400)r&&r.complete(),n.next(e),n.complete();else{r&&r.error(e);var u=void 0;try{u=new Tw("ajax error "+s,this,a)}catch(e){u=e}n.error(u)}}}e.ontimeout=s,s.request=t,s.subscriber=this,s.progressSubscriber=a,e.upload&&"withCredentials"in e&&(a&&(n=function(e){n.progressSubscriber.next(e)},hw.XDomainRequest?e.onprogress=n:e.upload.onprogress=n,n.progressSubscriber=a),r=function(e){var t,n=r,a=n.progressSubscriber,s=n.subscriber,o=n.request;a&&a.error(e);try{t=new Tw("ajax error",this,o)}catch(e){t=e}s.error(t)},e.onerror=r,r.request=t,r.subscriber=this,r.progressSubscriber=a),e.onreadystatechange=o,o.subscriber=this,o.progressSubscriber=a,o.request=t,e.onload=i,i.subscriber=this,i.progressSubscriber=a,i.request=t},t.prototype.unsubscribe=function(){var t=this.done,n=this.xhr;!t&&n&&4!==n.readyState&&"function"==typeof n.abort&&n.abort(),e.prototype.unsubscribe.call(this)},t}(w),ww=function(e,t,n){this.originalEvent=e,this.xhr=t,this.request=n,this.status=t.status,this.responseType=t.responseType||n.responseType,this.response=kw(this.responseType,t)},Tw=function(){function e(e,t,n){return Error.call(this),this.message=e,this.name="AjaxError",this.xhr=t,this.request=n,this.status=t.status,this.responseType=t.responseType||n.responseType,this.response=kw(this.responseType,t),this}return e.prototype=Object.create(Error.prototype),e}();function kw(e,t){switch(e){case"json":return function(e){return"response"in e?e.responseType?e.response:JSON.parse(e.response||e.responseText||"null"):JSON.parse(e.responseText||"null")}(t);case"xml":return t.responseXML;default:return"response"in t?t.response:t.responseText}}var Iw=function(e,t){return Tw.call(this,"ajax timeout",e,t),this.name="AjaxTimeoutError",this},Sw=xw.create,Ew=Uint8Array,Nw=Uint16Array,Cw=Uint32Array,Aw=new Ew([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Rw=new Ew([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),$w=new Ew([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Mw=function(e,t){for(var n=new Nw(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];var a=new Cw(n[30]);for(r=1;r<30;++r)for(var s=n[r];s<n[r+1];++s)a[s]=s-n[r]<<5|r;return[n,a]},Fw=Mw(Aw,2),Ow=Fw[0],Dw=Fw[1];Ow[28]=258,Dw[258]=28;for(var Lw=Mw(Rw,0)[0],Pw=new Nw(32768),Bw=0;Bw<32768;++Bw){var Uw=(43690&Bw)>>>1|(21845&Bw)<<1;Uw=(61680&(Uw=(52428&Uw)>>>2|(13107&Uw)<<2))>>>4|(3855&Uw)<<4,Pw[Bw]=((65280&Uw)>>>8|(255&Uw)<<8)>>>1}var zw=function(e,t,n){for(var r=e.length,a=0,s=new Nw(t);a<r;++a)++s[e[a]-1];var o,i=new Nw(t);for(a=0;a<t;++a)i[a]=i[a-1]+s[a-1]<<1;if(n){o=new Nw(1<<t);var u=15-t;for(a=0;a<r;++a)if(e[a])for(var l=a<<4|e[a],c=t-e[a],p=i[e[a]-1]++<<c,h=p|(1<<c)-1;p<=h;++p)o[Pw[p]>>>u]=l}else for(o=new Nw(r),a=0;a<r;++a)e[a]&&(o[a]=Pw[i[e[a]-1]++]>>>15-e[a]);return o},Vw=new Ew(288);for(Bw=0;Bw<144;++Bw)Vw[Bw]=8;for(Bw=144;Bw<256;++Bw)Vw[Bw]=9;for(Bw=256;Bw<280;++Bw)Vw[Bw]=7;for(Bw=280;Bw<288;++Bw)Vw[Bw]=8;var Ww=new Ew(32);for(Bw=0;Bw<32;++Bw)Ww[Bw]=5;var Hw=zw(Vw,9,1),Gw=zw(Ww,5,1),jw=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},Kw=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(7&t)&n},qw=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},Xw=function(e,t,n){(null==t||t<0)&&(t=0),(null==n||n>e.length)&&(n=e.length);var r=new(e instanceof Nw?Nw:e instanceof Cw?Cw:Ew)(n-t);return r.set(e.subarray(t,n)),r},Yw=function(e,t,n){var r=e.length;if(!r||n&&!n.l&&r<5)return t||new Ew(0);var a=!t||n,s=!n||n.i;n||(n={}),t||(t=new Ew(3*r));var o,i=function(e){var n=t.length;if(e>n){var r=new Ew(Math.max(2*n,e));r.set(t),t=r}},u=n.f||0,l=n.p||0,c=n.b||0,p=n.l,h=n.d,d=n.m,f=n.n,m=8*r;do{if(!p){n.f=u=Kw(e,l,1);var g=Kw(e,l+1,3);if(l+=3,!g){var y=e[(N=((o=l)/8|0)+(7&o&&1)+4)-4]|e[N-3]<<8,b=N+y;if(b>r){if(s)throw"unexpected EOF";break}a&&i(c+y),t.set(e.subarray(N,b),c),n.b=c+=y,n.p=l=8*b;continue}if(1==g)p=Hw,h=Gw,d=9,f=5;else{if(2!=g)throw"invalid block type";var _=Kw(e,l,31)+257,x=Kw(e,l+10,15)+4,v=_+Kw(e,l+5,31)+1;l+=14;for(var w=new Ew(v),T=new Ew(19),k=0;k<x;++k)T[$w[k]]=Kw(e,l+3*k,7);l+=3*x;var I=jw(T),S=(1<<I)-1,E=zw(T,I,1);for(k=0;k<v;){var N,C=E[Kw(e,l,S)];if(l+=15&C,(N=C>>>4)<16)w[k++]=N;else{var A=0,R=0;for(16==N?(R=3+Kw(e,l,3),l+=2,A=w[k-1]):17==N?(R=3+Kw(e,l,7),l+=3):18==N&&(R=11+Kw(e,l,127),l+=7);R--;)w[k++]=A}}var $=w.subarray(0,_),M=w.subarray(_);d=jw($),f=jw(M),p=zw($,d,1),h=zw(M,f,1)}if(l>m){if(s)throw"unexpected EOF";break}}a&&i(c+131072);for(var F=(1<<d)-1,O=(1<<f)-1,D=l;;D=l){var L=(A=p[qw(e,l)&F])>>>4;if((l+=15&A)>m){if(s)throw"unexpected EOF";break}if(!A)throw"invalid length/literal";if(L<256)t[c++]=L;else{if(256==L){D=l,p=null;break}var P=L-254;if(L>264){var B=Aw[k=L-257];P=Kw(e,l,(1<<B)-1)+Ow[k],l+=B}var U=h[qw(e,l)&O],z=U>>>4;if(!U)throw"invalid distance";if(l+=15&U,M=Lw[z],z>3&&(B=Rw[z],M+=qw(e,l)&(1<<B)-1,l+=B),l>m){if(s)throw"unexpected EOF";break}a&&i(c+131072);for(var V=c+P;c<V;c+=4)t[c]=t[c-M],t[c+1]=t[c+1-M],t[c+2]=t[c+2-M],t[c+3]=t[c+3-M];c=V}}n.l=p,n.p=D,n.b=c,p&&(u=1,n.m=d,n.d=h,n.n=f)}while(!u);return c==t.length?t:Xw(t,0,c)},Qw=new Ew(0),Jw=function(e,t){return e[t]|e[t+1]<<8},Zw=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},eT=function(e,t){return Zw(e,t)+4294967296*Zw(e,t+4)};function tT(e,t){return Yw(e,t)}var nT="undefined"!=typeof TextDecoder&&new TextDecoder;try{nT.decode(Qw,{stream:!0})}catch(e){}var rT=function(e){for(var t="",n=0;;){var r=e[n++],a=(r>127)+(r>223)+(r>239);if(n+a>e.length)return[t,Xw(e,n-1)];a?3==a?(r=((15&r)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t+=String.fromCharCode(55296|r>>10,56320|1023&r)):t+=1&a?String.fromCharCode((31&r)<<6|63&e[n++]):String.fromCharCode((15&r)<<12|(63&e[n++])<<6|63&e[n++]):t+=String.fromCharCode(r)}};function aT(e,t){if(t){for(var n="",r=0;r<e.length;r+=16384)n+=String.fromCharCode.apply(null,e.subarray(r,r+16384));return n}if(nT)return nT.decode(e);var a=rT(e),s=a[0];if(a[1].length)throw"invalid utf-8 data";return s}var sT=function(e,t){return t+30+Jw(e,t+26)+Jw(e,t+28)},oT=function(e,t,n){var r=Jw(e,t+28),a=aT(e.subarray(t+46,t+46+r),!(2048&Jw(e,t+8))),s=t+46+r,o=Zw(e,t+20),i=n&&4294967295==o?iT(e,s):[o,Zw(e,t+24),Zw(e,t+42)],u=i[0],l=i[1],c=i[2];return[Jw(e,t+10),u,l,a,s+Jw(e,t+30)+Jw(e,t+32),c]},iT=function(e,t){for(;1!=Jw(e,t);t+=4+Jw(e,t+2));return[eT(e,t+12),eT(e,t+4),eT(e,t+20)]};function uT(e){for(var t={},n=e.length-22;101010256!=Zw(e,n);--n)if(!n||e.length-n>65558)throw"invalid zip file";var r=Jw(e,n+8);if(!r)return{};var a=Zw(e,n+16),s=4294967295==a;if(s){if(n=Zw(e,n-12),101075792!=Zw(e,n))throw"invalid zip file";r=Zw(e,n+32),a=Zw(e,n+48)}for(var o=0;o<r;++o){var i=oT(e,a,s),u=i[0],l=i[1],c=i[2],p=i[3],h=i[4],d=i[5],f=sT(e,d);if(a=h,u){if(8!=u)throw"unknown compression type "+u;t[p]=tT(e.subarray(f,f+l),new Ew(c))}else t[p]=Xw(e,f,f+l)}return t}function lT(e){if(e)for(var t=0;t<e.length;t++)e[t]=~e[t];return e}var cT=function(){function e(e,t){this.jsonModel=e,this.weights=t}return e.prototype.load=function(){return a(this,void 0,void 0,(function(){var e,t,n,r;return s(this,(function(a){switch(a.label){case 0:return e={modelTopology:this.jsonModel.modelTopology,format:this.jsonModel.format,generatedBy:this.jsonModel.generatedBy,convertedBy:this.jsonModel.convertedBy},null==this.jsonModel.weightsManifest?[3,2]:[4,this.loadWeights()];case 1:t=a.sent(),n=t[0],r=t[1],e.weightSpecs=n,e.weightData=r,a.label=2;case 2:return null!=this.jsonModel.trainingConfig&&(e.trainingConfig=this.jsonModel.trainingConfig),null!=this.jsonModel.userDefinedMetadata&&(e.userDefinedMetadata=this.jsonModel.userDefinedMetadata),[2,e]}}))}))},e.prototype.loadWeights=function(){return a(this,void 0,void 0,(function(){var e,t,n,r,a,o,i,u;return s(this,(function(s){for(e=[],t=[],n=0,r=this.jsonModel.weightsManifest;n<r.length;n++){for(a=r[n],o=0,i=a.paths;o<i.length;o++){if(u=i[o],!this.weights[u])throw new Error("Error loading weights: cannot find ".concat(u));e.push(this.weights[u])}t.push.apply(t,a.weights)}return[2,[t,this.toArrayBuffer(e)]]}))}))},e.prototype.toArrayBuffer=function(e){if(Array.isArray(e)){for(var t=0,n=0,r=e;n<r.length;n++)t+=r[n].length;for(var a=new ArrayBuffer(t),s=new Uint8Array(a),o=0,i=0,u=e;i<u.length;i++)o+=u[i].copy(s,o);return a}return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)},e}(),pT=[],hT=[],dT="undefined"!=typeof Uint8Array?Uint8Array:Array,fT=!1;function mT(){fT=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0;t<64;++t)pT[t]=e[t],hT[e.charCodeAt(t)]=t;hT["-".charCodeAt(0)]=62,hT["_".charCodeAt(0)]=63}function gT(e,t,n){for(var r,a,s=[],o=t;o<n;o+=3)r=(e[o]<<16)+(e[o+1]<<8)+e[o+2],s.push(pT[(a=r)>>18&63]+pT[a>>12&63]+pT[a>>6&63]+pT[63&a]);return s.join("")}function yT(e){var t;fT||mT();for(var n=e.length,r=n%3,a="",s=[],o=16383,i=0,u=n-r;i<u;i+=o)s.push(gT(e,i,i+o>u?u:i+o));return 1===r?(t=e[n-1],a+=pT[t>>2],a+=pT[t<<4&63],a+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],a+=pT[t>>10],a+=pT[t>>4&63],a+=pT[t<<2&63],a+="="),s.push(a),s.join("")}function bT(e,t,n,r,a){var s,o,i=8*a-r-1,u=(1<<i)-1,l=u>>1,c=-7,p=n?a-1:0,h=n?-1:1,d=e[t+p];for(p+=h,s=d&(1<<-c)-1,d>>=-c,c+=i;c>0;s=256*s+e[t+p],p+=h,c-=8);for(o=s&(1<<-c)-1,s>>=-c,c+=r;c>0;o=256*o+e[t+p],p+=h,c-=8);if(0===s)s=1-l;else{if(s===u)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,r),s-=l}return(d?-1:1)*o*Math.pow(2,s-r)}function _T(e,t,n,r,a,s){var o,i,u,l=8*s-a-1,c=(1<<l)-1,p=c>>1,h=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:s-1,f=r?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-o))<1&&(o--,u*=2),(t+=o+p>=1?h/u:h*Math.pow(2,1-p))*u>=2&&(o++,u/=2),o+p>=c?(i=0,o=c):o+p>=1?(i=(t*u-1)*Math.pow(2,a),o+=p):(i=t*Math.pow(2,p-1)*Math.pow(2,a),o=0));a>=8;e[n+d]=255&i,d+=f,i/=256,a-=8);for(o=o<<a|i,l+=a;l>0;e[n+d]=255&o,d+=f,o/=256,l-=8);e[n+d-f]|=128*m}var xT={}.toString,vT=Array.isArray||function(e){return"[object Array]"==xT.call(e)};function wT(){return kT.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function TT(e,t){if(wT()<t)throw new RangeError("Invalid typed array length");return kT.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=kT.prototype:(null===e&&(e=new kT(t)),e.length=t),e}function kT(e,t,n){if(!(kT.TYPED_ARRAY_SUPPORT||this instanceof kT))return new kT(e,t,n);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return ET(this,e)}return IT(this,e,t,n)}function IT(e,t,n,r){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?function(e,t,n,r){if(t.byteLength,n<0||t.byteLength<n)throw new RangeError("'offset' is out of bounds");if(t.byteLength<n+(r||0))throw new RangeError("'length' is out of bounds");return t=void 0===n&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,n):new Uint8Array(t,n,r),kT.TYPED_ARRAY_SUPPORT?(e=t).__proto__=kT.prototype:e=NT(e,t),e}(e,t,n,r):"string"==typeof t?function(e,t,n){if("string"==typeof n&&""!==n||(n="utf8"),!kT.isEncoding(n))throw new TypeError('"encoding" must be a valid string encoding');var r=0|RT(t,n),a=(e=TT(e,r)).write(t,n);return a!==r&&(e=e.slice(0,a)),e}(e,t,n):function(e,t){if(AT(t)){var n=0|CT(t.length);return 0===(e=TT(e,n)).length||t.copy(e,0,0,n),e}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||(r=t.length)!=r?TT(e,0):NT(e,t);if("Buffer"===t.type&&vT(t.data))return NT(e,t.data)}var r;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function ST(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function ET(e,t){if(ST(t),e=TT(e,t<0?0:0|CT(t)),!kT.TYPED_ARRAY_SUPPORT)for(var n=0;n<t;++n)e[n]=0;return e}function NT(e,t){var n=t.length<0?0:0|CT(t.length);e=TT(e,n);for(var r=0;r<n;r+=1)e[r]=255&t[r];return e}function CT(e){if(e>=wT())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+wT().toString(16)+" bytes");return 0|e}function AT(e){return!(null==e||!e._isBuffer)}function RT(e,t){if(AT(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return ak(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return sk(e).length;default:if(r)return ak(e).length;t=(""+t).toLowerCase(),r=!0}}function $T(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return KT(this,t,n);case"utf8":case"utf-8":return WT(this,t,n);case"ascii":return GT(this,t,n);case"latin1":case"binary":return jT(this,t,n);case"base64":return VT(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return qT(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function MT(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function FT(e,t,n,r,a){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)return-1;n=0}if("string"==typeof t&&(t=kT.from(t,r)),AT(t))return 0===t.length?-1:OT(e,t,n,r,a);if("number"==typeof t)return t&=255,kT.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):OT(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function OT(e,t,n,r,a){var s,o=1,i=e.length,u=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,i/=2,u/=2,n/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(a){var c=-1;for(s=n;s<i;s++)if(l(e,s)===l(t,-1===c?0:s-c)){if(-1===c&&(c=s),s-c+1===u)return c*o}else-1!==c&&(s-=s-c),c=-1}else for(n+u>i&&(n=i-u),s=n;s>=0;s--){for(var p=!0,h=0;h<u;h++)if(l(e,s+h)!==l(t,h)){p=!1;break}if(p)return s}return-1}function DT(e,t,n,r){n=Number(n)||0;var a=e.length-n;r?(r=Number(r))>a&&(r=a):r=a;var s=t.length;if(s%2!=0)throw new TypeError("Invalid hex string");r>s/2&&(r=s/2);for(var o=0;o<r;++o){var i=parseInt(t.substr(2*o,2),16);if(isNaN(i))return o;e[n+o]=i}return o}function LT(e,t,n,r){return ok(ak(t,e.length-n),e,n,r)}function PT(e,t,n,r){return ok(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function BT(e,t,n,r){return PT(e,t,n,r)}function UT(e,t,n,r){return ok(sk(t),e,n,r)}function zT(e,t,n,r){return ok(function(e,t){for(var n,r,a,s=[],o=0;o<e.length&&!((t-=2)<0);++o)r=(n=e.charCodeAt(o))>>8,a=n%256,s.push(a),s.push(r);return s}(t,e.length-n),e,n,r)}function VT(e,t,n){return 0===t&&n===e.length?yT(e):yT(e.slice(t,n))}function WT(e,t,n){n=Math.min(e.length,n);for(var r=[],a=t;a<n;){var s,o,i,u,l=e[a],c=null,p=l>239?4:l>223?3:l>191?2:1;if(a+p<=n)switch(p){case 1:l<128&&(c=l);break;case 2:128==(192&(s=e[a+1]))&&(u=(31&l)<<6|63&s)>127&&(c=u);break;case 3:s=e[a+1],o=e[a+2],128==(192&s)&&128==(192&o)&&(u=(15&l)<<12|(63&s)<<6|63&o)>2047&&(u<55296||u>57343)&&(c=u);break;case 4:s=e[a+1],o=e[a+2],i=e[a+3],128==(192&s)&&128==(192&o)&&128==(192&i)&&(u=(15&l)<<18|(63&s)<<12|(63&o)<<6|63&i)>65535&&u<1114112&&(c=u)}null===c?(c=65533,p=1):c>65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|1023&c),r.push(c),a+=p}return function(e){var t=e.length;if(t<=HT)return String.fromCharCode.apply(String,e);for(var n="",r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=HT));return n}(r)}kT.TYPED_ARRAY_SUPPORT=void 0===_e.TYPED_ARRAY_SUPPORT||_e.TYPED_ARRAY_SUPPORT,wT(),kT.poolSize=8192,kT._augment=function(e){return e.__proto__=kT.prototype,e},kT.from=function(e,t,n){return IT(null,e,t,n)},kT.TYPED_ARRAY_SUPPORT&&(kT.prototype.__proto__=Uint8Array.prototype,kT.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&kT[Symbol.species]),kT.alloc=function(e,t,n){return function(e,t,n,r){return ST(t),t<=0?TT(e,t):void 0!==n?"string"==typeof r?TT(e,t).fill(n,r):TT(e,t).fill(n):TT(e,t)}(null,e,t,n)},kT.allocUnsafe=function(e){return ET(null,e)},kT.allocUnsafeSlow=function(e){return ET(null,e)},kT.isBuffer=function(e){return null!=e&&(!!e._isBuffer||ik(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&ik(e.slice(0,0))}(e))},kT.compare=function(e,t){if(!AT(e)||!AT(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,a=0,s=Math.min(n,r);a<s;++a)if(e[a]!==t[a]){n=e[a],r=t[a];break}return n<r?-1:r<n?1:0},kT.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},kT.concat=function(e,t){if(!vT(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return kT.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=kT.allocUnsafe(t),a=0;for(n=0;n<e.length;++n){var s=e[n];if(!AT(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(r,a),a+=s.length}return r},kT.byteLength=RT,kT.prototype._isBuffer=!0,kT.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)MT(this,t,t+1);return this},kT.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)MT(this,t,t+3),MT(this,t+1,t+2);return this},kT.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)MT(this,t,t+7),MT(this,t+1,t+6),MT(this,t+2,t+5),MT(this,t+3,t+4);return this},kT.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?WT(this,0,e):$T.apply(this,arguments)},kT.prototype.equals=function(e){if(!AT(e))throw new TypeError("Argument must be a Buffer");return this===e||0===kT.compare(this,e)},kT.prototype.inspect=function(){var e="";return this.length>0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),"<Buffer "+e+">"},kT.prototype.compare=function(e,t,n,r,a){if(!AT(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;for(var s=(a>>>=0)-(r>>>=0),o=(n>>>=0)-(t>>>=0),i=Math.min(s,o),u=this.slice(r,a),l=e.slice(t,n),c=0;c<i;++c)if(u[c]!==l[c]){s=u[c],o=l[c];break}return s<o?-1:o<s?1:0},kT.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},kT.prototype.indexOf=function(e,t,n){return FT(this,e,t,n,!0)},kT.prototype.lastIndexOf=function(e,t,n){return FT(this,e,t,n,!1)},kT.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(n)?(n|=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var a=this.length-t;if((void 0===n||n>a)&&(n=a),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return DT(this,e,t,n);case"utf8":case"utf-8":return LT(this,e,t,n);case"ascii":return PT(this,e,t,n);case"latin1":case"binary":return BT(this,e,t,n);case"base64":return UT(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return zT(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},kT.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var HT=4096;function GT(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(127&e[a]);return r}function jT(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(e[a]);return r}function KT(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var a="",s=t;s<n;++s)a+=rk(e[s]);return a}function qT(e,t,n){for(var r=e.slice(t,n),a="",s=0;s<r.length;s+=2)a+=String.fromCharCode(r[s]+256*r[s+1]);return a}function XT(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function YT(e,t,n,r,a,s){if(!AT(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||t<s)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function QT(e,t,n,r){t<0&&(t=65535+t+1);for(var a=0,s=Math.min(e.length-n,2);a<s;++a)e[n+a]=(t&255<<8*(r?a:1-a))>>>8*(r?a:1-a)}function JT(e,t,n,r){t<0&&(t=4294967295+t+1);for(var a=0,s=Math.min(e.length-n,4);a<s;++a)e[n+a]=t>>>8*(r?a:3-a)&255}function ZT(e,t,n,r,a,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function ek(e,t,n,r,a){return a||ZT(e,0,n,4),_T(e,t,n,r,23,4),n+4}function tk(e,t,n,r,a){return a||ZT(e,0,n,8),_T(e,t,n,r,52,8),n+8}kT.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e),kT.TYPED_ARRAY_SUPPORT)(n=this.subarray(e,t)).__proto__=kT.prototype;else{var a=t-e;n=new kT(a,void 0);for(var s=0;s<a;++s)n[s]=this[s+e]}return n},kT.prototype.readUIntLE=function(e,t,n){e|=0,t|=0,n||XT(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r},kT.prototype.readUIntBE=function(e,t,n){e|=0,t|=0,n||XT(e,t,this.length);for(var r=this[e+--t],a=1;t>0&&(a*=256);)r+=this[e+--t]*a;return r},kT.prototype.readUInt8=function(e,t){return t||XT(e,1,this.length),this[e]},kT.prototype.readUInt16LE=function(e,t){return t||XT(e,2,this.length),this[e]|this[e+1]<<8},kT.prototype.readUInt16BE=function(e,t){return t||XT(e,2,this.length),this[e]<<8|this[e+1]},kT.prototype.readUInt32LE=function(e,t){return t||XT(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},kT.prototype.readUInt32BE=function(e,t){return t||XT(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},kT.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||XT(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r>=(a*=128)&&(r-=Math.pow(2,8*t)),r},kT.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||XT(e,t,this.length);for(var r=t,a=1,s=this[e+--r];r>0&&(a*=256);)s+=this[e+--r]*a;return s>=(a*=128)&&(s-=Math.pow(2,8*t)),s},kT.prototype.readInt8=function(e,t){return t||XT(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},kT.prototype.readInt16LE=function(e,t){t||XT(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},kT.prototype.readInt16BE=function(e,t){t||XT(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},kT.prototype.readInt32LE=function(e,t){return t||XT(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},kT.prototype.readInt32BE=function(e,t){return t||XT(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},kT.prototype.readFloatLE=function(e,t){return t||XT(e,4,this.length),bT(this,e,!0,23,4)},kT.prototype.readFloatBE=function(e,t){return t||XT(e,4,this.length),bT(this,e,!1,23,4)},kT.prototype.readDoubleLE=function(e,t){return t||XT(e,8,this.length),bT(this,e,!0,52,8)},kT.prototype.readDoubleBE=function(e,t){return t||XT(e,8,this.length),bT(this,e,!1,52,8)},kT.prototype.writeUIntLE=function(e,t,n,r){e=+e,t|=0,n|=0,r||YT(this,e,t,n,Math.pow(2,8*n)-1,0);var a=1,s=0;for(this[t]=255&e;++s<n&&(a*=256);)this[t+s]=e/a&255;return t+n},kT.prototype.writeUIntBE=function(e,t,n,r){e=+e,t|=0,n|=0,r||YT(this,e,t,n,Math.pow(2,8*n)-1,0);var a=n-1,s=1;for(this[t+a]=255&e;--a>=0&&(s*=256);)this[t+a]=e/s&255;return t+n},kT.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||YT(this,e,t,1,255,0),kT.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},kT.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||YT(this,e,t,2,65535,0),kT.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):QT(this,e,t,!0),t+2},kT.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||YT(this,e,t,2,65535,0),kT.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):QT(this,e,t,!1),t+2},kT.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||YT(this,e,t,4,4294967295,0),kT.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):JT(this,e,t,!0),t+4},kT.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||YT(this,e,t,4,4294967295,0),kT.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):JT(this,e,t,!1),t+4},kT.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);YT(this,e,t,n,a-1,-a)}var s=0,o=1,i=0;for(this[t]=255&e;++s<n&&(o*=256);)e<0&&0===i&&0!==this[t+s-1]&&(i=1),this[t+s]=(e/o>>0)-i&255;return t+n},kT.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);YT(this,e,t,n,a-1,-a)}var s=n-1,o=1,i=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===i&&0!==this[t+s+1]&&(i=1),this[t+s]=(e/o>>0)-i&255;return t+n},kT.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||YT(this,e,t,1,127,-128),kT.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},kT.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||YT(this,e,t,2,32767,-32768),kT.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):QT(this,e,t,!0),t+2},kT.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||YT(this,e,t,2,32767,-32768),kT.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):QT(this,e,t,!1),t+2},kT.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||YT(this,e,t,4,2147483647,-2147483648),kT.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):JT(this,e,t,!0),t+4},kT.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||YT(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),kT.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):JT(this,e,t,!1),t+4},kT.prototype.writeFloatLE=function(e,t,n){return ek(this,e,t,!0,n)},kT.prototype.writeFloatBE=function(e,t,n){return ek(this,e,t,!1,n)},kT.prototype.writeDoubleLE=function(e,t,n){return tk(this,e,t,!0,n)},kT.prototype.writeDoubleBE=function(e,t,n){return tk(this,e,t,!1,n)},kT.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var a,s=r-n;if(this===e&&n<t&&t<r)for(a=s-1;a>=0;--a)e[a+t]=this[a+n];else if(s<1e3||!kT.TYPED_ARRAY_SUPPORT)for(a=0;a<s;++a)e[a+t]=this[a+n];else Uint8Array.prototype.set.call(e,this.subarray(n,n+s),t);return s},kT.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),1===e.length){var a=e.charCodeAt(0);a<256&&(e=a)}if(void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!kT.isEncoding(r))throw new TypeError("Unknown encoding: "+r)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{var o=AT(e)?e:ak(new kT(e,r).toString()),i=o.length;for(s=0;s<n-t;++s)this[s+t]=o[s%i]}return this};var nk=/[^+\/0-9A-Za-z-_]/g;function rk(e){return e<16?"0"+e.toString(16):e.toString(16)}function ak(e,t){var n;t=t||1/0;for(var r=e.length,a=null,s=[],o=0;o<r;++o){if((n=e.charCodeAt(o))>55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&s.push(239,191,189);if(a=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function sk(e){return function(e){var t,n,r,a,s,o;fT||mT();var i=e.length;if(i%4>0)throw new Error("Invalid string. Length must be a multiple of 4");s="="===e[i-2]?2:"="===e[i-1]?1:0,o=new dT(3*i/4-s),r=s>0?i-4:i;var u=0;for(t=0,n=0;t<r;t+=4,n+=3)a=hT[e.charCodeAt(t)]<<18|hT[e.charCodeAt(t+1)]<<12|hT[e.charCodeAt(t+2)]<<6|hT[e.charCodeAt(t+3)],o[u++]=a>>16&255,o[u++]=a>>8&255,o[u++]=255&a;return 2===s?(a=hT[e.charCodeAt(t)]<<2|hT[e.charCodeAt(t+1)]>>4,o[u++]=255&a):1===s&&(a=hT[e.charCodeAt(t)]<<10|hT[e.charCodeAt(t+1)]<<4|hT[e.charCodeAt(t+2)]>>2,o[u++]=a>>8&255,o[u++]=255&a),o}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(nk,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function ok(e,t,n,r){for(var a=0;a<r&&!(a+n>=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function ik(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function uk(e,t){var n=new ie(0),r=new ie(0),a=new ie(0),s=new ie(0),o=V([n,r,a,s]).pipe(K((function(e){return e.reduce((function(t,n){return t+n/e.length}),0)})));if("string"==typeof e){var i=function(e,t){return Sw({url:e,method:"GET",responseType:"arraybuffer",async:!0,progressSubscriber:new w((function(e){return t.next(e.loaded/e.total)}),(function(e){}),(function(){return t.next(1)}))}).pipe(ue(2))}(e,n).pipe(pe((function(e){return lk(e.response)})),pe((function(e){return ck(e,t,r).pipe(K((function(t){return{jszip:e,config:t}})))})),pe((function(e){var t=e.jszip,n=e.config;return pk(t,n,a).pipe(K((function(e){return{jszip:t,config:n,jsonModel:e}})))})),pe((function(e){var t=e.jszip,n=e.config,r=e.jsonModel;return hk(t,r,s).pipe(K((function(e){return{config:n,jsonModel:r,weights:e}})))})),pe((function(e){var t=e.config,n=e.jsonModel,r=e.weights;return G(mm(new cT(n,r))).pipe(K((function(e){return{config:t,graphModel:e}})))})));return{model$:i,progress$:o}}return i=lk(e).pipe(pe((function(e){return ck(e,t,r).pipe(K((function(t){return{jszip:e,config:t}})))})),pe((function(e){var t=e.jszip,n=e.config;return pk(t,n,a).pipe(K((function(e){return{jszip:t,config:n,jsonModel:e}})))})),pe((function(e){var t=e.jszip,n=e.config,r=e.jsonModel;return hk(t,r,s).pipe(K((function(e){return{config:n,jsonModel:r,weights:e}})))})),pe((function(e){var t=e.config,n=e.jsonModel,r=e.weights;return G(mm(new cT(n,r))).pipe(K((function(e){return{config:t,graphModel:e}})))}))),{model$:i,progress$:o}}function lk(e){return j(uT(new Uint8Array(e)))}function ck(e,t,n){return e[t]||(t=t.substring(0,t.lastIndexOf("."))+".json",e[t])?be((function(){return n.next(1),t.includes(".bin")?j(JSON.parse(aT(lT(e[t])))):j(JSON.parse(aT(e[t])))})):Q("Unable to retrieve model config: ".concat(t," is missing"))}function pk(e,t,n){return t?e[t.filename]?be((function(){return n.next(1),j(JSON.parse(aT(lT(e[t.filename]))))})):Q("Error extracting model: ".concat(t.filename," is missing")):Q("Invalid model config")}function hk(e,t,n){if(!t)return Q("Unable to extract weights: model is undefined");if(!t.weightsManifest)return n.next(1),j({});for(var r=0,a=0,s=t.weightsManifest;a<s.length;a++){var o=s[a];r+=o.paths.length}for(var i=new Array(r).fill(0),u={},l=0,c=0,p=t.weightsManifest;c<p.length;c++)for(var h=function(t){if(!e[t])return{value:Q("Error extracting weight: ".concat(t," is missing"))};u[t]=be((function(){var a=e[t];return i[l]=1,n.next(i.reduce((function(e,t){return e+t}),0)/r),j(lT(kT.from(a,a.byteOffset,a.byteLength)))})),l++},d=0,f=(o=p[c]).paths;d<f.length;d++){var m=h(f[d]);if("object"==typeof m)return m.value}return uw(u)}Rt.set("DEPRECATION_WARNINGS_ENABLED",!1),Rt.global.Math=Math,Rt.global.Float32Array=Float32Array,Ct().set("WEBGL_FORCE_F16_TEXTURES",!0);var dk,fk,mk,gk=function(){function e(){this._initialized=!1}return e.prototype.getWidth=function(){return this._modelConfig?this._modelConfig.inWidth:0},e.prototype.getHeight=function(){return this._modelConfig?this._modelConfig.inHeight:0},e.prototype.isInitialized=function(){return this._initialized},e.prototype.getOutput=function(){return this._cnnOutputData},e.prototype.initialize=function(e,n,r){return a(this,void 0,void 0,(function(){var a,o,i,u,l=this;return s(this,(function(s){switch(s.label){case 0:if(null==e)throw"Invalid parameter";return this.release(),this._videoManager=e,this._config=n?t(t({},iw),n):iw,a=uk(this._config.filename,"config.json"),o=a.model$,i=a.progress$,u=i.pipe(K((function(e){return r&&r(e)}))).subscribe(),[4,o.pipe(K((function(e){var t=e.config,n=e.graphModel;l._modelConfig=t,l._model=n;var r=Nc([1,l._modelConfig.inHeight,l._modelConfig.inWidth,l._modelConfig.inChannels]),a=l._model.predict(r,{batchSize:1,verbose:!0});Array.isArray(a)?a.forEach((function(e){e.dispose()})):a.dispose(),l._cnnOutput=Nc([1,l._modelConfig.inHeight,l._modelConfig.inWidth,1]),r.dispose(),l._initialized=!0})),Z((function(){return u.unsubscribe()}))).toPromise()];case 1:return s.sent(),[2]}}))}))},e.prototype.processSync=function(){var e;if(this._initialized){var t=this._videoManager.getLastBuffer();if(null!=t){var n,r=Li(t),a=pd.resizeBilinear(r,[this._modelConfig.inHeight,this._modelConfig.inWidth]),s=bi(a,"float32"),o=Fu(s,[1,this._modelConfig.inHeight,this._modelConfig.inWidth,3]),i=Ul(255);if(4==this._modelConfig.inChannels){var u=Fu(this._cnnOutput,[1,this._modelConfig.inHeight,this._modelConfig.inWidth,1]),l=ou(o,i);n=Pu([l,u],3),l.dispose(),u.dispose()}else n=ou(o,i);var c,p=this._model.predict(n);c=Array.isArray(p)?p[2]:p,null===(e=this._cnnOutput)||void 0===e||e.dispose();var h=c.shape;if(h&&h[3]>1){var d=Lp(c);this._cnnOutput=Uu(d,[0,0,0,1],[-1,-1,-1,1]),d.dispose(),this._cnnOutputData=this._cnnOutput.dataSync()}else this._cnnOutput=el(c,0,1),this._cnnOutputData=this._cnnOutput.dataSync();Array.isArray(p)?p.forEach((function(e){e.dispose()})):p.dispose(),r.dispose(),a.dispose(),s.dispose(),o.dispose(),i.dispose(),n.dispose()}else console.error("No video frame to process")}else console.error("Foot must be initialized to track")},e.prototype.release=function(){var e,t;null===(e=this._cnnOutput)||void 0===e||e.dispose(),null===(t=this._model)||void 0===t||t.dispose(),this._initialized=!1},e}(),yk=(dk="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0,function(e){var t,n,r;e=e||{},t||(t=void 0!==e?e:{}),t.ready=new Promise((function(e,t){n=e,r=t}));var a=Object.assign({},t),s="./this.program",o="";"undefined"!=typeof document&&document.currentScript&&(o=document.currentScript.src),dk&&(o=dk),o=0!==o.indexOf("blob:")?o.substr(0,o.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var i,u=t.print||console.log.bind(console),l=t.printErr||console.warn.bind(console);Object.assign(t,a),a=null,t.thisProgram&&(s=t.thisProgram),t.wasmBinary&&(i=t.wasmBinary),t.noExitRuntime,"object"!=typeof WebAssembly&&F("no native wasm support detected");var c,p,h,d,f,m,g,y,b,_=!1,x="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function v(e,t){for(var n=t+NaN,r=t;e[r]&&!(r>=n);)++r;if(16<r-t&&e.buffer&&x)return x.decode(e.subarray(t,r));for(n="";t<r;){var a=e[t++];if(128&a){var s=63&e[t++];if(192==(224&a))n+=String.fromCharCode((31&a)<<6|s);else{var o=63&e[t++];65536>(a=224==(240&a)?(15&a)<<12|s<<6|o:(7&a)<<18|s<<12|o<<6|63&e[t++])?n+=String.fromCharCode(a):(a-=65536,n+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else n+=String.fromCharCode(a)}return n}function w(e){return e?v(d,e):""}function T(e,t,n,r){if(!(0<r))return 0;var a=n;r=n+r-1;for(var s=0;s<e.length;++s){var o=e.charCodeAt(s);if(55296<=o&&57343>=o&&(o=65536+((1023&o)<<10)|1023&e.charCodeAt(++s)),127>=o){if(n>=r)break;t[n++]=o}else{if(2047>=o){if(n+1>=r)break;t[n++]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;t[n++]=224|o>>12}else{if(n+3>=r)break;t[n++]=240|o>>18,t[n++]=128|o>>12&63}t[n++]=128|o>>6&63}t[n++]=128|63&o}}return t[n]=0,n-a}function k(){var e=c.buffer;p=e,t.HEAP8=h=new Int8Array(e),t.HEAP16=f=new Int16Array(e),t.HEAP32=m=new Int32Array(e),t.HEAPU8=d=new Uint8Array(e),t.HEAPU16=new Uint16Array(e),t.HEAPU32=g=new Uint32Array(e),t.HEAPF32=y=new Float32Array(e),t.HEAPF64=b=new Float64Array(e)}var I=[],S=[],E=[];function N(){var e=t.preRun.shift();I.unshift(e)}var C,A,R,$=0,M=null;function F(e){throw t.onAbort&&t.onAbort(e),l(e="Aborted("+e+")"),_=!0,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),r(e),e}function O(){return C.startsWith("data:application/octet-stream;base64,")}if(C="libxzimgPoseEstimation.wasm",!O()){var D=C;C=t.locateFile?t.locateFile(D,o):o+D}function L(){var e=C;try{if(e==C&&i)return new Uint8Array(i);throw"both async and sync fetching of the wasm failed"}catch(e){F(e)}}function P(e){for(;0<e.length;)e.shift()(t)}function B(e){this.F=e-24,this.ta=function(e){g[this.F+4>>2]=e},this.oa=function(e){g[this.F+8>>2]=e},this.pa=function(){m[this.F>>2]=0},this.ma=function(){h[this.F+12>>0]=0},this.qa=function(){h[this.F+13>>0]=0},this.I=function(e,t){this.la(),this.ta(e),this.oa(t),this.pa(),this.ma(),this.qa()},this.la=function(){g[this.F+16>>2]=0}}var U=(e,t)=>{for(var n=0,r=e.length-1;0<=r;r--){var a=e[r];"."===a?e.splice(r,1):".."===a?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n;n--)e.unshift("..");return e},z=e=>{var t="/"===e.charAt(0),n="/"===e.substr(-1);return(e=U(e.split("/").filter((e=>!!e)),!t).join("/"))||t||(e="."),e&&n&&(e+="/"),(t?"/":"")+e},V=e=>{var t=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1);return e=t[0],t=t[1],e||t?(t&&(t=t.substr(0,t.length-1)),e+t):"."},W=e=>{if("/"===e)return"/";var t=(e=(e=z(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)};function H(){for(var e="",t=!1,n=arguments.length-1;-1<=n&&!t;n--){if("string"!=typeof(t=0<=n?arguments[n]:"/"))throw new TypeError("Arguments to path.resolve must be strings");if(!t)return"";e=t+"/"+e,t="/"===t.charAt(0)}return(t?"/":"")+(e=U(e.split("/").filter((e=>!!e)),!t).join("/"))||"."}function G(e,t){for(var n=0,r=0;r<e.length;++r){var a=e.charCodeAt(r);127>=a?n++:2047>=a?n+=2:55296<=a&&57343>=a?(n+=4,++r):n+=3}return e=T(e,n=Array(n+1),0,n.length),t&&(n.length=e),n}var j=[];function K(e,t){j[e]={input:[],m:[],J:t},ve(e,J)}var q,X,Y,Q,J={open:function(e){var t=j[e.node.P];if(!t)throw new ue(43);e.l=t,e.seekable=!1},close:function(e){e.l.J.M(e.l)},M:function(e){e.l.J.M(e.l)},read:function(e,t,n,r){if(!e.l||!e.l.J.ca)throw new ue(60);for(var a=0,s=0;s<r;s++){try{var o=e.l.J.ca(e.l)}catch(e){throw new ue(29)}if(void 0===o&&0===a)throw new ue(6);if(null==o)break;a++,t[n+s]=o}return a&&(e.node.timestamp=Date.now()),a},write:function(e,t,n,r){if(!e.l||!e.l.J.V)throw new ue(60);try{for(var a=0;a<r;a++)e.l.J.V(e.l,t[n+a])}catch(e){throw new ue(29)}return r&&(e.node.timestamp=Date.now()),a}},Z={ca:function(e){if(!e.input.length){var t=null;if("undefined"!=typeof window&&"function"==typeof window.prompt?null!==(t=window.prompt("Input: "))&&(t+="\n"):"function"==typeof readline&&null!==(t=readline())&&(t+="\n"),!t)return null;e.input=G(t,!0)}return e.input.shift()},V:function(e,t){null===t||10===t?(u(v(e.m,0)),e.m=[]):0!=t&&e.m.push(t)},M:function(e){e.m&&0<e.m.length&&(u(v(e.m,0)),e.m=[])}},ee={V:function(e,t){null===t||10===t?(l(v(e.m,0)),e.m=[]):0!=t&&e.m.push(t)},M:function(e){e.m&&0<e.m.length&&(l(v(e.m,0)),e.m=[])}},te={o:null,v:function(){return te.createNode(null,"/",16895,0)},createNode:function(e,t,n,r){if(24576==(61440&n)||4096==(61440&n))throw new ue(63);return te.o||(te.o={dir:{node:{B:te.h.B,s:te.h.s,K:te.h.K,N:te.h.N,ha:te.h.ha,ja:te.h.ja,ia:te.h.ia,ga:te.h.ga,R:te.h.R},stream:{D:te.i.D}},file:{node:{B:te.h.B,s:te.h.s},stream:{D:te.i.D,read:te.i.read,write:te.i.write,Y:te.i.Y,da:te.i.da,fa:te.i.fa}},link:{node:{B:te.h.B,s:te.h.s,L:te.h.L},stream:{}},Z:{node:{B:te.h.B,s:te.h.s},stream:xe}}),16384==(61440&(n=fe(e,t,n,r)).mode)?(n.h=te.o.dir.node,n.i=te.o.dir.stream,n.g={}):32768==(61440&n.mode)?(n.h=te.o.file.node,n.i=te.o.file.stream,n.j=0,n.g=null):40960==(61440&n.mode)?(n.h=te.o.link.node,n.i=te.o.link.stream):8192==(61440&n.mode)&&(n.h=te.o.Z.node,n.i=te.o.Z.stream),n.timestamp=Date.now(),e&&(e.g[t]=n,e.timestamp=n.timestamp),n},Ga:function(e){return e.g?e.g.subarray?e.g.subarray(0,e.j):new Uint8Array(e.g):new Uint8Array(0)},$:function(e,t){var n=e.g?e.g.length:0;n>=t||(t=Math.max(t,n*(1048576>n?2:1.125)>>>0),0!=n&&(t=Math.max(t,256)),n=e.g,e.g=new Uint8Array(t),0<e.j&&e.g.set(n.subarray(0,e.j),0))},ua:function(e,t){if(e.j!=t)if(0==t)e.g=null,e.j=0;else{var n=e.g;e.g=new Uint8Array(t),n&&e.g.set(n.subarray(0,Math.min(t,e.j))),e.j=t}},h:{B:function(e){var t={};return t.Fa=8192==(61440&e.mode)?e.id:1,t.Ia=e.id,t.mode=e.mode,t.Ka=1,t.uid=0,t.Ha=0,t.P=e.P,16384==(61440&e.mode)?t.size=4096:32768==(61440&e.mode)?t.size=e.j:40960==(61440&e.mode)?t.size=e.link.length:t.size=0,t.Ca=new Date(e.timestamp),t.Ja=new Date(e.timestamp),t.Ea=new Date(e.timestamp),t.ka=4096,t.Da=Math.ceil(t.size/t.ka),t},s:function(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&te.ua(e,t.size)},K:function(){throw le[44]},N:function(e,t,n,r){return te.createNode(e,t,n,r)},ha:function(e,t,n){if(16384==(61440&e.mode)){try{var r=de(t,n)}catch(e){}if(r)for(var a in r.g)throw new ue(55)}delete e.parent.g[e.name],e.parent.timestamp=Date.now(),e.name=n,t.g[n]=e,t.timestamp=e.parent.timestamp,e.parent=t},ja:function(e,t){delete e.g[t],e.timestamp=Date.now()},ia:function(e,t){var n,r=de(e,t);for(n in r.g)throw new ue(55);delete e.g[t],e.timestamp=Date.now()},ga:function(e){var t,n=[".",".."];for(t in e.g)e.g.hasOwnProperty(t)&&n.push(t);return n},R:function(e,t,n){return(e=te.createNode(e,t,41471,0)).link=n,e},L:function(e){if(40960!=(61440&e.mode))throw new ue(28);return e.link}},i:{read:function(e,t,n,r,a){var s=e.node.g;if(a>=e.node.j)return 0;if(8<(e=Math.min(e.node.j-a,r))&&s.subarray)t.set(s.subarray(a,a+e),n);else for(r=0;r<e;r++)t[n+r]=s[a+r];return e},write:function(e,t,n,r,a,s){if(t.buffer===h.buffer&&(s=!1),!r)return 0;if((e=e.node).timestamp=Date.now(),t.subarray&&(!e.g||e.g.subarray)){if(s)return e.g=t.subarray(n,n+r),e.j=r;if(0===e.j&&0===a)return e.g=t.slice(n,n+r),e.j=r;if(a+r<=e.j)return e.g.set(t.subarray(n,n+r),a),r}if(te.$(e,a+r),e.g.subarray&&t.subarray)e.g.set(t.subarray(n,n+r),a);else for(s=0;s<r;s++)e.g[a+s]=t[n+s];return e.j=Math.max(e.j,a+r),r},D:function(e,t,n){if(1===n?t+=e.position:2===n&&32768==(61440&e.node.mode)&&(t+=e.node.j),0>t)throw new ue(28);return t},Y:function(e,t,n){te.$(e.node,t+n),e.node.j=Math.max(e.node.j,t+n)},da:function(e,t,n,r,a){if(32768!=(61440&e.node.mode))throw new ue(43);if(e=e.node.g,2&a||e.buffer!==p){if((0<n||n+t<e.length)&&(e=e.subarray?e.subarray(n,n+t):Array.prototype.slice.call(e,n,n+t)),n=!0,F(),!(t=void 0))throw new ue(48);h.set(e,t)}else n=!1,t=e.byteOffset;return{F:t,Ba:n}},fa:function(e,t,n,r,a){if(32768!=(61440&e.node.mode))throw new ue(43);return 2&a||te.i.write(e,t,0,r,n,!1),0}}},ne=null,re={},ae=[],se=1,oe=null,ie=!0,ue=null,le={},ce=(e,t={})=>{if(!(e=H("/",e)))return{path:"",node:null};if(8<(t=Object.assign({ba:!0,W:0},t)).W)throw new ue(32);e=U(e.split("/").filter((e=>!!e)),!1);for(var n=ne,r="/",a=0;a<e.length;a++){var s=a===e.length-1;if(s&&t.parent)break;if(n=de(n,e[a]),r=z(r+"/"+e[a]),n.O&&(!s||s&&t.ba)&&(n=n.O.root),!s||t.aa)for(s=0;40960==(61440&n.mode);)if(n=Se(r),r=H(V(r),n),n=ce(r,{W:t.W+1}).node,40<s++)throw new ue(32)}return{path:r,node:n}},pe=e=>{for(var t;;){if(e===e.parent)return e=e.v.ea,t?"/"!==e[e.length-1]?e+"/"+t:e+t:e;t=t?e.name+"/"+t:e.name,e=e.parent}},he=(e,t)=>{for(var n=0,r=0;r<t.length;r++)n=(n<<5)-n+t.charCodeAt(r)|0;return(e+n>>>0)%oe.length},de=(e,t)=>{var n;if(n=(n=ye(e,"x"))?n:e.h.K?0:2)throw new ue(n,e);for(n=oe[he(e.id,t)];n;n=n.sa){var r=n.name;if(n.parent.id===e.id&&r===t)return n}return e.h.K(e,t)},fe=(e,t,n,r)=>(e=new Ve(e,t,n,r),t=he(e.parent.id,e.name),e.sa=oe[t],oe[t]=e),me={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},ge=e=>{var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},ye=(e,t)=>ie?0:!t.includes("r")||292&e.mode?t.includes("w")&&!(146&e.mode)||t.includes("x")&&!(73&e.mode)?2:0:2,be=(e,t)=>{try{return de(e,t),20}catch(e){}return ye(e,"wx")},_e=(e,t)=>(Y||((Y=function(){this.I={}}).prototype={},Object.defineProperties(Y.prototype,{object:{get:function(){return this.node},set:function(e){this.node=e}},flags:{get:function(){return this.I.flags},set:function(e){this.I.flags=e}},position:{get:function(){return this.I.position},set:function(e){this.I.position=e}}})),e=Object.assign(new Y,e),t=((e=0)=>{for(;4096>=e;e++)if(!ae[e])return e;throw new ue(33)})(t),e.A=t,ae[t]=e),xe={open:e=>{e.i=re[e.node.P].i,e.i.open&&e.i.open(e)},D:()=>{throw new ue(70)}},ve=(e,t)=>{re[e]={i:t}},we=(e,t)=>{var n="/"===t,r=!t;if(n&&ne)throw new ue(10);if(!n&&!r){var a=ce(t,{ba:!1});if(t=a.path,(a=a.node).O)throw new ue(10);if(16384!=(61440&a.mode))throw new ue(54)}t={type:e,La:{},ea:t,ra:[]},(e=e.v(t)).v=t,t.root=e,n?ne=e:a&&(a.O=t,a.v&&a.v.ra.push(t))},Te=(e,t,n)=>{var r=ce(e,{parent:!0}).node;if(!(e=W(e))||"."===e||".."===e)throw new ue(28);var a=be(r,e);if(a)throw new ue(a);if(!r.h.N)throw new ue(63);return r.h.N(r,e,t,n)},ke=(e,t,n)=>{void 0===n&&(n=t,t=438),Te(e,8192|t,n)},Ie=(e,t)=>{if(!H(e))throw new ue(44);var n=ce(t,{parent:!0}).node;if(!n)throw new ue(44);t=W(t);var r=be(n,t);if(r)throw new ue(r);if(!n.h.R)throw new ue(63);n.h.R(n,t,e)},Se=e=>{if(!(e=ce(e).node))throw new ue(44);if(!e.h.L)throw new ue(28);return H(pe(e.parent),e.h.L(e))},Ee=(e,n,r)=>{if(""===e)throw new ue(44);if("string"==typeof n){var a=me[n];if(void 0===a)throw Error("Unknown file open mode: "+n);n=a}if(r=64&n?4095&(void 0===r?438:r)|32768:0,"object"==typeof e)var s=e;else{e=z(e);try{s=ce(e,{aa:!(131072&n)}).node}catch(e){}}if(a=!1,64&n)if(s){if(128&n)throw new ue(20)}else s=Te(e,r,0),a=!0;if(!s)throw new ue(44);if(8192==(61440&s.mode)&&(n&=-513),65536&n&&16384!=(61440&s.mode))throw new ue(54);if(!a&&(r=s?40960==(61440&s.mode)?32:16384==(61440&s.mode)&&("r"!==ge(n)||512&n)?31:ye(s,ge(n)):44))throw new ue(r);if(512&n&&!a){if(!(r="string"==typeof(r=s)?ce(r,{aa:!0}).node:r).h.s)throw new ue(63);if(16384==(61440&r.mode))throw new ue(31);if(32768!=(61440&r.mode))throw new ue(28);if(a=ye(r,"w"))throw new ue(a);r.h.s(r,{size:0,timestamp:Date.now()})}return n&=-131713,(s=_e({node:s,path:pe(s),flags:n,seekable:!0,position:0,i:s.i,Aa:[],error:!1})).i.open&&s.i.open(s),!t.logReadFiles||1&n||(Q||(Q={}),e in Q||(Q[e]=1)),s},Ne=(e,t,n)=>{if(null===e.A)throw new ue(8);if(!e.seekable||!e.i.D)throw new ue(70);if(0!=n&&1!=n&&2!=n)throw new ue(28);e.position=e.i.D(e,t,n),e.Aa=[]},Ce=()=>{ue||((ue=function(e,t){this.node=t,this.va=function(e){this.C=e},this.va(e),this.message="FS error"}).prototype=Error(),ue.prototype.constructor=ue,[44].forEach((e=>{le[e]=new ue(e),le[e].stack="<generic error, no stack>"})))},Ae=(e,t,n)=>{e=z("/dev/"+e);var r=((e,t)=>{var n=0;return e&&(n|=365),t&&(n|=146),n})(!!t,!!n);X||(X=64);var a=X++<<8|0;ve(a,{open:e=>{e.seekable=!1},close:()=>{n&&n.buffer&&n.buffer.length&&n(10)},read:(e,n,r,a)=>{for(var s=0,o=0;o<a;o++){try{var i=t()}catch(e){throw new ue(29)}if(void 0===i&&0===s)throw new ue(6);if(null==i)break;s++,n[r+o]=i}return s&&(e.node.timestamp=Date.now()),s},write:(e,t,r,a)=>{for(var s=0;s<a;s++)try{n(t[r+s])}catch(e){throw new ue(29)}return a&&(e.node.timestamp=Date.now()),s}}),ke(e,r,a)},Re={},$e=void 0;function Me(){return m[($e+=4)-4>>2]}function Fe(e){if(!(e=ae[e]))throw new ue(8);return e}var Oe,De={};function Le(){if(!Oe){var e,t={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",_:s||"./this.program"};for(e in De)void 0===De[e]?delete t[e]:t[e]=De[e];var n=[];for(e in t)n.push(e+"="+t[e]);Oe=n}return Oe}function Pe(e){return 0==e%4&&(0!=e%100||0==e%400)}var Be=[31,29,31,30,31,30,31,31,30,31,30,31],Ue=[31,28,31,30,31,30,31,31,30,31,30,31];function ze(e,n,r,a){var s={string:e=>{var t=0;if(null!=e&&0!==e){var n=1+(e.length<<2);t=Xe(n),T(e,d,t,n)}return t},array:e=>{var t=Xe(e.length);return h.set(e,t),t}};e=t["_"+e];var o,i=[],u=0;if(a)for(var l=0;l<a.length;l++){var c=s[r[l]];c?(0===u&&(u=Ke()),i[l]=c(a[l])):i[l]=a[l]}return o=r=e.apply(null,i),0!==u&&qe(u),"string"===n?w(o):"boolean"===n?!!o:o}function Ve(e,t,n,r){e||(e=this),this.parent=e,this.v=e.v,this.O=null,this.id=se++,this.name=t,this.mode=n,this.h={},this.i={},this.P=r}"undefined"!=typeof TextDecoder&&new TextDecoder("utf-16le"),Object.defineProperties(Ve.prototype,{read:{get:function(){return 365==(365&this.mode)},set:function(e){e?this.mode|=365:this.mode&=-366}},write:{get:function(){return 146==(146&this.mode)},set:function(e){e?this.mode|=146:this.mode&=-147}}}),Ce(),oe=Array(4096),we(te,"/"),Te("/tmp",16895,0),Te("/home",16895,0),Te("/home/web_user",16895,0),(()=>{Te("/dev",16895,0),ve(259,{read:()=>0,write:(e,t,n,r)=>r}),ke("/dev/null",259),K(1280,Z),K(1536,ee),ke("/dev/tty",1280),ke("/dev/tty1",1536);var e=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return()=>(crypto.getRandomValues(e),e[0])}return()=>F("randomDevice")}();Ae("random",e),Ae("urandom",e),Te("/dev/shm",16895,0),Te("/dev/shm/tmp",16895,0)})(),(()=>{Te("/proc",16895,0);var e=Te("/proc/self",16895,0);Te("/proc/self/fd",16895,0),we({v:()=>{var t=fe(e,"fd",16895,73);return t.h={K:(e,t)=>{var n=ae[+t];if(!n)throw new ue(8);return(e={parent:null,v:{ea:"fake"},h:{L:()=>n.path}}).parent=e}},t}},"/proc/self/fd")})();var We={__assert_fail:function(e,t,n,r){F("Assertion failed: "+w(e)+", at: "+[t?w(t):"unknown filename",n,r?w(r):"unknown function"])},__cxa_allocate_exception:function(e){return He(e+24)+24},__cxa_throw:function(e,t,n){throw new B(e).I(t,n),e},__syscall_fcntl64:function(e,t,n){$e=n;try{var r=Fe(e);switch(t){case 0:var a=Me();return 0>a?-28:_e(r,a).A;case 1:case 2:case 6:case 7:return 0;case 3:return r.flags;case 4:return a=Me(),r.flags|=a,0;case 5:return a=Me(),f[a+0>>1]=2,0;case 16:case 8:default:return-28;case 9:return m[je()>>2]=28,-1}}catch(e){if(void 0===Re||!(e instanceof ue))throw e;return-e.C}},__syscall_ioctl:function(e,t,n){$e=n;try{var r=Fe(e);switch(t){case 21509:case 21505:case 21510:case 21511:case 21512:case 21506:case 21507:case 21508:case 21523:case 21524:return r.l?0:-59;case 21519:if(!r.l)return-59;var a=Me();return m[a>>2]=0;case 21520:return r.l?-28:-59;case 21531:if(e=a=Me(),!r.i.na)throw new ue(59);return r.i.na(r,t,e);default:return-28}}catch(e){if(void 0===Re||!(e instanceof ue))throw e;return-e.C}},__syscall_openat:function(e,t,n,r){$e=r;try{var a=t=w(t);if("/"===a.charAt(0))t=a;else{var s=-100===e?"/":Fe(e).path;if(0==a.length)throw new ue(44);t=z(s+"/"+a)}var o=r?Me():0;return Ee(t,n,o).A}catch(e){if(void 0===Re||!(e instanceof ue))throw e;return-e.C}},abort:function(){F("")},emscripten_memcpy_big:function(e,t,n){d.copyWithin(e,t,t+n)},emscripten_resize_heap:function(e){var t=d.length;if(2147483648<(e>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=t*(1+.2/n);r=Math.min(r,e+100663296);var a=Math;r=Math.max(e,r),a=a.min.call(a,2147483648,r+(65536-r%65536)%65536);e:{try{c.grow(a-p.byteLength+65535>>>16),k();var s=1;break e}catch(e){}s=void 0}if(s)return!0}return!1},environ_get:function(e,t){var n=0;return Le().forEach((function(r,a){var s=t+n;for(a=g[e+4*a>>2]=s,s=0;s<r.length;++s)h[a++>>0]=r.charCodeAt(s);h[a>>0]=0,n+=r.length+1})),0},environ_sizes_get:function(e,t){var n=Le();g[e>>2]=n.length;var r=0;return n.forEach((function(e){r+=e.length+1})),g[t>>2]=r,0},fd_close:function(e){try{var t=Fe(e);if(null===t.A)throw new ue(8);t.U&&(t.U=null);try{t.i.close&&t.i.close(t)}catch(e){throw e}finally{ae[t.A]=null}return t.A=null,0}catch(e){if(void 0===Re||!(e instanceof ue))throw e;return e.C}},fd_read:function(e,t,n,r){try{e:{var a=Fe(e);e=t;for(var s=t=0;s<n;s++){var o=g[e>>2],i=g[e+4>>2];e+=8;var u=a,l=o,c=i,p=void 0,d=h;if(0>c||0>p)throw new ue(28);if(null===u.A)throw new ue(8);if(1==(2097155&u.flags))throw new ue(8);if(16384==(61440&u.node.mode))throw new ue(31);if(!u.i.read)throw new ue(28);var f=void 0!==p;if(f){if(!u.seekable)throw new ue(70)}else p=u.position;var m=u.i.read(u,d,l,c,p);f||(u.position+=m);var y=m;if(0>y){var b=-1;break e}if(t+=y,y<i)break}b=t}return g[r>>2]=b,0}catch(e){if(void 0===Re||!(e instanceof ue))throw e;return e.C}},fd_seek:function(e,t,n,r,a){try{if(t=n+2097152>>>0<4194305-!!t?(t>>>0)+4294967296*n:NaN,isNaN(t))return 61;var s=Fe(e);return Ne(s,t,r),R=[s.position>>>0,(A=s.position,1<=+Math.abs(A)?0<A?(0|Math.min(+Math.floor(A/4294967296),4294967295))>>>0:~~+Math.ceil((A-+(~~A>>>0))/4294967296)>>>0:0)],m[a>>2]=R[0],m[a+4>>2]=R[1],s.U&&0===t&&0===r&&(s.U=null),0}catch(e){if(void 0===Re||!(e instanceof ue))throw e;return e.C}},fd_write:function(e,t,n,r){try{e:{var a=Fe(e);e=t;for(var s=t=0;s<n;s++){var o=g[e>>2],i=g[e+4>>2];e+=8;var u=a,l=o,c=i,p=void 0,d=h;if(0>c||0>p)throw new ue(28);if(null===u.A)throw new ue(8);if(0==(2097155&u.flags))throw new ue(8);if(16384==(61440&u.node.mode))throw new ue(31);if(!u.i.write)throw new ue(28);u.seekable&&1024&u.flags&&Ne(u,0,2);var f=void 0!==p;if(f){if(!u.seekable)throw new ue(70)}else p=u.position;var m=u.i.write(u,d,l,c,p,void 0);f||(u.position+=m);var y=m;if(0>y){var b=-1;break e}t+=y}b=t}return g[r>>2]=b,0}catch(e){if(void 0===Re||!(e instanceof ue))throw e;return e.C}},strftime_l:function(e,t,n,r){return function(e,t,n,r){function a(e,t,n){for(e="number"==typeof e?e.toString():e||"";e.length<t;)e=n[0]+e;return e}function s(e,t){return a(e,t,"0")}function o(e,t){function n(e){return 0>e?-1:0<e?1:0}var r;return 0===(r=n(e.getFullYear()-t.getFullYear()))&&0===(r=n(e.getMonth()-t.getMonth()))&&(r=n(e.getDate()-t.getDate())),r}function i(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function u(e){var t=e.G;for(e=new Date(new Date(e.H+1900,0,1).getTime());0<t;){var n=e.getMonth(),r=(Pe(e.getFullYear())?Be:Ue)[n];if(!(t>r-e.getDate())){e.setDate(e.getDate()+t);break}t-=r-e.getDate()+1,e.setDate(1),11>n?e.setMonth(n+1):(e.setMonth(0),e.setFullYear(e.getFullYear()+1))}return n=new Date(e.getFullYear()+1,0,4),t=i(new Date(e.getFullYear(),0,4)),n=i(n),0>=o(t,e)?0>=o(n,e)?e.getFullYear()+1:e.getFullYear():e.getFullYear()-1}var l=m[r+40>>2];for(var c in r={ya:m[r>>2],xa:m[r+4>>2],S:m[r+8>>2],X:m[r+12>>2],T:m[r+16>>2],H:m[r+20>>2],u:m[r+24>>2],G:m[r+28>>2],Ma:m[r+32>>2],wa:m[r+36>>2],za:l?w(l):""},n=w(n),l={"%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(c,"g"),l[c]);var p="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),d="January February March April May June July August September October November December".split(" ");for(c in l={"%a":function(e){return p[e.u].substring(0,3)},"%A":function(e){return p[e.u]},"%b":function(e){return d[e.T].substring(0,3)},"%B":function(e){return d[e.T]},"%C":function(e){return s((e.H+1900)/100|0,2)},"%d":function(e){return s(e.X,2)},"%e":function(e){return a(e.X,2," ")},"%g":function(e){return u(e).toString().substring(2)},"%G":function(e){return u(e)},"%H":function(e){return s(e.S,2)},"%I":function(e){return 0==(e=e.S)?e=12:12<e&&(e-=12),s(e,2)},"%j":function(e){for(var t=0,n=0;n<=e.T-1;t+=(Pe(e.H+1900)?Be:Ue)[n++]);return s(e.X+t,3)},"%m":function(e){return s(e.T+1,2)},"%M":function(e){return s(e.xa,2)},"%n":function(){return"\n"},"%p":function(e){return 0<=e.S&&12>e.S?"AM":"PM"},"%S":function(e){return s(e.ya,2)},"%t":function(){return"\t"},"%u":function(e){return e.u||7},"%U":function(e){return s(Math.floor((e.G+7-e.u)/7),2)},"%V":function(e){var t=Math.floor((e.G+7-(e.u+6)%7)/7);if(2>=(e.u+371-e.G-2)%7&&t++,t)53==t&&(4==(n=(e.u+371-e.G)%7)||3==n&&Pe(e.H)||(t=1));else{t=52;var n=(e.u+7-e.G-1)%7;(4==n||5==n&&Pe(e.H%400-1))&&t++}return s(t,2)},"%w":function(e){return e.u},"%W":function(e){return s(Math.floor((e.G+7-(e.u+6)%7)/7),2)},"%y":function(e){return(e.H+1900).toString().substring(2)},"%Y":function(e){return e.H+1900},"%z":function(e){var t=0<=(e=e.wa);return e=Math.abs(e)/60,(t?"+":"-")+String("0000"+(e/60*100+e%60)).slice(-4)},"%Z":function(e){return e.za},"%%":function(){return"%"}},n=n.replace(/%%/g,"\0\0"),l)n.includes(c)&&(n=n.replace(new RegExp(c,"g"),l[c](r)));return(c=G(n=n.replace(/\0\0/g,"%"),!1)).length>t?0:(h.set(c,e),c.length-1)}(e,t,n,r)}};!function(){function e(e){t.asm=e.exports,c=t.asm.memory,k(),S.unshift(t.asm.__wasm_call_ctors),$--,t.monitorRunDependencies&&t.monitorRunDependencies($),0==$&&M&&(e=M,M=null,e())}function n(t){e(t.instance)}function a(e){return(i||"function"!=typeof fetch?Promise.resolve().then((function(){return L()})):fetch(C,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+C+"'";return e.arrayBuffer()})).catch((function(){return L()}))).then((function(e){return WebAssembly.instantiate(e,s)})).then((function(e){return e})).then(e,(function(e){l("failed to asynchronously prepare wasm: "+e),F(e)}))}var s={env:We,wasi_snapshot_preview1:We};if($++,t.monitorRunDependencies&&t.monitorRunDependencies($),t.instantiateWasm)try{return t.instantiateWasm(s,e)}catch(e){return l("Module.instantiateWasm callback failed with error: "+e),!1}(i||"function"!=typeof WebAssembly.instantiateStreaming||O()||"function"!=typeof fetch?a(n):fetch(C,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,s).then(n,(function(e){return l("wasm streaming compile failed: "+e),l("falling back to ArrayBuffer instantiation"),a(n)}))}))).catch(r)}(),t.___wasm_call_ctors=function(){return(t.___wasm_call_ctors=t.asm.__wasm_call_ctors).apply(null,arguments)};var He=t._malloc=function(){return(He=t._malloc=t.asm.malloc).apply(null,arguments)};t._free=function(){return(t._free=t.asm.free).apply(null,arguments)},t._xzimgInitializeCamera=function(){return(t._xzimgInitializeCamera=t.asm.xzimgInitializeCamera).apply(null,arguments)},t._xzimgPoseEstimationInitializeFacePose=function(){return(t._xzimgPoseEstimationInitializeFacePose=t.asm.xzimgPoseEstimationInitializeFacePose).apply(null,arguments)},t._xzimgPoseEstimationInitialize=function(){return(t._xzimgPoseEstimationInitialize=t.asm.xzimgPoseEstimationInitialize).apply(null,arguments)},t._xzimgPoseEstimationRelease=function(){return(t._xzimgPoseEstimationRelease=t.asm.xzimgPoseEstimationRelease).apply(null,arguments)},t._xzimgPoseEstimationPrepareCrop=function(){return(t._xzimgPoseEstimationPrepareCrop=t.asm.xzimgPoseEstimationPrepareCrop).apply(null,arguments)},t._xzimgPoseEstimationEstimateFacePose=function(){return(t._xzimgPoseEstimationEstimateFacePose=t.asm.xzimgPoseEstimationEstimateFacePose).apply(null,arguments)},t._xzimgGetHeatmapsLocations=function(){return(t._xzimgGetHeatmapsLocations=t.asm.xzimgGetHeatmapsLocations).apply(null,arguments)},t._xzimgEstimateRigidPose=function(){return(t._xzimgEstimateRigidPose=t.asm.xzimgEstimateRigidPose).apply(null,arguments)},t._xzimgEstimateGetSimilarity=function(){return(t._xzimgEstimateGetSimilarity=t.asm.xzimgEstimateGetSimilarity).apply(null,arguments)},t._xzimgWarpAffine=function(){return(t._xzimgWarpAffine=t.asm.xzimgWarpAffine).apply(null,arguments)},t._xzimgMatchRecKeypsInit=function(){return(t._xzimgMatchRecKeypsInit=t.asm.xzimgMatchRecKeypsInit).apply(null,arguments)},t._xzimgMatchRecKeyps=function(){return(t._xzimgMatchRecKeyps=t.asm.xzimgMatchRecKeyps).apply(null,arguments)},t._xzimgEstimateInitNonRigidPose=function(){return(t._xzimgEstimateInitNonRigidPose=t.asm.xzimgEstimateInitNonRigidPose).apply(null,arguments)},t._xzimgEstimateNonRigidPose=function(){return(t._xzimgEstimateNonRigidPose=t.asm.xzimgEstimateNonRigidPose).apply(null,arguments)},t._xzimgEstimateBodyNonRigidPose=function(){return(t._xzimgEstimateBodyNonRigidPose=t.asm.xzimgEstimateBodyNonRigidPose).apply(null,arguments)},t._xzimgEstimateNonRigidPoseBase=function(){return(t._xzimgEstimateNonRigidPoseBase=t.asm.xzimgEstimateNonRigidPoseBase).apply(null,arguments)},t._xzimgEstimateGetNumVertices=function(){return(t._xzimgEstimateGetNumVertices=t.asm.xzimgEstimateGetNumVertices).apply(null,arguments)},t._xzimgEstimateGetDenseVertices=function(){return(t._xzimgEstimateGetDenseVertices=t.asm.xzimgEstimateGetDenseVertices).apply(null,arguments)},t._xzimgEstimateGetNumBlendShapes=function(){return(t._xzimgEstimateGetNumBlendShapes=t.asm.xzimgEstimateGetNumBlendShapes).apply(null,arguments)},t._xzimgEstimateGetBlendShapes=function(){return(t._xzimgEstimateGetBlendShapes=t.asm.xzimgEstimateGetBlendShapes).apply(null,arguments)},t._xzimgGeometryGetModelIntersection=function(){return(t._xzimgGeometryGetModelIntersection=t.asm.xzimgGeometryGetModelIntersection).apply(null,arguments)};var Ge,je=t.___errno_location=function(){return(je=t.___errno_location=t.asm.__errno_location).apply(null,arguments)},Ke=t.stackSave=function(){return(Ke=t.stackSave=t.asm.stackSave).apply(null,arguments)},qe=t.stackRestore=function(){return(qe=t.stackRestore=t.asm.stackRestore).apply(null,arguments)},Xe=t.stackAlloc=function(){return(Xe=t.stackAlloc=t.asm.stackAlloc).apply(null,arguments)};function Ye(){function e(){if(!Ge&&(Ge=!0,t.calledRun=!0,!_)){if(t.noFSInit||q||(q=!0,Ce(),t.stdin=t.stdin,t.stdout=t.stdout,t.stderr=t.stderr,t.stdin?Ae("stdin",t.stdin):Ie("/dev/tty","/dev/stdin"),t.stdout?Ae("stdout",null,t.stdout):Ie("/dev/tty","/dev/stdout"),t.stderr?Ae("stderr",null,t.stderr):Ie("/dev/tty1","/dev/stderr"),Ee("/dev/stdin",0),Ee("/dev/stdout",1),Ee("/dev/stderr",1)),ie=!1,P(S),n(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),t.postRun)for("function"==typeof t.postRun&&(t.postRun=[t.postRun]);t.postRun.length;){var e=t.postRun.shift();E.unshift(e)}P(E)}}if(!(0<$)){if(t.preRun)for("function"==typeof t.preRun&&(t.preRun=[t.preRun]);t.preRun.length;)N();P(I),0<$||(t.setStatus?(t.setStatus("Running..."),setTimeout((function(){setTimeout((function(){t.setStatus("")}),1),e()}),1)):e())}}if(t.___cxa_is_pointer_type=function(){return(t.___cxa_is_pointer_type=t.asm.__cxa_is_pointer_type).apply(null,arguments)},t.dynCall_jiji=function(){return(t.dynCall_jiji=t.asm.dynCall_jiji).apply(null,arguments)},t.dynCall_viijii=function(){return(t.dynCall_viijii=t.asm.dynCall_viijii).apply(null,arguments)},t.dynCall_iiiiij=function(){return(t.dynCall_iiiiij=t.asm.dynCall_iiiiij).apply(null,arguments)},t.dynCall_iiiiijj=function(){return(t.dynCall_iiiiijj=t.asm.dynCall_iiiiijj).apply(null,arguments)},t.dynCall_iiiiiijj=function(){return(t.dynCall_iiiiiijj=t.asm.dynCall_iiiiiijj).apply(null,arguments)},t.ccall=ze,t.cwrap=function(e,n,r,a){var s=(r=r||[]).every((e=>"number"===e||"boolean"===e));return"string"!==n&&s&&!a?t["_"+e]:function(){return ze(e,n,r,arguments)}},t.setValue=function(e,t,n="i8"){switch(n.endsWith("*")&&(n="*"),n){case"i1":case"i8":h[e>>0]=t;break;case"i16":f[e>>1]=t;break;case"i32":m[e>>2]=t;break;case"i64":R=[t>>>0,(A=t,1<=+Math.abs(A)?0<A?(0|Math.min(+Math.floor(A/4294967296),4294967295))>>>0:~~+Math.ceil((A-+(~~A>>>0))/4294967296)>>>0:0)],m[e>>2]=R[0],m[e+4>>2]=R[1];break;case"float":y[e>>2]=t;break;case"double":b[e>>3]=t;break;case"*":g[e>>2]=t;break;default:F("invalid type for setValue: "+n)}},t.getValue=function(e,t="i8"){switch(t.endsWith("*")&&(t="*"),t){case"i1":case"i8":return h[e>>0];case"i16":return f[e>>1];case"i32":case"i64":return m[e>>2];case"float":return y[e>>2];case"double":return b[e>>3];case"*":return g[e>>2];default:F("invalid type for getValue: "+t)}return null},M=function e(){Ge||Ye(),Ge||(M=e)},t.preInit)for("function"==typeof t.preInit&&(t.preInit=[t.preInit]);0<t.preInit.length;)t.preInit.pop()();return Ye(),e.ready});let bk;!function(e){e[e.float32=0]="float32",e[e.int32=1]="int32",e[e.bool=2]="bool",e[e.string=3]="string",e[e.complex64=4]="complex64"}(fk||(fk={})),function(e){e[e.linear=0]="linear",e[e.relu=1]="relu",e[e.relu6=2]="relu6",e[e.prelu=3]="prelu",e[e.leakyrelu=4]="leakyrelu",e[e.sigmoid=5]="sigmoid",e[e.elu=6]="elu"}(mk||(mk={}));const _k={kernelName:Sr,backendName:"wasm",setupFunc:function(e){bk=e.wasm.cwrap(Sr,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a,b:s,bias:o,preluActivationWeights:i}=t;if("float32"!==a.dtype||"float32"!==s.dtype)throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");const{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:p}=r,h=n.dataIdMap.get(a.dataId).id,d=n.dataIdMap.get(s.dataId).id;let f=0;if(null!=o){const e=n.dataIdMap.get(o.dataId);if(1!==e.shape.length)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${e.shape.length}.`);f=e.id}const m=null==i?0:n.dataIdMap.get(i.dataId).id,g=mk[c];if(null==g)throw new Error(`${c} activation not yet supported for FusedConv2D in the wasm backend.`);const y=u?a.shape[2]:a.shape[1],b=l?s.shape[1]:s.shape[2],_=Fi(a.shape.slice(0,-2),s.shape.slice(0,-2)),x=n.makeOutput([..._,y,b],a.dtype),v=n.dataIdMap.get(x.dataId).id,w=new Uint8Array(new Int32Array(a.shape).buffer),T=new Uint8Array(new Int32Array(s.shape).buffer);return bk(h,w,a.shape.length,d,T,s.shape.length,u,l,g,f,m,p||0,v),x}};function xk(e,t){let n;return{kernelName:e,backendName:"wasm",setupFunc:function(t){n=t.wasm.cwrap(e,null,["number","number","number"])},kernelFunc:function(e){const{backend:r,inputs:{x:a}}=e,s=r.dataIdMap.get(a.dataId).id,o=r.makeOutput(a.shape,t||a.dtype),i=r.dataIdMap.get(o.dataId).id;return 0===et(o.shape)||n(s,fk[a.dtype],i),o}}}const vk=xk("Abs");function wk(e,t,n){let r;return{kernelName:e,backendName:"wasm",setupFunc:function(t){r=t.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:a}=e,{a:s,b:o}=a,i=t.dataIdMap.get(s.dataId).id,u=t.dataIdMap.get(o.dataId).id,l=null!=n?n:s.dtype,c=Fi(s.shape,o.shape),p=t.makeOutput(c,l);if(0===et(c))return p;const h=new Uint8Array(new Int32Array(s.shape).buffer),d=new Uint8Array(new Int32Array(o.shape).buffer),f=t.dataIdMap.get(p.dataId).id;return r(i,h,s.shape.length,u,d,o.shape.length,fk[s.dtype],f),p}}}const Tk=wk(Ft);let kk;const Ik={kernelName:Ot,backendName:"wasm",setupFunc:function(e){kk=e.wasm.cwrap(Ot,null,["array","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n}=e,r=n.makeOutput(t[0].shape,t[0].dtype);if(0===et(r.shape))return r;const a=t.map((e=>n.dataIdMap.get(e.dataId).id)),s=new Uint8Array(new Int32Array(a).buffer),o=n.dataIdMap.get(r.dataId).id;return kk(s,a.length,fk[r.dtype],o),r}};function Sk(e){const{inputs:{x:t},backend:n}=e;if("string"===t.dtype)return go(n.readSync(t.dataId),t.shape,t.dtype);const r=n.makeOutput(t.shape,t.dtype),a=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(r).set(a),r}const Ek={kernelName:mn,backendName:"wasm",kernelFunc:Sk};let Nk;function Ck(e){const{inputs:t,backend:n,attrs:r}=e,[a,s]=function(e,t){const n=[],r=[];for(let a=0;a<e.length;++a)1!==e[a]&&n.push(e[a]),1!==e[t[a]]&&r.push(t[a]);for(let e=0;e<r.length;++e){let t=-1;for(let n=0;n<r.length;++n)r[n]>=e&&(-1===t||r[t]>r[n])&&(t=n);r[t]=e}return[n,r]}(t.x.shape,r.perm);let o=!0;for(let e=0;e<s.length;e++)s[e]!==e&&(o=!1);const i=function(e,t){const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[t[r]];return n}(t.x.shape,r.perm),u={dataId:t.x.dataId,shape:a,dtype:t.x.dtype};if(o){const e=Sk({inputs:t,backend:n});return e.shape=i,e}const l=n.makeOutput(i,u.dtype),c=n.dataIdMap.get(u.dataId).id,p=n.dataIdMap.get(l.dataId).id,h=new Uint8Array(new Int32Array(s).buffer),d=new Uint8Array(new Int32Array(u.shape).buffer);return Nk(c,d,u.shape.length,fk[u.dtype],p,h,s.length),l}const Ak={kernelName:xr,backendName:"wasm",kernelFunc:Ck,setupFunc:function(e){Nk=e.wasm.cwrap(xr,null,["number","array","number","number","number","array","number"])}};function Rk(e,t,n){const r=e.shape,a=e.shape.length,s=it(t,r);let o=s;const i=Fl(o,a);let u=null,l=!1;if(null!=i){const t=new Array(a);for(let e=0;e<t.length;e++)t[e]=r[i[e]];o=Dl(o.length,a),u=Ck({inputs:{x:e},attrs:{perm:i},backend:n});const s=n.dataIdMap.get(e.dataId).id;n.dataIdMap.get(u.dataId).id!==s&&(l=!0)}return{transposed:u,originalAxes:s,axes:o,inputWasTransposed:l}}let $k;const Mk={kernelName:Dt,backendName:"wasm",setupFunc:function(e){$k=e.wasm.cwrap(Dt,null,["number, number, number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:a,keepDims:s}=r,{x:o}=n;let i=t.dataIdMap.get(o.dataId).id,u=o;const{transposed:l,axes:c,originalAxes:p,inputWasTransposed:h}=Rk(o,a,t);h&&(u=l,i=t.dataIdMap.get(l.dataId).id),Ml("all",c,u.shape.length);const[d,f]=Rl(u.shape,c),m=et(f),g=t.makeOutput(d,o.dtype);if(0!==et(u.shape)){const e=t.dataIdMap.get(g.dataId).id;$k(i,m,e)}if(h&&t.disposeData(l.dataId),s){const e=$l(g.shape,p);g.shape=e}return g}};let Fk;const Ok={kernelName:Lt,backendName:"wasm",setupFunc:function(e){Fk=e.wasm.cwrap(Lt,null,["number, number, number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:a,keepDims:s}=r,{x:o}=n;let i=t.dataIdMap.get(o.dataId).id,u=o;const{transposed:l,axes:c,originalAxes:p,inputWasTransposed:h}=Rk(o,a,t);h&&(u=l,i=t.dataIdMap.get(l.dataId).id),Ml("any",c,u.shape.length);const[d,f]=Rl(u.shape,c),m=et(f),g=t.makeOutput(d,o.dtype);if(0!==et(u.shape)){const e=t.dataIdMap.get(g.dataId).id;Fk(i,m,e)}if(h&&t.disposeData(l.dataId),s){const e=$l(g.shape,p);g.shape=e}return g}};let Dk;const Lk={kernelName:Pt,backendName:"wasm",kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:a}=r,{x:s}=n,o=t.dataIdMap.get(s.dataId).id;let i=o,u=s;const{transposed:l,axes:c,inputWasTransposed:p}=Rk(s,a,t);if(p){const e=t.dataIdMap.get(l.dataId).id;e!==o&&(u=l,i=e)}const h=u.shape.slice(0,-1),d=t.makeOutput(h,"int32"),f=t.dataIdMap.get(d.dataId).id,m=et(d.shape),g=u.shape[c[0]];return Dk(i,fk[u.dtype],m,g,f),p&&t.disposeData(l.dataId),d},setupFunc:function(e){Dk=e.wasm.cwrap(Pt,null,["number","number","number","number","number"])}};let Pk;const Bk={kernelName:Bt,backendName:"wasm",setupFunc:function(e){Pk=e.wasm.cwrap(Bt,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,a=t.x,s=r.dataIdMap.get(a.dataId).id,{filterSize:o,strides:i,pad:u,dimRoundingMode:l}=n,c=vu(a.shape,o,i,1,u,l),p=c.filterHeight,h=c.filterWidth,d=c.padInfo.top,f=c.padInfo.right,m=c.padInfo.bottom,g=c.padInfo.left,y=c.strideHeight,b=c.strideWidth,_=c.inChannels;if("channelsLast"!==c.dataFormat)throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);if(1!==c.dilationWidth||1!==c.dilationHeight)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${c.dilationHeight}, ${c.dilationWidth}].`);const x=r.makeOutput(c.outShape,"float32"),v=r.dataIdMap.get(x.dataId).id;return Pk(s,a.shape[0],a.shape[1],a.shape[2],p,h,d,f,m,g,y,b,_,v),x}};function Uk(e){const{inputs:t,attrs:n}=e,{x:r}=t,{shape:a}=n,s=et(r.shape),o=ot(a,s);return Qe(s===et(o),(()=>`new shape: ${o}, old shape: ${r.shape}. New shape and old shape must have the same number of elements.`)),e.backend.incRef(r.dataId),{dataId:r.dataId,shape:o,dtype:r.dtype}}const zk={kernelName:Hn,backendName:"wasm",kernelFunc:Uk};let Vk;const Wk={kernelName:Ut,backendName:"wasm",setupFunc:function(e){Vk=e.wasm.cwrap(Ut,null,["number","array","number","number","array","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a,b:s}=t,{transposeA:o,transposeB:i}=r;if("float32"!==a.dtype||"float32"!==s.dtype)throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");const u=a.shape.length,l=s.shape.length,c=o?a.shape[u-2]:a.shape[u-1],p=i?s.shape[l-1]:s.shape[l-2],h=o?a.shape[u-1]:a.shape[u-2],d=i?s.shape[l-2]:s.shape[l-1],f=a.shape.slice(0,-2),m=s.shape.slice(0,-2),g=et(f),y=et(m),b=Fi(a.shape.slice(0,-2),s.shape.slice(0,-2)).concat([h,d]);Qe(c===p,(()=>`Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${a.shape} and ${s.shape} and transposeA=${o} and transposeB=${i} must match.`));const _=i?[y,d,p]:[y,p,d],x=Uk({inputs:{x:a},backend:n,attrs:{shape:o?[g,c,h]:[g,h,c]}}),v=Uk({inputs:{x:s},backend:n,attrs:{shape:_}}),w=n.dataIdMap.get(x.dataId).id,T=n.dataIdMap.get(v.dataId).id,k=o?x.shape[2]:x.shape[1],I=i?v.shape[1]:v.shape[2],S=Math.max(g,y),E=n.makeOutput([S,k,I],x.dtype),N=n.dataIdMap.get(E.dataId).id,C=new Uint8Array(new Int32Array(x.shape).buffer),A=new Uint8Array(new Int32Array(v.shape).buffer);return Vk(w,C,x.shape.length,T,A,v.shape.length,o,i,N),n.disposeData(x.dataId),n.disposeData(v.dataId),E.shape=b,E}};function Hk(e){const{inputs:{x:t},attrs:{begin:n,size:r},backend:a}=e,[s,o]=eu(t,n,r),i=Ji(t.shape,s,o),u=a.readSync(t.dataId),l=a.makeOutput(o,t.dtype),c=yt(t.shape),p=a.dataIdMap.get(l.dataId);if(i){const e=Zi(s,c);return"string"===t.dtype?p.stringBytes=u.slice(e,e+et(o)):a.typedArrayFromHeap(l).set(u.subarray(e,e+et(o))),l}if("string"===t.dtype){const e=gg(u,s,o,t.shape,t.dtype);return p.stringBytes=e,l}const h=a.typedArrayFromHeap(l),d=t.shape.length;if(2===d)!function(e,t,n,r,a){let s=0;const o=r[0],i=r[1],u=o+a[0];for(let r=o;r<u;r++){const o=r*t+i;n.set(e.subarray(o,o+a[1]),s),s+=a[1]}}(u,c[0],h,s,o);else if(3===d)!function(e,t,n,r,a,s){let o=0;const i=a[0],u=a[1],l=a[2],c=i+s[0],p=u+s[1];for(let a=i;a<c;a++)for(let i=u;i<p;i++){const u=a*t+i*n+l;r.set(e.subarray(u,u+s[2]),o),o+=s[2]}}(u,c[0],c[1],h,s,o);else if(4===d)!function(e,t,n,r,a,s,o){let i=0;const u=s[0],l=s[1],c=s[2],p=u+o[0],h=l+o[1],d=c+o[2],f=s[3];for(let s=u;s<p;s++)for(let u=l;u<h;u++)for(let l=c;l<d;l++){const c=s*t+u*n+l*r+f;a.set(e.subarray(c,c+o[3]),i),i+=o[3]}}(u,c[0],c[1],c[2],h,s,o);else{const e=gg(u,s,o,t.shape,t.dtype);h.set(e)}return l}const Gk={kernelName:Zn,backendName:"wasm",kernelFunc:Hk},jk={kernelName:zt,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,crops:o}=r,i=s.reduce(((e,t)=>e*t)),u=Ed(a.shape,s,i),l=Nd(u.length,s.length),c=Cd(a.shape,s,i),p=Ad(o,s.length),h=Rd(c,o,s.length),d=Uk({inputs:{x:a},backend:n,attrs:{shape:u}}),f=Ck({inputs:{x:d},backend:n,attrs:{perm:l}}),m=Hk({inputs:{x:Uk({inputs:{x:f},backend:n,attrs:{shape:c}})},backend:n,attrs:{begin:p,size:h}});return n.disposeData(d.dataId),n.disposeData(f.dataId),n.disposeData(d.dataId),m}};function Kk(e){const{inputs:{x:t},attrs:{dtype:n},backend:r}=e,a=r.makeOutput(t.shape,n),s=r.typedArrayFromHeap(t);return r.typedArrayFromHeap(a).set(s),a}const qk={kernelName:Vt,backendName:"wasm",kernelFunc:Kk},Xk=xk(Wt);let Yk;const Qk={kernelName:Ht,backendName:"wasm",setupFunc:function(e){Yk=e.wasm.cwrap(Ht,null,["number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{clipValueMin:s,clipValueMax:o}=r,i=n.dataIdMap.get(a.dataId).id,u=n.makeOutput(a.shape,a.dtype),l=n.dataIdMap.get(u.dataId).id;return Yk(i,s,o,l),u}};function Jk(e){const{inputs:t,backend:n}=e,r=it(e.attrs.axis,t[0].shape)[0];yd(t.map((e=>e.shape)),r);let a=bd(t.map((e=>e.shape)),r);const s=t.filter((e=>et(e.shape)>0));if(1===s.length)return Sk({inputs:{x:s[0]},backend:n});const o=n.makeOutput(a,t[0].dtype);if(0===et(a))return o;if("string"===s[0].dtype){const e=s.map((e=>{const t=et(e.shape.slice(r));return Uk({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),i=e.map((e=>({vals:n.readSync(e.dataId),shape:e.shape})));a=bd(e.map((e=>e.shape)),1);const u=1===e[0].shape[0],l=Lm(i,a,t[0].dtype,u),c=bd(s.map((e=>e.shape)),r);return o.shape=c,n.dataIdMap.get(o.dataId).stringBytes=qd(l),e.forEach((e=>n.disposeData(e.dataId))),o}const i=et(s[0].shape.slice(0,r));let u=0;const l=s.map((e=>{const t=et(e.shape.slice(r));return u+=t,t})),c=s.map((e=>n.typedArrayFromHeap(e))),p=n.typedArrayFromHeap(o);for(let e=0;e<i;e++){let t=e*u;for(let n=0;n<c.length;n++){const r=l[n],a=e*r,s=c[n].subarray(a,a+r);p.set(s,t),t+=r}}return o}const Zk={kernelName:Gt,backendName:"wasm",kernelFunc:Jk};let eI;const tI={kernelName:jt,backendName:"wasm",setupFunc:function(e){eI=e.wasm.cwrap(jt,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:a,filter:s}=t,o=r.dataIdMap.get(a.dataId).id,i=r.dataIdMap.get(s.dataId).id,{strides:u,dilations:l,pad:c,dimRoundingMode:p,dataFormat:h}=n,d=$u(h),f=wu(a.shape,s.shape,u,l,c,p,!1,d),m=f.filterHeight,g=f.filterWidth,y=f.padInfo.top,b=f.padInfo.right,_=f.padInfo.bottom,x=f.padInfo.left,v=f.dilationHeight,w=f.dilationWidth,T=f.strideHeight,k=f.strideWidth,I=f.inChannels,S=f.outChannels,E="SAME"===f.padInfo.type?1:0;if("channelsLast"!==f.dataFormat)throw new Error(`wasm backend Conv2D does not support dataFormat:'${f.dataFormat}'. Please use 'channelsLast'.`);const N=r.makeOutput(f.outShape,"float32"),C=r.dataIdMap.get(N.dataId).id;return eI(o,a.shape[0],a.shape[1],a.shape[2],i,m,g,y,b,_,x,E,v,w,T,k,I,S,C),N}};let nI;const rI={kernelName:Kt,backendName:"wasm",setupFunc:function(e){nI=e.wasm.cwrap(Kt,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{dy:a,filter:s}=n,{strides:o,pad:i,dataFormat:u,dimRoundingMode:l,inputShape:c}=r,p=$u(u),h=wu(c,s.shape,o,1,i,l,!1,p),{batchSize:d,filterHeight:f,filterWidth:m,inChannels:g,inHeight:y,inWidth:b,outChannels:_,outHeight:x,outWidth:v,strideHeight:w,strideWidth:T}=h,k=f-1-h.padInfo.top,I=m-1-h.padInfo.left,S="channelsLast"===h.dataFormat,E=yt(h.inShape),N=yt(a.shape),[C,A,R]=yt(s.shape),$=E[0],M=S?E[1]:E[2],F=S?E[2]:1,O=S?1:E[1],D=N[0],L=S?N[1]:N[2],P=S?N[2]:1,B=S?1:N[1],U=t.makeOutput(h.inShape,"float32"),z=t.dataIdMap.get(U.dataId).id,V=t.dataIdMap.get(a.dataId).id,W=t.dataIdMap.get(s.dataId).id;return nI(V,W,d,f,m,y,b,g,x,v,_,w,T,k,I,C,A,R,$,M,F,O,D,L,P,B,z),U}},aI=xk("Cos"),sI=xk(qt);var oI;let iI;!function(e){e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest"}(oI||(oI={}));const uI={kernelName:Qt,backendName:"wasm",setupFunc:function(e){iI=e.wasm.cwrap(Qt,null,["number","number","number","number","array","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{method:a,extrapolationValue:s,cropSize:o}=r,{image:i,boxes:u,boxInd:l}=n,c=u.shape[0],[p,h]=o,d=[c,p,h,i.shape[3]];let f,m=t.dataIdMap.get(i.dataId);"float32"!==i.dtype&&(f=Kk({backend:t,inputs:{x:i},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(f.dataId));const g=m.id,y=t.dataIdMap.get(u.dataId).id,b=t.dataIdMap.get(l.dataId).id,_=t.makeOutput(d,"float32"),x=t.dataIdMap.get(_.dataId).id,v=new Uint8Array(new Int32Array(i.shape).buffer);return iI(g,y,b,c,v,p,h,oI[a],s,x),null!=f&&t.disposeData(f.dataId),_}};let lI;const cI={kernelName:Xt,backendName:"wasm",setupFunc:function(e){lI=e.wasm.cwrap(Xt,null,["number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,exclusive:o,reverse:i}=r,u=a.shape.length;Qe("float32"===a.dtype||"int32"===a.dtype,(()=>`cumprod does not support ${a.dtype} tensors in the WASM backend`));const l=Fl([s],u);let c=a;null!==l&&(c=Ck({inputs:{x:a},attrs:{perm:l},backend:n}));const p=Dl(1,u)[0];Ml("cumprod",[p],u);const h=n.makeOutput(c.shape,c.dtype),d=c.shape[p],f=n.dataIdMap.get(c.dataId).id,m=n.dataIdMap.get(h.dataId).id;lI(f,o?1:0,i?1:0,d,m,fk[a.dtype]);let g=h;return null!==l&&(g=Ck({inputs:{x:h},attrs:{perm:Ol(l)},backend:n}),n.disposeData(c.dataId),n.disposeData(h.dataId)),g}};let pI;const hI={kernelName:Yt,backendName:"wasm",setupFunc:function(e){pI=e.wasm.cwrap(Yt,null,["number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,exclusive:o,reverse:i}=r,u=a.shape.length;Qe("float32"===a.dtype||"int32"===a.dtype,(()=>`cumsum does not support ${a.dtype} tensors in the WASM backend`));const l=Fl([s],u);let c=a;null!==l&&(c=Ck({inputs:{x:a},attrs:{perm:l},backend:n}));const p=Dl(1,u)[0];Ml("cumsum",[p],u);const h=n.makeOutput(c.shape,c.dtype),d=c.shape[p],f=n.dataIdMap.get(c.dataId).id,m=n.dataIdMap.get(h.dataId).id;pI(f,o?1:0,i?1:0,d,m,fk[a.dtype]);let g=h;return null!==l&&(g=Ck({inputs:{x:h},attrs:{perm:Ol(l)},backend:n}),n.disposeData(c.dataId),n.disposeData(h.dataId)),g}};let dI;const fI={kernelName:Jt,backendName:"wasm",setupFunc:function(e){dI=e.wasm.cwrap(Jt,null,["number","number","number","array","number","array","array","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{x:a}=n,{blockSize:s,dataFormat:o}=r,i=a.shape[0],u=("NHWC"===o?a.shape[1]:a.shape[2])*s,l=("NHWC"===o?a.shape[2]:a.shape[3])*s,c=("NHWC"===o?a.shape[3]:a.shape[1])/(s*s),p="NHWC"===o?[i,u,l,c]:[i,c,u,l],h=t.makeOutput(p,"float32"),d=t.dataIdMap.get(a.dataId).id,f=new Uint8Array(new Int32Array(yt(a.shape)).buffer),m=new Uint8Array(new Int32Array(p).buffer),g=new Uint8Array(new Int32Array(yt(p)).buffer),y=t.dataIdMap.get(h.dataId).id;return dI(d,s,"NHWC"===o?1:0,f,a.shape.length-1,m,g,p.length,y),h}};let mI;const gI={kernelName:Zt,backendName:"wasm",setupFunc:function(e){mI=e.wasm.cwrap(Zt,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:a,filter:s}=t,o=r.dataIdMap.get(a.dataId).id,i=r.dataIdMap.get(s.dataId).id,{strides:u,dilations:l,pad:c,dimRoundingMode:p}=n,h=null==l?[1,1]:l,d=wu(a.shape,s.shape,u,h,c,p,!0),f=d.filterHeight,m=d.filterWidth,g=d.padInfo.top,y=d.padInfo.right,b=d.padInfo.bottom,_=d.padInfo.left,x=d.dilationHeight,v=d.dilationWidth,w=d.strideHeight,T=d.strideWidth,k=d.inChannels,I=d.outChannels,S="SAME"===d.padInfo.type?1:0;if("channelsLast"!==d.dataFormat)throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${d.dataFormat}'. Please use 'channelsLast'.`);const E=r.makeOutput(d.outShape,"float32"),N=r.dataIdMap.get(E.dataId).id;return mI(o,a.shape[0],a.shape[1],a.shape[2],i,f,m,g,y,b,_,S,x,v,w,T,k,I,N),E}},yI=xk(tn),bI=wk(nn,0,"bool"),_I=xk(rn,"float32");function xI(e){const{inputs:t,attrs:n,backend:r}=e,{input:a}=t,{dim:s}=n,o=a.shape.length,i=a.shape.slice();let u=s;return s<0&&(Qe(-(o+1)<=s,(()=>`Axis must be in the interval [${-(o+1)}, ${o}]`)),u=o+s+1),i.splice(u,0,1),Uk({inputs:{x:a},backend:r,attrs:{shape:i}})}const vI={kernelName:an,backendName:"wasm",kernelFunc:xI};function wI(e){const{attrs:{shape:t,value:n,dtype:r},backend:a}=e,s=a.makeOutput(t,r);return a.typedArrayFromHeap(s).fill(n),s}const TI={kernelName:sn,backendName:"wasm",kernelFunc:wI};let kI;const II={kernelName:on,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n}=e,{image:r}=t,a=n.makeOutput(r.shape,r.dtype),s=n.dataIdMap.get(r.dataId).id,o=n.dataIdMap.get(a.dataId).id,[i,u,l,c]=r.shape;return kI(s,i,u,l,c,o),a},setupFunc:function(e){kI=e.wasm.cwrap(on,null,["number","number","number","number","number","number"])}},SI=xk(un),EI=wk(ln);let NI;const CI={kernelName:cn,backendName:"wasm",setupFunc:function(e){NI=e.wasm.cwrap(cn,null,["number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{varianceEpsilon:a}=r,{x:s,mean:o,variance:i,offset:u,scale:l}=n,c=t.dataIdMap.get(s.dataId).id,p=t.dataIdMap.get(o.dataId).id,h=t.dataIdMap.get(i.dataId).id,d=null!=u?t.dataIdMap.get(u.dataId).id:0,f=null!=l?t.dataIdMap.get(l.dataId).id:0,m=t.makeOutput(s.shape,s.dtype);if(0===et(s.shape))return m;const g=t.dataIdMap.get(m.dataId).id;return NI(c,p,h,d,f,a,g),m}};let AI;const RI={kernelName:Er,backendName:"wasm",setupFunc:function(e){AI=e.wasm.cwrap(Er,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dilations:c,dataFormat:p,dimRoundingMode:h,activation:d,leakyreluAlpha:f}=n,m=wu(a.shape,s.shape,u,c,l,h),g=mk[d];if(null==g)throw new Error(`${d} activation not yet supported for FusedConv2D in the wasm backend.`);const y=r.dataIdMap.get(a.dataId).id,b=r.dataIdMap.get(s.dataId).id,_=m.outChannels;let x=0;if(null!=o){const e=r.dataIdMap.get(o.dataId);if(1!==e.shape.length)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${e.shape.length}.`);if(e.shape[0]!==_)throw new Error(`FusedConv2D bias shape (${e.shape}) does not match the number of output channels (${_})`);x=e.id}const v=m.filterHeight,w=m.filterWidth,T=m.padInfo.top,k=m.padInfo.right,I=m.padInfo.bottom,S=m.padInfo.left,E=m.dilationHeight,N=m.dilationWidth,C=m.strideHeight,A=m.strideWidth,R=m.inChannels,$="SAME"===m.padInfo.type?1:0,M=m.batchSize,F=m.inHeight,O=m.inWidth;if("NHWC"!==p)throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);const D=r.makeOutput(m.outShape,"float32"),L=r.dataIdMap.get(D.dataId).id,P=null==i?0:r.dataIdMap.get(i.dataId).id;return AI(y,M,F,O,b,v,w,x,T,k,I,S,$,E,N,C,A,R,_,g,P,f||0,L),D}};let $I;const MI={kernelName:Nr,backendName:"wasm",setupFunc:function(e){$I=e.wasm.cwrap(Nr,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dilations:c,dataFormat:p,dimRoundingMode:h,activation:d,leakyreluAlpha:f}=n,m=wu(a.shape,s.shape,u,c,l,h,!0),g=mk[d];if(null==g)throw new Error(`${d} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);const y=r.dataIdMap.get(a.dataId).id,b=r.dataIdMap.get(s.dataId).id,_=m.outChannels;let x=0;if(null!=o){const e=r.dataIdMap.get(o.dataId);if(1!==e.shape.length)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${e.shape.length}.`);if(e.shape[0]!==_)throw new Error(`FusedDepthwiseConv2D bias shape (${e.shape}) does not match the number of output channels (${_})`);x=e.id}const v=m.filterHeight,w=m.filterWidth,T=m.padInfo.top,k=m.padInfo.right,I=m.padInfo.bottom,S=m.padInfo.left,E=m.dilationHeight,N=m.dilationWidth,C=m.strideHeight,A=m.strideWidth,R=m.inChannels,$="SAME"===m.padInfo.type?1:0,M=m.batchSize,F=m.inHeight,O=m.inWidth;if("NHWC"!==p)throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);const D=r.makeOutput(m.outShape,"float32"),L=r.dataIdMap.get(D.dataId).id,P=null==i?0:r.dataIdMap.get(i.dataId).id;return $I(y,M,F,O,b,v,w,x,T,k,I,S,$,E,N,C,A,R,_,g,P,f||0,L),D}};let FI;const OI={kernelName:hn,backendName:"wasm",setupFunc:function(e){FI=e.wasm.cwrap(hn,null,["number","number","number","number","number","number","array","number"])},kernelFunc:function(e){const{backend:t,inputs:n}=e,{params:r,indices:a}=n,[s,o,i,u]=Pi(r,a),l=t.makeOutput(s,r.dtype);if(0===o)return l;const c=a.shape,p=c[c.length-1],h=t.dataIdMap.get(r.dataId).id,d=t.dataIdMap.get(a.dataId).id,f=new Uint8Array(new Int32Array(u).buffer),m=t.dataIdMap.get(l.dataId).id;return FI(h,fk[r.dtype],d,o,p,i,f,m),l}};let DI;const LI={kernelName:pn,backendName:"wasm",setupFunc:function(e){DI=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{x:a,indices:s}=n,{axis:o,batchDims:i}=r,u=it(o,a.shape)[0],l=t.readSync(s.dataId),c=a.shape[u];for(let e=0;e<l.length;++e){const t=l[e];Qe(t<=c-1&&t>=0,(()=>`GatherV2: the index value ${t} is not in [0, ${c-1}]`))}const p=Gd(a,s,u,i),h=Uk({inputs:{x:a},attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]},backend:t}),d=et(s.shape),f=Uk({inputs:{x:s},attrs:{shape:[p.batchSize,d/p.batchSize]},backend:t}),m=[p.batchSize,p.outerSize,d/p.batchSize,p.sliceSize],g=t.makeOutput(m,a.dtype);if(0===et(a.shape))return g;const y=h.shape.length-1,b=t.dataIdMap.get(h.dataId).id,_=t.dataIdMap.get(f.dataId).id,x=t.dataIdMap.get(g.dataId).id,v=new Uint8Array(new Int32Array(yt(h.shape)).buffer),w=new Uint8Array(new Int32Array(yt(m)).buffer);return DI(b,fk[a.dtype],v,y,_,p.batchSize,w,x),t.disposeData(h.dataId),t.disposeData(f.dataId),g.shape=p.outputShape,g}},PI=wk(dn,0,"bool"),BI=wk(fn,0,"bool"),UI=xk(gn,"bool");let zI;const VI={kernelName:yn,backendName:"wasm",setupFunc:function(e){zI=e.wasm.cwrap(yn,null,["number","number","number","number"])},kernelFunc:function(e){const{inputs:{x:t},attrs:{alpha:n},backend:r}=e,a=r.dataIdMap.get(t.dataId).id,s=r.makeOutput(t.shape,"float32");if(0!==et(t.shape)){const e=r.dataIdMap.get(s.dataId).id;zI(a,fk[t.dtype],n,e)}return s}},WI=wk(bn,0,"bool"),HI=wk(_n,0,"bool"),GI=xk("Log"),jI=wk(xn,0,"bool"),KI=xk(vn),qI=wk(wn,0,"bool"),XI=wk("LogicalXor",0,"bool");let YI;const QI={kernelName:Tn,backendName:"wasm",setupFunc:function(e){YI=e.wasm.cwrap(Tn,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{reductionIndices:a,keepDims:s}=r,{x:o}=n;let i=t.dataIdMap.get(o.dataId).id,u=o;const{transposed:l,axes:c,originalAxes:p,inputWasTransposed:h}=Rk(o,a,t);h&&(u=l,i=t.dataIdMap.get(l.dataId).id),Ml("max",c,u.shape.length);const[d,f]=Rl(u.shape,c),m=et(f),g=t.makeOutput(d,o.dtype);if(0!==et(u.shape)){const e=t.dataIdMap.get(g.dataId).id;YI(i,fk[o.dtype],m,e)}if(h&&t.disposeData(l.dataId),s){const e=$l(g.shape,p);g.shape=e}return g}},JI=wk(kn);let ZI;const eS={kernelName:In,backendName:"wasm",setupFunc:function(e){ZI=e.wasm.cwrap(In,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,a=t.x,s=r.dataIdMap.get(a.dataId).id;Qe("float32"===a.dtype,(()=>`Error in MaxPool: only float32 input is supported. Got ${a.dtype}.`));const{filterSize:o,strides:i,pad:u,dimRoundingMode:l}=n,c=vu(a.shape,o,i,1,u,l),p=c.filterHeight,h=c.filterWidth,d=c.padInfo.top,f=c.padInfo.right,m=c.padInfo.bottom,g=c.padInfo.left,y=c.dilationHeight,b=c.dilationWidth,_=c.strideHeight,x=c.strideWidth,v=c.inChannels,w=c.outChannels;if("channelsLast"!==c.dataFormat)throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);const T=r.makeOutput(c.outShape,"float32"),k=r.dataIdMap.get(T.dataId).id;return ZI(s,a.shape[0],a.shape[1],a.shape[2],p,h,d,f,m,g,y,b,_,x,v,w,k),T}};let tS;const nS={kernelName:Sn,backendName:"wasm",setupFunc:function(e){tS=e.wasm.cwrap(Sn,null,["number, number, number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:a,keepDims:s}=r,{x:o}=n,i=t.dataIdMap.get(o.dataId).id;let u=i,l=o;const{transposed:c,axes:p,originalAxes:h,inputWasTransposed:d}=Rk(o,a,t);let f=p;if(d){const e=t.dataIdMap.get(c.dataId).id;e!==i&&(l=c,u=e,f=Dl(f.length,l.shape.length))}Ml("mean",f,l.shape.length);const[m,g]=Rl(l.shape,f),y=et(g);let b=l;"float32"!==l.dtype&&(b=Kk({backend:t,inputs:{x:l},attrs:{dtype:"float32"}}),u=t.dataIdMap.get(b.dataId).id);const _=t.makeOutput(m,"float32");if(0!==et(l.shape)){const e=t.dataIdMap.get(_.dataId).id;tS(u,y,e)}if(d&&t.disposeData(c.dataId),s){const e=$l(_.shape,h);_.shape=e}return"float32"!==l.dtype&&t.disposeData(b.dataId),_}};let rS;const aS={kernelName:En,backendName:"wasm",setupFunc:function(e){rS=e.wasm.cwrap(En,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:a,keepDims:s}=r,{x:o}=n,i=t.dataIdMap.get(o.dataId).id;let u=i,l=o;const{transposed:c,axes:p,originalAxes:h,inputWasTransposed:d}=Rk(o,a,t);if(d){const e=t.dataIdMap.get(c.dataId).id;e!==i&&(l=c,u=e)}Ml("min",p,l.shape.length);const[f,m]=Rl(l.shape,p),g=et(m),y=t.makeOutput(f,l.dtype);if(0!==et(l.shape)){const e=t.dataIdMap.get(y.dataId).id;rS(u,fk[o.dtype],g,e)}if(d&&t.disposeData(c.dataId),s){const e=$l(y.shape,h);y.shape=e}return y}},sS=wk(Nn);var oS;let iS;!function(e){e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric"}(oS||(oS={}));const uS={kernelName:Cn,backendName:"wasm",kernelFunc:function(e){const{inputs:{x:t},backend:n,attrs:{paddings:r,mode:a}}=e,s=r.map(((e,n)=>e[0]+t.shape[n]+e[1])),o=n.dataIdMap.get(t.dataId).id,i=n.makeOutput(s,t.dtype),u=n.dataIdMap.get(i.dataId).id,l=new Uint8Array(new Int32Array(t.shape).buffer),c=r.map((e=>e[0])),p=r.map((e=>e[1])),h=new Uint8Array(new Int32Array(c).buffer),d=new Uint8Array(new Int32Array(p).buffer);return iS(o,l,t.shape.length,fk[t.dtype],h,d,oS[a],u),i},setupFunc:function(e){iS=e.wasm.cwrap(Cn,null,["number","array","number","number","array","array","number","number"])}},lS=wk(An),cS=xk("Neg");function pS(e,t){const n=new Int32Array(e.wasm.HEAPU8.buffer,t,4),r=n[0],a=n[1],s=n[2],o=n[3];return e.wasm._free(t),{pSelectedIndices:r,selectedSize:a,pSelectedScores:s,pValidOutputs:o}}let hS;const dS={kernelName:$n,backendName:"wasm",setupFunc:function(e){hS=e.wasm.cwrap($n,"number",["number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{iouThreshold:a,maxOutputSize:s,scoreThreshold:o}=r,{boxes:i,scores:u}=n,l=t.dataIdMap.get(i.dataId).id,c=t.dataIdMap.get(u.dataId).id,p=hS(l,c,s,a,o),{pSelectedIndices:h,selectedSize:d,pSelectedScores:f,pValidOutputs:m}=pS(t,p);return t.wasm._free(f),t.wasm._free(m),t.makeOutput([d],"int32",h)}};let fS;const mS={kernelName:Mn,backendName:"wasm",setupFunc:function(e){fS=e.wasm.cwrap(Mn,"number",["number","number","number","number","number","bool"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{iouThreshold:a,maxOutputSize:s,scoreThreshold:o,padToMaxOutputSize:i}=r,{boxes:u,scores:l}=n,c=t.dataIdMap.get(u.dataId).id,p=t.dataIdMap.get(l.dataId).id,h=fS(c,p,s,a,o,i),{pSelectedIndices:d,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=pS(t,h);return t.wasm._free(m),[t.makeOutput([f],"int32",d),t.makeOutput([],"int32",g)]}};let gS;const yS={kernelName:Fn,backendName:"wasm",setupFunc:function(e){gS=e.wasm.cwrap(Fn,"number",["number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{iouThreshold:a,maxOutputSize:s,scoreThreshold:o,softNmsSigma:i}=r,{boxes:u,scores:l}=n,c=t.dataIdMap.get(u.dataId).id,p=t.dataIdMap.get(l.dataId).id,h=gS(c,p,s,a,o,i),{pSelectedIndices:d,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=pS(t,h);return t.wasm._free(g),[t.makeOutput([f],"int32",d),t.makeOutput([f],"float32",m)]}},bS=wk(Rn,0,"bool");let _S;const xS={kernelName:Dn,backendName:"wasm",setupFunc:function(e){_S=e.wasm.cwrap(Dn,null,["number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:a}=t,{dtype:s,depth:o,onValue:i,offValue:u}=r,l=n.makeOutput([...a.shape,o],s),c=n.dataIdMap.get(l.dataId).id,p=n.dataIdMap.get(a.dataId).id;return _S(p,o,i,u,c),l}},vS={kernelName:On,backendName:"wasm",kernelFunc:function(e){const{inputs:{x:t},backend:n}=e,r=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(r).fill(1),r}},wS={kernelName:Ln,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return xI({inputs:{input:t[0]},backend:n,attrs:{dim:a}});const s=t[0].shape,o=t[0].dtype;t.forEach((e=>{Je(s,e.shape,"All tensors passed to stack must have matching shapes"),Qe(o===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const i=[],u=Jk({inputs:t.map((e=>{const t=xI({inputs:{input:e},backend:n,attrs:{dim:a}});return i.push(t),t})),backend:n,attrs:{axis:a}});return i.forEach((e=>n.disposeData(e.dataId))),u}};let TS;const kS={kernelName:Pn,backendName:"wasm",kernelFunc:function(e){const{inputs:{x:t},backend:n,attrs:{paddings:r,constantValue:a}}=e,s=r.map(((e,n)=>e[0]+t.shape[n]+e[1]));if(0===et(t.shape))return wI({backend:n,attrs:{shape:s,value:a,dtype:t.dtype}});const o=n.dataIdMap.get(t.dataId).id,i=n.makeOutput(s,t.dtype),u=n.dataIdMap.get(i.dataId).id,l=new Uint8Array(new Int32Array(t.shape).buffer),c=r.map((e=>e[0])),p=r.map((e=>e[1])),h=new Uint8Array(new Int32Array(c).buffer),d=new Uint8Array(new Int32Array(p).buffer);return TS(o,l,t.shape.length,fk[t.dtype],h,d,a,u),i},setupFunc:function(e){TS=e.wasm.cwrap(Pn,null,["number","array","number","number","array","array","number","number"])}},IS=wk("Pow");let SS;const ES={kernelName:Bn,backendName:"wasm",setupFunc:function(e){SS=e.wasm.cwrap(Bn,null,["number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r,alpha:a}=t,s=n.dataIdMap.get(r.dataId).id,o=n.dataIdMap.get(a.dataId).id;let i=s;const u=r;let l=u;"float32"!==u.dtype&&(l=Kk({backend:n,inputs:{x:r},attrs:{dtype:"float32"}}),i=n.dataIdMap.get(l.dataId).id);const c=n.makeOutput(r.shape,"float32"),p=n.dataIdMap.get(c.dataId).id;return SS(i,o,p),"float32"!==u.dtype&&n.disposeData(l.dataId),c}};let NS;const CS={kernelName:Un,backendName:"wasm",setupFunc:function(e){NS=e.wasm.cwrap(Un,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:a,keepDims:s}=r,{x:o}=n,i=t.dataIdMap.get(o.dataId).id;let u=i,l=o;const{transposed:c,axes:p,originalAxes:h,inputWasTransposed:d}=Rk(o,a,t);let f=p;if(d){const e=t.dataIdMap.get(c.dataId).id;e!==i&&(l=c,u=e,f=Dl(f.length,l.shape.length))}Ml("prod",f,l.shape.length);const[m,g]=Rl(l.shape,f),y=et(g),b=t.makeOutput(m,l.dtype);if(0!==et(l.shape)){const e=t.dataIdMap.get(b.dataId).id;NS(u,y,fk[b.dtype],e)}if(d&&t.disposeData(c.dataId),s){const e=$l(b.shape,h);b.shape=e}return b}},AS={kernelName:zn,backendName:"wasm",kernelFunc:e=>{const{backend:t,attrs:n}=e,{start:r,stop:a,step:s,dtype:o}=n,i=pg(r,a,s,o),u=t.makeOutput([i.length],o);return t.typedArrayFromHeap(u).set(i),u}},RS=wk(en),$S=xk(Vn),MS=xk(Wn),FS=xk(Kn);let OS;const DS={kernelName:jn,backendName:"wasm",setupFunc:function(e){OS=e.wasm.cwrap(jn,null,["number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{images:a}=n,{alignCorners:s,halfPixelCenters:o,size:i}=r,[u,l]=i,[c,p,h,d]=a.shape,f=[c,u,l,d];let m,g=t.dataIdMap.get(a.dataId);"float32"!==g.dtype&&(m=Kk({backend:t,inputs:{x:a},attrs:{dtype:"float32"}}),g=t.dataIdMap.get(m.dataId));const y=g.id,b=t.makeOutput(f,"float32");if(0===et(a.shape))return b;const _=t.dataIdMap.get(b.dataId).id;return OS(y,c,p,h,d,u,l,s?1:0,o?1:0,_),null!=m&&t.disposeData(m.dataId),b}};let LS;const PS={kernelName:Gn,backendName:"wasm",setupFunc:function(e){LS=e.wasm.cwrap(Gn,null,["number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{images:a}=n,{alignCorners:s,halfPixelCenters:o,size:i}=r,[u,l]=i,[c,p,h,d]=a.shape,f=[c,u,l,d],m=t.makeOutput(f,"float32");if(0===et(a.shape))return m;let g,y=t.dataIdMap.get(a.dataId);"float32"!==y.dtype&&(g=Kk({backend:t,inputs:{x:a},attrs:{dtype:"float32"}}),y=t.dataIdMap.get(g.dataId));const b=y.id,_=t.dataIdMap.get(m.dataId).id;return LS(b,c,p,h,d,u,l,s?1:0,o?1:0,_),null!=g&&t.disposeData(g.dataId),m}};let BS;const US={kernelName:qn,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dims:s}=r,o=it(s,a.shape);if(0===a.shape.length)return Sk({inputs:{x:a},backend:n});const i=n.makeOutput(a.shape,a.dtype),u=n.dataIdMap.get(a.dataId).id,l=n.dataIdMap.get(i.dataId).id,c=new Uint8Array(new Int32Array(o).buffer),p=new Uint8Array(new Int32Array(a.shape).buffer);BS(u,c,o.length,p,a.shape.length,l);const h=Uk({inputs:{x:i},attrs:{shape:a.shape},backend:n});return n.disposeData(i.dataId),h},setupFunc:function(e){BS=e.wasm.cwrap(qn,null,["number","array","number","array","number","number"])}};let zS;const VS={kernelName:Ir,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:a}=t,{radians:s,fillValue:o,center:i}=r,u=n.makeOutput(a.shape,a.dtype),l=n.dataIdMap.get(a.dataId).id,c=n.dataIdMap.get(u.dataId).id,[p,h,d,f]=a.shape,[m,g]=Sd(i,h,d),y="number"==typeof o?[o,o,o,0===o?0:255]:[...o,255],b=new Uint8Array(new Int32Array(y).buffer);return zS(l,p,h,d,f,s,m,g,b,y.length,c),u},setupFunc:function(e){zS=e.wasm.cwrap(Ir,null,["number","number","number","number","number","number","number","number","array","number","number"])}},WS=xk(Xn),HS=xk(Yn);let GS;const jS={kernelName:Qn,backendName:"wasm",setupFunc:function(e){GS=e.wasm.cwrap(Qn,null,["number","number","number","number","number","number","array","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{indices:a,updates:s}=n,{shape:o}=r,i=t.makeOutput(o,s.dtype);if(0===et(o))return i;const{sliceRank:u,numUpdates:l,sliceSize:c,strides:p,outputSize:h}=zi(0,a,o),d=t.dataIdMap.get(a.dataId).id,f=t.dataIdMap.get(s.dataId).id,m=new Uint8Array(new Int32Array(p).buffer),g=t.dataIdMap.get(i.dataId).id;return GS(d,f,fk[s.dtype],u,l,c,m,h,g),i}};let KS;const qS={kernelName:Jn,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:r,t:a,e:s}=t,o=n.dataIdMap.get(r.dataId).id,i=n.dataIdMap.get(a.dataId).id,u=n.dataIdMap.get(s.dataId).id,l=n.makeOutput(a.shape,a.dtype),c=n.dataIdMap.get(l.dataId).id,p=r.shape.length,h=a.shape.length,d=0===p||p>1||1===h?1:et(a.shape.slice(1));return KS(o,i,u,d,c),l},setupFunc:function(e){KS=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}};let XS;const YS={kernelName:"Sigmoid",backendName:"wasm",setupFunc:function(e){XS=e.wasm.cwrap(er,null,["number","number"])},kernelFunc:function(e){const{backend:t,inputs:{x:n}}=e,r=t.dataIdMap.get(n.dataId).id,a=t.makeOutput(n.shape,n.dtype),s=t.dataIdMap.get(a.dataId).id;return 0===et(a.shape)||XS(r,s),a}},QS=xk("Sin");let JS;const ZS={kernelName:sr,backendName:"wasm",setupFunc:function(e){JS=e.wasm.cwrap(sr,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:{logits:n},attrs:{dim:r}}=e,a=t.dataIdMap.get(n.dataId).id,s=t.makeOutput(n.shape,n.dtype),o=t.dataIdMap.get(s.dataId).id,i=n.shape[r],u=et(n.shape)/i;return 0===et(s.shape)||JS(a,o,i,u),s}},eE={kernelName:rr,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,paddings:o}=r,i=et(s),u=[[0,0]];u.push(...o);for(let e=1+s.length;e<a.shape.length;++e)u.push([0,0]);const l=kS.kernelFunc({inputs:{x:a},backend:n,attrs:{paddings:u,constantValue:0}}),c=Ed(l.shape,s,i,!1),p=Nd(c.length,s.length,!1),h=Cd(l.shape,s,i,!1),d=Uk({inputs:{x:l},backend:n,attrs:{shape:c}}),f=Ck({inputs:{x:d},backend:n,attrs:{perm:p}}),m=Uk({inputs:{x:f},backend:n,attrs:{shape:h}});return n.disposeData(l.dataId),n.disposeData(d.dataId),n.disposeData(f.dataId),m}};let tE;const nE={kernelName:or,backendName:"wasm",setupFunc:function(e){tE=e.wasm.cwrap("SparseFillEmptyRows","number",["number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n}=e,{indices:r,values:a,denseShape:s,defaultValue:o}=n,i=r.shape[0],u=r.shape[1],l=t.readSync(s.dataId)[0],c=[i+l,u],p=t.dataIdMap.get(r.dataId).id,h=t.dataIdMap.get(a.dataId).id,d=t.dataIdMap.get(o.dataId).id,f=t.makeOutput(c,r.dtype),m=t.dataIdMap.get(f.dataId).id,g=t.makeOutput(c.slice(0,1),a.dtype),y=t.dataIdMap.get(g.dataId).id,b=t.makeOutput([l],"bool"),_=t.dataIdMap.get(b.dataId).id,x=t.makeOutput([i],r.dtype),v=t.dataIdMap.get(x.dataId).id,w=t.makeOutput([4],"int32"),T=t.dataIdMap.get(w.dataId).id,k=tE(p,h,fk[a.dtype],i,l,u,d,m,y,_,v,T),I=t.readSync(w.dataId);let S;switch(I[0]){case 1:S=Dd(I[1]);break;case 2:S=Ld(I[1],I[2]);break;case 3:S=Pd(I[1],I[2],I[3]);break;default:S=""}if(t.disposeData(w.dataId),S)throw t.disposeData(f.dataId),t.disposeData(g.dataId),t.disposeData(b.dataId),t.disposeData(x.dataId),new Error(S);let E=f,N=g;return k!==c[0]&&(E=Hk({inputs:{x:f},attrs:{begin:0,size:[k,u]},backend:t}),N=Hk({inputs:{x:g},attrs:{begin:0,size:k},backend:t}),t.disposeData(f.dataId),t.disposeData(g.dataId)),[E,N,b,x]}};let rE;const aE={kernelName:ir,backendName:"wasm",setupFunc:function(e){rE=e.wasm.cwrap(ir,null,["number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n}=e,{inputIndices:r,inputShape:a,newShape:s}=n;if(2!==r.shape.length)throw new Error(`Input indices should be a matrix but received shape\n ${r.shape}`);if(1!==a.shape.length)throw new Error(`Input shape should be a vector but received shape\n ${a.shape}`);if(1!==s.shape.length)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);const o=t.dataIdMap.get(r.dataId).id,i=t.dataIdMap.get(a.dataId).id,u=t.dataIdMap.get(s.dataId).id,l=r.shape[0],c=et(s.shape),p=t.makeOutput([l,c],r.dtype),h=t.dataIdMap.get(p.dataId).id,d=t.makeOutput([c],s.dtype),f=t.dataIdMap.get(d.dataId).id,m=t.makeOutput([3],"int32"),g=t.dataIdMap.get(m.dataId).id;rE(o,i,u,l,h,f,g);const y=t.readSync(m.dataId);let b;switch(y[0]){case 0:b=Bd(y[1],y[2]);break;case 1:b=Ud(y[1],y[2]);break;case 2:b="reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero";break;case 3:b=zd(Array.from(t.readSync(a.dataId)),Array.from(t.readSync(d.dataId)));break;case 4:b=Vd(Array.from(t.readSync(a.dataId)),Array.from(t.readSync(d.dataId)));break;default:b=""}if(t.disposeData(m.dataId),b)throw t.disposeData(p.dataId),t.disposeData(d.dataId),new Error(b);return[p,d]}};let sE;function oE(e){sE=e.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function iE(e,t){const{backend:n,inputs:r}=e,{data:a,indices:s,segmentIds:o}=r,i=s.shape[0],u=n.readSync(o.dataId,i-1,i)[0],l=i>0?u+1:0;if(l<0)throw new Error("segment ids must be >= 0");const c=a.shape.slice();c[0]=l;const p=n.dataIdMap.get(a.dataId).id,h=n.dataIdMap.get(s.dataId).id,d=n.dataIdMap.get(o.dataId).id,f=n.makeOutput(c,a.dtype),m=n.dataIdMap.get(f.dataId).id,g=n.makeOutput([4],"int32"),y=n.dataIdMap.get(g.dataId).id;sE(p,fk[a.dtype],a.shape[0],h,d,m,y,t,0);const b=n.readSync(g.dataId);let _;switch(b[0]){case 0:_="segment ids must be >= 0";break;case 1:_="segment ids are not increasing";break;case 2:_=Wd(b[1],b[2]);break;case 3:_=Hd(b[1],b[2],b[3]);break;default:_=""}if(n.disposeData(g.dataId),_)throw n.disposeData(f.dataId),new Error(_);return f}const uE={kernelName:ur,backendName:"wasm",setupFunc:oE,kernelFunc:function(e){return iE(e,!0)}},lE={kernelName:lr,backendName:"wasm",setupFunc:oE,kernelFunc:function(e){return iE(e,!1)}},cE={kernelName:ar,backendName:"wasm",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:a}=t,{numOrSizeSplits:s,axis:o}=n,i=it(o,a.shape)[0],u=Od(a,s,i),l=new Array(a.shape.length).fill(0),c=a.shape.slice();return u.map((e=>{const t=[...c];t[i]=e;const n=Hk({inputs:{x:a},attrs:{begin:l,size:t},backend:r});return l[i]+=e,n}))}},pE=xk(tr),hE=xk("Square"),dE=wk(cr);let fE;const mE={kernelName:Tr,backendName:"wasm",setupFunc:function(e){fE=e.wasm.cwrap(Tr,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{alpha:a}=r,{x:s}=n,o=t.dataIdMap.get(s.dataId).id,i=t.makeOutput(s.shape,s.dtype),u=t.dataIdMap.get(i.dataId).id;return fE(o,a,fk[s.dtype],u),i}};let gE;const yE={kernelName:pr,backendName:"wasm",setupFunc:function(e){gE=e.wasm.cwrap(pr,null,["number","array","number","array","array","array","array","array","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{x:a}=n,{begin:s,end:o,strides:i,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:h}=r,{finalShapeSparse:d,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:_,strides:x}=tu(a.shape,s,o,i,u,l,c,p,h);let v;if(m)v=Uk({inputs:{x:a},backend:t,attrs:{shape:f}});else if(g||y){Qe(a.shape.length>=1,(()=>`Input must have rank at least 1, got: ${a.shape.length}`));const e=Wi(b,_,x),n=Hk({inputs:{x:a},backend:t,attrs:{begin:b,size:e}});v=Uk({inputs:{x:n},backend:t,attrs:{shape:f}}),t.disposeData(n.dataId)}else{const e=t.makeOutput(d,"float32"),n=t.dataIdMap.get(a.dataId).id,r=new Uint8Array(new Int32Array(yt(a.shape)).buffer),s=new Uint8Array(new Int32Array(b).buffer),o=new Uint8Array(new Int32Array(_).buffer),i=new Uint8Array(new Int32Array(x).buffer),u=new Uint8Array(new Int32Array(d).buffer),l=new Uint8Array(new Int32Array(yt(d)).buffer),c=t.dataIdMap.get(e.dataId).id;gE(n,r,a.shape.length,s,o,i,u,l,d.length,c),v=Uk({inputs:{x:e},backend:t,attrs:{shape:f}}),t.disposeData(e.dataId)}return v}},bE={kernelName:hr,backendName:"wasm",kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{data:a,dataSplits:s}=n,{separator:o,nGramWidths:i,leftPad:u,rightPad:l,padWidth:c,preserveShortSequences:p}=r,h=t.readSync(a.dataId),d=t.readSync(s.dataId),[f,m]=Tg(h,d,o,i,u,l,c,p),g=t.makeOutput([f.length],"string");t.dataIdMap.get(g.dataId).stringBytes=f;const y=t.makeOutput(s.shape,"int32");return t.typedArrayFromHeap(y).set(m),[g,y]}},_E={kernelName:dr,backendName:"wasm",kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{input:a,delimiter:s}=n,{skipEmpty:o}=r,i=t.readSync(a.dataId),u=t.readSync(s.dataId),[l,c,p]=Ig(i,u[0],o),h=c.length,d=t.makeOutput([h,2],"int32");t.typedArrayFromHeap(d).set(l);const f=t.makeOutput([h],"string");t.dataIdMap.get(f.dataId).stringBytes=c;const m=t.makeOutput([2],"int32");return t.typedArrayFromHeap(m).set(p),[d,f,m]}},xE={kernelName:fr,backendName:"wasm",kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{input:a}=n,{numBuckets:s}=r,o=Sg(t.readSync(a.dataId),s),i=t.makeOutput(a.shape,"int32");return t.typedArrayFromHeap(i).set(o),i}},vE=wk(mr);let wE;const TE={kernelName:nr,backendName:"wasm",setupFunc:function(e){wE=e.wasm.cwrap(nr,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:a,keepDims:s}=r,{x:o}=n,i=t.dataIdMap.get(o.dataId).id;let u=i,l=o;const{transposed:c,axes:p,originalAxes:h,inputWasTransposed:d}=Rk(o,a,t);let f=p;if(d){const e=t.dataIdMap.get(c.dataId).id;e!==i&&(l=c,u=e,f=Dl(f.length,l.shape.length))}Ml("sum",f,l.shape.length);const[m,g]=Rl(l.shape,f),y=et(g),b=t.makeOutput(m,l.dtype);if(0!==et(l.shape)){const e=t.dataIdMap.get(b.dataId).id;wE(u,y,fk[b.dtype],e)}if(d&&t.disposeData(c.dataId),s){const e=$l(b.shape,h);b.shape=e}return b}},kE=xk("Tan"),IE=xk(gr);let SE;const EE={kernelName:yr,backendName:"wasm",setupFunc:function(e){SE=e.wasm.cwrap(yr,null,["number","array","number","array","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,s=n.dataIdMap.get(a.dataId).id,{reps:o}=r,i=new Array(a.shape.length);for(let e=0;e<i.length;e++)i[e]=a.shape[e]*o[e];const u=new Uint8Array(new Int32Array(a.shape).buffer),l=new Uint8Array(new Int32Array(i).buffer),c=n.makeOutput(i,a.dtype),p=n.dataIdMap.get(c.dataId).id;return SE(s,u,a.shape.length,l,i.length,fk[c.dtype],p),c}};let NE;const CE={kernelName:br,backendName:"wasm",setupFunc:function(e){NE=e.wasm.cwrap(br,null,["number","array","number","number","number","bool","number","number"])},kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r}=e,{k:a,sorted:s}=n,o=t.dataIdMap.get(r.dataId).id,i=new Uint8Array(new Int32Array(r.shape).buffer),u=r.shape.slice();u[u.length-1]=a;const l=t.makeOutput(u,r.dtype),c=t.dataIdMap.get(l.dataId).id,p=t.makeOutput(u,"int32"),h=t.dataIdMap.get(p.dataId).id;return NE(o,i,r.shape.length,fk[r.dtype],a,s,c,h),[l,p]}};let AE;const RE={kernelName:_r,backendName:"wasm",setupFunc:function(e){AE=e.wasm.cwrap(_r,null,["number","number","bool","number","number","number","number","number","number","array","number","array","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{image:a,transforms:s}=n,{interpolation:o,fillMode:i,fillValue:u,outputShape:l}=r,[c,p,h,d]=a.shape,[f,m]=null!=l?l:[p,h],g=[c,f,m,d],y=new Uint8Array(new Int32Array(yt(a.shape)).buffer),b=new Uint8Array(new Int32Array(yt(g)).buffer),_=t.makeOutput(g,a.dtype),x=t.dataIdMap.get(_.dataId).id,v=t.dataIdMap.get(a.dataId).id,w=t.dataIdMap.get(s.dataId).id,T="nearest"===o?1:2;let k;switch(i){case"constant":default:k=1;break;case"reflect":k=2;break;case"wrap":k=3;break;case"nearest":k=4}return AE(v,w,s.shape[0]>1,c,f,m,d,h,p,y,a.shape.length-1,b,g.length-1,T,k,u,x),_}},$E={kernelName:vr,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{value:a}=t;let{axis:s}=r;s<0&&(s+=a.shape.length);const o=a.shape[s],i=a.shape.length,u=new Array(i-1);let l=0;for(let e=0;e<i;e++)e!==s&&(u[l++]=a.shape[e]);const c=new Array(o),p=new Array(i).fill(0),h=a.shape.slice();h[s]=1;for(let e=0;e<c.length;e++)p[s]=e,c[e]=Hk({inputs:{x:a},attrs:{begin:p,size:h},backend:n});return c.map((({dataId:e,dtype:t})=>({dataId:e,dtype:t,shape:u})))}},ME={kernelName:wr,backendName:"wasm",kernelFunc:function(e){const{inputs:{x:t},backend:n}=e,r=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(r).fill(0),r}},FE=[_k,vk,Tk,Ik,Mk,Ok,Lk,Bk,Wk,jk,qk,Xk,Qk,Zk,tI,rI,aI,sI,uI,cI,hI,fI,gI,yI,bI,_I,vI,TI,II,SI,EI,CI,RI,MI,OI,LI,PI,BI,Ek,UI,VI,WI,HI,GI,jI,KI,qI,XI,QI,JI,eS,nS,aS,sS,uS,lS,cS,dS,mS,yS,bS,xS,vS,wS,kS,IS,ES,CS,AS,RS,$S,MS,FS,zk,DS,PS,US,VS,WS,HS,jS,qS,YS,QS,Gk,ZS,eE,nE,aE,uE,lE,cE,pE,hE,dE,mE,yE,bE,_E,xE,vE,TE,kE,IE,EE,CE,RE,Ak,$E,ME];for(const e of FE)Or(e);const OE=Ct();OE.registerFlag("WASM_HAS_SIMD_SUPPORT",(async()=>{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,9,1,7,0,65,0,253,15,26,11]))}catch(e){return!1}})),OE.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",(async()=>{if(OE.get("IS_NODE"))return!1;try{return(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(e){return!1}}));var DE=ep((function(e,t){var n=(()=>{var e="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0;return e=e||"/Users/kodbiro/Projects/GeometryTracking/xzimg-web-sdk/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out",function(t){function n(){return N.buffer!=$&&z(N.buffer),F}function r(){return N.buffer!=$&&z(N.buffer),O}function a(){return N.buffer!=$&&z(N.buffer),D}function s(){return N.buffer!=$&&z(N.buffer),L}var o,i,u,l=void 0!==(t=t||{})?t:{};l.ready=new Promise((function(e,t){o=e,i=t})),void 0!==He&&He.listeners&&(u={uncaughtException:He.listeners("uncaughtException"),unhandledRejection:He.listeners("unhandledRejection")});var c,p,h,d=Object.assign({},l),f=(e,t)=>{throw t},m="object"==typeof window,g="function"==typeof importScripts,y="object"==typeof He&&"object"==typeof He.versions&&"string"==typeof He.versions.node,b=l.ENVIRONMENT_IS_PTHREAD||!1,_="";function x(e){return l.locateFile?l.locateFile(e,_):_+e}if(y){var v=ip,w=ip;let e;_=g?w.dirname(_)+"/":"/Users/kodbiro/Projects/GeometryTracking/xzimg-web-sdk/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out/",c=(e,t)=>(e=ee(e)?new URL(e):w.normalize(e),v.readFileSync(e,t?void 0:"utf8")),h=e=>{var t=c(e,!0);return t.buffer||(t=new Uint8Array(t)),t},p=(e,t,n)=>{e=ee(e)?new URL(e):w.normalize(e),v.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},He.argv.length>1&&He.argv[1].replace(/\\/g,"/"),He.argv.slice(2),He.on("uncaughtException",(function(e){if(!(e instanceof re))throw e})),He.on("unhandledRejection",(function(e){throw e})),f=(e,t)=>{if(K())throw He.exitCode=e,t;!function(e){e instanceof re||E("exiting due to exception: "+e)}(t),He.exit(e)},l.inspect=function(){return"[Emscripten Module object]"};try{e=ip}catch(e){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),e}Zc.Worker=e.Worker}else(m||g)&&(g?_=self.location.href:"undefined"!=typeof document&&document.currentScript&&(_=document.currentScript.src),void 0!==e&&e&&(_=e),_=0!==_.indexOf("blob:")?_.substr(0,_.replace(/[?#].*/,"").lastIndexOf("/")+1):"",y||(c=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},g&&(h=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),p=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)}));y&&"undefined"==typeof performance&&(Zc.performance=ip.performance);var T=console.log.bind(console),k=console.warn.bind(console);y&&(T=e=>v.writeSync(1,e+"\n"),k=e=>v.writeSync(2,e+"\n"));var I,S=l.print||T,E=l.printErr||k;Object.assign(l,d),d=null,l.arguments&&l.arguments,l.thisProgram&&l.thisProgram,l.quit&&(f=l.quit),l.wasmBinary&&(I=l.wasmBinary);var N,C,A=l.noExitRuntime||!0;"object"!=typeof WebAssembly&&J("no native wasm support detected");var R,$,M,F,O,D,L,P=!1,B="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function U(e,t,n){for(var r=t+n,a=t;e[a]&&!(a>=r);)++a;if(a-t>16&&e.buffer&&B)return B.decode(e.buffer instanceof SharedArrayBuffer?e.slice(t,a):e.subarray(t,a));for(var s="";t<a;){var o=e[t++];if(128&o){var i=63&e[t++];if(192!=(224&o)){var u=63&e[t++];if((o=224==(240&o)?(15&o)<<12|i<<6|u:(7&o)<<18|i<<12|u<<6|63&e[t++])<65536)s+=String.fromCharCode(o);else{var l=o-65536;s+=String.fromCharCode(55296|l>>10,56320|1023&l)}}else s+=String.fromCharCode((31&o)<<6|i)}else s+=String.fromCharCode(o)}return s}function z(e){$=e,l.HEAP8=M=new Int8Array(e),l.HEAP16=new Int16Array(e),l.HEAP32=O=new Int32Array(e),l.HEAPU8=F=new Uint8Array(e),l.HEAPU16=new Uint16Array(e),l.HEAPU32=D=new Uint32Array(e),l.HEAPF32=new Float32Array(e),l.HEAPF64=L=new Float64Array(e)}b&&($=l.buffer);var V,W=l.INITIAL_MEMORY||16777216;if(b)N=l.wasmMemory,$=l.buffer;else if(l.wasmMemory)N=l.wasmMemory;else if(!((N=new WebAssembly.Memory({initial:W/65536,maximum:32768,shared:!0})).buffer instanceof SharedArrayBuffer))throw E("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"),y&&E("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");N&&($=N.buffer),W=$.byteLength,z($);var H=[],G=[],j=[];function K(){return A}function q(){b||le(G)}var X,Y=0,Q=null;function J(e){l.onAbort&&l.onAbort(e),E(e="Aborted("+e+")"),P=!0,R=1,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw i(t),t}function Z(e){return e.startsWith("data:application/octet-stream;base64,")}function ee(e){return e.startsWith("file://")}function te(e){try{if(e==X&&I)return new Uint8Array(I);if(h)return h(e);throw"both async and sync fetching of the wasm failed"}catch(e){J(e)}}Z(X="tfjs-backend-wasm-threaded-simd.wasm")||(X=x(X));var ne={};function re(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function ae(e){var t=ue.pthreads[e];t||J(void 0),ue.returnWorkerToPool(t)}function se(e){var t=ue.getNewWorker();if(!t)return 6;ue.runningWorkers.push(t),ue.pthreads[e.pthread_ptr]=t,t.pthread_ptr=e.pthread_ptr;var n={cmd:"run",start_routine:e.startRoutine,arg:e.arg,pthread_ptr:e.pthread_ptr};return t.runPthread=()=>{y&&t.ref(),t.postMessage(n,e.transferList),delete t.runPthread},t.loaded&&t.runPthread(),0}function oe(e){if(b)return ye(1,1,e);R=e,K()||(ue.terminateAllThreads(),l.onExit&&l.onExit(e),P=!0),f(e,new re(e))}var ie=function(e,t){if(R=e,!t&&b)throw ce(e),"unwind";oe(e)},ue={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init:function(){b?ue.initWorker():ue.initMainThread()},initMainThread:function(){for(var e=8;e--;)ue.allocateUnusedWorker()},initWorker:function(){A=!1},setExitStatus:function(e){R=e},terminateAllThreads:function(){for(var e of Object.values(ue.pthreads))ue.returnWorkerToPool(e);for(var e of ue.unusedWorkers)e.terminate();ue.unusedWorkers=[]},returnWorkerToPool:function(e){var t=e.pthread_ptr;delete ue.pthreads[t],ue.unusedWorkers.push(e),ue.runningWorkers.splice(ue.runningWorkers.indexOf(e),1),e.pthread_ptr=0,y&&e.unref(),De(t)},receiveObjectTransfer:function(e){},threadInitTLS:function(){ue.tlsInitFunctions.forEach((e=>e()))},loadWasmModuleToWorker:function(t,n){t.onmessage=e=>{var r,a=e.data,s=a.cmd;if(t.pthread_ptr&&(ue.currentProxiedOperationCallerThread=t.pthread_ptr),a.targetThread&&a.targetThread!=Ce()){var o=ue.pthreads[a.targetThread];return o?o.postMessage(a,a.transferList):E('Internal error! Worker sent a message "'+s+'" to target pthread '+a.targetThread+", but that thread no longer exists!"),void(ue.currentProxiedOperationCallerThread=void 0)}"processProxyingQueue"===s?me(a.queue):"spawnThread"===s?se(a):"cleanupThread"===s?ae(a.thread):"killThread"===s?function(e){var t=ue.pthreads[e];delete ue.pthreads[e],t.terminate(),De(e),ue.runningWorkers.splice(ue.runningWorkers.indexOf(t),1),t.pthread_ptr=0}(a.thread):"cancelThread"===s?(r=a.thread,ue.pthreads[r].postMessage({cmd:"cancel"})):"loaded"===s?(t.loaded=!0,y&&t.unref(),n&&n(t),t.runPthread&&t.runPthread()):"print"===s?S("Thread "+a.threadId+": "+a.text):"printErr"===s?E("Thread "+a.threadId+": "+a.text):"alert"===s?alert("Thread "+a.threadId+": "+a.text):"setimmediate"===a.target?t.postMessage(a):"callHandler"===s?l[a.handler](...a.args):s&&E("worker sent an unknown command "+s),ue.currentProxiedOperationCallerThread=void 0},t.onerror=e=>{throw E("worker sent an error! "+e.filename+":"+e.lineno+": "+e.message),e},y&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){})));var r=[];for(var a of["onExit","onAbort","print","printErr"])l.hasOwnProperty(a)&&r.push(a);t.postMessage({cmd:"load",handlers:r,urlOrBlob:l.mainScriptUrlOrBlob||e,wasmMemory:N,wasmModule:C})},allocateUnusedWorker:function(){var e,t=x("tfjs-backend-wasm-threaded-simd.worker.js");e=new Worker(t),ue.unusedWorkers.push(e)},getNewWorker:function(){return 0==ue.unusedWorkers.length&&(ue.allocateUnusedWorker(),ue.loadWasmModuleToWorker(ue.unusedWorkers[0])),ue.unusedWorkers.pop()}};function le(e){for(;e.length>0;)e.shift()(l)}function ce(e){if(b)return ye(2,0,e);try{ie(e)}catch(e){!function(e){if(e instanceof re||"unwind"==e)return R;f(1,e)}(e)}}l.PThread=ue,l.establishStackSpace=function(){var e=Ce(),t=r()[e+52>>2],n=r()[e+56>>2];Pe(t,t-n),Ue(t)};var pe,he=[];function de(e,t,n,r){return b?ye(3,1,e,t,n,r):fe(e,t,n,r)}function fe(e,t,n,r){if("undefined"==typeof SharedArrayBuffer)return E("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];if(b&&0===a.length)return de(e,t,n,r);var s={startRoutine:n,pthread_ptr:e,arg:r,transferList:a};return b?(s.cmd="spawnThread",postMessage(s,a),0):se(s)}function me(e){Atomics.store(r(),e>>2,1),Ce()&&Oe(e),Atomics.compareExchange(r(),e>>2,1,0)}function ge(e){ge.shown||(ge.shown={}),ge.shown[e]||(ge.shown[e]=1,y&&(e="warning: "+e),E(e))}function ye(e,t){var n=arguments.length-2,r=arguments;return function(e){var t=Be(),n=e();return Ue(t),n}((()=>{for(var a=n,o=ze(8*a),i=o>>3,u=0;u<n;u++){var l=r[2+u];s()[i+u]=l}return Re(e,a,o,t)}))}l.invokeEntryPoint=function(e,t){var n,r,a=((r=he[n=e])||(n>=he.length&&(he.length=n+1),he[n]=r=V.get(n)),r)(t);K()?ue.setExitStatus(a):Le(a)},l.executeNotifiedProxyingQueue=me,pe=y?()=>{var e=He.hrtime();return 1e3*e[0]+e[1]/1e6}:()=>performance.timeOrigin+performance.now();var be=[];function _e(e){try{return N.grow(e-$.byteLength+65535>>>16),z(N.buffer),1}catch(e){}}function xe(e){return b?ye(4,1,e):52}function ve(e,t,n,r,a){return b?ye(5,1,e,t,n,r,a):70}var we=[null,[],[]];function Te(e,t){var n=we[e];0===t||10===t?((1===e?S:E)(U(n,0)),n.length=0):n.push(t)}function ke(e,t,r,s){if(b)return ye(6,1,e,t,r,s);for(var o=0,i=0;i<r;i++){var u=a()[t>>2],l=a()[t+4>>2];t+=8;for(var c=0;c<l;c++)Te(e,n()[u+c]);o+=l}return a()[s>>2]=o,0}function Ie(e){return l["_"+e]}function Se(e,t,r,a,s){var o={string:e=>{var t=0;if(null!=e&&0!==e){var r=1+(e.length<<2);!function(e,t,r){!function(e,t,n,r){if(!(r>0))return 0;for(var a=n+r-1,s=0;s<e.length;++s){var o=e.charCodeAt(s);if(o>=55296&&o<=57343&&(o=65536+((1023&o)<<10)|1023&e.charCodeAt(++s)),o<=127){if(n>=a)break;t[n++]=o}else if(o<=2047){if(n+1>=a)break;t[n++]=192|o>>6,t[n++]=128|63&o}else if(o<=65535){if(n+2>=a)break;t[n++]=224|o>>12,t[n++]=128|o>>6&63,t[n++]=128|63&o}else{if(n+3>=a)break;t[n++]=240|o>>18,t[n++]=128|o>>12&63,t[n++]=128|o>>6&63,t[n++]=128|63&o}}t[n]=0}(e,n(),t,r)}(e,t=ze(r),r)}return t},array:e=>{var t=ze(e.length);return function(e,t){(N.buffer!=$&&z(N.buffer),M).set(e,t)}(e,t),t}},i=Ie(e),u=[],l=0;if(a)for(var c=0;c<a.length;c++){var p=o[r[c]];p?(0===l&&(l=Be()),u[c]=p(a[c])):u[c]=a[c]}return function(e){return 0!==l&&Ue(l),function(e){return"string"===t?(r=e)?U(n(),r,void 0):"":"boolean"===t?Boolean(e):e;var r}(e)}(i.apply(null,u))}ue.init();var Ee=[null,oe,ce,de,xe,ve,ke],Ne={__emscripten_init_main_thread_js:function(e){Ae(e,!g,1,!m),ue.threadInitTLS()},__emscripten_thread_cleanup:function(e){b?postMessage({cmd:"cleanupThread",thread:e}):ae(e)},__pthread_create_js:fe,_emscripten_default_pthread_stack_size:function(){return 65536},_emscripten_get_now_is_monotonic:function(){return!0},_emscripten_notify_task_queue:function(e,t,n,r){if(e==t)setTimeout((()=>me(r)));else if(b)postMessage({targetThread:e,cmd:"processProxyingQueue",queue:r});else{var a=ue.pthreads[e];if(!a)return;a.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},_emscripten_set_offscreencanvas_size:function(e,t,n){return-1},abort:function(){J("")},emscripten_check_blocking_allowed:function(){y||g||ge("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")},emscripten_date_now:function(){return Date.now()},emscripten_get_heap_max:function(){return 2147483648},emscripten_get_now:pe,emscripten_memcpy_big:function(e,t,r){n().copyWithin(e,t,t+r)},emscripten_num_logical_cores:function(){return y?ip.cpus().length:navigator.hardwareConcurrency},emscripten_receive_on_main_thread_js:function(e,t,n){be.length=t;for(var r=n>>3,a=0;a<t;a++)be[a]=s()[r+a];return(e<0?ne[-e-1]:Ee[e]).apply(null,be)},emscripten_resize_heap:function(e){var t=n().length;if((e>>>=0)<=t)return!1;var r=2147483648;if(e>r)return!1;let a=(e,t)=>e+(t-e%t)%t;for(var s=1;s<=4;s*=2){var o=t*(1+.2/s);if(o=Math.min(o,e+100663296),_e(Math.min(r,a(Math.max(e,o),65536))))return!0}return!1},emscripten_unwind_to_js_event_loop:function(){throw"unwind"},exit:ie,fd_close:xe,fd_seek:ve,fd_write:ke,memory:N||l.wasmMemory};!function(){var e={env:Ne,wasi_snapshot_preview1:Ne};function t(e,t){var n,r,a=e.exports;if(l.asm=a,n=l.asm._emscripten_tls_init,ue.tlsInitFunctions.push(n),V=l.asm.__indirect_function_table,r=l.asm.__wasm_call_ctors,G.unshift(r),C=t,!b){var s=ue.unusedWorkers.length;ue.unusedWorkers.forEach((function(e){ue.loadWasmModuleToWorker(e,(function(){--s||function(e){if(Y--,l.monitorRunDependencies&&l.monitorRunDependencies(Y),0==Y&&Q){var t=Q;Q=null,t()}}()}))}))}}function n(e){t(e.instance,e.module)}function r(t){return function(){if(!I&&(m||g)){if("function"==typeof fetch&&!ee(X))return fetch(X,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+X+"'";return e.arrayBuffer()})).catch((function(){return te(X)}));if(p)return new Promise((function(e,t){p(X,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return te(X)}))}().then((function(t){return WebAssembly.instantiate(t,e)})).then((function(e){return e})).then(t,(function(e){E("failed to asynchronously prepare wasm: "+e),J(e)}))}if(b||(Y++,l.monitorRunDependencies&&l.monitorRunDependencies(Y)),l.instantiateWasm)try{return l.instantiateWasm(e,t)}catch(e){E("Module.instantiateWasm callback failed with error: "+e),i(e)}(I||"function"!=typeof WebAssembly.instantiateStreaming||Z(X)||ee(X)||y||"function"!=typeof fetch?r(n):fetch(X,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,e).then(n,(function(e){return E("wasm streaming compile failed: "+e),E("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(i)}(),l.___wasm_call_ctors=function(){return(l.___wasm_call_ctors=l.asm.__wasm_call_ctors).apply(null,arguments)},l._init=function(){return(l._init=l.asm.init).apply(null,arguments)},l._init_with_threads_count=function(){return(l._init_with_threads_count=l.asm.init_with_threads_count).apply(null,arguments)},l._get_threads_count=function(){return(l._get_threads_count=l.asm.get_threads_count).apply(null,arguments)},l._register_tensor=function(){return(l._register_tensor=l.asm.register_tensor).apply(null,arguments)},l._dispose_data=function(){return(l._dispose_data=l.asm.dispose_data).apply(null,arguments)},l._dispose=function(){return(l._dispose=l.asm.dispose).apply(null,arguments)},l._Abs=function(){return(l._Abs=l.asm.Abs).apply(null,arguments)},l._Add=function(){return(l._Add=l.asm.Add).apply(null,arguments)},l._AddN=function(){return(l._AddN=l.asm.AddN).apply(null,arguments)},l._All=function(){return(l._All=l.asm.All).apply(null,arguments)},l._Any=function(){return(l._Any=l.asm.Any).apply(null,arguments)},l._ArgMax=function(){return(l._ArgMax=l.asm.ArgMax).apply(null,arguments)},l._AvgPool=function(){return(l._AvgPool=l.asm.AvgPool).apply(null,arguments)},l._BatchMatMul=function(){return(l._BatchMatMul=l.asm.BatchMatMul).apply(null,arguments)},l._Ceil=function(){return(l._Ceil=l.asm.Ceil).apply(null,arguments)},l._ClipByValue=function(){return(l._ClipByValue=l.asm.ClipByValue).apply(null,arguments)},l._Conv2D=function(){return(l._Conv2D=l.asm.Conv2D).apply(null,arguments)},l._Conv2DBackpropInput=function(){return(l._Conv2DBackpropInput=l.asm.Conv2DBackpropInput).apply(null,arguments)},l._Cos=function(){return(l._Cos=l.asm.Cos).apply(null,arguments)},l._Cosh=function(){return(l._Cosh=l.asm.Cosh).apply(null,arguments)},l._CropAndResize=function(){return(l._CropAndResize=l.asm.CropAndResize).apply(null,arguments)},l._Cumprod=function(){return(l._Cumprod=l.asm.Cumprod).apply(null,arguments)},l._Cumsum=function(){return(l._Cumsum=l.asm.Cumsum).apply(null,arguments)},l._DepthToSpace=function(){return(l._DepthToSpace=l.asm.DepthToSpace).apply(null,arguments)},l._DepthwiseConv2dNative=function(){return(l._DepthwiseConv2dNative=l.asm.DepthwiseConv2dNative).apply(null,arguments)},l._Elu=function(){return(l._Elu=l.asm.Elu).apply(null,arguments)},l._Equal=function(){return(l._Equal=l.asm.Equal).apply(null,arguments)},l._Exp=function(){return(l._Exp=l.asm.Exp).apply(null,arguments)},l._FlipLeftRight=function(){return(l._FlipLeftRight=l.asm.FlipLeftRight).apply(null,arguments)},l._Floor=function(){return(l._Floor=l.asm.Floor).apply(null,arguments)},l._FloorDiv=function(){return(l._FloorDiv=l.asm.FloorDiv).apply(null,arguments)},l._FusedBatchNorm=function(){return(l._FusedBatchNorm=l.asm.FusedBatchNorm).apply(null,arguments)},l._FusedConv2D=function(){return(l._FusedConv2D=l.asm.FusedConv2D).apply(null,arguments)},l._FusedDepthwiseConv2D=function(){return(l._FusedDepthwiseConv2D=l.asm.FusedDepthwiseConv2D).apply(null,arguments)},l._Gather=function(){return(l._Gather=l.asm.Gather).apply(null,arguments)},l._GatherNd=function(){return(l._GatherNd=l.asm.GatherNd).apply(null,arguments)},l._Greater=function(){return(l._Greater=l.asm.Greater).apply(null,arguments)},l._GreaterEqual=function(){return(l._GreaterEqual=l.asm.GreaterEqual).apply(null,arguments)},l._IsNan=function(){return(l._IsNan=l.asm.IsNan).apply(null,arguments)},l._LeakyRelu=function(){return(l._LeakyRelu=l.asm.LeakyRelu).apply(null,arguments)},l._Less=function(){return(l._Less=l.asm.Less).apply(null,arguments)},l._LessEqual=function(){return(l._LessEqual=l.asm.LessEqual).apply(null,arguments)},l._Log=function(){return(l._Log=l.asm.Log).apply(null,arguments)},l._LogicalAnd=function(){return(l._LogicalAnd=l.asm.LogicalAnd).apply(null,arguments)},l._LogicalNot=function(){return(l._LogicalNot=l.asm.LogicalNot).apply(null,arguments)},l._LogicalOr=function(){return(l._LogicalOr=l.asm.LogicalOr).apply(null,arguments)},l._LogicalXor=function(){return(l._LogicalXor=l.asm.LogicalXor).apply(null,arguments)},l._Max=function(){return(l._Max=l.asm.Max).apply(null,arguments)},l._MaxPool=function(){return(l._MaxPool=l.asm.MaxPool).apply(null,arguments)},l._Maximum=function(){return(l._Maximum=l.asm.Maximum).apply(null,arguments)},l._Mean=function(){return(l._Mean=l.asm.Mean).apply(null,arguments)},l._Min=function(){return(l._Min=l.asm.Min).apply(null,arguments)},l._Minimum=function(){return(l._Minimum=l.asm.Minimum).apply(null,arguments)},l._MirrorPad=function(){return(l._MirrorPad=l.asm.MirrorPad).apply(null,arguments)},l._Multiply=function(){return(l._Multiply=l.asm.Multiply).apply(null,arguments)},l._Neg=function(){return(l._Neg=l.asm.Neg).apply(null,arguments)},l._NonMaxSuppressionV3=function(){return(l._NonMaxSuppressionV3=l.asm.NonMaxSuppressionV3).apply(null,arguments)},l._NonMaxSuppressionV4=function(){return(l._NonMaxSuppressionV4=l.asm.NonMaxSuppressionV4).apply(null,arguments)},l._NonMaxSuppressionV5=function(){return(l._NonMaxSuppressionV5=l.asm.NonMaxSuppressionV5).apply(null,arguments)},l._NotEqual=function(){return(l._NotEqual=l.asm.NotEqual).apply(null,arguments)},l._OneHot=function(){return(l._OneHot=l.asm.OneHot).apply(null,arguments)},l._PadV2=function(){return(l._PadV2=l.asm.PadV2).apply(null,arguments)},l._Pow=function(){return(l._Pow=l.asm.Pow).apply(null,arguments)},l._Prelu=function(){return(l._Prelu=l.asm.Prelu).apply(null,arguments)},l._Prod=function(){return(l._Prod=l.asm.Prod).apply(null,arguments)},l._RealDiv=function(){return(l._RealDiv=l.asm.RealDiv).apply(null,arguments)},l._Reciprocal=function(){return(l._Reciprocal=l.asm.Reciprocal).apply(null,arguments)},l._Relu=function(){return(l._Relu=l.asm.Relu).apply(null,arguments)},l._Relu6=function(){return(l._Relu6=l.asm.Relu6).apply(null,arguments)},l._ResizeBilinear=function(){return(l._ResizeBilinear=l.asm.ResizeBilinear).apply(null,arguments)},l._ResizeNearestNeighbor=function(){return(l._ResizeNearestNeighbor=l.asm.ResizeNearestNeighbor).apply(null,arguments)},l._Reverse=function(){return(l._Reverse=l.asm.Reverse).apply(null,arguments)},l._RotateWithOffset=function(){return(l._RotateWithOffset=l.asm.RotateWithOffset).apply(null,arguments)},l._Round=function(){return(l._Round=l.asm.Round).apply(null,arguments)},l._Rsqrt=function(){return(l._Rsqrt=l.asm.Rsqrt).apply(null,arguments)},l._ScatterNd=function(){return(l._ScatterNd=l.asm.ScatterNd).apply(null,arguments)},l._SelectV2=function(){return(l._SelectV2=l.asm.SelectV2).apply(null,arguments)},l._Sigmoid=function(){return(l._Sigmoid=l.asm.Sigmoid).apply(null,arguments)},l._Sin=function(){return(l._Sin=l.asm.Sin).apply(null,arguments)},l._Softmax=function(){return(l._Softmax=l.asm.Softmax).apply(null,arguments)},l._SparseFillEmptyRows=function(){return(l._SparseFillEmptyRows=l.asm.SparseFillEmptyRows).apply(null,arguments)},l._SparseReshape=function(){return(l._SparseReshape=l.asm.SparseReshape).apply(null,arguments)},l._SparseSegmentReduction=function(){return(l._SparseSegmentReduction=l.asm.SparseSegmentReduction).apply(null,arguments)},l._Sqrt=function(){return(l._Sqrt=l.asm.Sqrt).apply(null,arguments)},l._Square=function(){return(l._Square=l.asm.Square).apply(null,arguments)},l._SquaredDifference=function(){return(l._SquaredDifference=l.asm.SquaredDifference).apply(null,arguments)},l._Step=function(){return(l._Step=l.asm.Step).apply(null,arguments)},l._StridedSlice=function(){return(l._StridedSlice=l.asm.StridedSlice).apply(null,arguments)},l._Sub=function(){return(l._Sub=l.asm.Sub).apply(null,arguments)},l._Sum=function(){return(l._Sum=l.asm.Sum).apply(null,arguments)},l._Tan=function(){return(l._Tan=l.asm.Tan).apply(null,arguments)},l._Tanh=function(){return(l._Tanh=l.asm.Tanh).apply(null,arguments)},l._Tile=function(){return(l._Tile=l.asm.Tile).apply(null,arguments)},l._TopK=function(){return(l._TopK=l.asm.TopK).apply(null,arguments)},l._Transform=function(){return(l._Transform=l.asm.Transform).apply(null,arguments)},l._Transpose=function(){return(l._Transpose=l.asm.Transpose).apply(null,arguments)},l.__FusedMatMul=function(){return(l.__FusedMatMul=l.asm._FusedMatMul).apply(null,arguments)},l._malloc=function(){return(l._malloc=l.asm.malloc).apply(null,arguments)},l._free=function(){return(l._free=l.asm.free).apply(null,arguments)},l.__emscripten_tls_init=function(){return(l.__emscripten_tls_init=l.asm._emscripten_tls_init).apply(null,arguments)};var Ce=l._pthread_self=function(){return(Ce=l._pthread_self=l.asm.pthread_self).apply(null,arguments)};l.___errno_location=function(){return(l.___errno_location=l.asm.__errno_location).apply(null,arguments)};var Ae=l.__emscripten_thread_init=function(){return(Ae=l.__emscripten_thread_init=l.asm._emscripten_thread_init).apply(null,arguments)};l.__emscripten_thread_crashed=function(){return(l.__emscripten_thread_crashed=l.asm._emscripten_thread_crashed).apply(null,arguments)},l._emscripten_main_thread_process_queued_calls=function(){return(l._emscripten_main_thread_process_queued_calls=l.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},l._emscripten_main_browser_thread_id=function(){return(l._emscripten_main_browser_thread_id=l.asm.emscripten_main_browser_thread_id).apply(null,arguments)};var Re=l._emscripten_run_in_main_runtime_thread_js=function(){return(Re=l._emscripten_run_in_main_runtime_thread_js=l.asm.emscripten_run_in_main_runtime_thread_js).apply(null,arguments)};l._emscripten_dispatch_to_thread_=function(){return(l._emscripten_dispatch_to_thread_=l.asm.emscripten_dispatch_to_thread_).apply(null,arguments)};var $e,Me,Fe,Oe=l.__emscripten_proxy_execute_task_queue=function(){return(Oe=l.__emscripten_proxy_execute_task_queue=l.asm._emscripten_proxy_execute_task_queue).apply(null,arguments)},De=l.__emscripten_thread_free_data=function(){return(De=l.__emscripten_thread_free_data=l.asm._emscripten_thread_free_data).apply(null,arguments)},Le=l.__emscripten_thread_exit=function(){return(Le=l.__emscripten_thread_exit=l.asm._emscripten_thread_exit).apply(null,arguments)},Pe=l._emscripten_stack_set_limits=function(){return(Pe=l._emscripten_stack_set_limits=l.asm.emscripten_stack_set_limits).apply(null,arguments)},Be=l.stackSave=function(){return(Be=l.stackSave=l.asm.stackSave).apply(null,arguments)},Ue=l.stackRestore=function(){return(Ue=l.stackRestore=l.asm.stackRestore).apply(null,arguments)},ze=l.stackAlloc=function(){return(ze=l.stackAlloc=l.asm.stackAlloc).apply(null,arguments)};function Ve(e){if(!(Y>0)){if(b)return o(l),q(),void startWorker(l);!function(){if(l.preRun)for("function"==typeof l.preRun&&(l.preRun=[l.preRun]);l.preRun.length;)e=l.preRun.shift(),H.unshift(e);var e;le(H)}(),Y>0||(l.setStatus?(l.setStatus("Running..."),setTimeout((function(){setTimeout((function(){l.setStatus("")}),1),t()}),1)):t())}function t(){$e||($e=!0,l.calledRun=!0,P||(q(),o(l),l.onRuntimeInitialized&&l.onRuntimeInitialized(),function(){if(!b){if(l.postRun)for("function"==typeof l.postRun&&(l.postRun=[l.postRun]);l.postRun.length;)e=l.postRun.shift(),j.unshift(e);var e;le(j)}}()))}}if(l.dynCall_iijjiiii=function(){return(l.dynCall_iijjiiii=l.asm.dynCall_iijjiiii).apply(null,arguments)},l.dynCall_jiji=function(){return(l.dynCall_jiji=l.asm.dynCall_jiji).apply(null,arguments)},l.keepRuntimeAlive=K,l.wasmMemory=N,l.cwrap=function(e,t,n,r){var a=(n=n||[]).every((e=>"number"===e||"boolean"===e));return"string"!==t&&a&&!r?Ie(e):function(){return Se(e,t,n,arguments)}},l.ExitStatus=re,l.PThread=ue,Q=function e(){$e||Ve(),$e||(Q=e)},l.preInit)for("function"==typeof l.preInit&&(l.preInit=[l.preInit]);l.preInit.length>0;)l.preInit.pop()();if(Ve(),u&&(Me={uncaughtException:He.listeners("uncaughtException").filter((function(e){return!u.uncaughtException.indexOf(e)>-1})),unhandledRejection:He.listeners("unhandledRejection").filter((function(e){return!u.unhandledRejection.indexOf(e)>-1}))}),"undefined"!=typeof WasmBackendModule)Fe=WasmBackendModule;else{if(void 0===t)throw new Error("Could not find wasm module in post.js");Fe=t}if(Me){var We=Fe._dispose;Fe._dispose=function(){We(),Me.uncaughtException.forEach((function(e){He.removeListener("uncaughtException",e)})),Me.unhandledRejection.forEach((function(e){He.removeListener("unhandledRejection",e)}))}}return t.ready}})();e.exports=n})),LE=e({__proto__:null,default:DE},[DE]),PE=ep((function(e,t){var n=(()=>{var e="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0;return e=e||"/Users/kodbiro/Projects/GeometryTracking/xzimg-web-sdk/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out",function(t){var n,r,a,s=void 0!==(t=t||{})?t:{};s.ready=new Promise((function(e,t){n=e,r=t})),void 0!==He&&He.listeners&&(a={uncaughtException:He.listeners("uncaughtException"),unhandledRejection:He.listeners("unhandledRejection")});var o,i,u,l=Object.assign({},s),c="object"==typeof window,p="function"==typeof importScripts,h="object"==typeof He&&"object"==typeof He.versions&&"string"==typeof He.versions.node,d="";if(h){var f=ip,m=ip;d=p?m.dirname(d)+"/":"/Users/kodbiro/Projects/GeometryTracking/xzimg-web-sdk/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out/",o=(e,t)=>(e=L(e)?new URL(e):m.normalize(e),f.readFileSync(e,t?void 0:"utf8")),u=e=>{var t=o(e,!0);return t.buffer||(t=new Uint8Array(t)),t},i=(e,t,n)=>{e=L(e)?new URL(e):m.normalize(e),f.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},He.argv.length>1&&He.argv[1].replace(/\\/g,"/"),He.argv.slice(2),He.on("uncaughtException",(function(e){if(!(e instanceof B))throw e})),He.on("unhandledRejection",(function(e){throw e})),s.inspect=function(){return"[Emscripten Module object]"}}else(c||p)&&(p?d=self.location.href:"undefined"!=typeof document&&document.currentScript&&(d=document.currentScript.src),e&&(d=e),d=0!==d.indexOf("blob:")?d.substr(0,d.replace(/[?#].*/,"").lastIndexOf("/")+1):"",o=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},p&&(u=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),i=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)});var g,y,b=s.print||console.log.bind(console),_=s.printErr||console.warn.bind(console);Object.assign(s,l),l=null,s.arguments&&s.arguments,s.thisProgram&&s.thisProgram,s.quit&&s.quit,s.wasmBinary&&(g=s.wasmBinary),s.noExitRuntime,"object"!=typeof WebAssembly&&O("no native wasm support detected");var x,v,w,T,k=!1,I="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function S(e,t,n){for(var r=t+n,a=t;e[a]&&!(a>=r);)++a;if(a-t>16&&e.buffer&&I)return I.decode(e.subarray(t,a));for(var s="";t<a;){var o=e[t++];if(128&o){var i=63&e[t++];if(192!=(224&o)){var u=63&e[t++];if((o=224==(240&o)?(15&o)<<12|i<<6|u:(7&o)<<18|i<<12|u<<6|63&e[t++])<65536)s+=String.fromCharCode(o);else{var l=o-65536;s+=String.fromCharCode(55296|l>>10,56320|1023&l)}}else s+=String.fromCharCode((31&o)<<6|i)}else s+=String.fromCharCode(o)}return s}function E(e){x=e,s.HEAP8=v=new Int8Array(e),s.HEAP16=new Int16Array(e),s.HEAP32=new Int32Array(e),s.HEAPU8=w=new Uint8Array(e),s.HEAPU16=new Uint16Array(e),s.HEAPU32=T=new Uint32Array(e),s.HEAPF32=new Float32Array(e),s.HEAPF64=new Float64Array(e)}s.INITIAL_MEMORY;var N,C,A=[],R=[],$=[],M=0,F=null;function O(e){s.onAbort&&s.onAbort(e),_(e="Aborted("+e+")"),k=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw r(t),t}function D(e){return e.startsWith("data:application/octet-stream;base64,")}function L(e){return e.startsWith("file://")}function P(e){try{if(e==N&&g)return new Uint8Array(g);if(u)return u(e);throw"both async and sync fetching of the wasm failed"}catch(e){O(e)}}function B(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function U(e){for(;e.length>0;)e.shift()(s)}function z(e){try{return y.grow(e-x.byteLength+65535>>>16),E(y.buffer),1}catch(e){}}D(N="tfjs-backend-wasm.wasm")||(C=N,N=s.locateFile?s.locateFile(C,d):d+C);var V=[null,[],[]];function W(e,t){var n=V[e];0===t||10===t?((1===e?b:_)(S(n,0)),n.length=0):n.push(t)}function H(e){return s["_"+e]}var G={abort:function(){O("")},emscripten_get_heap_max:function(){return 2147483648},emscripten_memcpy_big:function(e,t,n){w.copyWithin(e,t,t+n)},emscripten_resize_heap:function(e){var t=w.length,n=2147483648;if((e>>>=0)>n)return!1;let r=(e,t)=>e+(t-e%t)%t;for(var a=1;a<=4;a*=2){var s=t*(1+.2/a);if(s=Math.min(s,e+100663296),z(Math.min(n,r(Math.max(e,s),65536))))return!0}return!1},fd_close:function(e){return 52},fd_seek:function(e,t,n,r,a){return 70},fd_write:function(e,t,n,r){for(var a=0,s=0;s<n;s++){var o=T[t>>2],i=T[t+4>>2];t+=8;for(var u=0;u<i;u++)W(e,w[o+u]);a+=i}return T[r>>2]=a,0}};!function(){var e={env:G,wasi_snapshot_preview1:G};function t(e,t){var n,r=e.exports;s.asm=r,E((y=s.asm.memory).buffer),s.asm.__indirect_function_table,n=s.asm.__wasm_call_ctors,R.unshift(n),function(e){if(M--,s.monitorRunDependencies&&s.monitorRunDependencies(M),0==M&&F){var t=F;F=null,t()}}()}function n(e){t(e.instance)}function a(t){return function(){if(!g&&(c||p)){if("function"==typeof fetch&&!L(N))return fetch(N,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+N+"'";return e.arrayBuffer()})).catch((function(){return P(N)}));if(i)return new Promise((function(e,t){i(N,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return P(N)}))}().then((function(t){return WebAssembly.instantiate(t,e)})).then((function(e){return e})).then(t,(function(e){_("failed to asynchronously prepare wasm: "+e),O(e)}))}if(M++,s.monitorRunDependencies&&s.monitorRunDependencies(M),s.instantiateWasm)try{return s.instantiateWasm(e,t)}catch(e){_("Module.instantiateWasm callback failed with error: "+e),r(e)}(g||"function"!=typeof WebAssembly.instantiateStreaming||D(N)||L(N)||h||"function"!=typeof fetch?a(n):fetch(N,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,e).then(n,(function(e){return _("wasm streaming compile failed: "+e),_("falling back to ArrayBuffer instantiation"),a(n)}))}))).catch(r)}(),s.___wasm_call_ctors=function(){return(s.___wasm_call_ctors=s.asm.__wasm_call_ctors).apply(null,arguments)},s._init=function(){return(s._init=s.asm.init).apply(null,arguments)},s._init_with_threads_count=function(){return(s._init_with_threads_count=s.asm.init_with_threads_count).apply(null,arguments)},s._get_threads_count=function(){return(s._get_threads_count=s.asm.get_threads_count).apply(null,arguments)},s._register_tensor=function(){return(s._register_tensor=s.asm.register_tensor).apply(null,arguments)},s._dispose_data=function(){return(s._dispose_data=s.asm.dispose_data).apply(null,arguments)},s._dispose=function(){return(s._dispose=s.asm.dispose).apply(null,arguments)},s._Abs=function(){return(s._Abs=s.asm.Abs).apply(null,arguments)},s._Add=function(){return(s._Add=s.asm.Add).apply(null,arguments)},s._AddN=function(){return(s._AddN=s.asm.AddN).apply(null,arguments)},s._All=function(){return(s._All=s.asm.All).apply(null,arguments)},s._Any=function(){return(s._Any=s.asm.Any).apply(null,arguments)},s._ArgMax=function(){return(s._ArgMax=s.asm.ArgMax).apply(null,arguments)},s._AvgPool=function(){return(s._AvgPool=s.asm.AvgPool).apply(null,arguments)},s._BatchMatMul=function(){return(s._BatchMatMul=s.asm.BatchMatMul).apply(null,arguments)},s._Ceil=function(){return(s._Ceil=s.asm.Ceil).apply(null,arguments)},s._ClipByValue=function(){return(s._ClipByValue=s.asm.ClipByValue).apply(null,arguments)},s._Conv2D=function(){return(s._Conv2D=s.asm.Conv2D).apply(null,arguments)},s._Conv2DBackpropInput=function(){return(s._Conv2DBackpropInput=s.asm.Conv2DBackpropInput).apply(null,arguments)},s._Cos=function(){return(s._Cos=s.asm.Cos).apply(null,arguments)},s._Cosh=function(){return(s._Cosh=s.asm.Cosh).apply(null,arguments)},s._CropAndResize=function(){return(s._CropAndResize=s.asm.CropAndResize).apply(null,arguments)},s._Cumprod=function(){return(s._Cumprod=s.asm.Cumprod).apply(null,arguments)},s._Cumsum=function(){return(s._Cumsum=s.asm.Cumsum).apply(null,arguments)},s._DepthToSpace=function(){return(s._DepthToSpace=s.asm.DepthToSpace).apply(null,arguments)},s._DepthwiseConv2dNative=function(){return(s._DepthwiseConv2dNative=s.asm.DepthwiseConv2dNative).apply(null,arguments)},s._Elu=function(){return(s._Elu=s.asm.Elu).apply(null,arguments)},s._Equal=function(){return(s._Equal=s.asm.Equal).apply(null,arguments)},s._Exp=function(){return(s._Exp=s.asm.Exp).apply(null,arguments)},s._FlipLeftRight=function(){return(s._FlipLeftRight=s.asm.FlipLeftRight).apply(null,arguments)},s._Floor=function(){return(s._Floor=s.asm.Floor).apply(null,arguments)},s._FloorDiv=function(){return(s._FloorDiv=s.asm.FloorDiv).apply(null,arguments)},s._FusedBatchNorm=function(){return(s._FusedBatchNorm=s.asm.FusedBatchNorm).apply(null,arguments)},s._FusedConv2D=function(){return(s._FusedConv2D=s.asm.FusedConv2D).apply(null,arguments)},s._FusedDepthwiseConv2D=function(){return(s._FusedDepthwiseConv2D=s.asm.FusedDepthwiseConv2D).apply(null,arguments)},s._Gather=function(){return(s._Gather=s.asm.Gather).apply(null,arguments)},s._GatherNd=function(){return(s._GatherNd=s.asm.GatherNd).apply(null,arguments)},s._Greater=function(){return(s._Greater=s.asm.Greater).apply(null,arguments)},s._GreaterEqual=function(){return(s._GreaterEqual=s.asm.GreaterEqual).apply(null,arguments)},s._IsNan=function(){return(s._IsNan=s.asm.IsNan).apply(null,arguments)},s._LeakyRelu=function(){return(s._LeakyRelu=s.asm.LeakyRelu).apply(null,arguments)},s._Less=function(){return(s._Less=s.asm.Less).apply(null,arguments)},s._LessEqual=function(){return(s._LessEqual=s.asm.LessEqual).apply(null,arguments)},s._Log=function(){return(s._Log=s.asm.Log).apply(null,arguments)},s._LogicalAnd=function(){return(s._LogicalAnd=s.asm.LogicalAnd).apply(null,arguments)},s._LogicalNot=function(){return(s._LogicalNot=s.asm.LogicalNot).apply(null,arguments)},s._LogicalOr=function(){return(s._LogicalOr=s.asm.LogicalOr).apply(null,arguments)},s._LogicalXor=function(){return(s._LogicalXor=s.asm.LogicalXor).apply(null,arguments)},s._Max=function(){return(s._Max=s.asm.Max).apply(null,arguments)},s._MaxPool=function(){return(s._MaxPool=s.asm.MaxPool).apply(null,arguments)},s._Maximum=function(){return(s._Maximum=s.asm.Maximum).apply(null,arguments)},s._Mean=function(){return(s._Mean=s.asm.Mean).apply(null,arguments)},s._Min=function(){return(s._Min=s.asm.Min).apply(null,arguments)},s._Minimum=function(){return(s._Minimum=s.asm.Minimum).apply(null,arguments)},s._MirrorPad=function(){return(s._MirrorPad=s.asm.MirrorPad).apply(null,arguments)},s._Multiply=function(){return(s._Multiply=s.asm.Multiply).apply(null,arguments)},s._Neg=function(){return(s._Neg=s.asm.Neg).apply(null,arguments)},s._NonMaxSuppressionV3=function(){return(s._NonMaxSuppressionV3=s.asm.NonMaxSuppressionV3).apply(null,arguments)},s._NonMaxSuppressionV4=function(){return(s._NonMaxSuppressionV4=s.asm.NonMaxSuppressionV4).apply(null,arguments)},s._NonMaxSuppressionV5=function(){return(s._NonMaxSuppressionV5=s.asm.NonMaxSuppressionV5).apply(null,arguments)},s._NotEqual=function(){return(s._NotEqual=s.asm.NotEqual).apply(null,arguments)},s._OneHot=function(){return(s._OneHot=s.asm.OneHot).apply(null,arguments)},s._PadV2=function(){return(s._PadV2=s.asm.PadV2).apply(null,arguments)},s._Pow=function(){return(s._Pow=s.asm.Pow).apply(null,arguments)},s._Prelu=function(){return(s._Prelu=s.asm.Prelu).apply(null,arguments)},s._Prod=function(){return(s._Prod=s.asm.Prod).apply(null,arguments)},s._RealDiv=function(){return(s._RealDiv=s.asm.RealDiv).apply(null,arguments)},s._Reciprocal=function(){return(s._Reciprocal=s.asm.Reciprocal).apply(null,arguments)},s._Relu=function(){return(s._Relu=s.asm.Relu).apply(null,arguments)},s._Relu6=function(){return(s._Relu6=s.asm.Relu6).apply(null,arguments)},s._ResizeBilinear=function(){return(s._ResizeBilinear=s.asm.ResizeBilinear).apply(null,arguments)},s._ResizeNearestNeighbor=function(){return(s._ResizeNearestNeighbor=s.asm.ResizeNearestNeighbor).apply(null,arguments)},s._Reverse=function(){return(s._Reverse=s.asm.Reverse).apply(null,arguments)},s._RotateWithOffset=function(){return(s._RotateWithOffset=s.asm.RotateWithOffset).apply(null,arguments)},s._Round=function(){return(s._Round=s.asm.Round).apply(null,arguments)},s._Rsqrt=function(){return(s._Rsqrt=s.asm.Rsqrt).apply(null,arguments)},s._ScatterNd=function(){return(s._ScatterNd=s.asm.ScatterNd).apply(null,arguments)},s._SelectV2=function(){return(s._SelectV2=s.asm.SelectV2).apply(null,arguments)},s._Sigmoid=function(){return(s._Sigmoid=s.asm.Sigmoid).apply(null,arguments)},s._Sin=function(){return(s._Sin=s.asm.Sin).apply(null,arguments)},s._Softmax=function(){return(s._Softmax=s.asm.Softmax).apply(null,arguments)},s._SparseFillEmptyRows=function(){return(s._SparseFillEmptyRows=s.asm.SparseFillEmptyRows).apply(null,arguments)},s._SparseReshape=function(){return(s._SparseReshape=s.asm.SparseReshape).apply(null,arguments)},s._SparseSegmentReduction=function(){return(s._SparseSegmentReduction=s.asm.SparseSegmentReduction).apply(null,arguments)},s._Sqrt=function(){return(s._Sqrt=s.asm.Sqrt).apply(null,arguments)},s._Square=function(){return(s._Square=s.asm.Square).apply(null,arguments)},s._SquaredDifference=function(){return(s._SquaredDifference=s.asm.SquaredDifference).apply(null,arguments)},s._Step=function(){return(s._Step=s.asm.Step).apply(null,arguments)},s._StridedSlice=function(){return(s._StridedSlice=s.asm.StridedSlice).apply(null,arguments)},s._Sub=function(){return(s._Sub=s.asm.Sub).apply(null,arguments)},s._Sum=function(){return(s._Sum=s.asm.Sum).apply(null,arguments)},s._Tan=function(){return(s._Tan=s.asm.Tan).apply(null,arguments)},s._Tanh=function(){return(s._Tanh=s.asm.Tanh).apply(null,arguments)},s._Tile=function(){return(s._Tile=s.asm.Tile).apply(null,arguments)},s._TopK=function(){return(s._TopK=s.asm.TopK).apply(null,arguments)},s._Transform=function(){return(s._Transform=s.asm.Transform).apply(null,arguments)},s._Transpose=function(){return(s._Transpose=s.asm.Transpose).apply(null,arguments)},s.__FusedMatMul=function(){return(s.__FusedMatMul=s.asm._FusedMatMul).apply(null,arguments)},s._malloc=function(){return(s._malloc=s.asm.malloc).apply(null,arguments)},s._free=function(){return(s._free=s.asm.free).apply(null,arguments)},s.___errno_location=function(){return(s.___errno_location=s.asm.__errno_location).apply(null,arguments)};var j,K,q,X=s.stackSave=function(){return(X=s.stackSave=s.asm.stackSave).apply(null,arguments)},Y=s.stackRestore=function(){return(Y=s.stackRestore=s.asm.stackRestore).apply(null,arguments)},Q=s.stackAlloc=function(){return(Q=s.stackAlloc=s.asm.stackAlloc).apply(null,arguments)};function J(e){function t(){j||(j=!0,s.calledRun=!0,k||(U(R),n(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),function(){if(s.postRun)for("function"==typeof s.postRun&&(s.postRun=[s.postRun]);s.postRun.length;)e=s.postRun.shift(),$.unshift(e);var e;U($)}()))}M>0||(function(){if(s.preRun)for("function"==typeof s.preRun&&(s.preRun=[s.preRun]);s.preRun.length;)e=s.preRun.shift(),A.unshift(e);var e;U(A)}(),M>0||(s.setStatus?(s.setStatus("Running..."),setTimeout((function(){setTimeout((function(){s.setStatus("")}),1),t()}),1)):t()))}if(s.dynCall_iijjiiii=function(){return(s.dynCall_iijjiiii=s.asm.dynCall_iijjiiii).apply(null,arguments)},s.dynCall_jiji=function(){return(s.dynCall_jiji=s.asm.dynCall_jiji).apply(null,arguments)},s.cwrap=function(e,t,n,r){var a=(n=n||[]).every((e=>"number"===e||"boolean"===e));return"string"!==t&&a&&!r?H(e):function(){return function(e,t,n,r,a){var s={string:e=>{var t=0;if(null!=e&&0!==e){var n=1+(e.length<<2);!function(e,t,n){!function(e,t,n,r){if(!(r>0))return 0;for(var a=n+r-1,s=0;s<e.length;++s){var o=e.charCodeAt(s);if(o>=55296&&o<=57343&&(o=65536+((1023&o)<<10)|1023&e.charCodeAt(++s)),o<=127){if(n>=a)break;t[n++]=o}else if(o<=2047){if(n+1>=a)break;t[n++]=192|o>>6,t[n++]=128|63&o}else if(o<=65535){if(n+2>=a)break;t[n++]=224|o>>12,t[n++]=128|o>>6&63,t[n++]=128|63&o}else{if(n+3>=a)break;t[n++]=240|o>>18,t[n++]=128|o>>12&63,t[n++]=128|o>>6&63,t[n++]=128|63&o}}t[n]=0}(e,w,t,n)}(e,t=Q(n),n)}return t},array:e=>{var t=Q(e.length);return function(e,t){v.set(e,t)}(e,t),t}},o=H(e),i=[],u=0;if(r)for(var l=0;l<r.length;l++){var c=s[n[l]];c?(0===u&&(u=X()),i[l]=c(r[l])):i[l]=r[l]}return function(e){return 0!==u&&Y(u),function(e){return"string"===t?(n=e)?S(w,n,void 0):"":"boolean"===t?Boolean(e):e;var n}(e)}(o.apply(null,i))}(e,t,n,arguments)}},F=function e(){j||J(),j||(F=e)},s.preInit)for("function"==typeof s.preInit&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();if(J(),a&&(K={uncaughtException:He.listeners("uncaughtException").filter((function(e){return!a.uncaughtException.indexOf(e)>-1})),unhandledRejection:He.listeners("unhandledRejection").filter((function(e){return!a.unhandledRejection.indexOf(e)>-1}))}),void 0!==t)q=t;else{if("undefined"==typeof WasmBackendModuleThreadedSimd)throw new Error("Could not find wasm module in post.js");q=WasmBackendModuleThreadedSimd}if(K){var Z=q._dispose;q._dispose=function(){Z(),K.uncaughtException.forEach((function(e){He.removeListener("uncaughtException",e)})),K.unhandledRejection.forEach((function(e){He.removeListener("unhandledRejection",e)}))}}return t.ready}})();e.exports=n}));const BE=DE||LE,UE=PE||e({__proto__:null,default:PE},[PE]);class zE extends je{constructor(e){super(),this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(XE),YE=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new Ge(this,vi())}write(e,t,n){const r={id:this.dataIdNextNumber++};return this.move(r,e,t,n,1),r}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){const t=Ta();return e(),{kernelMs:Ta()-t}}move(e,t,n,r,a){const s=this.dataIdNextNumber++;if("string"===r){const o=t;return void this.dataIdMap.set(e,{id:s,stringBytes:o,shape:n,dtype:r,memoryOffset:null,refCount:a})}const o=et(n),i=o*ht(r),u=this.wasm._malloc(i);this.dataIdMap.set(e,{id:s,memoryOffset:u,shape:n,dtype:r,refCount:a}),this.wasm.tfjs.registerTensor(s,o,u),null!=t&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,i),u)}async read(e){return this.readSync(e)}readSync(e,t,n){const{memoryOffset:r,dtype:a,shape:s,stringBytes:o}=this.dataIdMap.get(e);if("string"===a)return null!=t&&0!==t||!(null==n||n>=o.length)?o.slice(t,n):o;t=t||0,n=n||et(s);const i=ht(a);return function(e,t){switch(t){case"float32":return new Float32Array(e);case"int32":return new Int32Array(e);case"bool":return new Uint8Array(e);default:throw new Error(`Unknown dtype ${t}`)}}(this.wasm.HEAPU8.slice(r+t*i,r+n*i).buffer,a)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){const n=this.dataIdMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;this.wasm._free(n.memoryOffset),this.wasm.tfjs.disposeData(n.id),this.dataIdMap.delete(e)}return!0}refCount(e){return this.dataIdMap.has(e)?this.dataIdMap.get(e).refCount:0}incRef(e){const t=this.dataIdMap.get(e);null!=t&&t.refCount++}floatPrecision(){return 32}getMemoryOffset(e){return this.dataIdMap.get(e).memoryOffset}dispose(){this.wasm.tfjs.dispose(),"PThread"in this.wasm&&this.wasm.PThread.terminateAllThreads(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(e,t,n){let r;if(null==n)r=this.write(null,e,t);else{const a=this.dataIdNextNumber++;r={id:a},this.dataIdMap.set(r,{id:a,memoryOffset:n,shape:e,dtype:t,refCount:1});const s=et(e);this.wasm.tfjs.registerTensor(a,s,n)}return{dataId:r,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:n}){const r=this.wasm.HEAPU8.buffer,{memoryOffset:a}=this.dataIdMap.get(n),s=et(e);switch(t){case"float32":return new Float32Array(r,a,s);case"int32":return new Int32Array(r,a,s);case"bool":return new Uint8Array(r,a,s);default:throw new Error(`Unknown dtype ${t}`)}}}function VE(e,t,n){let r="tfjs-backend-wasm.wasm";return e&&t?r="tfjs-backend-wasm-threaded-simd.wasm":e&&(r="tfjs-backend-wasm-simd.wasm"),null!=GE&&null!=GE[r]?GE[r]:n+r}const WE=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"];let HE=null,GE={},jE=!1,KE=!1;function qE(e,t=!1){if(jE)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPaths()` before you call `tf.setBackend()` or `tf.ready()`");if("string"==typeof e)HE=e;else{GE=e;const t=WE.filter((e=>null==GE[e]));if(t.length>0)throw new Error(`There were no entries found for the following binaries: ${t.join(",")}. Please either call setWasmPaths with a map providing a path for each binary, or with a string indicating the directory where all the binaries can be found.`)}KE=t}let XE=-1,YE=null;Ei("wasm",(async()=>{const{wasm:e}=await async function(){const[e,t]=await Promise.all([Ct().getAsync("WASM_HAS_SIMD_SUPPORT"),Ct().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise(((n,r)=>{const a={locateFile:(n,r)=>{if(n.endsWith(".worker.js")){const e='"use strict";var Module={};var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads");var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",data=>onmessage({data:data}));var fs=require("fs");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,"utf8")+"//# sourceURL="+f)},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}var initializedJS=false;var pendingNotifiedProxyingQueues=[];function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+"\n");return}console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=(info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports};self.onunhandledrejection=e=>{throw e.reason??e};self.startWorker=instance=>{Module=instance;postMessage({"cmd":"loaded"})};self.onmessage=e=>{try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;for(const handler of e.data.handlers){Module[handler]=function(){postMessage({cmd:"callHandler",handler:handler,args:[...arguments]})}}Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob=="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module)}else if(e.data.cmd==="run"){Module["__emscripten_thread_init"](e.data.pthread_ptr,0,0,1);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInitTLS();if(!initializedJS){pendingNotifiedProxyingQueues.forEach(queue=>{Module["executeNotifiedProxyingQueue"](queue)});pendingNotifiedProxyingQueues=[];initializedJS=true}try{Module["invokeEntryPoint"](e.data.start_routine,e.data.arg)}catch(ex){if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["__emscripten_thread_exit"](ex.status)}}else{throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["__emscripten_thread_exit"](-1)}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processProxyingQueue"){if(initializedJS){Module["executeNotifiedProxyingQueue"](e.data.queue)}else{pendingNotifiedProxyingQueues.push(e.data.queue)}}else if(e.data.cmd){err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){if(Module["__emscripten_thread_crashed"]){Module["__emscripten_thread_crashed"]()}throw ex}};'.replace(/\n/g,"\\n"),t=new Blob([e],{type:"application/javascript"});return URL.createObjectURL(t)}return n.endsWith(".wasm")?VE(e,t,null!=HE?HE:r):r+n}};KE&&(a.instantiateWasm=function(e){return(t,n)=>(function(e,t){return Ct().platform.fetch(e,{credentials:"same-origin"})}(e).then((r=>{r.ok||t.env.a(`failed to load wasm binary file at '${e}'`),r.arrayBuffer().then((e=>{WebAssembly.instantiate(e,t).then((e=>{n(e.instance,e.module)}))}))})),{})}(VE(e,t,null!=HE?HE:"")));let s,o=!1;a.onAbort=()=>{o||jE||(jE=!0,r({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"}))},t&&e?(a.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+BE.toString()],{type:"text/javascript"}),s=BE(a)):s=UE(a),s.then((e=>{o=!0,jE=!1,e.tfjs={init:e.cwrap("init",null,[]),initWithThreadsCount:e.cwrap("init_with_threads_count",null,["number"]),getThreadsCount:e.cwrap("get_threads_count","number",[]),registerTensor:e.cwrap("register_tensor",null,["number","number","number"]),disposeData:e.cwrap("dispose_data",null,["number"]),dispose:e.cwrap("dispose",null,[])},n({wasm:e})})).catch(r)}))}();return new zE(e)}),2);var QE={modelFilename:"",featuresFilename:"",objContainer:"",fovY:50,detectScoreThs:.2,trackScoreThs:.4,footToDetect:"RIGHT_FOOT",filteringLevel:2,filteringShift:.5,validTrackedKeypThs:.2,trackedNumKeypsThs:3,activeIds:new Int32Array};function JE(e){return!!(void 0===e.outputNames||e.outputNames.length<1||e.outputNames.includes("heatmaps"))}function ZE(e,t){for(var n=1e4,r=1e4,a=-1e4,s=-1e4,o=0;o<t;o++){var i=e[o],u=e[t+o];i>a&&(a=i),u>s&&(s=u),i<n&&(n=i),u<r&&(r=u)}return[Math.floor(n),Math.floor(a+1),Math.floor(r),Math.floor(s+1)]}function eN(e,t,n){for(var r=1e4,a=1e4,s=-1e4,o=-1e4,i=0;i<n;i++)if(t[i]>0){var u=e[i],l=e[n+i];u>s&&(s=u),l>o&&(o=l),u<r&&(r=u),l<a&&(a=l)}return[Math.floor(r),Math.floor(s+1),Math.floor(a),Math.floor(o+1)]}function tN(e,t){void 0===t&&(t=.1);for(var n=e.length,r=0,a=0,s=new Int32Array(n),o=0;o<n;o++)e[o]>t?(a+=1,s[o]=1,r+=e[o]):s[o]=0;return a>0?r/=a:r=0,{globalScore:r,visibilty:s,totalVisible:a}}function nN(e,t){void 0===t&&(t=.1);for(var n=e.length,r=new Int32Array(n),a=0;a<n;a++)e[a]>t?r[a]=1:r[a]=0;return r}function rN(e,t,n,r){void 0===n&&(n=""),void 0===r&&(r=new Int32Array([-1,-1]));var a=Float32Array.from(e),s=e.length/2;if(""!=n)if("left_right"==n)for(var o=0;o<s;o++)a[o]=r[1]-1-a[o];else if("up_down"==n)for(o=0;o<s;o++)a[o+s]=r[0]-1-a[o+s];for(o=0;o<s;o++){var i=a[o],u=a[o+s];a[o]=t[0]*i+t[1]*u+t[2],a[o+s]=t[3]*i+t[4]*u+t[5]}return a}function aN(e,t){if("UPPER-BODY"==e){if(15==t)return[13,14]}else if("FULL-BODY"==e){if(19==t)return[17,18]}else if("FACE"==e){if(68==t)return[36,45];if(19==t)return[8,13];if(21==t)return[10,15]}else if("HAND"==e){if(7==t)return[0,3];if(21==t)return[0,9];if(10==t)return[7,8];if(8==t)return[5,6];if(11==t)return[7,8];if(9==t)return[1,6]}else{if(5==t)return[1,2];if(14==t)return[1,7];if(20==t)return[2,12];if(7==t)return[0,6];if(19==t)return[10,15];if(9==t)return[1,6];if(23==t)return[0,14];if(181==t)return[30,163];if(44==t)return[19,37]}return console.time("==> (E) Incorrect number of vertices"),[0,1]}function sN(e,t){var n=t.length/2,r=aN(e,n),a=r[0],s=r[1],o=[t[a],t[a+n]],i=[t[s],t[s+n]],u=[(o[0]+i[0])/2,(o[1]+i[1])/2],l=-Math.atan2(o[1]-i[1],i[0]-o[0]);return[u[0],u[1],l]}function oN(e,t,n){for(var r=n[0],a=n[1],s=n[2],o=n[3],i=n[4],u=n[5],l=e.width,c=e.height,p=4*e.width,h=t.width,d=t.height,f=4*t.width,m=0;m<d;m++)for(var g=a*m+s,y=i*m+u,b=m*f,_=0;_<h;_++){var x=4*_,v=Math.floor(g),w=Math.floor(y),T=g-v,k=y-w,I=void 0,S=void 0;if(v>0&&v<l-1&&w>0&&w<c-1){for(var E=w*p+4*v,N=0;N<3;N++,E++){var C=e.data[E];I=C+T*(e.data[E+4]-C),S=e.data[E+p]+T*(e.data[E+p+4]-e.data[E+p]),t.data[b+x+N]=I+k*(S-I)}t.data[b+x+3]=255}else{for(N=0;N<3;N++)t.data[b+x+N]=0;t.data[b+x+3]=255}g+=r,y+=o}return t}var iN,uN=function(){function e(e,t){this.x=e,this.y=t}return e.prototype.Dist=function(e){return Math.sqrt((e.x-this.x)*(e.x-this.x)+(e.y-this.y)*(e.y-this.y))},e}(),lN=function(){function e(e,t){this.x=e,this.y=t}return e.prototype.Dist=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},e.CreateFromPoints=function(t,n){return new e(n.x-t.x,n.y-t.y)},e}(),cN=function(){function e(e,t,n,r){this.x=e,this.y=t,this.w=n,this.h=r}return e.prototype.Centre=function(){return new uN(this.x+this.w/2,this.y+this.h/2)},e.prototype.isPointInside=function(e){return e.x>=this.x&&e.x>=this.x&&e.x<this.x+this.w&&e.y<this.y+this.h},e}();function pN(e,t,n,r,a){void 0===a&&(a=.5);for(var s=e.length/2,o=eN(e,t,s),i=Math.max(o[1]-o[0],o[3]-o[2])/6,u=0;u<s;u++)if(t[u]<=0&&r[u]>0)e[u]=n[u],e[u+s]=n[u+s];else if(t[u]>0&&r[u]<=0);else if(t[u]>0&&r[u]>0){var l=Math.sqrt((n[u]-e[u])*(n[u]-e[u])+(n[u+s]-e[u+s])*(n[u+s]-e[u+s])),c=(1-a)*Math.exp(-.5*l*l/i);e[u]=c*n[u]+(1-c)*e[u],e[u+s]=c*n[u+s]+(1-c)*e[u+s]}return e}function hN(e,t,n,r,a,s,o){void 0===o&&(o=0);for(var i=e.length/2,u=new Float32Array(2*n.length),l=0;l<n.length;l++){var c=n[l];u[l]=e[c],u[l+n.length]=e[c+i]}var p=n.length,h=new uN(0,0);a.forEach((function(e){h.x+=u[e],h.y+=u[e+p]})),h.x/=a.length,h.y/=a.length;var d=r[0],f=r[1],m=new uN(u[d],u[d+p]),g=new uN(u[f],u[f+p]),y=-Math.atan2(g.y-m.y,m.x-g.x)+o,b=0;for(l=0;l<p;l++){var _=new uN(u[l],u[l+p]).Dist(h);_>b&&(b=_)}b*=2;var x=new cN(h.x-b/2,h.y-b/2,b,b),v=Math.cos(y),w=Math.sin(y);b=(x.w+s*x.w)/Math.max(t[0],t[1]);var T=t[1]/2,k=t[0]/2,I=h.x,S=h.y;return new Float32Array([v*b,-w*b,I-(v*b*T-w*b*k),w*b,v*b,S-(w*b*T+v*b*k)])}function dN(e,t){e.length;var n=function(e,t){var n=e.length/2,r=gN(n,t),a=r[0],s=r[1],o=[e[a],e[a+n]],i=[e[s],e[s+n]],u=[(o[0]+i[0])/2,(o[1]+i[1])/2],l=-Math.atan2(o[1]-i[1],i[0]-o[0]),c=Math.sqrt((o[0]-i[0])*(o[0]-i[0])+(o[1]-i[1])*(o[1]-i[1]));return[u[0],u[1],l,c]}(e,t),r=n[0],a=n[1],s=n[2],o=n[3],i=[Math.cos(s),Math.sin(s)],u=[-i[1],i[0]],l=o/1,c=o/2;return[r+i[0]*l+u[0]*c,a+i[1]*l+u[1]*c,r+i[0]*l-u[0]*c,a+i[1]*l-u[1]*c,r-i[0]*l-u[0]*c,a-i[1]*l-u[1]*c,r-i[0]*l+u[0]*c,a-i[1]*l+u[1]*c]}function fN(e,t,n){if(void 0===n&&(n=.1),6==e.length){for(var r=0,a=new Int32Array(3),s=0,o="RIGHT_FOOT"==t?3:0,i=o;i<o+3;i++)r+=e[i],e[i]>n&&(s+=1,a[i]=1);return{globalScore:r/=3,visibilty:a,totalVisible:s}}return tN(e,n)}function mN(e,t,n,r){var a=Float32Array.from(e),s=e.length/2;if(n)for(var o=0;o<s;o++)a[o+s]=r-1-a[o+s];for(o=0;o<s;o++){var i=a[o],u=a[o+s];a[o]=t[0]*i+t[1]*u+t[2],a[o+s]=t[3]*i+t[4]*u+t[5]}return a}function gN(e,t){if(void 0===t&&(t="face"),"face"==t){if(5==e)return[0,1];if(19==e)return[6,11];if(21==e)return[17,20];if(51==e)return[19,28];if(68==e)return[36,45];if(16==e)return[6,9]}return"eye"==t?[0,1]:6==e&&"RIGHT_FOOT"==t?[3,5]:6==e&&"LEFT_FOOT"==t?[0,2]:18!=e||"RIGHT_FOOT"!=t&&"LEFT_FOOT"!=t?13!=e||"RIGHT_FOOT"!=t&&"LEFT_FOOT"!=t?593!=e||"RIGHT_FOOT"!=t&&"LEFT_FOOT"!=t?200!=e||"RIGHT_FOOT"!=t&&"LEFT_FOOT"!=t?(console.error("no type or number of feature match"),[0,1]):[115,167]:[210,78]:[0,6]:[0,9]}function yN(e,t){var n=e.length/2,r=gN(n,t),a=r[0],s=r[1],o=[e[a],e[a+n]],i=[e[s],e[s+n]],u=[(o[0]+i[0])/2,(o[1]+i[1])/2],l=-Math.atan2(o[1]-i[1],i[0]-o[0]);return[u[0],u[1],l]}function bN(e,t,n){for(var r=n[0],a=n[1],s=n[2],o=n[3],i=n[4],u=n[5],l=e.width,c=e.height,p=4*e.width,h=t.width,d=t.height,f=4*t.width,m=0;m<d;m++)for(var g=a*m+s,y=i*m+u,b=m*f,_=0;_<h;_++){var x=4*_,v=Math.floor(g),w=Math.floor(y),T=g-v,k=y-w,I=void 0,S=void 0;if(v>0&&v<l-1&&w>0&&w<c-1){for(var E=w*p+4*v,N=0;N<3;N++,E++){var C=e.data[E];I=C+T*(e.data[E+4]-C),S=e.data[E+p]+T*(e.data[E+p+4]-e.data[E+p]),t.data[b+x+N]=I+k*(S-I)}t.data[b+x+3]=255}else{for(N=0;N<3;N++)t.data[b+x+N]=0;t.data[b+x+3]=255}g+=r,y+=o}return t}function _N(e,t,n,r,a,s){var o,i,u=e.length/2,l=0,c=0,p=0;6==u?(c=(o=yN(e,s))[0],l=o[1],p=o[2],ZE("RIGHT_FOOT"==s?[e[3],e[4],e[5],e[3+u],e[4+u],e[5+u]]:[e[0],e[1],e[2],e[0+u],e[1+u],e[2+u]],3)):(c=(i=yN(e,s))[0],l=i[1],p=i[2],eN(e,t,u));var h=Math.cos(p),d=Math.sin(p),f=.5;200==u&&(f=.7);var m=gN(u,s),g=m[0],y=m[1],b=[e[g],e[g+u]],_=[e[y],e[y+u]],x=Math.sqrt((b[0]-_[0])*(b[0]-_[0])+(b[1]-_[1])*(b[1]-_[1])),v=(x+=f*x)/Math.max(r,n),w=(n-1)/2,T=(r-1)/2,k=c-(h*v*w-d*v*T),I=l-(d*v*w+h*v*T);if(null!=a){var S=Math.sqrt((k-a[2])*(k-a[2])+(I-a[5])*(I-a[5])),E=1;S>20&&(E=.1),S>=10&&S<=20&&(E=1-.09*(S-5)),k=(1-E)*k+E*a[2],I=(1-E)*I+E*a[5],p=Math.abs(p-a[6])>1?(1-E)*p-E*a[6]:(1-E)*p+E*a[6],v=(1-E)*v+E*a[7],h=Math.cos(p),d=Math.sin(p)}return[h*v,-d*v,k,d*v,h*v,I,p,v]}function xN(e,t){var n=t.length,r=e._malloc(4*n),a=r/4;return e.HEAPF32.subarray(a,a+n).set(t),r}function vN(e,t){var n=e._malloc(4*t.length);return e.HEAPF32.set(t,n/4),n}function wN(e,t,n){var r=new Float32Array(n),a=t/4;return r.set(e.HEAPF32.subarray(a,a+n)),r.slice()}function TN(e,t,n){var r=new Uint32Array(t.data.buffer),a=r.length,s=n/4;e.HEAPU32.subarray(s,s+a).set(r)}function kN(e,t,n,r){var a=e._malloc(28);return e.setValue(a,n,"i32"),e.setValue(a+4,r,"i32"),e.setValue(a+8,t,"i32"),e.setValue(a+12,0,"i32"),e.setValue(a+16,4,"i32"),e.setValue(a+20,0,"i32"),e.setValue(a+24,0,"i32"),a}function IN(e,t,n,r,a){var s=e.cwrap("xzimgMatchRecKeyps","number",["number","number","number","number","number"]),o=r.length/2;TN(e,t,n);for(var i=kN(e,n,t.width,t.height),u=vN(e,r),l=vN(e,r.slice()),c=e._malloc(4*o),p=0;p<o;p++)e.setValue(c+4*p,1,"float"),a.length>p&&0==a[p]&&e.setValue(c+4*p,-1,"float");var h=e._malloc(16);s(i,u,l,o,c,h);var d=wN(e,c,o),f=wN(e,l,r.length),m=wN(e,h,4);for(p=0;p<o;p++)0==d[p]&&(f[p]=r[p],f[p+o]=r[p+o]);return e._free(i),e._free(u),e._free(l),e._free(c),e._free(h),[f,m,d]}function SN(e,t,n,r){var a=vN(e,t),s=vN(e,n),o=e._malloc(16);e.cwrap("xzimgEstimateGetSimilarity","number",["number","number","number","number"])(a,s,t.length/2,o);var i=wN(e,o,4);return e._free(a),e._free(s),e._free(o),i}function EN(e,t,n){void 0===n&&(n=null);for(var r=new Float32Array(2),a=e.length/2,s=0,o=0;o<a;o++)(null==n||n[o]>0)&&(r[0]+=t[o]-e[o],r[1]+=t[o+a]-e[o+a],s+=1);return s>0&&(r[0]/=s,r[1]/=s),r}function NN(e,t,n){var r,a,s,o,i;void 0===n&&(n=!0);var u=n?1:2;return r=function(e,t,n,r,a){void 0===a&&(a=1);var s=new Float32Array(r).fill(0),o=new Float32Array(2*r);if(1==a)for(var i=t*n,u=0;u<i;u++)for(var l=0;l<r;l++)(h=e[u*r+l])>s[l]&&(s[l]=h,o[l]=u%n,o[r+l]=Math.floor(u/n));else{var c=n*a;for(u=a;u<t;u+=a,c+=n*a)for(var p=a;p<n;p+=a)for(l=0;l<r;l++){var h;(h=e[(c+p)*r+l])>s[l]&&(s[l]=h,o[l]=p,o[r+l]=u)}}return[o,s]}(e,t[1],t[2],t[3],u),s=r[0],i=r[1],n?(a=function(e,t,n,r,a){for(var s=[-r*a-a,-r*a,-r*a+a,-a,0,a,r*a-a,r*a,r*a+a],o=new Float32Array(a),i=new Float32Array(2*a),u=0;u<a;u++){var l=t[u],c=t[a+u];i[u]=l,i[a+u]=c;var p=c*r*a+l*a+u,h=0;h=0;for(var d=0;d<9;d++)h+=e[p+s[d]];h/=9,o[u]=h;var f=Math.min(l+2,r-1),m=Math.max(l-2,0),g=Math.min(c+2,n-1),y=Math.max(c-2,0),b=0,_=0,x=c*r*a+m*a+u,v=c*r*a+f*a+u;for(d=0;d<9;d++)b+=e[x+s[d]],_+=e[v+s[d]];var w=2*(2*h-((b/=9)+(_/=9)));if(Math.abs(w)>1e-5){var T=2*(_-b)/w;i[u]+=T}var k=0,I=0,S=y*r*a+l*a+u,E=g*r*a+l*a+u;for(d=0;d<9;d++)k+=e[S+s[d]],I+=e[E+s[d]];w=2*(2*h-((k/=9)+(I/=9))),Math.abs(w)>1e-5&&(T=2*(I-k)/w,i[a+u]+=T)}return[i,o]}(e,s,t[1],t[2],t[3]),o=a[0],i=a[1]):o=s,[o,i]}function CN(e,t,n,r,a,s){var o=e.cwrap("xzimgGetHeatmapsLocations","number",["number","number","number","number","number","number","number","number"]),i=t[1]*t[2]*t[3],u=r/4;return e.HEAPF32.subarray(u,u+i).set(n),o(r,t[1],t[2],t[3],0,1,a,s),[new Float32Array(e.HEAPF32.buffer,a,2*t[3]),new Float32Array(e.HEAPF32.buffer,s,t[3])]}function AN(e,t){var n=new ie(0),r=n.asObservable();if("string"==typeof e)return{model$:a=Sw({url:e,method:"GET",responseType:"text",async:!0,progressSubscriber:new w((function(e){return n.next(e.loaded/e.total)}),(function(e){}),(function(){return n.next(1)}))}).pipe(ue(2),K((function(e){return RN(e.response,t)}))),progress$:r};var a=be((function(){return n.next(1),j(RN(function(e){var t,n,r="",a=0,s=new Uint8Array(e);for(a=0;a<s.length;a++)if(s[a]<128)r+=String.fromCharCode(s[a]);else{s[a]<224?(t=(63&s[a])<<6,n=a+1):s[a]<240?(t=(31&s[a])<<12,n=a+2):s[a]<248?(t=(15&s[a])<<18,n=a+3):s[a]<252?(t=(7&s[a])<<24,n=a+4):(t=(3&s[a])<<30,n=a+5);do{t|=(127&s[++a])<<6*(n-a)}while(a!=n);r+=String.fromCharCode(t)}return r}(e),t))}));return{model$:a,progress$:r}}function RN(e,t){var n,r,a,s,o={vertices:new Float32Array,uvs:new Float32Array,faces:new Uint16Array},i=e.match(/^v\s+(-?\d+(?:\.\d+)?\s+){2}-?\d+(?:\.\d+)?$/gm);if(i){var u=i.map((function(e){var t=e.split(" ");return t.shift(),t.map((function(e){return+e}))})),l=(n=[]).concat.apply(n,u);o.vertices=new Float32Array(l)}var c=e.match(/^vt( -?\d+(\.\d+)?){2}$/gm);if(c){var p=c.map((function(e){var t=e.split(" ");return t.shift(),t.map((function(e){return+e}))})),h=(r=[]).concat.apply(r,p);o.uvs=new Float32Array(h)}var d=e.match(/^f( \d+\/\d*\/\d*){3}$/gm);if(d){var f=d.map((function(e){var t=e.split(" ");return t.shift(),[+t[0].split("/")[0]-1,+t[1].split("/")[0]-1,+t[2].split("/")[0]-1]})),m=(a=[]).concat.apply(a,f);if(o.faces=new Uint16Array(m),t){var g=d.map((function(e){var t=e.split(" ");return t.shift(),[+t[0].split("/")[1]-1,+t[1].split("/")[1]-1,+t[2].split("/")[1]-1]})),y=new Uint16Array((s=[]).concat.apply(s,g)),b=o.uvs;o.uvs=new Float32Array(b.length);for(var _=0;_<y.length;_++){var x=y[_],v=b[2*x],w=b[2*x+1],T=o.faces[_];o.uvs[2*T]=v,o.uvs[2*T+1]=w}}}if(t){for(_=0;_<o.faces.length;_+=3){var k=o.faces[_];o.faces[_]=o.faces[_+1],o.faces[_+1]=k}for(_=0;_<o.vertices.length;_+=3)o.vertices[_]=-o.vertices[_]}return o}!function(e){e.Detection="DETECTION",e.Detected="DETECTED",e.Tracking="TRACKING"}(iN||(iN={}));var $N,MN=function(){function e(e,t){this._trackingState=iN.Detection,this._type=0,this._R=Float32Array.from(e),this._t=Float32Array.from(t),this._trackingState=iN.Detection}return e.prototype.setTrackingState=function(e){this._trackingState=e},e.prototype.getTrackingState=function(){return this._trackingState},e.prototype.isDetected=function(){return this._trackingState==iN.Tracking},Object.defineProperty(e.prototype,"type",{get:function(){return this._type},set:function(e){this._type=e},enumerable:!1,configurable:!0}),e.prototype.setRt=function(e,t){this._R=e.slice(0),this._t=t.slice(0)},e.prototype.setR=function(e){this._R=e.slice(0)},e.prototype.R=function(){return this._R},e.prototype.t=function(){return this._t},e.prototype.getPosition=function(){return[this._t[0],this._t[1],this._t[2]]},e.prototype.getRotation=function(){return[[this._R[0],this._R[1],this._R[2]],[this._R[3],this._R[4],this._R[5]],[this._R[6],this._R[7],this._R[8]]]},e.prototype.getRot=function(){return this._R},e.prototype.updateRotation=function(e){this._R=Float32Array.from(e)},e.prototype.translate=function(e,t,n){this._t[0]+=e,this._t[1]+=t,this._t[2]+=n},e.prototype.reset=function(){this._R=new Float32Array([1,0,0,0,-1,0,0,0,-1]),this._t=new Float32Array([0,0,0])},e.prototype.det=function(){return this._R[0]*(this._R[4]*this._R[8]-this._R[7]*this._R[5])-this._R[3]*(this._R[1]*this._R[8]-this._R[7]*this._R[2])+this._R[6]*(this._R[1]*this._R[5]-this._R[4]*this._R[2])},e.convert3x3Mat=function(e){return new Float32Array([e[0][0],e[0][1],e[0][2],e[1][0],e[1][1],e[1][2],e[2][0],e[2][1],e[2][2]])},e.convert3x3Mat_t=function(e){return new Float32Array([e[0][0],e[1][0],e[2][0],e[0][1],e[1][1],e[2][1],e[0][2],e[1][3],e[2][2]])},e.getQuatFromRotMat=function(e){var t=new Float32Array(4);return t[0]=Math.sqrt(Math.max(0,1+e[0]+e[4]+e[8]))/2,t[1]=Math.sqrt(Math.max(0,1+e[0]-e[4]-e[8]))/2,t[2]=Math.sqrt(Math.max(0,1-e[0]+e[4]-e[8]))/2,t[3]=Math.sqrt(Math.max(0,1-e[0]-e[4]+e[8]))/2,t[1]=e[7]-e[5]<0?-Math.abs(t[1]):Math.abs(t[1]),t[2]=e[2]-e[6]<0?-Math.abs(t[2]):Math.abs(t[2]),t[3]=e[3]-e[1]<0?-Math.abs(t[3]):Math.abs(t[3]),t},e.getRotMatFromQuat=function(e){var t=new Float32Array(9);return t[0]=1-2*e[2]*e[2]-2*e[3]*e[3],t[1]=2*e[1]*e[2]-2*e[3]*e[0],t[2]=2*e[1]*e[3]+2*e[2]*e[0],t[3]=2*e[1]*e[2]+2*e[3]*e[0],t[4]=1-2*e[1]*e[1]-2*e[3]*e[3],t[5]=2*e[2]*e[3]-2*e[1]*e[0],t[6]=2*e[1]*e[3]-2*e[2]*e[0],t[7]=2*e[2]*e[3]+2*e[1]*e[0],t[8]=1-2*e[1]*e[1]-2*e[2]*e[2],t},e.slerp=function(e,t,n){var r,a,s=new Float32Array(4),o=e[1]*t[1]+e[2]*t[2]+e[3]*t[3]+e[0]*t[0],i=Math.abs(o);if(i>=.99999)r=1-n,a=n;else{var u=Math.acos(i),l=Math.sin(u);r=Math.sin((1-n)*u)/l,a=Math.sin(n*u)/l}return o<0&&(a=-a),s[1]=r*e[1]+a*t[1],s[2]=r*e[2]+a*t[2],s[3]=r*e[3]+a*t[3],s[0]=r*e[0]+a*t[0],s},e.getCameraMat=function(e,t,n){var r=n/2/Math.tan(e*Math.PI/180/2),a=r,s=(t-1)/2,o=(n-1)/2,i=new Float32Array(9);return i[0]=a,i[2]=s,i[4]=r,i[5]=o,i[8]=1,i},e.getCameraParams=function(e,t,n){var r=n/2/Math.tan(e*Math.PI/180/2);return[r,r,(t-1)/2,(n-1)/2]},e.MatMultVec=function(e,t){var n=new Float32Array(3);return n[0]=e[0]*t[0]+e[1]*t[1]+e[2]*t[2],n[1]=e[3]*t[0]+e[4]*t[1]+e[5]*t[2],n[2]=e[6]*t[0]+e[7]*t[1]+e[8]*t[2],n},e.MatMult=function(e,t){var n=new Float32Array(9);return n[0]=e[0]*t[0]+e[1]*t[3]+e[2]*t[6],n[1]=e[0]*t[1]+e[1]*t[4]+e[2]*t[7],n[2]=e[0]*t[2]+e[1]*t[5]+e[2]*t[8],n[3]=e[3]*t[0]+e[4]*t[3]+e[5]*t[6],n[4]=e[3]*t[1]+e[4]*t[4]+e[5]*t[7],n[5]=e[3]*t[2]+e[4]*t[5]+e[5]*t[8],n[6]=e[6]*t[0]+e[7]*t[3]+e[8]*t[6],n[7]=e[6]*t[1]+e[7]*t[4]+e[8]*t[7],n[8]=e[6]*t[2]+e[7]*t[5]+e[8]*t[8],n},e.prototype.project=function(t,n){for(var r=new Float32Array(t.length/3*2),a=0;a<t.length/3;a++){var s=e.MatMultVec(this._R,new Float32Array([t[3*a],t[3*a+1],t[3*a+2]])),o=new Float32Array(3);o[0]=s[0]+this._t[0],o[1]=s[1]+this._t[1],o[2]=s[2]+this._t[2];var i=n[6]*o[0]+n[7]*o[1]+n[8]*o[2];r[2*a]=(n[0]*o[0]+n[1]*o[1]+n[2]*o[2])/i,r[2*a+1]=(n[3]*o[0]+n[4]*o[1]+n[5]*o[2])/i}return r},e.prototype.transform=function(t,n){for(var r=new Float32Array(t.length/3*2),a=0;a<t.length/3;a++){var s=e.MatMultVec(this._R,new Float32Array([t[3*a],t[3*a+1],t[3*a+2]]));r[3*a+0]=s[0]+this._t[0],r[3*a+1]=s[1]+this._t[1],r[3*a+2]=s[2]+this._t[2]}return r},e.prototype.transformInv=function(t){var n=new Float32Array(3),r=new Float32Array([this._R[0],this._R[3],this._R[6],this._R[1],this._R[4],this._R[7],this._R[2],this._R[5],this._R[8]]),a=e.MatMultVec(r,t),s=e.MatMultVec(r,this._t);return n[0]=a[0]-s[0],n[1]=a[1]-s[1],n[2]=a[2]-s[2],n},e}(),FN=function(){function e(e){this.NB_BUFFERS=6,this._poses=[],this._nbFramesDelay=0,this._interpolation=0,this._filteringLevel=2,this._filterThreshold=-1,e>=0&&e<this.NB_BUFFERS?this._nbFramesDelay=this._nbFramesDelay:console.error("Invalid frames delay, delay must be less than ",this.NB_BUFFERS)}return e.prototype.setNbFramesDelay=function(e){this._nbFramesDelay=e},e.prototype.setInterpolation=function(e){this._interpolation=e},e.prototype.setFilteringLevel=function(e){this._filteringLevel=e},e.prototype.setFilterThreshold=function(e){this._filterThreshold=e},e.prototype.reset=function(){this._poses=[]},e.prototype.setPose=function(e){this._poses.length===this.NB_BUFFERS&&(this._poses=this._poses.slice(0,-1)),this._poses=o([e],this._poses,!0)},e.prototype.getPose=function(){return this._poses.length>0?this._nbFramesDelay<this._poses.length?this._poses[this._nbFramesDelay]:this._poses[this._poses.length-1]:null},e.prototype.getInterpolatedPoseAtDelay=function(e){if(e>0&&e+1<this._poses.length){var t=this._poses[e-1],n=this._poses[e],r=this._poses[e+1];if(t.getTrackingState()!==iN.Tracking||r.getTrackingState()!==iN.Tracking)return n;for(var a=MN.getQuatFromRotMat(t.R()),s=MN.getQuatFromRotMat(r.R()),o=MN.slerp(a,s,.5),i=MN.getRotMatFromQuat(o),u=t.t(),l=r.t(),c=new Float32Array(3),p=0;p<3;p++)c[p]=.5*u[p]+.5*l[p];var h=new MN(i,c);return h.setTrackingState(n.getTrackingState()),h.type=n.type,h}return this._poses.length>0?this.getPose():this.getLastPose()},e.prototype.dst=function(e,t){return Math.sqrt((e[0]-t[0])*(e[0]-t[0])+(e[1]-t[1])*(e[1]-t[1])+(e[2]-t[2])*(e[2]-t[2]))},e.prototype.mvts=function(e,t,n){return(this.dst(e,t)+this.dst(t,n))/2},e.prototype.getInterpolatedPose=function(){if(1==this._filteringLevel)return this.getInterpolatedPoseAtDelay(this._nbFramesDelay);if(2==this._filteringLevel){var e=this.getInterpolatedPoseAtDelay(this._nbFramesDelay-1),t=this.getInterpolatedPoseAtDelay(this._nbFramesDelay+1);if(null==e||null==t)return this.getInterpolatedPoseAtDelay(this._nbFramesDelay);if(e.getTrackingState()!==iN.Tracking||t.getTrackingState()!==iN.Tracking)return this.getInterpolatedPoseAtDelay(this._nbFramesDelay);var n=this._poses[this._nbFramesDelay],r=e.t(),a=t.t();if(this._filterThreshold>0){var s=this.dst(r,n.t()),o=this.dst(a,n.t());if(s>this._filterThreshold||o>this._filterThreshold)return n}for(var i=MN.getQuatFromRotMat(e.R()),u=MN.getQuatFromRotMat(t.R()),l=MN.slerp(i,u,this._interpolation),c=MN.getRotMatFromQuat(l),p=new Float32Array(3),h=0;h<3;h++)p[h]=(1-this._interpolation)*r[h]+this._interpolation*a[h];var d=new MN(c,p);return d.setTrackingState(n.getTrackingState()),d.type=n.type,d}return this.getLastPose()},e.prototype.updateDelay=function(e){e!=this._nbFramesDelay&&(e>=0&&e<this.NB_BUFFERS?this._nbFramesDelay=e:console.error("Invalid frames delay, delay must be less than ",this.NB_BUFFERS))},e.prototype.getLastPose=function(){return this._poses.length>0?this._poses[0]:null},e}();!function(e){e.Left="LEFT_FOOT",e.Right="RIGHT_FOOT",e.Both="BOTH_FOOT",e.Single="SINGLE_FOOT"}($N||($N={}));var ON,DN="config.bin",LN=function(){function e(){this._initialized=!1,this._currentWidth=0,this._currentHeight=0,this._trackingState=iN.Detection,this._useWasmForHeatmaps=!1,this._float_size=4,this._bufferHeatmaps=null,this._bufferKeypsDet=null,this._bufferFeatureScores=null,this._bufKeyps3D_R=null,this._bufKeyps3D_L=null,this._footToDetect=$N.Right,this._leftFootState=iN.Detection,this._rightFootState=iN.Detection,this._bufferKeypsTrack_L=null,this._bufferKeypsTrack_R=null,this._bufferHeatmaps_L=null,this._bufferHeatmaps_R=null,this._fastMovements_L=!1,this._fastMovements_R=!1,this._cnnOutputDataInvMask=null,this._trackHasHeatmaps=!0,this._debug=!1,this._debugInitialized=!1,this._reproj_t=15,this._reproj_fast_t=30,this._isDetected=!1}return e.prototype.getDebugImage=function(){return this._debugInitialized?this._debugImage:null},e.prototype.isDetected=function(){return this._isDetected},e.prototype.getPosition=function(e){void 0===e&&(e=$N.Right);var t=null;return(t=e==$N.Right?this._poseManager_R.getInterpolatedPose():this._poseManager_L.getInterpolatedPose())?t.getPosition():null},e.prototype.getRotation=function(e){void 0===e&&(e=$N.Right);var t=null;return(t=e==$N.Right?this._poseManager_R.getInterpolatedPose():this._poseManager_L.getInterpolatedPose())?t.getRotation():null},e.prototype.getPose=function(e){return void 0===e&&(e=$N.Right),e==$N.Right?this._pose_L:this._pose_R},e.prototype.getInterpolatedPose=function(e){return void 0===e&&(e=$N.Right),e==$N.Right?this._poseManager_R.getInterpolatedPose():this._poseManager_L.getInterpolatedPose()},e.prototype.isInitialized=function(){return this._initialized},e.prototype.initialize=function(e,n,r){var o,i,u,l;return a(this,void 0,void 0,(function(){var a,c,p,h,d,f,m,g,y,b,_,x,v=this;return s(this,(function(s){switch(s.label){case 0:if(null==e)throw"Invalid parameter";return this._config=n?t(t({},QE),n):QE,(null===(o=null==n?void 0:n.wasmBackend)||void 0===o?void 0:o.enable)?(qE({"tfjs-backend-wasm.wasm":null===(i=n.wasmBackend)||void 0===i?void 0:i.tfjsBackendWasmPath,"tfjs-backend-wasm-simd.wasm":null===(u=n.wasmBackend)||void 0===u?void 0:u.tfjsBackendWasmSimdPath,"tfjs-backend-wasm-threaded-simd.wasm":null===(l=n.wasmBackend)||void 0===l?void 0:l.tfjsBackendWasmThreadedPath}),[4,Ii("wasm")]):[3,2];case 1:return s.sent(),[3,3];case 2:Ii("webgl"),s.label=3;case 3:return this.release(),this._videoManager=e,"BOTH"!==this._config.footToDetect&&"BOTH_FEET"!==this._config.footToDetect||(this._footToDetect=$N.Both),this._poseManager_R=new FN(this._videoManager.getNbFramesDelay()),this._poseManager_R.setInterpolation(this._config.filteringShift),this._poseManager_R.setFilteringLevel(this._config.filteringLevel),this._poseManager_R.setFilterThreshold(.1),this._poseManager_L=new FN(this._videoManager.getNbFramesDelay()),this._poseManager_L.setInterpolation(this._config.filteringShift),this._poseManager_L.setFilteringLevel(this._config.filteringLevel),this._poseManager_L.setFilterThreshold(.1),a=new ie(0),c=G(yk({locateFile:function(e,t){return v._config.poseEstimationWasmFilename||t+e}})).pipe(me((function(){return a.next(1)}))),p=uk(this._config.modelFilename,DN),h=p.model$,d=p.progress$,f=uk(this._config.featuresFilename,DN),m=f.model$,g=f.progress$,y=AN(this._config.objContainer,!1),b=y.model$,_=y.progress$,x=V([a,d,g,_]).pipe(K((function(e){return e.reduce((function(t,n){return t+n/e.length}),0)})),K((function(e){return r&&r(e)}))).subscribe(),[4,uw({poseModule:c,model:h,features:m,footObjModel:b}).pipe(K((function(e){var t;v._poseModule=e.poseModule,v._footObjModel=e.footObjModel,v._tfFootDetector=e.model.graphModel,v._footDetectorConfig=e.model.config,v._tfFootFeatures=e.features.graphModel,v._footFeaturesConfig=e.features.config,v._activeIds=v._config.activeIds,console.log(v._footFeaturesConfig),console.log(e.model.config),console.log(e.features.config),console.log("(DEBUG) XZIMG BACKEND",Si());var n=Nc([1,v._footDetectorConfig.inHeight,v._footDetectorConfig.inWidth,3]),r=v._tfFootDetector.predict(n);v._footDetectorShape=r.shape,r.dataSync(),r.dispose(),n.dispose();var a=v._footDetectorConfig.outChannels;n=Nc([1,v._footFeaturesConfig.inHeight,v._footFeaturesConfig.inWidth,3]),(r=v._tfFootFeatures.predict(n))instanceof Array?r.forEach((function(e){return e.dispose()})):r.dispose(),n.dispose(),n=Nc([2,v._footFeaturesConfig.inHeight,v._footFeaturesConfig.inWidth,3]),(r=v._tfFootFeatures.predict(n))instanceof Array?r.forEach((function(e){return e.dispose()})):r.dispose(),n.dispose();var s=v._footFeaturesConfig.outChannels;if(v._footFeaturesConfig.outputNames&&v._footFeaturesConfig.numOutputs&&v._footFeaturesConfig.numOutputs>1)for(var o=0,i=0,u=v._footFeaturesConfig.outputNames;i<u.length;i++){var l=u[i];"heatmaps"==l?s=v._footFeaturesConfig.outputDims[3*o+2]:"coordinates"==l&&(s=v._footFeaturesConfig.outputDims[3*o+2]/2),o+=1}if(t=function(e,t){var n=Array.from(Array(t).keys());13==t&&(n=[54,210,295,415,416,425,463,582,644,721,726,730,813]),18==t&&(n=[54,210,295,406,415,416,417,423,425,463,518,582,644,657,721,726,730,813]);for(var r=n.length,a=new Float32Array(3*r),s=0;s<r;s++){var o=n[s];a[3*s]=e[3*o],a[3*s+1]=e[3*o+1],a[3*s+2]=e[3*o+2]}var i=new Float32Array(3*r);for(s=0;s<r;s++)i[3*s]=-a[3*s],i[3*s+1]=a[3*s+1],i[3*s+2]=a[3*s+2];return[a,i]}(v._footObjModel.vertices,s),v._rightKeyps3D=t[0],v._leftKeyps3D=t[1],v._bufKeyps3D_R=v._poseModule._malloc(v._rightKeyps3D.length*v._float_size),v._poseModule.HEAPF32.set(v._rightKeyps3D,v._bufKeyps3D_R/4),v._bufKeyps3D_L=v._poseModule._malloc(v._leftKeyps3D.length*v._float_size),v._poseModule.HEAPF32.set(v._leftKeyps3D,v._bufKeyps3D_L/4),v._footDetectorConfig.outWidth>1&&v._footDetectorConfig.outHeight>1){var c=a*v._footDetectorConfig.outWidth*v._footDetectorConfig.outHeight;v._bufferHeatmaps=v._poseModule._malloc(c*v._float_size)}v._footFeaturesConfig.outWidth>1&&v._footFeaturesConfig.outHeight>1&&(c=s*v._footFeaturesConfig.outWidth*v._footFeaturesConfig.outHeight,v._bufferHeatmaps_L=v._poseModule._malloc(c*v._float_size),v._bufferHeatmaps_R=v._poseModule._malloc(c*v._float_size)),v._bufferKeypsDet=v._poseModule._malloc(2*a*v._float_size),v._bufferKeypsTrack_L=v._poseModule._malloc(2*s*v._float_size),v._bufferKeypsTrack_R=v._poseModule._malloc(2*s*v._float_size),v._bufferFeatureScores=v._poseModule._malloc(s*v._float_size),v._pose_R=new MN(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0])),v._pose_L=new MN(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0])),v._trackHasHeatmaps=JE(v._footFeaturesConfig),v._initialized=!0})),Z((function(){return x.unsubscribe()}))).toPromise()];case 4:return s.sent(),[2]}}))}))},e.prototype.release=function(){this._initialized&&(this._poseModule._free(this._bufferHeatmaps),this._bufferHeatmaps_L&&this._poseModule._free(this._bufferHeatmaps_L),this._bufferHeatmaps_R&&this._poseModule._free(this._bufferHeatmaps_R),this._bufferKeypsDet&&this._poseModule._free(this._bufferKeypsDet),this._poseModule._free(this._bufferKeypsTrack_L),this._poseModule._free(this._bufferKeypsTrack_R),this._poseModule._free(this._bufferFeatureScores),this._poseModule._free(this._bufKeyps3D_R),this._poseModule._free(this._bufKeyps3D_L),this._hptrImageBuffer&&this._poseModule._free(this._hptrImageBuffer))},e.prototype.trackSync=function(e){var t;if(this._initialized){var n=this._videoManager.getVideoCanvas();n.width===this._currentWidth&&n.height===this._currentHeight||(this._currentWidth=n.width,this._currentHeight=n.height,t=MN.getCameraParams(this._config.fovY,this._currentWidth,this._currentHeight),this._fx=t[0],this._fy=t[1],this._cx=t[2],this._cy=t[3],this._poseModule.cwrap("xzimgInitializeCamera","number",["number","number","number"])(this._config.fovY,this._currentWidth,this._currentHeight)),this._poseManager_L.setNbFramesDelay(this._videoManager.getNbFramesDelay()),this._poseManager_R.setNbFramesDelay(this._videoManager.getNbFramesDelay());var r=e;null==e&&(r=this._videoManager.getLastBuffer()),null!=r?this.trackFootSync(r):console.error("No video frame to process")}else console.error("Foot must be initialized to track")},e.prototype.trackFootSync=function(e){var t=-1;if(this._rightFootState!=iN.Detection&&this._leftFootState!=iN.Detection){var n=this.trackBothFeetFeaturesSync(e,this._leftFootState,this._rightFootState,this._leftFootState==iN.Detected?this._initShape:this._leftFootRecShape,this._rightFootState==iN.Detected?this._initShape:this._rightFootRecShape,this._leftFootVis,this._rightFootVis,this._leftFootOcclusions,this._rightFootOcclusions),r=fN(n.scores_R,"RIGHT_FOOT",this._config.validTrackedKeypThs);this._rightFootRecShape=n.refinedFeatures_R,this._rightFootOcclusions=n.occlusions_R,this._rightFootVis=r.visibilty;var a=fN(n.scores_L,"LEFT_FOOT",this._config.validTrackedKeypThs);this._leftFootRecShape=n.refinedFeatures_L,this._leftFootOcclusions=n.occlusions_L,this._leftFootVis=a.visibilty;var s=this._config.trackScoreThs,o=this._reproj_t;this._fastMovements_R&&(o=this._reproj_fast_t);var i=this._rightFootRecShape.length/2,u=gN(i,"RIGHT_FOOT"),l=new cN(0,0,e.width,e.height),c=new uN((this._rightFootRecShape[u[0]]+this._rightFootRecShape[u[1]])/2,(this._rightFootRecShape[u[0]+i]+this._rightFootRecShape[u[1]+i])/2);l.isPointInside(c)&&this._rightFootVis[u[0]]&&this._rightFootVis[u[1]]&&r.globalScore>=s&&r.totalVisible>=this._config.trackedNumKeypsThs?(t=this.computePoseSync(this._rightFootState,"RIGHT_FOOT"),this._rightFootState=iN.Tracking,t>o&&(this._rightFootState=iN.Detection)):this._rightFootState=iN.Detection,s=this._config.trackScoreThs,this._fastMovements_L&&(s=.1),o=this._reproj_t,this._fastMovements_L&&(o=this._reproj_fast_t),u=gN(i,"LEFT_FOOT");var p=new uN((this._leftFootRecShape[u[0]]+this._leftFootRecShape[u[1]])/2,(this._leftFootRecShape[u[0]+i]+this._leftFootRecShape[u[1]+i])/2);l.isPointInside(p)&&this._leftFootVis[u[0]]&&this._leftFootVis[u[1]]&&a.globalScore>=s&&a.totalVisible>=this._config.trackedNumKeypsThs?(t=this.computePoseSync(this._leftFootState,"LEFT_FOOT"),this._leftFootState=iN.Tracking,t>o&&(this._leftFootState=iN.Detection)):this._leftFootState=iN.Detection,this._leftFootState==iN.Tracking&&this._rightFootState==iN.Tracking&&this.bothFeetSamePlace()&&(this._leftFootState=iN.Detection,this._rightFootState=iN.Detection)}else if(this._rightFootState!==iN.Detection&&this._leftFootState===iN.Detection){var h=this.trackFootFeaturesSync(e,this._rightFootState,this._rightFootState==iN.Detected?this._initShape:this._rightFootRecShape,this._rightFootVis,this._rightFootOcclusions,"RIGHT_FOOT");this._rightFootRecShape=h.refinedFeatures,this._rightFootOcclusions=h.occlusions,r=fN(h.scores,"RIGHT_FOOT",this._config.validTrackedKeypThs),this._rightFootVis=r.visibilty,s=this._config.trackScoreThs,o=this._reproj_t,this._fastMovements_R&&(o=this._reproj_fast_t),u=gN(this._rightFootRecShape.length/2,"RIGHT_FOOT"),this._rightFootVis[u[0]]&&this._rightFootVis[u[1]]&&r.globalScore>=s&&r.totalVisible>=this._config.trackedNumKeypsThs?(t=this.computePoseSync(this._rightFootState,"RIGHT_FOOT"),this._rightFootState=iN.Tracking,t>o&&(this._rightFootState=iN.Detection)):this._rightFootState=iN.Detection;var d=this.detectFeetSync(e);this._initShape=d.refinedFeatures,a=fN(d.scores,"LEFT_FOOT",this._config.detectScoreThs),r=fN(d.scores,"RIGHT_FOOT",this._config.detectScoreThs);var f=!1;if(!this._fastMovements_R&&null!=this._cnnOutputDataInvMask){var m=NN(this._cnnOutputDataInvMask,this._footDetectorShape,!1);m[0];var g=fN(_=m[1],"LEFT_FOOT",this._config.detectScoreThs),y=fN(_,"RIGHT_FOOT",this._config.detectScoreThs);r.globalScore>a.globalScore&&r.globalScore>y.globalScore+.1&&g.globalScore>y.globalScore&&(f=!0)}f&&r.globalScore>this._config.detectScoreThs?(this.invertFoot(),this._rightFootRecShape=d.refinedFeatures,this._rightFootState=iN.Detected):a.globalScore>=this._config.detectScoreThs&&(this._leftFootRecShape=d.refinedFeatures,this._leftFootState=iN.Detected)}else if(this._leftFootState!==iN.Detection&&this._rightFootState===iN.Detection){var b=this.trackFootFeaturesSync(e,this._leftFootState,this._leftFootState==iN.Detected?this._initShape:this._leftFootRecShape,this._leftFootVis,this._leftFootOcclusions,"LEFT_FOOT");if(this._leftFootRecShape=b.refinedFeatures,this._leftFootOcclusions=b.occlusions,a=fN(b.scores,"LEFT_FOOT",this._config.validTrackedKeypThs),this._leftFootVis=a.visibilty,s=this._config.trackScoreThs,o=this._reproj_t,this._fastMovements_L&&(o=this._reproj_fast_t),u=gN(this._leftFootRecShape.length/2,"LEFT_FOOT"),this._leftFootVis[u[0]]&&this._leftFootVis[u[1]]&&a.globalScore>=s&&a.totalVisible>=this._config.trackedNumKeypsThs?(t=this.computePoseSync(this._leftFootState,"LEFT_FOOT"),this._leftFootState=iN.Tracking,t>o&&(this._leftFootState=iN.Detection)):this._leftFootState=iN.Detection,d=this.detectFeetSync(e),this._initShape=d.refinedFeatures,r=fN(d.scores,"RIGHT_FOOT",this._config.detectScoreThs),a=fN(d.scores,"LEFT_FOOT",this._config.detectScoreThs),f=!1,!this._fastMovements_L&&null!=this._cnnOutputDataInvMask){var _,x=NN(this._cnnOutputDataInvMask,this._footDetectorShape,!1);x[0],g=fN(_=x[1],"LEFT_FOOT",this._config.detectScoreThs),y=fN(_,"RIGHT_FOOT",this._config.detectScoreThs),a.globalScore>r.globalScore&&a.globalScore>g.globalScore+.1&&y.globalScore>g.globalScore&&(f=!0)}f&&a.globalScore>this._config.detectScoreThs?(this.invertFoot(),this._leftFootRecShape=d.refinedFeatures,this._leftFootState=iN.Detected):r.globalScore>=this._config.detectScoreThs&&(this._rightFootRecShape=d.refinedFeatures,this._rightFootState=iN.Detected)}else if(this._leftFootState===iN.Detection||this._rightFootState===iN.Detection){var v=this.detectFeetSync(e);if(this._initShape=v.refinedFeatures,a=fN(v.scores,"LEFT_FOOT",this._config.detectScoreThs),r=fN(v.scores,"RIGHT_FOOT",this._config.detectScoreThs),a.globalScore>=this._config.detectScoreThs&&(this._leftFootState=iN.Detected),r.globalScore>=this._config.detectScoreThs&&(this._rightFootState=iN.Detected),this._rightFootState!=iN.Detection&&this._leftFootState!=iN.Detection&&this.bothFeetSamePlaceInit()&&(this._rightFootState==iN.Detected?this._rightFootState=iN.Detection:this._leftFootState=iN.Detection),this._leftFootState==iN.Detected||this._rightFootState==iN.Detected){this._leftFootRecShape=v.refinedFeatures,this._rightFootRecShape=v.refinedFeatures,this._fastMovements_L=!0,this._fastMovements_R=!0;var w=this._poseModule.cwrap("xzimgMatchRecKeypsInit","number",["number"]);null==this._hptrImageBuffer&&(this._hptrImageBuffer=this._poseModule._malloc(e.width*e.height*4)),TN(this._poseModule,e,this._hptrImageBuffer);var T=kN(this._poseModule,this._hptrImageBuffer,e.width,e.height);w(T),this._poseModule._free(T)}}this._leftFootState===iN.Detection&&(this._pose_L=new MN(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0]))),this._rightFootState==iN.Detection&&(this._pose_R=new MN(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0]))),this._pose_R.setTrackingState(this._rightFootState),this._pose_R.type=0,this._poseManager_R.setPose(this._pose_R),this._pose_L.setTrackingState(this._leftFootState),this._pose_L.type=1,this._poseManager_L.setPose(this._pose_L)},e.prototype.detectFeetSync=function(e){var t,n,r,a,s=function(e,t){var n,r;return{crop:e>t?[(r=0)/t,(n=(e-t)/2)/e,1,(e-n)/e]:[(r=(t-e)/2)/t,(n=0)/e,(t-r)/t,1],deltaY:r,deltaX:n}}(this._currentWidth,this._currentHeight),o=s.crop,i=s.deltaY,u=s.deltaX,l=Li(e),c=bi(l,"float32"),p=Fu(c,[1,this._currentHeight,this._currentWidth,3]),h=pd.cropAndResize(p,[o],[0],[this._footDetectorConfig.inHeight,this._footDetectorConfig.inWidth]),d=Ul(255),f=ou(h,d),m=null;if(this._footToDetect==$N.Both&&(this._leftFootState===iN.Tracking||this._rightFootState===iN.Tracking)){var g=function(e,t,n,r,a,s,o,i){for(var u=e.length/2,l=new Float32Array(2*u),c=0;c<u;c++)l[c]=(e[c]-a)/o,l[c+u]=(e[c+u]-r)/s;for(var p=dN(l,i),h=p[0],d=p[1],f=p[2]-h,m=p[3]-d,g=p[6]-h,y=p[7]-d,b=f*f+m*m,_=g*g+y*y,x=new Float32Array(n*t),v=0;v<t;v++)for(var w=0;w<n;w++){var T=w-h,k=v-d,I=T*f+k*m,S=T*g+k*y;I>0&&S>0&&I<b&&S<_||(x[v*n+w]=1)}return x}(this._leftFootState===iN.Tracking?this._leftFootRecShape:this._rightFootRecShape,this._footDetectorConfig.inHeight,this._footDetectorConfig.inWidth,i,u,(this._currentHeight-2*i)/this._footDetectorConfig.inWidth,(this._currentWidth-2*u)/this._footDetectorConfig.inHeight,this._leftFootState===iN.Tracking?"LEFT_FOOT":"RIGHT_FOOT"),y=Xp(g,"float32");m=Fu(y,[1,this._footDetectorConfig.inHeight,this._footDetectorConfig.inWidth,1]),y.dispose()}var b=this._tfFootDetector.predict(f);if(null!=m){var _=fc(1,m),x=iu(b,_);this._cnnOutputDataInvMask=x.dataSync(),_.dispose(),x.dispose();var v=iu(b,m);b.dispose(),b=v,m.dispose()}var w,T,k=null!==(n=null==b?void 0:b.shape[3])&&void 0!==n?n:this._footDetectorConfig.outChannels,I=null!==(r=null==b?void 0:b.shape[1])&&void 0!==r?r:this._footDetectorConfig.outHeight,S=null!==(a=null==b?void 0:b.shape[2])&&void 0!==a?a:this._footDetectorConfig.outWidth;w=(t=NN(b.dataSync(),[1,I,S,k],!1))[0],T=t[1];var E=this._bufferKeypsDet/4;this._poseModule.HEAPF32.subarray(E,E+2*k).set(w),l.dispose(),c.dispose(),d.dispose(),h.dispose(),f.dispose(),p.dispose(),b.dispose();var N=Math.min(this._currentWidth,this._currentHeight),C=N/this._footDetectorConfig.inWidth,A=N/this._footDetectorConfig.inHeight;return this._simToImage_Det=function(e,t,n,r){var a=new Float32Array(6);return a[0]=r,a[1]=0,a[2]=t,a[3]=0,a[4]=n,a[5]=e,a}(i,u,A,C),{refinedFeatures:mN(w,this._simToImage_Det,!1,b.shape[1]),scores:T}},e.prototype.trackFootFeaturesSync=function(e,t,n,r,a,s){var o,i,u,l,c="LEFT_FOOT"==s?this._simToImage_L:this._simToImage_R;if(t!=iN.Detected){var p=Int32Array.from(r);this._activeIds.length>0&&(p.forEach((function(e,t){p[t]=0})),this._activeIds.forEach((function(e){p[e]=1})),r.forEach((function(e,t){0==e&&(p[t]=0)})),a&&a.forEach((function(e,t){e>0&&(r[t]=0)}))),i=(o=IN(this._poseModule,e,this._hptrImageBuffer,n,p))[0],u=o[1],l=o[2],Math.sqrt(u[2]*u[2]+u[3]*u[3])>10?"LEFT_FOOT"==s?this._fastMovements_L=!0:this._fastMovements_R=!0:"LEFT_FOOT"==s?this._fastMovements_L=!1:this._fastMovements_R=!1;var h=EN(n,i,l);"LEFT_FOOT"==s?this._pose_L.translate(h[0]*this._pose_L.t()[2]/this._fx,h[1]*this._pose_L.t()[2]/this._fy,0):"RIGHT_FOOT"==s&&this._pose_R.translate(h[0]*this._pose_R.t()[2]/this._fx,h[1]*this._pose_R.t()[2]/this._fy,0);for(var d=i.length/2,f=0;f<d;f++)i[f]=n[f]+h[0],i[f+d]=n[f+d]+h[1]}else i=n;c=_N(i,r,this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight,null,s);var m=new ImageData(this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight);m=bN(e,m,c),this._debug&&(this._debugInitialized=!0,this._debugImage=m,function(e,t,n,r){for(var a=new Uint8ClampedArray(e*t*4),s=e*t,o=0;o<s;o++){var i=4*o,u=4*o;a[u+0]=1*r[i+0],a[u+1]=1*r[i+1],a[u+2]=1*r[i+2],a[u+3]=255}new ImageData(a,t,e)}(this._footFeaturesConfig.inHeight,this._footFeaturesConfig.inWidth,0,m));var g=this.detectKeypointsSync([m],[s]),y=mN(g.coordinates[0],c,"LEFT_FOOT"==s,this._footFeaturesConfig.outHeight);return"LEFT_FOOT"==s?this._simToImage_L=c:this._simToImage_R=c,{refinedFeatures:y,scores:g.scores[0],occlusions:g.occlusions[0]}},e.prototype.detectKeypointsSync=function(e,t){for(var n=[],r=[],a=[],s=[],o=0,i=null,u=0,l=e;u<l.length;u++){var c=l[u],p=Li(c);s.push(p);var h=bi(p,"float32");s.push(h);var d=Fu(h,[1,this._footFeaturesConfig.inHeight,this._footFeaturesConfig.inWidth,3]);s.push(d);var f=Ul(255),m=ou(d,f);s.push(m),"LEFT_FOOT"==t[o]&&(m=vp(m,1),s.push(m)),i?(i=Pu([i,m]),s.push(i)):i=m,o+=1}if(null!=i){var g=[];if(this._footFeaturesConfig.numOutputs&&1!=this._footFeaturesConfig.numOutputs)for(var y=0,b=g=this._tfFootFeatures.predict(i);y<b.length;y++){var _=b[y];s.push(_)}else{var x=this._tfFootFeatures.predict(i);s.push(x),g.push(x)}for(var v=0,w=0,T=g;w<T.length;w++){x=T[w];for(var k=[],I=[],S=0,E=th(x,0);S<E.length;S++){var N=E[S];s.push(N);var C=ql(N,0);s.push(C),k.push(N.dataSync()),I.push(C.shape)}if(this._footFeaturesConfig.outputNames&&"heatmaps"!=this._footFeaturesConfig.outputNames[v]){if(this._footFeaturesConfig.outputNames&&"coordinates"==this._footFeaturesConfig.outputNames[v])for(P=0;P<k.length;P++){for(var A=I[P][1]/2,R=new Float32Array(2*A),$=this._footFeaturesConfig.inHeight/2,M=this._footFeaturesConfig.inWidth/2,F=0;F<A;F++)R[F]=(k[P][F]+1)*M,R[F+A]=(k[P][F+A]+1)*$;n.push(R)}else if(this._footFeaturesConfig.outputNames&&"scores"==this._footFeaturesConfig.outputNames[v])for(P=0;P<k.length;P++){var O=I[P][1],D=new Float32Array(O);for(F=0;F<O;F++)D[F]=1/(1+Math.exp(-k[P][F]));r.push(D)}else if(this._footFeaturesConfig.outputNames&&"occlusions"==this._footFeaturesConfig.outputNames[v])for(P=0;P<k.length;P++){O=I[P][1];var L=new Float32Array(O);for(F=0;F<O;F++)L[F]=1/(1+Math.exp(-k[P][F]));a.push(L)}}else for(var P=0;P<k.length;P++){var B;B=this._useWasmForHeatmaps?CN(this._poseModule,I[P],k[P],"LEFT_FOOT"==t[P]?this._bufferHeatmaps_L:this._bufferHeatmaps_R,"LEFT_FOOT"==t[P]?this._bufferKeypsTrack_L:this._bufferKeypsTrack_R,this._bufferFeatureScores):NN(k[P],I[P],!1),n.push(B[0]),r.push(B[1]);var U=I[P][1]*I[P][2]*I[P][3],z="LEFT_FOOT"==t[P]?this._bufferHeatmaps_L/4:this._bufferHeatmaps_R/4;this._poseModule.HEAPF32.subarray(z,z+U).set(k[P])}v+=1}for(P=0;P<n.length;P++)A=n[P].length,z="LEFT_FOOT"==t[P]?this._bufferKeypsTrack_L/4:this._bufferKeypsTrack_R/4,this._poseModule.HEAPF32.subarray(z,z+2*A).set(n[P])}return s.forEach((function(e){return e.dispose()})),{coordinates:n,scores:r,occlusions:a}},e.prototype.trackBothFeetFeaturesSync=function(e,t,n,r,a,s,o,i,u){var l,c,p;if(t!=iN.Detected&&n!=iN.Detected){var h=r.length/2,d=new Int32Array(2*h);d.set(s),d.set(o,h);var f=null;i&&u&&((f=new Float32Array(2*h)).set(i),f.set(u,h));var m=Int32Array.from(d);this._activeIds.length>0&&(m.forEach((function(e,t){m[t]=0})),this._activeIds.forEach((function(e){m[e]=1,m[e+h]=1})),d.forEach((function(e,t){0==e&&(m[t]=0)})),f&&f.forEach((function(e,t){e>0&&(d[t]=0)})));var g=IN(this._poseModule,e,this._hptrImageBuffer,function(e,t){for(var n=e.length/2,r=t.length/2,a=n+r,s=new Float32Array(e.length+t.length),o=0;o<n;o++)s[o]=e[o],s[o+a]=e[o+n];for(o=0;o<r;o++)s[o+n]=t[o],s[o+a+n]=t[o+r];return s}(r,a),m),y=g[0];g[1];var b=g[2];l=function(e,t,n){var r=new Float32Array(2*t),a=new Float32Array(2*n),s=e.length/2;t+n!=s&&console.log("ERROR (separateShapes): shapes not correct dims");for(var o=0;o<t;o++)r[o]=e[o],r[o+t]=e[o+s];for(o=0;o<n;o++)a[o]=e[o+t],a[o+n]=e[o+s+t];return[r,a]}(y,h,h),c=l[0],p=l[1];var _=b.slice(0,h),x=b.slice(h,2*h),v=SN(this._poseModule,r,c),w=SN(this._poseModule,a,p);Math.sqrt(v[2]*v[2]+v[3]*v[3])>10?this._fastMovements_L=!0:this._fastMovements_L=!1,Math.sqrt(w[2]*w[2]+w[3]*w[3])>10?this._fastMovements_R=!0:this._fastMovements_R=!1;var T=EN(r,c,_);this._pose_L.translate(T[0]*this._pose_L.t()[2]/this._fx,T[1]*this._pose_L.t()[2]/this._fy,0);var k=EN(a,p,x);this._pose_R.translate(k[0]*this._pose_R.t()[2]/this._fx,k[1]*this._pose_R.t()[2]/this._fy,0);for(var I=p.length/2,S=0;S<I;S++)p[S]=a[S]+k[0],p[S+I]=a[S+I]+k[1],c[S]=r[S]+T[0],c[S+I]=r[S+I]+T[1]}else c=r,p=a;this._simToImage_L=_N(c,s,this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight,null,"LEFT_FOOT");var E=new ImageData(this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight);E=bN(e,E,this._simToImage_L),this._simToImage_R=_N(p,o,this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight,null,"RIGHT_FOOT");var N=new ImageData(this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight);N=bN(e,N,this._simToImage_R);var C=this.detectKeypointsSync([E,N],["LEFT_FOOT","RIGHT_FOOT"]),A=mN(C.coordinates[0],this._simToImage_L,!0,this._footFeaturesConfig.outHeight),R=mN(C.coordinates[1],this._simToImage_R,!1,this._footFeaturesConfig.outHeight);return t!=iN.Detected&&(A=pN(A,nN(C.scores[0],this._config.validTrackedKeypThs),c,s,.2)),n!=iN.Detected&&(R=pN(R,nN(C.scores[1],this._config.validTrackedKeypThs),p,o,.2)),{refinedFeatures_L:A,refinedFeatures_R:R,scores_L:C.scores[0],scores_R:C.scores[1],occlusions_L:C.occlusions[0],occlusions_R:C.occlusions[1]}},e.prototype.computePoseSync=function(e,t){var n=this,r=-1,a=this._poseModule.cwrap("xzimgEstimateRigidPose","number",["number","number","number","number","number","number","number","number","number","number","number","number"]);if(e==iN.Detected||e==iN.Tracking){var s=1;e==iN.Detected&&(s=0);var o=1;this._trackHasHeatmaps&&(o=3);var i=3;"LEFT_FOOT"!=t||this._fastMovements_L||(i=1),"RIGHT_FOOT"!=t||this._fastMovements_R||(i=1);var u=new Float32Array(18);"LEFT_FOOT"==t?(u.set(this._pose_L.R()),u.set(this._pose_L.t(),9)):(u.set(this._pose_R.R()),u.set(this._pose_R.t(),9));var l=xN(this._poseModule,u),c="LEFT_FOOT"==t?this._simToImage_L:this._simToImage_R,p=Float32Array.from([1,0,0,0,1,0]);this._trackHasHeatmaps&&(p=Float32Array.from(c.slice(0,6)),"LEFT_FOOT"==t&&(p[2]+=p[1]*(this._footFeaturesConfig.outWidth-1),p[5]+=p[4]*(this._footFeaturesConfig.outHeight-1),p[1]=-p[1],p[4]=-p[4]));var h=xN(this._poseModule,p),d=null,f=null,m=new Float32Array(2*this._activeIds.length),g=new Float32Array(3*this._activeIds.length),y="LEFT_FOOT"==t?this._leftFootRecShape:this._rightFootRecShape,b="LEFT_FOOT"==t?this._leftKeyps3D:this._rightKeyps3D,_=y.length/2;this._activeIds.length>0?(this._activeIds.forEach((function(e,t){m[t]=y[e],m[t+n._activeIds.length]=y[e+_]})),d=xN(this._poseModule,m),this._activeIds.forEach((function(e,t){g[3*t]=b[3*e],g[3*t+1]=b[3*e+1],g[3*t+2]=b[3*e+2]})),f=xN(this._poseModule,g),_=this._activeIds.length):(d=this._trackHasHeatmaps?"LEFT_FOOT"==t?this._bufferKeypsTrack_L:this._bufferKeypsTrack_R:xN(this._poseModule,y),f=xN(this._poseModule,"LEFT_FOOT"==t?this._leftKeyps3D:this._rightKeyps3D)),-1==(r=a("LEFT_FOOT"==t?this._bufferHeatmaps_L:this._bufferHeatmaps_R,this._footFeaturesConfig.outHeight,this._footFeaturesConfig.outWidth,_,0,h,d,f,s,o,i,l))&&(r=1e4),"LEFT_FOOT"==t?this._pose_L=new MN(new Float32Array(this._poseModule.HEAPF32.buffer,l,9),new Float32Array(this._poseModule.HEAPF32.buffer,l+9*this._float_size,3)):this._pose_R=new MN(new Float32Array(this._poseModule.HEAPF32.buffer,l,9),new Float32Array(this._poseModule.HEAPF32.buffer,l+9*this._float_size,3)),h&&this._poseModule._free(h),d&&!this._trackHasHeatmaps&&this._poseModule._free(d),f&&this._activeIds.length>0&&this._poseModule._free(f)}return r},e.prototype.invertFoot=function(){var e,t,n,r,a,s,o;e=[this._rightFootRecShape,this._leftFootRecShape],this._rightFootRecShape=e[0],this._rightFootRecShape=e[1],t=[this._pose_L,this._pose_R],this._pose_R=t[0],this._pose_L=t[1],n=[this._poseManager_L,this._poseManager_R],this._poseManager_R=n[0],this._poseManager_L=n[1],r=[this._simToImage_R,this._simToImage_L],this._simToImage_L=r[0],this._simToImage_R=r[1],a=[this._rightFootState,this._leftFootState],this._leftFootState=a[0],this._rightFootState=a[1],s=[this._rightFootVis,this._leftFootVis],this._leftFootVis=s[0],this._rightFootVis=s[1],o=[this._bufferHeatmaps_L,this._bufferHeatmaps_R],this._bufferHeatmaps_R=o[0],this._bufferHeatmaps_L=o[1]},e.prototype.dst=function(e,t,n,r){return Math.sqrt((e-n)*(e-n)+(t-r)*(t-r))},e.prototype.bothFeetSamePlaceInit=function(){var e=this._initShape.length/2,t=0;return t+=this.dst(this._initShape[0],this._initShape[e],this._initShape[4],this._initShape[4+e]),t+=this.dst(this._initShape[1],this._initShape[1+e],this._initShape[3],this._initShape[3+e]),(t+=this.dst(this._initShape[2],this._initShape[2+e],this._initShape[5],this._initShape[5+e]))/3<this.dst(this._initShape[0],this._initShape[e],this._initShape[2],this._initShape[2+e])/5},e.prototype.bothFeetSamePlace=function(){var e=dN(this._leftFootRecShape,"LEFT_FOOT"),t=e[0],n=e[1],r=e[2],a=e[3],s=e[4],o=e[5],i=e[6],u=e[7],l=dN(this._rightFootRecShape,"RIGHT_FOOT"),c=l[0],p=l[1],h=l[2],d=l[3],f=l[4],m=l[5],g=l[6],y=l[7],b=this.dst(t,n,i,u)/8;return this.dst(t,n,c,p)<b&&this.dst(r,a,h,d)<b&&this.dst(s,o,f,m)<b&&this.dst(i,u,g,y)<b},e.prototype.getKeypoints_L=function(){return this._leftFootRecShape},e.prototype.getKeypoints_R=function(){return this._rightFootRecShape},e.prototype.getScores_L=function(){return this._leftFootVis},e.prototype.getScores_R=function(){return this._rightFootVis},e.prototype.getOcclusion_L=function(){return this._leftFootOcclusions},e.prototype.getOcclusion_R=function(){return this._rightFootOcclusions},e}(),PN={modelFilename:"",featuresFilename:"",objContainer:"",fovY:50,detectScoreThs:.2,trackScoreThs:.4,geometryToDetect:"LAMBORGHINI",filteringLevel:2,filteringShift:.5,validDetectedKeypThs:.2,validTrackedKeypThs:.2,detectNumKeypsThs:3,trackedNumKeypsThs:3,normMode:"",reprojThs:25,activeIds:new Int32Array,computePose:!0,useWasmBackend:!0,subTrackerSymmetric:!1},BN=function(){function e(e,t){this.x=e,this.y=t}return e.prototype.Dist=function(e){return Math.sqrt((e.x-this.x)*(e.x-this.x)+(e.y-this.y)*(e.y-this.y))},e}();function UN(e,t){var n=Math.cos(t),r=Math.sin(t);return new Float32Array([n*e[0]-r*e[1],r*e[0]+n*e[1]])}function zN(e,t,n,r,a,s,o,i){void 0===i&&(i=[""]);for(var u=[],l=[],c=[],p=[],h=0,d=null,f=0,m=o;f<m.length;f++){var g=m[f],y=Li(g);p.push(y);var b=bi(y,"float32");p.push(b);var _=Fu(b,[1,t.inHeight,t.inWidth,3]);p.push(_);var x=Ul(255),v=ou(_,x);p.push(v),"left_right"!=i[h]&&"up_down"!=i[h]||(v=vp(v,"left_right"==i[h]?2:1),p.push(v)),d?(d=Pu([d,v]),p.push(d)):d=v,h+=1}if(null!=d){var w=[];if(t.numOutputs&&1!=t.numOutputs)for(var T=0,k=w=e.predict(d);T<k.length;T++){var I=k[T];p.push(I)}else{var S=e.predict(d);p.push(S),w.push(S)}for(var E=0,N=0,C=w;N<C.length;N++){S=C[N];for(var A=[],R=[],$=0,M=th(S,0);$<M.length;$++){var F=M[$];p.push(F);var O=ql(F,0);p.push(O),A.push(F.dataSync()),R.push(O.shape)}if(t.outputNames&&"heatmaps"!=t.outputNames[E]){if(t.outputNames&&"coordinates"==t.outputNames[E])for(H=0;H<A.length;H++){for(var D=R[H][1]/2,L=new Float32Array(2*D),P=t.inHeight/2,B=t.inWidth/2,U=0;U<D;U++)L[U]=(A[H][U]+1)*B,L[U+D]=(A[H][U+D]+1)*P;u.push(L)}else if(t.outputNames&&"scores"==t.outputNames[E])for(H=0;H<A.length;H++){var z=R[H][1],V=new Float32Array(z);for(U=0;U<z;U++)V[U]=A[H][U];l.push(V)}else if(t.outputNames&&"occlusions"==t.outputNames[E])for(H=0;H<A.length;H++){z=R[H][1];var W=new Float32Array(z);for(U=0;U<z;U++)W[U]=A[H][U];c.push(W)}}else for(var H=0;H<A.length;H++){var G;G=n?CN(n,R[H],A[H],r[H],a[H],s[H]):NN(A[H],R[H],!0),u.push(G[0]),l.push(G[1])}E+=1}}return p.forEach((function(e){return e.dispose()})),{coordinates:u,scores:l,occlusions:c}}function VN(e){return e==ON.UpperBody||e==ON.FullBody}!function(e){e.Lamborghini="LAMBORGHINI",e.Horse="HORSE",e.WatsonCan="WATSON-CAN",e.MartellBottle="MARTELL-BOTTLE",e.Necklace="NECKLACE",e.Wrist="WRIST",e.Hand="HAND",e.UpperBody="UPPER-BODY",e.FullBody="FULL-BODY",e.CanKivisense="CAN-KIVISENSE",e.ToyTruck="TOY-TRUCK",e.Chivas="CHIVAS",e.ChivasLarge="CHIVAS-LARGE",e.Lion="LION",e.Bartender="BARTENDER",e.Wcbottle="WCBOTTLE",e.EQA="EQA",e.Face="FACE"}(ON||(ON={}));var WN="config.json",HN=function(){function e(){this._initialized=!1,this._nonRigidInitialized=!1,this._bufSubTrackerHmaps=null,this._bufSubTrackerHmapsSym=null,this._subTrackerCropKeyps=[],this._currentWidth=0,this._currentHeight=0,this._trackingState=iN.Detection,this._denseVertices=new Float32Array(0),this._bsCoefs=new Float32Array(0),this._geometryType=ON.Lamborghini,this._resetPose=!1,this._float_size=4,this._int_size=4,this._bufferHeatmaps=null,this._bufferKeypsDet=null,this._bufferFeatureScores=null,this._bufInOutPose=null,this._bufKeyps3D=null,this._bufMirroredKeyps3D=null,this._bufferKeypsTrack=null,this._bufferPdmModel=null,this._bufDenseVertices3D=null,this._bufModelTriangles=null,this._reprojError=0,this._hptrImageBuffer=null,this._fastMvt=!1,this._flipMode="",this._debug=!1,this._debugInitialized=!1,this.mean_t=0}return e.prototype.getDebugImage=function(){return this._debugInitialized?this._debugImage:null},e.prototype.isDetected=function(){return this._trackingState===iN.Tracking},e.prototype.getStatus=function(){return this._trackingState},e.prototype.getPosition=function(){var e=this._poseManager.getInterpolatedPose();return e?e.getPosition():null},e.prototype.getRotation=function(){var e=this._poseManager.getInterpolatedPose();return e?e.getRotation():null},e.prototype.getPose=function(){return this._pose},e.prototype.getVisibility=function(){return this._visibility},e.prototype.getKeypoints=function(){return this._keyps2D},e.prototype.getNumSubTracker=function(){return this._subTrackerKeyps?this._subTrackerKeyps.length:0},e.prototype.getSubTrackerKeyps=function(e){return this._subTrackerKeyps&&this._subTrackerKeyps.length>e?this._subTrackerKeyps[e]:new Float32Array(0)},e.prototype.getSubTrackerVisibility=function(e){return this._subTrackerScores&&this._subTrackerScores.length>e?this._subTrackerScores[e]:new Float32Array(0)},e.prototype.getReprojKeypoints=function(){return this._reprojKeyps2D},e.prototype.getKeypoints3D=function(){return this._keyps3D},e.prototype.getDenseKeypoints3D=function(){return this._denseVertices},e.prototype.getBlendShape=function(){return this._bsCoefs},e.prototype.getInterpolatedPose=function(){return this._poseManager.getInterpolatedPose()},e.prototype.isInitialized=function(){return this._initialized},e.prototype.isMirrored=function(){return""!=this._flipMode},e.prototype.getReprojError=function(){return this._reprojError},e.prototype.initialize=function(e,n,r){var o,i,u,l,c;return a(this,void 0,void 0,(function(){var a,p,h,d,f,m,g,y,b,_,x,v,T,k,I,S,E,N,C,A,R,$=this;return s(this,(function(s){switch(s.label){case 0:if(null==e)throw"Invalid parameter";return this._config=n?t(t({},PN),n):PN,(null===(o=null==n?void 0:n.wasmBackend)||void 0===o?void 0:o.enable)?(qE({"tfjs-backend-wasm.wasm":null===(i=n.wasmBackend)||void 0===i?void 0:i.tfjsBackendWasmPath,"tfjs-backend-wasm-simd.wasm":null===(u=n.wasmBackend)||void 0===u?void 0:u.tfjsBackendWasmSimdPath,"tfjs-backend-wasm-threaded-simd.wasm":null===(l=n.wasmBackend)||void 0===l?void 0:l.tfjsBackendWasmThreadedPath}),[4,Ii("wasm")]):[3,2];case 1:return s.sent(),[3,3];case 2:Ii("webgl"),s.label=3;case 3:return this.release(),this._videoManager=e,this._poseManager=new FN(this._videoManager.getNbFramesDelay()),this._poseManager.setInterpolation(this._config.filteringShift),this._poseManager.setFilteringLevel(this._config.filteringLevel),this._geometryType=function(e){if(e){if("LAMBORGHINI"===e)return ON.Lamborghini;if("HORSE"===e)return ON.Horse;if("WATSON-CAN"===e)return ON.WatsonCan;if("MARTELL-BOTTLE"===e)return ON.MartellBottle;if("NECKLACE"===e)return ON.Necklace;if("WRIST"===e)return ON.Wrist;if("HAND"===e)return ON.Hand;if("UPPER-BODY"===e)return ON.UpperBody;if("FULL-BODY"===e)return ON.FullBody;if("CAN-KIVISENSE"===e)return ON.CanKivisense;if("TOY-TRUCK"===e)return ON.ToyTruck;if("CHIVAS"===e)return ON.Chivas;if("CHIVAS-LARGE"===e)return ON.ChivasLarge;if("LION"===e)return ON.Lion;if("BARTENDER"===e)return ON.Bartender;if("WCBOTTLE"===e)return ON.Wcbottle;if("EQA"===e)return ON.EQA;if("FACE"===e)return ON.Face}return ON.Lamborghini}(this._config.geometryToDetect),a=new ie(0),p=G(yk({locateFile:function(e,t){return $._config.poseEstimationWasmFilename||t+e}})).pipe(me((function(){return a.next(1)}))),h=uk(this._config.modelFilename,WN),d=h.model$,f=h.progress$,m=uk(this._config.featuresFilename,WN),g=m.model$,y=m.progress$,_=new ie(0),"string"==typeof this._config.objContainer&&""===this._config.objContainer?(b=j({vertices:new Float32Array,uvs:new Float32Array,faces:new Uint16Array}),_.next(1)):(x=AN(this._config.objContainer,!1),v=x.model$,T=x.progress$,b=v,_=T),k=new ie(0),S="",this._config.pdmContainer?(E=this._config.pdmContainer,"string"==typeof this._config.pdmContainer&&(N=null===(c=this._config.pdmContainer)||void 0===c?void 0:c.replace(/\\/g,"/"),S=null==N?void 0:N.substring(N.lastIndexOf("/")+1,N.lastIndexOf("."))),I=function(e,t,n){return"string"==typeof e?Sw({url:e,method:"GET",responseType:"arraybuffer",async:!0,progressSubscriber:new w((function(e){return n.next(.5*e.loaded/e.total)}),(function(e){}),(function(){return n.next(.5)}))}).pipe(ue(2),pe((function(e){return j(uT(new Uint8Array(e.response)))})),pe((function(r){return r[t]?(n.next(1),j(r[t])):Q("File ".concat(t," not found in ").concat(e))}))):j(uT(new Uint8Array(e))).pipe(pe((function(e){return e[t]?(n.next(1),j(e[t])):Q("File ".concat(t," not found"))})))}(E,this._config.pdmName?this._config.pdmName:S+".bin",k)):(k.next(1),I=j(null)),new ie(0),this._config.subTrackerFilename&&""!=this._config.subTrackerFilename?(A=uk(this._config.subTrackerFilename,WN),C=A.model$,A.progress$):C=j(null),R=V([a,f,k,y,_]).pipe(K((function(e){return e.reduce((function(t,n){return t+n/e.length}),0)})),K((function(e){return r&&r(e)}))).subscribe(),[4,uw({poseModule:p,detectorModel:d,pdmModel:I,trackerModel:g,geometryObjModel:b,subTracker:C}).pipe(K((function(e){var t;$._poseModule=e.poseModule,$._geometryObjModel=e.geometryObjModel,$._tfKeypointsDetector=e.detectorModel.graphModel,$._detectorConfig=e.detectorModel.config,$._tfKeypointsTracker=e.trackerModel.graphModel,$._trackerConfig=e.trackerModel.config;var n=Nc([1,$._detectorConfig.inHeight,$._detectorConfig.inWidth,3]),r=$._tfKeypointsDetector.predict(n);$._detectorOutDims=r.shape,r.dispose(),$._detectorConfig.inHeight===$._trackerConfig.inHeight&&$._detectorConfig.inWidth===$._trackerConfig.inWidth||(n.dispose(),n=Nc([1,$._trackerConfig.inHeight,$._trackerConfig.inWidth,3])),(r=$._tfKeypointsTracker.predict(n))instanceof Array?($._debug&&r.forEach((function(e){return console.log(e.shape)})),r.forEach((function(e){return e.dispose()})),$._trackerOutDims=[1,$._trackerConfig.outHeight,$._trackerConfig.outWidth,$._trackerConfig.outChannels]):($._trackerOutDims=r.shape,r.dispose()),n.dispose(),$._debug&&(console.log($._detectorConfig),console.log($._trackerConfig),console.log("(DEBUG) XZIMG BACKEND",Si()),console.log("_trackerOutDims",$._trackerOutDims)),$._activeIds=$._config.activeIds,$._trackHasHeatmaps=JE($._trackerConfig),t=function(e,t,n){if("NECKLACE"==t)return[r=new Float32Array([-1.982586,1.762905,-1.256474,-1.4803,.73489,-.059477,-.863695,.091572,.505433,-179e-6,-.518833,.632376,.863894,.089272,.503284,1.479377,.729931,-.063135,1.981941,1.7644,-1.255762]),new Float32Array([-1.982586,1.762905,-1.256474,1.981941,1.7644,-1.255762])];if("CAN-KIVISENSE"==t)return[r=new Float32Array([.11749199777841568,.3616040050983429,-.5216580033302307,.3387719988822937,.1726129949092865,-.5216580033302307,.059477999806404114,-.37553098797798157,-.5216580033302307,-.1752689927816391,-.3439840078353882,.5761319994926453,.3802120089530945,-0,-.3024890124797821,.3387719988822937,-.1726129949092865,-.3024890124797821,-.1726129949092865,-.3387719988822937,-.3024890124797821,-.3616029918193817,-.11749199777841568,-.3024890124797821,-.11749199777841568,.3616040050983429,-.3024890124797821,.3802120089530945,-0,-.08331900089979172,.22348299622535706,-.3075979948043823,-.08331900089979172,-.3075979948043823,-.22348299622535706,-.08331900089979172,.37553098797798157,-.059477999806404114,.1358499974012375,-0,-.3802120089530945,.1358499974012375,-.37553098797798157,-.059477999806404114,.1358499974012375,.059477999806404114,.37553098797798157,.1358499974012375,.3616040050983429,.11749199777841568,.3550190031528473,-.3616029918193817,-.11749199777841568,.3550190031528473,-.3616029918193817,.11749199777841568,.3550190031528473,-.11749199777841568,.3616029918193817,.3550190031528473]),new Float32Array([0,0,-.5991089940071106,0,-0,.6023629903793335])];if("TOY-TRUCK"==t)return[r=new Float32Array([-.11474676430225372,.06819115579128265,.12616248428821564,-3.9706208099232754e-7,-.14720511436462402,.28020843863487244,5.515660461696825e-8,-.3098587989807129,.08606547862291336,-.18071073293685913,-.27267926931381226,-.012890318408608437,3.1216436013892235e-7,.39625027775764465,.03189631924033165,.23052667081356049,.24702677130699158,.002463694429025054,.1103515625,.2759860157966614,.15902937948703766,.18071091175079346,-.27267909049987793,-.012890467420220375,-.23046159744262695,-.11318685114383698,.0017448731232434511,.23046180605888367,-.1131867840886116,.0017446735873818398,-.1103513240814209,.275985985994339,.15902943909168243,.22978469729423523,.383583128452301,-.09141343832015991,-.22978472709655762,.38358309864997864,-.09141325950622559,-.23052656650543213,.247026726603508,.002463878598064184,.11429085582494736,.06870604306459427,.12790152430534363,.11895161867141724,-.05556913837790489,.37969091534614563,.11927806586027145,.1806230992078781,.373945027589798,-.1189512312412262,-.05556917190551758,.3796910345554352,-.11927773058414459,.18062305450439453,.3739452064037323]),new Float32Array([5.515660461696825e-8,-.3098587989807129,.08606547862291336,3.1216436013892235e-7,.39625027775764465,.03189631924033165])];if("CHIVAS"==t)return[r=new Float32Array([-3.1930644239785977e-10,-15140265077207005e-22,5.86190128326416,0,-.9621832966804504,1.9865937232971191,1.1873104572296143,-.9285097718238831,.9833493232727051,1.1932897567749023,-.9253148436546326,-1.3412771224975586,0,.9153332114219666,2.9489502906799316,-1.5160919427871704,.8744217157363892,.3604915142059326,-3.4059355336069075e-9,.9318456053733826,.3808324337005615,0,.9403911828994751,1.5472331047058105,.8038088083267212,-.9315917491912842,-.4920954704284668,1.5160919427871704,.8744216561317444,.3604915142059326,-2.058072090148926,-.06387438625097275,-2.1172304153442383,2.0580718517303467,-.06387437880039215,-2.1172304153442383,1.1926252841949463,.9239217042922974,-.5218658447265625,-4.4702903601034905e-9,-.9262475371360779,2.8632278442382812,-.02674211747944355,-1.5987444257348216e-8,-3.3316898345947266,-1.3472687005996704,-.9158325791358948,.9859023094177246,1.6359063386917114,-.8202042579650879,-2.4852395057678223,-1.6359063386917114,-.8202041983604431,-2.4852395057678223,-1.2821598052978516,-.9170172810554504,-1.34637451171875,-1.2809302806854248,-.9167184233665466,-.529242992401123,-2.0578272342681885,-.06386483460664749,1.5451469421386719,1.6359063386917114,.8202039003372192,-2.485239267349243,-1.5809047222137451,.8463804721832275,-2.4669992923736572,.7743757367134094,-.04055686667561531,3.7609105110168457,-1.099993348121643,.9303679466247559,-1.3362138271331787,1.0999937057495117,.9303681254386902,-1.3362138271331787,-1.2809303998947144,.9167175889015198,-.529242753982544,-.7743757367134094,-.040556877851486206,3.760910987854004,2.0578272342681885,-.06386483460664749,1.5451469421386719]),new Float32Array([-.02674211747944355,-1.5987444257348216e-8,-3.3316898345947266,-3.1930644239785977e-10,-15140265077207005e-22,5.86190128326416])];if("CHIVAS-LARGE"==t)return[r=new Float32Array([-.7353339195251465,-9.039938504429301e-7,2.8790359497070312,.7353339195251465,-9.039938504429301e-7,2.8790359497070312,-1.0241641998291016,-1.0241650342941284,2.1618540287017822,1.1196224689483643,-.9188478589057922,2.1618540287017822,.14197710156440735,-1.4414118528366089,2.1618540287017822,-.14197710156440735,1.4414103031158447,2.1618545055389404,-.5879112482070923,.057907234877347946,4.713740348815918,.5879112482070923,.057907234877347946,4.713740348815918,.06999345868825912,.0023226356133818626,-2.3130407333374023,0,-.07499408721923828,6.051614284515381,.0008376236073672771,1.707755446434021,-1.6613836288452148,-1.3236799240112305,1.0878145694732666,-.10835576057434082,-1.086346983909607,-1.323068618774414,-.10257232189178467,1.3245174884796143,1.0878145694732666,-.10835576057434082,1.2116090059280396,-1.2100292444229126,-.10835611820220947,.8094201683998108,1.5145108699798584,.6681584119796753,-.953505277633667,1.427893042564392,.6681584119796753,-1.0888724327087402,-1.3264672756195068,.6710498332977295,1.2140388488769531,-1.2132492065429688,.6681579351425171,.49678289890289307,-1.6338136196136475,-.8848701119422913,.00010470295092090964,1.7187724113464355,1.0564154386520386,1.0838285684585571,-1.3177416324615479,-1.2731270790100098,1.0838285684585571,1.3218059539794922,-1.2731266021728516,-1.0823626518249512,1.3218059539794922,-1.2731266021728516,-.9479852914810181,-1.4177916049957275,-1.2630056142807007,.3440423905849457,-.6436600685119629,3.901371479034424,-.46299880743026733,-.5641732215881348,3.901371479034424]),new Float32Array([.06999345868825912,.0023226356133818626,-2.3130407333374023,0,-.07499408721923828,6.051614284515381])];if("LION"==t)return[r=new Float32Array([-.0022359604481607676,-.951945424079895,2.026939868927002,-.448139488697052,-.6012729406356812,-1.6381982564926147,-.5041450262069702,.4640916585922241,-1.7428531646728516,.5572898387908936,.4562094509601593,-1.7489975690841675,.4558115005493164,-.6014943718910217,-1.639726161956787,-.5527711510658264,-.9193709492683411,3.0056838989257812,.5723921656608582,-.9076480865478516,3.0084033012390137,.5884838104248047,.0083160400390625,1.280758261680603,-.6188563108444214,-.009009452536702156,1.2967206239700317,.030467068776488304,.4174400866031647,-.521793007850647,-1.5193467140197754,.0034290971234440804,-.37409281730651855,1.5193467140197754,.0034290971234440804,-.37409281730651855,.012890640646219254,-.8310151696205139,2.4351325035095215,1.5662710666656494,.9279237985610962,3.319540500640869,-1.5894092321395874,.8687598705291748,3.289144515991211,.3409583568572998,-.5160142183303833,1.274591088294983,-.3600188195705414,-.5107225775718689,1.2790225744247437,-1.097593903541565,.11527538299560547,-1.0057109594345093,1.1363357305526733,-.5465875864028931,-.971623957157135,.8704371452331543,.5547775626182556,.3597971200942993,3.982757734721787e-10,.5748654007911682,.7409988641738892,1.0960721969604492,.12153985351324081,-.9948496222496033,-1.1377226114273071,-.5433639287948608,-.9926916360855103,-.8704371452331543,.5547775626182556,.3597968816757202,0,-.5633412003517151,-.9722840189933777,0,-.5655208826065063,.37440025806427]),new Float32Array([.012890640646219254,-.8310151696205139,2.4351325035095215,0,-.5633412003517151,-.9722840189933777])];if("BARTENDER"==t)return[r=new Float32Array([-.20026133954524994,-.9737697839736938,2.17860746383667,.19603070616722107,-.9857503771781921,2.1616086959838867,.3260974586009979,.7099164128303528,.10108458995819092,-.37390175461769104,-.42527586221694946,1.0039399862289429,.3709491193294525,-.42527586221694946,1.0039399862289429,8438758959528059e-20,-1.101210594177246,1.7955349683761597,2949934116831766e-31,-.04326578229665756,-.5318827629089355,.4412812888622284,-.2815903127193451,-1.3385579586029053,.45793405175209045,.37141913175582886,-1.6536355018615723,-.4412812888622284,-.2815903127193451,-1.3385579586029053,-.45793405175209045,.37141913175582886,-1.6536355018615723,6788047923913078e-31,-.8192819952964783,.4206336736679077,-.9793461561203003,-.015334106981754303,1.7865675687789917,.9793461561203003,-.015334106981754303,1.7865675687789917,1.4873708486557007,.04833114147186279,-.3768104314804077,.4768085777759552,.1994880586862564,.9495226144790649,.7653667330741882,-.3627835810184479,.15018165111541748,.308129221200943,-.6489158868789673,.557608962059021,-.0002116243413183838,.49473923444747925,1.0336977243423462,-.5404940247535706,.19043265283107758,.8128713369369507,-.7657899260520935,-.3627835810184479,.15018165111541748,1.4484371035905497e-7,.3663712441921234,3.387472629547119,-1.2087160348892212,-.6443189978599548,3.0043344497680664,1.2087161540985107,-.6443195343017578,3.0043344497680664,6141737432960813e-31,-.8464082479476929,.10243535041809082,-.3249528408050537,.7104986310005188,.10016584396362305,-.303207665681839,-.9462416172027588,.5075775384902954,-.37667226791381836,-1.0658020973205566,.9869986772537231]),new Float32Array([2949934116831766e-31,-.04326578229665756,-.5318827629089355,1.4484371035905497e-7,.3663712441921234,3.387472629547119])];if("WCBOTTLE"==t)return[r=new Float32Array([-.013366899453103542,-2.9939471346551727e-7,-2.511009931564331,.6493963599205017,-.7673797011375427,-2.4501447677612305,.7540126442909241,.6627629399299622,-2.4501450061798096,-.9611459970474243,-.36033540964126587,-2.4501450061798096,.1477278769016266,.9964179992675781,1.9307010173797607,-.9568377137184143,-.35869666934013367,1.9307011365890503,-.01336702425032854,3.722930728145002e-7,2.314748764038086,.9344120025634766,.3603347837924957,.22589847445487976,-.027811311185359955,1.0138630867004395,1.6714674234390259,-.9710267186164856,.3331884741783142,1.0331839323043823,.627266526222229,.7859488129615784,1.035000205039978,-.6761305332183838,.7673797011375427,.22936050593852997,-.02781102992594242,1.0138623714447021,-1.587138056755066,-.027811311185359955,1.0138630867004395,.45858100056648254,-.9372201561927795,-.4008185565471649,-.006537972949445248,.5878132581710815,-.8109326958656311,-.27440735697746277,-.3465554714202881,-.9576587677001953,1.3840690851211548,.34696754813194275,-.9477792978286743,-.5884990096092224,-.8841753602027893,-.519440233707428,-.5891181230545044,-.346555233001709,-.9576594829559326,.418072372674942]),new Float32Array([-.013366899453103542,-2.9939471346551727e-7,-2.511009931564331,-.01336702425032854,3.722930728145002e-7,2.314748764038086])];if("EQA"==t)return[r=new Float32Array([-3.7749502658843994,-.9271571040153503,.04594746232032776,-3.777569055557251,.92264324426651,.04048970341682434,-3.7703702449798584,-1.2227396965026855,-.9106809496879578,-3.7990496158599854,1.1855655908584595,-.9073726534843445,3.811656951904297,1.3718937635421753,-.7763562798500061,3.8001205921173096,-1.3779062032699585,-.7809855341911316,-.4568534791469574,-1.0891674757003784,1.2122516632080078,-.4568534791469574,1.08638596534729,1.2122514247894287,2.6531293392181396,-.925976037979126,1.2379950284957886,2.648271083831787,.9270637631416321,1.2376376390457153,3.459774971008301,-1.3973642587661743,.466232568025589,3.459774971008301,1.3945828676223755,.46623218059539795,-.9480692744255066,.0011375703616067767,1.0669147968292236,-4.019203186035156,-.0013908070977777243,-.24615326523780823,3.3231399059295654,-.0013906551757827401,1.151373267173767,3.907538652420044,-.0012724152766168118,.11990431696176529,.35528019070625305,-1.5870187282562256,.2603841722011566,.5474950671195984,-1.151407241821289,1.2155274152755737,-1.341339349746704,-1.5719798803329468,-.9050094485282898,-1.420742154121399,-1.4566854238510132,.4212491512298584,.35528019070625305,1.5842370986938477,.2603837251663208,.5482162833213806,1.1495895385742188,1.2244428396224976,-1.341339349746704,1.5691980123519897,-.9050098657608032,-1.420742154121399,1.4539037942886353,.42124876379966736,2.0402863025665283,-1.592824101448059,.3434940576553345,1.582544207572937,-1.5713834762573242,-.836898148059845,2.047945737838745,1.584236979484558,.3409099578857422,1.582544207572937,1.5686016082763672,-.8368985652923584]),new Float32Array([-4.019203186035156,-.0013908070977777243,-.24615326523780823,3.907538652420044,-.0012724152766168118,.11990431696176529])];if("FACE"==t)return[r=new Float32Array([-9.037608623504639,2.355806514620781,-8.28516685962677,-8.81279444694519,-.11831151321530342,-7.542072296142578,-8.38990831375122,-2.418052017688751,-7.253487825393677,8.400188446044922,-2.424757957458496,-7.240226984024048,8.831642150878906,-.11823836714029312,-7.535887956619263,9.061289668083191,2.362936556339264,-8.284585356712341,-1.901270106434822,6.1033472418785095,1.311941035091877,1.9072290509939194,6.117302238941193,1.3117250353097916,-.0015033446252346039,4.03810042142868,1.5223239958286285,.0047621168196201324,2.571689784526825,2.513868987560272,.004333397373557091,1.2499050498008728,3.5467670559883118,-.0007506050169467926,-.2351544015109539,4.379635065793991,-1.5987120568752289,-1.6273340582847595,1.7652730643749237,.013800747692584991,-1.9495649933815002,2.5874924659729004,1.6161270439624786,-1.629391998052597,1.7741851210594177,-5.2972798347473145,3.732409954071045,-.8603600263595581,-2.2803800106048584,3.479170083999634,-.39132800698280334,2.189579963684082,3.4696600437164307,-.3517009913921356,5.284249782562256,3.7591500282287598,-.8421319723129272]),new Float32Array([])];if("HAND"==t){for(var r,a=((r=new Float32Array([3.57,6.02,0,6.68,8.76,.75,10.68,6.14,0,10.19,4.74,0,9.27,3.56,0,8.04,2.58,0,11.75,2.81,.01]))[12]+r[18])/2,s=(r[13]+r[19])/2,o=(r[14]+r[20])/2,i=0;i<r.length/3;i++)r[3*i]-=a,r[3*i+1]-=s,r[3*i+2]-=o;return[r,new Float32Array([3.57,6.02,0,10.19,4.74,0])]}var u=[],l=[];if("LAMBORGHINI"==t)u=[85,131,198,203,320,391,401,404,791,886,891,1008,1075,1085];else if("HORSE"==t)u=[12,15,264,352,360,845,1119,1316,1498,1872,2065,3146,4269,4273,4590,4593,7671,8034,8756,9119];else if("WATSON-CAN"==t)u=[335,1290,1330,2591,2669,2700,2822,3488,3613,5569,5574,5613,5639,5679,5685],l=[871,482];else if("MARTELL-BOTTLE"==t)u=[11,24,38,83,85,151,182,200,207,222,893,1646,1971,2013,2221,2229,2271,2309,2376,2444,2459,2725,2787,2792],l=[24,893];else if("NECKLACE"==t)u=[670,42,48,551,160,155,762],l=[640,762];else if("CAN-KIVISENSE"==t)u=[38,53,89,981,1006,1009,1019,1024,1034,1046,1052,1062,1087,1096,1105,1117,1124,1144,1148,1154],l=[1914,2725];else if("TOY-TRUCK"==t)u=[],l=[];else if("WRIST"==t&&(181==n||44==n)){if(u=[2,15,24,33,42,56,65,74,83,92,213,321,338,360,393,416,472,481,487,576,622,746,804,838,896,905,913,922,931,940,949,958,977,986,996,1005,1010,1019,1028,1037,1046,1055,1077,1086,1092,1101,1164,1173,1182,1267,1311,1321,1323,1346,1354,1372,1428,1451,1460,1468,1478,1503,1513,1554,1588,1597,1605,1641,1649,1692,1709,1735,1738,1762,1772,1789,1793,1819,1840,1850,1876,1894,1899,1921,1926,1935,1948,1953,1962,1971,1980,1989,2002,2007,2016,2025,2038,2056,2061,2083,2170,2435,2459,2513,2530,2594,2674,2718,2745,2748,2753,2772,2775,2791,2797,2803,2899,2905,2947,3003,3034,3084,3093,3109,3112,3128,3129,3136,3168,3175,3205,3208,3305,3323,3324,3331,3365,3368,3371,3374,3378,3386,3389,3392,3395,3398,3414,3418,3434,3437,3440,3443,3446,3462,3496,3509,3512,3689,3690,3691,3692,3693,3747,3748,3760,3764,3777,3778,3782,3783,3784,3787,3788,3792,3793,3797,3799,3800,3804,3805,3809],44==n){var c=[10,12,14,15,18,20,21,22,23,34,35,36,39,40,44,45,49,50,52,59,63,72,76,77,102,105,106,107,115,116,120,121,125,126,128,135,141,143,145,163,165,173,174,175];c.forEach((function(e,t){c[t]=u[e]})),console.log(c),u=c}l=[]}var p=u.length,h=new Float32Array(3*p);u.forEach((function(t,n){h[3*n]=e[3*t],h[3*n+1]=e[3*t+1],h[3*n+2]=e[3*t+2]}));var d=new Float32Array(3*l.length);return l.forEach((function(t,n){d[3*n]=e[3*t],d[3*n+1]=e[3*t+1],d[3*n+2]=e[3*t+2]})),[h,d]}($._geometryObjModel.vertices,$._geometryType,$._trackerConfig.outChannels),$._keypsVts=t[0],$._refKeypsVts=t[1];var a=Math.max($._detectorOutDims[1]*$._detectorOutDims[2]*$._detectorOutDims[3]);$._trackHasHeatmaps&&(a=Math.max($._detectorOutDims[1]*$._detectorOutDims[2]*$._detectorOutDims[3],$._trackerOutDims[1]*$._trackerOutDims[2]*$._trackerOutDims[3]));var s=Math.max($._detectorOutDims[3],$._trackerOutDims[3]);if($._bufferHeatmaps=$._poseModule._malloc(a*$._float_size),$._bufferKeypsDet=$._poseModule._malloc(2*$._detectorOutDims[3]*$._float_size),$._bufferKeypsTrack=$._poseModule._malloc(2*$._trackerOutDims[3]*$._float_size),$._bufferFeatureScores=$._poseModule._malloc(s*$._float_size),$._bufInOutPose=$._poseModule._malloc(21*$._float_size),e.pdmModel){var o=new Uint8Array(e.pdmModel);$._bufferPdmModel=$._poseModule._malloc(o.byteLength),$._poseModule.HEAPU8.set(o,$._bufferPdmModel);var i={rigid_pose:0,num_iterations:1,filter_strength:5,reg_w:10,fovy_d:50,width:640,height:480,num_features:$._geometryType==ON.Face?$._trackerOutDims[3]:-1,modelContent:$._bufferPdmModel,modelContentSize:o.byteLength,modelEncoding:$._geometryType==ON.Face?2:1,bsMode:0},u=$._poseModule._malloc(48);$._poseModule.setValue(u+0,i.rigid_pose,"i32"),$._poseModule.setValue(u+4,i.num_iterations,"i32"),$._poseModule.setValue(u+8,i.filter_strength,"i32"),$._poseModule.setValue(u+12,i.reg_w,"float"),$._poseModule.setValue(u+16,i.fovy_d,"float"),$._poseModule.setValue(u+20,i.width,"i32"),$._poseModule.setValue(u+24,i.height,"i32"),$._poseModule.setValue(u+28,i.num_features,"i32"),$._poseModule.setValue(u+32,i.modelContent,"*"),$._poseModule.setValue(u+36,i.modelContentSize,"i32"),$._poseModule.setValue(u+40,i.modelEncoding,"i32"),$._poseModule.setValue(u+44,i.bsMode,"i32");var l=$._poseModule.cwrap("xzimgPoseEstimationInitialize","number",["number"])(u);$._debug&&console.log("PDM initialisation: ",l),$._poseModule._free(u),$._poseModule._free($._bufferPdmModel),$._nonRigidInitialized=!0}else if(null==$._bufKeyps3D){$._bufKeyps3D=$._poseModule._malloc($._keypsVts.length*$._float_size),$._poseModule.HEAPF32.set($._keypsVts,$._bufKeyps3D/4);var c=Array.from($._keypsVts);c.forEach((function(e,t){t%3==0&&(c[t]=-c[t])})),$._bufMirroredKeyps3D=$._poseModule._malloc(c.length*$._float_size),$._poseModule.HEAPF32.set($._keypsVts,$._bufMirroredKeyps3D/4)}if(e.subTracker){$._tfSubTracker=e.subTracker.graphModel,$._subTrackerConfig=e.subTracker.config;var p=Nc([$._config.subTrackerSymmetric?2:1,$._subTrackerConfig.inHeight,$._subTrackerConfig.inWidth,3]),h=$._tfSubTracker.predict(p);$._subTrackerOutDims=h.shape,h.dispose(),p.dispose();var d=Math.max($._subTrackerOutDims[1]*$._subTrackerOutDims[2]*$._subTrackerOutDims[3]);if($._bufSubTrackerHmaps=$._poseModule._malloc(d*$._float_size),$._bufSubTrackerHmapsSym=$._poseModule._malloc(d*$._float_size),$._config.subTrackerObjectType){var f=$._geometryObjModel.faces.length/3;$._bufModelTriangles=$._poseModule._malloc(9*f*$._float_size);for(var m=new Float32Array(9*f),g=0;g<f;g++){var y=$._geometryObjModel.faces[3*g],b=$._geometryObjModel.faces[3*g+1],_=$._geometryObjModel.faces[3*g+2];m[9*g]=$._geometryObjModel.vertices[3*y],m[9*g+1]=$._geometryObjModel.vertices[3*y+1],m[9*g+2]=$._geometryObjModel.vertices[3*y+2],m[9*g+3]=$._geometryObjModel.vertices[3*b],m[9*g+4]=$._geometryObjModel.vertices[3*b+1],m[9*g+5]=$._geometryObjModel.vertices[3*b+2],m[9*g+6]=$._geometryObjModel.vertices[3*_],m[9*g+7]=$._geometryObjModel.vertices[3*_+1],m[9*g+8]=$._geometryObjModel.vertices[3*_+2]}$._poseModule.HEAPF32.set(m,$._bufModelTriangles/4)}}$._initialized=!0})),Z((function(){return R.unsubscribe()}))).toPromise()];case 4:return s.sent(),[2]}}))}))},e.prototype.release=function(){this._initialized&&(this._tfKeypointsDetector.dispose(),this._tfKeypointsTracker.dispose(),null!=this._bufferHeatmaps&&this._poseModule._free(this._bufferHeatmaps),this._bufferHeatmaps=null,null!=this._bufferKeypsDet&&this._poseModule._free(this._bufferKeypsDet),this._bufferKeypsDet=null,null!=this._bufferKeypsTrack&&this._poseModule._free(this._bufferKeypsTrack),this._bufferKeypsTrack=null,null!=this._bufferFeatureScores&&this._poseModule._free(this._bufferFeatureScores),this._bufferFeatureScores=null,null!=this._bufInOutPose&&this._poseModule._free(this._bufInOutPose),this._bufInOutPose=null,null!=this._bufKeyps3D&&this._poseModule._free(this._bufKeyps3D),this._bufKeyps3D=null,null!=this._bufMirroredKeyps3D&&this._poseModule._free(this._bufMirroredKeyps3D),this._bufMirroredKeyps3D=null,null!=this._hptrImageBuffer&&this._poseModule._free(this._hptrImageBuffer),this._hptrImageBuffer=null,this._bufDenseVertices3D&&this._poseModule._free(this._bufDenseVertices3D),this._bufDenseVertices3D=null,this._bufModelTriangles&&this._poseModule._free(this._bufModelTriangles),this._bufModelTriangles=null,this._poseModule.cwrap("xzimgPoseEstimationRelease")(),this._currentWidth=0,this._currentHeight=0,this._initialized=!1,this._nonRigidInitialized=!1,this._trackingState=iN.Detection,this._bufSubTrackerHmaps&&this._poseModule._free(this._bufSubTrackerHmaps),this._bufSubTrackerHmaps=null,this._bufSubTrackerHmapsSym&&this._poseModule._free(this._bufSubTrackerHmapsSym),this._bufSubTrackerHmapsSym=null)},e.prototype.trackSync=function(e){var t;if(this._initialized){var n=this._videoManager.getVideoCanvas();n.width===this._currentWidth&&n.height===this._currentHeight||(this._currentWidth=n.width,this._currentHeight=n.height,t=MN.getCameraParams(this._config.fovY,this._currentWidth,this._currentHeight),this._fx=t[0],this._fy=t[1],this._cx=t[2],this._cy=t[3],this._poseModule.cwrap("xzimgInitializeCamera","number",["number","number","number"])(this._config.fovY,this._currentWidth,this._currentHeight)),this._poseManager.setNbFramesDelay(this._videoManager.getNbFramesDelay());var r=e;null==e&&(r=this._videoManager.getLastBuffer()),null!=r?this.trackGeometrySync(r):console.error("No video frame to process")}else console.error("Geometry must be initialized to track")},e.prototype.trackGeometrySync=function(e){var t,n,r=this,a=VN(this._geometryType)||this._geometryType==ON.Wrist||this._geometryType==ON.Hand||this._geometryType==ON.Face;if(this._trackingState===iN.Detection){var s=this._poseModule.cwrap("xzimgMatchRecKeypsInit","number",["number"]);null==this._hptrImageBuffer&&(this._hptrImageBuffer=this._poseModule._malloc(e.width*e.height*4)),TN(this._poseModule,e,this._hptrImageBuffer);var o=kN(this._poseModule,this._hptrImageBuffer,e.width,e.height);s(o),this._poseModule._free(o);var i=this.detectGeometrySync(e),u=i.refinedFeatures,l=i.scores;this._keyps2D=u;var c=tN(l,this._config.validDetectedKeypThs);this._visibility=c.visibilty,this._trackingState=iN.Detection,c.totalVisible>=this._config.detectNumKeypsThs&&c.globalScore>=this._config.detectScoreThs&&(this._geometryType==ON.Wrist&&(this._flipMode="","left"==(t=this._keyps2D,n=c.visibilty,(9==t.length/2?n[0]&&n[1]?lN.CreateFromPoints(new uN(t[0],t[9]),new uN(t[1],t[10])):lN.CreateFromPoints(new uN(t[1],t[10]),new uN(t[6],t[15])):lN.CreateFromPoints(new uN(t[30],t[211]),new uN(t[163],t[344]))).x>0?"left":"right")&&(this._flipMode="up_down")),a?this._trackingState=iN.Detected:(this._reprojError=this.computePoseSync(this._trackingState,this._geometryType),this._reprojError>0&&this._reprojError<this._config.reprojThs&&(this._trackingState=iN.Detected)))}else{var p=this.trackGeometryFeaturesSync(e,this._trackingState,this._keyps2D,this._visibility,this._geometryType);this._keyps2D=p.imageFilteredKeyps,this._cropKeyps2D=p.cropKeyps,c=tN(p.scores,this._config.validTrackedKeypThs),this._visibility=c.visibilty;var h=aN(this._geometryType,this._keyps2D.length/2);if(this._debug&&(console.log("globalScore",c.globalScore),console.log("totalVisible",c.totalVisible)),this._visibility[h[0]]&&this._visibility[h[1]]&&c.totalVisible>=this._config.trackedNumKeypsThs&&c.globalScore>=this._config.trackScoreThs){if(this._config.computePose?(this._reprojError=this.computePoseSync(this._trackingState,this._geometryType),this._reprojError<=0||this._reprojError>this._config.reprojThs?this._trackingState=iN.Detection:this._trackingState=iN.Tracking):this._trackingState=iN.Tracking,this._tfSubTracker&&this._trackingState==iN.Tracking){this._debug&&console.log("tracking subgeomerty");var d=this.trackSubGeometrySync(e,this._keyps2D,this._visibility);if(this._subTrackerKeyps&&this._subTrackerKeyps.length>0?this._subTrackerKeyps.forEach((function(e,t){r._subTrackerKeyps[t]=pN(d.subTrackerKeyps[t],d.subTrackerVisibility[t],e,r._subTrackerVis[t],.1)})):this._subTrackerKeyps=d.subTrackerKeyps,this._subTrackerScores=d.subTrackerKeypsScores,this._subTrackerVis=d.subTrackerVisibility,"ear"==this._config.subTrackerObjectType){var f=new Float32Array([0,0,0]);f=this._pose.transformInv(f);for(var m=this._poseModule.cwrap("xzimgGeometryGetModelIntersection","number",["number","number","number","number"]),g=0;g<this._subTrackerKeyps.length;g++){var y=0==g?2:3,b=this._keypsVts[3*y]-1.45;1==g&&(b=this._keypsVts[3*y]+1.45);var _=this._keypsVts[3*y+1]-.38,x=this._keypsVts[3*y+2]-1.6,v=Math.sqrt((b-f[0])*(b-f[0])+(_-f[1])*(_-f[1])+(x-f[2])*(x-f[2])),w=new Float32Array([(b-f[0])/v,(_-f[1])/v,(x-f[2])/v]);this._debug&&(console.log("dir",w),console.log("camCenter",f),console.log("numTriangles",this._geometryObjModel.faces.length/3));var T=this._poseModule._malloc(3*this._float_size),k=T/4,I=this._poseModule.HEAPF32.subarray(k,k+3);I.set(f);var S=this._poseModule._malloc(3*this._float_size);k=S/4,(I=this._poseModule.HEAPF32.subarray(k,k+3)).set(w);var E=m(T,S,this._bufModelTriangles,this._geometryObjModel.faces.length/3);if(this._poseModule._free(T),this._poseModule._free(S),1==E){var N=pN(this._pose.project(new Float32Array([b,_,x]),MN.getCameraMat(this._config.fovY,this._currentWidth,this._currentHeight)),new Int32Array([1]),new Float32Array([this._subTrackerKeyps[g][3],this._subTrackerKeyps[g][7]]),new Int32Array([1]),.1);this._subTrackerKeyps[g][3]=N[0],this._subTrackerKeyps[g][7]=N[1]}}}}}else this._trackingState=iN.Detection}(this._trackingState===iN.Detection||this._trackingState===iN.Detected&&a)&&(this._pose=new MN(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0])),this._pose.setTrackingState(iN.Detection)),this._pose.setTrackingState(this._trackingState),this._poseManager.setPose(this._pose)},e.prototype.detectGeometrySync=function(e){var t,n,r,a=function(e,t){var n,r;return{crop:e>t?[(r=0)/t,(n=(e-t)/2)/e,1,(e-n)/e]:[(r=(t-e)/2)/t,(n=0)/e,(t-r)/t,1],deltaY:r,deltaX:n}}(this._currentWidth,this._currentHeight),s=a.crop,o=a.deltaY,i=a.deltaX,u=Li(e),l=bi(u,"float32"),c=Fu(l,[1,this._currentHeight,this._currentWidth,3]),p=pd.cropAndResize(c,[s],[0],[this._detectorConfig.inHeight,this._detectorConfig.inWidth]),h=Ul(255),d=ou(p,h),f=this._tfKeypointsDetector.predict(d),m=f.dataSync(),g=this._poseModule.cwrap("xzimgGetHeatmapsLocations","number",["number","number","number","number","number","number","number","number"]),y=null!==(t=null==f?void 0:f.shape[3])&&void 0!==t?t:this._detectorConfig.outChannels,b=null!==(n=null==f?void 0:f.shape[1])&&void 0!==n?n:this._detectorConfig.outHeight,_=null!==(r=null==f?void 0:f.shape[2])&&void 0!==r?r:this._detectorConfig.outWidth,x=y*b*_,v=this._bufferHeatmaps/4;this._poseModule.HEAPF32.subarray(v,v+x).set(m),g(this._bufferHeatmaps,b,_,y,0,1,this._bufferKeypsDet,this._bufferFeatureScores);var w=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufferKeypsDet,2*y),T=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufferFeatureScores,y);u.dispose(),l.dispose(),h.dispose(),p.dispose(),d.dispose(),c.dispose(),f.dispose();var k=Math.min(this._currentWidth,this._currentHeight),I=k/this._detectorConfig.inWidth,S=k/this._detectorConfig.inHeight;return this._simCropToImage=function(e,t,n,r){var a=new Float32Array(6);return a[0]=r,a[1]=0,a[2]=t,a[3]=0,a[4]=n,a[5]=e,a}(o,i,S,I),{refinedFeatures:rN(w,this._simCropToImage),scores:T}},e.prototype.trackGeometryFeaturesSync=function(e,t,n,r,a){var s,o,i,u,l=Int32Array.from(r);this._activeIds.length>0&&(l.forEach((function(e,t){l[t]=0})),this._activeIds.forEach((function(e){l[e]=1})),r.forEach((function(e,t){0==e&&(l[t]=0)})));var c,p,h=new Float32Array([0,0]);if(t!=iN.Detected){if(o=(s=IN(this._poseModule,e,this._hptrImageBuffer,n,l))[0],i=s[1],u=s[2],Math.sqrt(i[2]*i[2]+i[3]*i[3])>10?this._fastMvt=!0:this._fastMvt=!1,a==ON.FullBody?[7,8,9,10,13,14,15,16].forEach((function(e){u[e]=0})):a==ON.UpperBody?[7,8,9,10].forEach((function(e){u[e]=0})):a==ON.Necklace?[1,2,3,4,5].forEach((function(e){u[e]=0})):this._activeIds.length>0&&this._activeIds.forEach((function(e){u[e]=0})),h=function(e,t,n,r,a,s,o){void 0===a&&(a=null);for(var i=new Float32Array(2),u=n.length/2,l=0,c=0;c<u;c++)(null==a||a[c]>0)&&(i[0]+=r[c]-n[c],i[1]+=r[c+u]-n[c+u],l+=1);l>0&&(i[0]/=l,i[1]/=l);var p=t/4,h=new Float32Array(18);return h.set(e.HEAPF32.subarray(p,p+18)),h[9]+=i[0]*h[11]/s,h[10]+=i[1]*h[11]/o,e.HEAPF32.set(h,t/4),i}(this._poseModule,this._bufInOutPose,n,o,u,this._fx,this._fy),a==ON.Necklace)for(var d=o.length/2,f=0;f<d;f++)o[f]=n[f]+h[0],o[f+d]=n[f+d]+h[1]}else o=n;if("WATSON-CAN"==a||"CAN-KIVISENSE"==a||"TOY-TRUCK"==a||"CHIVAS"==a||"CHIVAS-LARGE"==a||"LION"==a||"BARTENDER"==a||"WCBOTTLE"==a||"EQA"==a||"MARTELL-BOTTLE"==a){var m=this._pose.project(this._refKeypsVts,MN.getCameraMat(this._config.fovY,this._currentWidth,this._currentHeight));c=-Math.atan2(m[1]-m[3],m[2]-m[0]),"EQA"==a&&(c=0);var g=this._pose.project(this._keypsVts,MN.getCameraMat(this._config.fovY,this._currentWidth,this._currentHeight));for(p=new Float32Array(g.length),f=0;f<p.length/2;f++)p[f]=g[2*f],p[f+p.length/2]=g[2*f+1]}var y=Float32Array.from(n),b=o.length/2;for(f=0;f<b;f++)y[f]+=h[0],y[f+b]+=h[1];VN(a)?this._simCropToImage=function(e,t,n,r,a){var s,o,i,u=t.length/2,l=Array(5),c=new Array(5);if(7==u)l[0]=n[0]>0?1:0,c[0]=new BN(t[0],t[u]),l[1]=n[3]>0&&n[4]>0?1:0,c[1]=new BN((t[3]+t[4])/2,(t[3+u]+t[4+u])/2),l[2]=n[5]>0&&n[6]>0?1:0,c[2]=new BN((t[5]+t[6])/2,(t[5+u]+t[6+u])/2),l[3]=n[1]>0?1:0,c[3]=new BN(t[1],t[1+u]),l[4]=n[2]>0?1:0,c[4]=new BN(t[2],t[2+u]);else{var p=15==u?13:17,h=15==u?14:18;l[0]=n[0]>0?1:0,c[0]=new BN(t[0],t[u]),l[1]=n[p]>=0?1:0,c[1]=new BN(t[p],t[p+u]),l[2]=n[h]>=0?1:0,c[2]=new BN(t[h],t[h+u]),l[3]=n[1]>0?1:0,c[3]=new BN(t[1],t[1+u]),l[4]=n[2]>0?1:0,c[4]=new BN(t[2],t[2+u])}if("FULL-BODY"==e)if(l[1]>0&&l[2]>0)s=c[2],o=-Math.atan2(c[2].y-c[1].y,c[1].x-c[2].x),o+=Math.PI/2,i=2*c[2].Dist(c[1])*2.35;else if(l[0]>0&&l[1]>0)(s=c[1]).y+=2.24*(c[1].y-c[0].y),o=-Math.atan2(c[1].y-c[0].y,c[0].x-c[1].x),o+=Math.PI/2,i=2*c[0].Dist(c[1])*5.3;else if(l[0]>0&&l[2]>0)s=c[2],o=-Math.atan2(c[2].y-c[0].y,c[0].x-c[2].x),o+=Math.PI/2,i=2*c[0].Dist(c[2])*1.64;else{if(!(l[0]>0&&l[3]>0&&l[4]>0))return 0;var d=c[3].Dist(c[4]);(s=c[0]).y+=3*d,o=-Math.atan2(c[4].y-c[3].y,c[3].x-c[4].x),i=2*d*14}else if(console.log(l),l[1]>0&&l[2]>0)s=c[1],o=-Math.atan2(c[2].y-c[1].y,c[1].x-c[2].x),o+=Math.PI/2,i=2*c[2].Dist(c[1])*1.2;else if(l[0]>0&&l[1]>0)s=c[1],o=-Math.atan2(c[1].y-c[0].y,c[0].x-c[1].x),o+=Math.PI/2,i=2*c[0].Dist(c[1])*2.6;else if(l[0]>0&&l[2]>0)s=new BN(c[2].x+.75*(c[0].x-c[2].x),c[2].y+.75*(c[0].y-c[2].y)),o=-Math.atan2(c[2].y-c[0].y,c[0].x-c[2].x),o+=Math.PI/2,i=2*c[0].Dist(c[2])*.8;else{if(!(l[0]>0&&l[3]>0&&l[4]>0))return 0;d=c[3].Dist(c[4]),(s=c[0]).y+=5.5*d,o=-Math.atan2(c[4].y-c[3].y,c[3].x-c[4].x),i=2*d*11}for(var f=0,m=0;m<u;m++){var g=new BN(t[m],t[m+u]).Dist(s);n[m]>0&&g>f&&(f=g)}i=Math.max(i,2*f);var y=Math.cos(o),b=Math.sin(o),_=(i+.1*i)/Math.max(r[0],r[1]),x=(r[1]-1)/2,v=(r[0]-1)/2,w=s.x-(y*_*x-b*_*v),T=s.y-(b*_*x+y*_*v);if(null!=a){var k=.8;_=(1-k)*_+k*a[7],w=(1-k)*w+k*a[2],T=(1-k)*T+k*a[5],o=(1-k)*o+k*a[6],y=Math.cos(o),b=Math.sin(o)}return[y*_,-b*_,w,b*_,y*_,T,o,_]}(a,void 0===p?o:p,r,[this._trackerConfig.inWidth,this._trackerConfig.inHeight],t==iN.Detected||this._fastMvt?null:this._simCropToImage):a==ON.Face?this._simCropToImage=function(e,t,n,r,a){var s=e.length/2,o=eN(e,t,s),i=new uN((o[0]+o[1])/2,(o[2]+o[3])/2),u=0,l=0,c=.3;if(19==s||21==s){var p=[15,16,17,18];21==s&&(p=[17,18,19,20]),0!=t[17]&&0!=t[20]||(p=[18,19]),0!=t[18]&&0!=t[19]||(p=[17,20]),i=new uN(0,0),p.forEach((function(t){i.x+=e[t],i.y+=e[t+s]})),i.x/=p.length,i.y/=p.length;var h=new uN(e[8],e[8+s]),d=new uN(e[13],e[13+s]);21==s&&(h=new uN(e[10],e[10+s]),d=new uN(e[15],e[15+s])),l=1.57075-Math.atan2(d.y-h.y,h.x-d.x);for(var f=0;f<s;f++){var m=new uN(e[f],e[f+s]).Dist(i);t[f]>0&&m>u&&(u=m)}u*=2,c=.3}else{var g=27,y=62,b=66;22==s&&(g=9,y=18,b=20),24==s&&(g=9,y=20,b=22);var _=void 0;5==s?(_=new uN(.5*(e[0]+e[1]),.5*(e[0+s]+e[1+s])),y=3,b=4):_=new uN(e[g],e[g+s]);var x=new uN(.5*(e[y]+e[b]),.5*(e[y+s]+e[b+s]));if(l=1.57075-Math.atan2(x.y-_.y,_.x-x.x),u=Math.max(o[1]-o[0],o[3]-o[2]),a&&"face_center"==a){i=new uN((_.x+x.x)/2,(_.y+x.y)/2);var v=0;for(f=0;f<s;f++)m=new uN(e[f],e[f+s]).Dist(i),t[f]>0&&m>v&&(v=m);u=2*v}5==s&&(u=2*(o[1]-o[0])),22==s&&(c=.15)}var w=new cN(i.x-u/2,i.y-u/2,u,u),T=Math.cos(l),k=Math.sin(l),I=(w.w+c*w.w)/Math.max(n[0],n[1]),S=n[1]/2,E=n[0]/2,N=i.x-(T*I*S-k*I*E),C=i.y-(k*I*S+T*I*E);if(null!=r){var A=.8;N=A*N+(1-A)*r[2],C=A*C+(1-A)*r[5],I=.3*I+.7*r[7],Math.abs(l-r[6])<1&&(l=.3*l+.7*r[6]),T=Math.cos(l),k=Math.sin(l)}return[T*I,-k*I,N,k*I,T*I,C,l,I]}(void 0===p?y:p,r,[this._trackerConfig.inWidth,this._trackerConfig.inHeight],t==iN.Detected||this._fastMvt?null:this._simCropToImage,this._config.normMode):a==ON.Wrist?this._simCropToImage=function(e,t,n,r,a){var s=e.length/2,o=eN(e,t,s),i=aN("WRIST",s),u=i[0],l=i[1],c=[e[u],e[u+s]],p=[e[l],e[l+s]],h=-Math.atan2(p[1]-c[1],c[0]-p[0]),d=function(e,t,n){for(var r=e.length/2,a=new Float32Array(2*r),s=0;s<r;s++)if(t[s]>0){var o=UN(new Float32Array([e[s],e[s+r]]),n);a[s]=o[0],a[s+r]=o[1]}var i=eN(a,t,r);return Math.max(i[1]-i[0],i[3]-i[2])}(e,t,h),f=(o[1]+o[0])/2,m=(o[3]+o[2])/2;9==s&&(h=-Math.atan2(c[1]-p[1],p[0]-c[0]),h+=3.1415,!t[0]&&t[1]&&t[6]&&(f=e[1],m=e[10],d=2*Math.sqrt(Math.pow(e[6]-f,2)+Math.pow(e[15]-f,2))));var g=Math.cos(h),y=Math.sin(h),b=(d+=1*d)/Math.max(n[0],n[1]),_=n[1]/2,x=n[0]/2,v=f-(g*b*_-y*b*x),w=m-(y*b*_+g*b*x);if(null!=r){var T=.5;v=T*v+.5*r[2],w=T*w+.5*r[5],b=T*b+.5*r[7],Math.abs(h-r[6])<1&&(h=T*h+.5*r[6]),g=Math.cos(h),y=Math.sin(h)}return[g*b,-y*b,v,y*b,g*b,w,h,b]}(void 0===p?o:p,r,[this._trackerConfig.inWidth,this._trackerConfig.inHeight],t==iN.Detected||this._fastMvt?null:this._simCropToImage,this._config.normMode):a==ON.Hand?this._simCropToImage=function(e,t,n,r,a){var s=e.length/2,o=eN(e,t,s),i=Math.max(o[1]-o[0],o[3]-o[2]),u=sN("HAND",e),l=u[0],c=u[1],p=u[2];p+=3.1415,9==s?t[3]&&t[6]&&(l=.5*(e[3]+e[6]),c=.5*(e[3+s]+e[6+s]),t[1]&&(i=2*Math.sqrt(Math.pow(e[1]-l,2)+Math.pow(e[1+s]-l,2)))):(i=Math.max(o[1]-o[0],o[3]-o[2]),l=(o[1]+o[0])/2,c=(o[3]+o[2])/2);var h=Math.cos(p),d=Math.sin(p),f=(i+=1.2*i)/Math.max(n[0],n[1]),m=n[1]/2,g=n[0]/2,y=l-(h*f*m-d*f*g),b=c-(d*f*m+h*f*g);if(null!=r){var _=.9;y=_*y+(1-_)*r[2],b=_*b+(1-_)*r[5],f=.3*f+.7*r[7],Math.abs(p-r[6])<1&&(p=.3*p+.7*r[6]),h=Math.cos(p),d=Math.sin(p)}return[h*f,-d*f,y,d*f,h*f,b,p,f]}(void 0===p?o:p,r,[this._trackerConfig.inWidth,this._trackerConfig.inHeight],t==iN.Detected||this._fastMvt?null:this._simCropToImage,this._config.normMode):this._simCropToImage=function(e,t,n,r,a,s){var o,i,u=e.length/2;void 0===s&&((o=sN(a,e))[0],o[1],s=o[2]),i=ZE(e,u);var l=Math.cos(s),c=Math.sin(s),p=Math.sqrt((i[1]-i[0])*(i[1]-i[0])+(i[3]-i[2])*(i[3]-i[2])),h=.3;"NECKLACE"==a&&(h=.5),"MARTEL-BOTTLE"==a&&(h=.2),"EQA"==a&&(h=.2),"BARTENDER"==a&&(h=.2);var d=(p+=h*p)/Math.max(n,t),f=(t-1)/2,m=(n-1)/2,g=(i[0]+i[1])/2-(l*d*f-c*d*m),y=(i[2]+i[3])/2-(c*d*f+l*d*m);if(null!=r){if("NECKLACE"==a){var b=.9;g=b*g+(1-b)*r[2],y=b*y+(1-b)*r[5],d=.3*d+.7*r[7],Math.abs(s-r[6])<1&&(s=.3*s+.7*r[6])}else{var _=Math.sqrt((g-r[2])*(g-r[2])+(y-r[5])*(y-r[5])),x=1;_>20&&(x=.1),_>=10&&_<=20&&(x=1-.09*(_-5)),g=(1-x)*g+x*r[2],y=(1-x)*y+x*r[5],s=Math.abs(s-r[6])>1?(1-x)*s-x*r[6]:(1-x)*s+x*r[6],d=(1-x)*d+x*r[7]}l=Math.cos(s),c=Math.sin(s)}return[l*d,-c*d,g,c*d,l*d,y,s,d]}(void 0===p?o:p,this._trackerConfig.inWidth,this._trackerConfig.inHeight,t==iN.Detected||this._fastMvt?null:this._simCropToImage,a,c);var _=new ImageData(this._trackerConfig.inWidth,this._trackerConfig.inHeight);_=oN(e,_,this._simCropToImage),this._debug&&t!=iN.Detected&&(this._debugInitialized=!0,this._debugImage=_);var x=zN(this._tfKeypointsTracker,this._trackerConfig,this._poseModule,[this._bufferHeatmaps],[this._bufferKeypsTrack],[this._bufferFeatureScores],[_],[this._flipMode]),v=rN(x.coordinates[0],this._simCropToImage,this._flipMode,new Int32Array([this._trackerConfig.outHeight,this._trackerConfig.outWidth]));if(t!=iN.Detected){var w=nN(x.scores[0],this._config.validTrackedKeypThs);if(a==ON.Face&&!this._nonRigidInitialized){var T=this._pose.project(this._keypsVts,MN.getCameraMat(this._config.fovY,this._currentWidth,this._currentHeight)),k=v.length/2;for(f=0;f<k;f++)0==w[f]&&(w[f]=1,v[f]=T[2*f],v[f+k]=T[2*f+1])}v=pN(v,w,o,r,.1)}return{imageFilteredKeyps:v,cropKeyps:x.coordinates[0],scores:x.scores[0]}},e.prototype.trackSubGeometrySync=function(e,t,n){var r=this;if(!(this._config.subTrackerCenterIds&&this._config.subTrackerAngleIds&&this._config.subTrackerIds&&this._config.subTrackerExtRatio))return{subTrackerKeyps:[new Float32Array(0)],subTrackerKeypsScores:[new Float32Array(0)],subTrackerVisibility:[new Int32Array(0)]};var a=hN(t,new Int32Array([this._subTrackerConfig.inWidth,this._subTrackerConfig.inHeight]),this._config.subTrackerIds,this._config.subTrackerAngleIds,this._config.subTrackerCenterIds,this._config.subTrackerExtRatio,this._config.subTrackerAngleShift),s=[a],o=[oN(e,new ImageData(this._subTrackerConfig.inWidth,this._subTrackerConfig.inHeight),a)];if(this._config.subTrackerSymmetric&&this._config.subTrackerSymmetricIds){var i=hN(t,new Int32Array([this._subTrackerConfig.inWidth,this._subTrackerConfig.inHeight]),this._config.subTrackerSymmetricIds,this._config.subTrackerAngleIds,this._config.subTrackerCenterIds,this._config.subTrackerExtRatio,this._config.subTrackerAngleShift);s=s.concat([i]);var u=new ImageData(this._subTrackerConfig.inWidth,this._subTrackerConfig.inHeight);o=o.concat([oN(e,u,i)])}var l=[""],c=[this._poseModule._malloc(2*this._subTrackerOutDims[3]*this._float_size)],p=[this._poseModule._malloc(this._subTrackerOutDims[3]*this._float_size)];this._config.subTrackerSymmetric&&(c=c.concat([this._poseModule._malloc(2*this._subTrackerOutDims[3]*this._float_size)]),p=p.concat([this._poseModule._malloc(this._subTrackerOutDims[3]*this._float_size)]),l=l.concat(["left_right"]));for(var h=zN(this._tfSubTracker,this._subTrackerConfig,null,[this._bufSubTrackerHmaps,this._bufSubTrackerHmapsSym],c,p,o,l),d=0;d<c.length;d++)this._poseModule._free(c[d]);for(d=0;d<p.length;d++)this._poseModule._free(p[d]);var f=[],m=[],g=[];return h.coordinates.forEach((function(e,t){m=m.concat([h.scores[t]]);var n=new Int32Array(h.scores[t].length);h.scores[t].forEach((function(e,t){n[t]=e>.25?1:0})),g=g.concat([n]),r._subTrackerCropKeyps&&r._subTrackerCropKeyps.length>t?r._subTrackerCropKeyps[t]=pN(e,n,r._subTrackerCropKeyps[t],r._subTrackerVis[t],.1):r._subTrackerCropKeyps=r._subTrackerCropKeyps.concat([e]);var a=rN(r._subTrackerCropKeyps[t],s[t],l[t],new Int32Array([r._subTrackerConfig.outHeight,r._subTrackerConfig.outWidth]));f=f.concat([a])})),{subTrackerKeyps:f,subTrackerKeypsScores:m,subTrackerVisibility:g}},e.prototype.computePoseSync=function(e,t){return this._nonRigidInitialized&&(VN(t)||t==ON.Wrist||t==ON.Face)?this.computeNonRigidPoseSync(e,t):this.computeRigidPoseSync(e,t)},e.prototype.computeRigidPoseSync=function(e,t){var n=this,r=-1,a=this._poseModule.cwrap("xzimgEstimateRigidPose","number",["number","number","number","number","number","number","number","number","number","number","number","number"]);if(e==iN.Detection){var s=0,o=0,i=t==ON.Necklace?3:0,u=1,l=[1,0,0,0,1,0],c=(h=this._poseModule._malloc(6*this._float_size))/4,p=this._poseModule.HEAPF32.subarray(c,c+6);return this._trackHasHeatmaps?p.set(this._simCropToImage.slice(0,6)):p.set(l),r=a(this._bufferHeatmaps,this._detectorOutDims[1],this._detectorOutDims[2],this._detectorOutDims[3],s,h,this._bufferKeypsDet,this.isMirrored()?this._bufMirroredKeyps3D:this._bufKeyps3D,o,i,u,this._bufInOutPose),this._pose=new MN(new Float32Array(this._poseModule.HEAPF32.buffer,this._bufInOutPose,9),new Float32Array(this._poseModule.HEAPF32.buffer,this._bufInOutPose+9*this._float_size,3)),r}if(e==iN.Detected||e==iN.Tracking){s=0,o=e!=iN.Tracking||this._resetPose?0:1,this._resetPose=!1,i=t==ON.Hand||t==ON.Necklace||t==ON.Lamborghini?3:1,u=t==ON.Hand||t==ON.Necklace||t==ON.Lamborghini?3:1,c=(h=this._poseModule._malloc(6*this._float_size))/4;var h,d=this._poseModule.HEAPF32.subarray(c,c+6);this._trackHasHeatmaps&&3==i?d.set(this._simCropToImage.slice(0,6)):(l=[1,0,0,0,1,0],d.set(l));var f=null,m=null,g=new Float32Array(2*this._activeIds.length),y=new Float32Array(3*this._activeIds.length),b=this._keyps2D.length/2;this._activeIds.length>0?(this._activeIds.forEach((function(e,t){g[t]=n._keyps2D[e],g[t+n._activeIds.length]=n._keyps2D[e+b]})),c=(f=this._poseModule._malloc(this._activeIds.length*this._float_size*2))/4,(d=this._poseModule.HEAPF32.subarray(c,c+2*this._activeIds.length)).set(g),this._activeIds.forEach((function(e,t){y[3*t]=n._keypsVts[3*e],n.isMirrored()&&(y[3*t]=-y[3*t]),y[3*t+1]=n._keypsVts[3*e+1],y[3*t+2]=n._keypsVts[3*e+2]})),c=(m=this._poseModule._malloc(this._activeIds.length*this._float_size*3))/4,(d=this._poseModule.HEAPF32.subarray(c,c+3*this._activeIds.length)).set(y),b=this._activeIds.length):(c=(f=this._poseModule._malloc(this._keyps2D.length*this._float_size))/4,(d=this._poseModule.HEAPF32.subarray(c,c+this._keyps2D.length)).set(this._keyps2D),2!=i&&3!=i||d.set(this._cropKeyps2D),m=this.isMirrored()?this._bufMirroredKeyps3D:this._bufKeyps3D),r=a(2==i||3==i?this._bufferHeatmaps:null,this._trackerOutDims[1],this._trackerOutDims[2],b,s,h,f,m,o,i,u,this._bufInOutPose);var _=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufInOutPose,9),x=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufInOutPose+9*this._float_size,3);this._pose=new MN(_,x);var v=this._pose.project(this._keypsVts,MN.getCameraMat(this._config.fovY,this._currentWidth,this._currentHeight));this._reprojKeyps2D=new Float32Array(v.length);for(var w=0;w<v.length/2;w++)this._reprojKeyps2D[w]=v[2*w],this._reprojKeyps2D[w+this._reprojKeyps2D.length/2]=v[2*w+1];if(t==ON.Necklace){var T=this._pose.getRot();T[5]>.35&&(console.log(T[2],T[5],T[8]),T[2]=0,T[5]=0,T[8]=-1,this._pose.updateRotation(T))}return this._keyps3D=this._pose.transform(this._keypsVts),this._debug&&console.log("reprojDist",r),f&&this._poseModule._free(f),m&&this._activeIds.length>0&&this._poseModule._free(m),h&&this._poseModule._free(h),r}return-1},e.prototype.computeNonRigidPoseSync=function(e,t){var n;n=VN(t)?this._poseModule.cwrap("xzimgEstimateBodyNonRigidPose","number",["number","number","number","number","number","number","number","number","number","number","number"]):this._poseModule.cwrap("xzimgEstimateNonRigidPoseBase","number",["number","number","number","number","number","number","number","number","number","number","number","number"]);var r,a=e==iN.Detected?1:0,s=this._trackerOutDims[3],o=(r=this._poseModule._malloc(this._keyps2D.length*this._float_size))/4;this._poseModule.HEAPF32.subarray(o,o+this._keyps2D.length).set(this._keyps2D);var i=this._poseModule._malloc(s*this._int_size),u=i/4;this._poseModule.HEAPF32.subarray(u,u+s).set(this._visibility),null==this._bufKeyps3D&&(this._bufKeyps3D=this._poseModule._malloc(s*this._float_size*3));var l=1e3;t==ON.Face&&(l=25),t==ON.Wrist&&(l=100);var c=performance.now(),p=n(a,r,s,i,5,l,this._config.reprojThs,.5,.75,.95,this._bufInOutPose,this._bufKeyps3D),h=performance.now();this.mean_t=.95*this.mean_t+.05*(h-c);var d=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufInOutPose,9),f=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufInOutPose+9*this._float_size,3);this._pose=new MN(d,f),this._keyps3D=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufKeyps3D,3*s),this._poseModule._free(r),this._poseModule._free(i);var m=this._poseModule.cwrap("xzimgEstimateGetNumVertices","number"),g=this._poseModule.cwrap("xzimgEstimateGetDenseVertices","number"),y=m();y>0&&(null==this._bufDenseVertices3D&&(this._bufDenseVertices3D=this._poseModule._malloc(y*this._float_size*3)),g(this._bufDenseVertices3D),this._denseVertices=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufDenseVertices3D,3*y));var b=this._poseModule.cwrap("xzimgEstimateGetNumBlendShapes","number"),_=this._poseModule.cwrap("xzimgEstimateGetBlendShapes","number"),x=b();if(x>0){var v=this._poseModule._malloc(x*this._float_size),w=_(v);this._debug&&console.log(w),this._bsCoefs=new Float32Array(this._poseModule.HEAPF32.buffer,v,x),this._poseModule._free(v)}return this._debug&&console.log(p),this._debug&&console.log(d),this._debug&&console.log(f),p},e}()})(),r})()));
|
|
2
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.__deeparDynamicJsModule_xzimg__=t():e.__deeparDynamicJsModule_xzimg__=t()}(self,(()=>(()=>{var e={683:()=>{},345:()=>{}},t={};function n(r){var a=t[r];if(void 0!==a)return a.exports;var s=t[r]={exports:{}};return e[r](s,s.exports,n),s.exports}n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};return(()=>{"use strict";function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if("default"!==n&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}}))})),Object.freeze(e)}n.r(r),n.d(r,{Foot:()=>cN,Geometry:()=>yN,Segmentation:()=>WT,VideoManager:()=>i});var t=function(){return t=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var a in t=arguments[n])Object.prototype.hasOwnProperty.call(t,a)&&(e[a]=t[a]);return e},t.apply(this,arguments)};function a(e,t,n,r){return new(n||(n=Promise))((function(a,s){function o(e){try{u(r.next(e))}catch(e){s(e)}}function i(e){try{u(r.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?a(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,i)}u((r=r.apply(e,t||[])).next())}))}function s(e,t){var n,r,a,s,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return s={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function i(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,i[0]&&(o=0)),o;)try{if(n=1,r&&(a=2&i[0]?r.return:i[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,i[1])).done)return a;switch(r=0,a&&(i=[2&i[0],a.value]),i[0]){case 0:case 1:a=i;break;case 4:return o.label++,{value:i[1],done:!1};case 5:o.label++,r=i[1],i=[0];continue;case 7:i=o.ops.pop(),o.trys.pop();continue;default:if(!((a=(a=o.trys).length>0&&a[a.length-1])||6!==i[0]&&2!==i[0])){o=0;continue}if(3===i[0]&&(!a||i[1]>a[0]&&i[1]<a[3])){o.label=i[1];break}if(6===i[0]&&o.label<a[1]){o.label=a[1],a=i;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(i);break}a[2]&&o.ops.pop(),o.trys.pop();continue}i=t.call(e,o)}catch(e){i=[6,e],r=0}finally{n=a=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}}function o(e,t,n){if(n||2===arguments.length)for(var r,a=0,s=t.length;a<s;a++)!r&&a in t||(r||(r=Array.prototype.slice.call(t,0,a)),r[a]=t[a]);return e.concat(r||Array.prototype.slice.call(t))}var i=function(){function e(e,t,n){this.NB_BUFFERS=5,this._videoFrames=[],this._nbFramesDelay=0,this._videoElement=e,this._videoCanvas=document.createElement("canvas"),this._videoCanvas.style.display="none",this._videoCanvasContext=this._videoCanvas.getContext("2d",{willReadFrequently:!0}),null!=t&&(this._videoCanvas.width=t),null!=n&&(this._videoCanvas.height=n)}return e.prototype.getNbFramesDelay=function(){return this._nbFramesDelay},e.prototype.setNbFramesDelay=function(e){e>=0&&e<this.NB_BUFFERS?this._nbFramesDelay=e:console.error("Invalid frames delay, delay must be less than ",this.NB_BUFFERS)},e.prototype.getVideoCanvas=function(){return this._videoCanvas},e.prototype.preProcessWithBuffer=function(e){return this._videoFrames.length===this.NB_BUFFERS&&(this._videoFrames=this._videoFrames.slice(0,-1)),this._videoFrames=o([e],this._videoFrames,!0),!0},e.prototype.preProcess=function(){if(null==this._videoElement||0===this._videoElement.videoWidth||0===this._videoElement.videoHeight)return!1;this._videoCanvas.width===this._videoElement.videoWidth&&this._videoCanvas.height===this._videoElement.videoHeight||(this._videoFrames=[],this._videoCanvas.width=this._videoElement.videoWidth,this._videoCanvas.height=this._videoElement.videoHeight),this._videoCanvasContext.drawImage(this._videoElement,0,0,this._videoCanvas.width,this._videoCanvas.height);var e=this._videoCanvasContext.getImageData(0,0,this._videoCanvas.width,this._videoCanvas.height);return this._videoFrames.length===this.NB_BUFFERS&&(this._videoFrames=this._videoFrames.slice(0,-1)),this._videoFrames=o([e],this._videoFrames,!0),!0},e.prototype.postProcess=function(){if(this._nbFramesDelay>0&&this._videoFrames.length>0){var e=this._nbFramesDelay<this._videoFrames.length?this._videoFrames[this._nbFramesDelay]:this._videoFrames[this._videoFrames.length-1];this._videoCanvasContext.putImageData(e,0,0)}},e.prototype.getCameraFrame=function(){if(this._nbFramesDelay>0&&this._videoFrames.length>0)return this._nbFramesDelay<this._videoFrames.length?this._videoFrames[this._nbFramesDelay]:this._videoFrames[this._videoFrames.length-1]},e.prototype.updateDelay=function(e){e>=0&&e<this.NB_BUFFERS?this._nbFramesDelay=e:console.error("Invalid frames delay, delay must be less than ",this.NB_BUFFERS)},e.prototype.getLastBuffer=function(){return this._videoFrames.length>0?this._videoFrames[0]:null},e.prototype.setOverlapingImage=function(e){this._videoCanvasContext.putImageData(e,10,10)},e}(),u=function(e,t){return u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},u(e,t)};function l(e,t){function n(){this.constructor=e}u(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function c(e){return"function"==typeof e}var p=!1,h={Promise:void 0,set useDeprecatedSynchronousErrorHandling(e){e&&(new Error).stack,p=e},get useDeprecatedSynchronousErrorHandling(){return p}};function d(e){setTimeout((function(){throw e}),0)}var f={closed:!0,next:function(e){},error:function(e){if(h.useDeprecatedSynchronousErrorHandling)throw e;d(e)},complete:function(){}},m=Array.isArray||function(e){return e&&"number"==typeof e.length};function g(e){return null!==e&&"object"==typeof e}var y=function(){function e(e){return Error.call(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=e,this}return e.prototype=Object.create(Error.prototype),e}(),b=y,_=function(){function e(e){this.closed=!1,this._parentOrParents=null,this._subscriptions=null,e&&(this._ctorUnsubscribe=!0,this._unsubscribe=e)}return e.prototype.unsubscribe=function(){var t;if(!this.closed){var n=this,r=n._parentOrParents,a=n._ctorUnsubscribe,s=n._unsubscribe,o=n._subscriptions;if(this.closed=!0,this._parentOrParents=null,this._subscriptions=null,r instanceof e)r.remove(this);else if(null!==r)for(var i=0;i<r.length;++i)r[i].remove(this);if(c(s)){a&&(this._unsubscribe=void 0);try{s.call(this)}catch(e){t=e instanceof b?x(e.errors):[e]}}if(m(o)){i=-1;for(var u=o.length;++i<u;){var l=o[i];if(g(l))try{l.unsubscribe()}catch(e){t=t||[],e instanceof b?t=t.concat(x(e.errors)):t.push(e)}}}if(t)throw new b(t)}},e.prototype.add=function(t){var n=t;if(!t)return e.EMPTY;switch(typeof t){case"function":n=new e(t);case"object":if(n===this||n.closed||"function"!=typeof n.unsubscribe)return n;if(this.closed)return n.unsubscribe(),n;if(!(n instanceof e)){var r=n;(n=new e)._subscriptions=[r]}break;default:throw new Error("unrecognized teardown "+t+" added to Subscription.")}var a=n._parentOrParents;if(null===a)n._parentOrParents=this;else if(a instanceof e){if(a===this)return n;n._parentOrParents=[a,this]}else{if(-1!==a.indexOf(this))return n;a.push(this)}var s=this._subscriptions;return null===s?this._subscriptions=[n]:s.push(n),n},e.prototype.remove=function(e){var t=this._subscriptions;if(t){var n=t.indexOf(e);-1!==n&&t.splice(n,1)}},e.EMPTY=function(e){return e.closed=!0,e}(new e),e}();function x(e){return e.reduce((function(e,t){return e.concat(t instanceof b?t.errors:t)}),[])}var v="function"==typeof Symbol?Symbol("rxSubscriber"):"@@rxSubscriber_"+Math.random(),w=function(e){function t(n,r,a){var s=e.call(this)||this;switch(s.syncErrorValue=null,s.syncErrorThrown=!1,s.syncErrorThrowable=!1,s.isStopped=!1,arguments.length){case 0:s.destination=f;break;case 1:if(!n){s.destination=f;break}if("object"==typeof n){n instanceof t?(s.syncErrorThrowable=n.syncErrorThrowable,s.destination=n,n.add(s)):(s.syncErrorThrowable=!0,s.destination=new T(s,n));break}default:s.syncErrorThrowable=!0,s.destination=new T(s,n,r,a)}return s}return l(t,e),t.prototype[v]=function(){return this},t.create=function(e,n,r){var a=new t(e,n,r);return a.syncErrorThrowable=!1,a},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this))},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){this.destination.error(e),this.unsubscribe()},t.prototype._complete=function(){this.destination.complete(),this.unsubscribe()},t.prototype._unsubscribeAndRecycle=function(){var e=this._parentOrParents;return this._parentOrParents=null,this.unsubscribe(),this.closed=!1,this.isStopped=!1,this._parentOrParents=e,this},t}(_),T=function(e){function t(t,n,r,a){var s,o=e.call(this)||this;o._parentSubscriber=t;var i=o;return c(n)?s=n:n&&(s=n.next,r=n.error,a=n.complete,n!==f&&(c((i=Object.create(n)).unsubscribe)&&o.add(i.unsubscribe.bind(i)),i.unsubscribe=o.unsubscribe.bind(o))),o._context=i,o._next=s,o._error=r,o._complete=a,o}return l(t,e),t.prototype.next=function(e){if(!this.isStopped&&this._next){var t=this._parentSubscriber;h.useDeprecatedSynchronousErrorHandling&&t.syncErrorThrowable?this.__tryOrSetError(t,this._next,e)&&this.unsubscribe():this.__tryOrUnsub(this._next,e)}},t.prototype.error=function(e){if(!this.isStopped){var t=this._parentSubscriber,n=h.useDeprecatedSynchronousErrorHandling;if(this._error)n&&t.syncErrorThrowable?(this.__tryOrSetError(t,this._error,e),this.unsubscribe()):(this.__tryOrUnsub(this._error,e),this.unsubscribe());else if(t.syncErrorThrowable)n?(t.syncErrorValue=e,t.syncErrorThrown=!0):d(e),this.unsubscribe();else{if(this.unsubscribe(),n)throw e;d(e)}}},t.prototype.complete=function(){var e=this;if(!this.isStopped){var t=this._parentSubscriber;if(this._complete){var n=function(){return e._complete.call(e._context)};h.useDeprecatedSynchronousErrorHandling&&t.syncErrorThrowable?(this.__tryOrSetError(t,n),this.unsubscribe()):(this.__tryOrUnsub(n),this.unsubscribe())}else this.unsubscribe()}},t.prototype.__tryOrUnsub=function(e,t){try{e.call(this._context,t)}catch(e){if(this.unsubscribe(),h.useDeprecatedSynchronousErrorHandling)throw e;d(e)}},t.prototype.__tryOrSetError=function(e,t,n){if(!h.useDeprecatedSynchronousErrorHandling)throw new Error("bad call");try{t.call(this._context,n)}catch(t){return h.useDeprecatedSynchronousErrorHandling?(e.syncErrorValue=t,e.syncErrorThrown=!0,!0):(d(t),!0)}return!1},t.prototype._unsubscribe=function(){var e=this._parentSubscriber;this._context=null,this._parentSubscriber=null,e.unsubscribe()},t}(w),k="function"==typeof Symbol&&Symbol.observable||"@@observable";function I(e){return e}var S=function(){function e(e){this._isScalar=!1,e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var r=this.operator,a=function(e,t,n){if(e){if(e instanceof w)return e;if(e[v])return e[v]()}return e||t||n?new w(e,t,n):new w(f)}(e,t,n);if(r?a.add(r.call(a,this.source)):a.add(this.source||h.useDeprecatedSynchronousErrorHandling&&!a.syncErrorThrowable?this._subscribe(a):this._trySubscribe(a)),h.useDeprecatedSynchronousErrorHandling&&a.syncErrorThrowable&&(a.syncErrorThrowable=!1,a.syncErrorThrown))throw a.syncErrorValue;return a},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){h.useDeprecatedSynchronousErrorHandling&&(e.syncErrorThrown=!0,e.syncErrorValue=t),function(e){for(;e;){var t=e,n=t.closed,r=t.destination,a=t.isStopped;if(n||a)return!1;e=r&&r instanceof w?r:null}return!0}(e)?e.error(t):console.warn(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=E(t))((function(t,r){var a;a=n.subscribe((function(t){try{e(t)}catch(e){r(e),a&&a.unsubscribe()}}),r,t)}))},e.prototype._subscribe=function(e){var t=this.source;return t&&t.subscribe(e)},e.prototype[k]=function(){return this},e.prototype.pipe=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return 0===t.length?this:(0===(e=t).length?I:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)})(this)},e.prototype.toPromise=function(e){var t=this;return new(e=E(e))((function(e,n){var r;t.subscribe((function(e){return r=e}),(function(e){return n(e)}),(function(){return e(r)}))}))},e.create=function(t){return new e(t)},e}();function E(e){if(e||(e=h.Promise||Promise),!e)throw new Error("no Promise impl found");return e}var N=function(e){return function(t){for(var n=0,r=e.length;n<r&&!t.closed;n++)t.next(e[n]);t.complete()}},C="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator",A=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function R(e){return!!e&&"function"!=typeof e.subscribe&&"function"==typeof e.then}var $=function(e){if(e&&"function"==typeof e[k])return r=e,function(e){var t=r[k]();if("function"!=typeof t.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return t.subscribe(e)};if(A(e))return N(e);if(R(e))return n=e,function(e){return n.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,d),e};if(e&&"function"==typeof e[C])return t=e,function(e){for(var n=t[C]();;){var r=void 0;try{r=n.next()}catch(t){return e.error(t),e}if(r.done){e.complete();break}if(e.next(r.value),e.closed)break}return"function"==typeof n.return&&e.add((function(){n.return&&n.return()})),e};var t,n,r,a=g(e)?"an invalid object":"'"+e+"'";throw new TypeError("You provided "+a+" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.")},M=function(e){function t(t){var n=e.call(this)||this;return n.parent=t,n}return l(t,e),t.prototype._next=function(e){this.parent.notifyNext(e)},t.prototype._error=function(e){this.parent.notifyError(e),this.unsubscribe()},t.prototype._complete=function(){this.parent.notifyComplete(),this.unsubscribe()},t}(w),F=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l(t,e),t.prototype.notifyNext=function(e){this.destination.next(e)},t.prototype.notifyError=function(e){this.destination.error(e)},t.prototype.notifyComplete=function(){this.destination.complete()},t}(w);function O(e){return e&&"function"==typeof e.schedule}var D=function(e){function t(t,n,r){var a=e.call(this)||this;return a.parent=t,a.outerValue=n,a.outerIndex=r,a.index=0,a}return l(t,e),t.prototype._next=function(e){this.parent.notifyNext(this.outerValue,e,this.outerIndex,this.index++,this)},t.prototype._error=function(e){this.parent.notifyError(e,this),this.unsubscribe()},t.prototype._complete=function(){this.parent.notifyComplete(this),this.unsubscribe()},t}(w);function L(e,t,n,r,a){if(void 0===a&&(a=new D(e,n,r)),!a.closed)return t instanceof S?t.subscribe(a):$(t)(a)}var P=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l(t,e),t.prototype.notifyNext=function(e,t,n,r,a){this.destination.next(t)},t.prototype.notifyError=function(e,t){this.destination.error(e)},t.prototype.notifyComplete=function(e){this.destination.complete()},t}(w);function B(e,t){return new S((function(n){var r=new _,a=0;return r.add(t.schedule((function(){a!==e.length?(n.next(e[a++]),n.closed||r.add(this.schedule())):n.complete()}))),r}))}function U(e,t){return t?B(e,t):new S(N(e))}var z={};function V(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=void 0,r=void 0;return O(e[e.length-1])&&(r=e.pop()),"function"==typeof e[e.length-1]&&(n=e.pop()),1===e.length&&m(e[0])&&(e=e[0]),U(e,r).lift(new W(n))}var W=function(){function e(e){this.resultSelector=e}return e.prototype.call=function(e,t){return t.subscribe(new H(e,this.resultSelector))},e}(),H=function(e){function t(t,n){var r=e.call(this,t)||this;return r.resultSelector=n,r.active=0,r.values=[],r.observables=[],r}return l(t,e),t.prototype._next=function(e){this.values.push(z),this.observables.push(e)},t.prototype._complete=function(){var e=this.observables,t=e.length;if(0===t)this.destination.complete();else{this.active=t,this.toRespond=t;for(var n=0;n<t;n++){var r=e[n];this.add(L(this,r,void 0,n))}}},t.prototype.notifyComplete=function(e){0==(this.active-=1)&&this.destination.complete()},t.prototype.notifyNext=function(e,t,n){var r=this.values,a=r[n],s=this.toRespond?a===z?--this.toRespond:this.toRespond:0;r[n]=t,0===s&&(this.resultSelector?this._tryResultSelector(r):this.destination.next(r.slice()))},t.prototype._tryResultSelector=function(e){var t;try{t=this.resultSelector.apply(this,e)}catch(e){return void this.destination.error(e)}this.destination.next(t)},t}(P);function G(e,t){return t?function(e,t){if(null!=e){if(function(e){return e&&"function"==typeof e[k]}(e))return function(e,t){return new S((function(n){var r=new _;return r.add(t.schedule((function(){var a=e[k]();r.add(a.subscribe({next:function(e){r.add(t.schedule((function(){return n.next(e)})))},error:function(e){r.add(t.schedule((function(){return n.error(e)})))},complete:function(){r.add(t.schedule((function(){return n.complete()})))}}))}))),r}))}(e,t);if(R(e))return function(e,t){return new S((function(n){var r=new _;return r.add(t.schedule((function(){return e.then((function(e){r.add(t.schedule((function(){n.next(e),r.add(t.schedule((function(){return n.complete()})))})))}),(function(e){r.add(t.schedule((function(){return n.error(e)})))}))}))),r}))}(e,t);if(A(e))return B(e,t);if(function(e){return e&&"function"==typeof e[C]}(e)||"string"==typeof e)return function(e,t){if(!e)throw new Error("Iterable cannot be null");return new S((function(n){var r,a=new _;return a.add((function(){r&&"function"==typeof r.return&&r.return()})),a.add(t.schedule((function(){r=e[C](),a.add(t.schedule((function(){if(!n.closed){var e,t;try{var a=r.next();e=a.value,t=a.done}catch(e){return void n.error(e)}t?n.complete():(n.next(e),this.schedule())}})))}))),a}))}(e,t)}throw new TypeError((null!==e&&typeof e||e)+" is not observable")}(e,t):e instanceof S?e:new S($(e))}function j(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e[e.length-1];return O(n)?(e.pop(),B(e,n)):U(e)}function K(e,t){return function(n){if("function"!=typeof e)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return n.lift(new q(e,t))}}var q=function(){function e(e,t){this.project=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new X(e,this.project,this.thisArg))},e}(),X=function(e){function t(t,n,r){var a=e.call(this,t)||this;return a.project=n,a.count=0,a.thisArg=r||a,a}return l(t,e),t.prototype._next=function(e){var t;try{t=this.project.call(this.thisArg,e,this.count++)}catch(e){return void this.destination.error(e)}this.destination.next(t)},t}(w),Y=new S((function(e){return e.complete()}));function Q(e,t){return new S(t?function(n){return t.schedule(J,0,{error:e,subscriber:n})}:function(t){return t.error(e)})}function J(e){var t=e.error;e.subscriber.error(t)}function Z(e){return function(t){return t.lift(new ee(e))}}var ee=function(){function e(e){this.callback=e}return e.prototype.call=function(e,t){return t.subscribe(new te(e,this.callback))},e}(),te=function(e){function t(t,n){var r=e.call(this,t)||this;return r.add(new _(n)),r}return l(t,e),t}(w),ne=function(){function e(){return Error.call(this),this.message="object unsubscribed",this.name="ObjectUnsubscribedError",this}return e.prototype=Object.create(Error.prototype),e}(),re=function(e){function t(t,n){var r=e.call(this)||this;return r.subject=t,r.subscriber=n,r.closed=!1,r}return l(t,e),t.prototype.unsubscribe=function(){if(!this.closed){this.closed=!0;var e=this.subject,t=e.observers;if(this.subject=null,t&&0!==t.length&&!e.isStopped&&!e.closed){var n=t.indexOf(this.subscriber);-1!==n&&t.splice(n,1)}}},t}(_),ae=function(e){function t(t){var n=e.call(this,t)||this;return n.destination=t,n}return l(t,e),t}(w),se=function(e){function t(){var t=e.call(this)||this;return t.observers=[],t.closed=!1,t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return l(t,e),t.prototype[v]=function(){return new ae(this)},t.prototype.lift=function(e){var t=new oe(this,this);return t.operator=e,t},t.prototype.next=function(e){if(this.closed)throw new ne;if(!this.isStopped)for(var t=this.observers,n=t.length,r=t.slice(),a=0;a<n;a++)r[a].next(e)},t.prototype.error=function(e){if(this.closed)throw new ne;this.hasError=!0,this.thrownError=e,this.isStopped=!0;for(var t=this.observers,n=t.length,r=t.slice(),a=0;a<n;a++)r[a].error(e);this.observers.length=0},t.prototype.complete=function(){if(this.closed)throw new ne;this.isStopped=!0;for(var e=this.observers,t=e.length,n=e.slice(),r=0;r<t;r++)n[r].complete();this.observers.length=0},t.prototype.unsubscribe=function(){this.isStopped=!0,this.closed=!0,this.observers=null},t.prototype._trySubscribe=function(t){if(this.closed)throw new ne;return e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){if(this.closed)throw new ne;return this.hasError?(e.error(this.thrownError),_.EMPTY):this.isStopped?(e.complete(),_.EMPTY):(this.observers.push(e),new re(this,e))},t.prototype.asObservable=function(){var e=new S;return e.source=this,e},t.create=function(e,t){return new oe(e,t)},t}(S),oe=function(e){function t(t,n){var r=e.call(this)||this;return r.destination=t,r.source=n,r}return l(t,e),t.prototype.next=function(e){var t=this.destination;t&&t.next&&t.next(e)},t.prototype.error=function(e){var t=this.destination;t&&t.error&&this.destination.error(e)},t.prototype.complete=function(){var e=this.destination;e&&e.complete&&this.destination.complete()},t.prototype._subscribe=function(e){return this.source?this.source.subscribe(e):_.EMPTY},t}(se),ie=function(e){function t(t){var n=e.call(this)||this;return n._value=t,n}return l(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!0,configurable:!0}),t.prototype._subscribe=function(t){var n=e.prototype._subscribe.call(this,t);return n&&!n.closed&&t.next(this._value),n},t.prototype.getValue=function(){if(this.hasError)throw this.thrownError;if(this.closed)throw new ne;return this._value},t.prototype.next=function(t){e.prototype.next.call(this,this._value=t)},t}(se);function ue(e){return void 0===e&&(e=-1),function(t){return t.lift(new le(e,t))}}var le=function(){function e(e,t){this.count=e,this.source=t}return e.prototype.call=function(e,t){return t.subscribe(new ce(e,this.count,this.source))},e}(),ce=function(e){function t(t,n,r){var a=e.call(this,t)||this;return a.count=n,a.source=r,a}return l(t,e),t.prototype.error=function(t){if(!this.isStopped){var n=this.source,r=this.count;if(0===r)return e.prototype.error.call(this,t);r>-1&&(this.count=r-1),n.subscribe(this._unsubscribeAndRecycle())}},t}(w);function pe(e,t){return"function"==typeof t?function(n){return n.pipe(pe((function(n,r){return G(e(n,r)).pipe(K((function(e,a){return t(n,e,r,a)})))})))}:function(t){return t.lift(new he(e))}}var he=function(){function e(e){this.project=e}return e.prototype.call=function(e,t){return t.subscribe(new de(e,this.project))},e}(),de=function(e){function t(t,n){var r=e.call(this,t)||this;return r.project=n,r.index=0,r}return l(t,e),t.prototype._next=function(e){var t,n=this.index++;try{t=this.project(e,n)}catch(e){return void this.destination.error(e)}this._innerSub(t)},t.prototype._innerSub=function(e){var t=this.innerSubscription;t&&t.unsubscribe();var n=new M(this),r=this.destination;r.add(n),this.innerSubscription=function(e,t){if(!t.closed){if(e instanceof S)return e.subscribe(t);var n;try{n=$(e)(t)}catch(e){t.error(e)}return n}}(e,n),this.innerSubscription!==n&&r.add(this.innerSubscription)},t.prototype._complete=function(){var t=this.innerSubscription;t&&!t.closed||e.prototype._complete.call(this),this.unsubscribe()},t.prototype._unsubscribe=function(){this.innerSubscription=void 0},t.prototype.notifyComplete=function(){this.innerSubscription=void 0,this.isStopped&&e.prototype._complete.call(this)},t.prototype.notifyNext=function(e){this.destination.next(e)},t}(F);function fe(){}function me(e,t,n){return function(r){return r.lift(new ge(e,t,n))}}var ge=function(){function e(e,t,n){this.nextOrObserver=e,this.error=t,this.complete=n}return e.prototype.call=function(e,t){return t.subscribe(new ye(e,this.nextOrObserver,this.error,this.complete))},e}(),ye=function(e){function t(t,n,r,a){var s=e.call(this,t)||this;return s._tapNext=fe,s._tapError=fe,s._tapComplete=fe,s._tapError=r||fe,s._tapComplete=a||fe,c(n)?(s._context=s,s._tapNext=n):n&&(s._context=n,s._tapNext=n.next||fe,s._tapError=n.error||fe,s._tapComplete=n.complete||fe),s}return l(t,e),t.prototype._next=function(e){try{this._tapNext.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.next(e)},t.prototype._error=function(e){try{this._tapError.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.error(e)},t.prototype._complete=function(){try{this._tapComplete.call(this._context)}catch(e){return void this.destination.error(e)}return this.destination.complete()},t}(w);function be(e){return new S((function(t){var n;try{n=e()}catch(e){return void t.error(e)}return(n?G(n):Y).subscribe(t)}))}var _e=void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function xe(){throw new Error("setTimeout has not been defined")}function ve(){throw new Error("clearTimeout has not been defined")}var we=xe,Te=ve;function ke(e){if(we===setTimeout)return setTimeout(e,0);if((we===xe||!we)&&setTimeout)return we=setTimeout,setTimeout(e,0);try{return we(e,0)}catch(t){try{return we.call(null,e,0)}catch(t){return we.call(this,e,0)}}}"function"==typeof _e.setTimeout&&(we=setTimeout),"function"==typeof _e.clearTimeout&&(Te=clearTimeout);var Ie,Se=[],Ee=!1,Ne=-1;function Ce(){Ee&&Ie&&(Ee=!1,Ie.length?Se=Ie.concat(Se):Ne=-1,Se.length&&Ae())}function Ae(){if(!Ee){var e=ke(Ce);Ee=!0;for(var t=Se.length;t;){for(Ie=Se,Se=[];++Ne<t;)Ie&&Ie[Ne].run();Ne=-1,t=Se.length}Ie=null,Ee=!1,function(e){if(Te===clearTimeout)return clearTimeout(e);if((Te===ve||!Te)&&clearTimeout)return Te=clearTimeout,clearTimeout(e);try{Te(e)}catch(t){try{return Te.call(null,e)}catch(t){return Te.call(this,e)}}}(e)}}function Re(e,t){this.fun=e,this.array=t}function $e(){}Re.prototype.run=function(){this.fun.apply(null,this.array)};var Me=$e,Fe=$e,Oe=$e,De=$e,Le=$e,Pe=$e,Be=$e,Ue=_e.performance||{},ze=Ue.now||Ue.mozNow||Ue.msNow||Ue.oNow||Ue.webkitNow||function(){return(new Date).getTime()},Ve=new Date,We={nextTick:function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];Se.push(new Re(e,t)),1!==Se.length||Ee||ke(Ae)},title:"browser",browser:!0,env:{},argv:[],version:"",versions:{},on:Me,addListener:Fe,once:Oe,off:De,removeListener:Le,removeAllListeners:Pe,emit:Be,binding:function(e){throw new Error("process.binding is not supported")},cwd:function(){return"/"},chdir:function(e){throw new Error("process.chdir is not supported")},umask:function(){return 0},hrtime:function(e){var t=.001*ze.call(Ue),n=Math.floor(t),r=Math.floor(t%1*1e9);return e&&(n-=e[0],(r-=e[1])<0&&(n--,r+=1e9)),[n,r]},platform:"browser",release:{},config:{},uptime:function(){return(new Date-Ve)/1e3}},He=We;class Ge{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class je{refCount(e){return Ke("refCount")}incRef(e){return Ke("incRef")}timerAvailable(){return!0}time(e){return Ke("time")}read(e){return Ke("read")}readSync(e){return Ke("readSync")}readToGPU(e,t){return Ke("readToGPU")}numDataIds(){return Ke("numDataIds")}disposeData(e,t){return Ke("disposeData")}write(e,t,n){return Ke("write")}move(e,t,n,r,a){return Ke("move")}createTensorFromGPUData(e,t,n){return Ke("createTensorFromGPUData")}memory(){return Ke("memory")}floatPrecision(){return Ke("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return Ke("dispose")}}function Ke(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function qe(e,t,n){return Math.max(e,Math.min(t,n))}function Xe(e){return e%2==0?e:e+1}function Ye(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function Qe(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function Je(e,t,n=""){Qe(tt(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function Ze(e){Qe(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function et(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function tt(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function nt(e){return e%1==0}function rt(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function at(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function st(e,t=(e=>0),n,r){return new Promise(((a,s)=>{let o=0;const i=()=>{if(e())return void a();o++;const u=t(o);null!=n&&o>=n?s():null!=r?r(i,u):setTimeout(i,u)};i()}))}function ot(e,t){let n=1,r=-1;for(let t=0;t<e.length;++t)if(e[t]>=0)n*=e[t];else if(-1===e[t]){if(-1!==r)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${t}`);r=t}else if(e[t]<0)throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`);if(-1===r){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const a=e.slice();return a[r]=t/n,a}function it(e,t){const n=t.length;return Qe((e=null==e?t.map(((e,t)=>t)):[].concat(e)).every((e=>e>=-n&&e<n)),(()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),Qe(e.every((e=>nt(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function ut(e,t){const n=[],r=[],a=null!=t&&Array.isArray(t)&&0===t.length,s=null==t||a?null:it(t,e).sort();let o=0;for(let t=0;t<e.length;++t){if(null!=s){if(s[o]===t&&1!==e[t])throw new Error(`Can't squeeze axis ${t} since its dim '${e[t]}' is not 1`);(null==s[o]||s[o]>t)&&1===e[t]&&(n.push(e[t]),r.push(t)),s[o]<=t&&o++}1!==e[t]&&(n.push(e[t]),r.push(t))}return{newShape:n,keptDims:r}}function lt(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else{if("bool"!==e)throw new Error(`Unknown data type ${e}`);n=new Uint8Array(t)}return n}function ct(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error(`Unknown data type ${e}`);n=new Array(t)}return n}function pt(e,t){return!("complex64"===t||"float32"===t&&"complex64"!==e||"int32"===t&&"float32"!==e&&"complex64"!==e||"bool"===t&&"bool"===e)}function ht(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error(`Unknown dtype ${e}`)}function dt(e){return"string"==typeof e||e instanceof String}function ft(e){return Array.isArray(e)?ft(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":"number"==typeof e?"float32":dt(e)?"string":function(e){return"boolean"==typeof e}(e)?"bool":"float32"}function mt(e){return!!(e&&e.constructor&&e.call&&e.apply)}function gt(e,t){for(let n=t;n<e;++n)if(e%n==0)return n;return e}function yt(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}function bt(e,t,n,r=!1){const a=new Array;if(1===t.length){const s=t[0]*(r?2:1);for(let t=0;t<s;t++)a[t]=n[e+t]}else{const s=t[0],o=t.slice(1),i=o.reduce(((e,t)=>e*t))*(r?2:1);for(let t=0;t<s;t++)a[t]=bt(e+t*i,o,n,r)}return a}function _t(e,t,n=!1){if(0===e.length)return t[0];const r=e.reduce(((e,t)=>e*t))*(n?2:1);if(0===r)return[];if(r!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return bt(0,e,t,n)}function xt(e,t){const n=vt(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}function vt(e,t){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t)return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function wt(e){e.forEach((t=>{Qe(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function Tt(e,t,n){if(0===t)return 0;if(1===t)return e[0];let r=e[e.length-1];for(let t=0;t<e.length-1;++t)r+=n[t]*e[t];return r}function kt(e,t,n){if(0===t)return[];if(1===t)return[e];const r=new Array(t);for(let t=0;t<r.length-1;++t)r[t]=Math.floor(e/n[t]),e-=r[t]*n[t];return r[r.length-1]=e,r}function It(e){return e&&e.then&&"function"==typeof e.then}const St="tfjsflags";class Et{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=Nt,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(Ct().getBool("IS_TEST")||Ct().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},null!=this.urlFlags[e]){const t=this.urlFlags[e];Ct().getBool("IS_TEST")||Ct().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${t}.`),this.set(e,t)}}async getAsync(e){return e in this.flags||(this.flags[e]=await this.evaluateFlag(e)),this.flags[e]}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(It(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(null==this.flagRegistry[e])throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(null==this.flagRegistry[e])throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(void 0===this.global||void 0===this.global.location||void 0===this.global.location.search)return;const e=this.getQueryParams(this.global.location.search);St in e&&e[St].split(",").forEach((e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){if("true"===(t=t.toLowerCase())||"false"===t)return"true"===t;if(""+ +t===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}(t,n)}))}}function Nt(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,((e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("=")))),t}function Ct(){return Rt}let At,Rt=null;function $t(){if(null==At){let e;if("undefined"!=typeof window)e=window;else if(void 0!==_e)e=_e;else if(void 0!==He)e=He;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}At=e}return At}function Mt(e,t){const n=function(){const e=$t();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const r=t();return n.set(e,r),n.get(e)}}const Ft="Add",Ot="AddN",Dt="All",Lt="Any",Pt="ArgMax",Bt="AvgPool",Ut="BatchMatMul",zt="BatchToSpaceND",Vt="Cast",Wt="Ceil",Ht="ClipByValue",Gt="Concat",jt="Conv2D",Kt="Conv2DBackpropInput",qt="Cosh",Xt="Cumprod",Yt="Cumsum",Qt="CropAndResize",Jt="DepthToSpace",Zt="DepthwiseConv2dNative",en="RealDiv",tn="Elu",nn="Equal",rn="Exp",an="ExpandDims",sn="Fill",on="FlipLeftRight",un="Floor",ln="FloorDiv",cn="FusedBatchNorm",pn="GatherV2",hn="GatherNd",dn="Greater",fn="GreaterEqual",mn="Identity",gn="IsNan",yn="LeakyRelu",bn="Less",_n="LessEqual",xn="LogicalAnd",vn="LogicalNot",wn="LogicalOr",Tn="Max",kn="Maximum",In="MaxPool",Sn="Mean",En="Min",Nn="Minimum",Cn="MirrorPad",An="Multiply",Rn="NotEqual",$n="NonMaxSuppressionV3",Mn="NonMaxSuppressionV4",Fn="NonMaxSuppressionV5",On="OnesLike",Dn="OneHot",Ln="Pack",Pn="PadV2",Bn="Prelu",Un="Prod",zn="Range",Vn="Reciprocal",Wn="Relu",Hn="Reshape",Gn="ResizeNearestNeighbor",jn="ResizeBilinear",Kn="Relu6",qn="Reverse",Xn="Round",Yn="Rsqrt",Qn="ScatterNd",Jn="Select",Zn="Slice",er="Sigmoid",tr="Sqrt",nr="Sum",rr="SpaceToBatchND",ar="SplitV",sr="Softmax",or="SparseFillEmptyRows",ir="SparseReshape",ur="SparseSegmentMean",lr="SparseSegmentSum",cr="SquaredDifference",pr="StridedSlice",hr="StringNGrams",dr="StringSplit",fr="StringToHashBucketFast",mr="Sub",gr="Tanh",yr="Tile",br="TopK",_r="Transform",xr="Transpose",vr="Unpack",wr="ZerosLike",Tr="Step",kr="FromPixels",Ir="RotateWithOffset",Sr="_FusedMatMul",Er="FusedConv2D",Nr="FusedDepthwiseConv2D";function Cr(...e){Ct().getBool("IS_TEST")||Ct().getBool("PROD")||console.warn(...e)}const Ar=Mt("kernelRegistry",(()=>new Map)),Rr=Mt("gradRegistry",(()=>new Map));function $r(e,t){const n=Dr(e,t);return Ar.get(n)}function Mr(e){return Rr.get(e)}function Fr(e){const t=Ar.entries(),n=[];for(;;){const{done:r,value:a}=t.next();if(r)break;const[s,o]=a,[i]=s.split("_");i===e&&n.push(o)}return n}function Or(e){const{kernelName:t,backendName:n}=e,r=Dr(t,n);Ar.has(r)&&Cr(`The kernel '${t}' for backend '${n}' is already registered`),Ar.set(r,e)}function Dr(e,t){return`${t}_${e}`}var Lr=Br,Pr=null;try{Pr=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(e){}function Br(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function Ur(e){return!0===(e&&e.__isLong__)}Br.prototype.__isLong__,Object.defineProperty(Br.prototype,"__isLong__",{value:!0}),Br.isLong=Ur;var zr={},Vr={};function Wr(e,t){var n,r,a;return t?(a=0<=(e>>>=0)&&e<256)&&(r=Vr[e])?r:(n=Gr(e,(0|e)<0?-1:0,!0),a&&(Vr[e]=n),n):(a=-128<=(e|=0)&&e<128)&&(r=zr[e])?r:(n=Gr(e,e<0?-1:0,!1),a&&(zr[e]=n),n)}function Hr(e,t){if(isNaN(e))return t?ea:Zr;if(t){if(e<0)return ea;if(e>=Yr)return sa}else{if(e<=-Qr)return oa;if(e+1>=Qr)return aa}return e<0?Hr(-e,t).neg():Gr(e%Xr|0,e/Xr|0,t)}function Gr(e,t,n){return new Br(e,t,n)}Br.fromInt=Wr,Br.fromNumber=Hr,Br.fromBits=Gr;var jr=Math.pow;function Kr(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return Zr;if("number"==typeof t?(n=t,t=!1):t=!!t,(n=n||10)<2||36<n)throw RangeError("radix");var r;if((r=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===r)return Kr(e.substring(1),t,n).neg();for(var a=Hr(jr(n,8)),s=Zr,o=0;o<e.length;o+=8){var i=Math.min(8,e.length-o),u=parseInt(e.substring(o,o+i),n);if(i<8){var l=Hr(jr(n,i));s=s.mul(l).add(Hr(u))}else s=(s=s.mul(a)).add(Hr(u))}return s.unsigned=t,s}function qr(e,t){return"number"==typeof e?Hr(e,t):"string"==typeof e?Kr(e,t):Gr(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}Br.fromString=Kr,Br.fromValue=qr;var Xr=4294967296,Yr=Xr*Xr,Qr=Yr/2,Jr=Wr(1<<24),Zr=Wr(0);Br.ZERO=Zr;var ea=Wr(0,!0);Br.UZERO=ea;var ta=Wr(1);Br.ONE=ta;var na=Wr(1,!0);Br.UONE=na;var ra=Wr(-1);Br.NEG_ONE=ra;var aa=Gr(-1,2147483647,!1);Br.MAX_VALUE=aa;var sa=Gr(-1,-1,!0);Br.MAX_UNSIGNED_VALUE=sa;var oa=Gr(0,-2147483648,!1);Br.MIN_VALUE=oa;var ia=Br.prototype;ia.toInt=function(){return this.unsigned?this.low>>>0:this.low},ia.toNumber=function(){return this.unsigned?(this.high>>>0)*Xr+(this.low>>>0):this.high*Xr+(this.low>>>0)},ia.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(oa)){var t=Hr(e),n=this.div(t),r=n.mul(t).sub(this);return n.toString(e)+r.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var a=Hr(jr(e,6),this.unsigned),s=this,o="";;){var i=s.div(a),u=(s.sub(i.mul(a)).toInt()>>>0).toString(e);if((s=i).isZero())return u+o;for(;u.length<6;)u="0"+u;o=""+u+o}},ia.getHighBits=function(){return this.high},ia.getHighBitsUnsigned=function(){return this.high>>>0},ia.getLowBits=function(){return this.low},ia.getLowBitsUnsigned=function(){return this.low>>>0},ia.getNumBitsAbs=function(){if(this.isNegative())return this.eq(oa)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<<t);t--);return 0!=this.high?t+33:t+1},ia.isZero=function(){return 0===this.high&&0===this.low},ia.eqz=ia.isZero,ia.isNegative=function(){return!this.unsigned&&this.high<0},ia.isPositive=function(){return this.unsigned||this.high>=0},ia.isOdd=function(){return 1==(1&this.low)},ia.isEven=function(){return 0==(1&this.low)},ia.equals=function(e){return Ur(e)||(e=qr(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low},ia.eq=ia.equals,ia.notEquals=function(e){return!this.eq(e)},ia.neq=ia.notEquals,ia.ne=ia.notEquals,ia.lessThan=function(e){return this.comp(e)<0},ia.lt=ia.lessThan,ia.lessThanOrEqual=function(e){return this.comp(e)<=0},ia.lte=ia.lessThanOrEqual,ia.le=ia.lessThanOrEqual,ia.greaterThan=function(e){return this.comp(e)>0},ia.gt=ia.greaterThan,ia.greaterThanOrEqual=function(e){return this.comp(e)>=0},ia.gte=ia.greaterThanOrEqual,ia.ge=ia.greaterThanOrEqual,ia.compare=function(e){if(Ur(e)||(e=qr(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},ia.comp=ia.compare,ia.negate=function(){return!this.unsigned&&this.eq(oa)?oa:this.not().add(ta)},ia.neg=ia.negate,ia.add=function(e){Ur(e)||(e=qr(e));var t=this.high>>>16,n=65535&this.high,r=this.low>>>16,a=65535&this.low,s=e.high>>>16,o=65535&e.high,i=e.low>>>16,u=0,l=0,c=0,p=0;return c+=(p+=a+(65535&e.low))>>>16,l+=(c+=r+i)>>>16,u+=(l+=n+o)>>>16,u+=t+s,Gr((c&=65535)<<16|(p&=65535),(u&=65535)<<16|(l&=65535),this.unsigned)},ia.subtract=function(e){return Ur(e)||(e=qr(e)),this.add(e.neg())},ia.sub=ia.subtract,ia.multiply=function(e){if(this.isZero())return Zr;if(Ur(e)||(e=qr(e)),Pr)return Gr(Pr.mul(this.low,this.high,e.low,e.high),Pr.get_high(),this.unsigned);if(e.isZero())return Zr;if(this.eq(oa))return e.isOdd()?oa:Zr;if(e.eq(oa))return this.isOdd()?oa:Zr;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Jr)&&e.lt(Jr))return Hr(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,n=65535&this.high,r=this.low>>>16,a=65535&this.low,s=e.high>>>16,o=65535&e.high,i=e.low>>>16,u=65535&e.low,l=0,c=0,p=0,h=0;return p+=(h+=a*u)>>>16,c+=(p+=r*u)>>>16,p&=65535,c+=(p+=a*i)>>>16,l+=(c+=n*u)>>>16,c&=65535,l+=(c+=r*i)>>>16,c&=65535,l+=(c+=a*o)>>>16,l+=t*u+n*i+r*o+a*s,Gr((p&=65535)<<16|(h&=65535),(l&=65535)<<16|(c&=65535),this.unsigned)},ia.mul=ia.multiply,ia.divide=function(e){if(Ur(e)||(e=qr(e)),e.isZero())throw Error("division by zero");var t,n,r;if(Pr)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?Gr((this.unsigned?Pr.div_u:Pr.div_s)(this.low,this.high,e.low,e.high),Pr.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?ea:Zr;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return ea;if(e.gt(this.shru(1)))return na;r=ea}else{if(this.eq(oa))return e.eq(ta)||e.eq(ra)?oa:e.eq(oa)?ta:(t=this.shr(1).div(e).shl(1)).eq(Zr)?e.isNegative()?ta:ra:(n=this.sub(e.mul(t)),r=t.add(n.div(e)));if(e.eq(oa))return this.unsigned?ea:Zr;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();r=Zr}for(n=this;n.gte(e);){t=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(t)/Math.LN2),s=a<=48?1:jr(2,a-48),o=Hr(t),i=o.mul(e);i.isNegative()||i.gt(n);)i=(o=Hr(t-=s,this.unsigned)).mul(e);o.isZero()&&(o=ta),r=r.add(o),n=n.sub(i)}return r},ia.div=ia.divide,ia.modulo=function(e){return Ur(e)||(e=qr(e)),Pr?Gr((this.unsigned?Pr.rem_u:Pr.rem_s)(this.low,this.high,e.low,e.high),Pr.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},ia.mod=ia.modulo,ia.rem=ia.modulo,ia.not=function(){return Gr(~this.low,~this.high,this.unsigned)},ia.and=function(e){return Ur(e)||(e=qr(e)),Gr(this.low&e.low,this.high&e.high,this.unsigned)},ia.or=function(e){return Ur(e)||(e=qr(e)),Gr(this.low|e.low,this.high|e.high,this.unsigned)},ia.xor=function(e){return Ur(e)||(e=qr(e)),Gr(this.low^e.low,this.high^e.high,this.unsigned)},ia.shiftLeft=function(e){return Ur(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Gr(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):Gr(0,this.low<<e-32,this.unsigned)},ia.shl=ia.shiftLeft,ia.shiftRight=function(e){return Ur(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Gr(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):Gr(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},ia.shr=ia.shiftRight,ia.shiftRightUnsigned=function(e){if(Ur(e)&&(e=e.toInt()),0==(e&=63))return this;var t=this.high;return e<32?Gr(this.low>>>e|t<<32-e,t>>>e,this.unsigned):Gr(32===e?t:t>>>e-32,0,this.unsigned)},ia.shru=ia.shiftRightUnsigned,ia.shr_u=ia.shiftRightUnsigned,ia.toSigned=function(){return this.unsigned?Gr(this.low,this.high,!1):this},ia.toUnsigned=function(){return this.unsigned?this:Gr(this.low,this.high,!0)},ia.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},ia.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},ia.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},Br.fromBytes=function(e,t,n){return n?Br.fromBytesLE(e,t):Br.fromBytesBE(e,t)},Br.fromBytesLE=function(e,t){return new Br(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},Br.fromBytesBE=function(e,t){return new Br(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};const ua=Lr||e({__proto__:null,default:Lr},[Lr]);function la(e){return ua.fromString(e,!0,16)}const ca=la("c3a5c85c97cb3127"),pa=la("b492b66fbe98f273"),ha=la("9ae16a3b2f90404f");function da(e){return e.xor(e.shru(47))}function fa(e,t,n){const r=e.slice(t,t+n);return ua.fromBytes(Array.from(r),!0,!0)}function ma(e,t){return fa(e,t,8)}function ga(e,t){return fa(e,t,4)}function ya(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function ba(e,t,n=la("9ddfea08eb382d69")){let r=e.xor(t).mul(n);r=r.xor(r.shru(47));let a=t.xor(r).mul(n);return a=a.xor(a.shru(47)),a=a.mul(n),a}function _a(e,t,n,r){return function(e,t,n,r,a,s){a=a.add(e),s=ya(s.add(a).add(r),21);const o=a;return a=(a=a.add(t)).add(n),s=s.add(ya(a,44)),[a.add(r),s.add(o)]}(ma(e,t),ma(e,t+8),ma(e,t+16),ma(e,t+24),n,r)}function xa(e,t=e.length){const n=ua.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=ha.add(2*t),r=ma(e,0).add(ha),a=ma(e,t-8);return ba(ya(a,37).mul(n).add(r),ya(r,25).add(a).mul(n),n)}if(t>=4){const n=ha.add(2*t);return ba(ga(e,0).shl(3).add(t),ga(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),r=t+(e[t-1]<<2);return da(ha.mul(n).xor(ca.mul(r))).mul(ha)}return ha}(e,t):function(e,t=e.length){const n=ha.add(2*t),r=ma(e,0).mul(pa),a=ma(e,8),s=ma(e,t-8).mul(n),o=ma(e,t-16).mul(ha);return ba(ya(r.add(a),43).add(ya(s,30)).add(o),r.add(ya(a.add(ha),18)).add(s),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=ha.add(2*t),r=ma(e,0).mul(ha),a=ma(e,8),s=ma(e,t-8).mul(n),o=ma(e,t-16).mul(ha),i=ya(r.add(a),43).add(ya(s,30)).add(o),u=ba(i,r.add(ya(a.add(ha),18)).add(s),n),l=ma(e,16).mul(n),c=ma(e,24),p=i.add(ma(e,t-32)).mul(n),h=u.add(ma(e,t-24)).mul(n);return ba(ya(l.add(c),43).add(ya(p,30)).add(h),l.add(ya(c.add(r),18)).add(p),n)}(e,t);let r=n,a=n.mul(pa).add(113),s=da(a.mul(ha).add(113)).mul(ha),o=[ua.UZERO,ua.UZERO],i=[ua.UZERO,ua.UZERO];r=r.mul(ha).add(ma(e,0));let u=0;const l=64*(t-1>>6),c=l+(t-1&63)-63;do{r=ya(r.add(a).add(o[0]).add(ma(e,u+8)),37).mul(pa),a=ya(a.add(o[1]).add(ma(e,u+48)),42).mul(pa),r=r.xor(i[1]),a=a.add(o[0]).add(ma(e,u+40)),s=ya(s.add(i[0]),33).mul(pa),o=_a(e,u,o[1].mul(pa),r.add(i[0])),i=_a(e,u+32,s.add(i[1]),a.add(ma(e,u+16))),[s,r]=[r,s],u+=64}while(u!==l);const p=pa.add(s.and(255).shl(1));return u=c,i[0]=i[0].add(t-1&63),o[0]=o[0].add(i[0]),i[0]=i[0].add(o[0]),r=ya(r.add(a).add(o[0]).add(ma(e,u+8)),37).mul(p),a=ya(a.add(o[1]).add(ma(e,u+48)),42).mul(p),r=r.xor(i[1].mul(9)),a=a.add(o[0].mul(9).add(ma(e,u+40))),s=ya(s.add(i[0]),33).mul(p),o=_a(e,u,o[1].mul(p),r.add(i[0])),i=_a(e,u+32,s.add(i[1]),a.add(ma(e,u+16))),[s,r]=[r,s],ba(ba(o[0],i[0],p).add(da(a).mul(ca)).add(s),ba(o[1],i[1],p).add(r),p)}function va(e,t){return"string"===t?ka(e):wa([e],t)}function wa(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Ea(e)),Ct().getBool("DEBUG")&&function(e,t){for(let n=0;n<e.length;n++){const r=e[n];if(isNaN(r)||!isFinite(r))throw Error(`A tensor of type ${t} being uploaded contains ${r}.`)}}(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){const t=new Uint8Array(e.length);for(let n=0;n<t.length;++n)0!==Math.round(e[n])&&(t[n]=1);return t}throw new Error(`Unknown data type ${t}`)}function Ta(){return Ct().platform.now()}function ka(e,t="utf-8"){return t=t||"utf-8",Ct().platform.encode(e,t)}function Ia(e,t="utf-8"){return t=t||"utf-8",Ct().platform.decode(e,t)}function Sa(e){return Ct().platform.isTypedArray(e)}function Ea(e,t=[],n=!1){if(null==t&&(t=[]),"boolean"==typeof e||"number"==typeof e||"string"==typeof e||It(e)||null==e||Sa(e)&&n)t.push(e);else if(Array.isArray(e)||Sa(e))for(let r=0;r<e.length;++r)Ea(e[r],t,n);else{let r=-1;for(const t of Object.keys(e))/^([1-9]+[0-9]*|0)$/.test(t)&&(r=Math.max(r,Number(t)));for(let a=0;a<=r;a++)Ea(e[a],t,n)}return t}class Na{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new Aa)}profileKernel(e,t,n){let r;const a=()=>{r=n()};let s;const o=Ta();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(a);else{a();for(const e of r)e.dataSync();s=Promise.resolve({kernelMs:Ta()-o})}if(Ct().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<r.length;t++){const n=r[t];n.data().then((t=>{Ca(t,n.dtype,e)}))}return{kernelName:e,outputs:r,inputs:t,timeMs:s.then((e=>e.kernelMs)),extraInfo:s.then((e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():""))}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:a,extraInfo:s}=e;n.forEach((e=>{Promise.all([e.data(),r,s]).then((n=>{this.logger.logKernelProfile(t,e,n[0],n[1],a,n[2])}))}))}}function Ca(e,t,n){if("float32"!==t)return!1;for(let t=0;t<e.length;t++){const r=e[t];if(isNaN(r)||!isFinite(r))return console.warn(`Found ${r} in the result of '${n}'`),!0}return!1}class Aa{logKernelProfile(e,t,n,r,a,s){const o="number"==typeof r?at(`${r}ms`,9):r.error,i=at(e,25),u=t.rank,l=t.size,c=at(t.shape.toString(),14);let p="";for(const e in a){const n=a[e];if(null!=n){const r=n.shape||t.shape,a=r.length;p+=`${e}: ${a}D ${a>0?r:""} `}}console.log(`%c${i}\t%c${o}\t%c${u}D ${c}\t%c${l}\t%c${p}\t%c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function Ra(e,t,n,r){const a=yt(t),s=function(e,t,n,r){const a=et(t),s=r[r.length-1],o=new Array(s).fill(0),i=t.length,u="complex64"===n?Oa(e):e;if(i>1)for(let e=0;e<a/s;e++){const t=e*s;for(let e=0;e<s;e++)o[e]=Math.max(o[e],$a(u[t+e],0,n).length)}return o}(e,t,n,a),o=t.length,i=Fa(e,t,n,a,s),u=["Tensor"];return r&&(u.push(` dtype: ${n}`),u.push(` rank: ${o}`),u.push(` shape: [${t}]`),u.push(" values:")),u.push(i.map((e=>" "+e)).join("\n")),u.join("\n")}function $a(e,t,n){let r;return r=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:dt(e)?`'${e}'`:"bool"===n?Ma(e):parseFloat(e.toFixed(7)).toString(),at(r,t)}function Ma(e){return 0===e?"false":"true"}function Fa(e,t,n,r,a,s=!0){const o="complex64"===n?2:1,i=t[0],u=t.length;if(0===u)return"complex64"===n?[$a(Oa(e)[0],0,n)]:"bool"===n?[Ma(e[0])]:[e[0].toString()];if(1===u){if(i>20){const t=3*o;let r=Array.from(e.slice(0,t)),s=Array.from(e.slice((i-3)*o,i*o));return"complex64"===n&&(r=Oa(r),s=Oa(s)),["["+r.map(((e,t)=>$a(e,a[t],n))).join(", ")+", ..., "+s.map(((e,t)=>$a(e,a[i-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?Oa(e):Array.from(e)).map(((e,t)=>$a(e,a[t],n))).join(", ")+"]"]}const l=t.slice(1),c=r.slice(1),p=r[0]*o,h=[];if(i>20){for(let t=0;t<3;t++){const r=t*p,s=r+p;h.push(...Fa(e.slice(r,s),l,n,c,a,!1))}h.push("...");for(let t=i-3;t<i;t++){const r=t*p,s=r+p;h.push(...Fa(e.slice(r,s),l,n,c,a,t===i-1))}}else for(let t=0;t<i;t++){const r=t*p,s=r+p;h.push(...Fa(e.slice(r,s),l,n,c,a,t===i-1))}const d=2===u?",":"";h[0]="["+(i>0?h[0]+d:"");for(let e=1;e<h.length-1;e++)h[e]=" "+h[e]+d;let f=",\n";for(let e=2;e<u;e++)f+="\n";return h[h.length-1]=" "+h[h.length-1]+"]"+(s?"":f),h}function Oa(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class Da{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=et(e),null!=n){const e=n.length;Qe(e===this.size,(()=>`Length of values '${e}' does not match the size inferred by the shape '${this.size}'.`))}if("complex64"===t)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||ct(t,this.size),this.strides=yt(e)}set(e,...t){0===t.length&&(t=[0]),Qe(t.length===this.rank,(()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`));const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const t=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(t)}t++}let n=e[e.length-1];for(let t=0;t<e.length-1;++t)n+=this.strides[t]*e[t];return this.values[n]}locToIndex(e){if(0===this.rank)return 0;if(1===this.rank)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(0===this.rank)return[];if(1===this.rank)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return La().makeTensor(this.values,this.shape,this.dtype)}}let La=null,Pa=null;class Ba{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=et(e),this.strides=yt(e),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return Pa.buffer(this.shape,this.dtype,e)}bufferSync(){return Pa.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return _t(this.shape,e,"complex64"===this.dtype)}arraySync(){return _t(this.shape,this.dataSync(),"complex64"===this.dtype)}async data(){this.throwIfDisposed();const e=La().read(this.dataId);if("string"===this.dtype){const t=await e;try{return t.map((e=>Ia(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),La().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=La().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>Ia(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await La().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(La().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Pa.print(this,e)}clone(){return this.throwIfDisposed(),Pa.clone(this)}toString(e=!1){return Ra(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Pa.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),La().makeVariable(this,e,t,n)}}Object.defineProperty(Ba,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),Mt("Tensor",(()=>Ba));class Ua extends Ba{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!tt(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);La().disposeTensor(this),this.dataId=e.dataId,La().incRef(this,null)}dispose(){La().disposeVariable(this),this.isDisposedInternal=!0}}var za,Va,Wa,Ha,Ga;Object.defineProperty(Ua,Symbol.hasInstance,{value:e=>e instanceof Ba&&null!=e.assign&&e.assign instanceof Function}),function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"}(za||(za={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(Va||(Va={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(Wa||(Wa={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(Ha||(Ha={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(Ga||(Ga={}));const ja={float32:Ha,int32:Va,bool:Wa,complex64:Ga};function Ka(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return ja[e][t]}function qa(e,t){if(e.dtype===t.dtype)return[e,t];const n=Ka(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function Xa(e){const t=[];return Ya(e,t,new Set),t}function Ya(e,t,n){if(null==e)return;if(e instanceof Ba)return void t.push(e);if(r=e,!Array.isArray(r)&&"object"!=typeof r)return;var r;const a=e;for(const e in a){const r=a[e];n.has(r)||(n.add(r),Ya(r,t,n))}}function Qa(e){return null!=e.kernelName}class Ja{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map((e=>e.name))))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class Za{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Ja}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then((()=>{}));if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t];if(await this.initializeBackend(n).success)return void await this.setBackend(n)}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(null!=this.pendingBackendInit)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(null==this.backendInstance){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry)){if(!(e in this.registryFactory))return null;{const{asyncInit:t}=this.initializeBackend(e);if(t)return null}}return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(Cr(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(null==this.registryFactory[e])throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,null==this.registry[e]){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new Na(this.backendInstance),!0}setupRegisteredKernels(){Fr(this.backendName).forEach((e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){Fr(e).forEach((t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])}))}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(!n||n instanceof je||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,r=n.then((n=>!(t<this.pendingBackendInitId||(this.registry[e]=n,this.pendingBackendInit=null,0)))).catch((n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,Cr(`Initialization of backend ${e} failed`),Cr(n.stack||n.message)),!1)));return this.pendingBackendInit=r,{success:r,asyncInit:!0}}}catch(t){return Cr(`Initialization of backend ${e} failed`),Cr(t.stack||t.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort(((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority))}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:r,asyncInit:a}=this.initializeBackend(n);if(a||r)return{name:n,asyncInit:a}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),r=n.backend,a=this.readSync(t),s=r.refCount(t);r.disposeData(t,!0),n.backend=e,e.move(t,a,n.shape,n.dtype,s),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n,r=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");r=e}return this.scopedRun((()=>this.startScope(r)),(()=>this.endScope(n)),(()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n)))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(e){throw t(),e}}nextTensorId(){return Za.nextTensorId++}nextVariableId(){return Za.nextVariableId++}clone(e){const t=ts.runKernel(mn,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e};return ts.runKernel(Vt,t,{dtype:"float32"})}})),[],{}),t}runKernel(e,t,n){if(null==this.backendName&&this.backend,null==$r(e,this.backendName))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const r=this.backend.numDataIds();let a=0;n.forEach((e=>{a+="complex64"===e.dtype?3:1}));const s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=r-t-a-s;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const r=this.isTapeOn(),a=this.state.numBytes,s=this.state.numTensors;let o,i;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const u=Qa(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(Qa(e)){const{kernelName:t,inputs:a,attrs:s}=e;null==this.backendName&&this.backend;const u=$r(t,this.backendName);Qe(null!=u,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),o=()=>{const e=this.backend.numDataIds();i=u.kernelFunc({inputs:a,attrs:s,backend:this.backend});const o=Array.isArray(i)?i:[i];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,o);const l=o.map((e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e)));if(r){const e=this.getTensorsForGradient(t,a,l);n=this.saveTensorsForBackwardMode(e)}return l}}else{const{forwardFunc:t}=e,a=e=>{r&&(n=e.map((e=>this.keep(this.clone(e)))))};o=()=>{const e=this.backend.numDataIds();i=this.tidy((()=>t(this.backend,a)));const n=Array.isArray(i)?i:[i];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(u,e,n),n}}const{inputs:l,attrs:c}=e,p=Qa(e)?null:e.backwardsFunc;let h;return this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(h=this.profiler.profileKernel(u,l,(()=>o())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(h),t=h.outputs):t=o()})),r&&this.addTapeNode(u,l,t,p,n,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:u,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(l).map((e=>null!=l[e]?l[e].shape:null)),outputShapes:t.map((e=>e.shape)),kernelTimeMs:h.timeMs,extraInfo:h.extraInfo}),Array.isArray(i)?t:t[0]}saveTensorsForBackwardMode(e){return e.map((e=>this.keep(this.clone(e))))}getTensorsForGradient(e,t,n){const r=Mr(e);if(null!=r){const e=r.inputsToSave||[],a=r.outputsToSave||[];let s;r.saveAllInputs?(Qe(Array.isArray(t),(()=>"saveAllInputs is true, expected inputs to be an array.")),s=Object.keys(t).map((e=>t[e]))):s=e.map((e=>t[e]));const o=n.filter(((e,t)=>a[t]));return s.concat(o)}return[]}makeTensor(e,t,n,r){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let a=e;"string"===n&&dt(e[0])&&(a=e.map((e=>ka(e))));const s=r.write(a,t,n),o=new Ba(t,n,s,this.nextTensorId());if(this.trackTensor(o,r),"string"===n){const e=this.state.tensorInfo.get(s),t=function(e){if(null==e)return 0;let t=0;return e.forEach((e=>t+=e.length)),t}(a);this.state.numBytes+=t-e.bytes,e.bytes=t}return o}makeTensorFromDataId(e,t,n,r){const a={dataId:e,shape:t,dtype:n=n||"float32"};return this.makeTensorFromTensorInfo(a,r)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:r,dtype:a}=e,s=new Ba(r,a,n,this.nextTensorId());return this.trackTensor(s,t),s}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),null!=r&&r!==e.dtype&&(e=e.cast(r));const a=new Ua(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[a.name])throw new Error(`Variable with name ${a.name} was already registered`);return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*ht(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof Ua||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*ht(e.dtype);this.state.numBytes-=t}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map((e=>e.totalBytesSnapshot))),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const e of this.state.activeProfile.kernels)e.kernelTimeMs=await e.kernelTimeMs,e.extraInfo=await e.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,r,a,s){const o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:a},i=Mr(e);null!=i&&(r=i.gradFunc),null!=r&&(o.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],r=vt(e.size,e.dtype);return this.makeTensor(r,e.shape,e.dtype)}return e})),r(e.length>1?e:e[0],a,s))),this.state.activeTape.push(o)}keep(e){return e.kept=!0,e}startTape(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=Xa(e),n=new Set(t.map((e=>e.id)));for(let e=0;e<this.state.activeScope.track.length;e++){const t=this.state.activeScope.track[e];t.kept||n.has(t.id)||t.dispose()}const r=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach((e=>{e.kept||e.scopeId!==r.id||this.track(e)}))}gradients(e,t,n,r=!1){if(Qe(t.length>0,(()=>"gradients() received an empty list of xs.")),null!=n&&"float32"!==n.dtype)throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const a=this.scopedRun((()=>this.startTape()),(()=>this.endTape()),(()=>this.tidy("forward",e)));Qe(a instanceof Ba,(()=>"The result y returned by f() must be a tensor."));const s=function(e,t,n){const r={},a={};for(let e=0;e<t.length;e++)r[t[e].id]=!0;for(let n=0;n<e.length;n++){const s=e[n],o=s.inputs;for(const e in o){const n=o[e];let i=!1;for(let e=0;e<t.length;e++)if(r[n.id]){s.outputs.forEach((e=>r[e.id]=!0)),i=!0,a[s.id]=!0;break}if(i)break}}const s={};s[n.id]=!0;const o={};for(let t=e.length-1;t>=0;t--){const n=e[t],r=n.inputs;for(let e=0;e<n.outputs.length;e++)if(s[n.outputs[e].id]){for(const e in r)s[r[e].id]=!0,o[n.id]=!0;break}}const i=[];for(let t=0;t<e.length;t++){const n=e[t];if(a[n.id]&&o[n.id]){const e={};for(const t in n.inputs){const a=n.inputs[t];r[a.id]&&(e[t]=a)}const t=Object.assign({},n);t.inputs=e,t.outputs=n.outputs,i.push(t)}}return i}(this.state.activeTape,t,a);if(!r&&0===s.length&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",(()=>{const e={};e[a.id]=null==n?function(e){const t=xt(et(e),"float32");return ts.makeTensor(t,e,"float32")}(a.shape):n,function(e,t,n,r){for(let a=t.length-1;a>=0;a--){const s=t[a],o=[];if(s.outputs.forEach((t=>{const n=e[t.id];null!=n?o.push(n):o.push(null)})),null==s.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);const i=s.gradient(o);for(const t in s.inputs){if(!(t in i))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(i)}.`);const a=n((()=>i[t]()));if("float32"!==a.dtype)throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${a.dtype}'`);const o=s.inputs[t];if(!tt(a.shape,o.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${t}' has shape '${a.shape}', which does not match the shape of the input '${o.shape}'`);if(null==e[o.id])e[o.id]=a;else{const t=e[o.id];e[o.id]=r(t,a),t.dispose()}}}}(e,s,(e=>this.tidy(e)),ns);const r=t.map((t=>e[t.id]));return 0===this.state.gradientDepth&&(this.state.activeTape.forEach((e=>{for(const t of e.saved)t.dispose()})),this.state.activeTape=null),{value:a,grads:r}}))}customGrad(e){return Qe(mt(e),(()=>"The f passed in customGrad(f) must be a function.")),(...t)=>{let n;Qe(t.every((e=>e instanceof Ba)),(()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors"));const r={};return t.forEach(((e,t)=>{r[t]=e})),this.runKernelFunc({forwardFunc:(r,a)=>(n=e(...t,a),Qe(n.value instanceof Ba,(()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor")),Qe(mt(n.gradFunc),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function.")),n.value),backwardsFunc:(e,r)=>{const a=n.gradFunc(e,r),s=Array.isArray(a)?a:[a];Qe(s.length===t.length,(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...).")),Qe(s.every((e=>e instanceof Ba)),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."));const o={};return s.forEach(((e,t)=>{o[t]=()=>e})),o},inputs:r})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){const t=Ta(),n=await this.backend.time(e);return n.wallMs=Ta()-t,n}track(e){return null!=this.state.activeScope&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new Ja;for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}function es(){const e=$t();if(null==e._tfengine){const t=new Et(e);e._tfengine=new Za(t)}var t;return t=e._tfengine.ENV,Rt=t,La=()=>e._tfengine,e._tfengine}Za.nextTensorId=0,Za.nextVariableId=0;const ts=es();function ns(e,t){const n={a:e,b:t};return ts.runKernel(Ft,n)}function rs(e){if(e||"undefined"!=typeof navigator&&null!=navigator){if(e||(e=navigator),"ReactNative"===e.product)return!0;const t=e.userAgent||e.vendor||("undefined"!=typeof window?window.opera:"");if(!t){const t=e;return t.userAgentData&&t.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))}return!1}function as(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}const ss=Ct();ss.registerFlag("DEBUG",(()=>!1),(e=>{e&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")})),ss.registerFlag("IS_BROWSER",(()=>as())),ss.registerFlag("IS_NODE",(()=>void 0!==He&&void 0!==He.versions&&void 0!==He.versions.node)),ss.registerFlag("IS_CHROME",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor))),ss.registerFlag("PROD",(()=>!1)),ss.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(()=>ss.getBool("DEBUG"))),ss.registerFlag("DEPRECATION_WARNINGS_ENABLED",(()=>!0)),ss.registerFlag("IS_TEST",(()=>!1)),ss.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",(()=>!0)),ss.registerFlag("WRAP_TO_IMAGEBITMAP",(()=>!1)),ss.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",(()=>!1)),ss.registerFlag("USE_SETTIMEOUTCUSTOM",(()=>!1));var os=[],is=[],us="undefined"!=typeof Uint8Array?Uint8Array:Array,ls=!1;function cs(){ls=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0,n=e.length;t<n;++t)os[t]=e[t],is[e.charCodeAt(t)]=t;is["-".charCodeAt(0)]=62,is["_".charCodeAt(0)]=63}function ps(e,t,n){for(var r,a,s=[],o=t;o<n;o+=3)r=(e[o]<<16)+(e[o+1]<<8)+e[o+2],s.push(os[(a=r)>>18&63]+os[a>>12&63]+os[a>>6&63]+os[63&a]);return s.join("")}function hs(e){var t;ls||cs();for(var n=e.length,r=n%3,a="",s=[],o=16383,i=0,u=n-r;i<u;i+=o)s.push(ps(e,i,i+o>u?u:i+o));return 1===r?(t=e[n-1],a+=os[t>>2],a+=os[t<<4&63],a+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],a+=os[t>>10],a+=os[t>>4&63],a+=os[t<<2&63],a+="="),s.push(a),s.join("")}function ds(e,t,n,r,a){var s,o,i=8*a-r-1,u=(1<<i)-1,l=u>>1,c=-7,p=n?a-1:0,h=n?-1:1,d=e[t+p];for(p+=h,s=d&(1<<-c)-1,d>>=-c,c+=i;c>0;s=256*s+e[t+p],p+=h,c-=8);for(o=s&(1<<-c)-1,s>>=-c,c+=r;c>0;o=256*o+e[t+p],p+=h,c-=8);if(0===s)s=1-l;else{if(s===u)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,r),s-=l}return(d?-1:1)*o*Math.pow(2,s-r)}function fs(e,t,n,r,a,s){var o,i,u,l=8*s-a-1,c=(1<<l)-1,p=c>>1,h=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:s-1,f=r?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-o))<1&&(o--,u*=2),(t+=o+p>=1?h/u:h*Math.pow(2,1-p))*u>=2&&(o++,u/=2),o+p>=c?(i=0,o=c):o+p>=1?(i=(t*u-1)*Math.pow(2,a),o+=p):(i=t*Math.pow(2,p-1)*Math.pow(2,a),o=0));a>=8;e[n+d]=255&i,d+=f,i/=256,a-=8);for(o=o<<a|i,l+=a;l>0;e[n+d]=255&o,d+=f,o/=256,l-=8);e[n+d-f]|=128*m}var ms={}.toString,gs=Array.isArray||function(e){return"[object Array]"==ms.call(e)};function ys(){return _s.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function bs(e,t){if(ys()<t)throw new RangeError("Invalid typed array length");return _s.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=_s.prototype:(null===e&&(e=new _s(t)),e.length=t),e}function _s(e,t,n){if(!(_s.TYPED_ARRAY_SUPPORT||this instanceof _s))return new _s(e,t,n);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return ws(this,e)}return xs(this,e,t,n)}function xs(e,t,n,r){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?function(e,t,n,r){if(t.byteLength,n<0||t.byteLength<n)throw new RangeError("'offset' is out of bounds");if(t.byteLength<n+(r||0))throw new RangeError("'length' is out of bounds");return t=void 0===n&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,n):new Uint8Array(t,n,r),_s.TYPED_ARRAY_SUPPORT?(e=t).__proto__=_s.prototype:e=Ts(e,t),e}(e,t,n,r):"string"==typeof t?function(e,t,n){if("string"==typeof n&&""!==n||(n="utf8"),!_s.isEncoding(n))throw new TypeError('"encoding" must be a valid string encoding');var r=0|Ss(t,n),a=(e=bs(e,r)).write(t,n);return a!==r&&(e=e.slice(0,a)),e}(e,t,n):function(e,t){if(Is(t)){var n=0|ks(t.length);return 0===(e=bs(e,n)).length||t.copy(e,0,0,n),e}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||(r=t.length)!=r?bs(e,0):Ts(e,t);if("Buffer"===t.type&&gs(t.data))return Ts(e,t.data)}var r;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function vs(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function ws(e,t){if(vs(t),e=bs(e,t<0?0:0|ks(t)),!_s.TYPED_ARRAY_SUPPORT)for(var n=0;n<t;++n)e[n]=0;return e}function Ts(e,t){var n=t.length<0?0:0|ks(t.length);e=bs(e,n);for(var r=0;r<n;r+=1)e[r]=255&t[r];return e}function ks(e){if(e>=ys())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+ys().toString(16)+" bytes");return 0|e}function Is(e){return!(null==e||!e._isBuffer)}function Ss(e,t){if(Is(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return Zs(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return eo(e).length;default:if(r)return Zs(e).length;t=(""+t).toLowerCase(),r=!0}}function Es(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return Vs(this,t,n);case"utf8":case"utf-8":return Ps(this,t,n);case"ascii":return Us(this,t,n);case"latin1":case"binary":return zs(this,t,n);case"base64":return Ls(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ws(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function Ns(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function Cs(e,t,n,r,a){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)return-1;n=0}if("string"==typeof t&&(t=_s.from(t,r)),Is(t))return 0===t.length?-1:As(e,t,n,r,a);if("number"==typeof t)return t&=255,_s.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):As(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function As(e,t,n,r,a){var s,o=1,i=e.length,u=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,i/=2,u/=2,n/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(a){var c=-1;for(s=n;s<i;s++)if(l(e,s)===l(t,-1===c?0:s-c)){if(-1===c&&(c=s),s-c+1===u)return c*o}else-1!==c&&(s-=s-c),c=-1}else for(n+u>i&&(n=i-u),s=n;s>=0;s--){for(var p=!0,h=0;h<u;h++)if(l(e,s+h)!==l(t,h)){p=!1;break}if(p)return s}return-1}function Rs(e,t,n,r){n=Number(n)||0;var a=e.length-n;r?(r=Number(r))>a&&(r=a):r=a;var s=t.length;if(s%2!=0)throw new TypeError("Invalid hex string");r>s/2&&(r=s/2);for(var o=0;o<r;++o){var i=parseInt(t.substr(2*o,2),16);if(isNaN(i))return o;e[n+o]=i}return o}function $s(e,t,n,r){return to(Zs(t,e.length-n),e,n,r)}function Ms(e,t,n,r){return to(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function Fs(e,t,n,r){return Ms(e,t,n,r)}function Os(e,t,n,r){return to(eo(t),e,n,r)}function Ds(e,t,n,r){return to(function(e,t){for(var n,r,a,s=[],o=0;o<e.length&&!((t-=2)<0);++o)r=(n=e.charCodeAt(o))>>8,a=n%256,s.push(a),s.push(r);return s}(t,e.length-n),e,n,r)}function Ls(e,t,n){return 0===t&&n===e.length?hs(e):hs(e.slice(t,n))}function Ps(e,t,n){n=Math.min(e.length,n);for(var r=[],a=t;a<n;){var s,o,i,u,l=e[a],c=null,p=l>239?4:l>223?3:l>191?2:1;if(a+p<=n)switch(p){case 1:l<128&&(c=l);break;case 2:128==(192&(s=e[a+1]))&&(u=(31&l)<<6|63&s)>127&&(c=u);break;case 3:s=e[a+1],o=e[a+2],128==(192&s)&&128==(192&o)&&(u=(15&l)<<12|(63&s)<<6|63&o)>2047&&(u<55296||u>57343)&&(c=u);break;case 4:s=e[a+1],o=e[a+2],i=e[a+3],128==(192&s)&&128==(192&o)&&128==(192&i)&&(u=(15&l)<<18|(63&s)<<12|(63&o)<<6|63&i)>65535&&u<1114112&&(c=u)}null===c?(c=65533,p=1):c>65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|1023&c),r.push(c),a+=p}return function(e){var t=e.length;if(t<=Bs)return String.fromCharCode.apply(String,e);for(var n="",r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=Bs));return n}(r)}_s.TYPED_ARRAY_SUPPORT=void 0===_e.TYPED_ARRAY_SUPPORT||_e.TYPED_ARRAY_SUPPORT,ys(),_s.poolSize=8192,_s._augment=function(e){return e.__proto__=_s.prototype,e},_s.from=function(e,t,n){return xs(null,e,t,n)},_s.TYPED_ARRAY_SUPPORT&&(_s.prototype.__proto__=Uint8Array.prototype,_s.__proto__=Uint8Array),_s.alloc=function(e,t,n){return function(e,t,n,r){return vs(t),t<=0?bs(e,t):void 0!==n?"string"==typeof r?bs(e,t).fill(n,r):bs(e,t).fill(n):bs(e,t)}(null,e,t,n)},_s.allocUnsafe=function(e){return ws(null,e)},_s.allocUnsafeSlow=function(e){return ws(null,e)},_s.isBuffer=function(e){return null!=e&&(!!e._isBuffer||no(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&no(e.slice(0,0))}(e))},_s.compare=function(e,t){if(!Is(e)||!Is(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,a=0,s=Math.min(n,r);a<s;++a)if(e[a]!==t[a]){n=e[a],r=t[a];break}return n<r?-1:r<n?1:0},_s.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},_s.concat=function(e,t){if(!gs(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return _s.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=_s.allocUnsafe(t),a=0;for(n=0;n<e.length;++n){var s=e[n];if(!Is(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(r,a),a+=s.length}return r},_s.byteLength=Ss,_s.prototype._isBuffer=!0,_s.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)Ns(this,t,t+1);return this},_s.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)Ns(this,t,t+3),Ns(this,t+1,t+2);return this},_s.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)Ns(this,t,t+7),Ns(this,t+1,t+6),Ns(this,t+2,t+5),Ns(this,t+3,t+4);return this},_s.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?Ps(this,0,e):Es.apply(this,arguments)},_s.prototype.equals=function(e){if(!Is(e))throw new TypeError("Argument must be a Buffer");return this===e||0===_s.compare(this,e)},_s.prototype.inspect=function(){var e="";return this.length>0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),"<Buffer "+e+">"},_s.prototype.compare=function(e,t,n,r,a){if(!Is(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;for(var s=(a>>>=0)-(r>>>=0),o=(n>>>=0)-(t>>>=0),i=Math.min(s,o),u=this.slice(r,a),l=e.slice(t,n),c=0;c<i;++c)if(u[c]!==l[c]){s=u[c],o=l[c];break}return s<o?-1:o<s?1:0},_s.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},_s.prototype.indexOf=function(e,t,n){return Cs(this,e,t,n,!0)},_s.prototype.lastIndexOf=function(e,t,n){return Cs(this,e,t,n,!1)},_s.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(n)?(n|=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var a=this.length-t;if((void 0===n||n>a)&&(n=a),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return Rs(this,e,t,n);case"utf8":case"utf-8":return $s(this,e,t,n);case"ascii":return Ms(this,e,t,n);case"latin1":case"binary":return Fs(this,e,t,n);case"base64":return Os(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ds(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},_s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Bs=4096;function Us(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(127&e[a]);return r}function zs(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(e[a]);return r}function Vs(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var a="",s=t;s<n;++s)a+=Js(e[s]);return a}function Ws(e,t,n){for(var r=e.slice(t,n),a="",s=0;s<r.length;s+=2)a+=String.fromCharCode(r[s]+256*r[s+1]);return a}function Hs(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function Gs(e,t,n,r,a,s){if(!Is(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||t<s)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function js(e,t,n,r){t<0&&(t=65535+t+1);for(var a=0,s=Math.min(e.length-n,2);a<s;++a)e[n+a]=(t&255<<8*(r?a:1-a))>>>8*(r?a:1-a)}function Ks(e,t,n,r){t<0&&(t=4294967295+t+1);for(var a=0,s=Math.min(e.length-n,4);a<s;++a)e[n+a]=t>>>8*(r?a:3-a)&255}function qs(e,t,n,r,a,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function Xs(e,t,n,r,a){return a||qs(e,0,n,4),fs(e,t,n,r,23,4),n+4}function Ys(e,t,n,r,a){return a||qs(e,0,n,8),fs(e,t,n,r,52,8),n+8}_s.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e),_s.TYPED_ARRAY_SUPPORT)(n=this.subarray(e,t)).__proto__=_s.prototype;else{var a=t-e;n=new _s(a,void 0);for(var s=0;s<a;++s)n[s]=this[s+e]}return n},_s.prototype.readUIntLE=function(e,t,n){e|=0,t|=0,n||Hs(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r},_s.prototype.readUIntBE=function(e,t,n){e|=0,t|=0,n||Hs(e,t,this.length);for(var r=this[e+--t],a=1;t>0&&(a*=256);)r+=this[e+--t]*a;return r},_s.prototype.readUInt8=function(e,t){return t||Hs(e,1,this.length),this[e]},_s.prototype.readUInt16LE=function(e,t){return t||Hs(e,2,this.length),this[e]|this[e+1]<<8},_s.prototype.readUInt16BE=function(e,t){return t||Hs(e,2,this.length),this[e]<<8|this[e+1]},_s.prototype.readUInt32LE=function(e,t){return t||Hs(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},_s.prototype.readUInt32BE=function(e,t){return t||Hs(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},_s.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||Hs(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r>=(a*=128)&&(r-=Math.pow(2,8*t)),r},_s.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||Hs(e,t,this.length);for(var r=t,a=1,s=this[e+--r];r>0&&(a*=256);)s+=this[e+--r]*a;return s>=(a*=128)&&(s-=Math.pow(2,8*t)),s},_s.prototype.readInt8=function(e,t){return t||Hs(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},_s.prototype.readInt16LE=function(e,t){t||Hs(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},_s.prototype.readInt16BE=function(e,t){t||Hs(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},_s.prototype.readInt32LE=function(e,t){return t||Hs(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},_s.prototype.readInt32BE=function(e,t){return t||Hs(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},_s.prototype.readFloatLE=function(e,t){return t||Hs(e,4,this.length),ds(this,e,!0,23,4)},_s.prototype.readFloatBE=function(e,t){return t||Hs(e,4,this.length),ds(this,e,!1,23,4)},_s.prototype.readDoubleLE=function(e,t){return t||Hs(e,8,this.length),ds(this,e,!0,52,8)},_s.prototype.readDoubleBE=function(e,t){return t||Hs(e,8,this.length),ds(this,e,!1,52,8)},_s.prototype.writeUIntLE=function(e,t,n,r){e=+e,t|=0,n|=0,r||Gs(this,e,t,n,Math.pow(2,8*n)-1,0);var a=1,s=0;for(this[t]=255&e;++s<n&&(a*=256);)this[t+s]=e/a&255;return t+n},_s.prototype.writeUIntBE=function(e,t,n,r){e=+e,t|=0,n|=0,r||Gs(this,e,t,n,Math.pow(2,8*n)-1,0);var a=n-1,s=1;for(this[t+a]=255&e;--a>=0&&(s*=256);)this[t+a]=e/s&255;return t+n},_s.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||Gs(this,e,t,1,255,0),_s.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},_s.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||Gs(this,e,t,2,65535,0),_s.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):js(this,e,t,!0),t+2},_s.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||Gs(this,e,t,2,65535,0),_s.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):js(this,e,t,!1),t+2},_s.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||Gs(this,e,t,4,4294967295,0),_s.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):Ks(this,e,t,!0),t+4},_s.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||Gs(this,e,t,4,4294967295,0),_s.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Ks(this,e,t,!1),t+4},_s.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);Gs(this,e,t,n,a-1,-a)}var s=0,o=1,i=0;for(this[t]=255&e;++s<n&&(o*=256);)e<0&&0===i&&0!==this[t+s-1]&&(i=1),this[t+s]=(e/o>>0)-i&255;return t+n},_s.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);Gs(this,e,t,n,a-1,-a)}var s=n-1,o=1,i=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===i&&0!==this[t+s+1]&&(i=1),this[t+s]=(e/o>>0)-i&255;return t+n},_s.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||Gs(this,e,t,1,127,-128),_s.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},_s.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||Gs(this,e,t,2,32767,-32768),_s.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):js(this,e,t,!0),t+2},_s.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||Gs(this,e,t,2,32767,-32768),_s.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):js(this,e,t,!1),t+2},_s.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||Gs(this,e,t,4,2147483647,-2147483648),_s.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):Ks(this,e,t,!0),t+4},_s.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||Gs(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),_s.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Ks(this,e,t,!1),t+4},_s.prototype.writeFloatLE=function(e,t,n){return Xs(this,e,t,!0,n)},_s.prototype.writeFloatBE=function(e,t,n){return Xs(this,e,t,!1,n)},_s.prototype.writeDoubleLE=function(e,t,n){return Ys(this,e,t,!0,n)},_s.prototype.writeDoubleBE=function(e,t,n){return Ys(this,e,t,!1,n)},_s.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var a,s=r-n;if(this===e&&n<t&&t<r)for(a=s-1;a>=0;--a)e[a+t]=this[a+n];else if(s<1e3||!_s.TYPED_ARRAY_SUPPORT)for(a=0;a<s;++a)e[a+t]=this[a+n];else Uint8Array.prototype.set.call(e,this.subarray(n,n+s),t);return s},_s.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),1===e.length){var a=e.charCodeAt(0);a<256&&(e=a)}if(void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!_s.isEncoding(r))throw new TypeError("Unknown encoding: "+r)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{var o=Is(e)?e:Zs(new _s(e,r).toString()),i=o.length;for(s=0;s<n-t;++s)this[s+t]=o[s%i]}return this};var Qs=/[^+\/0-9A-Za-z-_]/g;function Js(e){return e<16?"0"+e.toString(16):e.toString(16)}function Zs(e,t){var n;t=t||1/0;for(var r=e.length,a=null,s=[],o=0;o<r;++o){if((n=e.charCodeAt(o))>55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&s.push(239,191,189);if(a=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function eo(e){return function(e){var t,n,r,a,s,o;ls||cs();var i=e.length;if(i%4>0)throw new Error("Invalid string. Length must be a multiple of 4");s="="===e[i-2]?2:"="===e[i-1]?1:0,o=new us(3*i/4-s),r=s>0?i-4:i;var u=0;for(t=0,n=0;t<r;t+=4,n+=3)a=is[e.charCodeAt(t)]<<18|is[e.charCodeAt(t+1)]<<12|is[e.charCodeAt(t+2)]<<6|is[e.charCodeAt(t+3)],o[u++]=a>>16&255,o[u++]=a>>8&255,o[u++]=255&a;return 2===s?(a=is[e.charCodeAt(t)]<<2|is[e.charCodeAt(t+1)]>>4,o[u++]=255&a):1===s&&(a=is[e.charCodeAt(t)]<<10|is[e.charCodeAt(t+1)]<<4|is[e.charCodeAt(t+2)]>>2,o[u++]=a>>8&255,o[u++]=255&a),o}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(Qs,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function to(e,t,n,r){for(var a=0;a<r&&!(a+n>=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function no(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function ro(e,t){let n=e;if(Sa(e))return"string"===t?[]:[e.length];if("object"==typeof e){if("texture"in e){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if("buffer"in e&&!(e.buffer instanceof ArrayBuffer))return[e.buffer.size/(null==t?4:ht(t))]}if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||Sa(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&Ct().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&ao(e,r,[]),r}function ao(e,t,n){if(n=n||[],!Array.isArray(e)&&!Sa(e))return void Qe(0===t.length,(()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`));Qe(t.length>0,(()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`)),Qe(e.length===t[0],(()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`));const r=t.slice(1);for(let t=0;t<e.length;++t)ao(e[t],r,n.concat(t))}function so(e,t,n,r){if("string_or_numeric"!==e){if(null==e)throw new Error("Expected dtype cannot be null.");if("numeric"!==e&&e!==t||"numeric"===e&&"string"===t)throw new Error(`Argument '${n}' passed to '${r}' must be ${e} tensor, but got ${t} tensor`)}}function oo(e,t,n,r="numeric"){if(e instanceof Ba)return so(r,e.dtype,t,n),e;let a=ft(e);if("string"!==a&&["bool","int32","float32"].indexOf(r)>=0&&(a=r),so(r,a,t,n),null==e||!Sa(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){const r=null==e?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${r}'`)}const s=ro(e,a);Sa(e)||Array.isArray(e)||(e=[e]);const o="string"!==a?wa(e,a):Ea(e,[],!0);return ts.makeTensor(o,s,a)}function io(e,t,n,r="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map(((e,a)=>oo(e,`${t}[${a}]`,n,r)))}const uo="__op";function lo(e){const t=Object.keys(e);if(1!==t.length)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0];const r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n+=uo;const a=(...e)=>{ts.startScope(n);try{const t=r(...e);return It(t)&&console.error("Cannot return a Promise inside of tidy."),ts.endScope(t),t}catch(e){throw ts.endScope(null),e}};return Object.defineProperty(a,"name",{value:n,configurable:!0}),a}const co=lo({complex_:function(e,t){const n=oo(e,"real","complex"),r=oo(t,"imag","complex");Je(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, must match in call to tf.complex().`);const a={real:n,imag:r};return ts.runKernel("Complex",a)}});function po(e,t,n,r){if(null==r)r=ft(e);else if("complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if("object"==typeof e&&("texture"in e||"buffer"in e&&!(e.buffer instanceof ArrayBuffer))){if("float32"!==r&&"int32"!==r)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${r}.`);return ts.backend.createTensorFromGPUData(e,t||n,r)}if(!Sa(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=t){wt(t);const e=et(t),r=et(n);Qe(e===r,(()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${r}`));for(let e=0;e<n.length;++e){const r=n[e],a=e!==n.length-1||r!==et(t.slice(e));Qe(n[e]===t[e]||!a,(()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `))}}return Sa(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==r?wa(e,r):Ea(e,[],!0),ts.makeTensor(e,t,r)}function ho(e,t,n){return po(e,t,ro(e,n),n)}const fo={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};function mo(e,t){const n={};let r,a=0;for(const s of t){const t=s.name,o=s.dtype,i=s.shape,u=et(i);let l;if("quantization"in s){const n=s.quantization;if("uint8"===n.dtype||"uint16"===n.dtype){if(!("min"in n)||!("scale"in n))throw new Error(`Weight ${s.name} with quantization ${n.dtype} doesn't have corresponding metadata min and scale.`)}else{if("float16"!==n.dtype)throw new Error(`Weight ${s.name} has unknown quantization dtype ${n.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);if("float32"!==o)throw new Error(`Weight ${s.name} is quantized with ${n.dtype} which only supports weights of type float32 not ${o}.`)}const i=fo[n.dtype],c=e.slice(a,a+u*i),p="uint8"===n.dtype?new Uint8Array(c):new Uint16Array(c);if("float32"===o)if("uint8"===n.dtype||"uint16"===n.dtype){l=new Float32Array(p.length);for(let e=0;e<p.length;e++){const t=p[e];l[e]=t*n.scale+n.min}}else{if("float16"!==n.dtype)throw new Error(`Unsupported quantization type ${n.dtype} for weight type float32.`);void 0===r&&(r=So()),l=r(p)}else{if("int32"!==o)throw new Error(`Unsupported dtype in weight '${t}': ${o}`);if("uint8"!==n.dtype&&"uint16"!==n.dtype)throw new Error(`Unsupported quantization type ${n.dtype} for weight type int32.`);l=new Int32Array(p.length);for(let e=0;e<p.length;e++){const t=p[e];l[e]=Math.round(t*n.scale+n.min)}}a+=u*i}else if("string"===o){const t=et(s.shape);l=[];for(let n=0;n<t;n++){const t=new Uint32Array(e.slice(a,a+4))[0];a+=4;const n=new Uint8Array(e.slice(a,a+t));l.push(n),a+=t}}else{const r=fo[o],s=e.slice(a,a+u*r);if("float32"===o)l=new Float32Array(s);else if("int32"===o)l=new Int32Array(s);else if("bool"===o)l=new Uint8Array(s);else{if("complex64"!==o)throw new Error(`Unsupported dtype in weight '${t}': ${o}`);{l=new Float32Array(s);const e=new Float32Array(l.length/2),r=new Float32Array(l.length/2);for(let t=0;t<e.length;t++)e[t]=l[2*t],r[t]=l[2*t+1];const a=ho(e,i,"float32"),o=ho(r,i,"float32");n[t]=co(a,o),a.dispose(),o.dispose()}}a+=u*r}"complex64"!==o&&(n[t]=ho(l,i,o))}return n}function go(e){if(null===e)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0;const n=[];e.forEach((e=>{if(t+=e.byteLength,n.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${e.constructor.name}`)}));const r=new Uint8Array(t);let a=0;return n.forEach((e=>{r.set(new Uint8Array(e.buffer),a),a+=e.byteLength})),r.buffer}const yo=void 0!==_s&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function bo(e){return yo?_s.byteLength(e):new Blob([e]).size}function _o(e){if(1===e.length)return e[0];let t=0;e.forEach((e=>{t+=e.byteLength}));const n=new Uint8Array(t);let r=0;return e.forEach((e=>{n.set(new Uint8Array(e),r),r+=e.byteLength})),n.buffer}function xo(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function vo(e,t){const n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return null!=e.signature&&(n.signature=e.signature),null!=e.userDefinedMetadata&&(n.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(n.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(n.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(n.trainingConfig=e.trainingConfig),n}function wo(e,t,n){const r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(null!=e.trainingConfig&&(r.trainingConfig=e.trainingConfig),null!=e.weightsManifest){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!n)throw new Error("modelJSON has weightsManifest but weightData is null");r.weightSpecs=t,r.weightData=n}return null!=e.signature&&(r.signature=e.signature),null!=e.userDefinedMetadata&&(r.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(r.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(r.initializerSignature=e.initializerSignature),r}async function To(e,t){let n,r;return null!=e.weightsManifest&&([n,r]=await t(e.weightsManifest)),wo(e,n,r)}function ko(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:bo(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:bo(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:e.weightData.byteLength}}function Io(e){const t=[];for(const n of e)t.push(...n.weights);return t}function So(){const e=function(){const e=e=>{let t=e<<13,n=0;for(;0==(8388608&t);)n-=8388608,t<<=1;return t&=-8388609,n+=947912704,t|n},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let e=1024;e<2048;e++)t[e]=939524096+(e-1024<<13);return t}(),t=function(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}(),n=function(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}();return r=>{const a=new ArrayBuffer(4*r.length),s=new Uint32Array(a);for(let a=0;a<r.length;a++){const o=r[a],i=e[n[o>>10]+(1023&o)]+t[o>>10];s[a]=i}return new Float32Array(a)}}class Eo{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==Eo.instance&&(Eo.instance=new Eo),Eo.instance}static registerSaveRouter(e){Eo.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Eo.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Eo.getHandlers(e,"save")}static getLoadHandlers(e,t){return Eo.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[];return("load"===t?Eo.getInstance().loadRouters:Eo.getInstance().saveRouters).forEach((t=>{const a=t(e,n);null!==a&&r.push(a)})),r}}const No="tensorflowjs",Co="models_store",Ao="model_info_store";function Ro(){if(!Ct().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e="undefined"==typeof window?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function $o(e){const t=e.result;t.createObjectStore(Co,{keyPath:"modelPath"}),t.createObjectStore(Ao,{keyPath:"modelPath"})}class Mo{constructor(e){if(this.indexedDB=Ro(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise(((e,n)=>{const r=this.indexedDB.open(No,1);r.onupgradeneeded=()=>$o(r),r.onsuccess=()=>{const a=r.result;if(null==t){const t=a.transaction(Co,"readonly"),r=t.objectStore(Co).get(this.modelPath);r.onsuccess=()=>{if(null==r.result)return a.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(r.result.modelArtifacts)},r.onerror=e=>(a.close(),n(r.error)),t.oncomplete=()=>a.close()}else{const r=ko(t),s=a.transaction(Ao,"readwrite");let o=s.objectStore(Ao);const i=o.put({modelPath:this.modelPath,modelArtifactsInfo:r});let u;i.onsuccess=()=>{u=a.transaction(Co,"readwrite");const i=u.objectStore(Co).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:r});i.onsuccess=()=>e({modelArtifactsInfo:r}),i.onerror=e=>{o=s.objectStore(Ao);const t=o.delete(this.modelPath);t.onsuccess=()=>(a.close(),n(i.error)),t.onerror=e=>(a.close(),n(i.error))}},i.onerror=e=>(a.close(),n(i.error)),s.oncomplete=()=>{null==u?a.close():u.oncomplete=()=>a.close()}}},r.onerror=e=>n(r.error)}))}}Mo.URL_SCHEME="indexeddb://";const Fo=e=>{return Ct().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Mo.URL_SCHEME)?(t=e.slice(Mo.URL_SCHEME.length),new Mo(t)):null;var t};Eo.registerSaveRouter(Fo),Eo.registerLoadRouter(Fo);class Oo{constructor(){this.indexedDB=Ro()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open(No,1);n.onupgradeneeded=()=>$o(n),n.onsuccess=()=>{const r=n.result,a=r.transaction(Ao,"readonly"),s=a.objectStore(Ao).getAll();s.onsuccess=()=>{const t={};for(const e of s.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},s.onerror=e=>(r.close(),t(s.error)),a.oncomplete=()=>r.close()},n.onerror=e=>t(n.error)}))}async removeModel(e){var t;return e=(t=e).startsWith(Mo.URL_SCHEME)?t.slice(Mo.URL_SCHEME.length):t,new Promise(((t,n)=>{const r=this.indexedDB.open(No,1);r.onupgradeneeded=()=>$o(r),r.onsuccess=()=>{const a=r.result,s=a.transaction(Ao,"readwrite"),o=s.objectStore(Ao),i=o.get(e);let u;i.onsuccess=()=>{if(null==i.result)return a.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const r=o.delete(e),s=()=>{u=a.transaction(Co,"readwrite");const r=u.objectStore(Co).delete(e);r.onsuccess=()=>t(i.result.modelArtifactsInfo),r.onerror=e=>n(i.error)};r.onsuccess=s,r.onerror=e=>(s(),a.close(),n(i.error))}},i.onerror=e=>(a.close(),n(i.error)),s.oncomplete=()=>{null==u?a.close():u.oncomplete=()=>a.close()}},r.onerror=e=>n(r.error)}))}}const Do="/",Lo="tensorflowjs_models",Po="info",Bo="model_topology",Uo="weight_specs",zo="weight_data",Vo="model_metadata";function Wo(e){return{info:[Lo,e,Po].join(Do),topology:[Lo,e,Bo].join(Do),weightSpecs:[Lo,e,Uo].join(Do),weightData:[Lo,e,zo].join(Do),modelMetadata:[Lo,e,Vo].join(Do)}}function Ho(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function Go(e){const t=e.split(Do);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Do)}class jo{constructor(e){if(!Ct().getBool("IS_BROWSER")||"undefined"==typeof window||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=Wo(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),r=ko(e);try{this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(e){if(yo)return _s.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let e=0,r=t.length;e<r;e++)n+=String.fromCharCode(t[e]);return btoa(n)}(e.weightData));const a={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:null!=e.signature?e.signature:void 0,userDefinedMetadata:null!=e.userDefinedMetadata?e.userDefinedMetadata:void 0,modelInitializer:null!=e.modelInitializer?e.modelInitializer:void 0,initializerSignature:null!=e.initializerSignature?e.initializerSignature:void 0,trainingConfig:null!=e.trainingConfig?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(a)),{modelArtifactsInfo:r}}catch(e){throw Ho(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${r.modelTopologyBytes}, weightSpecsBytes=${r.weightSpecsBytes}, weightDataBytes=${r.weightDataBytes}.`)}}}async load(){const e=JSON.parse(this.LS.getItem(this.keys.info));if(null==e)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if("JSON"!==e.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(null==n)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;const r=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(null==r)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=r;const a=this.LS.getItem(this.keys.modelMetadata);if(null!=a){const e=JSON.parse(a);t.format=e.format,t.generatedBy=e.generatedBy,t.convertedBy=e.convertedBy,null!=e.signature&&(t.signature=e.signature),null!=e.userDefinedMetadata&&(t.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(t.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(t.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(t.trainingConfig=e.trainingConfig)}const s=this.LS.getItem(this.keys.weightData);if(null==s)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=function(e){if(yo){const t=_s.from(e,"base64");return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n.set([t.charCodeAt(e)],e);return n.buffer}(s),t}}jo.URL_SCHEME="localstorage://";const Ko=e=>{return Ct().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(jo.URL_SCHEME)?(t=e.slice(jo.URL_SCHEME.length),new jo(t)):null;var t};Eo.registerSaveRouter(Ko),Eo.registerLoadRouter(Ko);class qo{constructor(){Qe(Ct().getBool("IS_BROWSER"),(()=>"Current environment is not a web browser")),Qe("undefined"==typeof window||void 0!==window.localStorage,(()=>"Current browser does not appear to support localStorage")),this.LS=window.localStorage}async listModels(){const e={},t=Lo+Do,n=Do+Po;for(let r=0;r<this.LS.length;++r){const a=this.LS.key(r);a.startsWith(t)&&a.endsWith(n)&&(e[Go(a)]=JSON.parse(this.LS.getItem(a)))}return e}async removeModel(e){var t;const n=Wo(e=(t=e).startsWith(jo.URL_SCHEME)?t.slice(jo.URL_SCHEME.length):t);if(null==this.LS.getItem(n.info))throw new Error(`Cannot find model at path '${e}'`);const r=JSON.parse(this.LS.getItem(n.info));return Ho(n),r}}function Xo(e){return new Promise((e=>setTimeout(e))).then(e)}class Yo{constructor(e){if(!Ct().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Yo.URL_SCHEME)&&(e=e.slice(Yo.URL_SCHEME.length)),null!=e&&0!==e.length||(e="model"),this.modelJsonFileName=e+".json",this.weightDataFileName=e+".weights.bin"}async save(e){if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const n=vo(e,[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}]),r=window.URL.createObjectURL(new Blob([JSON.stringify(n)],{type:"application/json"})),a=null==this.modelJsonAnchor?document.createElement("a"):this.modelJsonAnchor;if(a.download=this.modelJsonFileName,a.href=r,await Xo((()=>a.dispatchEvent(new MouseEvent("click")))),null!=e.weightData){const e=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor;e.download=this.weightDataFileName,e.href=t,await Xo((()=>e.dispatchEvent(new MouseEvent("click"))))}return{modelArtifactsInfo:ko(e)}}}}Yo.URL_SCHEME="downloads://";class Qo{constructor(e){if(null==e||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise(((e,t)=>{const n=new FileReader;n.onload=n=>{const r=JSON.parse(n.target.result),a=r.modelTopology;if(null==a)return void t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));if(null==r.weightsManifest)return void t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));if(0===this.weightsFiles.length)return void e({modelTopology:a});const s=To(r,(e=>this.loadWeights(e)));e(s)},n.onerror=e=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),n.readAsText(this.jsonFile)}))}loadWeights(e){const t=[],n=[];for(const r of e)t.push(...r.weights),n.push(...r.paths);const r=this.checkManifestAndWeightFiles(e),a=n.map((e=>this.loadWeightsFile(e,r[e])));return Promise.all(a).then((e=>[t,_o(e)]))}loadWeightsFile(e,t){return new Promise(((n,r)=>{const a=new FileReader;a.onload=e=>{const t=e.target.result;n(t)},a.onerror=t=>r(`Failed to weights data from file of path '${e}'.`),a.readAsArrayBuffer(t)}))}checkManifestAndWeightFiles(e){const t=[],n=this.weightsFiles.map((e=>xo(e.name))),r={};for(const a of e)a.paths.forEach((e=>{const a=xo(e);if(-1!==t.indexOf(a))throw new Error(`Duplicate file basename found in weights manifest: '${a}'`);if(t.push(a),-1===n.indexOf(a))throw new Error(`Weight file with basename '${a}' is not provided.`);r[e]=this.weightsFiles[n.indexOf(a)]}));if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return r}}function Jo(e,t,n,r){!function(e){Qe(null!=e&&Array.isArray(e)&&e.length>0,(()=>"promises must be a none empty array"))}(e),function(e,t){Qe(e>=0&&e<=1,(()=>`Progress fraction must be in range [0, 1], but got startFraction ${e}`)),Qe(t>=0&&t<=1,(()=>`Progress fraction must be in range [0, 1], but got endFraction ${t}`)),Qe(t>=e,(()=>`startFraction must be no more than endFraction, but got startFraction ${e} and endFraction ${t}`))}(n=null==n?0:n,r=null==r?1:r);let a=0;return Promise.all(e.map((s=>(s.then((s=>{const o=n+ ++a/e.length*(r-n);return t(o),s})),s))))}async function Zo(e,t){null==t&&(t={});const n=null==t.fetchFunc?Ct().platform.fetch:t.fetchFunc,r=e.map((e=>n(e,t.requestInit,{isBinary:!0}))),a=(null==t.onProgress?await Promise.all(r):await Jo(r,t.onProgress,0,.5)).map((e=>e.arrayBuffer()));return null==t.onProgress?await Promise.all(a):await Jo(a,t.onProgress,.5,1)}function ei(e){return async(t,n="",r)=>{const a=t.map((()=>!1)),s={},o=null!=r?r.map((()=>!1)):[],i=[];if(t.forEach(((e,t)=>{let n=0;e.weights.forEach((e=>{const u="quantization"in e?e.quantization.dtype:e.dtype,l=fo[u]*et(e.shape),c=()=>{a[t]=!0,null==s[t]&&(s[t]=[]),s[t].push({manifestEntry:e,groupOffset:n,sizeBytes:l})};null!=r?r.forEach(((t,n)=>{t===e.name&&(c(),o[n]=!0)})):c(),i.push(e.name),n+=l}))})),!o.every((e=>e))){const e=r.filter(((e,t)=>!o[t]));throw new Error(`Could not find weights in manifest with names: ${e.join(", ")}. \nManifest JSON has weights with names: ${i.join(", ")}.`)}const u=a.reduce(((e,t,n)=>(t&&e.push(n),e)),[]),l=[];u.forEach((e=>{t[e].paths.forEach((e=>{const t=n+(n.endsWith("/")?"":"/")+e;l.push(t)}))}));const c=await e(l),p={};let h=0;return u.forEach((e=>{const n=t[e].paths.length;let r=0;for(let e=0;e<n;e++)r+=c[h+e].byteLength;const a=new ArrayBuffer(r),o=new Uint8Array(a);let i=0;for(let e=0;e<n;e++){const t=new Uint8Array(c[h+e]);o.set(t,i),i+=t.byteLength}s[e].forEach((e=>{const t=mo(a.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(const e in t)p[e]=t[e]})),h+=n})),p}}Eo.registerSaveRouter((e=>Ct().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Yo.URL_SCHEME)?function(e="model"){return new Yo(e)}(e.slice(Yo.URL_SCHEME.length)):null));class ti{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?(Qe("function"==typeof t.fetchFunc,(()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)")),this.fetch=t.fetchFunc):this.fetch=Ct().platform.fetch,Qe(null!=e&&e.length>0,(()=>"URL path for http must not be null, undefined or empty.")),Array.isArray(e)&&Qe(2===e.length,(()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`)),this.path=e,null!=t.requestInit&&null!=t.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=vo(e,[{paths:["./model.weights.bin"],weights:e.weightSpecs}]);t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:"application/octet-stream"}),"model.weights.bin");const r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:ko(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async load(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(e){let t=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?t+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":t+=" Please make sure the server is serving valid JSON for this request.",new Error(t)}const n=t.modelTopology,r=t.weightsManifest;if(null==n&&null==r)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return To(t,(e=>this.loadWeights(e)))}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=function(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?");return[e.substring(0,t)+"/",n>t?e.substring(n):""]}(t),a=this.weightPathPrefix||n,s=Io(e),o=[],i=[];for(const t of e)for(const e of t.paths)null!=this.weightUrlConverter?i.push(this.weightUrlConverter(e)):o.push(a+e+r);return this.weightUrlConverter&&o.push(...await Promise.all(i)),[s,_o(await Zo(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress}))]}}function ni(e){return null!=e.match(ti.URL_SCHEME_REGEX)}ti.URL_SCHEME_REGEX=/^https?:\/\//;const ri=(e,t)=>{if("undefined"==typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every((e=>ni(e))):ni(e),n)return ai(e,t)}return null};function ai(e,t){return new ti(e,t)}Eo.registerSaveRouter(ri),Eo.registerLoadRouter(ri);class si{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class oi{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class ii{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function ui(e,t,n,r){return 1===arguments.length?null!=e.modelTopology||null!=e.weightSpecs?new si(e):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new si({modelTopology:e})):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new si({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r}))}const li="://";class ci{constructor(){this.managers={}}static getInstance(){return null==ci.instance&&(ci.instance=new ci),ci.instance}static registerManager(e,t){Qe(null!=e,(()=>"scheme must not be undefined or null.")),e.endsWith(li)&&(e=e.slice(0,e.indexOf(li))),Qe(e.length>0,(()=>"scheme must not be an empty string."));const n=ci.getInstance();Qe(null==n.managers[e],(()=>`A model store manager is already registered for scheme '${e}'.`)),n.managers[e]=t}static getManager(e){const t=ci.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(ci.getInstance().managers)}}function pi(e){if(-1===e.indexOf(li))throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${ci.getSchemes().join(",")}`);return{scheme:e.split(li)[0],path:e.split(li)[1]}}async function hi(e,t,n=!1){Qe(e!==t,(()=>`Old path and new path are the same: '${e}'`));const r=Eo.getLoadHandlers(e);Qe(r.length>0,(()=>`Copying failed because no load handler is found for source URL ${e}.`)),Qe(r.length<2,(()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${e}.`));const a=r[0],s=Eo.getSaveHandlers(t);Qe(s.length>0,(()=>`Copying failed because no save handler is found for destination URL ${t}.`)),Qe(s.length<2,(()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${t}.`));const o=s[0],i=pi(e).scheme,u=pi(e).path,l=i===pi(e).scheme,c=await a.load();n&&l&&await ci.getManager(i).removeModel(u);const p=await o.save(c);return n&&!l&&await ci.getManager(i).removeModel(u),p.modelArtifactsInfo}var di=Object.freeze({__proto__:null,browserFiles:function(e){return new Qo(e)},browserHTTPRequest:function(e,t){return ai(e,t)},concatenateArrayBuffers:_o,decodeWeights:mo,encodeWeights:async function(e,t){const n=[],r=[],a=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);for(let s=0;s<a.length;++s){const o=a[s],i=Array.isArray(e)?e[s].tensor:e[o];if("float32"!==i.dtype&&"int32"!==i.dtype&&"bool"!==i.dtype&&"string"!==i.dtype&&"complex64"!==i.dtype)throw new Error(`Unsupported dtype in weight '${o}': ${i.dtype}`);const u={name:o,shape:i.shape,dtype:i.dtype};if("string"===i.dtype){const e=new Promise((async e=>{const t=await i.bytes(),n=t.reduce(((e,t)=>e+t.length),0)+4*t.length,r=new Uint8Array(n);let a=0;for(let e=0;e<t.length;e++){const n=t[e],s=new Uint8Array(new Uint32Array([n.length]).buffer);r.set(s,a),a+=4,r.set(n,a),a+=n.length}e(r)}));r.push(e)}else r.push(i.data());null!=t&&(u.group=t),n.push(u)}return{data:go(await Promise.all(r)),specs:n}},fromMemory:function(e,t,n,r){return new ii(ui(...arguments))},fromMemorySync:ui,getLoadHandlers:(e,t)=>Eo.getLoadHandlers(e,t),getModelArtifactsForJSON:To,getModelArtifactsForJSONSync:wo,getModelArtifactsInfoForJSON:ko,getSaveHandlers:e=>Eo.getSaveHandlers(e),getWeightSpecs:Io,http:ai,isHTTPScheme:ni,loadWeights:async function(e,t="",n,r){return ei((e=>Zo(e,{requestInit:r})))(e,t,n)},registerLoadRouter:e=>Eo.registerLoadRouter(e),registerSaveRouter:e=>Eo.registerSaveRouter(e),weightsLoaderFactory:ei,withSaveHandler:function(e){return new oi(e)},withSaveHandlerSync:function(e){return new oi(e)},copyModel:async function(e,t){return hi(e,t,!1)},listModels:async function(){const e=ci.getSchemes(),t={};for(const n of e){const e=await ci.getManager(n).listModels();for(const r in e)t[n+li+r]=e[r]}return t},moveModel:async function(e,t){return hi(e,t,!0)},removeModel:async function(e){const t=pi(e);return ci.getManager(t.scheme).removeModel(t.path)}});const fi=lo({cast_:function(e,t){const n=oo(e,"x","cast");if(!function(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if("string"===t&&"string"!==n.dtype||"string"!==t&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");const r={x:n},a={dtype:t};return ts.runKernel(Vt,r,a)}}),mi=lo({matMul_:function(e,t,n=!1,r=!1){let a=oo(e,"a","matMul"),s=oo(t,"b","matMul");[a,s]=qa(a,s);const o={a,b:s},i={transposeA:n,transposeB:r};return ts.runKernel(Ut,o,i)}}),gi=lo({oneHot_:function(e,t,n=1,r=0,a="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const s={indices:oo(e,"indices","oneHot","int32")},o={dtype:a,depth:t,onValue:n,offValue:r};return ts.runKernel(Dn,s,o)}});function yi(){return ts}function bi(e,t){return ts.tidy(e,t)}function _i(e){Xa(e).forEach((e=>e.dispose()))}function xi(e){return ts.keep(e)}function vi(e){return ts.setBackend(e)}function wi(e,t,n=1){return ts.registerBackend(e,t,n)}const Ti=lo({imag_:function(e){const t={input:oo(e,"input","imag")};return ts.runKernel("Imag",t)}}),ki=lo({neg_:function(e){const t={x:oo(e,"x","neg")};return ts.runKernel("Neg",t)}}),Ii=lo({real_:function(e){const t={input:oo(e,"input","real")};return ts.runKernel("Real",t)}}),Si=lo({transpose_:function(e,t,n){const r=oo(e,"x","transpose");if(null==t&&(t=r.shape.map(((e,t)=>t)).reverse()),Qe(r.rank===t.length,(()=>`Error in transpose: rank of input ${r.rank} must match length of perm ${t}.`)),t.forEach((e=>{Qe(e>=0&&e<r.rank,(()=>"All entries in 'perm' must be between 0 and "+(r.rank-1)+` but got ${t}`))})),r.rank<=1)return r.clone();const a={x:r},s={perm:t};return"complex64"===r.dtype?bi((()=>{let e=Ii(r),t=Ti(r);return e=ts.runKernel(xr,{x:e},s),t=ts.runKernel(xr,{x:t},s),n&&(t=ki(t)),co(e,t)})):ts.runKernel(xr,a,s)}});function Ei(e,t){const n=e.length,r=[];for(let a=0;a<n;a++){const s=n-1-a,o=e[s]||1;(t[t.length-1-a]||1)>1&&1===o&&r.unshift(s)}return r}function Ni(e,t){const n=[];for(let r=0;r<t.length;r++){const a=e[e.length-r-1],s=t.length-r-1,o=t[s];(null==a||1===a&&o>1)&&n.unshift(s)}return n}function Ci(e,t){const n=[],r=Math.max(e.length,t.length);for(let a=0;a<r;a++){let r=e[e.length-a-1];null==r&&(r=1);let s=t[t.length-a-1];if(null==s&&(s=1),1===r)n.unshift(s);else if(1===s)n.unshift(r);else{if(r!==s)throw Error(`Operands could not be broadcast together with shapes ${e} and ${t}.`);n.unshift(r)}}return n}function Ai(e,t,n){if(Ze(e),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");const r=ro(e,n);if(3!==r.length&&1!==r.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return po(e,t,r,n)}let Ri;const $i=lo({fromPixels_:function(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,r=!1,a=!1,s=!1,o=!1,i=!1;if(e.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&e instanceof ImageData)r=!0;else if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)a=!0;else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)s=!0;else if(null!=e.getContext)o=!0;else{if(!("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap))throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);i=!0}if(null!=$r(kr,ts.backendName)){const n={pixels:e},r={numChannels:t};return ts.runKernel(kr,n,r)}const[u,l]=a?[e.videoWidth,e.videoHeight]:[e.width,e.height];let c,p;if(o)c=e.getContext("2d").getImageData(0,0,u,l).data;else if(r||n)c=e.data;else if(s||a||i){if(null==Ri)if("undefined"==typeof document){if("undefined"==typeof OffscreenCanvas||"undefined"==typeof OffscreenCanvasRenderingContext2D)throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");Ri=new OffscreenCanvas(1,1).getContext("2d")}else Ri=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});Ri.canvas.width=u,Ri.canvas.height=l,Ri.drawImage(e,0,0,u,l),c=Ri.getImageData(0,0,u,l).data}if(4===t)p=new Int32Array(c);else{const e=u*l;p=new Int32Array(e*t);for(let n=0;n<e;n++)for(let e=0;e<t;++e)p[n*t+e]=c[4*n+e]}return Ai(p,[l,u,t],"int32")}});function Mi(e,t){const n=e.shape.length,r=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(r<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${r}.`);if("int32"!==t.dtype)throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[r-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[r-1]} vs. ${n}`);if(0===et(e.shape))throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const a=t.shape,s=a[a.length-1];let o=1;for(let e=0;e<a.length-1;++e)o*=a[e];const i=e.shape,u=a.slice();u.pop();let l=1;for(let e=s;e<n;++e)l*=i[e],u.push(i[e]);const c=[...yt(e.shape).map((e=>e/l)),1].slice(0,s);return[u,o,l,c]}function Fi(e,t,n){const r=t.rank>1?t.shape[t.rank-1]:1,a=t.rank>1?t.rank-1:1,s=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${r}, and batchDim: ${a}.`;if(n.rank<a)throw new Error(s+` update.rank < ${a}. `);if(e.length<r+(n.rank-a))throw new Error(s+` Output shape length < ${r+(n.rank-a)}`);if(n.rank!==a+e.length-r)throw new Error(s+" update.rank != "+(a+e.length-r));for(let e=0;e<a;++e)if(n.shape[e]!==t.shape[e])throw new Error(s+` updates.shape[${e}] (${n.shape[e]}) != indices.shape[${e}] (${t.shape[e]}).`);for(let t=0;t<n.rank-a;++t)if(n.shape[t+a]!==e[t+r])throw new Error(s+` updates.shape[${t+a}] (${n.shape[t+a]}) != shape[${t+a}] (${e[t+a]})`)}function Oi(e,t,n){if(t.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(e.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);if("int32"!==t.dtype)throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);if(n.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${n}`);if(0===n.length){if(0===t.size)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(0===e.size)throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`)}Fi(n,t,e)}function Di(e,t,n){const r=t.shape.length,a=r>1?t.shape[r-1]:1,s=n.length;let o=1;for(let e=a;e<s;++e)o*=n[e];const i=a<1?1:a;return{sliceRank:a,numUpdates:et(t.shape)/i,sliceSize:o,strides:[...yt(n.slice(0,a)),1],outputSize:et(n)}}function Li(e,t,n){const r=e.shape.length;Qe(r===t.length,(()=>`Error in slice${r}D: Length of begin ${t} must match the rank of the array (${r}).`)),Qe(r===n.length,(()=>`Error in slice${r}D: Length of size ${n} must match the rank of the array (${r}).`));for(let a=0;a<r;++a)Qe(t[a]+n[a]<=e.shape[a],(()=>`Error in slice${r}D: begin[${a}] + size[${a}] (${t[a]+n[a]}) would overflow input.shape[${a}] (${e.shape[a]})`))}function Pi(e,t,n){const r=[];for(let a=0;a<e.length;a++)r[a]=Math.ceil((t[a]-e[a])/n[a]);return r}function Bi(e,t,n,r){const a=[...e];for(let e=a.length;e<r.length;e++)a.push(1);for(let e=0;e<n;e++)0===e?a[t]=1:(a.splice(t,0,1),a.pop());return a}function Ui(e,t,n){return n<=e?n:n-(t-1)}function zi(e,t){const n=[];for(let r=0;r<e;r++)n.push(t+r);return n}function Vi(e,t,n,r,a){const s=[...a],o=zi(n,t);for(let a=0;a<s.length;a++)if(o.indexOf(a)>-1)s[a]=0;else{const o=Ui(t,n,a);let i=r[o];e&1<<o&&(i=0),s[a]=i}return s}function Wi(e,t,n,r,a){const s=[...a],o=zi(n,t);for(let a=0;a<s.length;a++)if(o.indexOf(a)>-1)s[a]=Number.MAX_SAFE_INTEGER;else{const o=Ui(t,n,a);let i=r[o];e&1<<o&&(i=Number.MAX_SAFE_INTEGER),s[a]=i}for(let e=0;e<s.length;e++){const t=a[e];s[e]<0&&(s[e]+=t),s[e]=qe(0,s[e],a[e])}return s}function Hi(e,t,n){let r=e[t];return(n&1<<t||null==r)&&(r=1),r}function Gi(e,t,n,r,a,s){let o=t[a];const i=n[a]||1;(e&1<<a||s&1<<a||null==o)&&(o=i>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);const u=r[a];return o<0&&(o+=u),o=qe(0,o,u-1),o}function ji(e,t,n,r,a,s){let o=t[a];const i=n[a]||1;(e&1<<a||s&1<<a||null==o)&&(o=i>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);const u=r[a];return o<0&&(o+=u),o=i>0?qe(0,o,u):qe(-1,o,u-1),o}function Ki(e,t,n){let r=n.length;for(let e=0;e<n.length;e++)if(n[e]>1){r=e;break}for(let a=r+1;a<n.length;a++)if(t[a]>0||n[a]!==e[a])return!1;return!0}function qi(e,t){let n=e.length>0?e[e.length-1]:1;for(let r=0;r<e.length-1;r++)n+=e[r]*t[r];return n}function Xi(e,t,n){let r;const a=e.shape.length;let s;return r="number"==typeof t?[t,...new Array(a-1).fill(0)]:t.length<a?t.concat(new Array(a-t.length).fill(0)):t.slice(),r.forEach((e=>{Qe(-1!==e,(()=>"slice() does not support negative begin indexing."))})),s=null==n?new Array(a).fill(-1):"number"==typeof n?[n,...new Array(a-1).fill(-1)]:n.length<a?n.concat(new Array(a-n.length).fill(-1)):n,s=s.map(((t,n)=>t>=0?t:(Qe(-1===t,(()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`)),e.shape[n]-r[n]))),[r,s]}function Yi(e,t,n,r,a,s,o,i,u){let l;if(null==r?(l=new Array(t.length),l.fill(1)):l=r,null!=o&&0!=(o&o-1))throw new Error("Multiple ellipses in slice is not allowed.");let c=!1;const p={dims:l.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:l.slice(),beginMask:a,endMask:s,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:u};for(let e=0;e<p.dims;e++)c&&0!=(1<<e&i)&&p.numAddAxisAfterEllipsis++,1<<e&o&&(c=!0);c||(p.ellipsisMask|=1<<p.dims,p.dims++);const h={dims:e.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};!function(e,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let n=0;t.beginValid=null!=e.begin,t.endValid=null!=e.end,t.begin=new Array(t.dims),t.end=new Array(t.dims),t.strides=new Array(t.dims),t.finalShapeGatherIndices=[],t.finalShapeGatherIndicesSparse=[],t.inputShapeGatherIndicesSparse=new Array(t.dims);for(let r=0;r<e.dims;r++)if(1<<r&e.ellipsisMask){const a=Math.min(t.dims-(e.dims-r)+1+e.numAddAxisAfterEllipsis,t.dims);for(;n<a;n++)t.begin[n]=0,t.end[n]=0,t.strides[n]=1,t.beginMask|=1<<n,t.endMask|=1<<n,t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(-1),t.inputShapeGatherIndicesSparse[n]=r}else if(1<<r&e.newAxisMask)t.finalShapeGatherIndices.push(-2),t.finalShapeGatherIndicesSparse.push(-1);else{if(n===t.begin.length)throw Error(`Index out of range using input dim ${n}; input has only ${t.dims} dims, ${t.begin.length}.`);null!=e.begin&&(t.begin[n]=e.begin[r]),null!=e.end&&(t.end[n]=e.end[r]),t.strides[n]=e.strides[r],e.beginMask&1<<r&&(t.beginMask|=1<<n),e.endMask&1<<r&&(t.endMask|=1<<n),e.shrinkAxisMask&1<<r?(t.finalShapeGatherIndices.push(-1),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<n):(t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(r)),t.inputShapeGatherIndicesSparse[n]=r,n++}}(p,h);let d=!0,f=!0,m=!0;const g=[],y=[];for(let t=0;t<e.length;++t){if(0===h.strides[t])throw Error(`strides[${t}] must be non-zero`);const n=!!(h.shrinkAxisMask&1<<t),r=e[t];if(-1===r){g.push(n?1:-1);continue}const a=[h.beginMask&1<<t,h.endMask&1<<t],s=[h.strides[t]>0?0:-1,h.strides[t]>0?r:r-1];if(n&&h.strides[t]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&1===h.strides[t];const o=!!(h.beginMask&1<<t&&h.endMask&1<<t);if(h.beginValid&&h.endValid){if(n){const e=h.begin[t]<0?r+h.begin[t]:h.begin[t];if(h.begin[t]=e,h.end[t]=h.begin[t]+1,e<0||e>=r)throw Error(`slice index ${h.begin[t]} of dimension ${t} out of bounds.`)}else h.begin[t]=Qi(h.begin[t],0,h.strides[t],r,a,s),h.end[t]=Qi(h.end[t],1,h.strides[t],r,a,s);const e=1===h.strides[t]&&0===h.begin[t]&&h.end[t]===r;d=d&&e,f=f&&(0===t&&1===h.strides[t]||e)}else d=d&&1===h.strides[t]&&o,f=f&&(0===t&&1===h.strides[t]||o);let i,u=!1;if(h.beginValid&&h.endValid?(i=h.end[t]-h.begin[t],u=!0):n?(i=1,u=!0):o&&r>=0&&(i=h.strides[t]<0?-r:r,u=!0),u){let e;e=0===i||i<0!=h.strides[t]<0?0:Math.trunc(i/h.strides[t])+(i%h.strides[t]!=0?1:0),g.push(e)}else g.push(-1)}for(let e=0;e<h.finalShapeGatherIndices.length;++e){const t=h.finalShapeGatherIndices[e];t>=0?y.push(g[t]):-2===t&&y.push(1)}const b=y.filter(((e,t)=>-2!==h.finalShapeGatherIndices[t]));return{finalShapeSparse:b,finalShape:y,isIdentity:d,sliceDim0:f,isSimpleSlice:m,begin:h.begin,end:h.end,strides:h.strides}}function Qi(e,t,n,r,a,s){if(a[t])return n>0?s[t]:s[t+1&1];{const t=e<0?r+e:e;return t<s[0]?s[0]:t>s[1]?s[1]:t}}var Ji=Object.freeze({__proto__:null,assertParamsValid:Li,maskToAxes:function(e){const t=[];let n=0;for(;e>0;)1&e&&t.push(n),e/=2,n++;return t},computeOutShape:Pi,stridesWithElidedDims:Bi,getNormalizedAxes:function(e,t,n,r,a,s,o,i,u){const l=e.length;let c=new Array(l),p=new Array(l),h=new Array(l);if(t.length&&n>0){const u=t[0],l=n+1;c=Vi(o,u,l,r,e),p=Wi(i,u,l,a,e),h=Bi(s,u,l,e)}else for(let t=0;t<l;t++)c[t]=Gi(o,r,s,e,t,u),p[t]=ji(i,a,s,e,t,u),h[t]=Hi(s,t,u);return{begin:c,end:p,strides:h}},startIndicesWithElidedDims:Vi,stopIndicesWithElidedDims:Wi,stridesForAxis:Hi,startForAxis:Gi,stopForAxis:ji,isSliceContinous:Ki,computeFlatOffset:qi,parseSliceParams:Xi,sliceInfo:Yi});const Zi=lo({add_:function(e,t){let n=oo(e,"a","add"),r=oo(t,"b","add");[n,r]=qa(n,r);const a={a:n,b:r};return ts.runKernel(Ft,a)}}),eu=lo({floorDiv_:function(e,t){let n=oo(e,"a","floorDiv"),r=oo(t,"b","floorDiv");[n,r]=qa(n,r);const a={a:n,b:r};return ts.runKernel(ln,a)}}),tu=lo({div_:function(e,t){let n=oo(e,"a","div"),r=oo(t,"b","div");if([n,r]=qa(n,r),"int32"===n.dtype&&"int32"===r.dtype)return eu(n,r);const a={a:n,b:r};return ts.runKernel(en,a,{})}}),nu=lo({mul_:function(e,t){let n=oo(e,"a","mul"),r=oo(t,"b","mul");[n,r]=qa(n,r);const a={a:n,b:r};return ts.runKernel(An,a)}}),ru=lo({abs_:function(e){const t=oo(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return ts.runKernel("ComplexAbs",e)}{const e={x:t};return ts.runKernel("Abs",e)}}}),au=lo({acos_:function(e){const t={x:oo(e,"x","acos")};return ts.runKernel("Acos",t)}}),su=lo({acosh_:function(e){const t={x:oo(e,"x","acosh")};return ts.runKernel("Acosh",t)}}),ou=lo({addN_:function(e){Qe(Array.isArray(e),(()=>"The argument passed to tf.addN() must be a list of tensors")),Qe(e.length>=1,(()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`));const t=e.map(((e,t)=>oo(e,`tensors${t}`,"addN"))),n=t[0];t.forEach((e=>{if(e.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")})),t.forEach((e=>{if(!tt(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));const r=t;return ts.runKernel(Ot,r)}}),iu=lo({all_:function(e,t=null,n=!1){const r={x:oo(e,"x","all","bool")},a={axis:t,keepDims:n};return ts.runKernel(Dt,r,a)}}),uu=lo({any_:function(e,t=null,n=!1){const r={x:oo(e,"x","any","bool")},a={axis:t,keepDims:n};return ts.runKernel(Lt,r,a)}}),lu=lo({argMax_:function(e,t=0){const n={x:oo(e,"x","argMax")},r={axis:t};return ts.runKernel(Pt,n,r)}}),cu=lo({argMin_:function(e,t=0){const n={x:oo(e,"x","argMin")},r={axis:t};return ts.runKernel("ArgMin",n,r)}}),pu=lo({asin_:function(e){const t={x:oo(e,"x","asin")};return ts.runKernel("Asin",t)}}),hu=lo({asinh_:function(e){const t={x:oo(e,"x","asinh")};return ts.runKernel("Asinh",t)}}),du=lo({atan_:function(e){const t={x:oo(e,"x","atan")};return ts.runKernel("Atan",t)}}),fu=lo({atan2_:function(e,t){let n=oo(e,"a","atan2"),r=oo(t,"b","atan2");[n,r]=qa(n,r);const a={a:n,b:r};return ts.runKernel("Atan2",a)}}),mu=lo({atanh_:function(e){const t={x:oo(e,"x","atanh")};return ts.runKernel("Atanh",t)}});function gu(e,t,n,r,a,s,o="channelsLast"){const[i,u]=xu(t);let l;if("channelsLast"===o)l=[i,u,e[3],e[3]];else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);l=[i,u,e[1],e[1]]}return yu(e,l,n,r,a,s,!1,o)}function yu(e,t,n,r,a,s,o=!1,i="channelsLast"){let[u,l,c,p]=[-1,-1,-1,-1];if("channelsLast"===i)[u,l,c,p]=e;else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);[u,p,l,c]=e}const[h,d,,f]=t,[m,g]=xu(n),[y,b]=xu(r),_=wu(h,y),x=wu(d,b),{padInfo:v,outHeight:w,outWidth:T}=function(e,t,n,r,a,s,o,i,u){let l,c,p;if("number"==typeof e){l={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const a=function(e,t,n,r,a){null==r&&(r=_u(e,t,n));const s=e[1];return[Tu((e[0]-t+2*r)/n+1,a),Tu((s-t+2*r)/n+1,a)]}([t,n],s,r,e,i);c=a[0],p=a[1]}else if("same"===e){c=Math.ceil(t/r),p=Math.ceil(n/a);const e=Math.max(0,(c-1)*r+s-t),i=Math.max(0,(p-1)*a+o-n),u=Math.floor(e/2),h=e-u,d=Math.floor(i/2);l={top:u,bottom:h,left:d,right:i-d,type:"SAME"}}else if("valid"===e)l={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-s+1)/r),p=Math.ceil((n-o+1)/a);else{if("object"!=typeof e)throw Error(`Unknown padding parameter: ${e}`);{const h="channelsLast"===u?e[1][0]:e[2][0],d="channelsLast"===u?e[1][1]:e[2][1],f="channelsLast"===u?e[2][0]:e[3][0],m="channelsLast"===u?e[2][1]:e[3][1];l={top:h,bottom:d,left:f,right:m,type:0===h&&0===d&&0===f&&0===m?"VALID":"EXPLICIT"},c=Tu((t-s+h+d)/r+1,i),p=Tu((n-o+f+m)/a+1,i)}}return{padInfo:l,outHeight:c,outWidth:p}}(a,l,c,m,g,_,x,s,i),k=o?f*p:f;let I;return"channelsFirst"===i?I=[u,k,w,T]:"channelsLast"===i&&(I=[u,w,T,k]),{batchSize:u,dataFormat:i,inHeight:l,inWidth:c,inChannels:p,outHeight:w,outWidth:T,outChannels:k,padInfo:v,strideHeight:m,strideWidth:g,filterHeight:h,filterWidth:d,effectiveFilterHeight:_,effectiveFilterWidth:x,dilationHeight:y,dilationWidth:b,inShape:e,outShape:I,filterShape:t}}function bu(e,t,n,r,a,s=!1,o="channelsLast",i){let[u,l,c,p,h]=[-1,-1,-1,-1,-1];if("channelsLast"===o)[u,l,c,p,h]=e;else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);[u,h,l,c,p]=e}const[d,f,m,,g]=t,[y,b,_]=vu(n),[x,v,w]=vu(r),T=wu(d,x),k=wu(f,v),I=wu(m,w),{padInfo:S,outDepth:E,outHeight:N,outWidth:C}=function(e,t,n,r,a,s,o,i,u,l,c){let p,h,d,f;if("valid"===e&&(e=0),"number"==typeof e){p={top:e,bottom:e,left:e,right:e,front:e,back:e,type:0===e?"VALID":"NUMBER"};const m=function(e,t,n,r,a,s){null==a&&(a=_u(e,t[0],r[0]));const o=[0,0,0,1];for(let n=0;n<3;n++)e[n]+2*a>=t[n]&&(o[n]=Tu((e[n]-t[n]+2*a)/r[n]+1,s));return o}([t,n,r,1],[i,u,l],0,[a,s,o],e,c);h=m[0],d=m[1],f=m[2]}else{if("same"!==e)throw Error(`Unknown padding parameter: ${e}`);{h=Math.ceil(t/a),d=Math.ceil(n/s),f=Math.ceil(r/o);const e=(h-1)*a+i-t,c=(d-1)*s+u-n,m=(f-1)*o+l-r,g=Math.floor(e/2),y=e-g,b=Math.floor(c/2),_=c-b,x=Math.floor(m/2);p={top:b,bottom:_,left:x,right:m-x,front:g,back:y,type:"SAME"}}}return{padInfo:p,outDepth:h,outHeight:d,outWidth:f}}(a,l,c,p,y,b,_,T,k,I,i),A=s?g*h:g;let R;return"channelsFirst"===o?R=[u,A,E,N,C]:"channelsLast"===o&&(R=[u,E,N,C,A]),{batchSize:u,dataFormat:o,inDepth:l,inHeight:c,inWidth:p,inChannels:h,outDepth:E,outHeight:N,outWidth:C,outChannels:A,padInfo:S,strideDepth:y,strideHeight:b,strideWidth:_,filterDepth:d,filterHeight:f,filterWidth:m,effectiveFilterDepth:T,effectiveFilterHeight:k,effectiveFilterWidth:I,dilationDepth:x,dilationHeight:v,dilationWidth:w,inShape:e,outShape:R,filterShape:t}}function _u(e,t,n,r=1){const a=wu(t,r);return Math.floor((e[0]*(n-1)-n+a)/2)}function xu(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function vu(e){return"number"==typeof e?[e,e,e]:e}function wu(e,t){return t<=1?e:e+(e-1)*(t-1)}function Tu(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function ku(e){const[t,n,r]=xu(e);return 1===t&&1===n&&1===r}function Iu(e,t){return ku(e)||ku(t)}function Su(e){return xu(e).every((e=>e>0))}function Eu(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function Nu(e,t,n){if(null!=n){if("string"==typeof t)throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if("number"==typeof t)Qe(nt(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`));else{if("object"!=typeof t)throw Error(`Error in ${e}: Unknown padding parameter: ${t}`);t.forEach((t=>{t.forEach((t=>{Qe(nt(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`))}))}))}}}const Cu=lo({reshape_:function(e,t){const n={x:oo(e,"x","reshape","string_or_numeric")},r={shape:t};return ts.runKernel(Hn,n,r)}}),Au=lo({avgPool_:function(e,t,n,r,a){const s=oo(e,"x","avgPool","float32");Qe(Iu(n,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`));let o=s,i=!1;3===s.rank&&(i=!0,o=Cu(s,[1,s.shape[0],s.shape[1],s.shape[2]])),Qe(4===o.rank,(()=>`Error in avgPool: x must be rank 4 but got rank ${o.rank}.`)),Nu("avgPool",r,a);const u={x:o},l={filterSize:t,strides:n,pad:r,dimRoundingMode:a};let c=ts.runKernel(Bt,u,l);return c=fi(c,s.dtype),i?Cu(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),Ru=lo({avgPool3d_:function(e,t,n,r,a,s="NDHWC"){const o=oo(e,"x","avgPool3d","float32");let i=o,u=!1;4===o.rank&&(u=!0,i=Cu(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),Qe(5===i.rank,(()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`)),Qe("NDHWC"===s,(()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`)),Qe("number"==typeof n&&n>0||Array.isArray(n)&&n[0]>0&&n[1]>0&&n[2]>0,(()=>`Error in avgPool3d: Stride must be > 0, but got '${n}'`)),Nu("avgPool3d",r,a);const l={x:i},c={filterSize:t,strides:n,pad:r,dimRoundingMode:a,dataFormat:s};let p=ts.runKernel("AvgPool3D",l,c);return p=fi(p,i.dtype),u?Cu(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}}),$u=lo({clone_:function(e){const t={x:oo(e,"x","clone","string_or_numeric")};return ts.runKernel(mn,t)}}),Mu=lo({concat_:function(e,t=0){Qe(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=io(e,"tensors","concat","string_or_numeric");if("complex64"===n[0].dtype&&n.forEach((e=>{if("complex64"!==e.dtype)throw new Error(`Cannot concatenate complex64 tensors with a tensor\n with dtype ${e.dtype}. `)})),1===n.length)return $u(n[0]);const r=n,a={axis:t};return ts.runKernel(Gt,r,a)}}),Fu=lo({sigmoid_:function(e){const t={x:oo(e,"x","sigmoid","float32")};return ts.runKernel(er,t)}}),Ou=lo({slice_:function(e,t,n){const r=oo(e,"x","slice","string_or_numeric");if(0===r.rank)throw new Error("Slicing scalar is not possible");const a={x:r},s={begin:t,size:n};return ts.runKernel(Zn,a,s)}}),Du=lo({tanh_:function(e){const t={x:oo(e,"x","tanh","float32")};return ts.runKernel(gr,t)}}),Lu=lo({basicLSTMCell_:function(e,t,n,r,a,s){const o=oo(e,"forgetBias","basicLSTMCell"),i=oo(t,"lstmKernel","basicLSTMCell"),u=oo(n,"lstmBias","basicLSTMCell"),l=oo(r,"data","basicLSTMCell"),c=oo(a,"c","basicLSTMCell"),p=oo(s,"h","basicLSTMCell"),h=Mu([l,p],1),d=mi(h,i),f=Zi(d,u),m=f.shape[0],g=f.shape[1]/4,y=[m,g],b=Ou(f,[0,0],y),_=Ou(f,[0,g],y),x=Ou(f,[0,2*g],y),v=Ou(f,[0,3*g],y),w=Zi(nu(Fu(b),Du(_)),nu(c,Fu(Zi(o,x))));return[w,nu(Du(w),Fu(v))]}}),Pu=lo({batchToSpaceND_:function(e,t,n){const r=oo(e,"x","batchToSpaceND"),a=t.reduce(((e,t)=>e*t));Qe(r.rank>=1+t.length,(()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`)),Qe(n.length===t.length,(()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`)),Qe(r.shape[0]%a==0,(()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${a}`));const s={x:r},o={blockShape:t,crops:n};return ts.runKernel(zt,s,o)}}),Bu=lo({batchNorm_:function(e,t,n,r,a,s){null==s&&(s=.001);const o=oo(e,"x","batchNorm"),i=oo(t,"mean","batchNorm"),u=oo(n,"variance","batchNorm");let l,c;null!=a&&(l=oo(a,"scale","batchNorm")),null!=r&&(c=oo(r,"offset","batchNorm")),Qe(i.rank===u.rank,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),Qe(null==c||i.rank===c.rank,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),Qe(null==l||i.rank===l.rank,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));const p=function(e){let t;return t=0===e.rank||1===e.rank?Cu(e,[1,1,1,e.size]):2===e.rank?Cu(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?Cu(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(o),h={x:p,scale:l,offset:c,mean:i,variance:u},d={varianceEpsilon:s},f=ts.runKernel(cn,h,d);return Cu(f,o.shape)}}),Uu=lo({batchNorm2d_:function(e,t,n,r,a,s){const o=oo(e,"x","batchNorm"),i=oo(t,"mean","batchNorm"),u=oo(n,"variance","batchNorm");let l,c;return null!=a&&(l=oo(a,"scale","batchNorm")),null!=r&&(c=oo(r,"offset","batchNorm")),Qe(2===o.rank,(()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`)),Qe(2===i.rank||1===i.rank,(()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`)),Qe(2===u.rank||1===u.rank,(()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${u.rank}.`)),null!=l&&Qe(2===l.rank||1===l.rank,(()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${l.rank}.`)),null!=c&&Qe(2===c.rank||1===c.rank,(()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`)),Bu(o,i,u,c,l,s)}}),zu=lo({batchNorm3d_:function(e,t,n,r,a,s){const o=oo(e,"x","batchNorm"),i=oo(t,"mean","batchNorm"),u=oo(n,"variance","batchNorm");let l,c;return null!=a&&(l=oo(a,"scale","batchNorm")),null!=r&&(c=oo(r,"offset","batchNorm")),Qe(3===o.rank,(()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`)),Qe(3===i.rank||1===i.rank,(()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`)),Qe(3===u.rank||1===u.rank,(()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${u.rank}.`)),null!=l&&Qe(3===l.rank||1===l.rank,(()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${l.rank}.`)),null!=c&&Qe(3===c.rank||1===c.rank,(()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`)),Bu(o,i,u,c,l,s)}}),Vu=lo({batchNorm4d_:function(e,t,n,r,a,s){const o=oo(e,"x","batchNorm"),i=oo(t,"mean","batchNorm"),u=oo(n,"variance","batchNorm");let l,c;return null!=a&&(l=oo(a,"scale","batchNorm")),null!=r&&(c=oo(r,"offset","batchNorm")),Qe(4===o.rank,(()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`)),Qe(4===i.rank||1===i.rank,(()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`)),Qe(4===u.rank||1===u.rank,(()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${u.rank}.`)),null!=l&&Qe(4===l.rank||1===l.rank,(()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${l.rank}.`)),null!=c&&Qe(4===c.rank||1===c.rank,(()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`)),Bu(o,i,u,c,l,s)}}),Wu=lo({bincount_:function(e,t,n){const r=oo(e,"x","bincount"),a=oo(t,"weights","bincount");Qe("int32"===r.dtype,(()=>`Error in bincount: input dtype must be int32, but got ${r.dtype}`)),Qe(n>=0,(()=>`size must be non-negative, but got ${n}.`)),Qe(a.size===r.size||0===a.size,(()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${r.shape}, weights shape: ${a.shape}.`));const s={x:r,weights:a},o={size:n};return ts.runKernel("Bincount",s,o)}}),Hu=lo({broadcastArgs_:function(e,t){const n=oo(e,"s0","broadcastArgs","int32"),r=oo(t,"s1","broadcastArgs","int32");if(1!==n.rank)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(1!==r.rank)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${r.rank}`);const a={s0:n,s1:r};return ts.runKernel("BroadcastArgs",a)}}),Gu=lo({broadcastTo_:function(e,t){let n=oo(e,"broadcastTo","x");const r=n.shape;if(wt(t),t.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){const e=n.shape.slice();for(;e.length<t.length;)e.unshift(1);n=Cu(n,e)}const a=n.shape,s=Array.from(t);for(let e=t.length-1;e>=0;e--)if(a[e]===t[e])s[e]=1;else if(1!==n.shape[e])throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${t}].`);const o=s.map(((e,t)=>e>1?t:-1)).filter((e=>e>=0));if(0===o.length)return $u(n);const i={x:n},u={reps:s};return ts.runKernel(yr,i,u)}});function ju(e,t="float32",n){return t=t||"float32",wt(e),new Da(e,t,n)}const Ku=lo({ceil_:function(e){const t={x:oo(e,"x","ceil","float32")};return ts.runKernel(Wt,t)}});function qu(e,t,n){wt(e);const r={shape:e,value:t,dtype:n};return ts.runKernel(sn,{},r)}const Xu=lo({clipByValue_:function(e,t,n){const r=oo(e,"x","clipByValue");if(Qe(t<=n,(()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`)),t===n)return qu(r.shape,t,r.dtype);const a={x:r},s={clipValueMin:t,clipValueMax:n};return ts.runKernel(Ht,a,s)}}),Yu=lo({concat1d_:function(e){return Mu(e,0)}}),Qu=lo({concat2d_:function(e,t){return Mu(e,t)}}),Ju=lo({concat3d_:function(e,t){return Mu(e,t)}}),Zu=lo({concat4d_:function(e,t){return Mu(e,t)}}),el=lo({conv2d_:function(e,t,n,r,a="NHWC",s=[1,1],o){const i=oo(e,"x","conv2d","float32"),u=oo(t,"filter","conv2d","float32");let l=i,c=!1;3===i.rank&&(c=!0,l=Cu(i,[1,i.shape[0],i.shape[1],i.shape[2]])),Qe(4===l.rank,(()=>`Error in conv2d: input must be rank 4, but got rank ${l.rank}.`)),Qe(4===u.rank,(()=>`Error in conv2d: filter must be rank 4, but got rank ${u.rank}.`)),Nu("conv2d",r,o);const p="NHWC"===a?l.shape[3]:l.shape[1];Qe(p===u.shape[2],(()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${u.shape[2]}.`)),Qe(Iu(n,s),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`)),Qe(Su(s),(()=>"Error in conv2D: Dilated rates should be larger than 0.")),Qe(Su(n),(()=>"Error in conv2D: Strides should be larger than 0."));const h={x:l,filter:u},d={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o},f=ts.runKernel(jt,h,d);return c?Cu(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),tl=lo({conv1d_:function(e,t,n,r,a="NWC",s=1,o){const i=oo(e,"x","conv1d"),u=oo(t,"filter","conv1d");let l=i,c=!1;2===i.rank&&(c=!0,l=Cu(i,[1,i.shape[0],i.shape[1]])),Qe(3===l.rank,(()=>`Error in conv1d: input must be rank 3, but got rank ${l.rank}.`)),Qe(3===u.rank,(()=>`Error in conv1d: filter must be rank 3, but got rank ${u.rank}.`)),Nu("conv1d",r,o),Qe(l.shape[2]===u.shape[1],(()=>`Error in conv1d: depth of input (${l.shape[2]}) must match input depth for filter ${u.shape[1]}.`)),Qe(Iu(n,s),(()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${s}'`)),Qe(Su(s),(()=>"Error in conv1D: Dilated rates should be larger than 0.")),Qe(Su(n),(()=>"Error in conv1D: Stride should be larger than 0.")),Qe("NWC"===a,(()=>`Error in conv1d: got dataFormat of ${a} but only NWC is currently supported.`));const p=Cu(u,[1,u.shape[0],u.shape[1],u.shape[2]]),h=Cu(l,[l.shape[0],1,l.shape[1],l.shape[2]]),d=el(h,p,[1,n],r,"NHWC",[1,s],o);return Cu(d,c?[d.shape[2],d.shape[3]]:[d.shape[0],d.shape[2],d.shape[3]])}}),nl=lo({conv2DBackpropInput_:function(e,t,n,r,a,s="NHWC",o){Qe(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let i=e,u=t,l=!1;3===t.rank&&(l=!0,u=Cu(t,[1,t.shape[0],t.shape[1],t.shape[2]]),i=[1,e[0],e[1],e[2]]),Qe(4===i.length,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`)),Qe(4===u.rank,(()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${u.rank}`)),Qe(4===n.rank,(()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`));const c="NHWC"===s?i[3]:i[1],p="NHWC"===s?u.shape[3]:u.shape[1];Qe(c===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${n.shape[2]}.`)),Qe(p===n.shape[3],(()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[3]}.`)),Nu("conv2dDerInput",a,o);const h={dy:u,filter:n},d={strides:r,pad:a,dataFormat:s,dimRoundingMode:o,inputShape:i},f=ts.runKernel(Kt,h,d);return l?Cu(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),rl=lo({conv2dTranspose_:function(e,t,n,r,a,s){const o=oo(e,"x","conv2dTranspose"),i=oo(t,"filter","conv2dTranspose");return nl(n,o,i,r,a,"NHWC",s)}}),al=lo({conv3d_:function(e,t,n,r,a="NDHWC",s=[1,1,1]){const o=oo(e,"x","conv3d"),i=oo(t,"filter","conv3d");let u=o,l=!1;4===o.rank&&(l=!0,u=Cu(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),Qe(5===u.rank,(()=>`Error in conv3d: input must be rank 5, but got rank ${u.rank}.`)),Qe(5===i.rank,(()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`)),Qe(u.shape[4]===i.shape[3],(()=>`Error in conv3d: depth of input (${u.shape[4]}) must match input depth for filter ${i.shape[3]}.`)),Qe(Iu(n,s),(()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`)),Qe("NDHWC"===a,(()=>`Error in conv3d: got dataFormat of ${a} but only NDHWC is currently supported.`)),Qe(Su(s),(()=>"Error in conv3D: Dilated rates should be larger than 0.")),Qe(Su(n),(()=>"Error in conv3D: Strides should be larger than 0."));const c={x:u,filter:i},p={strides:n,pad:r,dataFormat:a,dilations:s},h=ts.runKernel("Conv3D",c,p);return l?Cu(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}}),sl=lo({conv3DBackpropInput_:function(e,t,n,r,a){Qe(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let s=e,o=t,i=!1;4===t.rank&&(i=!0,o=Cu(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),s=[1,e[0],e[1],e[2],e[3]]);const u=s[4],l=o.shape[4];Qe(5===s.length,(()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`)),Qe(5===o.rank,(()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`)),Qe(5===n.rank,(()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`)),Qe(u===n.shape[3],(()=>`Error in conv3dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[3]}.`)),Qe(l===n.shape[4],(()=>`Error in conv3dDerInput: depth of output (${l}) must match output depth for filter ${n.shape[4]}.`));const c={dy:o,filter:n},p={pad:a,strides:r,inputShape:s},h=ts.runKernel("Conv3DBackpropInputV2",c,p);return i?Cu(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}}),ol=lo({conv3dTranspose_:function(e,t,n,r,a){const s=oo(e,"x","conv3dTranspose"),o=oo(t,"filter","conv3dTranspose");return sl(n,s,o,r,a)}}),il=lo({cos_:function(e){const t={x:oo(e,"x","cos","float32")};return ts.runKernel("Cos",t)}}),ul=lo({cosh_:function(e){const t={x:oo(e,"x","cosh","float32")};return ts.runKernel(qt,t)}}),ll=lo({cumprod_:function(e,t=0,n=!1,r=!1){const a={x:oo(e,"x","cumprod")},s={axis:t,exclusive:n,reverse:r};return ts.runKernel(Xt,a,s)}}),cl=lo({cumsum_:function(e,t=0,n=!1,r=!1){const a={x:oo(e,"x","cumsum")},s={axis:t,exclusive:n,reverse:r};return ts.runKernel(Yt,a,s)}}),pl=lo({denseBincount_:function(e,t,n,r=!1){const a=oo(e,"x","denseBincount"),s=oo(t,"weights","denseBincount");Qe("int32"===a.dtype,(()=>`Error in denseBincount: input dtype must be int32, but got ${a.dtype}`)),Qe(a.rank<=2,(()=>`Error in denseBincount: input must be at most rank 2, but got rank ${a.rank}.`)),Qe(n>=0,(()=>`size must be non-negative, but got ${n}.`)),Qe(s.size===a.size||0===s.size,(()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${a.shape}, weights shape: ${s.shape}.`));const o={x:a,weights:s},i={size:n,binaryOutput:r};return ts.runKernel("DenseBincount",o,i)}}),hl=lo({depthToSpace_:function(e,t,n="NHWC"){const r=oo(e,"x","depthToSpace","float32"),a="NHWC"===n?r.shape[1]:r.shape[2],s="NHWC"===n?r.shape[2]:r.shape[3],o="NHWC"===n?r.shape[3]:r.shape[1];Qe(t>1,(()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`)),Qe(a*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${a} and ${t} for depthToSpace with input shape\n ${r.shape}`)),Qe(s*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${s} and ${t} for depthToSpace with input shape\n ${r.shape}`)),Qe(o%(t*t)==0,(()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${r.shape}`));const i={x:r},u={blockSize:t,dataFormat:n};return ts.runKernel(Jt,i,u)}}),dl=lo({depthwiseConv2d_:function(e,t,n,r,a="NHWC",s=[1,1],o){const i=oo(e,"x","depthwiseConv2d","float32"),u=oo(t,"filter","depthwiseConv2d","float32");let l=i,c=!1;3===i.rank&&(c=!0,l=Cu(i,[1,i.shape[0],i.shape[1],i.shape[2]])),Qe(4===l.rank,(()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${l.rank}.`)),Qe(4===u.rank,(()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${u.rank}.`));const p="NHWC"===a?l.shape[3]:l.shape[1];Qe(p===u.shape[2],(()=>`Error in depthwiseConv2d: number of input channels (${p}) must match the inChannels dimension in filter ${u.shape[2]}.`)),Nu("depthwiseConv2d",r,o);const h={x:l,filter:u},d={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o},f=ts.runKernel(Zt,h,d);return c?Cu(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),fl=lo({diag_:function(e){const t={x:oo(e,"x","diag")};return ts.runKernel("Diag",t)}}),ml=lo({dilation2d_:function(e,t,n,r,a=[1,1],s="NHWC"){const o=oo(e,"x","dilation2d"),i=oo(t,"filter","dilation2d");Qe(3===o.rank||4===o.rank,(()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`)),Qe(3===i.rank,(()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`)),Qe("NHWC"===s,(()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`));let u=o,l=!1;3===o.rank&&(u=Cu(o,[1,o.shape[0],o.shape[1],o.shape[2]]),l=!0),Qe(u.shape[3]===i.shape[2],(()=>`Error in dilation2d: input and filter must have the same depth: ${u.shape[3]} vs ${i.shape[2]}`));const c={x:u,filter:i},p={strides:n,pad:r,dilations:a},h=ts.runKernel("Dilation2D",c,p);return l?Cu(h,[h.shape[1],h.shape[2],h.shape[3]]):h}}),gl=lo({equal_:function(e,t){let n=oo(e,"a","equal","string_or_numeric"),r=oo(t,"b","equal","string_or_numeric");[n,r]=qa(n,r),Ci(n.shape,r.shape);const a={a:n,b:r};return ts.runKernel(nn,a)}}),yl=lo({where_:function(e,t,n){const r=oo(t,"a","where"),a=oo(n,"b","where"),s=oo(e,"condition","where","bool"),o=Ci(Ci(s.shape,r.shape),a.shape),i={condition:Gu(s,o),t:Gu(r,o),e:Gu(a,o)};return ts.runKernel(Jn,i)}}),bl=lo({zerosLike_:function(e){const t={x:oo(e,"x","zerosLike")};return ts.runKernel(wr,t)}}),_l=lo({divNoNan_:function(e,t){let n=oo(e,"a","div"),r=oo(t,"b","div");[n,r]=qa(n,r);const a=tu(n,r),s=bl(a),o=gl(r,s);return yl(o,s,a)}}),xl=lo({dot_:function(e,t){const n=oo(e,"t1","dot"),r=oo(t,"t2","dot");Qe(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),(()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${r.rank}.`));const a=1===n.rank?n.size:n.shape[1],s=1===r.rank?r.size:r.shape[0];if(Qe(a===s,(()=>`Error in dot: inner dimensions of inputs must match, but got ${a} and ${s}.`)),1===n.rank&&1===r.rank){const e=Cu(n,[1,-1]),t=Cu(r,[-1,1]),a=mi(e,t);return Cu(a,[])}if(1===n.rank&&2===r.rank){const e=Cu(n,[1,-1]),t=Cu(r,[r.shape[0],r.shape[1]]),a=mi(e,t);return Cu(a,[a.size])}if(2===n.rank&&1===r.rank){const e=Cu(r,[-1,1]),t=mi(n,e);return Cu(t,[t.size])}{const e=Cu(r,[r.shape[0],r.shape[1]]);return mi(n,e)}}}),vl=lo({einsum_:function(e,...t){const n=t.map(((e,t)=>oo(e,`tensors${t}`,"einsum"))),r={equation:e};return ts.runKernel("Einsum",n,r)}}),wl=lo({elu_:function(e){const t={x:oo(e,"x","elu","float32")};return ts.runKernel(tn,t)}}),Tl=lo({erf_:function(e){let t=oo(e,"x","erf");Qe("int32"===t.dtype||"float32"===t.dtype,(()=>"Input dtype must be `int32` or `float32`.")),"int32"===t.dtype&&(t=fi(t,"float32"));const n={x:t};return ts.runKernel("Erf",n)}});function kl(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function Il(e,t,n){const r=e.length+t.length,a=[];let s=0,o=0;for(let i=0;i<r;i++)-1===n.indexOf(i)?a.push(e[s++]):a.push(t[o++]);return a}function Sl(e,t){const n=[],r=e.length;for(let a=0;a<r;a++)-1===t.indexOf(a)&&n.push(e[a]);return[n,t.map((t=>e[t]))]}function El(e,t){return Il(e,t.map((e=>1)),t)}function Nl(e,t,n){Qe(kl(t,n),(()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`))}function Cl(e,t){if(kl(e,t))return null;const n=[];for(let r=0;r<t;++r)-1===e.indexOf(r)&&n.push(r);return e.forEach((e=>n.push(e))),n}function Al(e){return e.map(((e,t)=>[t,e])).sort(((e,t)=>e[1]-t[1])).map((e=>e[0]))}function Rl(e,t){const n=[];for(let r=t-e;r<t;++r)n.push(r);return n}const $l=lo({max_:function(e,t=null,n=!1){const r={x:oo(e,"x","max")},a={reductionIndices:t,keepDims:n};return ts.runKernel(Tn,r,a)}}),Ml=lo({min_:function(e,t=null,n=!1){const r={x:oo(e,"x","min")},a={axis:t,keepDims:n};return ts.runKernel(En,r,a)}}),Fl=lo({pow_:function(e,t){let n=oo(e,"base","pow"),r=oo(t,"exp","pow");[n,r]=qa(n,r);const a={a:n,b:r};return ts.runKernel("Pow",a)}});function Ol(e,t){if((Sa(e)&&"string"!==t||Array.isArray(e))&&"complex64"!==t)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===t&&Sa(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return po(e,[],[],t)}const Dl=lo({sqrt_:function(e){const t={x:oo(e,"x","sqrt","float32")};return ts.runKernel(tr,t)}}),Ll=lo({square_:function(e){const t=oo(e,"x","square");return ts.runKernel("Square",{x:t},{})}}),Pl=lo({sum_:function(e,t=null,n=!1){let r=oo(e,"x","sum");"bool"===r.dtype&&(r=fi(r,"int32"));const a={x:r},s={axis:t,keepDims:n};return ts.runKernel(nr,a,s)}});function Bl(e,t,n=null){if(0===e.rank)return ru(e);if(1!==e.rank&&null===n)return Bl(Cu(e,[-1]),t,n);if(1===e.rank||"number"==typeof n||Array.isArray(n)&&1===n.length){if(1===t)return Pl(ru(e),n);if(t===1/0)return $l(ru(e),n);if(t===-1/0)return Ml(ru(e),n);if("euclidean"===t||2===t)return Dl(Pl(Fl(ru(e),Ol(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&2===n.length){if(1===t)return $l(Pl(ru(e),n[0]),n[1]-1);if(t===1/0)return $l(Pl(ru(e),n[1]),n[0]);if(t===-1/0)return Ml(Pl(ru(e),n[1]),n[0]);if("fro"===t||"euclidean"===t)return Dl(Pl(Ll(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const Ul=lo({norm_:function(e,t="euclidean",n=null,r=!1){const a=Bl(e=oo(e,"x","norm"),t,n);let s=a.shape;if(r){const t=it(n,e.shape);s=El(a.shape,t)}return Cu(a,s)}}),zl=lo({euclideanNorm_:function(e,t=null,n=!1){return Ul(e,"euclidean",t,n)}}),Vl=lo({exp_:function(e){const t={x:oo(e,"x","exp")};return ts.runKernel(rn,t)}}),Wl=lo({expandDims_:function(e,t=0){const n=oo(e,"x","expandDims","string_or_numeric");Qe(t<=n.rank,(()=>"Axis must be <= rank of the tensor"));const r={input:n},a={dim:t};return ts.runKernel(an,r,a)}}),Hl=lo({expm1_:function(e){const t={x:oo(e,"x","expm1")};return ts.runKernel("Expm1",t)}}),Gl=lo({tile_:function(e,t){const n=oo(e,"x","tile","string_or_numeric");Qe(n.rank===t.length,(()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`));const r={x:n},a={reps:t};return ts.runKernel(yr,r,a)}}),jl=lo({eye_:function(e,t,n,r="float32"){null==t&&(t=e);const a=ju([e,t],r),s=e<=t?e:t;for(let e=0;e<s;++e)a.set(1,e,e);const o=Cu(a.toTensor(),[e,t]);if(null==n)return o;if(1===n.length)return Gl(Wl(o,0),[n[0],1,1]);if(2===n.length)return Gl(Wl(Wl(o,0),0),[n[0],n[1],1,1]);if(3===n.length)return Gl(Wl(Wl(Wl(o,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${n.length}D.`)}}),Kl=lo({floor_:function(e){const t={x:oo(e,"x","floor","float32")};return ts.runKernel(un,t)}}),ql=lo({gather_:function(e,t,n=0,r=0){const a={x:oo(e,"x","gather"),indices:oo(t,"indices","gather","int32")},s={axis:n,batchDims:r};return ts.runKernel(pn,a,s)}}),Xl=lo({greater_:function(e,t){let n=oo(e,"a","greater","string_or_numeric"),r=oo(t,"b","greater","string_or_numeric");[n,r]=qa(n,r),Ci(n.shape,r.shape);const a={a:n,b:r};return ts.runKernel(dn,a)}}),Yl=lo({greaterEqual_:function(e,t){let n=oo(e,"a","greaterEqual","string_or_numeric"),r=oo(t,"b","greaterEqual","string_or_numeric");[n,r]=qa(n,r),Ci(n.shape,r.shape);const a={a:n,b:r};return ts.runKernel(fn,a)}}),Ql=lo({isFinite_:function(e){const t={x:oo(e,"x","isFinite")};return ts.runKernel("IsFinite",t)}}),Jl=lo({isInf_:function(e){const t={x:oo(e,"x","isInf")};return ts.runKernel("IsInf",t)}}),Zl=lo({isNaN_:function(e){const t={x:oo(e,"x","isNaN")};return ts.runKernel(gn,t)}}),ec=lo({leakyRelu_:function(e,t=.2){const n={x:oo(e,"x","leakyRelu")},r={alpha:t};return ts.runKernel(yn,n,r)}}),tc=lo({less_:function(e,t){let n=oo(e,"a","less","string_or_numeric"),r=oo(t,"b","less","string_or_numeric");[n,r]=qa(n,r),Ci(n.shape,r.shape);const a={a:n,b:r};return ts.runKernel(bn,a)}}),nc=lo({lessEqual_:function(e,t){let n=oo(e,"a","lessEqual","string_or_numeric"),r=oo(t,"b","lessEqual","string_or_numeric");[n,r]=qa(n,r),Ci(n.shape,r.shape);const a={a:n,b:r};return ts.runKernel(_n,a)}}),rc=lo({localResponseNormalization_:function(e,t=5,n=1,r=1,a=.5){const s=oo(e,"x","localResponseNormalization");Qe(4===s.rank||3===s.rank,(()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank ${s.rank}.`)),Qe(nt(t),(()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`));let o=s,i=!1;3===s.rank&&(i=!0,o=Cu(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const u={x:o},l={depthRadius:t,bias:n,alpha:r,beta:a},c=ts.runKernel("LRN",u,l);return i?Cu(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),ac=lo({log_:function(e){const t={x:oo(e,"x","log","float32")};return ts.runKernel("Log",t)}}),sc=lo({log1p_:function(e){const t={x:oo(e,"x","log1p")};return ts.runKernel("Log1p",t)}});function oc(e){return ts.customGrad(e)}const ic=lo({softplus_:function(e){const t={x:oo(e,"x","softplus")};return ts.runKernel("Softplus",t)}}),uc=lo({logSigmoid_:function(e){const t=oo(e,"x","logSigmoid"),n=oc((e=>({value:ki(ic(ki(e))),gradFunc:t=>nu(t,Fu(ki(e)))})));return n(t)}}),lc=lo({sub_:function(e,t){let n=oo(e,"a","sub"),r=oo(t,"b","sub");[n,r]=qa(n,r);const a={a:n,b:r};return ts.runKernel(mr,a)}}),cc=lo({logSoftmax_:function(e,t=-1){const n=oo(e,"logits","logSoftmax");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);const r=oc(((e,n)=>{const r=$l(e,t,!0),a=lc(e,r),s=lc(fi(a,"float32"),ac(Pl(Vl(a),t,!0)));return n([s]),{value:s,gradFunc:(e,n)=>{const[r]=n,a=Vl(r);return lc(e,nu(Pl(e,t,!0),a))}}}));return r(n)}}),pc=lo({logSumExp_:function(e,t=null,n=!1){const r=oo(e,"x","logSumExp"),a=it(t,r.shape),s=$l(r,a,!0),o=lc(r,s),i=Vl(o),u=Pl(i,a),l=ac(u),c=Zi(Cu(s,l.shape),l);if(n){const e=El(c.shape,a);return Cu(c,e)}return c}}),hc=lo({logicalAnd_:function(e,t){const n=oo(e,"a","logicalAnd","bool"),r=oo(t,"b","logicalAnd","bool");Ci(n.shape,r.shape);const a={a:n,b:r};return ts.runKernel(xn,a)}}),dc=lo({logicalNot_:function(e){const t={x:oo(e,"x","logicalNot","bool")};return ts.runKernel(vn,t)}}),fc=lo({logicalOr_:function(e,t){const n=oo(e,"a","logicalOr","bool"),r=oo(t,"b","logicalOr","bool");Ci(n.shape,r.shape);const a={a:n,b:r};return ts.runKernel(wn,a)}}),mc=lo({logicalXor_:function(e,t){const n=oo(e,"a","logicalXor","bool"),r=oo(t,"b","logicalXor","bool");return Ci(n.shape,r.shape),hc(fc(e,t),dc(hc(e,t)))}}),gc=2147483648,yc=lo({searchSorted_:function(e,t,n="left"){const r=oo(e,"sortedSequence","searchSorted"),a=oo(t,"values","searchSorted"),s=r.shape[r.shape.length-1],o=a.shape[a.shape.length-1],i=Cu(r,[-1,s]),u=Cu(a,[-1,o]);if(i.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(i.shape[0]!==u.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(et(u.shape)>=gc)throw new Error("values tensor size must less than 2147483648");if(i.shape[1]>=gc)throw new Error(`trailing dim_size must less than 2147483648 for int32 output type, was ${i.shape[1]}`);const l={sortedSequence:i,values:u},c={side:n};return ts.runKernel("SearchSorted",l,c)}}),bc=lo({maxPool_:function(e,t,n,r,a){const s=oo(e,"x","maxPool");let o=s,i=!1;3===s.rank&&(i=!0,o=Cu(s,[1,s.shape[0],s.shape[1],s.shape[2]])),Qe(4===o.rank,(()=>`Error in maxPool: input must be rank 4 but got rank ${o.rank}.`)),Qe(Iu(n,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`)),Nu("maxPool",r,a);const u={x:o},l={filterSize:t,strides:n,pad:r,dimRoundingMode:a},c=ts.runKernel(In,u,l);return i?Cu(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),_c=lo({maxPool3d_:function(e,t=[1,1,1],n,r,a,s="NDHWC"){const o=oo(e,"x","maxPool3d");let i=o,u=!1;4===o.rank&&(u=!0,i=Cu(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),Qe(5===i.rank,(()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`)),Qe("NDHWC"===s,(()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`)),Nu("maxPool3d",r,a);const l={x:i},c={filterSize:t,strides:n,pad:r,dimRoundingMode:a,dataFormat:s},p=ts.runKernel("MaxPool3D",l,c);return u?Cu(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}}),xc=lo({maxPoolWithArgmax_:function(e,t,n,r,a=!1){const s={x:oo(e,"x","maxPoolWithArgmax")},o={filterSize:t,strides:n,pad:r,includeBatchInIndex:a},i=ts.runKernel("MaxPoolWithArgmax",s,o);return{result:i[0],indexes:i[1]}}}),vc=lo({maximum_:function(e,t){let n=oo(e,"a","maximum"),r=oo(t,"b","maximum");[n,r]=qa(n,r),"bool"===n.dtype&&(n=fi(n,"int32"),r=fi(r,"int32")),Ci(n.shape,r.shape);const a={a:n,b:r};return ts.runKernel(kn,a)}}),wc=lo({mean_:function(e,t=null,n=!1){const r={x:oo(e,"x","mean")},a={axis:t,keepDims:n};return ts.runKernel(Sn,r,a)}});function Tc(e,t="float32"){if(wt(e),"complex64"===t){const t=Tc(e,"float32"),n=Tc(e,"float32");return co(t,n)}const n=vt(et(e),t);return ts.makeTensor(n,e,t)}function kc(e,t="float32"){if(wt(e),"complex64"===t){const t=kc(e,"float32"),n=Tc(e,"float32");return co(t,n)}const n=xt(et(e),t);return ts.makeTensor(n,e,t)}const Ic=lo({minimum_:function(e,t){let n=oo(e,"a","minimum"),r=oo(t,"b","minimum");[n,r]=qa(n,r),"bool"===n.dtype&&(n=fi(n,"int32"),r=fi(r,"int32")),Ci(n.shape,r.shape);const a={a:n,b:r};return ts.runKernel(Nn,a)}}),Sc=lo({mirrorPad_:function(e,t,n){Qe("reflect"===n||"symmetric"===n,(()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`));const r=oo(e,"x","mirrorPad");if(0===r.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");Qe(t.length===r.rank,(()=>`Padding doesn't match input. Must be ${r.rank}. Got ${t.length}.`));const a="reflect"===n?1:0;for(let e=0;e<r.rank;e++)Qe(2===t[e].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),Qe(t[e][0]>=0&&t[e][0]<=r.shape[e]-a&&t[e][1]>=0&&t[e][1]<=r.shape[e]-a,(()=>`Padding in dimension ${e} cannot be greater than or equal to ${r.shape[e]-a} or less than 0 for input of shape ${r.shape}`));const s={paddings:t,mode:n},o={x:r};return ts.runKernel(Cn,o,s)}}),Ec=lo({mod_:function(e,t){let n=oo(e,"a","mod"),r=oo(t,"b","mod");[n,r]=qa(n,r);const a={a:n,b:r};return ts.runKernel("Mod",a)}}),Nc=lo({moments_:function(e,t=null,n=!1){const r=it(t,(e=oo(e,"x","moments")).shape),a=wc(e,r,n);let s=a.shape;n||(s=El(a.shape,r));const o=Ll(lc(fi(e,"float32"),Cu(a,s)));return{mean:a,variance:wc(o,r,n)}}}),Cc=lo({multiRNNCell_:function(e,t,n,r){const a=oo(t,"data","multiRNNCell"),s=io(n,"c","multiRNNCell"),o=io(r,"h","multiRNNCell");let i=a;const u=[];for(let t=0;t<e.length;t++){const n=e[t](i,s[t],o[t]);u.push(n[0]),u.push(n[1]),i=n[1]}const l=[],c=[];for(let e=0;e<u.length;e+=2)l.push(u[e]),c.push(u[e+1]);return[l,c]}}),Ac=lo({multinomial_:function(e,t,n,r=!1){const a=oo(e,"logits","multinomial"),s=a.size,o=a.rank;if(s<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${s}.`);if(o>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${o}`);n=n||Math.random();const i={logits:1===o?Cu(a,[1,-1]):a},u={numSamples:t,seed:n,normalized:r},l=ts.runKernel("Multinomial",i,u);return 1===o?Cu(l,[l.size]):l}}),Rc=lo({notEqual_:function(e,t){let n=oo(e,"a","notEqual","string_or_numeric"),r=oo(t,"b","notEqual","string_or_numeric");[n,r]=qa(n,r),Ci(n.shape,r.shape);const a={a:n,b:r};return ts.runKernel(Rn,a)}}),$c=lo({onesLike_:function(e){const t={x:oo(e,"x","onesLike")};return ts.runKernel(On,t)}}),Mc=lo({outerProduct_:function(e,t){const n=oo(e,"v1","outerProduct"),r=oo(t,"v2","outerProduct");Qe(1===n.rank&&1===r.rank,(()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${r.rank}.`));const a=Cu(n,[-1,1]),s=Cu(r,[1,-1]);return mi(a,s)}}),Fc=lo({pad_:function(e,t,n=0){const r=oo(e,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const a={paddings:t,constantValue:n},s={x:r};return ts.runKernel(Pn,s,a)}}),Oc=lo({pad1d_:function(e,t,n=0){return Qe(2===t.length,(()=>"Invalid number of paddings. Must be length of 2.")),Fc(e,[t],n)}}),Dc=lo({pad2d_:function(e,t,n=0){return Qe(2===t.length&&2===t[0].length&&2===t[1].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),Fc(e,t,n)}}),Lc=lo({pad3d_:function(e,t,n=0){return Qe(3===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),Fc(e,t,n)}}),Pc=lo({pad4d_:function(e,t,n=0){return Qe(4===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length&&2===t[3].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),Fc(e,t,n)}}),Bc=lo({spaceToBatchND_:function(e,t,n){const r=oo(e,"x","spaceToBatchND");Qe(r.rank>=1+t.length,(()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`)),Qe(n.length===t.length,(()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`)),Qe(r.shape.reduce(((e,r,a)=>a>0&&a<=t.length?e&&(r+n[a-1][0]+n[a-1][1])%t[a-1]==0:e),!0),(()=>`input spatial dimensions ${r.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`));const a={x:r},s={blockShape:t,paddings:n};return ts.runKernel(rr,a,s)}}),Uc=lo({pool_:function(e,t,n,r,a,s,o){null==a&&(a=[1,1]),null==s&&(s=1),0===r&&(r="valid");const i=oo(e,"x","maxPool");let u=i,l=!1;3===i.rank&&(l=!0,u=Cu(i,[1,i.shape[0],i.shape[1],i.shape[2]])),Qe(Iu(s,a),(()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${a}'`));const c=gu(u.shape,t,s,a,r),p=[c.dilationHeight,c.dilationWidth];let h;h="same"===r?function(e,t){const n=e.map(((e,n)=>e+(e-1)*(t[n]-1))).map((e=>e-1)),r=n.map((e=>Math.floor(e/2))),a=n.map(((e,t)=>e-r[t]));return n.map(((e,t)=>[r[t],a[t]]))}([c.filterHeight,c.filterWidth],p):[[0,0],[0,0]];const d=1===p[0]&&1===p[1],[f,m]=function(e,t,n){const r=n.map((e=>e[0])),a=n.map((e=>e[1])),s=e.concat(r,a),o=t.map(((e,t)=>(e-s[t]%e)%e)),i=a.map(((e,t)=>e+o[t]));return[t.map(((e,t)=>[r[t],i[t]])),t.map(((e,t)=>[0,o[t]]))]}([c.inHeight,c.inWidth],p,h),g=d?r:"valid",y=d?u:Bc(u,p,f),b=("avg"===n?()=>Au(y,t,s,g,o):()=>bc(y,t,s,g,o))(),_=d?b:Pu(b,p,m);return l?Cu(_,[_.shape[1],_.shape[2],_.shape[3]]):_}}),zc=lo({prelu_:function(e,t){const n={x:oo(e,"x","prelu"),alpha:oo(t,"alpha","prelu")};return ts.runKernel(Bn,n)}});function Vc(e,t=!1){console.log(e.toString(t))}const Wc=lo({prod_:function(e,t=null,n=!1){let r=oo(e,"x","prod");"bool"===r.dtype&&(r=fi(r,"int32"));const a={x:r},s={axis:t,keepDims:n};return ts.runKernel(Un,a,s)}}),Hc=lo({raggedGather_:function(e,t,n,r){const a=e.map(((e,t)=>oo(e,`tensors${t}`,"raggedGather","int32"))),s={paramsNestedSplits:a,paramsDenseValues:oo(t,"paramsDenseValues","raggedGather"),indices:oo(n,"indices","raggedGather","int32")},o={outputRaggedRank:r},i=ts.runKernel("RaggedGather",s,o);return{outputNestedSplits:i.slice(0,i.length-1),outputDenseValues:i[i.length-1]}}}),Gc=lo({raggedRange_:function(e,t,n){const r=oo(e,"starts","raggedRange"),a={starts:r,limits:oo(t,"limits","raggedRange",r.dtype),deltas:oo(n,"deltas","raggedRange",r.dtype)},s=ts.runKernel("RaggedRange",a);return{rtNestedSplits:s[0],rtDenseValues:s[1]}}}),jc=lo({raggedTensorToTensor_:function(e,t,n,r,a){const s=oo(e,"shape","raggedTensorToTensor","int32"),o=oo(t,"values","raggedTensorToTensor"),i=oo(n,"defaultValue","raggedTensorToTensor",o.dtype),u=r.map(((e,t)=>oo(e,`tensors${t}`,"raggedTensorToTensor","int32"))),l={shape:s,values:o,defaultValue:i,rowPartitionTensors:u},c={rowPartitionTypes:a};return ts.runKernel("RaggedTensorToTensor",l,c)}}),Kc=lo({rand_:function(e,t,n){wt(e);const r=et(e);let a=null;if(null==n||"float32"===n)a=new Float32Array(r);else if("int32"===n)a=new Int32Array(r);else{if("bool"!==n)throw new Error(`Unknown data type ${n}`);a=new Uint8Array(r)}for(let e=0;e<r;e++)a[e]=t();return ts.makeTensor(a,e,n)}});var qc="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==n.g?n.g:"undefined"!=typeof self?self:{};function Xc(e){var t={exports:{}};return e(t,t.exports),t.exports}var Yc=Xc((function(e){!function(e,t,n){function r(e){var t=this,n=function(){var e=4022871197;return function(t){t=String(t);for(var n=0;n<t.length;n++){var r=.02519603282416938*(e+=t.charCodeAt(n));r-=e=r>>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)}}();t.next=function(){var e=2091639*t.s0+2.3283064365386963e-10*t.c;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=0|e)},t.c=1,t.s0=n(" "),t.s1=n(" "),t.s2=n(" "),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function a(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function s(e,t){var n=new r(e),s=t&&t.state,o=n.next;return o.int32=function(){return 4294967296*n.next()|0},o.double=function(){return o()+11102230246251565e-32*(2097152*o()|0)},o.quick=o,s&&("object"==typeof s&&a(s,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=s:this.alea=s}(0,e)})),Qc=Xc((function(e){!function(e,t,n){function r(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=0|n.charCodeAt(r),t.next()}function a(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function s(e,t){var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,s&&("object"==typeof s&&a(s,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=s:this.xor128=s}(0,e)})),Jc=Xc((function(e){!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=0|n.charCodeAt(r),r==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function a(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function s(e,t){var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,s&&("object"==typeof s&&a(s,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=s:this.xorwow=s}(0,e)})),Zc=Xc((function(e){!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.x,a=t.i;return e=r[a],n=(e^=e>>>7)^e<<24,n^=(e=r[a+1&7])^e>>>10,n^=(e=r[a+3&7])^e>>>3,n^=(e=r[a+4&7])^e<<7,e=r[a+7&7],n^=(e^=e<<13)^e<<9,r[a]=n,t.i=a+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,n=0;n<t.length;++n)r[7&n]=r[7&n]<<15^t.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],e.x=r,e.i=0,n=256;n>0;--n)e.next()}(t,e)}function a(e,t){return t.x=e.x.slice(),t.i=e.i,t}function s(e,t){null==e&&(e=+new Date);var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,s&&(s.x&&a(s,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=s:this.xorshift7=s}(0,e)})),ep=Xc((function(e){!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.w,a=t.X,s=t.i;return t.w=r=r+1640531527|0,n=a[s+34&127],e=a[s=s+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=a[s]=n^e,t.i=s,n+(r^r>>>16)|0},function(e,t){var n,r,a,s,o,i=[],u=128;for(t===(0|t)?(r=t,t=null):(t+="\0",r=0,u=Math.max(u,t.length)),a=0,s=-32;s<u;++s)t&&(r^=t.charCodeAt((s+32)%t.length)),0===s&&(o=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,s>=0&&(o=o+1640531527|0,a=0==(n=i[127&s]^=r+o)?a+1:0);for(a>=128&&(i[127&(t&&t.length||0)]=-1),a=127,s=512;s>0;--s)r=i[a+34&127],n=i[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,i[a]=r^n;e.w=o,e.X=i,e.i=a}(t,e)}function a(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function s(e,t){null==e&&(e=+new Date);var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,s&&(s.X&&a(s,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=s:this.xor4096=s}(0,e)})),tp=Xc((function(e){!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,a=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^a,a=a-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^a,t.a=a-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r<n.length+20;r++)t.b^=0|n.charCodeAt(r),t.next()}function a(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function s(e,t){var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,s&&("object"==typeof s&&a(s,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=s:this.tychei=s}(0,e)})),np=function(e){if(e.__esModule)return e;var t=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(e).forEach((function(n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})})),t}(Object.freeze({__proto__:null,default:{}})),rp=Xc((function(e){!function(t,n,r){var a,s=256,o="random",i=r.pow(s,6),u=r.pow(2,52),l=2*u,c=255;function p(e,c,p){var y=[],b=m(f((c=1==c?{entropy:!0}:c||{}).entropy?[e,g(n)]:null==e?function(){try{var e;return a&&(e=a.randomBytes)?e=e(s):(e=new Uint8Array(s),(t.crypto||t.msCrypto).getRandomValues(e)),g(e)}catch(e){var r=t.navigator,o=r&&r.plugins;return[+new Date,t,o,t.screen,g(n)]}}():e,3),y),_=new h(y),x=function(){for(var e=_.g(6),t=i,n=0;e<u;)e=(e+n)*s,t*=s,n=_.g(1);for(;e>=l;)e/=2,t/=2,n>>>=1;return(e+n)/t};return x.int32=function(){return 0|_.g(4)},x.quick=function(){return _.g(4)/4294967296},x.double=x,m(g(_.S),n),(c.pass||p||function(e,t,n,a){return a&&(a.S&&d(a,_),e.state=function(){return d(_,{})}),n?(r[o]=e,t):e})(x,b,"global"in c?c.global:this==r,c.state)}function h(e){var t,n=e.length,r=this,a=0,o=r.i=r.j=0,i=r.S=[];for(n||(e=[n++]);a<s;)i[a]=a++;for(a=0;a<s;a++)i[a]=i[o=c&o+e[a%n]+(t=i[a])],i[o]=t;(r.g=function(e){for(var t,n=0,a=r.i,o=r.j,i=r.S;e--;)t=i[a=c&a+1],n=n*s+i[c&(i[a]=i[o=c&o+t])+(i[o]=t)];return r.i=a,r.j=o,n})(s)}function d(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function f(e,t){var n,r=[],a=typeof e;if(t&&"object"==a)for(n in e)try{r.push(f(e[n],t-1))}catch(e){}return r.length?r:"string"==a?e:e+"\0"}function m(e,t){for(var n,r=e+"",a=0;a<r.length;)t[c&a]=c&(n^=19*t[c&a])+r.charCodeAt(a++);return g(t)}function g(e){return String.fromCharCode.apply(0,e)}if(m(r.random(),n),e.exports){e.exports=p;try{a=np}catch(e){}}else r["seed"+o]=p}("undefined"!=typeof self?self:qc,[],Math)}));rp.alea=Yc,rp.xor128=Qc,rp.xorwow=Jc,rp.xorshift7=Zc,rp.xor4096=ep,rp.tychei=tp;var ap=rp;class sp{constructor(e,t,n,r,a){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);const s=a||Math.random();this.random=ap.alea(s.toString())}nextValue(){if(!isNaN(this.nextVal)){const e=this.nextVal;return this.nextVal=NaN,e}let e,t,n=!1;for(;!n;){let r,a,s;do{r=2*this.random()-1,a=2*this.random()-1,s=r*r+a*a}while(s>=1||0===s);const o=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*r*o,t=this.mean+this.stdDev*a*o,this.truncated&&!this.isValidTruncated(e)||(n=!0)}return this.truncated&&!this.isValidTruncated(t)||(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class op{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const a=r||Math.random();this.randu=ap.alea(a.toString()),this.randn=new sp(0,1,n,!1,this.randu()),this.d=e<1?e+2/3:e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,r,a,s;for(;;){do{r=this.randn.nextValue(),s=1+this.c*r}while(s<=0);if(s*=s*s,e=r*r,t=1-.331*e*e,n=.5*e+this.d*(1-s+Math.log(s)),a=this.randu(),a<t||Math.log(a)<n)break}return s=1/this.beta*this.d*s,this.alpha<1&&(s*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(s)}convertValue(e){return"float32"===this.dtype?e:Math.round(e)}}class ip{constructor(e=0,t=1,n,r){if(this.canReturnFloat=()=>null==this.dtype||"float32"===this.dtype,this.min=e,this.range=t-e,this.dtype=n,null==r&&(r=Math.random()),"number"==typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=ap.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const up=lo({randomGamma_:function(e,t,n=1,r="float32",a){if(wt(e),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error(`Unsupported data type ${r}`);const s=new op(t,n,r,a),o=ju(e,r);for(let e=0;e<o.values.length;e++)o.values[e]=s.nextValue();return o.toTensor()}}),lp=lo({randomNormal_:function(e,t=0,n=1,r,a){if(wt(e),null!=r&&"bool"===r)throw new Error(`Unsupported data type ${r}`);const s=new sp(t,n,r,!1,a),o=ju(e,r);for(let e=0;e<o.values.length;e++)o.values[e]=s.nextValue();return o.toTensor()}}),cp=lo({randomStandardNormal_:function(e,t,n){if(null!=t&&"bool"===t)throw new Error(`Unsupported data type ${t}`);return lp(e,0,1,t,n)}}),pp=lo({randomUniform_:function(e,t=0,n=1,r="float32",a){wt(e);const s=ju(e,r),o=new ip(t,n,null,a);for(let e=0;e<s.values.length;e++)s.values[e]=o.nextValue();return s.toTensor()}});function hp(e,t,n=1,r="float32"){if(0===n)throw new Error("Cannot have a step of zero");const a={start:e,stop:t,step:n,dtype:r};return ts.runKernel(zn,{},a)}const dp=lo({reciprocal_:function(e){const t={x:oo(e,"x","reciprocal")};return ts.runKernel(Vn,t)}}),fp=lo({relu_:function(e){const t={x:oo(e,"x","relu")};return ts.runKernel(Wn,t)}}),mp=lo({relu6_:function(e){const t={x:oo(e,"x","relu6")};return ts.runKernel(Kn,t)}}),gp=lo({reverse_:function(e,t){const n={x:oo(e,"x","reverse")},r={dims:t};return ts.runKernel(qn,n,r)}}),yp=lo({reverse1d_:function(e){const t=oo(e,"x","reverse");return Qe(1===t.rank,(()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`)),gp(t,0)}}),bp=lo({reverse2d_:function(e,t){const n=oo(e,"x","reverse");return Qe(2===n.rank,(()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`)),gp(n,t)}}),_p=lo({reverse3d_:function(e,t){const n=oo(e,"x","reverse");return Qe(3===n.rank,(()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`)),gp(n,t)}}),xp=lo({reverse4d_:function(e,t){const n=oo(e,"x","reverse");return Qe(4===n.rank,(()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`)),gp(n,t)}}),vp=lo({round_:function(e){const t={x:oo(e,"x","round")};return ts.runKernel(Xn,t)}}),wp=lo({rsqrt_:function(e){const t={x:oo(e,"x","rsqrt","float32")};return ts.runKernel(Yn,t)}}),Tp=lo({selu_:function(e){const t={x:oo(e,"x","selu")};return ts.runKernel("Selu",t)}}),kp=lo({separableConv2d_:function(e,t,n,r,a,s=[1,1],o="NHWC"){const i=oo(e,"x","separableConv2d"),u=oo(t,"depthwiseFilter","separableConv2d"),l=oo(n,"pointwiseFilter","separableConv2d");let c=i,p=!1;if(3===i.rank&&(p=!0,c=Cu(i,[1,i.shape[0],i.shape[1],i.shape[2]])),"NCHW"===o)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");Qe(4===c.rank,(()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`)),Qe(4===u.rank,(()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${u.rank}.`)),Qe(4===l.rank,(()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${u.rank}.`)),Qe(1===l.shape[0],(()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${l.shape[0]}.`)),Qe(1===l.shape[1],(()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${l.shape[1]}.`));const h=u.shape[2],d=u.shape[3];Qe(l.shape[2]===h*d,(()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${h*d}, but got ${l.shape[2]}.`));const f=dl(c,u,r,a,o,s),m=el(f,l,1,"valid",o);return p?Cu(m,[m.shape[1],m.shape[2],m.shape[3]]):m}}),Ip=lo({sign_:function(e){const t={x:oo(e,"x","sign")};return ts.runKernel("Sign",t)}}),Sp=lo({sin_:function(e){const t={x:oo(e,"x","sin","float32")};return ts.runKernel("Sin",t)}}),Ep=lo({sinh_:function(e){const t={x:oo(e,"x","sinh")};return ts.runKernel("Sinh",t)}}),Np=lo({slice1d_:function(e,t,n){const r=oo(e,"x","slice1d");return Qe(1===r.rank,(()=>`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`)),Ou(r,[t],[n])}}),Cp=lo({slice2d_:function(e,t,n){const r=oo(e,"x","slice2d");return Qe(2===r.rank,(()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`)),Ou(r,t,n)}}),Ap=lo({slice3d_:function(e,t,n){const r=oo(e,"x","slice3d");return Qe(3===r.rank,(()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`)),Ou(r,t,n)}}),Rp=lo({slice4d_:function(e,t,n){const r=oo(e,"x","slice4d");return Qe(4===r.rank,(()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`)),Ou(r,t,n)}}),$p=lo({softmax_:function(e,t=-1){const n=oo(e,"logits","softmax","float32");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);const r={logits:n},a={dim:t};return ts.runKernel(sr,r,a)}}),Mp=lo({fft_:function(e){Qe("complex64"===e.dtype,(()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`));const t={input:e};return ts.runKernel("FFT",t)}}),Fp=lo({ifft_:function(e){Qe("complex64"===e.dtype,(()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`));const t={input:e};return ts.runKernel("IFFT",t)}}),Op=lo({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let r;if(t<=2){const a=Cu(e,[n,t]);r=Fp(a)}else{const a=[n,2*(t-1)],s=Cu(Ii(e),[n,t]),o=Cu(Ti(e),[n,t]),i=gp(Ou(s,[0,1],[n,t-2]),1),u=nu(gp(Ou(o,[0,1],[n,t-2]),1),Ol(-1)),l=Mu([s,i],1),c=Mu([o,u],1),p=Cu(co(l,c),[a[0],a[1]]);r=Fp(p)}if(r=Ii(r),3===e.rank&&0!==e.shape[0]){const t=r,n=e.shape[0];r=Cu(r,[n,r.shape[0]/n,r.shape[1]]),t.dispose()}return r}}),Dp=lo({split_:function(e,t,n=0){const r={x:oo(e,"x","split")},a={numOrSizeSplits:t,axis:n};return ts.runKernel(ar,r,a)}}),Lp=lo({rfft_:function(e,t){Qe("float32"===e.dtype,(()=>`The dtype for rfft() must be real value but got ${e.dtype}`));let n=e.shape[e.shape.length-1];const r=e.size/n;let a;if(null!=t&&t<n){const r=e.shape.map((e=>0)),s=e.shape.map((e=>e));s[e.shape.length-1]=t,a=Ou(e,r,s),n=t}else if(null!=t&&t>n){const r=e.shape.map((e=>e));r[e.shape.length-1]=t-n,a=Mu([e,Tc(r)],e.shape.length-1),n=t}else a=e;const s=bl(a),o=Cu(co(a,s),[r,n]),i=Mp(o),u=Math.floor(n/2)+1,l=Ii(i),c=Ti(i),p=Dp(l,[u,n-u],l.shape.length-1),h=Dp(c,[u,n-u],c.shape.length-1),d=a.shape.slice();return d[a.shape.length-1]=u,Cu(co(p[0],h[0]),d)}}),Pp=lo({squaredDifference_:function(e,t){let n=oo(e,"a","squaredDifference"),r=oo(t,"b","squaredDifference");[n,r]=qa(n,r),Ci(n.shape,r.shape);const a={a:n,b:r};return ts.runKernel(cr,a,{})}}),Bp=lo({squeeze_:function(e,t){const n=oo(e,"x","squeeze","string_or_numeric");return Cu(n,ut(n.shape,t).newShape)}}),Up=lo({stack_:function(e,t=0){const n=io(e,"tensors","stack","string_or_numeric");Qe(n.length>=1,(()=>"Pass at least one tensor to tf.stack")),n.length>0&&Qe(t<=n[0].rank,(()=>"Axis must be <= rank of the tensor"));const r=n,a={axis:t};return ts.runKernel(Ln,r,a)}}),zp=lo({step_:function(e,t=0){const n={x:oo(e,"x","step")},r={alpha:t};return ts.runKernel(Tr,n,r)}}),Vp=lo({stridedSlice_:function(e,t,n,r,a=0,s=0,o=0,i=0,u=0){const l={x:oo(e,"x","stridedSlice","string_or_numeric")},c={begin:t,end:n,strides:r,beginMask:a,endMask:s,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:u};return ts.runKernel(pr,l,c)}}),Wp=lo({tan_:function(e){const t={x:oo(e,"x","tan","float32")};return ts.runKernel("Tan",t)}});function Hp(e,t){Ze(e);const n=ro(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return po(e,null,n,t)}function Gp(e,t,n){if(Ze(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const r=ro(e,n);if(2!==r.length&&1!==r.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return po(e,t,r,n)}const jp=lo({topk_:function(e,t=1,n=!0){const r=oo(e,"x","topk");if(0===r.rank)throw new Error("topk() expects the input to be of rank 1 or higher");const a=r.shape[r.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>a)throw new Error(`'k' passed to topk() must be <= the last dimension (${a}) but got ${t}`);const s={x:r},o={k:t,sorted:n},[i,u]=ts.runKernel(br,s,o);return{values:i,indices:u}}}),Kp=lo({truncatedNormal_:function(e,t=0,n=1,r,a){if(wt(e),null!=r&&"bool"===r)throw new Error("Unsupported data type $ { dtype }");const s=new sp(t,n,r,!0,a),o=ju(e,r);for(let e=0;e<o.values.length;e++)o.values[e]=s.nextValue();return o.toTensor()}}),qp=lo({unique_:function(e,t=0){const n=oo(e,"x","unique","string_or_numeric");Qe(n.rank>0,(()=>"The input tensor must be at least 1D"));const r={x:n},a={axis:t},[s,o]=ts.runKernel("Unique",r,a);return{values:s,indices:o}}}),Xp=lo({unsortedSegmentSum_:function(e,t,n){const r=oo(e,"x","unsortedSegmentSum"),a=oo(t,"segmentIds","unsortedSegmentSum","int32");Qe(nt(n),(()=>"numSegments must be of dtype int"));const s={x:r,segmentIds:a},o={numSegments:n};return ts.runKernel("UnsortedSegmentSum",s,o)}}),Yp=lo({unstack_:function(e,t=0){const n=oo(e,"x","unstack","string_or_numeric");Qe(t>=-n.shape.length&&t<n.shape.length,(()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`));const r={value:n},a={axis:t};return ts.runKernel(vr,r,a)}});function Qp(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const r=ju(e,"int32"),a=ju([n.length,e.length],"int32");for(let t=0;t<n.length;t++){const s=r.indexToLoc(n[t]),o=t*e.length;a.values.set(s,o)}return a.toTensor()}const Jp=async function(e){const t=oo(e,"condition","whereAsync","bool"),n=await t.data(),r=Qp(t.shape,n);return e!==t&&t.dispose(),r},Zp=lo({movingAverage_:function(e,t,n,r,a=!0){const s=oo(e,"v","movingAverage"),o=oo(t,"x","movingAverage"),i=oo(n,"decay","movingAverage");var u,l;l=o,Qe((u=s).dtype===l.dtype,(()=>`The dtypes of the first(${u.dtype}) and second(${l.dtype}) input must match`)),Qe(tt(s.shape,o.shape),(()=>"Shape mismatch in v and x"));const c=Ol(1),p=lc(c,i);let h=nu(lc(o,s),p);if(a){Qe(null!=r,(()=>"When using zeroDebias: true, step is required."));const e=oo(r,"step","movingAverage");h=tu(h,lc(c,Fl(i,e)))}return Zi(s,h)}}),eh=lo({scatterND_:function(e,t,n){wt(n);const r=oo(e,"indices","scatterND","int32"),a=oo(t,"updates","scatterND");Oi(a,r,n);const s={indices:r,updates:a},o={shape:n};return ts.runKernel(Qn,s,o)}}),th=lo({sparseToDense_:function(e,t,n,r=0){wt(n);const a=oo(e,"sparseIndices","sparseToDense","int32"),s=oo(t,"sparseValues","sparseToDense","string_or_numeric"),o=oo(r,"defaultValue","sparseToDense",s.dtype);!function(e,t,n,r){if("int32"!==e.dtype)throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);const a=e.rank>0?e.shape[0]:1,s=e.rank>1?e.shape[1]:1;if(n.length!==s)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${s}.`);const o=t.size;if(0!==t.rank&&(1!==t.rank||o!==a))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${a}]`);if(t.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(a,s,n,o);const i={sparseIndices:a,sparseValues:s,defaultValue:o},u={outputShape:n};return ts.runKernel("SparseToDense",i,u)}}),nh=lo({gatherND_:function(e,t){const n=oo(t,"indices","gatherND","int32"),r={params:oo(e,"x","gatherND","string_or_numeric"),indices:n};return ts.runKernel(hn,r)}}),rh=lo({dropout_:function(e,t,n,r){const a=oo(e,"x","dropout");if(Qe("float32"===a.dtype,(()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${a.dtype} tensor instead.`)),Qe(t>=0&&t<1,(()=>`rate must be a float in the range [0, 1), but got ${t}.`)),0===t)return e instanceof Ba?a.clone():a;const s=function(e,t){if(null==t)return e.shape.slice();if(tt(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let r=0;r<e.shape.length;r++)null==t[r]&&null!=e.shape[r]?n.push(e.shape[r]):n.push(t[r]);return n}return t}(a,n),o=1-t,i=tu(Kl(Zi(pp(s,0,1,"float32",r),o)),o);return nu(a,i)}});function ah(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function sh(e,t,n){const r=1-e%2,a=new Float32Array(e);for(let s=0;s<e;++s){const o=2*Math.PI*s/(e+r-1);a[s]=t-n*Math.cos(o)}return Hp(a,"float32")}const oh=lo({conv2DBackpropFilter_:function(e,t,n,r,a,s="NHWC",o){let i=e;3===e.rank&&(i=Cu(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u=t;3===u.rank&&(u=Cu(t,[1,t.shape[0],t.shape[1],t.shape[2]])),Qe(4===i.rank,(()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`)),Qe(4===u.rank,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${u.shape}.`)),Qe(4===n.length,(()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`));const l="NHWC"===s?i.shape[3]:i.shape[1],c="NHWC"===s?u.shape[3]:u.shape[1];Qe(l===n[2],(()=>`Error in conv2dDerFilter: depth of input ${l}) must match input depth in filter (${n[2]}.`)),Qe(c===n[3],(()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${n[3]}).`)),Nu("conv2dDerFilter",a,o);const p={x:i,dy:u},h={strides:r,pad:a,dataFormat:s,dimRoundingMode:o,filterShape:n};return ts.runKernel("Conv2DBackpropFilter",p,h)}});function ih(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return nu(e,zp(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function uh(e,t){let n=t;const r=Ni(e.shape,t.shape);return r.length>0&&(n=Pl(n,r)),Cu(n,e.shape)}function lh(e,t,n,r){if("linear"===t)return e;if("relu"===t)return fp(e);if("elu"===t)return wl(e);if("relu6"===t)return mp(e);if("prelu"===t)return zc(e,n);if("leakyrelu"===t)return ec(e,r);if("sigmoid"===t)return Fu(e);throw new Error(`Unknown fused activation ${t}.`)}const ch=(e,t)=>!(e>0)||"linear"===t,ph=lo({fusedConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:o,bias:i,activation:u="linear",preluActivationWeights:l,leakyreluAlpha:c}){if(u=u||"linear",!1===ch(ts.state.gradientDepth,u)){Qe("NHWC"===a,(()=>`Error in fused conv2d: got dataFormat of ${a} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`));let p=el(e,t,n,r,a,s,o);return null!=i&&(p=Zi(p,i)),lh(p,u,l,c)}const p=oo(e,"x","conv2d","float32"),h=oo(t,"filter","conv2d","float32");let d=p,f=!1;3===p.rank&&(f=!0,d=Cu(p,[1,p.shape[0],p.shape[1],p.shape[2]])),Qe(4===d.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${d.rank}.`)),Qe(4===h.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${h.rank}.`)),Nu("fused conv2d",r,o);const m="NHWC"===a?d.shape[3]:d.shape[1];Qe(h.shape[2]===m,(()=>`Error in conv2d: depth of input (${m}) must match input depth for filter ${h.shape[2]}.`)),Qe(Iu(n,s),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`));const g=yu(d.shape,h.shape,n,s,r,o);let y,b;if(null!=i&&(y=oo(i,"bias","fused conv2d"),[y]=qa(y,p),"NHWC"===a?Ci(g.outShape,y.shape):(Qe(y.shape.length<=1,(()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${y.shape.length}.`)),Qe(0===y.shape.length||y.shape[0]===g.outChannels||1===y.shape[0],(()=>`Error in fused conv2d: bias shape (${y.shape}) is not compatible with the number of output channels (${g.outChannels})`)))),null!=l){const e=l.shape;if(Qe(e.length<=1||3===e.length,(()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${e.length}.`)),1===e.length)Qe(1===e[0]||e[0]===g.outChannels,(()=>`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the number of output channels (${g.outChannels}).`));else if(3===e.length)try{Ci(e,g.outShape)}catch(t){const n=`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(n)}b=oo(l,"prelu weights","fused conv2d")}const _=(e,t)=>{Qe("NHWC"===a,(()=>`Error in gradient of fused conv2D: got dataFormat of ${a} but only NHWC is currently supported.`));const[o,i,l,c]=t,p=ih(e,l,u);Qe(ku(s),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`));const h=[nl(i.shape,p,o,n,r),oh(i,p,o.shape,n,r)];if(null!=c){const e=uh(c,p);h.push(e)}return h},x={x:d,filter:h,bias:y,preluActivationWeights:b},v={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o,activation:u,leakyreluAlpha:c};if(null==i){const e=oc(((e,t,n)=>{let r=ts.runKernel(Er,x,v);return n([t,e,r]),f&&(r=Cu(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:_}}));return e(d,h)}{const e=oc(((e,t,n,r)=>{let a=ts.runKernel(Er,x,v);return r([t,e,a,n]),f&&(a=Cu(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:_}}));return e(d,h,y)}}}),hh=lo({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,r,a,s=[1,1],o){let i=e;3===e.rank&&(i=Cu(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u=t;3===u.rank&&(u=Cu(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={x:i,dy:u},c={strides:r,pad:a,dimRoundingMode:o,dilations:s,filterShape:n};return ts.runKernel("DepthwiseConv2dNativeBackpropFilter",l,c)}}),dh=lo({depthwiseConv2dNativeBackpropInput_:function(e,t,n,r,a,s=[1,1],o){let i=t,u=!1;3===t.rank&&(u=!0,i=Cu(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={dy:i,filter:n},c={strides:r,pad:a,dimRoundingMode:o,dilations:s,inputShape:e},p=ts.runKernel("DepthwiseConv2dNativeBackpropInput",l,c);return u?Cu(p,[p.shape[1],p.shape[2],p.shape[3]]):p}}),fh=lo({fusedDepthwiseConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:o,bias:i,activation:u="linear",preluActivationWeights:l,leakyreluAlpha:c}){if(!1===ch(ts.state.gradientDepth,u)){let p=dl(e,t,n,r,a,s,o);return null!=i&&(p=Zi(p,i)),lh(p,u,l,c)}const p=oo(e,"x","depthwiseConv2d","float32"),h=oo(t,"filter","depthwiseConv2d","float32");let d=p,f=!1;3===p.rank&&(f=!0,d=Cu(p,[1,p.shape[0],p.shape[1],p.shape[2]])),Qe(4===d.rank,(()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${d.rank}.`)),Qe(4===h.rank,(()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`)),Qe(d.shape[3]===h.shape[2],(()=>`Error in fused depthwiseConv2d: number of input channels (${d.shape[3]}) must match the inChannels dimension in filter ${h.shape[2]}.`)),null==s&&(s=[1,1]),Qe(Iu(n,s),(()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`)),Nu("fused depthwiseConv2d",r,o);const m=yu(d.shape,h.shape,n,s,r,o,!0);let g,y;null!=i&&(g=oo(i,"bias","fused conv2d"),[g]=qa(g,p),Ci(m.outShape,g.shape)),null!=l&&(y=oo(l,"prelu weights","fused depthwiseConv2d"));const b=(e,t)=>{Qe(ku(s),(()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`));const[a,i,l,c]=t,p=ih(e,l,u),h=dh(i.shape,p,a,n,r,s,o),d=hh(i,p,a.shape,n,r,s,o);return null!=c?[h,d,uh(g,p)]:[h,d]},_={x:d,filter:h,bias:g,preluActivationWeights:y},x={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o,activation:u,leakyreluAlpha:c};if(null==i){const e=oc(((e,t,n)=>{let r=ts.runKernel(Nr,_,x);return n([t,e,r]),f&&(r=Cu(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:b}}));return e(d,h)}{const e=oc(((e,t,n,r)=>{let a=ts.runKernel(Nr,_,x);return r([t,e,a,n]),f&&(a=Cu(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:b}}));return e(d,h,g)}}}),mh=lo({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:a,activation:s="linear",preluActivationWeights:o,leakyreluAlpha:i=.2}){if(!1===ch(ts.state.gradientDepth,s)){let u=mi(e,t,n,r);return null!=a&&(u=Zi(u,a)),lh(u,s,o,i)}let u=oo(e,"a","fused matMul"),l=oo(t,"b","fused matMul");[u,l]=qa(u,l);const c=n?u.shape[u.rank-2]:u.shape[u.rank-1],p=r?l.shape[l.rank-1]:l.shape[l.rank-2],h=n?u.shape[u.rank-1]:u.shape[u.rank-2],d=r?l.shape[l.rank-2]:l.shape[l.rank-1],f=u.shape.slice(0,-2),m=l.shape.slice(0,-2),g=et(f),y=et(m);Qe(c===p,(()=>`Error in fused matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${u.shape} and ${l.shape} and transposeA=${n} and transposeB=${r} must match.`));const b=Ci(u.shape.slice(0,-2),l.shape.slice(0,-2)).concat([h,d]),_=Cu(u,n?[g,c,h]:[g,h,c]),x=Cu(l,r?[y,d,p]:[y,p,d]);let v,w;null!=a&&(v=oo(a,"bias","fused matMul"),[v]=qa(v,u),Ci(b,v.shape)),null!=o&&(w=oo(o,"prelu weights","fused matMul"));const T=(e,t)=>{const[o,i,u,l]=t,c=ih(Cu(e,u.shape),u,s);let p,h;return n||r?!n&&r?(p=mi(c,i,!1,!1),h=mi(c,o,!0,!1)):n&&!r?(p=mi(i,c,!1,!0),h=mi(o,c,!1,!1)):(p=mi(i,c,!0,!0),h=mi(c,o,!0,!0)):(p=mi(c,i,!1,!0),h=mi(o,c,!0,!1)),null!=a?[p,h,uh(l,c)]:[p,h]},k={a:_,b:x,bias:v,preluActivationWeights:w},I={transposeA:n,transposeB:r,activation:s,leakyreluAlpha:i};if(null==a){const e=oc(((e,t,n)=>{const r=ts.runKernel(Sr,k,I);return n([e,t,r]),{value:Cu(r,b),gradFunc:T}}));return e(_,x)}{const e=oc(((e,t,n,r)=>{const a=ts.runKernel(Sr,k,I);return r([e,t,a,n]),{value:Cu(a,b),gradFunc:T}}));return e(_,x,v)}}});var gh=Object.freeze({__proto__:null,conv2d:ph,depthwiseConv2d:fh,matMul:mh});const yh=lo({hammingWindow_:function(e){return sh(e,.54,.46)}}),bh=lo({hannWindow_:function(e){return sh(e,.5,.5)}}),_h=lo({frame_:function(e,t,n,r=!1,a=0){let s=0;const o=[];for(;s+t<=e.size;)o.push(Ou(e,s,t)),s+=n;if(r)for(;s<e.size;){const r=s+t-e.size,i=Mu([Ou(e,s,t-r),qu([r],a)]);o.push(i),s+=n}return 0===o.length?Gp([],[0,t]):Cu(Mu(o),[o.length,t])}}),xh=lo({stft_:function(e,t,n,r,a=bh){null==r&&(r=ah(t));const s=_h(e,t,n),o=nu(s,a(t));return Lp(o,r)}}),vh=lo({cropAndResize_:function(e,t,n,r,a="bilinear",s=0){const o=oo(e,"image","cropAndResize"),i=oo(t,"boxes","cropAndResize","float32"),u=oo(n,"boxInd","cropAndResize","int32"),l=i.shape[0];Qe(4===o.rank,(()=>`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`)),Qe(2===i.rank&&4===i.shape[1],(()=>`Error in cropAndResize: boxes must be have size [${l},4] but had shape ${i.shape}.`)),Qe(1===u.rank&&u.shape[0]===l,(()=>`Error in cropAndResize: boxInd must be have size [${l}] but had shape ${i.shape}.`)),Qe(2===r.length,(()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`)),Qe(r[0]>=1&&r[1]>=1,(()=>`cropSize must be atleast [1,1], but was ${r}`)),Qe("bilinear"===a||"nearest"===a,(()=>`method must be bilinear or nearest, but was ${a}`));const c={image:o,boxes:i,boxInd:u},p={method:a,extrapolationValue:s,cropSize:r};return ts.runKernel(Qt,c,p)}}),wh=lo({flipLeftRight_:function(e){const t=oo(e,"image","flipLeftRight","float32");Qe(4===t.rank,(()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`));const n={image:t};return ts.runKernel(on,n,{})}}),Th=lo({grayscaleToRGB_:function(e){const t=oo(e,"image","grayscaleToRGB"),n=t.rank-1,r=t.shape[n];Qe(t.rank>=2,(()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`)),Qe(1===r,(()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${r}.`));const a=new Array(t.rank);return a.fill(1,0,n),a[n]=3,Gl(t,a)}}),kh=lo({rotateWithOffset_:function(e,t,n=0,r=.5){const a=oo(e,"image","rotateWithOffset","float32");Qe(4===a.rank,(()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${a.rank}.`));const s={image:a},o={radians:t,fillValue:n,center:r};return ts.runKernel(Ir,s,o)}});function Ih(e,t,n,r,a,s){null==r&&(r=.5),null==a&&(a=Number.NEGATIVE_INFINITY),null==s&&(s=0);const o=e.shape[0];return n=Math.min(n,o),Qe(0<=r&&r<=1,(()=>`iouThreshold must be in [0, 1], but was '${r}'`)),Qe(2===e.rank,(()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`)),Qe(4===e.shape[1],(()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`)),Qe(1===t.rank,(()=>"scores must be a 1D tensor")),Qe(t.shape[0]===o,(()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`)),Qe(0<=s&&s<=1,(()=>`softNmsSigma must be in [0, 1], but was '${s}'`)),{maxOutputSize:n,iouThreshold:r,scoreThreshold:a,softNmsSigma:s}}const Sh=lo({nonMaxSuppression_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY){const s=oo(e,"boxes","nonMaxSuppression","float32"),o=oo(t,"scores","nonMaxSuppression","float32"),i=Ih(s,o,n,r,a),u={maxOutputSize:n=i.maxOutputSize,iouThreshold:r=i.iouThreshold,scoreThreshold:a=i.scoreThreshold};return ts.runKernel($n,{boxes:s,scores:o},u)}});function Eh(e,t,n){const r=function(e,t,n){return function(e,t,n){let r=0,a=e.length,s=0,o=!1;for(;r<a;){s=r+(a-r>>>1);const i=n(t,e[s]);i>0?r=s+1:(a=s,o=!i)}return o?r:-r-1}(e,t,n||Nh)}(e,t,n),a=r<0?-(r+1):r;e.splice(a,0,t)}function Nh(e,t){return e>t?1:e<t?-1:0}function Ch(e,t,n,r,a,s,o=!1,i=!1,u=!1){const l=[];for(let e=0;e<t.length;e++)t[e]>a&&l.push({score:t[e],boxIndex:e,suppressBeginIndex:0});l.sort($h);const c=s>0?-.5/s:0,p=[],h=[];for(;p.length<n&&l.length>0;){const t=l.pop(),{score:n,boxIndex:s,suppressBeginIndex:o}=t;if(n<a)break;let i=!1;for(let n=p.length-1;n>=o;--n){const o=Ah(e,s,p[n]);if(o>=r){i=!0;break}if(t.score=t.score*Rh(r,c,o),t.score<=a)break}t.suppressBeginIndex=p.length,i||(t.score===n?(p.push(s),h.push(t.score)):t.score>a&&Eh(l,t,$h))}const d=p.length,f=n-d;i&&f>0&&(p.push(...new Array(f).fill(0)),h.push(...new Array(f).fill(0)));const m={selectedIndices:p};return o&&(m.selectedScores=h),u&&(m.validOutputs=d),m}function Ah(e,t,n){const r=e.subarray(4*t,4*t+4),a=e.subarray(4*n,4*n+4),s=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),i=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(a[0],a[2]),c=Math.min(a[1],a[3]),p=Math.max(a[0],a[2]),h=Math.max(a[1],a[3]),d=(i-s)*(u-o),f=(p-l)*(h-c);if(d<=0||f<=0)return 0;const m=Math.max(s,l),g=Math.max(o,c),y=Math.min(i,p),b=Math.min(u,h),_=Math.max(y-m,0)*Math.max(b-g,0);return _/(d+f-_)}function Rh(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function $h(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const Mh=lo({nonMaxSuppressionWithScore_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=0){const o=oo(e,"boxes","nonMaxSuppression"),i=oo(t,"scores","nonMaxSuppression"),u=Ih(o,i,n,r,a,s),l={boxes:o,scores:i},c={maxOutputSize:n=u.maxOutputSize,iouThreshold:r=u.iouThreshold,scoreThreshold:a=u.scoreThreshold,softNmsSigma:s=u.softNmsSigma},p=ts.runKernel(Fn,l,c);return{selectedIndices:p[0],selectedScores:p[1]}}}),Fh=lo({nonMaxSuppressionPadded_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=!1){const o=oo(e,"boxes","nonMaxSuppression"),i=oo(t,"scores","nonMaxSuppression"),u=Ih(o,i,n,r,a,null),l={boxes:o,scores:i},c={maxOutputSize:u.maxOutputSize,iouThreshold:u.iouThreshold,scoreThreshold:u.scoreThreshold,padToMaxOutputSize:s},p=ts.runKernel(Mn,l,c);return{selectedIndices:p[0],validOutputs:p[1]}}}),Oh=lo({resizeBilinear_:function(e,t,n=!1,r=!1){const a=oo(e,"images","resizeBilinear");Qe(3===a.rank||4===a.rank,(()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${a.rank}.`)),Qe(2===t.length,(()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`)),Qe(!1===r||!1===n,(()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false."));let s=a,o=!1;3===a.rank&&(o=!0,s=Cu(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const i={images:s},u={alignCorners:n,halfPixelCenters:r,size:t},l=ts.runKernel(jn,i,u);return o?Cu(l,[l.shape[1],l.shape[2],l.shape[3]]):l}}),Dh=lo({resizeNearestNeighbor_:function(e,t,n=!1,r=!1){const a=oo(e,"images","resizeNearestNeighbor");Qe(3===a.rank||4===a.rank,(()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${a.rank}.`)),Qe(2===t.length,(()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`)),Qe("float32"===a.dtype||"int32"===a.dtype,(()=>"`images` must have `int32` or `float32` as dtype")),Qe(!1===r||!1===n,(()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false."));let s=a,o=!1;3===a.rank&&(o=!0,s=Cu(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const i={images:s},u={alignCorners:n,halfPixelCenters:r,size:t},l=ts.runKernel(Gn,i,u);return o?Cu(l,[l.shape[1],l.shape[2],l.shape[3]]):l}}),Lh=lo({threshold_:function(e,t="binary",n=!1,r=.5){const a=oo(e,"image","threshold"),s=a.shape[0]*a.shape[1];let o,i,u,l,c=nu(Hp([r]),255);if(Qe(3===a.rank,(()=>`Error in threshold: image must be rank 3,but got rank ${a.rank}.`)),Qe(3===a.shape[2]||1===a.shape[2],(()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${a.shape[2]}.`)),Qe("int32"===a.dtype||"float32"===a.dtype,(()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${a.dtype}.`)),Qe("otsu"===t||"binary"===t,(()=>`Method must be binary or otsu, but was ${t}`)),3===a.shape[2]){[o,i,u]=Dp(a,[1,1,1],-1);const e=nu(o,.2989),t=nu(i,.587),n=nu(u,.114);l=Zi(Zi(e,t),n)}else l=e;"otsu"===t&&(c=function(e,t){let n,r,a,s,o,i,u=Hp([-1]),l=Hp([0]),c=Hp([0]);for(let p=0;p<e.size-1;p++){n=Ou(e,0,p+1),r=Ou(e,p+1),o=tu(Pl(n),t),i=tu(Pl(r),t);const h=Pl(nu(n,hp(0,n.size)));a=tu(h,Pl(n));const d=qu(r.shape,n.size),f=Zi(hp(0,r.size),d),m=nu(r,f);s=tu(Pl(m),Pl(r));const g=lc(a,s),y=lc(a,s),b=nu(o,i);c=nu(nu(b,g),y);const _=Xl(c,l);l=yl(_,c,l),u=yl(_,Hp([p]),u)}return u}(Wu(fi(vp(l),"int32"),ho([]),256),s));const p=n?nc(l,c):Xl(l,c);return fi(nu(p,255),"int32")}}),Ph=lo({transform_:function(e,t,n="nearest",r="constant",a=0,s){const o=oo(e,"image","transform","float32"),i=oo(t,"transforms","transform","float32");Qe(4===o.rank,(()=>`Error in transform: image must be rank 4,but got rank ${o.rank}.`)),Qe(2===i.rank&&(i.shape[0]===o.shape[0]||1===i.shape[0])&&8===i.shape[1],(()=>"Error in transform: Input transform should be batch x 8 or 1 x 8")),Qe(null==s||2===s.length,(()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`));const u={image:o,transforms:i},l={interpolation:n,fillMode:r,fillValue:a,outputShape:s};return ts.runKernel(_r,u,l)}}),Bh=lo({bandPart_:function(e,t,n){Qe(t%1==0,(()=>`bandPart(): numLower must be an integer, got ${t}.`)),Qe(n%1==0,(()=>`bandPart(): numUpper must be an integer, got ${n}.`));const r=oo(e,"a","bandPart");Qe(r.rank>=2,(()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`));const a=r.shape,[s,o]=r.shape.slice(-2);if(!(t<=s))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`);if(!(n<=o))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${o}).`);t<0&&(t=s),n<0&&(n=o);const i=Cu(hp(0,s,1,"int32"),[-1,1]),u=hp(0,o,1,"int32"),l=lc(i,u),c=hc(nc(l,Ol(+t,"int32")),Yl(l,Ol(-n,"int32"))),p=Tc([s,o],r.dtype);return Cu(Up(Yp(Cu(r,[-1,s,o])).map((e=>yl(c,e,p)))),a)}}),Uh=lo({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,Qe(null!=e&&e.length>0,(()=>"Gram-Schmidt process: input must not be null, undefined, or empty"));const n=e[0].shape[0];for(let t=1;t<e.length;++t)Qe(e[t].shape[0]===n,(()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[t].shape[0]} vs. ${n})`))}else t=!0,e=Dp(e,e.shape[0],0).map((e=>Bp(e,[0])));Qe(e.length<=e[0].shape[0],(()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`));const n=[],r=e;for(let t=0;t<e.length;++t)n.push(ts.tidy((()=>{let e=r[t];if(t>0)for(let r=0;r<t;++r){const t=nu(Pl(nu(n[r],e)),n[r]);e=lc(e,t)}return tu(e,Ul(e,"euclidean"))})));return t?Up(n,0):n}});function zh(e,t=!1){return ts.tidy((()=>{Qe(2===e.shape.length,(()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`));const n=e.shape[0],r=e.shape[1];let a=jl(n),s=$u(e);const o=Gp([[1]],[1,1]);let i=$u(o);const u=n>=r?r:n;for(let e=0;e<u;++e){const t=s,u=i,l=a;[i,s,a]=ts.tidy((()=>{const t=Ou(s,[e,e],[n-e,1]),u=Ul(t),l=Ou(s,[e,e],[1,1]),c=yl(Xl(l,0),Gp([[-1]]),Gp([[1]])),p=lc(l,nu(c,u)),h=tu(t,p);i=1===h.shape[0]?$u(o):Mu([o,Ou(h,[1,0],[h.shape[0]-1,h.shape[1]])],0);const d=ki(tu(mi(c,p),u)),f=Ou(s,[e,0],[n-e,r]),m=nu(d,i),g=Si(i);if(0===e)s=lc(f,mi(m,mi(g,f)));else{const t=lc(f,mi(m,mi(g,f)));s=Mu([Ou(s,[0,0],[e,r]),t],0)}const y=Si(m),b=Ou(a,[0,e],[n,a.shape[1]-e]);if(0===e)a=lc(b,mi(mi(b,i),y));else{const t=lc(b,mi(mi(b,i),y));a=Mu([Ou(a,[0,0],[n,e]),t],1)}return[i,s,a]})),_i([t,u,l])}return!t&&n>r&&(a=Ou(a,[0,0],[n,r]),s=Ou(s,[0,0],[r,r])),[a,s]}))}const Vh=lo({qr_:function(e,t=!1){if(Qe(e.rank>=2,(()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`)),2===e.rank)return zh(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),r=Yp(Cu(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),a=[],s=[];return r.forEach((e=>{const[n,r]=zh(e,t);a.push(n),s.push(r)})),[Cu(Up(a,0),e.shape),Cu(Up(s,0),e.shape)]}}});var Wh;!function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(Wh||(Wh={}));const Hh=lo({computeWeightedLoss_:function(e,t,n=Wh.SUM_BY_NONZERO_WEIGHTS){const r=oo(e,"losses","computeWeightedLoss");let a=null;null!=t&&(a=oo(t,"weights","computeWeightedLoss"));const s=null==a?r:nu(r,a);if(n===Wh.NONE)return s;if(n===Wh.SUM)return Pl(s);if(n===Wh.MEAN){if(null==a)return wc(s);{const e=r.size/a.size,t=tu(Pl(s),Pl(a));return e>1?tu(t,Ol(e)):t}}if(n===Wh.SUM_BY_NONZERO_WEIGHTS){if(null==a)return tu(Pl(s),Ol(r.size));{const e=nu(a,kc(r.shape)),t=fi(Pl(Rc(e,Ol(0))),"float32");return tu(Pl(s),t)}}throw Error(`Unknown reduction: ${n}`)}}),Gh=lo({absoluteDifference_:function(e,t,n,r=Wh.SUM_BY_NONZERO_WEIGHTS){const a=oo(e,"labels","absoluteDifference"),s=oo(t,"predictions","absoluteDifference");let o=null;null!=n&&(o=oo(n,"weights","absoluteDifference")),Je(a.shape,s.shape,"Error in absoluteDifference: ");const i=ru(lc(a,s));return Hh(i,o,r)}}),jh=lo({cosineDistance_:function(e,t,n,r,a=Wh.SUM_BY_NONZERO_WEIGHTS){const s=oo(e,"labels","cosineDistance"),o=oo(t,"predictions","cosineDistance");let i=null;null!=r&&(i=oo(r,"weights","cosineDistance")),Je(s.shape,o.shape,"Error in cosineDistance: ");const u=Ol(1),l=lc(u,Pl(nu(s,o),n,!0));return Hh(l,i,a)}}),Kh=lo({hingeLoss_:function(e,t,n,r=Wh.SUM_BY_NONZERO_WEIGHTS){let a=oo(e,"labels","hingeLoss");const s=oo(t,"predictions","hingeLoss");let o=null;null!=n&&(o=oo(n,"weights","hingeLoss")),Je(a.shape,s.shape,"Error in hingeLoss: ");const i=Ol(1);a=lc(nu(Ol(2),a),i);const u=fp(lc(i,nu(a,s)));return Hh(u,o,r)}}),qh=lo({huberLoss_:function(e,t,n,r=1,a=Wh.SUM_BY_NONZERO_WEIGHTS){const s=oo(e,"labels","huberLoss"),o=oo(t,"predictions","huberLoss");let i=null;null!=n&&(i=oo(n,"weights","huberLoss")),Je(s.shape,o.shape,"Error in huberLoss: ");const u=Ol(r),l=ru(lc(o,s)),c=Ic(l,u),p=lc(l,c),h=Zi(nu(Ol(.5),Ll(c)),nu(u,p));return Hh(h,i,a)}}),Xh=lo({logLoss_:function(e,t,n,r=1e-7,a=Wh.SUM_BY_NONZERO_WEIGHTS){const s=oo(e,"labels","logLoss"),o=oo(t,"predictions","logLoss");let i=null;null!=n&&(i=oo(n,"weights","logLoss")),Je(s.shape,o.shape,"Error in logLoss: ");const u=Ol(1),l=Ol(r),c=ki(nu(s,ac(Zi(o,l)))),p=nu(lc(u,s),ac(Zi(lc(u,o),l))),h=lc(c,p);return Hh(h,i,a)}}),Yh=lo({meanSquaredError_:function(e,t,n,r=Wh.SUM_BY_NONZERO_WEIGHTS){const a=oo(e,"labels","meanSquaredError"),s=oo(t,"predictions","meanSquaredError");let o=null;null!=n&&(o=oo(n,"weights","meanSquaredError")),Je(a.shape,s.shape,"Error in meanSquaredError: ");const i=Pp(a,s);return Hh(i,o,r)}}),Qh=lo({sigmoidCrossEntropy_:function(e,t,n,r=0,a=Wh.SUM_BY_NONZERO_WEIGHTS){let s=oo(e,"multiClassLabels","sigmoidCrossEntropy");const o=oo(t,"logits","sigmoidCrossEntropy");let i=null;if(null!=n&&(i=oo(n,"weights","sigmoidCrossEntropy")),Je(s.shape,o.shape,"Error in sigmoidCrossEntropy: "),r>0){const e=Ol(r),t=Ol(1),n=Ol(.5);s=Zi(nu(s,lc(t,e)),nu(n,e))}const u=function(e,t){const n=oo(e,"labels","sigmoidCrossEntropyWithLogits"),r=oo(t,"logits","sigmoidCrossEntropyWithLogits");Je(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const a=fp(r),s=nu(r,n),o=sc(Vl(ki(ru(r))));return Zi(lc(a,s),o)}(s,o);return Hh(u,i,a)}}),Jh=lo({softmaxCrossEntropy_:function(e,t,n,r=0,a=Wh.SUM_BY_NONZERO_WEIGHTS){let s=oo(e,"onehotLabels","softmaxCrossEntropy");const o=oo(t,"logits","softmaxCrossEntropy");let i=null;if(null!=n&&(i=oo(n,"weights","softmaxCrossEntropy")),Je(s.shape,o.shape,"Error in softmaxCrossEntropy: "),r>0){const e=Ol(r),t=Ol(1),n=Ol(s.shape[1]);s=Zi(nu(s,lc(t,e)),tu(e,n))}const u=function(e,t,n=-1){if(-1===n&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);const r=oc(((e,t,r)=>{const a=pc(t,[n],!0),s=lc(fi(t,"float32"),a);r([e,s]);const o=ki(nu(s,e));return{value:Pl(o,[n]),gradFunc:(e,t)=>{const[r,a]=t,s=El(e.shape,[n]);return[nu(Cu(e,s),lc(fi(r,"float32"),Vl(a))),nu(Cu(e,s),lc(Vl(a),fi(r,"float32")))]}}}));return r(e,t)}(s,o);return Hh(u,i,a)}}),Zh=lo({sparseFillEmptyRows_:function(e,t,n,r){const a=oo(e,"indices","sparseFillEmptyRows","int32"),s=oo(t,"values","sparseFillEmptyRows"),o=oo(n,"denseShape","sparseFillEmptyRows","int32"),i=oo(r,"defaultValue","sparseFillEmptyRows",s.dtype);if(2!==a.rank)throw new Error(`Indices should be Tensor2D but received shape\n ${a.shape}`);if(1!==s.rank)throw new Error(`Values should be Tensor1D but received shape ${s.shape}`);if(1!==o.rank)throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);if(0!==i.rank)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);const u={indices:a,values:s,denseShape:o,defaultValue:i},l=ts.runKernel(or,u);return{outputIndices:l[0],outputValues:l[1],emptyRowIndicator:l[2],reverseIndexMap:l[3]}}}),ed=lo({sparseReshape_:function(e,t,n){const r=oo(e,"inputIndices","sparseReshape","int32"),a=oo(t,"inputShape","sparseReshape","int32"),s=oo(n,"newShape","sparseReshape","int32");if(2!==r.rank)throw new Error(`Input indices should be Tensor2D but received shape\n ${r.shape}`);if(1!==a.rank)throw new Error(`Input shape should be Tensor1D but received shape ${a.shape}`);if(1!==s.rank)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);const o={inputIndices:r,inputShape:a,newShape:s},i=ts.runKernel(ir,o);return{outputIndices:i[0],outputShape:i[1]}}}),td=lo({sparseSegmentMean_:function(e,t,n){const r=oo(e,"data","sparseSegmentMean"),a=oo(t,"indices","sparseSegmentMean","int32"),s=oo(n,"segmentIds","sparseSegmentMean","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${a.shape}`);if(1!==s.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${s.shape}`);const o={data:r,indices:a,segmentIds:s};return ts.runKernel(ur,o)}}),nd=lo({sparseSegmentSum_:function(e,t,n){const r=oo(e,"data","sparseSegmentSum"),a=oo(t,"indices","sparseSegmentSum","int32"),s=oo(n,"segmentIds","sparseSegmentSum","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==a.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${a.shape}`);if(1!==s.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${s.shape}`);const o={data:r,indices:a,segmentIds:s};return ts.runKernel(lr,o)}}),rd=lo({stringNGrams_:function(e,t,n,r,a,s,o,i){const u=oo(e,"data","stringNGrams","string");if("string"!==u.dtype)throw new Error("Data must be of datatype string");if(1!==u.shape.length)throw new Error(`Data must be a vector, saw: ${u.shape}`);const l=oo(t,"dataSplits","stringNGrams");if("int32"!==l.dtype)throw new Error("Data splits must be of datatype int32");const c={separator:n,nGramWidths:r,leftPad:a,rightPad:s,padWidth:o,preserveShortSequences:i},p={data:u,dataSplits:l},h=ts.runKernel(hr,p,c);return{nGrams:h[0],nGramsSplits:h[1]}}}),ad={fft:Mp,ifft:Fp,rfft:Lp,irfft:Op},sd={hammingWindow:yh,hannWindow:bh,frame:_h,stft:xh},od={flipLeftRight:wh,grayscaleToRGB:Th,resizeNearestNeighbor:Dh,resizeBilinear:Oh,rotateWithOffset:kh,cropAndResize:vh,nonMaxSuppression:Sh,nonMaxSuppressionAsync:async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY){const s=oo(e,"boxes","nonMaxSuppressionAsync"),o=oo(t,"scores","nonMaxSuppressionAsync"),i=Ih(s,o,n,r,a);n=i.maxOutputSize,r=i.iouThreshold,a=i.scoreThreshold;const u=await Promise.all([s.data(),o.data()]),l=u[0],c=u[1],{selectedIndices:p}=function(e,t,n,r,a){return Ch(e,t,n,r,a,0)}(l,c,n,r,a);return s!==e&&s.dispose(),o!==t&&o.dispose(),Hp(p,"int32")},nonMaxSuppressionWithScore:Mh,nonMaxSuppressionWithScoreAsync:async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=0){const o=oo(e,"boxes","nonMaxSuppressionAsync"),i=oo(t,"scores","nonMaxSuppressionAsync"),u=Ih(o,i,n,r,a,s);n=u.maxOutputSize,r=u.iouThreshold,a=u.scoreThreshold,s=u.softNmsSigma;const l=await Promise.all([o.data(),i.data()]),c=l[0],p=l[1],{selectedIndices:h,selectedScores:d}=function(e,t,n,r,a,s){return Ch(e,t,n,r,a,s,!0)}(c,p,n,r,a,s);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Hp(h,"int32"),selectedScores:Hp(d)}},nonMaxSuppressionPadded:Fh,nonMaxSuppressionPaddedAsync:async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=!1){const o=oo(e,"boxes","nonMaxSuppressionAsync"),i=oo(t,"scores","nonMaxSuppressionAsync"),u=Ih(o,i,n,r,a,null),l=u.maxOutputSize,c=u.iouThreshold,p=u.scoreThreshold,[h,d]=await Promise.all([o.data(),i.data()]),{selectedIndices:f,validOutputs:m}=function(e,t,n,r,a,s){return Ch(e,t,n,r,a,0,!1,s,!0)}(h,d,l,c,p,s);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Hp(f,"int32"),validOutputs:Ol(m,"int32")}},threshold:Lh,transform:Ph},id={bandPart:Bh,gramSchmidt:Uh,qr:Vh},ud={absoluteDifference:Gh,computeWeightedLoss:Hh,cosineDistance:jh,hingeLoss:Kh,huberLoss:qh,logLoss:Xh,meanSquaredError:Yh,sigmoidCrossEntropy:Qh,softmaxCrossEntropy:Jh},ld={sparseFillEmptyRows:Zh,sparseReshape:ed,sparseSegmentMean:td,sparseSegmentSum:nd},cd={stringNGrams:rd,stringSplit:lo({stringSplit_:function(e,t,n=!0){const r=oo(e,"input","stringSplit","string"),a=oo(t,"delimiter","stringSplit","string");if(1!==r.rank)throw new Error(`Input should be Tensor1D but received shape ${r.shape}`);if(0!==a.rank)throw new Error(`Delimiter should be a scalar but received shape ${a.shape}`);const s={skipEmpty:n},o={input:r,delimiter:a},i=ts.runKernel(dr,o,s);return{indices:i[0],values:i[1],shape:i[2]}}}),stringToHashBucketFast:lo({stringToHashBucketFast_:function(e,t){const n=oo(e,"input","stringToHashBucketFast","string"),r={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");const a={input:n};return ts.runKernel(fr,a,r)}})},pd="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:e=>e();function hd(e,t){const n=e[0].length;e.forEach(((e,t)=>{Qe(e.length===n,(()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`))})),Qe(t>=0&&t<n,(()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`));const r=e[0];e.forEach(((e,a)=>{for(let s=0;s<n;s++)Qe(s===t||e[s]===r[s],(()=>`Error in concat${n}D: Shape of tensors[${a}] (${e}) does not match the shape of the rest (${r}) along the non-concatenated axis ${a}.`))}))}function dd(e,t){const n=e[0].slice();for(let r=1;r<e.length;r++)n[t]+=e[r][t];return n}var fd;function md(e,t,n){let r=new Array;if(null==n&&null==t)return r;if(null==t)for(;r.length<e+n.length;)r.push(-1);else r=t.slice();if(null==n)return r;if(e+n.length!==r.length)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.rank = ${e+n.length}, but shape.rank = ${r.length}`);for(let a=1;a<n.length;++a){const s=n[a],o=r[r.length-n.length+a],i=r[o];if(s>=0)if(i>=0){if(i!==s)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${a+e}] = ${s} but shape[${a+e}] = ${i}`)}else r[o]=s}return r}function gd(e){const t={FIRST_DIM_SIZE:fd.FIRST_DIM_SIZE,VALUE_ROWIDS:fd.VALUE_ROWIDS,ROW_LENGTHS:fd.ROW_LENGTHS,ROW_SPLITS:fd.ROW_SPLITS,ROW_LIMITS:fd.ROW_LIMITS,ROW_STARTS:fd.ROW_STARTS},n=[];for(const r of e){if(!(r in t))break;n.push(t[r])}return n}function yd(e){return 0===e.length?0:e[0]===fd.FIRST_DIM_SIZE?e.length-1:e.length}function bd(e,t){if(null==e||null==t)return;const n=e.length,r=t.length;if(n>=r)throw new Error(`defaultValue.shape=${e} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${n} must be less than ragged tensor input flatValues.rank = ${r})`);for(let a=0;a<Math.min(n,r-1);++a){const n=e[a],r=t[a+1];if(n>=0&&r>=0&&1!==n&&n!==r)throw new Error(`defaultValue.shape=${e}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${a-e.length}] = ${n} but ragged tensor input.flatValues.shape[${a-e.length}] = ${r}`)}}function _d(e){return e<=30?e:gt(e,Math.floor(Math.sqrt(e)))}function xd(e,t,n){return[n*("number"==typeof e?e:e[0]),t*("number"==typeof e?e:e[1])]}function vd(e,t,n,r=!0){let a=[];if(r)a=a.concat(t.slice(0)),a.push(e[0]/n),a=a.concat(e.slice(1));else{a=a.concat(e[0]);const n=t.length;for(let r=0;r<n;++r)a=a.concat([e[r+1]/t[r],t[r]]);a=a.concat(e.slice(n+1))}return a}function wd(e,t,n=!0){const r=[];if(n){r.push(t);for(let n=t+1;n<e;++n)n<=2*t?(r.push(n),r.push(n-(t+1))):r.push(n)}else{const n=[],a=[];for(let r=1;r<e;++r)r>=2*t+1||r%2==1?a.push(r):n.push(r);r.push(...n),r.push(0),r.push(...a)}return r}function Td(e,t,n,r=!0){const a=[];r?a.push(e[0]/n):a.push(e[0]*n);for(let n=1;n<e.length;++n)n<=t.length?r?a.push(t[n-1]*e[n]):a.push(e[n]/t[n-1]):a.push(e[n]);return a}function kd(e,t){const n=[0];for(let r=0;r<t;++r)n.push(e[r][0]);return n}function Id(e,t,n){const r=e.slice(0,1);for(let a=0;a<n;++a)r.push(e[a+1]-t[a][0]-t[a][1]);return r}function Sd(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);const n=new Float32Array(2*e.length);for(let r=0;r<n.length;r+=2)n[r]=e[r/2],n[r+1]=t[r/2];return n}!function(e){e[e.FIRST_DIM_SIZE=0]="FIRST_DIM_SIZE",e[e.VALUE_ROWIDS=1]="VALUE_ROWIDS",e[e.ROW_LENGTHS=2]="ROW_LENGTHS",e[e.ROW_SPLITS=3]="ROW_SPLITS",e[e.ROW_LIMITS=4]="ROW_LIMITS",e[e.ROW_STARTS=5]="ROW_STARTS"}(fd||(fd={}));const Ed=/->/g;function Nd(e,t){const n=[];for(let r=0;r<e.length;++r)0!==e[r].length&&-1===e[r].indexOf(t)&&-1!==t||n.push(r);return n}function Cd(e,t,n=0){let r=[];if("number"==typeof t)Qe(e.shape[n]%t==0,(()=>"Number of splits must evenly divide the axis.")),r=new Array(t).fill(e.shape[n]/t);else{Qe(t.reduce(((e,t)=>(-1===t&&(e+=1),e)),0)<=1,(()=>"There should be only one negative value in split array."));const a=t.indexOf(-1);if(-1!==a){const r=t.reduce(((e,t)=>t>0?e+t:e));t[a]=e.shape[n]-r}Qe(e.shape[n]===t.reduce(((e,t)=>e+t)),(()=>"The sum of sizes must match the size of the axis dimension.")),r=t}return r}function Ad(e){return`Received SparseTensor with denseShape[0] = 0 but\n indices.shape[0] = ${e}`}function Rd(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function $d(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function Md(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function Fd(e,t){return`size ${e} must be non-negative, not ${t}`}function Od(e,t){return`Input to reshape is a SparseTensor with ${et(e)}\n dense values, but the requested shape requires a multiple of ${et(t)}. inputShape=${e} outputShape= ${t}`}function Dd(e,t){return`Input to reshape is a tensor with ${et(e)} dense values, but the requested shape has ${et(t)}. inputShape=${e} outputShape=${t}`}function Ld(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function Pd(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}function Bd(e,t,n,r){const a=t.shape.length,s=e.shape.length;if(0!==r&&(r<-a||r>a))throw new Error(`Expect batchDims in the range of [-${a}, ${a}], but got ${r}`);if(r<0&&(r+=a),r>s)throw new Error(`batchDims (${r}) must be less than rank(x) (\n ${s}).`);if(n<r)throw new Error(`batchDims (${r}) must be less than or equal to axis (${n}).`);for(let n=0;n<r;++n)if(e.shape[n]!==t.shape[n])throw new Error(`x.shape[${n}]: ${e.shape[n]} should be equal to indices.shape[${n}]: ${t.shape[n]}.`);const o=e.shape[n],i=[];let u=1,l=1,c=1;for(let t=0;t<r;++t)i.push(e.shape[t]),u*=e.shape[t];for(let t=r;t<n;t++)i.push(e.shape[t]),l*=e.shape[t];for(let e=r;e<a;e++)i.push(t.shape[e]);for(let t=n+1;t<s;t++)i.push(e.shape[t]),c*=e.shape[t];return{batchSize:u,sliceSize:c,outerSize:l,dimSize:o,outputShape:i}}var Ud=Object.freeze({__proto__:null,segOpComputeOptimalWindowSize:function(e,t){let n,r=!1;for(e<=30?(n=e,r=!0):n=gt(e,Math.floor(Math.sqrt(e)));!r;)n>t||n===e?r=!0:n=gt(e,n+1);return n},computeOutShape:function(e,t,n){const r=[],a=e.length;for(let s=0;s<a;s++)s!==t?r.push(e[s]):r.push(n);return r},collectGatherOpShapeInfo:Bd});function zd(e){try{return e.map((e=>Ia(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function Vd(e){return e.map((e=>ka(e)))}var Wd=Object.freeze({__proto__:null,slice_util:Ji,segment_util:Ud,fromUint8ToStringArray:zd,fromStringArrayToUint8:Vd,upcastType:Ka,axesAreInnerMostDims:kl,combineLocations:Il,computeOutAndReduceShapes:Sl,expandShapeToKeepDim:El,assertAxesAreInnerMostDims:Nl,getAxesPermutation:Cl,getUndoAxesPermutation:Al,getInnerMostAxes:Rl,getBroadcastDims:Ei,getReductionAxes:Ni,assertAndGetBroadcastShape:Ci,assertParamsConsistent:hd,computeOutShape:dd,computeDilation2DInfo:function(e,t,n,r,a="NHWC",s){return yu(e,[...t,e[3]],n,s,r,null,null,Eu(a))},computePool2DInfo:gu,computePool3DInfo:function(e,t,n,r,a,s,o="NDHWC"){const[i,u,l]=vu(t);let c,p;if("NDHWC"===o)p="channelsLast",c=[i,u,l,e[4],e[4]];else{if("NCDHW"!==o)throw new Error(`Unknown dataFormat ${o}`);p="channelsFirst",c=[i,u,l,e[1],e[1]]}return bu(e,c,n,r,a,!1,p,s)},computeConv2DInfo:yu,computeConv3DInfo:bu,computeDefaultPad:_u,tupleValuesAreOne:ku,eitherStridesOrDilationsAreOne:Iu,stridesOrDilationsArePositive:Su,convertConv2DDataFormat:Eu,checkPadOnDimRoundingMode:Nu,getFusedDyActivation:ih,getFusedBiasGradient:uh,applyActivation:lh,shouldFuse:ch,get RowPartitionType(){return fd},combineRaggedTensorToTensorShapes:md,getRowPartitionTypesHelper:gd,getRaggedRank:yd,validateDefaultValueShape:bd,PARALLELIZE_THRESHOLD:30,computeOptimalWindowSize:_d,getImageCenter:xd,getReshaped:vd,getPermuted:wd,getReshapedPermuted:Td,getSliceBeginCoords:kd,getSliceSize:Id,prepareAndValidate:Mi,validateUpdateShape:Fi,validateInput:Oi,calculateShapes:Di,SELU_SCALEALPHA:1.7580993408473768,SELU_SCALE:1.0507009873554805,ERF_P:.3275911,ERF_A1:.254829592,ERF_A2:-.284496736,ERF_A3:1.421413741,ERF_A4:-1.453152027,ERF_A5:1.061405429,warn:Cr,log:function(...e){Ct().getBool("IS_TEST")||Ct().getBool("PROD")||console.log(...e)},mergeRealAndImagArrays:Sd,splitRealAndImagArrays:function(e){const t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=e[r],n[r/2]=e[r+1];return{real:t,imag:n}},complexWithEvenIndex:function(e){const t=Math.ceil(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let t=0;t<e.length;t+=4)n[Math.floor(t/4)]=e[t],r[Math.floor(t/4)]=e[t+1];return{real:n,imag:r}},complexWithOddIndex:function(e){const t=Math.floor(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let t=2;t<e.length;t+=4)n[Math.floor(t/4)]=e[t],r[Math.floor(t/4)]=e[t+1];return{real:n,imag:r}},getComplexWithIndex:function(e,t){return{real:e[2*t],imag:e[2*t+1]}},assignToTypedArray:function(e,t,n,r){e[2*r]=t,e[2*r+1]=n},exponents:function(e,t){const n=new Float32Array(e/2),r=new Float32Array(e/2);for(let a=0;a<Math.ceil(e/2);a++){const s=(t?2:-2)*Math.PI*(a/e);n[a]=Math.cos(s),r[a]=Math.sin(s)}return{real:n,imag:r}},exponent:function(e,t,n){const r=(n?2:-2)*Math.PI*(e/t);return{real:Math.cos(r),imag:Math.sin(r)}},decodeEinsumEquation:function(e,t){const n=((e=e.replace(/\s/g,"")).length-e.replace(Ed,"").length)/"->".length;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error('Equation must contain exactly one arrow ("->").');const[r,a]=e.split("->");Qe(-1===r.indexOf("..."),(()=>'The ellipsis notation ("...") is not supported yet.'));const s=r.split(","),o=s.length;if(t!==o)throw new Error(`Expected ${o} input tensors, received ${t}`);if(o>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");const i=[];for(let e=0;e<a.length;++e){const t=a[e];if(!s.some((e=>-1!==e.indexOf(t))))throw new Error(`Output subscripts contain the label ${t} not present in the input subscripts.`);-1===i.indexOf(t)&&i.push(t)}for(let e=0;e<r.length;++e){const t=r[e];-1===i.indexOf(t)&&","!==t&&i.push(t)}const u=new Array(s.length);for(let e=0;e<o;++e){if(new Set(s[e].split("")).size!==s[e].length)throw new Error(`Found duplicate axes in input component ${s[e]}. Support for duplicate axes in input is not implemented yet.`);u[e]=[];for(let t=0;t<s[e].length;++t)u[e].push(i.indexOf(s[e][t]))}const l=i.length,c=[];for(let e=a.length;e<l;++e)c.push(e);return{allDims:i,summedDims:c,idDims:u}},getEinsumPermutation:function(e,t){let n=new Array(e);n.fill(-1);for(let e=0;e<t.length;++e)n[t[e]]=e;const r=[];for(let t=0;t<e;++t)-1===n[t]&&r.push(t);return n=n.filter((e=>-1!==e)),{permutationIndices:n,expandDims:r}},checkEinsumDimSizes:function(e,t,n){const r=new Array(e);for(let e=0;e<n.length;++e){const a=n[e].shape;for(let n=0;n<t[e].length;++n)void 0===r[t[e][n]]?r[t[e][n]]=a[n]:Qe(r[t[e][n]]===a[n],(()=>`Expected dimension ${r[t[e][n]]} at axis ${n} of input shaped ${JSON.stringify(a)}, but got dimension ${a[n]}`))}},getEinsumComputePath:function(e,t){const n=e,r=[];let a=0;0===e.length&&n.push(-1),a=e.length+1;for(let e=0;e<a;++e)r.push([]);const s=[];for(let e=0;e<n.length;++e){const a=Nd(t,n[e]);for(const t of a)-1===s.indexOf(t)&&(r[e].push(t),s.push(t))}return{path:n,steps:r}},isIdentityPermutation:function(e){return e.every(((e,t)=>e===t))},prepareSplitSize:Cd,getSparseFillEmptyRowsIndicesDenseShapeMismatch:Ad,getSparseFillEmptyRowsNegativeIndexErrorMessage:Rd,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:$d,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:Md,getSparseReshapeNegativeOutputDimErrorMessage:Fd,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:function(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"},getSparseReshapeInputOutputMultipleErrorMessage:Od,getSparseReshapeInputOutputMismatchErrorMessage:Dd,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:function(){return"segment ids must be >= 0"},getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:function(){return"segment ids are not increasing"},getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:Ld,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:Pd});class Hd{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}setTimeoutCustom(e,t){"undefined"!=typeof window&&Ct().getBool("USE_SETTIMEOUTCUSTOM")?(this.functionRefs.push(e),setTimeout((()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")}),t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",(e=>{e.source===window&&e.data.name===this.messageName&&(e.stopPropagation(),(0,this.functionRefs[e.data.index])(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0))}),!0))):setTimeout(e,t)}isTypedArray(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}}if(Ct().get("IS_BROWSER")){Ct().setPlatform("browser",new Hd);try{ci.registerManager(jo.URL_SCHEME,new qo)}catch(e){}try{ci.registerManager(Mo.URL_SCHEME,new Oo)}catch(e){}}let Gd;var jd,Kd;Ct().get("IS_NODE")&&!Ct().get("IS_BROWSER")&&Ct().setPlatform("node",new class{constructor(){this.util=n(345),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=Ct().global.fetch?Ct().global.fetch(e,t):(null==Gd&&(Gd=n(683)),Gd(e,t))}now(){const e=He.hrtime();return 1e3*e[0]+e[1]/1e6}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return 0===e.length?"":new this.util.TextDecoder(t).decode(e)}isTypedArray(e){return this.util.types.isFloat32Array(e)||this.util.types.isInt32Array(e)||this.util.types.isUint8Array(e)||this.util.types.isUint8ClampedArray(e)}}),es(),Pa={buffer:ju,cast:fi,clone:$u,print:Vc},Ct().registerFlag("KEEP_INTERMEDIATE_TENSORS",(()=>!1),(e=>{e&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")})),function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_QINT16=15]="DT_QINT16",e[e.DT_QUINT16=16]="DT_QUINT16",e[e.DT_UINT16=17]="DT_UINT16",e[e.DT_COMPLEX128=18]="DT_COMPLEX128",e[e.DT_HALF=19]="DT_HALF",e[e.DT_RESOURCE=20]="DT_RESOURCE",e[e.DT_VARIANT=21]="DT_VARIANT",e[e.DT_UINT32=22]="DT_UINT32",e[e.DT_UINT64=23]="DT_UINT64",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",e[e.DT_QINT16_REF=115]="DT_QINT16_REF",e[e.DT_QUINT16_REF=116]="DT_QUINT16_REF",e[e.DT_UINT16_REF=117]="DT_UINT16_REF",e[e.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",e[e.DT_HALF_REF=119]="DT_HALF_REF",e[e.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",e[e.DT_VARIANT_REF=121]="DT_VARIANT_REF",e[e.DT_UINT32_REF=122]="DT_UINT32_REF",e[e.DT_UINT64_REF=123]="DT_UINT64_REF"}(jd||(jd={})),function(e){var t;(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"}(Kd||(Kd={}));const qd={};function Xd(e){return qd[e]}function Yd(e,t,n,r,a){const s=t.inputParams[e];if(s&&void 0!==s.inputIndexStart){const e=s.inputIndexStart,o=0===s.inputIndexEnd?void 0:void 0===s.inputIndexEnd?e+1:s.inputIndexEnd;if("tensor"===s.type)return Qd(t.inputNames[s.inputIndexStart],n,r,a);if("tensors"===s.type)return t.inputNames.slice(e,o).map((e=>Qd(e,n,r,a)));const i=Qd(t.inputNames.slice(e)[0],n,r,a),u=i.dataSync();return"number"===s.type?u[0]:_t(i.shape,u)}const o=t.attrParams[e];return o&&o.value}function Qd(e,t,n,r){const[a,s]=ef(e);if(null!=r){const e=r.getHashTableHandleByName(a);if(null!=e)return e}const o=n.currentContextIds.find((e=>!!t[Zd(a,e)]));return void 0!==o?t[Zd(a,o)][s]:void 0}function Jd(e,t){const[n,r,a]=ef(e);return[Zd(n,t&&t.currentContextId),r,a]}function Zd(e,t){return t?`${e}-${t}`:e}function ef(e){const t=e.split(":");if(1===t.length)return[e,0,void 0];const n=t[0],r=3===t.length?t[1]:void 0;return[n,Number(t[t.length-1]),r]}function tf(e,t,n){let r=Yd("pad",e,t,n);if("explicit"===r){r=Yd("explicitPaddings",e,t,n);const a=[[0,0],[0,0],[0,0],[0,0]];for(let e=0;e<4;e++)a[e][0]=r[2*e],a[e][1]=r[2*e+1];return a}return r}function nf(e){return e.kept?e:$u(e)}var rf=Object.freeze({__proto__:null,json:[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),af=Object.freeze({__proto__:null,json:[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),sf=Object.freeze({__proto__:null,json:[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcatV2",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListLength",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}]},{tfOpName:"TensorListResize",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"size",type:"number"}]}]}),of=Object.freeze({__proto__:null,json:[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}]}),uf=Object.freeze({__proto__:null,json:[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomStandardNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}]}),lf=Object.freeze({__proto__:null,json:[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),cf=Object.freeze({__proto__:null,json:[{tfOpName:"LowerBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"UpperBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}]}),pf=Object.freeze({__proto__:null,json:[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}]}),hf=Object.freeze({__proto__:null,json:[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"InitializeTable",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]},{tfOpName:"InitializeTableV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]}]}),df=Object.freeze({__proto__:null,json:[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]},{tfOpName:"ImageProjectiveTransformV3",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"transforms",type:"tensor"},{start:2,name:"outputShape",type:"number[]"},{start:3,name:"fillValue",type:"number"}],attrs:[{tfName:"interpolation",name:"interpolation",type:"string"},{tfName:"fill_mode",name:"fillMode",type:"string"}]}]}),ff=Object.freeze({__proto__:null,json:[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),mf=Object.freeze({__proto__:null,json:[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]}]}),gf=Object.freeze({__proto__:null,json:[{tfOpName:"EuclideanNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",defaultValue:!1}]},{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}]}),yf=Object.freeze({__proto__:null,json:[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Cumprod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}]}),bf=Object.freeze({__proto__:null,json:[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}]}),_f=Object.freeze({__proto__:null,json:[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}]}),xf=Object.freeze({__proto__:null,json:[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}]}),vf=Object.freeze({__proto__:null,json:[{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}]}),wf=Object.freeze({__proto__:null,json:[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}]});class Tf{constructor(){const e=[].concat(...[rf,af,sf,of,uf,lf,cf,pf,hf,df,ff,mf,gf,yf,bf,_f,xf,vf,wf].map((e=>e.json)));this.opMappers=e.reduce(((e,t)=>(e[t.tfOpName]=t,e)),{})}static get Instance(){return this._instance||(this._instance=new this)}transformGraph(e,t={}){const n=e.node,r=[],a=[],s=[],o=n.reduce(((e,t)=>(e[t.name]=this.mapNode(t),t.op.startsWith("Placeholder")?r.push(e[t.name]):"Const"===t.op?a.push(e[t.name]):null!=t.input&&0!==t.input.length||s.push(e[t.name]),e)),{});let i=[];const u=[];let l={},c={};null!=t&&(l=this.mapSignatureEntries(t.inputs),c=this.mapSignatureEntries(t.outputs));const p=Object.keys(o);p.forEach((e=>{const t=o[e];t.inputNames.forEach(((e,n)=>{const[r,,a]=Jd(e),s=o[r];if(null!=s.outputs){const e=s.outputs.indexOf(a);if(-1!==e){const a=`${r}:${e}`;t.inputNames[n]=a}}t.inputs.push(s),s.children.push(t)}))})),0===Object.keys(c).length?p.forEach((e=>{const t=o[e];0===t.children.length&&u.push(t)})):Object.keys(c).forEach((e=>{const[t]=Jd(e),n=o[t];null!=n&&(n.signatureKey=c[e],u.push(n))})),Object.keys(l).length>0?Object.keys(l).forEach((e=>{const[t]=Jd(e),n=o[t];n&&(n.signatureKey=l[e],i.push(n))})):i=r;let h={};null!=e.library&&null!=e.library.function&&(h=e.library.function.reduce(((e,t)=>(e[t.signature.name]=this.mapFunction(t),e)),{}));const d={nodes:o,inputs:i,outputs:u,weights:a,placeholders:r,signature:t,functions:h};return s.length>0&&(d.initNodes=s),d}mapSignatureEntries(e){return Object.keys(e||{}).reduce(((t,n)=>(t[e[n].name]=n,t)),{})}mapNode(e){const t=Xd(e.op)||this.opMappers[e.op]||{};null==e.attr&&(e.attr={});const n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map((e=>e.startsWith("^")?e.slice(1):e)),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return null!=t.inputs&&(n.inputParams=t.inputs.reduce(((e,t)=>(e[t.name]={type:t.type,inputIndexStart:t.start,inputIndexEnd:t.end},e)),{})),null!=t.attrs&&(n.attrParams=t.attrs.reduce(((t,n)=>{const r=n.type;let a;switch(n.type){case"string":a=If(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=If(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":a=Of(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Of(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":a=Ef(e.attr,n.tfName,n.defaultValue||0),void 0===a&&n.tfDeprecatedName&&(a=Ef(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":a=Ff(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Ff(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":a=Sf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Sf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":a=Lf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Lf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":a=Mf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Mf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":a=Df(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Df(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":a=Af(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Af(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":a=Rf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Rf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":a=Cf(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Cf(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${n.type} for op: ${e.op}`)}return t[n.name]={value:a,type:r},t}),{})),n}mapFunction(e){const t=e.nodeDef,n=[];let r={};null!=t&&(r=t.reduce(((e,t)=>(e[t.name]=this.mapNode(t),"Const"===t.op&&n.push(e[t.name]),e)),{}));const a=[],s=[];e.signature.inputArg.forEach((e=>{const[t]=Jd(e.name),n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Nf(e.type),type:"dtype"}},children:[]};n.signatureKey=e.name,a.push(n),r[t]=n})),Object.keys(r).forEach((e=>{const t=r[e];t.inputNames.forEach(((e,n)=>{const[a,,s]=Jd(e),o=r[a];if(null!=o.outputs){const e=o.outputs.indexOf(s);if(-1!==e){const r=`${a}:${e}`;t.inputNames[n]=r}}t.inputs.push(o),o.children.push(t)}))}));const o=e.ret;e.signature.outputArg.forEach((e=>{const[t,n]=Jd(o[e.name]),a=r[t];null!=a&&(a.defaultOutput=n,s.push(a))}));const i=this.mapArgsToSignature(e);return{nodes:r,inputs:a,outputs:s,weights:n,placeholders:[],signature:i}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce(((e,t)=>(e[t.name]=this.mapArgToTensorInfo(t),e)),{}),outputs:e.signature.outputArg.reduce(((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t)),{})}}mapArgToTensorInfo(e,t){let n=e.name;return null!=t&&(n=t[n]),{name:n,dtype:e.type}}}function kf(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){const t=Ct().global;if(void 0!==t.atob)return t.atob(e);if(void 0!==_s)return new _s(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}(e);return t?n:n.toLowerCase()}function If(e,t,n,r=!1){const a=e[t];return null!=a?kf(a.s,r):n}function Sf(e,t,n){const r=e[t];return r?r.b:n}function Ef(e,t,n){const r=e[t]||{},a=null!=r.i?r.i:null!=r.f?r.f:n;return"number"==typeof a?a:parseInt(a,10)}function Nf(e){switch("string"==typeof e&&(e=jd[e]),e){case jd.DT_FLOAT:case jd.DT_HALF:return"float32";case jd.DT_INT32:case jd.DT_INT64:case jd.DT_INT8:case jd.DT_UINT8:return"int32";case jd.DT_BOOL:return"bool";case jd.DT_DOUBLE:return"float32";case jd.DT_STRING:return"string";default:return null}}function Cf(e,t,n){const r=e[t];return r&&r.func?r.func.name:n}function Af(e,t,n){const r=e[t];return r&&r.type?Nf(r.type):n}function Rf(e,t,n){const r=e[t];return r&&r.list&&r.list.type?r.list.type.map((e=>Nf(e))):n}function $f(e){if(!e.unknownRank)return null!=e.dim?e.dim.map((e=>"number"==typeof e.size?e.size:parseInt(e.size,10))):[]}function Mf(e,t,n){const r=e[t];return r&&r.shape?$f(r.shape):n}function Ff(e,t,n){const r=e[t];return r?((r.list.f&&r.list.f.length?r.list.f:r.list.i)||[]).map((e=>"number"==typeof e?e:parseInt(e,10))):n}function Of(e,t,n,r=!1){const a=e[t];return a&&a.list&&a.list.s?a.list.s.map((e=>kf(e,r))):n}function Df(e,t,n){const r=e[t];return r&&r.list&&r.list.shape?r.list.shape.map((e=>$f(e))):n}function Lf(e,t,n){const r=e[t];return r&&r.list&&r.list.b?r.list.b:n}class Pf{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map((e=>this.getInput(e))),null!=e.rawAttrs&&(this.attrs=Object.keys(e.rawAttrs).reduce(((e,t)=>(e[t]=this.getAttr(t),e)),{}))}getInput(e){return Qd(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(null!=n.tensor)return Qd(e,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return Ef(this.node.rawAttrs,e,t);if(null!=n.s)return If(this.node.rawAttrs,e,t);if(null!=n.b)return Sf(this.node.rawAttrs,e,t);if(null!=n.shape)return Mf(this.node.rawAttrs,e,t);if(null!=n.type)return Af(this.node.rawAttrs,e,t);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return Ff(this.node.rawAttrs,e,t);if(null!=n.list.s)return Of(this.node.rawAttrs,e,t);if(null!=n.list.shape)return Df(this.node.rawAttrs,e,t);if(null!=n.list.b)return Lf(this.node.rawAttrs,e,t);if(null!=n.list.type)return Rf(this.node.rawAttrs,e,t)}return t}}var Bf=Object.freeze({__proto__:null,abs:ru,acos:au,acosh:su,add:Zi,addN:ou,all:iu,any:uu,argMax:lu,argMin:cu,asin:pu,asinh:hu,atan:du,atan2:fu,atanh:mu,avgPool:Au,avgPool3d:Ru,basicLSTMCell:Lu,batchToSpaceND:Pu,batchNorm:Bu,batchNorm2d:Uu,batchNorm3d:zu,batchNorm4d:Vu,bincount:Wu,broadcastArgs:Hu,broadcastTo:Gu,buffer:ju,cast:fi,ceil:Ku,clipByValue:Xu,clone:$u,complex:co,concat:Mu,concat1d:Yu,concat2d:Qu,concat3d:Ju,concat4d:Zu,conv1d:tl,conv2d:el,conv2dTranspose:rl,conv3d:al,conv3dTranspose:ol,cos:il,cosh:ul,cumprod:ll,cumsum:cl,denseBincount:pl,depthToSpace:hl,depthwiseConv2d:dl,diag:fl,dilation2d:ml,div:tu,divNoNan:_l,dot:xl,einsum:vl,elu:wl,equal:gl,erf:Tl,euclideanNorm:zl,exp:Vl,expandDims:Wl,expm1:Hl,eye:jl,fill:qu,floor:Kl,floorDiv:eu,gather:ql,greater:Xl,greaterEqual:Yl,imag:Ti,isFinite:Ql,isInf:Jl,isNaN:Zl,leakyRelu:ec,less:tc,lessEqual:nc,linspace:function(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");const r={start:e,stop:t,num:n};return ts.runKernel("LinSpace",{},r)},localResponseNormalization:rc,log:ac,log1p:sc,logSigmoid:uc,logSoftmax:cc,logSumExp:pc,logicalAnd:hc,logicalNot:dc,logicalOr:fc,logicalXor:mc,lowerBound:function(e,t){return yc(e,t,"left")},matMul:mi,max:$l,maxPool:bc,maxPool3d:_c,maxPoolWithArgmax:xc,maximum:vc,mean:wc,meshgrid:function(e,t,{indexing:n="xy"}={}){if("xy"!==n&&"ij"!==n)throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(void 0===e)return[];let r=oo(e,"x","meshgrid",e instanceof Ba?e.dtype:"float32");if(void 0===t)return[r];let a=oo(t,"y","meshgrid",t instanceof Ba?t.dtype:"float32");const s=et(r.shape),o=et(a.shape);return"xy"===n?(r=Cu(r,[1,-1]),a=Cu(a,[-1,1]),[mi(kc([o,1],r.dtype),r),mi(a,kc([1,s],a.dtype))]):(r=Cu(r,[-1,1]),a=Cu(a,[1,-1]),[mi(r,kc([1,o],r.dtype)),mi(kc([s,1],a.dtype),a)])},min:Ml,minimum:Ic,mirrorPad:Sc,mod:Ec,moments:Nc,mul:nu,multiRNNCell:Cc,multinomial:Ac,neg:ki,notEqual:Rc,oneHot:gi,ones:kc,onesLike:$c,outerProduct:Mc,pad:Fc,pad1d:Oc,pad2d:Dc,pad3d:Lc,pad4d:Pc,pool:Uc,pow:Fl,prelu:zc,print:Vc,prod:Wc,raggedGather:Hc,raggedRange:Gc,raggedTensorToTensor:jc,rand:Kc,randomGamma:up,randomNormal:lp,randomStandardNormal:cp,randomUniform:pp,range:hp,real:Ii,reciprocal:dp,relu:fp,relu6:mp,reshape:Cu,reverse:gp,reverse1d:yp,reverse2d:bp,reverse3d:_p,reverse4d:xp,round:vp,rsqrt:wp,scalar:Ol,selu:Tp,separableConv2d:kp,setdiff1dAsync:async function(e,t){const n=oo(e,"x","setdiff1d"),r=oo(t,"y","setdiff1d");Qe(n.dtype===r.dtype,(()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`)),Qe(1===n.rank,(()=>`x should be 1D tensor, but got x (${n.shape}).`)),Qe(1===r.rank,(()=>`y should be 1D tensor, but got y (${r.shape}).`));const a=await n.data(),s=await r.data(),o=new Set(s);let i=0;for(let e=0;e<a.length;e++)o.has(a[e])||i++;const u=new Da([i],n.dtype),l=new Da([i],"int32");for(let e=0,t=0;e<a.length;e++)o.has(a[e])||(u.values[t]=a[e],l.values[t]=e,t++);return[u.toTensor(),l.toTensor()]},sigmoid:Fu,sign:Ip,sin:Sp,sinh:Ep,slice:Ou,slice1d:Np,slice2d:Cp,slice3d:Ap,slice4d:Rp,softmax:$p,softplus:ic,spaceToBatchND:Bc,fft:Mp,ifft:Fp,irfft:Op,rfft:Lp,split:Dp,sqrt:Dl,square:Ll,squaredDifference:Pp,squeeze:Bp,stack:Up,step:zp,stridedSlice:Vp,sub:lc,sum:Pl,tan:Wp,tanh:Du,tensor:ho,tensor1d:Hp,tensor2d:Gp,tensor3d:Ai,tensor4d:function(e,t,n){if(Ze(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");const r=ro(e,n);if(4!==r.length&&1!==r.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return po(e,t,r,n)},tensor5d:function(e,t,n){if(Ze(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");const r=ro(e,n);if(5!==r.length&&1!==r.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return po(e,t,r,n)},tensor6d:function(e,t,n){if(Ze(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");const r=ro(e,n);if(6!==r.length&&1!==r.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return po(e,t=t||r,r,n)},tile:Gl,topk:jp,truncatedNormal:Kp,unique:qp,unsortedSegmentSum:Xp,unstack:Yp,upperBound:function(e,t){return yc(e,t,"right")},variable:function(e,t=!0,n,r){return ts.makeVariable(e,t,n,r)},where:yl,whereAsync:Jp,zeros:Tc,zerosLike:bl,op:lo,OP_SCOPE_SUFFIX:uo,booleanMaskAsync:async function(e,t,n){const r=oo(e,"tensor","boolMask"),a=oo(t,"mask","boolMask","bool"),s=null==n?0:n,o=a.rank,i=r.shape;Qe(o>0,(()=>"mask cannot be scalar")),Je(i.slice(s,s+o),a.shape,"mask's shape must match the first K dimensions of tensor's shape,");let u=1;for(let e=s;e<s+o;e++)u*=i[e];const l=i.slice(0,s).concat([u],i.slice(s+o)),c=Cu(r,l),p=Cu(a,[-1]),h=await Jp(p),d=Bp(h,[1]),f=ql(c,d,s);return e!==r&&r.dispose(),t!==a&&a.dispose(),d.dispose(),c.dispose(),p.dispose(),h.dispose(),f},transpose:Si,norm:Ul,movingAverage:Zp,scatterND:eh,searchSorted:yc,sparseToDense:th,gatherND:nh,dropout:rh,enclosingPowerOfTwo:ah,cosineWindow:sh,inTopKAsync:async function(e,t,n=1){const r=oo(e,"predictions","inTopK"),a=oo(t,"targets","inTopK");Qe(r.rank>1,(()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`)),Qe(r.rank-1===a.rank,(()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${r.rank} and targets rank ${a.rank}`)),Je(r.shape.slice(0,r.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const s=r.shape[r.shape.length-1];Qe(n>0&&n<=s,(()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${n}`));const o=await r.data(),i=await a.data(),[u,l]=[o.length/s,s],c=lt("bool",u);for(let e=0;e<u;e++){const t=e*l,r=o.subarray(t,t+l),a=[];for(let e=0;e<r.length;e++)a.push({value:r[e],index:e});a.sort(((e,t)=>t.value-e.value)),c[e]=0;for(let t=0;t<n;t++)if(a[t].index===i[e]){c[e]=1;break}}return e!==r&&r.dispose(),t!==a&&a.dispose(),ho(c,a.shape,"bool")},image:od,linalg:id,losses:ud,spectral:ad,fused:gh,signal:sd,sparse:ld,string:cd});function Uf(e,t,n=""){if("number"!=typeof e&&"number"!=typeof t){Qe(e.length===t.length,(()=>n+` Shapes ${e} and ${t} must match`));for(let r=0;r<e.length;r++){const a=e[r],s=t[r];Qe(a<0||s<0||a===s,(()=>n+` Shapes ${e} and ${t} must match`))}}}function zf(e){return"number"!=typeof e&&!e.some((e=>e<0))}function Vf(e,t,n){let r=Wf(e,n);const a=!zf(r);if(a&&0===t.length)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${r}`);if(a&&t.forEach((e=>{r=Wf(e.shape,r)})),!zf(r))throw new Error(`Non-fully-defined elementShape: ${r}`);return r}function Wf(e,t){if("number"==typeof e)return t;if("number"==typeof t)return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);const n=[];for(let r=0;r<e.length;++r){const a=e[r],s=t[r];if(a>=0&&s>=0&&a!==s)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[r]=a>=0?a:s}return n}class Hf{constructor(e,t,n,r,a,s,o){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=r,this.identicalElementShapes=a,this.dynamicSize=s,this.clearAfterRead=o,this.tensors=[],this.closed_=!1,this.idTensor=Ol(0),xi(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach((t=>{null!=e&&e.has(t.tensor.id)||t.tensor.dispose()})),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);const t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map((e=>this.read(e)))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);const n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},\n because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=t.shape),Uf(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,xi(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach(((e,n)=>this.write(e,t[n])))}gather(e,t){if(t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let t=0;t<this.size();t++)e.push(t)}if(0===e.length)return ho([],[0].concat(this.elementShape));const n=this.readMany(e);return Uf(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),Up(n,0)}concat(e){if(e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(0===this.size())return ho([],[0].concat(this.elementShape));const t=[];for(let e=0;e<this.size();e++)t.push(e);const n=this.readMany(t);return Uf(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Mu(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);const n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,Yp(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0;const r=e.map((e=>(n+=e,n)));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);const a=0===n?0:t.size/n,s=[];bi((()=>{t=Cu(t,[1,n,a]);for(let n=0;n<e.length;++n){const o=[0,0===n?0:r[n-1],0],i=[1,e[n],a];s[n]=Cu(Ou(t,o,i),this.elementShape)}return s}));const o=[];for(let t=0;t<e.length;t++)o[t]=t;this.writeMany(o,s)}}class Gf{constructor(e,t,n,r=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,null!=e&&e.forEach((e=>{if(n!==e.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${e.dtype}`);Uf(t,e.shape,"TensorList shape mismatch: "),xi(e)})),this.idTensor=Ol(0),this.maxNumElements=r,xi(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Gf([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach((t=>{null!=e&&e.has(t.id)||t.dispose()})),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(-1!==n&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);Uf(e,this.elementShape,"TensorList shape mismatch: ");const r=Vf(this.elementShape,this.tensors,e);return bi((()=>{const e=this.tensors.map((e=>Cu(e,r)));return Up(e,0)}))}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(0===this.size())throw new Error("Trying to pop from an empty list.");const n=Vf(this.elementShape,this.tensors,e),r=this.tensors.pop();return r.kept=!1,Uf(r.shape,e,"TensorList shape mismatch: "),Cu(r,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Uf(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");xi(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(-1!==this.maxNumElements&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);const t=new Gf([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let n=0;n<Math.min(this.tensors.length,e);++n)t.tensors[n]=this.tensors[n];return t}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(null==this.tensors[e])throw new Error(`element at index ${e} is null.`);Uf(this.tensors[e].shape,t,"TensorList shape mismatch: ");const r=Vf(this.elementShape,this.tensors,t);return Cu(this.tensors[e],r)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||-1!==this.maxNumElements&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Uf(this.elementShape,t.shape,"TensorList shape mismatch: "),xi(t),null!=this.tensors[e]&&(this.tensors[e].kept=!1),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);Uf(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());const r=Vf(this.elementShape,this.tensors,n);return 0===e.length?ho([],[0].concat(r)):bi((()=>{const t=e.map((e=>Cu(this.tensors[e],r)));return Up(t,0)}))}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Uf(this.elementShape,t,"TensorList shape mismatch: ");const n=Vf(this.elementShape,this.tensors,t);return 0===this.size()?ho([],[0].concat(n)):bi((()=>{const e=this.tensors.map((e=>Cu(e,n)));return Mu(e,0)}))}}function jf(e,t,n){const[r,a]=Yd("fusedOps",e,t,n),s="biasadd"===r,o=!s,i="prelu"===a,u="fusedbatchnorm"===r,l=Yd("numArgs",e,t,n);if(s){if(i&&2!==l)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&s&&1!==l)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(u)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");const c=Yd("strides",e,t,n),p=tf(e,t,n),h=Yd("dataFormat",e,t,n).toUpperCase(),d=Yd("dilations",e,t,n);let[f,m]=Yd("args",e,t,n);return o&&(m=f,f=void 0),{stride:c,pad:p,dataFormat:h,dilations:d,biasArg:f,preluArg:m,activationFunc:a,leakyreluAlpha:Yd("leakyreluAlpha",e,t,n)}}function Kf(e,t,n){return{boxes:Yd("boxes",e,t,n),scores:Yd("scores",e,t,n),maxOutputSize:Yd("maxOutputSize",e,t,n),iouThreshold:Yd("iouThreshold",e,t,n),scoreThreshold:Yd("scoreThreshold",e,t,n),softNmsSigma:Yd("softNmsSigma",e,t,n)}}class qf{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=Ol(0),this.tensorMap=new Map,xi(this.handle)}get id(){return this.handle.id}clearAndClose(){this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Ol(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),bi((()=>{const e=Yp(t),r=n.length,a=e.length;Qe(r===a,(()=>`The number of elements doesn't match, keys has ${r} elements, the values has ${a} elements.`));for(let t=0;t<r;t++){const r=n[t],a=e[t];xi(a),this.tensorMap.set(r,a)}return this.handle}))}async find(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return bi((()=>{const e=[];for(let r=0;r<n.length;r++){const a=n[r],s=this.findWithDefault(a,t);e.push(s)}return Up(e)}))}findWithDefault(e,t){const n=this.tensorMap.get(e);return null!=n?n:t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);if(t.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`)}}function Xf(e,t,n,r,a=bi){const s=((e,t,n)=>{switch(e.category){case"arithmetic":return a((()=>((e,t,n,r=Bf)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[r.add(Yd("a",e,t,n),Yd("b",e,t,n))];case"AddN":return[r.addN(Yd("tensors",e,t,n))];case"FloorMod":case"Mod":return[r.mod(Yd("a",e,t,n),Yd("b",e,t,n))];case"Mul":return[r.mul(Yd("a",e,t,n),Yd("b",e,t,n))];case"RealDiv":case"Div":return[r.div(Yd("a",e,t,n),Yd("b",e,t,n))];case"DivNoNan":return[r.divNoNan(Yd("a",e,t,n),Yd("b",e,t,n))];case"FloorDiv":return[r.floorDiv(Yd("a",e,t,n),Yd("b",e,t,n))];case"Sub":return[r.sub(Yd("a",e,t,n),Yd("b",e,t,n))];case"Minimum":return[r.minimum(Yd("a",e,t,n),Yd("b",e,t,n))];case"Maximum":return[r.maximum(Yd("a",e,t,n),Yd("b",e,t,n))];case"Pow":return[r.pow(Yd("a",e,t,n),Yd("b",e,t,n))];case"SquaredDifference":return[r.squaredDifference(Yd("a",e,t,n),Yd("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"basic_math":return a((()=>((e,t,n,r=Bf)=>{switch(e.op){case"Abs":case"ComplexAbs":return[r.abs(Yd("x",e,t,n))];case"Acos":return[r.acos(Yd("x",e,t,n))];case"Acosh":return[r.acosh(Yd("x",e,t,n))];case"Asin":return[r.asin(Yd("x",e,t,n))];case"Asinh":return[r.asinh(Yd("x",e,t,n))];case"Atan":return[r.atan(Yd("x",e,t,n))];case"Atan2":return[r.atan2(Yd("x",e,t,n),Yd("y",e,t,n))];case"Atanh":return[r.atanh(Yd("x",e,t,n))];case"Ceil":return[r.ceil(Yd("x",e,t,n))];case"Complex":return[r.complex(Yd("real",e,t,n),Yd("imag",e,t,n))];case"Cos":return[r.cos(Yd("x",e,t,n))];case"Cosh":return[r.cosh(Yd("x",e,t,n))];case"Elu":return[r.elu(Yd("x",e,t,n))];case"Erf":return[r.erf(Yd("x",e,t,n))];case"Exp":return[r.exp(Yd("x",e,t,n))];case"Expm1":return[r.expm1(Yd("x",e,t,n))];case"Floor":return[r.floor(Yd("x",e,t,n))];case"Log":return[r.log(Yd("x",e,t,n))];case"Log1p":return[r.log1p(Yd("x",e,t,n))];case"Imag":return[r.imag(Yd("x",e,t,n))];case"Neg":return[r.neg(Yd("x",e,t,n))];case"Reciprocal":return[r.reciprocal(Yd("x",e,t,n))];case"Real":return[r.real(Yd("x",e,t,n))];case"Relu":return[r.relu(Yd("x",e,t,n))];case"Round":return[r.round(Yd("x",e,t,n))];case"Selu":return[r.selu(Yd("x",e,t,n))];case"Sigmoid":return[r.sigmoid(Yd("x",e,t,n))];case"Sin":return[r.sin(Yd("x",e,t,n))];case"Sign":return[r.sign(Yd("x",e,t,n))];case"Sinh":return[r.sinh(Yd("x",e,t,n))];case"Softplus":return[r.softplus(Yd("x",e,t,n))];case"Sqrt":return[r.sqrt(Yd("x",e,t,n))];case"Square":return[r.square(Yd("x",e,t,n))];case"Tanh":return[r.tanh(Yd("x",e,t,n))];case"Tan":return[r.tan(Yd("x",e,t,n))];case"ClipByValue":return[r.clipByValue(Yd("x",e,t,n),Yd("clipValueMin",e,t,n),Yd("clipValueMax",e,t,n))];case"Relu6":return[r.relu6(Yd("x",e,t,n))];case"Rsqrt":return[r.rsqrt(Qd(e.inputNames[0],t,n))];case"Prod":return[r.prod(Yd("x",e,t,n),Yd("axes",e,t,n))];case"LeakyRelu":return[r.leakyRelu(Yd("x",e,t,n),Yd("alpha",e,t,n))];case"Prelu":return[r.prelu(Yd("x",e,t,n),Yd("alpha",e,t,n))];case"IsNan":return[r.isNaN(Qd(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"control":return(async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const r=Yd("thenBranch",e,t,n),a=Yd("elseBranch",e,t,n),s=Yd("cond",e,t,n),o=Yd("args",e,t,n);return(await s.data())[0]?n.functionMap[r].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap):n.functionMap[a].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{const r=Yd("body",e,t,n),a=Yd("cond",e,t,n),s=Yd("args",e,t,n),o=await n.functionMap[a].executeFunctionAsync(s,n.tensorArrayMap,n.tensorListMap),i=s.map((e=>e.id));let u=await o[0].data();o.forEach((e=>{e.kept||-1!==i.indexOf(e.id)||e.dispose()}));let l=s;for(;u[0];){const e=l;l=await n.functionMap[r].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);const t=l.map((e=>e.id));e.forEach((e=>{e.kept||-1!==i.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()}));const s=await n.functionMap[a].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);u=await s[0].data(),s.forEach((e=>{e.kept||-1!==i.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()}))}return l}case"LoopCond":return[nf(Yd("pred",e,t,n))];case"Switch":{const r=Yd("pred",e,t,n);let a=Yd("data",e,t,n);return a.kept||(a=nf(a)),(await r.data())[0]?[void 0,a]:[a,void 0]}case"Merge":{const r=e.inputNames.find((e=>void 0!==Qd(e,t,n)));return r?[nf(Qd(r,t,n))]:void 0}case"Enter":{const r=Yd("frameName",e,t,n),a=Yd("tensor",e,t,n);return n.enterFrame(r),[nf(a)]}case"Exit":{const r=Yd("tensor",e,t,n);return n.exitFrame(),[nf(r)]}case"NextIteration":{const r=Yd("tensor",e,t,n);return n.nextIteration(),[nf(r)]}case"TensorArrayV3":{const r=Yd("size",e,t,n),a=Yd("dtype",e,t,n),s=Yd("elementShape",e,t,n),o=Yd("dynamicSize",e,t,n),i=Yd("clearAfterRead",e,t,n),u=Yd("identicalElementShapes",e,t,n),l=Yd("name",e,t,n),c=new Hf(l,a,r,s,u,o,i);return n.addTensorArray(c),[c.idTensor,Ol(1)]}case"TensorArrayWriteV3":{const r=Yd("tensorArrayId",e,t,n),a=Yd("index",e,t,n),s=Yd("tensor",e,t,n),o=n.getTensorArray(r.id);return o.write(a,s),[o.idTensor]}case"TensorArrayReadV3":{const r=Yd("tensorArrayId",e,t,n),a=Yd("index",e,t,n);return[n.getTensorArray(r.id).read(a)]}case"TensorArrayGatherV3":{const r=Yd("tensorArrayId",e,t,n),a=Yd("indices",e,t,n),s=Yd("dtype",e,t,n);return[n.getTensorArray(r.id).gather(a,s)]}case"TensorArrayScatterV3":{const r=Yd("tensorArrayId",e,t,n),a=Yd("indices",e,t,n),s=Yd("tensor",e,t,n),o=n.getTensorArray(r.id);return o.scatter(a,s),[o.idTensor]}case"TensorArrayConcatV3":{const r=Yd("tensorArrayId",e,t,n),a=n.getTensorArray(r.id),s=Yd("dtype",e,t,n);return[a.concat(s)]}case"TensorArraySplitV3":{const r=Yd("tensorArrayId",e,t,n),a=Yd("tensor",e,t,n),s=Yd("lengths",e,t,n),o=n.getTensorArray(r.id);return o.split(s,a),[o.idTensor]}case"TensorArraySizeV3":{const r=Yd("tensorArrayId",e,t,n);return[Ol(n.getTensorArray(r.id).size(),"int32")]}case"TensorArrayCloseV3":{const r=Yd("tensorArrayId",e,t,n),a=n.getTensorArray(r.id);return a.clearAndClose(),[a.idTensor]}case"TensorListSetItem":{const r=Yd("tensorListId",e,t,n),a=Yd("index",e,t,n),s=Yd("tensor",e,t,n),o=n.getTensorList(r.id);return o.setItem(a,s),[o.idTensor]}case"TensorListGetItem":{const r=Yd("tensorListId",e,t,n),a=Yd("index",e,t,n),s=Yd("elementShape",e,t,n),o=Yd("elementDType",e,t,n);return[n.getTensorList(r.id).getItem(a,s,o)]}case"TensorListScatterV2":case"TensorListScatter":{const r=Yd("indices",e,t,n),a=function(e,t,n,r){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);const a=Math.max(...t);if(null!=r&&-1!==r&&a>=r)throw new Error(`Max index must be < array size (${a} vs. ${r})`);const s=new Gf([],n,e.dtype,r),o=Yp(e,0);return t.forEach(((e,t)=>{s.setItem(e,o[t])})),s}(Yd("tensor",e,t,n),r,Yd("elementShape",e,t,n),Yd("numElements",e,t,n));return n.addTensorList(a),[a.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const r=Yd("elementShape",e,t,n),a=Yd("elementDType",e,t,n);let s;s="TensorListReserve"===e.op?"numElements":"maxNumElements";const o=Yd(s,e,t,n),i=function(e,t,n,r){return new Gf([],e,t,r)}(r,a,0,"TensorListReserve"===e.op?-1:o);return n.addTensorList(i),[i.idTensor]}case"TensorListGather":{const r=Yd("tensorListId",e,t,n),a=Yd("indices",e,t,n),s=Yd("elementShape",e,t,n),o=Yd("elementDType",e,t,n);return[n.getTensorList(r.id).gather(a,o,s)]}case"TensorListStack":{const r=Yd("tensorListId",e,t,n),a=Yd("elementShape",e,t,n),s=Yd("elementDType",e,t,n),o=Yd("numElements",e,t,n);return[n.getTensorList(r.id).stack(a,s,o)]}case"TensorListFromTensor":{const r=function(e,t,n){const r=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);Uf(e.shape.slice(1),t,"TensorList shape mismatch: ");const a=Yp(e);return new Gf(a,t,r)}(Yd("tensor",e,t,n),Yd("elementShape",e,t,n),Yd("elementDType",e,t,n));return n.addTensorList(r),[r.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const r=Yd("tensorListId",e,t,n),a=n.getTensorList(r.id),s=Yd("dtype",e,t,n),o=Yd("elementShape",e,t,n);return[a.concat(s,o)]}case"TensorListPushBack":{const r=Yd("tensorListId",e,t,n),a=Yd("tensor",e,t,n),s=n.getTensorList(r.id);return s.pushBack(a),[s.idTensor]}case"TensorListPopBack":{const r=Yd("tensorListId",e,t,n),a=Yd("elementShape",e,t,n),s=Yd("elementDType",e,t,n);return[n.getTensorList(r.id).popBack(a,s)]}case"TensorListSplit":{const r=Yd("tensor",e,t,n),a=Yd("elementShape",e,t,n),s=function(e,t,n){let r=0;const a=t.map((e=>(r+=e,r)));if(r!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n ${r}, and tensor's shape is: ${e.shape}`);const s=Wf(e.shape.slice(1),n),o=0===r?0:e.size/r,i=bi((()=>{const n=[];e=Cu(e,[1,r,o]);for(let r=0;r<t.length;++r){const i=[0,0===r?0:a[r-1],0],u=[1,t[r],o];n[r]=Cu(Ou(e,i,u),s)}return e.dispose(),n})),u=new Gf([],n,e.dtype,t.length);for(let e=0;e<i.length;e++)u.setItem(e,i[e]);return u}(r,Yd("lengths",e,t,n),a);return n.addTensorList(s),[s.idTensor]}case"TensorListLength":{const r=Yd("tensorListId",e,t,n);return[Ol(n.getTensorList(r.id).size(),"int32")]}case"TensorListResize":{const r=Yd("tensorListId",e,t,n),a=Yd("size",e,t,n),s=n.getTensorList(r.id).resize(a);return n.addTensorList(s),[s.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n);case"convolution":return a((()=>((e,t,n,r=Bf)=>{switch(e.op){case"Conv1D":{const a=Yd("stride",e,t,n),s=Yd("pad",e,t,n),o=Yd("dataFormat",e,t,n).toUpperCase(),i=Yd("dilation",e,t,n);return[r.conv1d(Yd("x",e,t,n),Yd("filter",e,t,n),a,s,o,i)]}case"Conv2D":{const a=Yd("strides",e,t,n),s=tf(e,t,n),o=Yd("dataFormat",e,t,n).toUpperCase(),i=Yd("dilations",e,t,n);return[r.conv2d(Yd("x",e,t,n),Yd("filter",e,t,n),[a[1],a[2]],s,o,[i[1],i[2]])]}case"_FusedConv2D":{const{stride:a,pad:s,dataFormat:o,dilations:i,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:p}=jf(e,t,n);return[r.fused.conv2d({x:Yd("x",e,t,n),filter:Yd("filter",e,t,n),strides:[a[1],a[2]],pad:s,dataFormat:o,dilations:[i[1],i[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:p})]}case"FusedDepthwiseConv2dNative":{const{stride:a,pad:s,dataFormat:o,dilations:i,biasArg:u,preluArg:l,activationFunc:c,leakyreluAlpha:p}=jf(e,t,n);return[r.fused.depthwiseConv2d({x:Yd("x",e,t,n),filter:Yd("filter",e,t,n),strides:[a[1],a[2]],pad:s,dataFormat:o,dilations:[i[1],i[2]],bias:u,activation:c,preluActivationWeights:l,leakyreluAlpha:p})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const a=Yd("outputShape",e,t,n),s=Yd("strides",e,t,n),o=tf(e,t,n);return[r.conv2dTranspose(Yd("x",e,t,n),Yd("filter",e,t,n),a,[s[1],s[2]],o)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const a=Yd("strides",e,t,n),s=tf(e,t,n),o=Yd("dilations",e,t,n),i=Yd("dataFormat",e,t,n).toUpperCase();return[r.depthwiseConv2d(Yd("input",e,t,n),Yd("filter",e,t,n),[a[1],a[2]],s,i,[o[1],o[2]])]}case"Conv3D":{const a=Yd("strides",e,t,n),s=Yd("pad",e,t,n),o=Yd("dataFormat",e,t,n).toUpperCase(),i=Yd("dilations",e,t,n);return[r.conv3d(Yd("x",e,t,n),Yd("filter",e,t,n),[a[1],a[2],a[3]],s,o,[i[1],i[2],i[3]])]}case"AvgPool":{const a=Yd("strides",e,t,n),s=Yd("pad",e,t,n),o=Yd("kernelSize",e,t,n);return[r.avgPool(Yd("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s)]}case"MaxPool":{const a=Yd("strides",e,t,n),s=Yd("pad",e,t,n),o=Yd("kernelSize",e,t,n);return[r.maxPool(Yd("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s)]}case"MaxPoolWithArgmax":{const a=Yd("strides",e,t,n),s=Yd("pad",e,t,n),o=Yd("kernelSize",e,t,n),i=Yd("includeBatchInIndex",e,t,n),{result:u,indexes:l}=r.maxPoolWithArgmax(Yd("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s,i);return[u,l]}case"AvgPool3D":{const a=Yd("strides",e,t,n),s=Yd("pad",e,t,n),o=Yd("kernelSize",e,t,n);return[r.avgPool3d(Yd("x",e,t,n),[o[1],o[2],o[3]],[a[1],a[2],a[3]],s)]}case"MaxPool3D":{const a=Yd("strides",e,t,n),s=Yd("pad",e,t,n),o=Yd("kernelSize",e,t,n);return[r.maxPool3d(Yd("x",e,t,n),[o[1],o[2],o[3]],[a[1],a[2],a[3]],s)]}case"Dilation2D":{const a=Yd("strides",e,t,n),s=Yd("pad",e,t,n),o=Yd("dilations",e,t,n),i=a[1],u=a[2],l=o[1],c=o[2];return[r.dilation2d(Yd("x",e,t,n),Yd("filter",e,t,n),[i,u],s,[l,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"creation":return a((()=>((e,t,n,r=Bf)=>{switch(e.op){case"Fill":{const a=Yd("shape",e,t,n),s=Yd("dtype",e,t,n),o=Yd("value",e,t,n);return[r.fill(a,o,s)]}case"LinSpace":{const a=Yd("start",e,t,n),s=Yd("stop",e,t,n),o=Yd("num",e,t,n);return[r.linspace(a,s,o)]}case"Multinomial":{const a=Yd("logits",e,t,n),s=Yd("numSamples",e,t,n),o=Yd("seed",e,t,n);return[r.multinomial(a,s,o)]}case"OneHot":{const a=Yd("indices",e,t,n),s=Yd("depth",e,t,n),o=Yd("onValue",e,t,n),i=Yd("offValue",e,t,n),u=Yd("dtype",e,t,n);return[r.oneHot(a,s,o,i,u)]}case"Ones":return[r.ones(Yd("shape",e,t,n),Yd("dtype",e,t,n))];case"OnesLike":return[r.onesLike(Yd("x",e,t,n))];case"RandomStandardNormal":return[r.randomStandardNormal(Yd("shape",e,t,n),Yd("dtype",e,t,n),Yd("seed",e,t,n))];case"RandomUniform":return[r.randomUniform(Yd("shape",e,t,n),Yd("minval",e,t,n),Yd("maxval",e,t,n),Yd("dtype",e,t,n))];case"Range":{const a=Yd("start",e,t,n),s=Yd("stop",e,t,n),o=Yd("step",e,t,n);return[r.range(a,s,o,Yd("dtype",e,t,n))]}case"TruncatedNormal":{const a=Yd("shape",e,t,n),s=Yd("mean",e,t,n),o=Yd("stdDev",e,t,n),i=Yd("seed",e,t,n);return[r.truncatedNormal(a,s,o,Yd("dtype",e,t,n),i)]}case"Zeros":return[r.zeros(Yd("shape",e,t,n),Yd("dtype",e,t,n))];case"ZerosLike":return[r.zerosLike(Yd("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"dynamic":return(async(e,t,n,r,a=Bf)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u,softNmsSigma:l}=Kf(e,t,n),c=await a.image.nonMaxSuppressionWithScoreAsync(r,s,o,i,u,l);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u}=Kf(e,t,n),l=Yd("padToMaxOutputSize",e,t,n),c=await a.image.nonMaxSuppressionPaddedAsync(r,s,o,i,u,l);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u}=Kf(e,t,n);return[await a.image.nonMaxSuppressionAsync(r,s,o,i,u)]}case"Where":{const r=a.cast(Yd("condition",e,t,n),"bool"),s=[await a.whereAsync(r)];return r.dispose(),s}case"ListDiff":return a.setdiff1dAsync(Yd("x",e,t,n),Yd("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n);case"evaluation":return a((()=>((e,t,n,r=Bf)=>{switch(e.op){case"LowerBound":{const a=Yd("sortedSequence",e,t,n),s=Yd("values",e,t,n);return[r.lowerBound(a,s)]}case"TopKV2":{const a=Yd("x",e,t,n),s=Yd("k",e,t,n),o=Yd("sorted",e,t,n),i=r.topk(a,s,o);return[i.values,i.indices]}case"UpperBound":{const a=Yd("sortedSequence",e,t,n),s=Yd("values",e,t,n);return[r.upperBound(a,s)]}case"Unique":{const a=Yd("x",e,t,n),s=r.unique(a);return[s.values,s.indices]}case"UniqueV2":{const a=Yd("x",e,t,n),s=Yd("axis",e,t,n),o=r.unique(a,s);return[o.values,o.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"image":return a((()=>((e,t,n,r=Bf)=>{switch(e.op){case"ResizeBilinear":{const a=Yd("images",e,t,n),s=Yd("size",e,t,n),o=Yd("alignCorners",e,t,n),i=Yd("halfPixelCenters",e,t,n);return[r.image.resizeBilinear(a,[s[0],s[1]],o,i)]}case"ResizeNearestNeighbor":{const a=Yd("images",e,t,n),s=Yd("size",e,t,n),o=Yd("alignCorners",e,t,n),i=Yd("halfPixelCenters",e,t,n);return[r.image.resizeNearestNeighbor(a,[s[0],s[1]],o,i)]}case"CropAndResize":{const a=Yd("image",e,t,n),s=Yd("boxes",e,t,n),o=Yd("boxInd",e,t,n),i=Yd("cropSize",e,t,n),u=Yd("method",e,t,n),l=Yd("extrapolationValue",e,t,n);return[r.image.cropAndResize(a,s,o,i,u,l)]}case"ImageProjectiveTransformV3":{const a=Yd("images",e,t,n),s=Yd("transforms",e,t,n),o=Yd("outputShape",e,t,n),i=Yd("fillValue",e,t,n),u=Yd("interpolation",e,t,n),l=Yd("fillMode",e,t,n);return[r.image.transform(a,s,u.toLowerCase(),l.toLowerCase(),i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"graph":return a((()=>((e,t,n,r=Bf)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const a=Yd("default",e,t,n);return[Qd(e.name,t,n)||a];case"Placeholder":return[Qd(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":case"Snapshot":return[nf(Yd("x",e,t,n))];case"IdentityN":return Yd("x",e,t,n).map((e=>nf(e)));case"Shape":return[r.tensor1d(Yd("x",e,t,n).shape,"int32")];case"ShapeN":return Yd("x",e,t,n).map((e=>r.tensor1d(e.shape)));case"Size":return[r.scalar(Yd("x",e,t,n).size,"int32")];case"Rank":return[r.scalar(Yd("x",e,t,n).rank,"int32")];case"NoOp":return[r.scalar(1)];case"Print":const s=Yd("x",e,t,n),o=Yd("data",e,t,n),i=Yd("message",e,t,n),u=Yd("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(i);for(let e=0;e<o.length;e++)console.log(Array.prototype.slice.call(o[e].dataSync()).slice(0,u));return[s];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"logical":return a((()=>((e,t,n,r=Bf)=>{switch(e.op){case"Equal":return[r.equal(Yd("a",e,t,n),Yd("b",e,t,n))];case"NotEqual":return[r.notEqual(Yd("a",e,t,n),Yd("b",e,t,n))];case"Greater":return[r.greater(Yd("a",e,t,n),Yd("b",e,t,n))];case"GreaterEqual":return[r.greaterEqual(Yd("a",e,t,n),Yd("b",e,t,n))];case"Less":return[r.less(Yd("a",e,t,n),Yd("b",e,t,n))];case"LessEqual":return[r.lessEqual(Yd("a",e,t,n),Yd("b",e,t,n))];case"LogicalAnd":return[r.logicalAnd(Yd("a",e,t,n),Yd("b",e,t,n))];case"LogicalNot":return[r.logicalNot(Yd("a",e,t,n))];case"LogicalOr":return[r.logicalOr(Yd("a",e,t,n),Yd("b",e,t,n))];case"Select":case"SelectV2":return[r.where(Yd("condition",e,t,n),Yd("a",e,t,n),Yd("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"matrices":return a((()=>((e,t,n,r=Bf)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[r.matMul(Yd("a",e,t,n),Yd("b",e,t,n),Yd("transposeA",e,t,n),Yd("transposeB",e,t,n))];case"Einsum":return[r.einsum(Yd("equation",e,t,n),...Yd("tensors",e,t,n))];case"Transpose":return[r.transpose(Yd("x",e,t,n),Yd("perm",e,t,n))];case"_FusedMatMul":const[a,s]=Yd("fusedOps",e,t,n),o="biasadd"===a,i="prelu"===s,u=Yd("numArgs",e,t,n),l=Yd("leakyreluAlpha",e,t,n);if(o){if(i&&2!==u)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&1!==u)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[c,p]=Yd("args",e,t,n);return[r.fused.matMul({a:Yd("a",e,t,n),b:Yd("b",e,t,n),transposeA:Yd("transposeA",e,t,n),transposeB:Yd("transposeB",e,t,n),bias:c,activation:s,preluActivationWeights:p,leakyreluAlpha:l})];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"normalization":return a((()=>((e,t,n,r=Bf)=>{switch(e.op){case"EuclideanNorm":return[r.euclideanNorm(Yd("x",e,t,n),Yd("axis",e,t,n),Yd("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[r.batchNorm(Yd("x",e,t,n),Yd("mean",e,t,n),Yd("variance",e,t,n),Yd("offset",e,t,n),Yd("scale",e,t,n),Yd("epsilon",e,t,n))];case"LRN":return[r.localResponseNormalization(Yd("x",e,t,n),Yd("radius",e,t,n),Yd("bias",e,t,n),Yd("alpha",e,t,n),Yd("beta",e,t,n))];case"Softmax":return[r.softmax(Yd("x",e,t,n))];case"LogSoftmax":return[r.logSoftmax(Yd("x",e,t,n))];case"SparseToDense":return[r.sparseToDense(Yd("sparseIndices",e,t,n),Yd("outputShape",e,t,n),Yd("sparseValues",e,t,n),Yd("defaultValue",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"ragged":return a((()=>((e,t,n,r=Bf)=>{switch(e.op){case"RaggedGather":{const{outputNestedSplits:a,outputDenseValues:s}=r.raggedGather(Yd("paramsNestedSplits",e,t,n),Yd("paramsDenseValues",e,t,n),Yd("indices",e,t,n),Yd("outputRaggedRank",e,t,n));return a.concat(s)}case"RaggedRange":{const{rtNestedSplits:a,rtDenseValues:s}=r.raggedRange(Yd("starts",e,t,n),Yd("limits",e,t,n),Yd("splits",e,t,n));return[a,s]}case"RaggedTensorToTensor":return[r.raggedTensorToTensor(Yd("shape",e,t,n),Yd("values",e,t,n),Yd("defaultValue",e,t,n),Yd("rowPartitionTensors",e,t,n),Yd("rowPartitionTypes",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"reduction":return a((()=>((e,t,n,r=Bf)=>{switch(e.op){case"Max":{const a=Yd("axis",e,t,n),s=Yd("keepDims",e,t,n);return[r.max(Yd("x",e,t,n),a,s)]}case"Mean":{const a=Yd("axis",e,t,n),s=Yd("keepDims",e,t,n);return[r.mean(Yd("x",e,t,n),a,s)]}case"Min":{const a=Yd("axis",e,t,n),s=Yd("keepDims",e,t,n);return[r.min(Yd("x",e,t,n),a,s)]}case"Sum":{const a=Yd("axis",e,t,n),s=Yd("keepDims",e,t,n);return[r.sum(Yd("x",e,t,n),a,s)]}case"All":{const a=Yd("axis",e,t,n),s=Yd("keepDims",e,t,n);return[r.all(Yd("x",e,t,n),a,s)]}case"Any":{const a=Yd("axis",e,t,n),s=Yd("keepDims",e,t,n);return[r.any(Yd("x",e,t,n),a,s)]}case"ArgMax":{const a=Yd("axis",e,t,n);return[r.argMax(Yd("x",e,t,n),a)]}case"ArgMin":{const a=Yd("axis",e,t,n);return[r.argMin(Yd("x",e,t,n),a)]}case"Prod":{const a=Yd("axis",e,t,n),s=Yd("keepDims",e,t,n);return[r.prod(Yd("x",e,t,n),a,s)]}case"Cumprod":{const a=Yd("axis",e,t,n),s=Yd("exclusive",e,t,n),o=Yd("reverse",e,t,n);return[r.cumprod(Yd("x",e,t,n),a,s,o)]}case"Cumsum":{const a=Yd("axis",e,t,n),s=Yd("exclusive",e,t,n),o=Yd("reverse",e,t,n);return[r.cumsum(Yd("x",e,t,n),a,s,o)]}case"Bincount":const a=Yd("x",e,t,n),s=Yd("weights",e,t,n),o=Yd("size",e,t,n);return[r.bincount(a,s,o)];case"DenseBincount":{const a=Yd("x",e,t,n),s=Yd("weights",e,t,n),o=Yd("size",e,t,n),i=Yd("binaryOutput",e,t,n);return[r.denseBincount(a,s,o,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"slice_join":return a((()=>((e,t,n,r=Bf)=>{switch(e.op){case"ConcatV2":case"Concat":{const a=Yd("n",e,t,n),s=Yd("axis",e,t,n);let o=Yd("tensors",e,t,n);return o=o.slice(0,a),[r.concat(o,s)]}case"Gather":{const a=Yd("x",e,t,n),s=Yd("indices",e,t,n);return[r.gather(a,r.cast(s,"int32"),0)]}case"GatherV2":{const a=Yd("axis",e,t,n),s=Yd("batchDims",e,t,n),o=Yd("x",e,t,n),i=Yd("indices",e,t,n);return[r.gather(o,r.cast(i,"int32"),a,s)]}case"Reverse":{const a=Yd("dims",e,t,n),s=[];for(let e=0;e<a.length;e++)a[e]&&s.push(e);const o=Yd("x",e,t,n);return[r.reverse(o,s)]}case"ReverseV2":{const a=Yd("axis",e,t,n),s=Yd("x",e,t,n);return[r.reverse(s,a)]}case"Slice":{const a=Yd("begin",e,t,n),s=Yd("size",e,t,n);return[r.slice(Yd("x",e,t,n),a,s)]}case"StridedSlice":{const a=Yd("begin",e,t,n),s=Yd("end",e,t,n),o=Yd("strides",e,t,n),i=Yd("beginMask",e,t,n),u=Yd("endMask",e,t,n),l=Yd("ellipsisMask",e,t,n),c=Yd("newAxisMask",e,t,n),p=Yd("shrinkAxisMask",e,t,n),h=Yd("x",e,t,n);return[r.stridedSlice(h,a,s,o,i,u,l,c,p)]}case"Pack":return bi((()=>{const a=Yd("axis",e,t,n),s=Yd("tensors",e,t,n),o=s[0].shape,i=r.squeeze(s[0]).shape,u=s.map((e=>{const t=tt(e.shape,o);if(!t&&!tt(r.squeeze(e).shape,i))throw new Error("the input tensors shape does not match");return t?e:r.reshape(e,o)}));return[r.stack(u,a)]}));case"Unpack":{const a=Yd("axis",e,t,n),s=Yd("tensor",e,t,n);return r.unstack(s,a)}case"Tile":{const a=Yd("reps",e,t,n);return[r.tile(Yd("x",e,t,n),a)]}case"Split":case"SplitV":{const a=Yd("axis",e,t,n),s=Yd("numOrSizeSplits",e,t,n),o=Yd("x",e,t,n);return r.split(o,s,a)}case"ScatterNd":{const a=Yd("indices",e,t,n),s=Yd("values",e,t,n),o=Yd("shape",e,t,n);return[r.scatterND(a,s,o)]}case"GatherNd":{const a=Yd("x",e,t,n),s=Yd("indices",e,t,n);return[r.gatherND(a,s)]}case"SparseToDense":{const a=Yd("sparseIndices",e,t,n),s=Yd("outputShape",e,t,n),o=Yd("sparseValues",e,t,n),i=Yd("defaultValue",e,t,n);return[r.sparseToDense(a,o,s,o.dtype===i.dtype?i:r.cast(i,o.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"sparse":return a((()=>((e,t,n,r=Bf)=>{switch(e.op){case"SparseFillEmptyRows":{const{outputIndices:a,outputValues:s,emptyRowIndicator:o,reverseIndexMap:i}=r.sparse.sparseFillEmptyRows(Yd("indices",e,t,n),Yd("values",e,t,n),Yd("denseShape",e,t,n),Yd("defaultValue",e,t,n));return[a,s,o,i]}case"SparseReshape":{const{outputIndices:a,outputShape:s}=r.sparse.sparseReshape(Yd("inputIndices",e,t,n),Yd("inputShape",e,t,n),Yd("newShape",e,t,n));return[a,s]}case"SparseSegmentMean":return[r.sparse.sparseSegmentMean(Yd("data",e,t,n),Yd("indices",e,t,n),Yd("segmentIds",e,t,n))];case"SparseSegmentSum":return[r.sparse.sparseSegmentSum(Yd("data",e,t,n),Yd("indices",e,t,n),Yd("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"spectral":return a((()=>((e,t,n,r=Bf)=>{switch(e.op){case"FFT":return[r.fft(Yd("x",e,t,n))];case"IFFT":return[r.ifft(Yd("x",e,t,n))];case"RFFT":return[r.rfft(Yd("x",e,t,n))];case"IRFFT":return[r.irfft(Yd("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"string":return a((()=>((e,t,n,r=Bf)=>{switch(e.op){case"StringNGrams":{const{nGrams:a,nGramsSplits:s}=r.string.stringNGrams(Yd("data",e,t,n),Yd("dataSplits",e,t,n),Yd("separator",e,t,n),Yd("nGramWidths",e,t,n),Yd("leftPad",e,t,n),Yd("rightPad",e,t,n),Yd("padWidth",e,t,n),Yd("preserveShortSequences",e,t,n));return[a,s]}case"StringSplit":{const{indices:a,values:s,shape:o}=r.string.stringSplit(Yd("input",e,t,n),Yd("delimiter",e,t,n),Yd("skipEmpty",e,t,n));return[a,s,o]}case"StringToHashBucketFast":return[r.string.stringToHashBucketFast(Yd("input",e,t,n),Yd("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"transformation":return a((()=>((e,t,n,r=Bf)=>{switch(e.op){case"Cast":return[r.cast(Yd("x",e,t,n),Yd("dtype",e,t,n))];case"ExpandDims":{const a=Yd("axis",e,t,n);return[r.expandDims(Yd("x",e,t,n),a)]}case"Squeeze":{const a=Yd("axis",e,t,n);return[r.squeeze(Yd("x",e,t,n),a)]}case"Reshape":return[r.reshape(Yd("x",e,t,n),Yd("shape",e,t,n))];case"MirrorPad":return[r.mirrorPad(Yd("x",e,t,n),Yd("padding",e,t,n),Yd("mode",e,t,n))];case"PadV2":case"Pad":return[r.pad(Yd("x",e,t,n),Yd("padding",e,t,n),Yd("constantValue",e,t,n))];case"SpaceToBatchND":{const a=Yd("blockShape",e,t,n),s=Yd("paddings",e,t,n);return[r.spaceToBatchND(Yd("x",e,t,n),a,s)]}case"BatchToSpaceND":{const a=Yd("blockShape",e,t,n),s=Yd("crops",e,t,n);return[r.batchToSpaceND(Yd("x",e,t,n),a,s)]}case"DepthToSpace":{const a=Yd("blockSize",e,t,n),s=Yd("dataFormat",e,t,n).toUpperCase();return[r.depthToSpace(Yd("x",e,t,n),a,s)]}case"BroadcastTo":return[r.broadcastTo(Yd("x",e,t,n),Yd("shape",e,t,n))];case"BroadcastArgs":return[r.broadcastArgs(Yd("s0",e,t,n),Yd("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"hash_table":return(async(e,t,n,r)=>{switch(e.op){case"HashTable":case"HashTableV2":{const a=r.getHashTableHandleByName(e.name);if(null!=a)return[a];{const a=Yd("keyDType",e,t,n),s=Yd("valueDType",e,t,n),o=new qf(a,s);return r.addHashTable(e.name,o),[o.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{const a=Yd("tableHandle",e,t,n,r),s=Yd("keys",e,t,n),o=Yd("values",e,t,n),i=r.getHashTableById(a.id);return[await i.import(s,o)]}case"LookupTableFind":case"LookupTableFindV2":{const a=Yd("tableHandle",e,t,n,r),s=Yd("keys",e,t,n),o=Yd("defaultValue",e,t,n),i=r.getHashTableById(a.id);return[await i.find(s,o)]}case"LookupTableSize":case"LookupTableSizeV2":{const a=Yd("tableHandle",e,t,n,r);return[r.getHashTableById(a.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n,r);case"custom":const s=Xd(e.op);if(s&&s.customExecutor)return s.customExecutor(new Pf(e,t,n));throw TypeError(`Custom op ${e.op} is not registered.`);default:throw TypeError(`Unknown op '${e.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return It(s)?s.then((e=>[].concat(e))):[].concat(s)}class Yf{constructor(e={},t={},n={},r={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=r,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){const e=[];for(let t=0;t<this.contexts.length-1;t++){const n=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(n))}e.push(""),this._currentContextIds=e}contextIdforContexts(e){return e?e.map((e=>0===e.id&&0===e.iterationId?"":`${e.frameName}-${e.iterationId}`)).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(!(this.contexts&&this.contexts.length>1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()}nextIteration(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");{this.contexts=this.contexts.slice(),this.lastId++;const e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(const t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(const t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}}function Qf(e,t,n,r){const a=new Set,s=[];let o=null,i=null;const u=new Set,l=Object.keys(e).map((e=>ef(e)[0]));let c=[];null!=r&&(c=r.map((e=>ef(e.name)[0])));const p=[...t];for(;p.length>0;){const e=p.pop();(tm(e)||nm(e)||rm(e))&&null==o&&(o=e,i=o.children.map((e=>e.name)).filter((e=>a.has(e)))),a.add(e.name),null==n[e.name]&&-1===l.indexOf(e.name)&&-1===c.indexOf(e.name)&&(0!==e.inputs.length?e.inputs.forEach((e=>{u.has(e.name)||(u.add(e.name),p.push(e))})):s.push(e.name))}return{inputs:e,outputs:t,usedNodes:a,missingInputs:s,dynamicNode:o,syncInputs:i}}const Jf=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],Zf=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],em=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function tm(e){return Jf.indexOf(e.op)>=0}function nm(e){return Zf.indexOf(e.op)>=0}function rm(e){return em.indexOf(e.op)>=0}class am{constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._functions={},this._functionExecutorMap={},this.keepIntermediateTensors=!1,this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,null!=e.functions&&Object.keys(e.functions).forEach((t=>{this._functionExecutorMap[t]=new am(e.functions[t],this)}))}get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){const t=Object.keys(e).map((t=>e[t].map((e=>e.id))));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map((e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0})))}get outputs(){return this._outputs.map((e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0})))}get inputNodes(){return this._inputs.map((e=>e.signatureKey||e.name))}get outputNodes(){return this._outputs.map((e=>{const t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t}))}get functions(){return Object.keys(this._functions).reduce(((e,t)=>(e[t]=this._functions[t].signature,e)),{})}getCompilationKey(e,t){const n=e.map((e=>e.name)).sort(),r=t.map((e=>e.name)).sort();return n.join(this.SEPERATOR)+"--"+r.join(this.SEPERATOR)}compile(e,t){const n=Qf(e,t,this.weightMap,this._initNodes),{missingInputs:r,dynamicNode:a,syncInputs:s}=n;if(null!=a)throw new Error(`This execution contains the node '${a.name}', which has the dynamic op '${a.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${s}]`);if(r.length>0){const n=t.map((e=>e.name)),a=Object.keys(e);throw new Error(`Cannot compute the outputs [${n}] from the provided inputs [${a}]. Missing the following inputs: [${r}]`)}return function(e,t,n){const{usedNodes:r,inputs:a}=n,s=[],o=Object.keys(a).map((e=>ef(e)[0])).map((t=>e.nodes[t])),i=e.initNodes;o.forEach((e=>{r.has(e.name)&&s.push(e)})),e.weights.forEach((e=>{r.has(e.name)&&s.push(e)})),null!=i&&i.forEach((e=>{r.has(e.name)&&s.push(e)}));const u=new Set,l=[];for(;s.length>0;){const e=s.pop();u.add(e.name),t[e.name]||l.push(e),e.children.forEach((e=>{!u.has(e.name)&&r.has(e.name)&&e.inputs.every((e=>u.has(e.name)))&&s.push(e)}))}return l}(this.graph,this.weightMap,n)}cloneAndKeepTensor(e){if(null==e)return null;const t=e.clone();return xi(t),t}cloneTensorList(e){return e?e.map((e=>this.cloneAndKeepTensor(e))):null}cloneTensorMap(e){return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,this.cloneTensorList(t)])))}execute(e,t){this.disposeIntermediateTensors(),e=this.mapInputs(e);const n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);const r=n.map((e=>this.graph.nodes[ef(e)[0]])),a=t.map((e=>ef(e)[0]));let s=a.map((e=>this.graph.nodes[e]));0===s.length&&(s=this._outputs);const o=this.getCompilationKey(r,s);let i=this.compiledMap.get(o);null==i&&(i=this.compile(e,s),this.compiledMap.set(o,i));try{this.keepIntermediateTensors=Ct().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const u={},l={};return bi((()=>{const n=new Yf(this.weightMap,u,l,this.functionExecutorMap),r=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(e).forEach((t=>{const[n,a]=ef(t),s=[];s[a]=e[t],r[n]=s,this.keepIntermediateTensors&&(this.clonedTensorsMap[n]=this.cloneTensorList(s))}));const s=this.getFrozenTensorIds(r),o={};for(let e=0;e<i.length;e++){const t=i[e];if(!r[t.name]){const e=Xf(t,r,n,this._resourceManager);if(It(e))throw new Error(`The execution of the op '${t.op}' returned a promise. Please use model.executeAsync() instead.`);r[t.name]=e,this.keepIntermediateTensors&&(this.clonedTensorsMap[t.name]=this.cloneTensorList(e)),this.checkTensorForDisposal(t.name,t,r,n,s,a,o)}}return null==this.parent&&n.dispose(s),t.map((e=>Qd(e,r,n)))}))}getFrozenTensorIds(e){const t=[].concat.apply([],Object.keys(e).map((t=>e[t])).map((e=>e.map((e=>e.id)))));return new Set(t)}checkTensorForDisposal(e,t,n,r,a,s,o){"control"!==t.category&&-1===s.indexOf(e)&&(n[e].forEach((e=>{null!=e&&(o[e.id]=(o[e.id]||0)+t.children.length)})),t.inputs.forEach((e=>{if("control"!==e.category){const t=function(e,t,n){return t[Zd(e,n.currentContextId)]}(e.name,n,r);null!=t&&t.forEach((e=>{if(e&&!e.kept&&!a.has(e.id)){const t=o[e.id];1===t?(e.dispose(),delete o[e.id]):null!=t&&o[e.id]--}}))}})))}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){this.clonedTensorsMap&&(Object.values(this.clonedTensorsMap).forEach((e=>{for(const t of e)t&&!t.isDisposed&&t.dispose()})),this.clonedTensorsMap=null)}getIntermediateTensors(){return this.clonedTensorsMap}async _executeAsync(e,t,n=!1,r={},a={}){this.disposeIntermediateTensors(),n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepIntermediateTensors=Ct().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const s=new Yf(this.weightMap,r,a,this.functionExecutorMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));const o=await this.executeWithControlFlow(e,s,t,n),i=t.map((e=>Qd(e,o,s))),u=i.map((e=>e.id)),l=Object.keys(e).map((t=>e[t].id)),c=new Set([...u,...l,...this.weightIds]);return Object.values(o).forEach((e=>{e.forEach((e=>{!e||e.isDisposed||c.has(e.id)||e.dispose()}))})),null==this.parent&&s.dispose(c),i}async executeFunctionAsync(e,t,n){const r=e.reduce(((e,t,n)=>(e[this.inputs[n].name]=t,e)),{});return this._executeAsync(r,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,r){const a=Object.keys(e),s=a.map((e=>this.graph.nodes[ef(e)[0]])),o=n.map((e=>ef(e)[0]));let i=o.map((e=>this.graph.nodes[e]));0===i.length&&(i=this._outputs);const{usedNodes:u,missingInputs:l,dynamicNode:c,syncInputs:p}=Qf(e,i,this.weightMap,this._initNodes),h=[...s,...this.graph.weights,...this._initNodes||[]].map((e=>({node:e,contexts:t.currentContext}))),d=Object.assign({},this.weightMap);Object.keys(e).forEach((t=>{const[n,r]=ef(t),a=[];a[r]=e[t],d[n]=a}));const f={},m=this.getFrozenTensorIds(d),g={};for(;h.length>0;){const e=this.processStack(s,h,t,d,g,m,o,f,u);await Promise.all(e)}null!=c||r||console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");const y=i.filter((e=>!tm(e)&&!Qd(e.name,d,t))).map((e=>e.name));if(y.length>0){let e="";throw null!=c&&(e=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${p}]`),new Error(`Cannot compute the outputs [${y}] from the provided inputs [${a}]. Consider providing the following inputs: [${l}]. ${e}`)}return d}processStack(e,t,n,r,a,s,o,i,u){const l=[];for(;t.length>0;){const e=t.pop();n.currentContext=e.contexts;let c="";if("Enter"===e.node.op&&Yd("isConstant",e.node,r,n)&&([c]=Jd(e.node.name,n)),null==r[e.node.name]){const p=Xf(e.node,r,n,this._resourceManager);c||([c]=Jd(e.node.name,n));const h=n.currentContext;It(p)?l.push(p.then((l=>(r[c]=l,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(l)),n.currentContext=h,this.checkTensorForDisposal(c,e.node,r,n,s,o,i),this.processChildNodes(e.node,t,n,r,a,u),l)))):(r[c]=p,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(p)),this.checkTensorForDisposal(c,e.node,r,n,s,o,i),this.processChildNodes(e.node,t,n,r,a,u))}else this.processChildNodes(e.node,t,n,r,a,u)}return l}processChildNodes(e,t,n,r,a,s){e.children.forEach((e=>{const[o]=Jd(e.name,n);!a[o]&&s.has(e.name)&&("Merge"===e.op?e.inputNames.some((e=>!!Qd(e,r,n)))&&(a[o]=!0,t.push({contexts:n.currentContext,node:e})):e.inputNames.every((e=>!!Qd(e,r,n)))&&(a[o]=!0,t.push({contexts:n.currentContext,node:e})))}))}dispose(){Object.keys(this.weightMap).forEach((e=>this.weightMap[e].forEach((e=>e.dispose()))))}checkInputShapeAndType(e){Object.keys(e).forEach((t=>{const n=e[t],[r]=ef(t),a=this.graph.nodes[r];if(a.attrParams.shape&&a.attrParams.shape.value){const e=a.attrParams.shape.value;Qe(e.length===n.shape.length&&n.shape.every(((t,n)=>-1===e[n]||e[n]===t)),(()=>`The shape of dict['${a.name}'] provided in model.execute(dict) must be [${e}], but was [${n.shape}]`))}a.attrParams.dtype&&a.attrParams.dtype.value&&Qe(n.dtype===a.attrParams.dtype.value,(()=>`The dtype of dict['${a.name}'] provided in model.execute(dict) must be ${a.attrParams.dtype.value}, but was ${n.dtype}`))}))}mapInputs(e){var t,n;const r={};for(const a in e){const s=null===(n=null===(t=this._signature)||void 0===t?void 0:t.inputs)||void 0===n?void 0:n[a];null!=s?r[s.name]=e[a]:r[a]=e[a]}return r}checkInputs(e){const t=Object.keys(e).filter((e=>{const[t]=ef(e);return null==this.graph.nodes[t]}));if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map((e=>{var t,n;const r=null===(n=null===(t=this._signature)||void 0===t?void 0:t.outputs)||void 0===n?void 0:n[e];return null!=r?r.name:e}),{})}checkOutputs(e){e.forEach((e=>{const[t]=ef(e);if(!this.graph.nodes[t])throw new Error(`The output '${e}' is not found in the graph`)}))}}class sm{constructor(e={},t={}){this.hashTableNameToHandle=e,this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(const e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(const e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}}class om{constructor(e,t={},n=di){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=n,null==t&&(this.loadOptions={}),this.resourceManager=new sm}get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}get modelStructuredOutputKeys(){return this.structuredOutputKeys}findIOHandler(){const e=this.modelUrl;if(null!=e.load)this.handler=e;else if(null!=this.loadOptions.requestInit)this.handler=this.io.browserHTTPRequest(e,this.loadOptions);else{const t=this.io.getLoadHandlers(e,this.loadOptions);if(0===t.length)t.push(this.io.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}load(){if(this.findIOHandler(),null==this.handler.load)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const e=this.handler.load();return It(e)?e.then((e=>this.loadSync(e))):this.loadSync(e)}loadSync(e){this.artifacts=e;const t=this.artifacts.modelTopology;let n=this.artifacts.signature;if(null!=this.artifacts.userDefinedMetadata){const e=this.artifacts.userDefinedMetadata;null!=e.signature&&(n=e.signature),null!=e.structuredOutputKeys&&(this.structuredOutputKeys=e.structuredOutputKeys)}this.signature=n,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;const r=this.io.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new am(Tf.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(r),this.executor.resourceManager=this.resourceManager,null!=e.modelInitializer&&null!=e.modelInitializer.node){const t=Tf.Instance.transformGraph(e.modelInitializer);this.initializer=new am(t),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializerSignature=e.initializerSignature}return!0}async save(e,t){if("string"==typeof e){const t=this.io.getSaveHandlers(e);if(0===t.length)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Error(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}if(null==e.save)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}addStructuredOutputNames(e){if(this.structuredOutputKeys){const t={};return(e instanceof Ba?[e]:e).forEach(((e,n)=>t[this.structuredOutputKeys[n]]=e)),t}return e}predict(e,t){const n=this.execute(e,this.outputNodes);return this.addStructuredOutputNames(n)}async predictAsync(e,t){const n=await this.executeAsync(e,this.outputNodes);return this.addStructuredOutputNames(n)}normalizeInputs(e){var t;if(!(e instanceof Ba||Array.isArray(e))){const n=null===(t=this.signature)||void 0===t?void 0:t.inputs;if(null!=n)for(const t in n){const r=n[t];null!=r.resourceId&&(e[t]=this.resourceIdToCapturedInput[r.resourceId])}return e}e=Array.isArray(e)?e:[e];const n=Object.keys(this.resourceIdToCapturedInput).length;if(e.length+n!==this.inputNodes.length)throw new Error(`Input tensor count mismatch, the graph model has ${this.inputNodes.length-n} non-resource placeholders, while there are ${e.length} input tensors provided.`);let r=0;return this.inputNodes.reduce(((t,n)=>{var a,s,o;const i=null===(o=null===(s=null===(a=this.signature)||void 0===a?void 0:a.inputs)||void 0===s?void 0:s[n])||void 0===o?void 0:o.resourceId;return t[n]=null!=i?this.resourceIdToCapturedInput[i]:e[r++],t}),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}executeInitializerGraph(){return null==this.initializer?[]:null==this.initializerSignature?this.initializer.execute({},[]):this.initializer.execute({},Object.keys(this.initializerSignature.outputs))}async executeInitializerGraphAsync(){return null==this.initializer?[]:null==this.initializerSignature?this.initializer.executeAsync({},[]):this.initializer.executeAsync({},Object.keys(this.initializerSignature.outputs))}setResourceIdToCapturedInput(e){if(this.resourceIdToCapturedInput={},this.initializerSignature){const t=this.initializerSignature.outputs,n=Object.keys(t);for(let r=0;r<n.length;r++){const a=t[n[r]];this.resourceIdToCapturedInput[a.resourceId]=e[r]}}}execute(e,t){null==this.resourceIdToCapturedInput&&this.setResourceIdToCapturedInput(this.executeInitializerGraph()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){null==this.resourceIdToCapturedInput&&this.setResourceIdToCapturedInput(await this.executeInitializerGraphAsync()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce(((t,n)=>(t[n]=[e[n]],t)),{})}dispose(){this.executor.dispose(),this.initializer&&(this.initializer.dispose(),this.resourceIdToCapturedInput&&_i(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}}async function im(e,t={},n=di){if(null==e)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");null==t&&(t={}),t.fromTFHub&&"string"==typeof e&&(e=function(e){return e.endsWith("/")||(e+="/"),`${e}model.json?tfjs-format=file`}(e));const r=new om(e,t,n);return await r.load(),r}function um(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&Qe("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the CPU backend.`))}))}const lm=Qp;class cm extends je{constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new Ge(this,yi())}nextDataId(){return cm.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,Ct().get("IS_NODE")&&Cr("\n============================\nHi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details. \n============================"));const r={id:this.nextDataId()};return this.data.set(r,{values:e,dtype:n,refCount:1}),r}makeTensorInfo(e,t,n){let r;if("string"===t&&null!=n&&n.length>0&&dt(n[0])){const a=n.map((e=>ka(e)));r=this.write(a,e,t)}else r=this.write(n,e,t);return{dataId:r,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){this.data.get(e).refCount++}decRef(e){this.data.has(e)&&this.data.get(e).refCount--}move(e,t,n,r,a){this.data.set(e,{values:t,dtype:r,refCount:a})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);return"complex64"===t?Sd(this.readSync(n.real.dataId),this.readSync(n.imag.dataId)):function(e,t){if(Array.isArray(e))return e;if("float32"===t)return e instanceof Float32Array?e:new Float32Array(e);if("int32"===t)return e instanceof Int32Array?e:new Int32Array(e);if("bool"===t||"string"===t)return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}(this.data.get(e).values,t)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map((e=>Ia(e)));return ju(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return ju(e.shape,e.dtype,t)}makeOutput(e,t,n){return yi().makeTensorFromTensorInfo(this.makeTensorInfo(t,n,e),this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;const{complexTensorInfos:n}=this.data.get(e);null!=n&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){const t=Ta();return e(),{kernelMs:Ta()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){um([e],"where");const t=this.readSync(e.dataId);return lm(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}function pm(e){return(t,n,r,a,s)=>{const o=Ci(t,n),i=o.length,u=yt(o),l=lt(s,et(o)),c=t.length,p=n.length,h=yt(t),d=yt(n),f=Ei(t,o),m=Ei(n,o);if(f.length+m.length===0)for(let t=0;t<l.length;++t)l[t]=e(r[t%r.length],a[t%a.length]);else for(let t=0;t<l.length;++t){const n=kt(t,i,u),s=n.slice(-c);f.forEach((e=>s[e]=0));const o=Tt(s,c,h),g=n.slice(-p);m.forEach((e=>g[e]=0));const y=Tt(g,p,d);l[t]=e(r[o],a[y])}return[l,o]}}function hm(e){const{inputs:t,backend:n}=e,{real:r,imag:a}=t,s=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values,i=n.makeTensorInfo(r.shape,"complex64");return n.data.get(i.dataId).complexTensorInfos={real:n.makeTensorInfo(r.shape,"float32",s),imag:n.makeTensorInfo(a.shape,"float32",o)},i}function dm(e,t,n="float32"){if("complex64"===n)return hm({inputs:{real:dm(e,t,"float32"),imag:dm(e,t,"float32")},backend:e});const r=vt(et(t),n);return e.makeTensorInfo(t,n,r)}function fm(e){const{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}cm.nextDataId=0;const mm={kernelName:mn,backendName:"cpu",kernelFunc:fm};function gm(e){const{inputs:t,backend:n}=e,{input:r}=t,a=n.data.get(r.dataId).complexTensorInfos.real,s=n.data.get(a.dataId).values;return n.makeTensorInfo(a.shape,a.dtype,s)}function ym(e,t,n,r){if("int32"===r)return[t,"int32",Int32Array.from(e)];if("bool"===r){const r=wa([0],n),[a,s]=pm(((e,t)=>e!==t?1:0))(t,[],e,r,"bool");return[s,"bool",a]}throw new Error(`Error in Cast: failed to cast ${n} to ${r}`)}function bm(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dtype:s}=r;if("complex64"===s){if("complex64"===a.dtype)return fm({inputs:{x:a},backend:n});const e=dm(n,a.shape,a.dtype),t=bm({inputs:{x:a},backend:n,attrs:{dtype:"float32"}}),r=hm({inputs:{real:t,imag:e},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),r}if("complex64"===a.dtype){const e=gm({inputs:{input:a},backend:n}),t=bm({inputs:{x:e},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(e),t}if(!pt(a.dtype,s)){const e=fm({inputs:{x:a},backend:n});return{dataId:e.dataId,shape:e.shape,dtype:s}}const o=n.data.get(a.dataId).values,[i,u,l]=ym(o,a.shape,a.dtype,s);return n.makeTensorInfo(i,u,l)}const _m={kernelName:Vt,backendName:"cpu",kernelFunc:bm};function xm(e,t,n,r){return null==n?({inputs:n,backend:a})=>{const{a:s,b:o}=n,i=a;um([s,o],e);const u=i.data.get(s.dataId).values,l=i.data.get(o.dataId).values,c="string"===s.dtype?zd(u):u,p="string"===s.dtype?zd(l):l,h=r||s.dtype,[d,f]=t(s.shape,o.shape,c,p,h);return i.makeTensorInfo(f,h,d)}:({inputs:e,backend:a})=>{const{a:s,b:o}=e,i=a;if("complex64"===s.dtype||"complex64"===o.dtype){const e=bm({inputs:{x:s},backend:i,attrs:{dtype:"complex64"}}),t=i.data.get(e.dataId),r=t.complexTensorInfos.real,a=t.complexTensorInfos.imag,u=i.data.get(r.dataId).values,l=i.data.get(a.dataId).values,c=bm({inputs:{x:o},backend:i,attrs:{dtype:"complex64"}}),p=i.data.get(c.dataId),h=p.complexTensorInfos.real,d=p.complexTensorInfos.imag,f=i.data.get(h.dataId).values,m=i.data.get(d.dataId).values,[g,y,b]=n(s.shape,o.shape,u,l,f,m),_=i.makeTensorInfo(b,"float32",g),x=i.makeTensorInfo(b,"float32",y),v=hm({inputs:{real:_,imag:x},backend:i});return i.disposeIntermediateTensorInfo(e),i.disposeIntermediateTensorInfo(c),i.disposeIntermediateTensorInfo(_),i.disposeIntermediateTensorInfo(x),v}{const e=i.data.get(s.dataId).values,n=i.data.get(o.dataId).values,a=r||s.dtype,[u,l]=t(s.shape,o.shape,e,n,a);return i.makeTensorInfo(l,a,u)}}}function vm(e){return(t,n,r,a,s,o)=>{const i=Ci(t,n),u=et(i),l=i.length,c=yt(i),p=lt("float32",u),h=lt("float32",u),d=Ei(t,i),f=Ei(n,i),m=Sd(r,a),g=Sd(s,o),y=t.length,b=yt(t),_=n.length,x=yt(n);if(d.length+f.length===0)for(let t=0;t<p.length;t++){const n=t%m.length,r=t%g.length,a=e(m[2*n],m[2*n+1],g[2*r],g[2*r+1]);p[t]=a.real,h[t]=a.imag}else for(let t=0;t<p.length;t++){const n=kt(t,l,c),r=n.slice(-y);d.forEach((e=>r[e]=0));const a=Tt(r,y,b),s=n.slice(-_);f.forEach((e=>s[e]=0));const o=Tt(s,_,x),i=e(m[2*a],m[2*a+1],g[2*o],g[2*o+1]);p[t]=i.real,h[t]=i.imag}return[p,h,i]}}const wm=pm(((e,t)=>e+t)),Tm=vm(((e,t,n,r)=>({real:e+n,imag:t+r}))),km=xm(Ft,wm,Tm),Im={kernelName:Ft,backendName:"cpu",kernelFunc:km};function Sm(e){return(t,n,r)=>{const a=lt(n,t.length);for(let n=0;n<t.length;++n)a[n]=e(t[n],r);return a}}function Em(e,t,n){return({inputs:r,attrs:a,backend:s})=>{const{x:o}=r;if(um(o,e),"string"===o.dtype||"string"===n)throw new Error("unaryKernelFunc does not support string input/output");const i=s,u=i.data.get(o.dataId).values,l=et(o.shape),c=n||o.dtype,p=ct(c,l);for(let e=0;e<l;++e)p[e]=t(u[e],a);return i.makeTensorInfo(o.shape,c,p)}}const Nm=Sm((e=>Math.ceil(e)));function Cm(e,t,n,r){const a=ct(n,et(t));if(r&&"string"!==n){let t=0;e.forEach((e=>{const n=et(e.shape);a.set(e.vals,t),t+=n}))}else{let r=0;e.forEach((e=>{const s="string"===n?zd(e.vals):e.vals;let o=0;for(let n=0;n<e.shape[0];++n){const i=n*t[1]+r;for(let t=0;t<e.shape[1];++t)a[i+t]=s[o++]}r+=e.shape[1]}))}return a}const Am=pm(((e,t)=>e===t?1:0)),Rm=Sm((e=>Math.exp(e))),$m=(Mm=Rm,"float32",({inputs:e,attrs:t,backend:n})=>{const{x:r}=e;if(um(r,"Exp"),"string"===r.dtype)throw new Error("unaryKernelFunc does not support string input/output");const a=n,s=a.data.get(r.dataId).values,o="float32",i=Mm(s,o,t);return a.makeTensorInfo(r.shape,o,i)});var Mm;const Fm=Sm((e=>Math.expm1(e))),Om=Sm((e=>Math.floor(e))),Dm=pm(((e,t)=>e>t?1:0)),Lm=pm(((e,t)=>e>=t?1:0)),Pm=pm(((e,t)=>e<t?1:0)),Bm=pm(((e,t)=>e<=t?1:0)),Um=Sm((e=>Math.log(e)));function zm(e,t,n,r){const a=lt(r,et(n));for(let n=0;n<a.length;++n){const r=n*t;let s=e[r];for(let n=0;n<t;++n){const t=e[r+n];(Number.isNaN(t)||t>s)&&(s=t)}a[n]=s}return a}const Vm=pm(((e,t)=>Math.max(e,t))),Wm=pm(((e,t)=>Math.min(e,t))),Hm=pm(((e,t)=>e*t)),Gm=vm(((e,t,n,r)=>({real:e*n-t*r,imag:e*r+t*n}))),jm=xm(An,Hm,Gm),Km={kernelName:An,backendName:"cpu",kernelFunc:jm},qm=pm(((e,t)=>e!==t?1:0));function Xm(e,t,n,r,a){const s=t.length,o=et(t),i=yt(t),u=yt(a),l=lt(n,et(a));for(let t=0;t<o;++t){const n=kt(t,s,i),a=new Array(n.length);for(let e=0;e<a.length;e++)a[e]=n[r[e]];l[Tt(a,s,u)]=e[t]}return l}function Ym(e){const{inputs:t,attrs:n,backend:r}=e,{x:a}=t,{perm:s}=n;um(a,"transpose");const o=a.shape.length,i=new Array(o);for(let e=0;e<i.length;e++)i[e]=a.shape[s[e]];const u=Xm(r.data.get(a.dataId).values,a.shape,a.dtype,s,i);return{dataId:r.write(u,i,a.dtype),shape:i,dtype:a.dtype}}function Qm(e,t){const n=e.slice(0,t);for(;n.length<t;)n.push(1);for(let r=t;r<e.length;r++)n[t-1]*=e[r];return n}var Jm=fd;class Zm{constructor(e,t,n,r,a,s,o,i,u,l){this.shape=e,this.shapeShape=t,this.values=n,this.valuesShape=r,this.valuesDType=a,this.defaultValue=s,this.defaultValueShape=o,this.rowPartitionValues=i,this.rowPartitionValuesShapes=u,this.rowPartitionTypes=gd(l),this.raggedRank=yd(this.rowPartitionTypes)}getRowPartitionTypeByDimension(e){return this.rowPartitionTypes[0]===Jm.FIRST_DIM_SIZE?this.rowPartitionTypes[e+1]:this.rowPartitionTypes[e]}getRowPartitionTensor(e){return this.rowPartitionTypes[0]===Jm.FIRST_DIM_SIZE?this.rowPartitionValues[e+1]:this.rowPartitionValues[e]}getMaxWidth(e){const t=this.getRowPartitionTensor(e-1);switch(this.getRowPartitionTypeByDimension(e-1)){case Jm.VALUE_ROWIDS:return Zm.getMaxWidthValueRowID(t);case Jm.ROW_SPLITS:return Zm.getMaxWidthRowSplit(t);default:throw new Error(`Cannot handle partition type ${Jm[this.getRowPartitionTypeByDimension(e-1)]}`)}}static getMaxWidthRowSplit(e){const t=e.length;if(0===t||1===t)return 0;let n=0;for(let r=0;r<t-1;++r){const t=e[r+1]-e[r];t>n&&(n=t)}return n}static getMaxWidthValueRowID(e){const t=e.length;if(0===t)return 0;let n=0,r=e[0],a=0;for(let s=1;s<t;++s){const t=e[s];t!==r&&(r=t,a=Math.max(s-n,a),n=s)}return Math.max(t-n,a)}tensorShapeFromTensor(e,t,n=!0){if(0===t.length){if(-1===e[0])return[];throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.")}return tg(e,n)}calculateOutputSize(e){const t=this.valuesShape;bd(this.defaultValueShape,t);const n=this.tensorShapeFromTensor(this.shape,this.shapeShape),r=md(this.raggedRank,n,t);r[0]<0&&(r[0]=e);for(let e=1;e<=this.raggedRank;++e)r[e]<0&&(r[e]=this.getMaxWidth(e));return r}calculateFirstParentOutputIndex(e,t,n){const r=Math.min(e,n),a=[];let s=0;for(let e=0;e<r;++e,s+=t)a.push(s);for(let t=r;t<e;++t)a.push(-1);return Qe(a.length===e,(()=>"Final length of result must be equal to firstDimension.")),a}calculateOutputIndexRowSplit(e,t,n,r){const a=e.length,s=[];for(let o=0;o<a-1;++o){const a=e[o+1]-e[o];let i=Math.min(r,a),u=t[o];-1===u&&(i=0);for(let e=0;e<i;++e)s.push(u),u+=n;for(let e=0;e<a-i;++e)s.push(-1)}if(a>0&&s.length!==e[a-1])throw new Error("Invalid row split size.");return s}calculateOutputIndexValueRowID(e,t,n,r){const a=e.length,s=[];if(0===a)return[];let o=0,i=e[0];if(i>=t.length)throw new Error(`Got currentValueRowId=${i}, which is not less than ${t.length}`);let u=t[i];s.push(u);for(let l=1;l<a;++l){const a=e[l];if(a===i)u>=0&&(++o,o<r?u+=n:u=-1);else{if(o=0,i=a,a>=t.length)throw new Error(`Got nextValueRowId=${a} which is not less than ${t.length}`);u=t[a]}s.push(u)}if(s.length!==e.length)throw new Error("Invalid row ids.");return s}calculateOutputIndex(e,t,n,r){const a=this.getRowPartitionTensor(e),s=this.getRowPartitionTypeByDimension(e);switch(s){case Jm.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(a,t,n,r);case Jm.ROW_SPLITS:if(a.length-1>t.length)throw new Error(`Row partition size is greater than output size: ${a.length-1} > ${t.length}`);return this.calculateOutputIndexRowSplit(a,t,n,r);default:throw new Error(`Unsupported partition type: ${Jm[s]}`)}}getFirstDimensionSize(){const e=this.rowPartitionValues[0];if(0===this.rowPartitionTypes.length)throw new Error("No row_partition_types given.");const t=this.rowPartitionTypes[0];switch(t){case Jm.FIRST_DIM_SIZE:return e[0];case Jm.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case Jm.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${Jm[t]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");const e=this.getFirstDimensionSize(),t=this.calculateOutputSize(e),n=new Array(this.raggedRank+1);n[n.length-1]=1;for(let e=n.length-2;e>=0;--e)n[e]=n[e+1]*t[e+1];const r=tg(t,!1),a=ct(this.valuesDType,et(r));if(n[0]*t[0]>0){let s=this.calculateFirstParentOutputIndex(e,n[0],t[0]);for(let e=1;e<=this.raggedRank;++e)s=this.calculateOutputIndex(e-1,s,n[e],t[e]);this.setOutput(this.raggedRank,s,a,r)}return[r,a]}setOutput(e,t,n,r){if(0===n.length)return;const a=this.values,s=n;let o=r.slice();o=o.slice(e+1);const i=et(o),u=t.length;let l=this.defaultValue;if(l.length!==i&&1!==l.length){const e=this.defaultValueShape;bi((()=>{const t=Cu(l,e),n=Gu(t,o);l=n.dataSync()}))}let c=0,p=0,h=0;for(let e=0;e<=u;++e){let r=e<u?t[e]:-1;if(r!==h){if(p<h){const e=a.subarray(c*i);eg(s.subarray(p*i),e,(h-p)*i)}if(e>=u){const e=n.length;r=Math.floor(e/i)}if(r>h)if(1===this.defaultValue.length)s.subarray(h*i,r*i).fill(this.defaultValue[0]),h=r;else for(;r>h;)eg(s.slice(h*i),l,i),++h;r<0?(c=e+1,p=h):(c=e,p=h,h=p+1)}else++h}}}function eg(e,t,n){for(let r=0;r<n;r++)e[r]=t[r]}function tg(e,t){const n=[];for(let r of e){if(r<0){if(!t)throw new Error(`Dimension ${r} must be >= 0`);if(r<-1)throw new Error(`Dimension ${r} must be >= -1`);r=-1}n.push(r)}return n}function ng(e,t,n,r){if(e===t||e<t&&n<0||t<e&&n>1)return vt(0,r);const a=vt(Math.abs(Math.ceil((t-e)/n)),r);t<e&&1===n&&(n=-1),a[0]=e;for(let e=1;e<a.length;e++)a[e]=a[e-1]+n;return a}const rg=Sm((e=>1/Math.sqrt(e))),ag=Sm((e=>1/(1+Math.exp(-e)))),sg=Em(er,(e=>1/(1+Math.exp(-e)))),og={kernelName:er,backendName:"cpu",kernelFunc:sg};function ig(e,t,n,r,a){const s=Ki(r,t,n),o=et(n),i=yt(r);if(s){const n=qi(t,i);return"string"===a?e.slice(n,n+o):e.subarray(n,n+o)}const u=ju(r,a,"string"===a?zd(e):e),l=ju(n,a);for(let e=0;e<l.size;++e){const n=l.indexToLoc(e),r=n.map(((e,n)=>e+t[n]));l.set(u.get(...r),...n)}return"string"===a?Vd(l.values):l.values}function ug(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,size:o}=r;um(a,"slice");const[i,u]=Xi(a,s,o);Li(a,i,u);const l=ig(n.data.get(a.dataId).values,i,u,a.shape,a.dtype);return n.makeTensorInfo(u,a.dtype,l)}const lg={kernelName:Zn,backendName:"cpu",kernelFunc:ug},cg=Sm((e=>Math.sqrt(e))),pg=pm(((e,t)=>{const n=e-t;return n*n}));function hg(e,t,n,r){const a=ju(e,t.dtype);for(let e=0;e<a.size;e++){const s=a.indexToLoc(e),o=new Array(s.length);for(let e=0;e<o.length;e++)o[e]=s[e]*n[e]+r[e];a.set(t.get(...o),...s)}return a}class dg{constructor(e,t,n,r,a,s){this.separator=ka(e),this.nGramWidths=t,this.leftPad=ka(n),this.rightPad=ka(r),this.padWidth=a,this.preserveShort=s}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){const n=this.getPadWidth(t);return Math.max(0,e+2*n-t+1)}createNGrams(e,t,n,r,a,s){for(let o=0;o<a;++o){const i=this.getPadWidth(s),u=Math.max(0,i-o),l=Math.max(0,i-(a-(o+1))),c=s-(u+l),p=t+(u>0?0:o-i);let h=0;h+=u*this.leftPad.length;for(let t=0;t<c;++t)h+=e[p+t].length;h+=l*this.rightPad.length,h+=(u+l+c-1)*this.separator.length,n[r+o]=new Uint8Array(h);const d=n[r+o];let f=0;const m=e=>e.forEach((e=>d[f++]=e));for(let e=0;e<u;++e)m(this.leftPad),m(this.separator);for(let t=0;t<c-1;++t)m(e[p+t]),m(this.separator);if(c>0){m(e[p+c-1]);for(let e=0;e<l;++e)m(this.separator),m(this.rightPad)}else{for(let e=0;e<l-1;++e)m(this.rightPad),m(this.separator);m(this.rightPad)}}}compute(e,t){const n=e.length,r=t.length;if(r>0){let e=t[0];if(0!==e)throw new Error(`First split value must be 0, got ${e}`);for(let a=1;a<r;++a){let r=t[a]>=e;if(r=r&&t[a]<=n,!r)throw new Error(`Invalid split value ${t[a]}, must be in [${e}, ${n}]`);e=t[a]}if(e!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${e}`)}const a=r-1,s=ct("int32",r);if(0===n||0===r){const e=new Array(n);for(let e=0;e<=a;++e)s[e]=0;return[e,s]}s[0]=0;for(let e=1;e<=a;++e){const n=t[e]-t[e-1];let r=0;this.nGramWidths.forEach((e=>{r+=this.getNumNGrams(n,e)})),this.preserveShort&&n>0&&0===r&&(r=1),s[e]=s[e-1]+r}const o=new Array(s[a]);for(let n=0;n<a;++n){const r=t[n];let a=s[n];if(this.nGramWidths.forEach((s=>{const i=t[n+1]-t[n],u=this.getNumNGrams(i,s);this.createNGrams(e,r,o,a,u,s),a+=u})),this.preserveShort&&a===s[n]){const s=t[n+1]-t[n];if(0===s)continue;const i=s+2*this.padWidth,u=1;this.createNGrams(e,r,o,a,u,i)}}return[o,s]}}function fg(e,t,n,r,a,s,o,i){return new dg(n,r,a,s,o,i).compute(e,t)}function mg(e,t,n,r){if(!e.length)return;if(0===t.length){for(let t=0;t<e.length;++t)r.push(e.subarray(t,t+1));return}if(1===t.length){const a=t[0];let s=e.indexOf(a);for(;-1!==s;){const t=e.subarray(0,s);n&&0===t.length||r.push(t),s=(e=e.subarray(s+1)).indexOf(a)}return void(n&&0===e.length||r.push(e))}let a=0;for(let s=0;s<e.length+1;s++)if(s===e.length||-1!==t.indexOf(e[s])){const t=e.subarray(a,s);n&&0===t.length||r.push(t),a=s+1}}function gg(e,t,n){const r=e.length,a=[];let s=0,o=0;const i=new Array(r);for(let u=0;u<r;++u){const r=a.length;mg(e[u],t,n,a);const l=a.length-r;i[u]=l,s+=l,o=Math.max(o,l)}const u=ct("int32",2*s),l=new Array(s),c=[r,o];let p=0;for(let e=0;e<r;++e)for(let t=0;t<i[e];++t)u[2*p]=e,u[2*p+1]=t,l[p]=a[p],++p;return[u,l,c]}function yg(e,t){const n=ct("int32",e.length);for(let r=0;r<e.length;++r)n[r]=xa(e[r]).modulo(t).getLowBitsUnsigned();return n}const bg=pm(((e,t)=>e-t)),_g=vm(((e,t,n,r)=>({real:e-n,imag:t-r}))),xg=xm(mr,bg,_g),vg={kernelName:mr,backendName:"cpu",kernelFunc:xg},wg=(e,t)=>{const n=t.value-e.value;return 0===n?e.index-t.index:n};function Tg(e,t,n=0,r=e.length-1){for(;r>n;){if(r-n>600){const a=r-n+1,s=t-n+1,o=Math.log(a),i=.5*Math.exp(2*o/3),u=.5*Math.sqrt(o*i*(a-i)/a)*Math.sign(s-a/2);Tg(e,t,Math.max(n,Math.floor(t-s*i/a+u)),Math.min(r,Math.floor(t+(a-s)*i/a+u)))}const a=e[t];let s=n,o=r;for(Ye(e,n,t),wg(e[r],a)>0&&Ye(e,n,r);s<o;){for(Ye(e,s,o),s++,o--;wg(e[s],a)<0;)s+=1;for(;wg(e[o],a)>0;)o-=1}0===wg(e[n],a)?Ye(e,n,o):(o+=1,Ye(e,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}}var kg=Object.freeze({__proto__:null,simpleAbsImpl:function(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t},addImpl:wm,bincountImpl:function(e,t,n,r,a){const s=et(r),o=vt(a,n);for(let n=0;n<e.length;n++){const r=e[n];if(r<0)throw new Error("Input x must be non-negative!");r>=a||(o[r]+=s>0?t[n]:1)}return o},bincountReduceImpl:function(e,t,n,r=!1){const a=e.shape[0],s=e.shape[1],o=ju([a,n],t.dtype);for(let i=0;i<a;i++)for(let a=0;a<s;a++){const s=e.get(i,a);if(s<0)throw new Error("Input x must be non-negative!");s>=n||(r?o.set(1,i,s):t.size>0?o.set(o.get(i,s)+t.get(i,a),i,s):o.set(o.get(i,s)+1,i,s))}return o},castImpl:ym,ceilImpl:Nm,concatImpl:Cm,equalImpl:Am,expImpl:Rm,expm1Impl:Fm,floorImpl:Om,gatherNdImpl:function(e,t,n,r,a,s,o,i,u){const l=ju([r,s],n);for(let n=0;n<r;n++){const r=[];let c=0;for(let t=0;t<a;t++){const s=e[n*a+t];c+=s*o[t],r.push(s)}if(c<0||c>=u/s)throw new Error(`Invalid indices: ${r} does not index into ${i}`);for(let e=0;e<s;e++)l.values[n*s+e]=t.get(...t.indexToLoc(c*s+e))}return l},gatherV2Impl:function(e,t,n){const r=ju(n,e.dtype);for(let n=0;n<r.size;++n){const a=r.indexToLoc(n).slice(),s=a[0],o=a[2],i=t.locToIndex([s,o]);a[2]=t.values[i];const u=e.locToIndex(a);0<=u&&u<e.values.length&&(r.values[n]=e.values[u])}return r},greaterImpl:Dm,greaterEqualImpl:Lm,lessImpl:Pm,lessEqualImpl:Bm,linSpaceImpl:function(e,t,n){const r=(t-e)/(n-1),a=vt(n,"float32");a[0]=e;for(let e=1;e<a.length;e++)a[e]=a[e-1]+r;return a},logImpl:Um,maxImpl:zm,maximumImpl:Vm,minimumImpl:Wm,multiplyImpl:Hm,negImpl:function(e,t,n){const r=va(-1,n);return Hm([],t,r,e,n)},notEqualImpl:qm,prodImpl:function(e,t,n,r){const[a,s]=Sl(e,r),o=Ka(t,"int32"),i=vt(et(a),o),u=et(s);for(let e=0;e<i.length;++e){const t=e*u;let r=1;for(let e=0;e<u;++e)r*=n[t+e];i[e]=r}return{outVals:i,outShape:a,outDtype:o}},raggedGatherImpl:function(e,t,n,r,a,s,o,i){if(0===e.length)throw new Error("paramsNestedSplits must be non empty");if(0===t[0].length)throw new Error("Split tensors must not be scalars");if(function(e,t,n){e.forEach(((e,r)=>{if(e<0||e>=n){const a=kt(r,t.length,yt(t)).join(",");throw new Error(`indices[${a}] = ${e} is not in [0, ${n})`)}}))}(s,o,t[0][0]-1),0===r.length)throw new Error("params.rank must be nonzero");const u=r[0],{outSplits:l,valueSlices:c,numValues:p}=function(e,t,n,r){const a=[];let s=0;const o=t.length-1+n.length,i=new Array(o).fill(null).map((()=>[0]));!function(e,t){for(let n=0;n<e.length;++n){const r=e[n],a=n===e.length-1?t:e[n+1].length;if(0===r.length)throw new Error("Ragged splits may not be empty");if(r[0]<0)throw new Error("Ragged splits must be non-negative");if(r[r.length-1]>a)throw new Error("Ragged splits must not point past values");for(let e=1;e<r.length;++e)if(r[e-1]>r[e])throw new Error("Ragged splits must be sorted in ascending order")}}(n,r);let u=1;for(let e=0;e<t.length-1;++e){u*=t[e];const n=t[e+1];for(let t=1;t<u+1;++t)i[e].push(t*n)}for(let r=0;r<e.length;++r){let o=e[r],u=e[r]+1;for(let e=0;e<n.length;++e){const r=n[e],a=e+t.length-1;if(a>=0){const e=i[a],t=e[e.length-1]-r[o];for(let e=o;e<u;++e)i[a].push(r[e+1]+t)}o=r[o],u=r[u]}u!==o&&(a.push([o,u]),s+=u-o)}return{outSplits:i,valueSlices:a,numValues:s}}(s,o,e,u),h=function(e){const t=[];for(let n=0;n<e.length;++n){const r=ct("int32",e[n].length);t.push(r),e[n].forEach(((e,t)=>r[t]=e))}return t}(l),d=function(e,t,n,r,a){const s=t.slice();s[0]=a;const o=ct(n,et(s)),i=e.length;return function(e,t,n,r,a,s){const o=Qm(t,2)[1],i=Qm(s,2)[1];let u=0;for(const t of n)for(let n=t[0];n<t[1];++n){for(let t=0;t<r;++t)a[u*i+t]=e[n*o+t];++u}}(e,t,r,0===i?0:i/t[0],o,s),[o,s]}(n,r,a,c,p);return[h,d[0],d[1]]},raggedRangeImpl:function(e,t,n,r,a,s,o){if(t.length>1)throw new Error("starts must be a scalar or vector");if(a.length>1)throw new Error("limits must be a scalar or vector");if(o.length>1)throw new Error("deltas must be a scalar or vector");const i=0===t.length,u=0===a.length,l=0===o.length,c=[];i||c.push(t[0]),u||c.push(a[0]),l||c.push(o[0]);for(let e=1;e<c.length;++e)if(c[e]!==c[e-1])throw new Error("starts, limits, and deltas must have the same shape");const p=0===c.length?1:c[0],h=ct("int32",p+1);h[0]=0;for(let t=0;t<p;++t){const n=i?e[0]:e[t],a=u?r[0]:r[t],o=l?s[0]:s[t];if(0===o)throw new Error("Requires delta != 0");let c;if(o>0&&a<n||o<0&&a>n)c=0;else if(c=Math.ceil(Math.abs((a-n)/o)),c>2147483647)throw new Error("Requires ((limit - start) / delta) <= 2147483647");h[t+1]=h[t]+c}const d=ct(n,h[p]);let f=0;for(let t=0;t<p;++t){const n=h[t+1]-h[t];let r=i?e[0]:e[t];const a=l?s[0]:s[t];for(let e=0;e<n;++e)d[f++]=r,r+=a}return[h,d]},raggedTensorToTensorImpl:function(e,t,n,r,a,s,o,i,u,l){return new Zm(e,t,n,r,a,s,o,i,u,l).compute()},rangeImpl:ng,rsqrtImpl:rg,scatterImpl:function(e,t,n,r,a,s,o,i,u,l){const c=[r/a,a],p=e.values,h=t.values;if(0===r)return ju(n,t.dtype);const d=ju(c,t.dtype);"string"==typeof u||"number"==typeof u?d.values.fill(u):"boolean"==typeof u&&d.values.fill(+u);for(let e=0;e<s;e++){const s=[];let u=0;for(let t=0;t<o;t++){const n=p[e*o+t];s.push(n),u+=n*i[t]}if(u<0||u>=r/a)throw new Error(`Invalid indices: ${s} does not index into ${n}`);for(let n=0;n<a;n++)l?d.values[u*a+n]+=h[e*a+n]:d.values[u*a+n]=0===t.rank?h[0]:h[e*a+n]}return d},sigmoidImpl:ag,sliceImpl:ig,sparseFillEmptyRowsImpl:function(e,t,n,r,a,s,o){const i=t[0],u=s[0],l=new Array(u),c=new Array(i),p=t[1];if(0===u){if(0!==i)throw new Error(Ad(i));return[ct(n,0),[0,p],ct(a,0),l,c]}let h=!0,d=0;const f=new Array(u).fill(0);for(let t=0;t<i;++t){const n=e[t*p];if(n<0)throw new Error(Rd(t,n));if(n>=u)throw new Error($d(t,n,u));++f[n],h=h&&n>=d,d=n}let m=!0;for(let e=0;e<u;++e){const t=0===f[e];l[e]=t,m=m&&!t,f[e]=Math.max(f[e],1),e>0&&(f[e]+=f[e-1])}if(m&&h){const t=e,n=r;for(let e=0;e<i;++e)c[e]=e;return[t,[i,p],n,l,c]}{const t=f[u-1],s=ct(n,t*p),h=ct(a,t),d=new Array(u).fill(0);for(let t=0;t<i;++t){const n=e[t*p],a=d[n],o=(0===n?0:f[n-1])+a;d[n]++;for(let n=0;n<p;++n)s[o*p+n]=e[t*p+n];h[o]=r[t],c[t]=o}for(let e=0;e<u;++e)if(0===d[e]){const t=0===e?0:f[e-1];s[t*p+0]=e;for(let e=1;e<p;++e)s[t*p+e]=0;h[t]=o}return[s,[t,p],h,l,c]}},sparseReshapeImpl:function(e,t,n,r,a){const s=et(r),o=t[0],i=a.length,u=[];let l=1,c=-1;for(let e=0;e<i;++e){const t=a[e];if(-1===t){if(-1!==c)throw new Error(Md(c,e));c=e,u.push(1)}else{if(t<0)throw new Error(Fd(e,t));l*=t,u.push(t)}}if(-1!==c){if(l<=0)throw new Error("reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero");const e=Math.trunc(s/l);if(l*e!==s)throw new Error(Od(r,u));u[c]=e}if(et(u)!==s)throw new Error(Dd(r,u));const p=r.length,h=[];if(p>0){h[p-1]=1;for(let e=p-2;e>=0;--e)h[e]=h[e+1]*r[e+1]}const d=[];if(i>0){d[i-1]=1;for(let e=i-2;e>=0;--e)d[e]=d[e+1]*u[e+1]}const f=ct(n,o*i);for(let t=0;t<o;++t){let n=0;for(let r=0;r<p;++r)n+=e[t*p+r]*h[r];for(let e=0;e<i;++e)f[t*i+e]=Math.trunc(n/d[e]),n%=d[e]}return[f,[o,i],u]},sparseSegmentReductionImpl:function(e,t,n,r,a,s=!1,o=0){const i=r.length,u=[t[0],e.length/t[0]],l=u[1],c=i>0?a[i-1]+1:0;if(c<0)throw new Error("segment ids must be >= 0");const p=t.slice();p[0]=c;const h=ct(n,p.reduce(((e,t)=>e*t),1));if(0===i)return c>0&&h.fill(o),[h,p];if(c<=0)throw new Error("segment ids must be >= 0");let d=0,f=1,m=0,g=a[d];for(;;){let t=0;if(f<i){if(t=a[f],g===t){++f;continue}if(g>=t)throw new Error("segment ids are not increasing")}if(g<0||g>=c)throw new Error(Ld(g,c));g>m&&h.fill(o,m*l,g*l);for(let t=d;t<f;++t){const n=r[t];if(n<0||n>=u[0])throw new Error(Pd(t,r[t],u[0]));for(let t=0;t<l;t++)h[g*l+t]+=e[n*l+t]}if(s)for(let e=0;e<l;e++)h[g*l+e]/=f-d;if(d=f,++f,m=g+1,g=t,f>i)break}return m<c&&h.fill(o,m*l,c*l),[h,p]},sqrtImpl:cg,squaredDifferenceImpl:pg,stridedSliceImpl:hg,stringNGramsImpl:fg,stringSplitImpl:gg,stringToHashBucketFastImpl:yg,subImpl:bg,tileImpl:function(e,t){const n=new Array(e.rank);for(let r=0;r<n.length;r++)n[r]=e.shape[r]*t[r];const r=ju(n,e.dtype);for(let t=0;t<r.values.length;++t){const n=r.indexToLoc(t),a=new Array(e.rank);for(let t=0;t<a.length;t++)a[t]=n[t]%e.shape[t];const s=e.locToIndex(a);r.values[t]=e.values[s]}return r},topKImpl:function(e,t,n,r,a){const s=t[t.length-1],[o,i]=[e.length/s,s],u=lt(n,o*r),l=lt("int32",o*r);for(let t=0;t<o;t++){const n=t*i,s=e.subarray(n,n+i);let o=new Array(s.length);s.forEach(((e,t)=>o[t]={value:e,index:t})),r<o.length&&(Tg(o,r),o=o.slice(0,r)),a&&o.sort(wg);const c=t*r,p=u.subarray(c,c+r),h=l.subarray(c,c+r);for(let e=0;e<r;e++)p[e]=o[e].value,h[e]=o[e].index}const c=t.slice();return c[c.length-1]=r,[ju(c,n,u),ju(c,"int32",l)]},transposeImpl:Xm,uniqueImpl:function(e,t,n,r){const a=it(t,n)[0],s=[1,n[0],1];for(let e=0;e<a;e++)s[0]*=n[e];s[1]=n[a];for(let e=a+1;e<n.length;e++)s[2]*=n[e];const o={},i=new Int32Array(n[a]),u=new Da(s,r,e),l=[],c=1===s[0]&&1===s[2];for(let t=0;t<n[a];t++){let n;if(c)n=e[t].toString();else{const e=[];for(let n=0;n<s[0];n++)for(let r=0;r<s[2];r++)e.push(u.get(n,t,r));n=e.join(",")}if(void 0!==o[n])i[t]=o[n];else{const e=Object.keys(o).length;o[n]=e,i[t]=e,l.push(t)}}const p=s.slice();p[1]=Object.keys(o).length;const h=new Da(p,r);l.forEach(((e,t)=>{for(let n=0;n<s[0];n++)for(let r=0;r<s[2];r++)h.set(u.get(n,e,r),n,t,r)}));const d=n.slice();return d[a]=p[1],{outputValues:h.values,outputShape:d,indices:i}}});function Ig(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{shape:s}=r,o=et(a.shape),i=ot(s,o),u=et(i);Qe(o===u,(()=>`The new shape (${i}) has ${u} elements and the old shape (${a.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`)),n.incRef(a.dataId);const l=n.data.get(a.dataId);if(null!=l.complexTensorInfos){const e=l.complexTensorInfos.real,t=l.complexTensorInfos.imag;e.shape=i,t.shape=i}return{dataId:a.dataId,shape:i,dtype:a.dtype}}wi("cpu",(()=>new cm),1);const Sg={kernelName:Hn,backendName:"cpu",kernelFunc:Ig},Eg={kernelName:jn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:o,size:i}=r;um(a,"resizeBilinear");const u=yt(a.shape),[l,c]=i,[p,h,d,f]=a.shape,m=n.data.get(a.dataId).values,g=new Float32Array(et([p,l,c,f])),y=[s&&l>1?h-1:h,s&&c>1?d-1:d],b=[s&&l>1?l-1:l,s&&c>1?c-1:c];let _=0;const x=y[0]/b[0],v=y[1]/b[1];for(let e=0;e<p;e++)for(let t=0;t<l;t++){let n;n=o?x*(t+.5)-.5:x*t;const r=Math.max(0,Math.floor(n)),a=n-r,s=Math.min(h-1,Math.ceil(n)),i=e*u[0]+r*u[1],l=e*u[0]+s*u[1];for(let e=0;e<c;e++){let t;t=o?v*(e+.5)-.5:v*e;const n=Math.max(0,Math.floor(t)),r=t-n,s=Math.min(d-1,Math.ceil(t)),c=i+n*u[2],p=l+n*u[2],h=i+s*u[2],y=l+s*u[2];for(let e=0;e<f;e++){const t=m[c+e],n=m[p+e],s=t+(m[h+e]-t)*r,o=s+(n+(m[y+e]-n)*r-s)*a;g[_++]=o}}}return n.makeTensorInfo([p,l,c,f],"float32",g)}},Ng=pm(((e,t)=>e/t)),Cg=xm(en,Ng),Ag={kernelName:en,backendName:"cpu",kernelFunc:Cg},Rg={kernelName:Pn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{paddings:s,constantValue:o}=r;um(a,"pad");const i=s.map(((e,t)=>e[0]+a.shape[t]+e[1])),u=s.map((e=>e[0])),l=n.data.get(a.dataId).values,c=et(a.shape),p=a.shape.length,h=yt(a.shape),d=et(i),f=i.length,m=yt(i),g=lt(a.dtype,d);0!==o&&g.fill(o);for(let e=0;e<c;e++)g[Tt(kt(e,p,h).map(((e,t)=>e+u[t])),f,m)]=l[e];return{dataId:n.write(g,i,a.dtype),shape:i,dtype:a.dtype}}};function $g(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dataFormat:u,dilations:l,dimRoundingMode:c}=r;um([a,s],"conv2d");const p=Eu(u),h=yu(a.shape,s.shape,o,l,i,c,!1,p),d=h.filterHeight,f=h.filterWidth,m=h.dilationHeight,g=h.dilationWidth,y=h.padInfo.left,b=h.padInfo.top,_="channelsLast"===h.dataFormat,x=new Da(h.outShape,a.dtype),v=yt(a.shape),w=yt(s.shape),T=v[0],k=_?v[1]:v[2],I=_?v[2]:1,S=_?1:v[1],E=x.strides[0],N=_?x.strides[1]:x.strides[2],C=_?x.strides[2]:1,A=_?1:x.strides[1],R=n.data.get(a.dataId).values,$=n.data.get(s.dataId).values,M=x.values;for(let e=0;e<h.batchSize;++e){const t=e*T,n=e*E;for(let e=0;e<h.outHeight;++e){const r=n+e*N,a=e*h.strideHeight-b;for(let e=0;e<d;++e){const n=a+e*m;if(n<0||n>=h.inHeight)continue;const s=e*w[0],o=t+n*k;for(let e=0;e<h.outWidth;++e){const t=r+e*C,n=e*h.strideWidth-y;for(let e=0;e<f;++e){const r=n+e*g;if(r<0||r>=h.inWidth)continue;const a=o+r*I;let i=s+e*w[1];for(let e=0;e<h.inChannels;++e){const n=R[a+e*S];for(let e=0;e<h.outChannels;++e)M[t+e*A]+=n*$[i+e];i+=h.outChannels}}}}}}return n.makeTensorInfo(x.shape,x.dtype,M)}const Mg={kernelName:jt,backendName:"cpu",kernelFunc:$g},Fg=Em(tn,(e=>e>=0?e:Math.exp(e)-1)),Og=pm(((e,t)=>e<0?t*e:e)),Dg=Em(Wn,(e=>Math.max(0,e))),Lg={kernelName:Wn,backendName:"cpu",kernelFunc:Dg},Pg=Em(Kn,(e=>Math.min(Math.max(0,e),6))),Bg={kernelName:Kn,backendName:"cpu",kernelFunc:Pg};function Ug(e,t,n,r,a){if("linear"===n)return fm({inputs:{x:t},backend:e});if("relu"===n)return Dg({inputs:{x:t},backend:e});if("elu"===n)return Fg({inputs:{x:t},backend:e});if("relu6"===n)return Pg({inputs:{x:t},backend:e});if("prelu"===n)return function(e){const{inputs:t,backend:n}=e,{x:r,alpha:a}=t;um([r,a],"prelu");const s=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values,[i,u]=Og(r.shape,a.shape,s,o,"float32");return n.makeTensorInfo(u,"float32",i)}({inputs:{x:t,alpha:r},backend:e});if("leakyrelu"===n)return function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{alpha:s}=r;um([a],"leakyRelu");const o=et(a.shape),i=n.data.get(a.dataId).values,u=lt("float32",o);for(let e=0;e<i.length;e++)u[e]=i[e]<0?s*i[e]:i[e];return n.makeTensorInfo(a.shape,"float32",u)}({inputs:{x:t},backend:e,attrs:{alpha:a}});if("sigmoid"===n)return sg({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}const zg={kernelName:Er,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dataFormat:c,dilations:p,dimRoundingMode:h,activation:d,leakyreluAlpha:f}=r;let m=$g({inputs:{x:a,filter:s},backend:n,attrs:{strides:u,pad:l,dataFormat:c,dilations:p,dimRoundingMode:h}});if(o){const e=m;if("NCHW"===c&&1===o.shape.length&&1!==o.shape[0]){const e=Ig({inputs:{x:o},backend:n,attrs:{shape:[o.shape[0],1,1]}});m=km({inputs:{a:m,b:e},backend:n}),n.disposeIntermediateTensorInfo(e)}else m=km({inputs:{a:m,b:o},backend:n});n.disposeIntermediateTensorInfo(e)}if(d){const e=m;if("NCHW"===c&&"prelu"===d&&1===i.shape.length&&1!==i.shape[0]){const e=Ig({inputs:{x:i},backend:n,attrs:{shape:[i.shape[0],1,1]}});m=Ug(n,m,d,e,f),n.disposeIntermediateTensorInfo(e)}else m=Ug(n,m,d,i,f);n.disposeIntermediateTensorInfo(e)}return m}};function Vg(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dilations:u,dimRoundingMode:l}=r;um([a,s],"depthwiseConv2DNative");const c=yt(a.shape),p=yt(s.shape);let h=u;null==h&&(h=[1,1]),Qe(Iu(o,h),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${h}'`));const d=yu(a.shape,s.shape,o,h,i,l,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:y,padInfo:b}=d,_=b.left,x=b.top,v=d.outChannels/d.inChannels,w=new Da(d.outShape,a.dtype),T=n.data.get(a.dataId).values,k=n.data.get(s.dataId).values,I=w.values;for(let e=0;e<d.batchSize;++e){const t=e*c[0],n=e*w.strides[0];for(let e=0;e<d.outHeight;++e){const r=n+e*w.strides[1],a=e*d.strideHeight-x;for(let e=0;e<f;++e){const n=a+e*g;if(n<0||n>=d.inHeight)continue;const s=e*p[0],o=t+n*c[1];for(let e=0;e<d.outWidth;++e){const t=r+e*w.strides[2],n=e*d.strideWidth-_;for(let e=0;e<m;++e){const r=n+e*y;if(r<0||r>=d.inWidth)continue;const a=s+e*p[1],i=o+r*d.inChannels;let u=t,l=a;for(let e=0;e<d.inChannels;++e){const t=T[i+e];for(let e=0;e<v;++e)I[u+e]+=t*k[l+e];u+=v,l+=v}}}}}}return n.makeTensorInfo(w.shape,w.dtype,w.values)}const Wg={kernelName:Zt,backendName:"cpu",kernelFunc:Vg},Hg={kernelName:Nr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dataFormat:c,dilations:p,dimRoundingMode:h,activation:d,leakyreluAlpha:f}=r;let m=Vg({inputs:{x:a,filter:s},backend:n,attrs:{strides:u,pad:l,dataFormat:c,dilations:p,dimRoundingMode:h}});if(o){const e=m;m=km({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(e)}if(d){const e=m;m=Ug(n,m,d,i,f),n.disposeIntermediateTensorInfo(e)}return m}},Gg={kernelName:rr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,paddings:o}=r;um([a],"spaceToBatchND");const i=et(s),u=[[0,0]];u.push(...o);for(let e=1+s.length;e<a.shape.length;++e)u.push([0,0]);const l=Rg.kernelFunc({inputs:{x:a},backend:n,attrs:{paddings:u,constantValue:0}}),c=vd(l.shape,s,i,!1),p=wd(c.length,s.length,!1),h=Td(l.shape,s,i,!1),d=Ig({inputs:{x:l},backend:n,attrs:{shape:c}}),f=Ym({inputs:{x:d},backend:n,attrs:{perm:p}}),m=Ig({inputs:{x:f},backend:n,attrs:{shape:h}});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),m}},jg={kernelName:zt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,crops:o}=r;um([a],"batchToSpaceND");const i=s.reduce(((e,t)=>e*t)),u=vd(a.shape,s,i),l=wd(u.length,s.length),c=Td(a.shape,s,i),p=kd(o,s.length),h=Id(c,o,s.length),d=Ig({inputs:{x:a},backend:n,attrs:{shape:u}}),f=Ym({inputs:{x:d},backend:n,attrs:{perm:l}}),m=Ig({inputs:{x:f},backend:n,attrs:{shape:c}}),g=ug({inputs:{x:m},backend:n,attrs:{begin:p,size:h}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}},Kg={kernelName:pr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,end:o,strides:i,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:h}=r;um(a,"stridedSlice");const{finalShapeSparse:d,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:_,strides:x}=Yi(a.shape,s,o,i,u,l,c,p,h);let v;if(m)v=Ig({inputs:{x:a},backend:n,attrs:{shape:f}});else if(g||y){Qe(a.shape.length>=1,(()=>`Input must have rank at least 1, got: ${a.shape.length}`));const e=Pi(b,_,x),t=ug({inputs:{x:a},backend:n,attrs:{begin:b,size:e}});v=Ig({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else{const e=hg(d,n.bufferSync(a),x,b);v=n.makeTensorInfo(f,e.dtype,e.values)}return v}};function qg(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r,s=it(a,t[0].shape)[0];hd(t.map((e=>e.shape)),s);let o=dd(t.map((e=>e.shape)),s);if(0===et(o))return n.makeTensorInfo(o,t[0].dtype,[]);const i=t.filter((e=>et(e.shape)>0));if(1===i.length)return fm({inputs:{x:i[0]},backend:n});if("complex64"===i[0].dtype){const e=i.map((e=>gm({inputs:{input:e},backend:n}))),t=i.map((e=>function(e){const{inputs:t,backend:n}=e,{input:r}=t,a=n.data.get(r.dataId).complexTensorInfos.imag,s=n.data.get(a.dataId).values;return n.makeTensorInfo(a.shape,a.dtype,s)}({inputs:{input:e},backend:n}))),r=qg({inputs:e,backend:n,attrs:{axis:s}}),a=qg({inputs:t,backend:n,attrs:{axis:s}}),o=hm({inputs:{real:r,imag:a},backend:n});return e.forEach((e=>n.disposeIntermediateTensorInfo(e))),t.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),o}const u=i.map((e=>{const t=et(e.shape.slice(s));return Ig({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),l=u.map((e=>({vals:n.data.get(e.dataId).values,shape:e.shape})));o=dd(u.map((e=>e.shape)),1);const c=1===u[0].shape[0],p=Cm(l,o,t[0].dtype,c),h=dd(i.map((e=>e.shape)),s),d=n.makeTensorInfo(h,t[0].dtype,p);return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}const Xg={kernelName:Gt,backendName:"cpu",kernelFunc:qg};function Yg(e){const{inputs:t,backend:n,attrs:r}=e,{input:a}=t,{dim:s}=r,o=a.shape.length,i=a.shape.slice();let u=s;return s<0&&(Qe(-(o+1)<=s,(()=>`Axis must be in the interval [${-(o+1)}, ${o}]`)),u=o+s+1),i.splice(u,0,1),Ig({inputs:{x:a},backend:n,attrs:{shape:i}})}const Qg={kernelName:Ln,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return Yg({inputs:{input:t[0]},backend:n,attrs:{dim:a}});const s=t[0].shape,o=t[0].dtype;t.forEach((e=>{Je(s,e.shape,"All tensors passed to stack must have matching shapes"),Qe(o===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const i=[],u=qg({inputs:t.map((e=>{const t=Yg({inputs:{input:e},backend:n,attrs:{dim:a}});return i.push(t),t})),backend:n,attrs:{axis:a}});return i.forEach((e=>n.disposeIntermediateTensorInfo(e))),u}},Jg={kernelName:Kt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{inputShape:o,strides:i,pad:u,dataFormat:l,dimRoundingMode:c}=r;um([a,s],"conv2dBackpropInput");const p=yt(s.shape),h=yt(a.shape);let d=Eu(l);const f=yu(o,s.shape,i,1,u,c,!1,d),m=new Da(f.inShape,"float32"),g=m.values,y=n.data.get(a.dataId).values,b=n.data.get(s.dataId).values,[_,x,v]=p,{batchSize:w,filterHeight:T,filterWidth:k,inChannels:I,inHeight:S,inWidth:E,outChannels:N,outHeight:C,outWidth:A,strideHeight:R,strideWidth:$}=f;d=f.dataFormat;const M=T-1-f.padInfo.top,F=k-1-f.padInfo.left,O="channelsLast"===d,D=m.strides[0],L=O?m.strides[1]:m.strides[2],P=O?m.strides[2]:1,B=O?1:m.strides[1],U=h[0],z=O?h[1]:h[2],V=O?h[2]:1,W=O?1:h[1];for(let e=0;e<w;++e)for(let t=0;t<I;++t)for(let n=0;n<S;++n){const r=n-M,a=Math.max(0,Math.ceil(r/R)),s=Math.min(C,(T+r)/R);for(let o=0;o<E;++o){const i=o-F,u=Math.max(0,Math.ceil(i/$)),l=Math.min(A,(k+i)/$);let c=0;for(let n=a;n<s;++n){const a=n*R-r;for(let r=u;r<l;++r){const s=U*e+z*n+V*r,o=_*(T-1-a)+x*(k-1-(r*$-i))+v*t;for(let e=0;e<N;++e)c+=y[s+W*e]*b[o+e]}}g[D*e+L*n+P*o+B*t]=c}}return n.makeTensorInfo(m.shape,m.dtype,m.values)}},Zg={kernelName:Qt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:a,boxes:s,boxInd:o}=t,{cropSize:i,method:u,extrapolationValue:l}=r,[c,p,h,d]=a.shape,f=s.shape[0],[m,g]=i,y=ju([f,m,g,d],"float32"),b=n.data.get(s.dataId).values,_=n.data.get(o.dataId).values,x=n.data.get(a.dataId).values,v=yt(a.shape),w=yt(y.shape);for(let e=0;e<f;e++){const t=4*e,n=b[t],r=b[t+1],a=b[t+2],s=b[t+3],o=_[e];if(o>=c)continue;const i=m>1?(a-n)*(p-1)/(m-1):0,f=g>1?(s-r)*(h-1)/(g-1):0;for(let t=0;t<m;t++){const c=m>1?n*(p-1)+t*i:.5*(n+a)*(p-1);if(c<0||c>p-1)for(let n=0;n<g;n++)for(let r=0;r<d;r++){const a=r+n*w[2]+t*w[1]+e*w[0];y.values[a]=l}else if("bilinear"===u){const n=Math.floor(c),a=Math.ceil(c),i=c-n;for(let u=0;u<g;u++){const c=g>1?r*(h-1)+u*f:.5*(r+s)*(h-1);if(c<0||c>h-1){for(let n=0;n<d;n++){const r=n+u*w[2]+t*w[1]+e*w[0];y.values[r]=l}continue}const p=Math.floor(c),m=Math.ceil(c),b=c-p;for(let r=0;r<d;r++){let s=r+p*v[2]+n*v[1]+o*v[0];const l=x[s];s=r+m*v[2]+n*v[1]+o*v[0];const c=x[s];s=r+p*v[2]+a*v[1]+o*v[0];const h=x[s];s=r+m*v[2]+a*v[1]+o*v[0];const d=l+(c-l)*b,f=h+(x[s]-h)*b;s=r+u*w[2]+t*w[1]+e*w[0],y.values[s]=d+(f-d)*i}}}else for(let n=0;n<g;++n){const a=g>1?r*(h-1)+n*f:.5*(r+s)*(h-1);if(a<0||a>h-1){for(let r=0;r<d;r++){const a=r+n*w[2]+t*w[1]+e*w[0];y.values[a]=l}continue}const i=Math.round(a),u=Math.round(c);for(let r=0;r<d;r++){const a=r+i*v[2]+u*v[1]+o*v[0],s=r+n*w[2]+t*w[1]+e*w[0];y.values[s]=x[a]}}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}},ey={kernelName:qn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dims:s}=r;um(a,"reverse");const o=a.shape.length,i=it(s,a.shape);if(0===o)return fm({inputs:{x:a},backend:n});const u=new Da(a.shape,a.dtype),l=n.bufferSync(a);for(let e=0;e<u.size;e++){const t=u.indexToLoc(e),n=t.slice();i.forEach((e=>n[e]=a.shape[e]-1-n[e])),u.set(l.get(...n),...t)}return n.makeTensorInfo(u.shape,u.dtype,u.values)}},ty={kernelName:vr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{value:a}=t;let{axis:s}=r;s<0&&(s+=a.shape.length);const o=a.shape.length,i=a.shape[s],u=new Array(o-1);let l=0;for(let e=0;e<o;e++)e!==s&&(u[l++]=a.shape[e]);const c=new Array(o).fill(0),p=a.shape.slice();p[s]=1;const h=new Array(i);for(let e=0;e<h.length;e++){c[s]=e;const t=ug({inputs:{x:a},backend:n,attrs:{begin:c,size:p}});h[e]=Ig({inputs:{x:t},backend:n,attrs:{shape:u}}),n.disposeIntermediateTensorInfo(t)}return h}},ny={kernelName:Pt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;um(a,"argMax");let o=it(s,a.shape);const i=Cl(o,a.shape.length);let u=a;const l=[];null!=i&&(u=Ym({inputs:{x:a},backend:n,attrs:{perm:i}}),l.push(u),o=Rl(o.length,u.shape.length)),o=[o[0]],Nl("argMax",o,u.shape.length);const[c,p]=Sl(u.shape,o),h=vt(et(c),"int32"),d=et(p),f=n.data.get(u.dataId).values;for(let e=0;e<h.length;++e){const t=e*d;let n=f[t],r=0;for(let e=0;e<d;++e){const a=f[t+e];a>n&&(n=a,r=e)}h[e]=r}return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(c,"int32",h)}};function ry(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r;let i;um(a,"sum"),i="bool"===a.dtype?bm({inputs:{x:a},backend:n,attrs:{dtype:"int32"}}):fm({inputs:{x:a},backend:n});const u=i.shape.length,l=it(s,i.shape),c=Cl(l,u);let p=l,h=i;null!=c&&(h=Ym({inputs:{x:i},backend:n,attrs:{perm:c}}),p=Rl(p.length,u)),Nl("sum",p,h.shape.length);const[d,f]=Sl(h.shape,p);let m=dm(n,d,Ka(h.dtype,"int32"));const g=et(f),y=n.data.get(m.dataId).values,b=n.data.get(h.dataId).values;for(let e=0;e<y.length;++e){const t=e*g;let n=0;for(let e=0;e<g;++e)n+=b[t+e];y[e]=n}if(o){const e=m;m=Ig({inputs:{x:m},backend:n,attrs:{shape:El(m.shape,l)}}),n.disposeIntermediateTensorInfo(e)}return n.disposeIntermediateTensorInfo(i),null!=c&&n.disposeIntermediateTensorInfo(h),m}const ay={kernelName:Sn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r,i=it(s,a.shape),u=et(Sl(a.shape,i)[1]),l=[],c=n.makeTensorInfo([],"float32",new Float32Array([u]));l.push(c);const p=bm({inputs:{x:a},backend:n,attrs:{dtype:"float32"}});l.push(p);const h=Cg({inputs:{a:p,b:c},backend:n});l.push(h);const d=ry({inputs:{x:h},backend:n,attrs:{axis:s,keepDims:o}});return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}},sy={kernelName:sr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{dim:s}=r,o=a.shape.length;let i=s;if(-1===i&&(i=o-1),i!==o-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${o} and dim was ${i}`);const u=it([i],a.shape),l=function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{reductionIndices:s,keepDims:o}=r,i=n;let u=a.shape;const l=u.length,c=it(s,u);let p=c;const h=Cl(p,l);let d=i.data.get(a.dataId).values;if(null!=h){const e=new Array(l);for(let t=0;t<e.length;t++)e[t]=u[h[t]];d=Xm(d,u,a.dtype,h,e),p=Rl(p.length,l),u=e}um(a,"max"),Nl("max",p,l);const[f,m]=Sl(u,p),g=zm(d,et(m),f,a.dtype),y=i.write(g,f,a.dtype);let b=f;return o&&(b=El(f,c)),{dataId:y,shape:b,dtype:a.dtype}}({inputs:{x:a},backend:n,attrs:{reductionIndices:u,keepDims:!1}}),c=El(l.shape,u),p=Ig({inputs:{x:l},backend:n,attrs:{shape:c}}),h=xg({inputs:{a,b:p},backend:n}),d=$m({inputs:{x:h},backend:n}),f=ry({inputs:{x:d},backend:n,attrs:{axis:u,keepDims:!1}}),m=Ig({inputs:{x:f},backend:n,attrs:{shape:c}}),g=Cg({inputs:{a:d,b:m},backend:n});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}},oy=Em(Ht,((e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e})),iy={kernelName:Ht,backendName:"cpu",kernelFunc:oy},uy={kernelName:Bt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;um(a,"avgPool");const{filterSize:s,strides:o,pad:i,dimRoundingMode:u}=r;Qe(Iu(o,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '1'`));const l=gu(a.shape,s,o,1,i,u);let c;if(1===l.filterWidth&&1===l.filterHeight&&tt(l.inShape,l.outShape))c=fm({inputs:{x:a},backend:n});else{const e=n.data.get(a.dataId).values,t=yt(a.shape),r=function(e,t,n,r,a,s){const o=a.strideHeight,i=a.strideWidth,u=a.dilationHeight,l=a.dilationWidth,c=a.effectiveFilterHeight,p=a.effectiveFilterWidth,h=a.padInfo.top,d=a.padInfo.left,f=Number.POSITIVE_INFINITY,m=ju(a.outShape,n),g=m.values,y=a.outShape[1]*a.outShape[2]*a.outShape[3],b=a.outShape[2]*a.outShape[3],_=a.outShape[3];for(let t=0;t<a.batchSize;++t){const n=t*y,s=t*r[0];for(let t=0;t<a.inChannels;++t)for(let m=0;m<a.outHeight;++m){const y=m*o-h,x=Math.max(0,y),v=Math.min(a.inHeight,c+y),w=n+m*b;for(let n=0;n<a.outWidth;++n){const o=n*i-d,c=Math.max(0,o),h=Math.min(a.inWidth,p+o);let m=f,y=0,b=0;for(let n=x;n<v;n+=u){const a=s+n*r[1];for(let n=c;n<h;n+=l){const s=e[a+n*r[2]+t];y+=s,b++}if(isNaN(m))break}g[w+n*_+t]=y/b}}}return m}(e,a.shape,a.dtype,t,l);c=n.makeTensorInfo(l.outShape,a.dtype,r.values)}return c}},ly={kernelName:Ut,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a,b:s}=t,{transposeA:o,transposeB:i}=r;um([a,s],"matMul");const u=a.shape.length,l=s.shape.length,c=o?a.shape[u-2]:a.shape[u-1],p=i?s.shape[l-1]:s.shape[l-2],h=o?a.shape[u-1]:a.shape[u-2],d=i?s.shape[l-2]:s.shape[l-1],f=a.shape.slice(0,-2),m=s.shape.slice(0,-2),g=et(f),y=et(m),b=Ci(a.shape.slice(0,-2),s.shape.slice(0,-2)).concat([h,d]);Qe(c===p,(()=>`Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${a.shape} and ${s.shape} and transposeA=${o} and transposeB=${i} must match.`));const _=i?[y,d,p]:[y,p,d],x=Ig({inputs:{x:a},backend:n,attrs:{shape:o?[g,c,h]:[g,h,c]}}),v=Ig({inputs:{x:s},backend:n,attrs:{shape:_}}),w=o?x.shape[1]:x.shape[2],T=o?x.shape[2]:x.shape[1],k=i?v.shape[1]:v.shape[2],I=Math.max(g,y),S=n.data.get(x.dataId).values,E=n.data.get(v.dataId).values,N=yt(x.shape),C=yt(v.shape),[A,R,$]=o?[N[0],1,N[1]]:[N[0],N[1],1],[M,F,O]=i?[1,C[1],C[0]]:[C[1],1,C[0]],D=T*k,L=ju([I,T,k],x.dtype),P=L.values,B=n.blockSize;for(let e=0;e<I;e++){const t=e%g,n=e%y;for(let r=0;r<T;r+=B){const a=Math.min(r+B,T);for(let s=0;s<k;s+=B){const o=Math.min(s+B,k);for(let i=0;i<w;i+=B){const u=Math.min(i+B,w);for(let l=r;l<a;l++)for(let r=s;r<o;r++){let a=0;for(let e=i;e<u;e++)a+=S[t*A+l*R+e*$]*E[e*M+r*F+n*O];P[e*D+(l*k+r)]+=a}}}}}return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(v),n.makeTensorInfo(b,L.dtype,L.values)}},cy={},py={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function hy(e,t){if(!(e in cy)||null!=t){const n=function(e,t){if(1!==e&&2!==e)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const n=null==t?function(e){if("undefined"!=typeof OffscreenCanvas&&2===e)return new OffscreenCanvas(300,150);if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}(e):t;return n.addEventListener("webglcontextlost",(t=>{t.preventDefault(),delete cy[e]}),!1),Ct().getBool("SOFTWARE_WEBGL_ENABLED")&&(py.failIfMajorPerformanceCaveat=!1),1===e?n.getContext("webgl",py)||n.getContext("experimental-webgl",py):n.getContext("webgl2",py)}(e,t);if(null===n)return console.log("Could not get context for WebGL version",e),null;cy[e]=n}const n=cy[e];return null==n||n.isContextLost()?(delete cy[e],hy(e)):(n.disable(n.DEPTH_TEST),n.disable(n.STENCIL_TEST),n.disable(n.BLEND),n.disable(n.DITHER),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SAMPLE_COVERAGE),n.enable(n.SCISSOR_TEST),n.enable(n.CULL_FACE),n.cullFace(n.BACK),cy[e])}var dy,fy,my;function gy(e,t){return[t,e]}function yy(e){const t=et(e);return rt(Math.ceil(t/4))}function by(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function _y(e,t){const n=e;let r,a,s,o,i,u,l,c,p,h;return 2===Ct().getNumber("WEBGL_VERSION")?(r=n.R32F,a=n.R16F,s=n.RGBA16F,o=n.RGBA32F,i=n.RED,l=4,c=1,p=n.HALF_FLOAT,h=n.FLOAT,u=n.RGBA8):(r=e.RGBA,a=e.RGBA,s=e.RGBA,o=n.RGBA,i=e.RGBA,l=4,c=4,p=null!=t?t.HALF_FLOAT_OES:null,h=e.FLOAT,u=e.RGBA),{internalFormatFloat:r,internalFormatHalfFloat:a,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:o,textureFormatFloat:i,downloadTextureFormat:u,downloadUnpackNumChannels:l,defaultNumChannels:c,textureTypeHalfFloat:p,textureTypeFloat:h}}function xy(e,t){const n=t();return Ct().getBool("DEBUG")&&function(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+function(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}(e,t))}(e),n}function vy(e){return!!(Ct().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||5.96e-8<Math.abs(e)&&Math.abs(e)<65504)}function wy(e,t){return Ay(e,(()=>e.getExtension(t)),'Extension "'+t+'" not supported on this browser.')}!function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"}(dy||(dy={})),function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"}(fy||(fy={})),function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(my||(my={}));const Ty=/ERROR: [0-9]+:([0-9]+):/g;function ky(e,t){const n=Ty.exec(t);if(null==n)return console.log(`Couldn't parse line number in error: ${t}`),void console.log(e);const r=+n[1],a=e.split("\n"),s=a.length.toString().length+2,o=a.map(((e,t)=>at((t+1).toString(),s)+e));let i=0;for(let e=0;e<o.length;e++)i=Math.max(o[e].length,i);const u=o.slice(0,r-1),l=o.slice(r-1,r),c=o.slice(r);console.log(u.join("\n")),console.log(t.split("\n")[0]),console.log(`%c ${at(l[0],i)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(c.join("\n"))}function Iy(e,t){if(xy(e,(()=>e.validateProgram(t))),!1===e.getProgramParameter(t,e.VALIDATE_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function Sy(e,t,n,r,a,s,o){const i=e.getAttribLocation(t,n);return-1!==i&&(xy(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,r))),xy(e,(()=>e.vertexAttribPointer(i,a,e.FLOAT,!1,s,o))),xy(e,(()=>e.enableVertexAttribArray(i))),!0)}function Ey(e,t,n){xy(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,n))),xy(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)))}function Ny(e,t){xy(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,t))),xy(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)))}function Cy(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+function(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}(e,t))}function Ay(e,t,n){const r=xy(e,(()=>t()));if(null==r)throw new Error(n);return r}function Ry(e,t=2){return et(e.slice(0,e.length-t))}function $y(e){if(0===e.length)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function My(e){let t=[1,1,1];return 0===e.length||1===e.length&&1===e[0]||(t=[Ry(e),...$y(e)]),t}function Fy(e){return e%2==0}function Oy(e,t){if(tt(e=e.slice(-2),t=t.slice(-2)))return!0;if(!e.length||!t.length)return!0;if(0===e[0]||0===e[1]||0===t[0]||0===t[1])return!0;if(e.length!==t.length){const n=e.slice(-1)[0],r=t.slice(-1)[0];if(n===r)return!0;if(Fy(n)&&Fy(r)&&(1===e[0]||1===t[0]))return!0}return e[1]===t[1]&&Fy(e[0])&&Fy(t[0])}let Dy,Ly;function Py(e,t){return null!=e.getExtension(t)}function By(e){try{if(null!=hy(e))return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function Uy(e){const t=_y(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n),e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);const a=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(r),a}const zy=Ct();function Vy(){let e,t,n,r,a,s,o,i,u,l;return 2===Ct().getNumber("WEBGL_VERSION")?(e="#version 300 es",t="in",n="out",r="in",a="texture",s="outputColor",o="out vec4 outputColor;",i=Ct().getBool("WEBGL2_ISNAN_CUSTOM")?"\n bool isnan_custom(float val) {\n uint floatToUint = floatBitsToUint(val);\n return (floatToUint & 0x7fffffffu) > 0x7f800000u;\n }\n\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan_custom(val.x),\n isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n }\n\n #define isnan(value) isnan_custom(value)\n ":"",u="",l="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(e="",t="attribute",n="varying",r="varying",a="texture2D",s="gl_FragColor",o="",i="\n #define isnan(value) isnan_custom(value)\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n ",u="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",l="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:a,output:s,defineOutput:o,defineSpecialNaN:i,defineSpecialInf:u,defineRound:l}}function Wy(e,t,n="index"){const r=yt(t);return r.map(((t,a)=>`int ${e[a]} = ${n} / ${t}; ${a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * ${t}`:`index -= ${e[a]} * ${t}`};`)).join("")}function Hy(e,t,n="index"){const r=yt(t);return r.map(((t,a)=>`int ${e[a]} = ${n} / outShapeStrides[${a}]; ${a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * outShapeStrides[${a}]`:`index -= ${e[a]} * outShapeStrides[${a}]`};`)).join("")}function Gy(e){const t=yt(e).map((e=>e.toString()));return`\n int getFlatIndex(ivec3 coords) {\n return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;\n }\n`}zy.registerFlag("HAS_WEBGL",(()=>zy.getNumber("WEBGL_VERSION")>0)),zy.registerFlag("WEBGL_VERSION",(()=>By(2)?2:By(1)?1:0)),zy.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",(()=>!1)),zy.registerFlag("WEBGL_BUFFER_SUPPORTED",(()=>2===zy.get("WEBGL_VERSION"))),zy.registerFlag("WEBGL_CPU_FORWARD",(()=>!0)),zy.registerFlag("WEBGL_FORCE_F16_TEXTURES",(()=>!1)),zy.registerFlag("WEBGL_PACK",(()=>zy.getBool("HAS_WEBGL"))),zy.registerFlag("WEBGL_PACK_NORMALIZATION",(()=>zy.getBool("WEBGL_PACK"))),zy.registerFlag("WEBGL_PACK_CLIP",(()=>zy.getBool("WEBGL_PACK"))),zy.registerFlag("WEBGL_PACK_DEPTHWISECONV",(()=>zy.getBool("WEBGL_PACK"))),zy.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(()=>zy.getBool("WEBGL_PACK"))),zy.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(()=>zy.getBool("WEBGL_PACK"))),zy.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(()=>zy.getBool("WEBGL_PACK"))),zy.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(()=>zy.getBool("WEBGL_PACK"))),zy.registerFlag("WEBGL_PACK_REDUCE",(()=>zy.getBool("WEBGL_PACK"))),zy.registerFlag("WEBGL_LAZILY_UNPACK",(()=>zy.getBool("WEBGL_PACK"))),zy.registerFlag("WEBGL_CONV_IM2COL",(()=>zy.getBool("WEBGL_PACK"))),zy.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(()=>function(e){if(null==Dy){const t=hy(e);Dy=t.getParameter(t.MAX_TEXTURE_SIZE)}return Dy}(zy.getNumber("WEBGL_VERSION")))),zy.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(()=>function(e){if(null==Ly){const t=hy(e);Ly=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Ly)}(zy.getNumber("WEBGL_VERSION")))),zy.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(()=>{const e=zy.getNumber("WEBGL_VERSION");return 0===e?0:function(e){if(0===e)return 0;let t;const n=hy(e);return t=Py(n,"EXT_disjoint_timer_query_webgl2")&&2===e?2:Py(n,"EXT_disjoint_timer_query")?1:0,t}(e)})),zy.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(()=>zy.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!rs())),zy.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(()=>function(e){if(0===e)return!1;const t=hy(e);if(1===e){if(!Py(t,"OES_texture_float"))return!1}else if(!Py(t,"EXT_color_buffer_float"))return!1;return Uy(t)}(zy.getNumber("WEBGL_VERSION")))),zy.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(()=>!zy.getBool("WEBGL_FORCE_F16_TEXTURES")&&zy.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))),zy.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(()=>function(e){if(0===e)return!1;const t=hy(e);if(1!==e){if(Py(t,"EXT_color_buffer_float"))return Uy(t);const e="EXT_color_buffer_half_float";if(Py(t,e)){const n=t.getExtension(e);return function(e,t){const n=_y(e,t),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r),e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);const a=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,a),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const s=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(r),e.deleteFramebuffer(a),s}(t,n)}return!1}return!!Py(t,"OES_texture_float")&&!!Py(t,"WEBGL_color_buffer_float")&&Uy(t)}(zy.getNumber("WEBGL_VERSION")))),zy.registerFlag("WEBGL_FENCE_API_ENABLED",(()=>{return 2===(e=zy.getNumber("WEBGL_VERSION"))&&null!=hy(e).fenceSync;var e})),zy.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(()=>zy.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0)),zy.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",(()=>-1),(e=>{if(e<0&&-1!==e)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`)})),zy.registerFlag("WEBGL_FLUSH_THRESHOLD",(()=>rs()?1:-1),(e=>{if(e<0&&-1!==e)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${e}.`)})),zy.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",(()=>128)),zy.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",(()=>!1)),zy.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",(()=>1e5)),zy.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",(()=>128)),zy.registerFlag("WEBGL_EXP_CONV",(()=>!1)),zy.registerFlag("SOFTWARE_WEBGL_ENABLED",(()=>zy.getBool("IS_TEST"))),zy.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",(()=>1/0)),zy.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",(()=>!1)),zy.registerFlag("WEBGL2_ISNAN_CUSTOM",(()=>!1)),zy.registerFlag("ENGINE_COMPILE_ONLY",(()=>!1));const jy="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isnan(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n",{getBroadcastDims:Ky}=Wd;function qy(e,t,n){const r=[];if(e.forEach((e=>{const t=et(e.shapeInfo.logicalShape);if(e.shapeInfo.isUniform?r.push(`uniform float ${e.name}${t>1?`[${t}]`:""};`):(r.push(`uniform sampler2D ${e.name};`),r.push(`uniform int offset${e.name};`)),n.enableShapeUniforms){const{uniformShape:t}=ab(n.packedInputs,e.shapeInfo.logicalShape,e.shapeInfo.texShape);switch(t.length){case 1:r.push(`uniform int ${e.name}Shape;`);break;case 2:r.push(`uniform ivec2 ${e.name}Shape;`);break;case 3:r.push(`uniform ivec3 ${e.name}Shape;`);break;case 4:r.push(`uniform ivec4 ${e.name}Shape;`)}r.push(`uniform ivec2 ${e.name}TexShape;`)}})),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:r.push("uniform int outShape;");break;case 2:r.push("uniform ivec2 outShape;"),r.push("uniform int outShapeStrides;");break;case 3:r.push("uniform ivec3 outShape;"),r.push("uniform ivec2 outShapeStrides;");break;case 4:r.push("uniform ivec4 outShape;"),r.push("uniform ivec3 outShapeStrides;")}r.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach((e=>{r.push(`uniform ${e.type} ${e.name}${e.arrayIndex?`[${e.arrayIndex}]`:""};`)}));const a=r.join("\n"),s=e.map((e=>function(e,t,n=!1,r){let a="";a+=n?Yy(e,r):Xy(e,r);const s=e.shapeInfo.logicalShape,o=t.logicalShape;return s.length<=o.length&&(a+=n?function(e,t){const n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),a="get"+r+"AtOutCoords",s=e.shapeInfo.logicalShape.length,o=t.logicalShape.length,i=Ky(e.shapeInfo.logicalShape,t.logicalShape),u=rb(o),l=o-s;let c;const p=["x","y","z","w","u","v"];c=0===s?"":o<2&&i.length>=1?"coords = 0;":i.map((e=>`coords.${p[e+l]} = 0;`)).join("\n");let h="";h=o<2&&s>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${p[t+l]}`)).join(", ");let d="return outputValue;";const f=1===et(e.shapeInfo.logicalShape),m=1===et(t.logicalShape);if(1!==s||f||m){if(f&&!m)d=1===o?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(i.length){const e=s-2,t=s-1;i.indexOf(e)>-1&&i.indexOf(t)>-1?d="return vec4(outputValue.x);":i.indexOf(e)>-1?d="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(t)>-1&&(d="return vec4(outputValue.xx, outputValue.zz);")}}else d="\n return vec4(outputValue.xy, outputValue.xy);\n ";return`\n vec4 ${a}() {\n ${u} coords = getOutputCoords();\n ${c}\n vec4 outputValue = get${r}(${h});\n ${d}\n }\n `}(e,t):function(e,t){const n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),a="get"+r+"AtOutCoords",s=t.texShape,o=e.shapeInfo.texShape,i=e.shapeInfo.logicalShape.length,u=t.logicalShape.length;if(!e.shapeInfo.isUniform&&i===u&&null==e.shapeInfo.flatOffset&&tt(o,s))return`\n float ${a}() {\n return sampleTexture(${n}, resultUV);\n }\n `;const l=rb(u),c=Ky(e.shapeInfo.logicalShape,t.logicalShape),p=u-i;let h;const d=["x","y","z","w","u","v"];h=0===i?"":u<2&&c.length>=1?"coords = 0;":c.map((e=>`coords.${d[e+p]} = 0;`)).join("\n");let f="";return f=u<2&&i>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${d[t+p]}`)).join(", "),`\n float ${a}() {\n ${l} coords = getOutputCoords();\n ${h}\n return get${r}(${f});\n }\n `}(e,t)),a}(e,t,n.packedInputs,n.enableShapeUniforms))).join("\n"),o=t.texShape,i=Vy(),u=function(e){return`\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return ${e.texture2D}(textureSampler, uv).r;\n }\n `}(i);let l,c,p=function(e){return`${e.version}\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n ${e.varyingFs} vec2 resultUV;\n ${e.defineOutput}\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n ${e.defineSpecialNaN}\n ${e.defineSpecialInf}\n ${e.defineRound}\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n ${Qy}\n ${Jy}\n ${Zy}\n `}(i);return t.isPacked?(l=function(e,t,n){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(e,t,n){const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return 1===r[0]?n?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));\n }\n ":`\n int getOutputCoords() {\n return 2 * int(resultUV.x * ${r[1]}.0);\n }\n `:1===r[1]?n?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));\n }\n ":`\n int getOutputCoords() {\n return 2 * int(resultUV.y * ${r[0]}.0);\n }\n `:n?"\n int getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);\n }\n ":`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n return 2 * (resTexRC.x * ${r[1]} + resTexRC.y);\n }\n `}(0,t,n);case 2:return function(e,t,n){const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(tt(e,t))return n?"\n ivec2 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));\n }\n ":`\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2(${r[0]}, ${r[1]}));\n }\n `;const a=Math.ceil(e[1]/2);return n?"\n ivec2 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec2(r, c);\n }\n ":`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n\n int index = resTexRC.x * ${r[1]} + resTexRC.y;\n int r = 2 * (index / ${a});\n int c = imod(index, ${a}) * 2;\n\n return ivec2(r, c);\n }\n `}(e,t,n);case 3:return function(e,t,n){if(n)return"\n ivec3 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));\n int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n\n int b = index / texelsInBatch;\n index -= b * texelsInBatch;\n\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec3(b, r, c);\n }\n ";const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],a=Math.ceil(e[2]/2),s=a*Math.ceil(e[1]/2);return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n int index = resTexRC.x * ${r[1]} + resTexRC.y;\n\n int b = index / ${s};\n index -= b * ${s};\n\n int r = 2 * (index / ${a});\n int c = imod(index, ${a}) * 2;\n\n return ivec3(b, r, c);\n }\n `}(e,t,n);default:return function(e,t,n){if(n)return"\n ivec4 getOutputCoords() {\n ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(packedTexShape[0], packedTexShape[1]));\n int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n\n int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));\n int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));\n int texelsInBatchN = texelsInBatch * outShape[1];\n\n int b2 = index / texelsInBatchN;\n index -= b2 * texelsInBatchN;\n\n int b = index / texelsInBatch;\n index -= b * texelsInBatch;\n\n int r = 2 * (index / texelsInLogicalRow);\n int c = imod(index, texelsInLogicalRow) * 2;\n\n return ivec4(b2, b, r, c);\n }\n ";const r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],a=Math.ceil(e[e.length-1]/2),s=a*Math.ceil(e[e.length-2]/2);let o=s,i="",u="b, r, c";for(let t=2;t<e.length-1;t++)o*=e[e.length-t-1],i=`\n int b${t} = index / ${o};\n index -= b${t} * ${o};\n `+i,u=`b${t}, `+u;return`\n ivec${e.length} getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${r[0]}, ${r[1]}));\n int index = resTexRC.x * ${r[1]} + resTexRC.y;\n\n ${i}\n\n int b = index / ${s};\n index -= b * ${s};\n\n int r = 2 * (index / ${a});\n int c = imod(index, ${a}) * 2;\n\n return ivec${e.length}(${u});\n }\n `}(e,t,n)}}(t.logicalShape,o,n.enableShapeUniforms),c=function(e){return`\n void setOutput(vec4 val) {\n ${e.output} = val;\n }\n `}(i)):(l=function(e,t,n){switch(e.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(e,t,n){return 1===t[0]?n?"\n int getOutputCoords() {\n return int(resultUV.x * float(outTexShape[1]));\n }\n ":`\n int getOutputCoords() {\n return int(resultUV.x * ${t[1]}.0);\n }\n `:1===t[1]?n?"\n int getOutputCoords() {\n return int(resultUV.y * float(outTexShape[0]));\n }\n ":`\n int getOutputCoords() {\n return int(resultUV.y * ${t[0]}.0);\n }\n `:n?"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n return resTexRC.x * outTexShape[1] + resTexRC.y;\n }\n ":`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n return resTexRC.x * ${t[1]} + resTexRC.y;\n }\n `}(0,t,n);case 2:return function(e,t,n){return tt(e,t)?n?"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));\n }\n ":`\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));\n }\n `:1===e[1]?n?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n return ivec2(index, 0);\n }\n ":`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n return ivec2(index, 0);\n }\n `:1===e[0]?n?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n return ivec2(0, index);\n }\n ":`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n return ivec2(0, index);\n }\n `:n?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n int r = index / outShape[1];\n int c = index - r * outShape[1];\n return ivec2(r, c);\n }\n ":`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n int r = index / ${e[1]};\n int c = index - r * ${e[1]};\n return ivec2(r, c);\n }\n `}(e,t,n);case 3:return function(e,t,n){if(n)return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n ${Hy(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n`;const r=Wy(["r","c","d"],e);return`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n ${r}\n return ivec3(r, c, d);\n }\n `}(e,t,n);case 4:return function(e,t,n){if(n)return`\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(outTexShape[0], outTexShape[1]));\n int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n ${Hy(["r","c","d","d2"],e)}\n return ivec4(r, c, d, d2);\n }\n `;const r=Wy(["r","c","d","d2"],e);return`\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n ${r}\n return ivec4(r, c, d, d2);\n }\n `}(e,t,n);case 5:return function(e,t){const n=Wy(["r","c","d","d2","d3"],e);return`\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},\n ${t[1]}));\n\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n\n ${n}\n\n ivec5 outShape = ivec5(r, c, d, d2, d3);\n return outShape;\n }\n `}(e,t);case 6:return function(e,t){const n=Wy(["r","c","d","d2","d3","d4"],e);return`\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2(${t[0]}, ${t[1]}));\n int index = resTexRC.x * ${t[1]} + resTexRC.y;\n\n ${n}\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n `}(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}(t.logicalShape,o,n.enableShapeUniforms),c=function(e){return`\n void setOutput(float val) {\n ${e.output} = vec4(val, 0, 0, 0);\n }\n `}(i)),n.packedInputs&&(p+=eb),[p,u,c,a,l,s,n.userCode].join("\n")}function Xy(e,t=!1){const n=e.shapeInfo.logicalShape;switch(n.length){case 0:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`float ${r}() {return ${n};}`;const[a,s]=e.shapeInfo.texShape;if(1===a&&1===s)return`\n float ${r}() {\n return sampleTexture(${n}, halfCR);\n }\n `;const o=tb(n);if(t)return`\n float ${r}() {\n vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], ${o});\n return sampleTexture(${n}, uv);\n }\n `;const[i,u]=e.shapeInfo.texShape;return`\n float ${r}() {\n vec2 uv = uvFromFlat(${i}, ${u}, ${o});\n return sampleTexture(${n}, uv);\n }\n `}(e,t);case 1:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`\n float ${r}(int index) {\n ${nb(e)}\n }\n `;const a=e.shapeInfo.texShape,s=a[0],o=a[1];if(1===o&&1===s)return`\n float ${r}(int index) {\n return sampleTexture(${n}, halfCR);\n }\n `;const i=tb(n);return 1===o?t?`\n float ${r}(int index) {\n vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / float(${n}TexShape[0]));\n return sampleTexture(${n}, uv);\n }\n `:`\n float ${r}(int index) {\n vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / ${s}.0);\n return sampleTexture(${n}, uv);\n }\n `:1===s?t?`\n float ${r}(int index) {\n vec2 uv = vec2((float(index + ${i}) + 0.5) / float(${n}TexShape[1]), 0.5);\n return sampleTexture(${n}, uv);\n }\n `:`\n float ${r}(int index) {\n vec2 uv = vec2((float(index + ${i}) + 0.5) / ${o}.0, 0.5);\n return sampleTexture(${n}, uv);\n }\n `:t?`\n float ${r}(int index) {\n vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${i});\n return sampleTexture(${n}, uv);\n }\n `:`\n float ${r}(int index) {\n vec2 uv = uvFromFlat(${s}, ${o}, index + ${i});\n return sampleTexture(${n}, uv);\n }\n `}(e,t);case 2:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),s=e.shapeInfo.texShape;if(null!=s&&tt(n,s)){if(t)return`\n float ${a}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `;const e=s[0];return`\n float ${a}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${s[1]}.0, ${e}.0);\n return sampleTexture(${r}, uv);\n }\n `}const{newShape:o,keptDims:i}=ut(n),u=o;if(u.length<n.length){const n=["row","col"];return`\n ${Xy(sb(e,u),t)}\n float ${a}(int row, int col) {\n return ${a}(${ob(n,i)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${a}(int row, int col) {\n int index = round(dot(vec2(row, col), vec2(${n[1]}, 1)));\n ${nb(e)}\n }\n `;const l=s[0],c=s[1],p=tb(r);return 1===c?t?`\n float ${a}(int row, int col) {\n float index = dot(vec3(row, col, ${p}), vec3(${r}Shape[1], 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / float(${r}TexShape[0]));\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col) {\n float index = dot(vec3(row, col, ${p}), vec3(${n[1]}, 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);\n return sampleTexture(${r}, uv);\n }\n `:1===l?t?`\n float ${a}(int row, int col) {\n float index = dot(vec3(row, col, ${p}), vec3(${r}Shape[1], 1, 1));\n vec2 uv = vec2((index + 0.5) / float(${r}TexShape[1]), 0.5);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col) {\n float index = dot(vec3(row, col, ${p}), vec3(${n[1]}, 1, 1));\n vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);\n return sampleTexture(${r}, uv);\n }\n `:t?`\n float ${a}(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${r}Shape[1] + col + ${p};\n vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${n[1]} + col + ${p};\n vec2 uv = uvFromFlat(${l}, ${c}, index);\n return sampleTexture(${r}, uv);\n }\n`}(e,t);case 3:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),s=n[1]*n[2],o=n[2],{newShape:i,keptDims:u}=ut(n),l=i;if(l.length<n.length){const n=["row","col","depth"];return`\n ${Xy(sb(e,l),t)}\n float ${a}(int row, int col, int depth) {\n return ${a}(${ob(n,u)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${a}(int row, int col, int depth) {\n int index = round(dot(vec3(row, col, depth),\n vec3(${s}, ${o}, 1)));\n ${nb(e)}\n }\n `;const c=e.shapeInfo.texShape,p=c[0],h=c[1],d=e.shapeInfo.flatOffset;if(h===s&&null==d)return t?`\n float ${a}(int row, int col, int depth) {\n int stride1 = ${r}Shape[2];\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2(stride1, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col, int depth) {\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2(${o}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${h}.0, ${p}.0);\n return sampleTexture(${r}, uv);\n }\n `;if(h===o&&null==d)return t?`\n float ${a}(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2(${r}Shape[1], 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2(${n[1]}, 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${h}.0, ${p}.0);\n return sampleTexture(${r}, uv);\n }\n `;const f=tb(r);return t?`\n float ${a}(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int stride0 = ${r}Shape[1] * ${r}Shape[2];\n int stride1 = ${r}Shape[2];\n int index = row * stride0 + col * stride1 + depth + ${f};\n vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${s} + col * ${o} + depth + ${f};\n vec2 uv = uvFromFlat(${p}, ${h}, index);\n return sampleTexture(${r}, uv);\n }\n `}(e,t);case 4:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),s=n[3],o=n[2]*s,i=n[1]*o,{newShape:u,keptDims:l}=ut(n);if(u.length<n.length){const n=["row","col","depth","depth2"];return`\n ${Xy(sb(e,u),t)}\n float ${a}(int row, int col, int depth, int depth2) {\n return ${a}(${ob(n,l)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${a}(int row, int col, int depth, int depth2) {\n int index = round(dot(vec4(row, col, depth, depth2),\n vec4(${i}, ${o}, ${s}, 1)));\n ${nb(e)}\n }\n `;const c=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,h=p[0],d=p[1],f=`int stride2 = ${r}Shape[3];`,m=`int stride1 = ${r}Shape[2] * stride2;`,g=`int stride0 = ${r}Shape[1] * stride1;`;if(d===i&&null==c)return t?`\n float ${a}(int row, int col, int depth, int depth2) {\n ${f}\n ${m}\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3(stride1, stride2, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col, int depth, int depth2) {\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3(${o}, ${s}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${d}.0, ${h}.0);\n return sampleTexture(${r}, uv);\n }\n `;if(d===s&&null==c)return t?`\n float ${a}(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3(${r}Shape[1] * ${r}Shape[2], ${r}Shape[2], 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${r}TexShape[1], ${r}TexShape[0]);\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3(${n[1]*n[2]}, ${n[2]}, 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${d}.0, ${h}.0);\n return sampleTexture(${r}, uv);\n }\n `;const y=tb(r);return t?`\n float ${a}(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n ${f}\n ${m}\n ${g}\n int index = row * stride0 + col * stride1 +\n depth * stride2 + depth2;\n vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index + ${y});\n return sampleTexture(${r}, uv);\n }\n `:`\n float ${a}(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${i} + col * ${o} +\n depth * ${s} + depth2;\n vec2 uv = uvFromFlat(${h}, ${d}, index + ${y});\n return sampleTexture(${r}, uv);\n }\n `}(e,t);case 5:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=t[4],s=t[3]*a,o=t[2]*s,i=t[1]*o,{newShape:u,keptDims:l}=ut(t);if(u.length<t.length){const t=["row","col","depth","depth2","depth3"];return`\n ${Xy(sb(e,u))}\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n return ${r}(${ob(t,l)});\n }\n `}if(e.shapeInfo.isUniform)return`\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n float index = dot(\n vec4(row, col, depth, depth2),\n vec4(${i}, ${o}, ${s}, ${a})) +\n depth3;\n ${nb(e)}\n }\n `;const c=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,h=p[0],d=p[1];return d===i&&null==c?`\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4(${o}, ${s}, ${a}, 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${d}.0, ${h}.0);\n return sampleTexture(${n}, uv);\n }\n `:d===a&&null==c?`\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n float texR = dot(\n vec4(row, col, depth, depth2),\n vec4(${t[1]*t[2]*t[3]},\n ${t[2]*t[3]}, ${t[3]}, 1));\n int texC = depth3;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${d}.0, ${h}.0);\n return sampleTexture(${n}, uv);\n }\n `:`\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${i} + col * ${o} + depth * ${s} +\n depth2 * ${a} + depth3 + ${tb(n)};\n vec2 uv = uvFromFlat(${h}, ${d}, index);\n return sampleTexture(${n}, uv);\n }\n `}(e);case 6:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:a,keptDims:s}=ut(t);if(a.length<t.length){const t=["row","col","depth","depth2","depth3","depth4"];return`\n ${Xy(sb(e,a))}\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return ${r}(${ob(t,s)});\n }\n `}const o=t[5],i=t[4]*o,u=t[3]*i,l=t[2]*u,c=t[1]*l;if(e.shapeInfo.isUniform)return`\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int index = round(dot(\n vec4(row, col, depth, depth2),\n vec4(${c}, ${l}, ${u}, ${i})) +\n dot(\n vec2(depth3, depth4),\n vec2(${o}, 1)));\n ${nb(e)}\n }\n `;const p=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,d=h[0],f=h[1];return f===c&&null==p?`\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n int texR = row;\n float texC = dot(vec4(col, depth, depth2, depth3),\n vec4(${l}, ${u}, ${i}, ${o})) +\n float(depth4);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${f}.0, ${d}.0);\n return sampleTexture(${n}, uv);\n }\n `:f===o&&null==p?`\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n float texR = dot(vec4(row, col, depth, depth2),\n vec4(${t[1]*t[2]*t[3]*t[4]},\n ${t[2]*t[3]*t[4]},\n ${t[3]*t[4]},\n ${t[4]})) + float(depth3);\n int texC = depth4;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${f}.0, ${d}.0);\n return sampleTexture(${n}, uv);\n }\n `:`\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * ${c} + col * ${l} + depth * ${u} +\n depth2 * ${i} + depth3 * ${o} + depth4 + ${tb(n)};\n vec2 uv = uvFromFlat(${d}, ${f}, index);\n return sampleTexture(${n}, uv);\n }\n `}(e);default:throw new Error(`${n.length}-D input sampling is not yet supported`)}}function Yy(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return function(e){const t=e.name;return`\n vec4 ${"get"+t.charAt(0).toUpperCase()+t.slice(1)}() {\n return ${Vy().texture2D}(${t}, halfCR);\n }\n `}(e);case 1:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=e.shapeInfo.texShape,s=Vy();if(t)return`\n vec4 ${r}(int index) {\n ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));\n vec2 uv = packedUVfrom1D(\n packedTexShape[0], packedTexShape[1], index);\n return ${s.texture2D}(${n}, uv);\n }\n `;const o=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];return`\n vec4 ${r}(int index) {\n vec2 uv = packedUVfrom1D(\n ${o[0]}, ${o[1]}, index);\n return ${s.texture2D}(${n}, uv);\n }\n `}(e,t);case 2:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),s=e.shapeInfo.texShape,o=s[0],i=s[1],u=Vy();if(null!=s&&tt(n,s))return t?`\n vec4 ${a}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);\n\n return ${u.texture2D}(${r}, uv);\n }\n `:`\n vec4 ${a}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${i}.0, ${o}.0);\n\n return ${u.texture2D}(${r}, uv);\n }\n `;if(t)return`\n vec4 ${a}(int row, int col) {\n ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));\n int valuesPerRow = int(ceil(float(${r}Shape[1]) / 2.0));\n vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);\n return ${u.texture2D}(${r}, uv);\n }\n `;const l=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];return`\n vec4 ${a}(int row, int col) {\n vec2 uv = packedUVfrom2D(${Math.ceil(n[1]/2)}, ${l[0]}, ${l[1]}, row, col);\n return ${u.texture2D}(${r}, uv);\n }\n `}(e,t);case 3:return function(e,t){const n=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),s=e.shapeInfo.texShape,o=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];if(1===n[0]){const r=[1,2],s=["b","row","col"];return`\n ${Yy(sb(e,n.slice(1)),t)}\n vec4 ${a}(int b, int row, int col) {\n return ${a}(${ob(s,r)});\n }\n `}const i=Vy();if(t)return`\n vec4 ${a}(int b, int row, int col) {\n ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));\n int valuesPerRow = int(ceil(float(${r}Shape[2]) / 2.0));\n int texelsInBatch = valuesPerRow * int(ceil(float(${r}Shape[1]) / 2.0));\n vec2 uv = packedUVfrom3D(\n packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);\n return ${i.texture2D}(${r}, uv);\n }\n `;const u=o[0],l=o[1],c=Math.ceil(n[2]/2);return`\n vec4 ${a}(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n ${u}, ${l}, ${c*Math.ceil(n[1]/2)}, ${c}, b, row, col);\n return ${i.texture2D}(${r}, uv);\n }\n `}(e,t);default:return function(e,t){const n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=Vy();if(t)return`\n vec4 ${r}(int b2, int b, int row, int col) {\n int valuesPerRow = int(ceil(float(${n}Shape[3]) / 2.0));\n int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[2]) / 2.0));\n int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);\n texelsInBatch *= ${n}Shape[1];\n index = b2 * texelsInBatch + index;\n ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));\n int texR = index / packedTexShape[1];\n int texC = index - texR * packedTexShape[1];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${a.texture2D}(${n}, uv);\n }\n `;const s=e.shapeInfo.logicalShape,o=s.length,i=e.shapeInfo.texShape,u=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],l=u[0],c=u[1],p=Math.ceil(s[o-1]/2);let h=p*Math.ceil(s[o-2]/2),d="int b, int row, int col",f=`b * ${h} + (row / 2) * ${p} + (col / 2)`;for(let e=2;e<o-1;e++)d=`int b${e}, `+d,h*=s[o-e-1],f=`b${e} * ${h} + `+f;return`\n vec4 ${r}(${d}) {\n int index = ${f};\n int texR = index / ${c};\n int texC = index - texR * ${c};\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${c}, ${l});\n return ${a.texture2D}(${n}, uv);\n }\n `}(e,t)}}const Qy="\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",Jy="\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n int texNumC, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",Zy="\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",eb="\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n float getChannel(vec4 frag, int dim) {\n float modCoord = mod(float(dim), 2.);\n return modCoord == 0. ? frag.r : frag.g;\n }\n";function tb(e){return`offset${e}`}function nb(e){const t=e.name,n=et(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`\n for (int i = 0; i < ${n}; i++) {\n if (i == index) {\n return ${t}[i];\n }\n }\n `}function rb(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function ab(e,t,n){const{newShape:r,keptDims:a}=ut(t),s=t.length,o=e&&3===s&&1===t[0],i=o?t.slice(1):r,u=!e&&s>1&&!tt(t,n)&&r.length<s||o;return{useSqueezeShape:u,uniformShape:u?i:t,keptDims:a}}function sb(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function ob(e,t){return t.map((t=>e[t])).join(", ")}function ib(e,t,n){const r={},a={},s={},o=[];let i,u,l,c=null,p=null;p=e.getUniformLocation(n,"NAN",!1),1===Ct().getNumber("WEBGL_VERSION")&&(c=e.getUniformLocation(n,"INFINITY",!1));const h=!1;for(let o=0;o<t.variableNames.length;o++){const i=t.variableNames[o];r[i]=e.getUniformLocation(n,i,h),r[`offset${i}`]=e.getUniformLocation(n,`offset${i}`,h),t.enableShapeUniforms&&(a[`${i}Shape`]=e.getUniformLocation(n,`${i}Shape`,h),s[`${i}TexShape`]=e.getUniformLocation(n,`${i}TexShape`,h))}return t.enableShapeUniforms&&(i=e.getUniformLocation(n,"outShape",h),l=e.getUniformLocation(n,"outShapeStrides",h),u=e.getUniformLocation(n,"outTexShape",h)),t.customUniforms&&t.customUniforms.forEach(((t,r)=>{o[r]=e.getUniformLocation(n,t.name,h)})),{uniformLocations:r,customUniformLocations:o,infLoc:c,nanLoc:p,inShapesLocations:a,inTexShapesLocations:s,outShapeLocation:i,outShapeStridesLocation:l,outTexShapeLocation:u}}function ub(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach(((e,n)=>{const r=e.logicalShape,a=t[n],s=a.shape;if(!tt(r,s))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${r} and ${s} must match`);if(e.isUniform&&a.isUniform)return;const o=e.texShape,i=a.isUniform?null:a.texData.texShape;if(!tt(o,i))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${o} and ${i} must match`)}))}function lb(e){return Ct().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}class cb{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=dy.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=Vy();this.outputShape=e,this.enableShapeUniforms=lb(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?Hy(["r","c","d"],e):Wy(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));\n int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n ${t.output} = result;\n }\n `}}class pb{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=dy.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=Vy();this.outputShape=e,this.enableShapeUniforms=lb(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?Hy(["r","c","d"],e):Wy(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));\n int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n ${t.output} = result;\n }\n `}}class hb{constructor(e){this.variableNames=["A"],this.outTexUsage=fy.DOWNLOAD;const t=Vy();this.outputShape=e,this.userCode=`\n ${jy}\n\n void main() {\n float x = getAAtOutCoords();\n ${t.output} = encode_float(x);\n }\n `}}class db{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=fy.DOWNLOAD;const t=Vy();this.outputShape=e,this.userCode=`\n ${jy}\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n ${t.output} = encode_float(x);\n }\n `}}const fb={R:0,G:1,B:2,A:3};class mb{constructor(e,t=!1,n="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const r=Vy();this.outputShape=e,this.enableShapeUniforms=lb(this.outputShape.length);let a="result";t&&(a="floor(result * 255. + 0.5)");let s="";for(let e=0;e<n.length;e++){const t=n[e];s+=`\n if(offset == ${e}) {\n result = values[${fb[t]}];\n }`}this.userCode=`\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":Gy(e)}\n\n void main() {\n ivec3 coords = getOutputCoords();\n int flatIndex = getFlatIndex(coords);\n float result = 0.;\n int offset = imod(flatIndex, ${n.length});\n\n flatIndex = idiv(flatIndex, ${n.length}, 1.);\n\n int r = flatIndex / texShape[1];\n if (r < texShape[0]) {\n int c = imod(flatIndex, texShape[1]);\n vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\n vec4 values = ${r.texture2D}(A, uv);\n ${s}\n }\n ${r.output} = vec4(${a}, 0., 0., 0.);\n }\n `}}class gb{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=Vy();this.outputShape=e,this.enableShapeUniforms=lb(this.outputShape.length);let r="",a="result";t&&(a="floor(result * 255. + 0.5)");for(let t=0;t<=1;t++)for(let a=0;a<=1;a++){const s=2*t+a;r+=`\n localCoords = coords;\n if(localCoords[2] + ${a} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {\n localCoords[2] += ${a};\n if (localCoords[1] + ${t} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {\n localCoords[1] += ${t};\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n\n int r = flatIndex / texShape[1];\n int c = imod(flatIndex, texShape[1]);\n vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\n values = ${n.texture2D}(A, uv);\n\n if (offset == 0) {\n result[${s}] = values[0];\n } else if (offset == 1) {\n result[${s}] = values[1];\n } else if (offset == 2) {\n result[${s}] = values[2];\n } else {\n result[${s}] = values[3];\n }\n }\n }\n `}this.userCode=`\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":Gy(e)}\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n\n ${r}\n\n ${n.output} = ${a};\n }\n `}}function yb(e,t,n,r,a,s){!function(e,t){const n=Ct().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0)throw new Error(`Requested texture size [${e}x${t}] is invalid.`);if(e>n||t>n)throw new Error(`Requested texture size [${e}x${t}] greater than WebGL maximum on this browser / GPU [${n}x${n}].`)}(t,n);const o=function(e){return Ay(e,(()=>e.createTexture()),"Unable to create WebGLTexture.")}(e),i=e.TEXTURE_2D;return xy(e,(()=>e.bindTexture(i,o))),xy(e,(()=>e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE))),xy(e,(()=>e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE))),xy(e,(()=>e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST))),xy(e,(()=>e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST))),1===Ct().getNumber("WEBGL_VERSION")?xy(e,(()=>e.texImage2D(i,0,r,t,n,0,a,s,null))):xy(e,(()=>e.texStorage2D(i,1,r,t,n))),xy(e,(()=>e.bindTexture(e.TEXTURE_2D,null))),{texture:o,texShape:[n,t]}}function bb(e){return e.internalFormatFloat}function _b(e){return e.internalFormatHalfFloat}function xb(e){return e.downloadTextureFormat}function vb(e){return e.internalFormatPackedFloat}function wb(e){return e.internalFormatPackedHalfFloat}class Tb{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];const t=Ct().getNumber("WEBGL_VERSION");if(null!=e?(this.gl=e,function(e,t){cy[e]=t}(t,e)):this.gl=hy(t),e=this.gl,2===Ct().getNumber("WEBGL_VERSION")){const t=e;this.createVertexArray=()=>xy(t,(()=>t.createVertexArray())),this.bindVertexArray=e=>xy(t,(()=>t.bindVertexArray(e))),this.deleteVertexArray=e=>xy(t,(()=>t.deleteVertexArray(e))),this.getVertexArray=()=>xy(t,(()=>t.getParameter(t.VERTEX_ARRAY_BINDING)))}else if(null!=e){const t=e.getExtension("OES_vertex_array_object");if(null==t)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>xy(e,(()=>t.createVertexArrayOES())),this.bindVertexArray=n=>xy(e,(()=>t.bindVertexArrayOES(n))),this.deleteVertexArray=n=>xy(e,(()=>t.deleteVertexArrayOES(n))),this.getVertexArray=()=>xy(e,(()=>e.getParameter(t.VERTEX_ARRAY_BINDING_OES)))}let n="WEBGL_color_buffer_float";const r="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),1===Ct().getNumber("WEBGL_VERSION")){const e="OES_texture_float",t="OES_texture_half_float";if(this.textureFloatExtension=wy(this.gl,e),Py(this.gl,t))this.textureHalfFloatExtension=wy(this.gl,t);else if(Ct().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Py(this.gl,r))this.colorBufferHalfFloatExtension=wy(this.gl,r);else if(Ct().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Py(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!Py(this.gl,r))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension(r)}this.vertexBuffer=function(e){return function(e,t){const n=Ay(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return xy(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),xy(e,(()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW))),n}(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}(this.gl),this.indexBuffer=function(e){return function(e,t){const n=Ay(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return xy(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n))),xy(e,(()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW))),n}(e,new Uint16Array([0,1,2,2,1,3]))}(this.gl),this.framebuffer=function(e){return Ay(e,(()=>e.createFramebuffer()),"Unable to create WebGLFramebuffer.")}(this.gl),this.textureConfig=_y(this.gl,this.textureHalfFloatExtension)}get debug(){return Ct().getBool("DEBUG")}dispose(){if(this.disposed)return;null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");const e=this.gl;xy(e,(()=>e.finish())),xy(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,null))),xy(e,(()=>e.deleteFramebuffer(this.framebuffer))),xy(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,null))),xy(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null))),xy(e,(()=>e.deleteBuffer(this.indexBuffer))),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=gy(t,n);return yb(e,a,s,bb(r),r.textureFormatFloat,e.FLOAT)}(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=gy(t,n);return yb(e,a,s,_b(r),r.textureFormatFloat,r.textureTypeHalfFloat)}(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=gy(t,n);return yb(e,a,s,xb(r),e.RGBA,e.UNSIGNED_BYTE)}(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),function(e,t,n){xy(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),n.data instanceof Uint8Array?2===Ct().getNumber("WEBGL_VERSION")?xy(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data))):xy(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data))):2===Ct().getNumber("WEBGL_VERSION")?xy(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n))):xy(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n))),xy(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,r){this.throwIfDisposed(),function(e,t,n,r,a,s){let o,i,u;xy(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),a instanceof Uint8Array?(o=new Uint8Array(n*r*4),i=e.UNSIGNED_BYTE,u=e.RGBA):(o=new Float32Array(n*r*4),i=e.FLOAT,u=s.internalFormatPackedFloat),o.set(a),2===Ct().getNumber("WEBGL_VERSION")?xy(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGBA,i,o))):xy(e,(()=>e.texImage2D(e.TEXTURE_2D,0,u,n,r,0,e.RGBA,i,o))),xy(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}(this.gl,e,t,n,r,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=by(t,n);return yb(e,a,s,wb(r),e.RGBA,r.textureTypeHalfFloat)}(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=by(t,n);return yb(e,a,s,vb(r),e.RGBA,e.FLOAT)}(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Ny(this.gl,this.framebuffer),this.outputTexture=null),xy(this.gl,(()=>this.gl.deleteTexture(e)))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>function(e,t,n,r){const[a,s]=gy(t,n),o=new Uint8Array(t*n*4);return xy(e,(()=>e.readPixels(0,0,a,s,r.downloadTextureFormat,e.UNSIGNED_BYTE,o))),new Float32Array(o.buffer)}(this.gl,t,n,this.textureConfig)))}downloadPackedMatrixFromBuffer(e,t,n,r,a,s){return function(e,t,n,r,a,s,o,i){const u=e,l=new Float32Array(function(e,t){const[n,r]=by(e,t);return n*r*4}(s,o));return u.bindBuffer(u.PIXEL_PACK_BUFFER,t),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,l),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),l}(this.gl,e,0,0,0,a,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return function(e,t,n){const r=e,a=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,t),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,a),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),a}(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const r=function(e,t,n,r){const a=e.createBuffer();xy(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,a)));const s=16*t*n;return xy(e,(()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ))),xy(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0))),xy(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null))),a}(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(Ct().getBool("WEBGL_FENCE_API_ENABLED")){const r=e,a=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{const e=r.clientWaitSync(a,0,0);return e===r.ALREADY_SIGNALED||e===r.CONDITION_SATISFIED},t=a}else Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>function(e,t,n){const r=new Float32Array(t*n*4);return xy(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,r))),r}(this.gl,t,n)))}createProgram(e){this.throwIfDisposed();const t=this.gl;null==this.vertexShader&&(this.vertexShader=function(e){const t=Vy();return function(e,t){const n=Ay(e,(()=>e.createShader(e.VERTEX_SHADER)),"Unable to create vertex WebGLShader.");if(xy(e,(()=>e.shaderSource(n,t))),xy(e,(()=>e.compileShader(n))),!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw console.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}(e,`${t.version}\n precision highp float;\n ${t.attribute} vec3 clipSpacePos;\n ${t.attribute} vec2 uv;\n ${t.varyingVs} vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }`)}(t));const n=function(e){return Ay(e,(()=>e.createProgram()),"Unable to create WebGLProgram.")}(t);let r;return xy(t,(()=>t.attachShader(n,this.vertexShader))),xy(t,(()=>t.attachShader(n,e))),function(e,t){if(xy(e,(()=>e.linkProgram(t))),!Ct().get("ENGINE_COMPILE_ONLY")&&!1===e.getProgramParameter(t,e.LINK_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}(t,n),r=Object.assign(n,{vao:this.createVertexArray()}),this.bindVertexArray(r.vao),xy(t,(()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer))),console.assert(function(e,t,n){return xy(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),Sy(e,t,"clipSpacePos",n,3,20,0)&&Sy(e,t,"uv",n,2,20,12)}(t,r,this.vertexBuffer),"gpgpu_util.bindVertexProgramAttributeStreams not fully successful."),this.debug&&Iy(t,r),this.setProgram(r),r}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&(xy(this.gl,(()=>this.gl.deleteProgram(e))),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,null!=this.program&&(this.bindVertexArray(this.program.vao),this.debug&&Iy(this.gl,this.program)),xy(this.gl,(()=>this.gl.useProgram(e)))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?function(e,t,n){return Ay(e,(()=>e.getUniformLocation(t,n)),'uniform "'+n+'" not present in program.')}(this.gl,e,t):function(e,t,n){return e.getUniformLocation(t,n)}(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),xy(this.gl,(()=>this.gl.getAttribLocation(e,t)))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),function(e,t,n,r){xy(e,(()=>function(e,t,n){!function(e,t){const n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+e.TEXTURE0;if(r<e.TEXTURE0||r>n)throw new Error(`textureUnit must be in [gl.TEXTURE0, gl.TEXTURE${n}].`)}(e,n),xy(e,(()=>e.activeTexture(e.TEXTURE0+n))),xy(e,(()=>e.bindTexture(e.TEXTURE_2D,t)))}(e,t,r))),xy(e,(()=>e.uniform1i(n,r)))}(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[r,a]=by(t,n);this.setOutputMatrixTextureDriver(e,r,a)}setOutputMatrixWriteRegion(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t)}setOutputPackedMatrixWriteRegion(e,t,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){null!=this.program&&Iy(this.gl,this.program),Cy(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;if(this.debug){const e=this.getVertexArray();console.assert(e===this.program.vao,"VAO changed between setProgram and executeProgram!"),this.debugValidate()}xy(e,(()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),xy(this.gl,(()=>this.gl.finish()))}getQueryTimerExtension(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=wy(this.gl,2===Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(2===Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}const e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(2===Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2();return void e.endQuery(t.TIME_ELAPSED_EXT)}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await st((()=>this.disposed||this.isQueryAvailable(e,Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")))),this.getQueryTime(e,Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(0===t)return null;if(2===t){const t=this.gl;return t.getQueryParameter(e,t.QUERY_RESULT)/1e6}{const t=this.getQueryTimerExtensionWebGL1();return t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(0===t)return!0;if(2===t){const t=this.gl,n=this.getQueryTimerExtensionWebGL2(),r=t.getQueryParameter(e,t.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),r&&!this.disjoint}{const t=this.getQueryTimerExtensionWebGL1(),n=t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(t.GPU_DISJOINT_EXT)),n&&!this.disjoint}}pollFence(e){return new Promise((t=>{this.addItemToPoll((()=>e.isFencePassed()),(()=>t()))}))}pollItems(){const e=function(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}(this.itemsToPoll.map((e=>e.isDoneFn)));for(let t=0;t<=e;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;let n;"setTimeoutCustom"in Ct().platform&&(n=Ct().platform.setTimeoutCustom.bind(Ct().platform)),st((()=>(this.pollItems(),0===this.itemsToPoll.length)),(()=>0),null,n)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),Ey(this.gl,e,this.framebuffer),this.debug&&Cy(this.gl)}unbindTextureToFrameBuffer(){null!=this.outputTexture?(Ey(this.gl,this.outputTexture,this.framebuffer),this.debug&&Cy(this.gl)):Ny(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();const r=this.gl;Ey(r,e,this.framebuffer),this.debug&&Cy(r),this.outputTexture=e,xy(r,(()=>r.viewport(0,0,t,n))),xy(r,(()=>r.scissor(0,0,t,n)))}setOutputMatrixWriteRegionDriver(e,t,n,r){this.throwIfDisposed(),xy(this.gl,(()=>this.gl.scissor(e,t,n,r)))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(null==this.program)throw new Error("No GPU program is currently set.")}}const{addImpl:kb,bincountImpl:Ib,bincountReduceImpl:Sb,castImpl:Eb,ceilImpl:Nb,concatImpl:Cb,equalImpl:Ab,expImpl:Rb,expm1Impl:$b,floorImpl:Mb,gatherNdImpl:Fb,gatherV2Impl:Ob,greaterImpl:Db,greaterEqualImpl:Lb,lessImpl:Pb,lessEqualImpl:Bb,linSpaceImpl:Ub,logImpl:zb,maxImpl:Vb,maximumImpl:Wb,minimumImpl:Hb,multiplyImpl:Gb,negImpl:jb,notEqualImpl:Kb,prodImpl:qb,raggedGatherImpl:Xb,raggedRangeImpl:Yb,raggedTensorToTensorImpl:Qb,rangeImpl:Jb,rsqrtImpl:Zb,scatterImpl:e_,sigmoidImpl:t_,simpleAbsImpl:n_,sliceImpl:r_,sparseFillEmptyRowsImpl:a_,sparseReshapeImpl:s_,sparseSegmentReductionImpl:o_,sqrtImpl:i_,stridedSliceImpl:u_,stringNGramsImpl:l_,stringSplitImpl:c_,stringToHashBucketFastImpl:p_,subImpl:h_,tileImpl:d_,topKImpl:f_,transposeImpl:m_,uniqueImpl:g_}=kg;function y_(e,t){return["x","y","z","w","u","v"].slice(0,t).map((t=>`${e}.${t}`))}function b_(e,t){return 1===t?[e]:y_(e,t)}class __{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=lb(this.outputShape.length),0===this.rank)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{const e=b_("rc",this.rank),t=rb(this.rank),n=this.getOutOfBoundsCondition(e),r=this.getSetup(e),a=this.getOutput(e);this.userCode=`\n void main() {\n ${t} rc = getOutputCoords();\n\n if(${n}) {\n setOutput(vec4(0));\n } else {\n ${r}\n\n setOutput(vec4(${a}));\n }\n }\n `}}getSourceCoordsArr(e){const t=[];for(let n=0;n<=1;n++)for(let r=0;r<=1;r++){let a=`${0===n?"r":"rp1"}, ${0===r?"c":"cp1"}`;for(let t=2;t<this.rank;t++)a=`${e[e.length-1-t]},`+a;t.push(a)}return t}getOutOfBoundsCondition(e){if(1===this.rank)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let n=this.rank-2;n<this.rank;n++)t+=`${e[n]} >= ${this.enableShapeUniforms?`outShape[${n}]`:this.outputShape[n]}`,n<this.rank-1&&(t+="||");return t}getSetup(e){if(1===this.rank)return"";const t=e.slice(-2),n=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],r=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`\n int r = ${t[0]};\n int c = ${t[1]};\n int rp1 = r + 1;\n int cp1 = c + 1;\n\n bool cEdge = cp1 >= ${n};\n bool rEdge = rp1 >= ${r};\n `}getOutput(e){const t=this.getSourceCoordsArr(e);return 1===this.rank?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${t[0]}),\n cEdge ? 0. : getA(${t[1]}),\n rEdge ? 0. : getA(${t[2]}),\n rEdge || cEdge ? 0. : getA(${t[3]})`}}class x_{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=lb(this.outputShape.length);let n="";for(let e=0;e<4;e++){let t="thisRC = rc;";e%2==1&&(t+="thisRC.z += 1;"),e>1&&(t+="thisRC.y += 1;"),n+=`\n ${t}\n ${e>0?"if(thisRC.y < rows && thisRC.z < cols){":""}\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result[${e}] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n ${e>0?"}":""}\n `}var r,a;this.userCode=`\n ${r=t,a=this.enableShapeUniforms,`\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n ${a?function(e,t,n="index"){const r=e.map(((e,t)=>t)),a=function(e,t){const n=e.length,r=e.map((e=>`${t}[${e}]`)),a=new Array(n-1);a[n-2]=r[n-1];for(let e=n-3;e>=0;--e)a[e]=`(${a[e+1]} * ${r[e+1]})`;return a}(r,t);return a.map(((t,r)=>`int ${e[r]} = ${n} / ${a[r]}; ${r===a.length-1?`int ${e[r+1]} = ${n} - ${e[r]} * ${a[r]}`:`index -= ${e[r]} * ${a[r]}`};`)).join("")}(["r","c","d"],"inputShape"):Wy(["r","c","d"],r)}\n return ivec3(r, c, d);\n }\n `}\n ${this.enableShapeUniforms?"\n int getFlatIndex(ivec3 coords) {\n return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n }\n":Gy(e)}\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]};\n int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]};\n\n ${n}\n\n setOutput(result);\n }\n `}}class v_{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,n){const r=T_(t,n),a=k_(e,r,n);a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]);const s=w_(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=s,this.log();const e=this.freeTextures[a].shift();return this.usedTextures[a].push(e),e}let o;return r===my.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===my.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===my.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===my.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===my.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[a].push(o),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),o}releaseTexture(e,t,n,r){if(null==this.freeTextures)return;const a=T_(n,r),s=k_(t,a,r);s in this.freeTextures||(this.freeTextures[s]=[]);const o=w_(t,a,this.gpgpu.gl,this.gpgpu.textureConfig,r),i=Ct().get("WEBGL_DELETE_TEXTURE_THRESHOLD");-1!==i&&this._numBytesAllocated>i?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=o):(this.freeTextures[s].push(e),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;const u=this.usedTextures[s],l=u.indexOf(e);if(l<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u.splice(l,1),this.log()}log(){if(!this.logEnabled)return;const e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(null!=this.freeTextures){for(const e in this.freeTextures)this.freeTextures[e].forEach((e=>{this.gpgpu.deleteMatrixTexture(e.texture)}));for(const e in this.usedTextures)this.usedTextures[e].forEach((e=>{this.gpgpu.deleteMatrixTexture(e.texture)}));this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}}function w_(e,t,n,r,a){const s=function(e,t){switch(e){case my.PACKED_2X2_FLOAT32:return vb(t);case my.PACKED_2X2_FLOAT16:return wb(t);case my.UNPACKED_FLOAT32:return bb(t);case my.UNPACKED_FLOAT16:return _b(t);case my.PACKED_4X1_UNSIGNED_BYTE:return xb(t);default:throw new Error(`Unknown physical texture type ${e}`)}}(t,r);let o;if(a){const[t,n]=by(e[0],e[1]);o=t*n}else{const[t,n]=gy(e[0],e[1]);o=t*n}const i=function(e,t){const n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;if(t===n.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}(n,s);return o*i}function T_(e,t){if(e===fy.UPLOAD)return my.PACKED_2X2_FLOAT32;if(e===fy.RENDER||null==e)return function(e){return Ct().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?my.PACKED_2X2_FLOAT32:my.UNPACKED_FLOAT32:e?my.PACKED_2X2_FLOAT16:my.UNPACKED_FLOAT16}(t);if(e===fy.DOWNLOAD||e===fy.PIXELS)return my.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function k_(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class I_{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=lb(this.outputShape.length),this.userCode=`\n float unaryOperation(float x) {\n ${t}\n }\n\n void main() {\n float x = getAAtOutCoords();\n float y = unaryOperation(x);\n\n setOutput(y);\n }\n `}}const S_="if (isnan(x)) return x;",E_="return abs(x);",N_="return x;";class C_{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=lb(this.outputShape.length),this.userCode=`\n vec4 unaryOperation(vec4 x) {\n ${t}\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n `}}class A_{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=lb(this.outputShape.length);const t=e.length,n=b_("rc",t),r=rb(t),a=function(e,t){if(1===e)return"rc";let n="";for(let r=0;r<e;r++)n+=t[r],r<e-1&&(n+=",");return n}(t,n),s=n.slice(-2),o=t<=1?"rc":`vec2(${s.join(",")})`;this.userCode=`\n void main() {\n ${r} rc = getOutputCoords();\n vec4 packedInput = getA(${a});\n\n setOutput(getChannel(packedInput, ${o}));\n }\n `}}const R_=Qp,$_={},M_=Ct().getNumber("CPU_HANDOFF_SIZE_THRESHOLD");class F_ extends je{constructor(e){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!Ct().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(null!=e){if(e instanceof Tb)t=e;else{const n=hy(Ct().getNumber("WEBGL_VERSION"),e);t=new Tb(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{const e=hy(Ct().getNumber("WEBGL_VERSION"));t=new Tb(e),this.binaryCache=((n=Ct().getNumber("WEBGL_VERSION"))in $_||($_[n]={}),$_[n]),this.gpgpuCreatedLocally=!0}var n;this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new v_(this.gpgpu),this.numMBBeforeWarning=null==Ct().global.screen?1024:Ct().global.screen.height*Ct().global.screen.width*window.devicePixelRatio*600/1024/1024,this.texData=new Ge(this,yi())}nextDataId(){return F_.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(e,t,n,r,a,s){const o=this.makeTensorInfo(t,n),i=this.texData.get(o.dataId);i.isPacked=!1,i.texture={texture:e,texShape:[r,a]},i.texShape=[r,a];const u=My(t),l=new mb(u,!1,s),c=this.runWebGLProgram(l,[o],n,[[r,a]]);return c.shape=t,i.texture=null,this.disposeIntermediateTensorInfo(o),c.dataId}write(e,t,n){if((Ct().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||Ct().getBool("DEBUG"))&&this.checkNumericalProblems(e),"complex64"===n&&null!=e)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const r={id:this.nextDataId()};return this.texData.set(r,{shape:t,dtype:n,values:e,usage:fy.UPLOAD,refCount:1}),r}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){this.texData.get(e).refCount++}decRef(e){this.texData.has(e)&&this.texData.get(e).refCount--}move(e,t,n,r,a){if(Ct().getBool("DEBUG")&&this.checkNumericalProblems(t),"complex64"===r)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:r,values:t,usage:fy.UPLOAD,refCount:a})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){const t=this.texData.get(e),{values:n,dtype:r,complexTensorInfos:a,slice:s,shape:o,isPacked:i}=t;if(null!=s){let t;t=i?new C_(o,N_):new I_(o,N_);const n=this.runWebGLProgram(t,[{dataId:e,shape:o,dtype:r}],r),a=this.readSync(n.dataId);return this.disposeIntermediateTensorInfo(n),a}if(null!=n)return this.convertAndCacheOnCPU(e);if("string"===r)return n;const u=null!=this.activeTimers;let l,c;return u&&(l=Ta()),c="complex64"===r?Sd(this.readSync(a.real.dataId),this.readSync(a.imag.dataId)):this.getValuesFromTexture(e),u&&(this.downloadWaitMs+=Ta()-l),this.convertAndCacheOnCPU(e,c)}async read(e){if(this.pendingRead.has(e)){const t=this.pendingRead.get(e);return new Promise((e=>t.push(e)))}const t=this.texData.get(e),{values:n,shape:r,slice:a,dtype:s,complexTensorInfos:o,isPacked:i}=t;if(null!=a){let t;t=i?new C_(r,N_):new I_(r,N_);const n=this.runWebGLProgram(t,[{dataId:e,shape:r,dtype:s}],s),a=this.read(n.dataId);return this.disposeIntermediateTensorInfo(n),a}if(null!=n)return this.convertAndCacheOnCPU(e);if(Ct().getBool("DEBUG")&&!Ct().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===Ct().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let u,l,c=null;if("complex64"!==s&&Ct().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);const t=this.texData.get(u.dataId);c=this.gpgpu.createBufferFromTexture(t.texture.texture,...yy(r))}if(this.pendingRead.set(e,[]),"complex64"!==s&&await this.gpgpu.createAndWaitForFence(),"complex64"===s){const e=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]);l=Sd(e[0],e[1])}else if(null==c)l=this.getValuesFromTexture(e);else{const e=et(r);l=this.gpgpu.downloadFloat32MatrixFromBuffer(c,e)}if(null!=u&&this.disposeIntermediateTensorInfo(u),null!=c){const e=this.gpgpu.gl;xy(e,(()=>e.deleteBuffer(c)))}const p=this.convertAndCacheOnCPU(e,l),h=this.pendingRead.get(e);return this.pendingRead.delete(e),h.forEach((e=>e(p))),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&yi().removeDataId(e,this),this.pendingDeletes--),p}readToGPU(e,t={}){const n=this.texData.get(e),{values:r,shape:a,slice:s,dtype:o,isPacked:i,texture:u}=n;if("complex64"===o)throw new Error("Does not support reading texture for complex64 dtype.");if(null!=s){let n;n=i?new C_(a,N_):new I_(a,N_);const r=this.runWebGLProgram(n,[{dataId:e,shape:a,dtype:o}],o),s=this.readToGPU(r,t);return this.disposeIntermediateTensorInfo(r),s}if(null==u)throw null!=r?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");const l=this.decode(e,t.customTexShape),c=yi().makeTensorFromTensorInfo(l),p=this.texData.get(l.dataId);return Object.assign({tensorRef:c},p.texture)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map((e=>Ia(e)));return ju(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return ju(e.shape,e.dtype,t)}checkNumericalProblems(e){if(null!=e)for(let t=0;t<e.length;t++){const n=e[t];if(!vy(n)){if(Ct().getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))throw Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`);throw Error(`The value ${n} cannot be represented on this device.`)}}}getValuesFromTexture(e){const{shape:t,dtype:n,isPacked:r}=this.texData.get(e),a=et(t);if(Ct().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const n=this.decode(e),r=this.texData.get(n.dataId),s=this.gpgpu.downloadMatrixFromPackedTexture(r.texture.texture,...yy(t)).subarray(0,a);return this.disposeIntermediateTensorInfo(n),s}const s=Ct().getBool("WEBGL_PACK")&&!0===r,o=s?My(t):t,i=s?new db(o):new hb(o),u=this.runWebGLProgram(i,[{shape:o,dtype:n,dataId:e}],"float32"),l=this.texData.get(u.dataId),c=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(l.texture.texture,l.texShape[0],l.texShape[1]).subarray(0,a);return this.disposeIntermediateTensorInfo(u),c}timerAvailable(){return Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(e){const t=this.activeTimers,n=[];let r=!1;null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e();const a=Ea(this.activeTimers.map((e=>e.query))).filter((e=>null!=e)),s=Ea(this.activeTimers.map((e=>e.name))).filter((e=>null!=e));this.activeTimers=t,r&&(this.programTimersStack=null);const o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const e=await Promise.all(a);o.kernelMs=function(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}(e),o.getExtraProfileInfo=()=>e.map(((e,t)=>({name:s[t],ms:e}))).map((e=>`${e.name}: ${e.ms}`)).join(", ")}else o.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,o})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:Ta(),endMs:null}}endTimer(e){return Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=Ta(),e)}async getQueryTime(e){if(Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);const t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);const{complexTensorInfos:n}=this.texData.get(e);return null!=n&&(this.disposeData(n.real.dataId,t),this.disposeData(n.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){const{texture:t,dtype:n,texShape:r,usage:a,isPacked:s,slice:o}=this.texData.get(e),i=o&&o.origDataId||e,u=this.dataRefCount.get(i);u>1?this.dataRefCount.set(i,u-1):(this.dataRefCount.delete(i),null!=t&&(this.numBytesInGPU-=this.computeBytes(r,n),this.textureManager.releaseTexture(t,r,a,s)));const l=this.texData.get(e);l.texture=null,l.texShape=null,l.isPacked=!1,l.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=M_){return Ct().getBool("WEBGL_CPU_FORWARD")&&e.every((e=>null==this.texData.get(e.dataId).texture&&et(e.shape)<t))}getGPGPUContext(){return this.gpgpu}where(e){Cr("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return R_(e.shape,t)}packedUnaryOp(e,t,n){const r=new C_(e.shape,t),a=this.compileAndRun(r,[e],n);return yi().makeTensorFromTensorInfo(a)}abs(e){if(this.shouldExecuteOnCPU([e])&&"complex64"!==e.dtype){const t=n_(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,t)}if(Ct().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,E_,e.dtype);const t=new I_(e.shape,E_),n=this.compileAndRun(t,[e]);return yi().makeTensorFromTensorInfo(n)}makeTensorInfo(e,t,n){let r;if("string"===t&&null!=n&&n.length>0&&dt(n[0])){const a=n.map((e=>ka(e)));r=this.write(a,e,t)}else r=this.write(n,e,t);return this.texData.get(r).usage=null,{dataId:r,shape:e,dtype:t}}makeOutput(e,t,n){return yi().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,n),this)}unpackTensor(e){const t=new A_(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new __(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const n=[Ry(e.shape),...$y(e.shape)],r={dtype:e.dtype,shape:n,dataId:e.dataId},a=[Ry(t),...$y(t)],s=new x_(a,n),o=[n],i=this.runWebGLProgram(s,[r],e.dtype,o,!0);return{dataId:i.dataId,shape:t,dtype:i.dtype}}decode(e,t){const n=this.texData.get(e),{isPacked:r,shape:a,dtype:s}=n;null!=t&&Qe(et(a)<=t[0]*t[1]*4,(()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data."));const o=My(a);let i;i=r?new pb(o):new cb(o);const u=[null!=t?t:yy(o)];return{dtype:s,shape:a,dataId:this.runWebGLProgram(i,[{shape:o,dtype:s,dataId:e}],s,u,!0,t).dataId}}runWebGLProgram(e,t,n,r,a=!1,s){const o=this.makeTensorInfo(e.outputShape,n),i=this.texData.get(o.dataId);if(e.packedOutput&&(i.isPacked=!0),e.outPackingScheme===dy.DENSE){const t=null!=s?s:yy(e.outputShape);i.texShape=t.map((e=>2*e))}if(null!=e.outTexUsage&&(i.usage=e.outTexUsage),0===et(o.shape))return i.values=lt(o.dtype,0),o;const u=[],l=t.map((t=>{if("complex64"===t.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let n=this.texData.get(t.dataId);if(null==n.texture){if(!e.packedInputs&&et(t.shape)<=Ct().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:t.shape,texData:null,isUniform:!0,uniformValues:n.values};e.packedInputs&&(n.isPacked=!0,n.shape=t.shape)}if(this.uploadToGPU(t.dataId),!!n.isPacked!=!!e.packedInputs)t=n.isPacked?this.unpackTensor(t):this.packTensor(t),u.push(t),n=this.texData.get(t.dataId);else if(n.isPacked&&!Oy(n.shape,t.shape)){const e=t,r=t.shape;t.shape=n.shape,t=this.packedReshape(t,r),u.push(t),n=this.texData.get(t.dataId),e.shape=r}return{shape:t.shape,texData:n,isUniform:!1}}));this.uploadToGPU(o.dataId);const c={shape:o.shape,texData:i,isUniform:!1},p=function(e,t,n){let r="";t.concat(n).forEach((t=>{const a=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!t.isUniform){const s=t.texData.texShape,{useSqueezeShape:o,uniformShape:i,keptDims:u}=ab(e.packedInputs,t.shape,s);let l="",c="",p="";if(1===i.length&&e.packedInputs){const e=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];l=`${e[0]>1}_${e[1]>1}`}else if(2!==i.length||e.packedInputs){if(i.length>2&&!e.packedInputs){const e=yt(i);p=`${e[0]===s[1]}_${e[e.length-1]===s[1]}`}}else c=`${i[0]>1}_${i[1]>1}`;const h=t.shape.length,d=2===i.length&&tt(t.shape,s),f=1===et(t.shape),m=Ei(t.shape,n.shape),g=!e.packedInputs&&h===n.shape.length&&tt(s,n.texData.texShape),y=e.packedInputs||i.length>2?"":`${s[0]>1}_${s[1]>1}`;r+=`${h}_${g}_${o?u:""}_${i.length}_${f}_${m}_${d}_${l}_${c}_${p}_${y}_${a}`}else{const e=t.isUniform?"uniform":t.texData.texShape;r+=`${t.shape}_${e}_${a}`}}));const a=e.userCode;let s=e.constructor.name;return s+="_"+r+"_"+a+`${Ct().getNumber("WEBGL_VERSION")}`,s}(e,l,c),h=this.getAndSaveBinary(p,(()=>function(e,t,n,r){const a=n.map(((e,n)=>{const r={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.isPacked,flatOffset:null};return null!=e.texData&&null!=e.texData.slice&&e.texData.slice.flatOffset>0&&(r.flatOffset=e.texData.slice.flatOffset),{name:t.variableNames[n],shapeInfo:r}})),s=a.map((e=>e.shapeInfo)),o={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},i=qy(a,o,t),u=function(e,t){const n=Ay(e,(()=>e.createShader(e.FRAGMENT_SHADER)),"Unable to create fragment WebGLShader.");if(xy(e,(()=>e.shaderSource(n,t))),xy(e,(()=>e.compileShader(n))),Ct().get("ENGINE_COMPILE_ONLY"))return n;if(!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw ky(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}(e.gl,i),l=e.createProgram(u);return Ct().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:u,source:i,webGLProgram:l,inShapeInfos:s,outShapeInfo:o,uniformLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,inShapesLocations:null,inTexShapesLocations:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:Object.assign({program:t,fragmentShader:u,source:i,webGLProgram:l,inShapeInfos:s,outShapeInfo:o},ib(e,t,l))}(this.gpgpu,e,l,c))),d=null!=this.activeTimers;let f;d&&(f=this.startTimer()),Ct().get("ENGINE_COMPILE_ONLY")||function(e,t,n,r,a){t.program.enableShapeUniforms||(ub(t.inShapeInfos,n),ub([t.outShapeInfo],[r]));const s=r.texData.texture,o=r.texData.texShape;r.texData.isPacked?e.setOutputPackedMatrixTexture(s.texture,o[0],o[1]):e.setOutputMatrixTexture(s.texture,o[0],o[1]),e.setProgram(t.webGLProgram),1===Ct().getNumber("WEBGL_VERSION")&&null!==t.infLoc&&e.gl.uniform1f(t.infLoc,1/0),null!==t.nanLoc&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach(((n,r)=>{const a=t.program.variableNames[r],s=t.uniformLocations[a],o=t.uniformLocations[`offset${a}`],i=t.inShapesLocations[`${a}Shape`],u=t.inTexShapesLocations[`${a}TexShape`];if(i){const{uniformShape:r}=ab(t.program.packedInputs,n.shape,n.texData.texShape);switch(r.length){case 1:e.gl.uniform1iv(i,new Int32Array(r));break;case 2:e.gl.uniform2iv(i,new Int32Array(r));break;case 3:e.gl.uniform3iv(i,new Int32Array(r));break;case 4:e.gl.uniform4iv(i,new Int32Array(r))}}if(u&&e.gl.uniform2i(u,n.texData.texShape[0],n.texData.texShape[1]),null!=s)if(n.isUniform)if(et(n.shape)<2)e.gl.uniform1f(s,n.uniformValues[0]);else{let t=n.uniformValues;t instanceof Float32Array||(t=new Float32Array(t)),e.gl.uniform1fv(s,t)}else null!=n.texData.slice&&null!=o&&e.gl.uniform1i(o,n.texData.slice.flatOffset),e.setInputMatrixTexture(n.texData.texture.texture,s,r)}));const i=t.outShapeLocation;if(i)switch(r.shape.length){case 1:e.gl.uniform1iv(i,new Int32Array(r.shape));break;case 2:e.gl.uniform2iv(i,new Int32Array(r.shape));break;case 3:e.gl.uniform3iv(i,new Int32Array(r.shape));break;case 4:e.gl.uniform4iv(i,new Int32Array(r.shape))}if(t.outShapeStridesLocation){const n=yt(r.shape);switch(r.shape.length){case 2:e.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(n));break;case 3:e.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(n));break;case 4:e.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(n))}}t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,r.texData.texShape[0],r.texData.texShape[1]),t.program.customUniforms&&a&&t.program.customUniforms.forEach(((n,r)=>{const s=t.customUniformLocations[r],o=a[r];if("float"===n.type)e.gl.uniform1fv(s,o);else if("vec2"===n.type)e.gl.uniform2fv(s,o);else if("vec3"===n.type)e.gl.uniform3fv(s,o);else if("vec4"===n.type)e.gl.uniform4fv(s,o);else if("int"===n.type)e.gl.uniform1iv(s,o);else if("ivec2"===n.type)e.gl.uniform2iv(s,o);else if("ivec3"===n.type)e.gl.uniform3iv(s,o);else{if("ivec4"!==n.type)throw Error(`uniform type ${n.type} is not supported yet.`);e.gl.uniform4iv(s,o)}})),e.executeProgram()}(this.gpgpu,h,l,c,r),u.forEach((e=>this.disposeIntermediateTensorInfo(e))),d&&(f=this.endTimer(f),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(f)}));const m=Ct().get("WEBGL_FLUSH_THRESHOLD");if(m>0){const e=Ta();e-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=e)}if(!Ct().getBool("WEBGL_LAZILY_UNPACK")&&i.isPacked&&!1===a){const e=this.unpackTensor(o);return this.disposeIntermediateTensorInfo(o),e}return o}compileAndRun(e,t,n,r,a=!1){return n=n||t[0].dtype,this.runWebGLProgram(e,t,n,r,a)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(Ct().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach((e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]})),this.textureManager.dispose(),null!=this.canvas&&"undefined"!=typeof HTMLCanvasElement&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return null==this.floatPrecisionValue&&(this.floatPrecisionValue=bi((()=>{if(!Ct().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=Ct().getBool("DEBUG");Ct().set("DEBUG",!1);const t=this.abs(Ol(1e-8)).dataSync()[0];if(Ct().set("DEBUG",e),t>0)return 32}return 16}))),this.floatPrecisionValue}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}uploadToGPU(e){const t=this.texData.get(e),{shape:n,dtype:r,values:a,texture:s,usage:o,isPacked:i}=t;if(null!=s)return;const u=null!=this.activeTimers;let l;u&&(l=Ta());let c=t.texShape;if(null==c&&(c=function(e,t=!1){let n=Ct().getNumber("WEBGL_MAX_TEXTURE_SIZE"),r=Ct().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");if(r===1/0&&Ct().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(r=n/2),t&&(n*=2,r*=2,e=e.map(((t,n)=>n>=e.length-2?Xe(e[n]):e[n])),1===e.length&&(e=[2,e[0]])),2!==e.length){const t=ut(e);e=t.newShape}let a=et(e),s=null;e.length<=1&&a<=n?s=[1,a]:2===e.length&&e[0]<=n&&e[1]<=n?s=e:3===e.length&&e[0]*e[1]<=n&&e[2]<=n?s=[e[0]*e[1],e[2]]:3===e.length&&e[0]<=n&&e[1]*e[2]<=n?s=[e[0],e[1]*e[2]]:4===e.length&&e[0]*e[1]*e[2]<=n&&e[3]<=n?s=[e[0]*e[1]*e[2],e[3]]:4===e.length&&e[0]<=n&&e[1]*e[2]*e[3]<=n&&(s=[e[0],e[1]*e[2]*e[3]]);const o=null!=s&&Math.max(...s)>r&&Math.min(...s)<=(t?2:1)&&Math.min(...s)>0;if(null==s||o)if(t){const t=Ry(e);let n=2,r=2;e.length&&([n,r]=$y(e)),a=t*(n/2)*(r/2),s=rt(a).map((e=>2*e))}else s=rt(a);return s}(n,i),t.texShape=c),null!=a){const e=My(n);let s,o=c[1],p=c[0];const h=a instanceof Uint8Array||a instanceof Uint8ClampedArray;!i&&h||([o,p]=by(c[0],c[1])),s=i?new gb(e,h):new mb(e,h);const d=h?[p,o]:c,f=this.makeTensorInfo(d,r),m=this.texData.get(f.dataId);m.usage=h?fy.PIXELS:fy.UPLOAD,m.texShape=d,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(f.dataId),o,p,a);const g=[[p,o]],y=!0,b=this.runWebGLProgram(s,[f],r,g,y),_=this.texData.get(b.dataId);t.texShape=_.texShape,t.isPacked=_.isPacked,t.usage=_.usage,Ct().get("ENGINE_COMPILE_ONLY")?this.disposeData(b.dataId):(t.texture=_.texture,t.values=null,this.texData.delete(b.dataId)),this.disposeIntermediateTensorInfo(f),u&&(this.uploadWaitMs+=Ta()-l)}else{const e=this.acquireTexture(c,o,r,i);t.texture=e}}convertAndCacheOnCPU(e,t){const n=this.texData.get(e),{dtype:r}=n;return null!=t&&(n.values=function(e,t){if("float32"===t||"complex64"===t)return e;if("int32"===t||"bool"===t){const n="int32"===t?new Int32Array(e.length):new Uint8Array(e.length);for(let t=0;t<n.length;++t)n[t]=Math.round(e[t]);return n}throw new Error(`Unknown dtype ${t}`)}(t,r)),n.values}acquireTexture(e,t,n,r){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){const e=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${e} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,r)}computeBytes(e,t){return e[0]*e[1]*ht(t)}checkCompileCompletion(){for(const[,e]of Object.entries(this.binaryCache))this.checkCompletion_(e)}async checkCompileCompletionAsync(){const e=[];if(this.gpgpu.parallelCompilationExtension){for(const[,t]of Object.entries(this.binaryCache))e.push(this.checkCompletionAsync_(t));return Promise.all(e)}for(const[,t]of Object.entries(this.binaryCache)){const n=new Promise((e=>{try{this.checkCompletion_(t),e(!0)}catch(e){throw e}}));e.push(n)}return Promise.all(e)}async checkCompletionAsync_(e){return this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(e):(await new Promise((e=>pd((()=>e())))),this.checkCompletionAsync_(e))}checkCompletion_(e){if(!1===this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.gl.LINK_STATUS)){if(console.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram)),!1===this.gpgpu.gl.getShaderParameter(e.fragmentShader,this.gpgpu.gl.COMPILE_STATUS))throw ky(e.source,this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)),new Error("Failed to compile fragment shader.");throw new Error("Failed to link vertex and fragment shaders.")}return!0}getUniformLocations(){for(const[,e]of Object.entries(this.binaryCache)){const{uniformLocations:t,customUniformLocations:n,infLoc:r,nanLoc:a,inShapesLocations:s,inTexShapesLocations:o,outShapeLocation:i,outShapeStridesLocation:u,outTexShapeLocation:l}=ib(this.gpgpu,e.program,e.webGLProgram);e.uniformLocations=t,e.customUniformLocations=n,e.infLoc=r,e.nanLoc=a,e.inShapesLocations=s,e.inTexShapesLocations=o,e.outShapeLocation=i,e.outShapeStridesLocation=u,e.outTexShapeLocation=l}}createTensorFromGPUData(e,t,n){e.channels=e.channels||"RGBA";const{texture:r,height:a,width:s,channels:o}=e,i=yi().backend;if(!i.gpgpu.gl.isTexture(r))throw new Error("The texture is invalid. Also, please make sure the texture and the TFJS WebGL backend are using the same canvas. If you want to use your own custom canvas, you have to create and use the custom TFJS WebGL backend created from the canvas through 'new tf.MathBackendWebGL(customCanvas)'.");const u=i.writeTexture(r,t,n,a,s,o);return yi().makeTensorFromDataId(u,t,n,i)}}F_.nextDataId=0,as()&&wi("webgl",(()=>new F_),2);class O_{constructor(e){this.variableNames=["A"];const t=Vy(),[n,r]=e;this.outputShape=e,this.userCode=`\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}.0, ${n}.0);\n\n vec4 values = ${t.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n `}}class D_{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=Vy(),[n,r]=e;this.outputShape=e,this.userCode=`\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2(${r}.0, ${n}.0);\n vec4 values = ${t.texture2D}(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n ${t.output} = result;\n }\n `}}const L_={kernelName:kr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e;let{pixels:a}=t;const{numChannels:s}=r,o="undefined"!=typeof HTMLVideoElement&&a instanceof HTMLVideoElement,i="undefined"!=typeof HTMLImageElement&&a instanceof HTMLImageElement,[u,l]=o?[a.videoWidth,a.videoHeight]:[a.width,a.height],c=[l,u],p=[l,u,s];if(i||o){const e=Ct().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");null!=P_&&e===B_||(B_=e,P_=document.createElement("canvas").getContext("2d",{willReadFrequently:B_})),P_.canvas.width=u,P_.canvas.height=l,P_.drawImage(a,0,0,u,l),a=P_.canvas}const h=n.makeTensorInfo(c,"int32");n.texData.get(h.dataId).usage=fy.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(h.dataId),a);const d=Ct().getBool("WEBGL_PACK")?new D_(p):new O_(p),f=n.runWebGLProgram(d,[h],"int32");return n.disposeData(h.dataId),f}};let P_,B_=Ct().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function U_(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{shape:s}=r,o=n,i=et(a.shape),u=ot(s,i),l=et(u);Qe(i===l,(()=>`The new shape (${u}) has ${l} elements and the old shape (${a.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`));const c=o.texData.get(a.dataId);return!c.isPacked||Oy(a.shape,u)||null!==c.texture&&Oy(c.shape,u)?(o.incRef(a.dataId),{dataId:a.dataId,shape:u,dtype:a.dtype}):function(e,t,n){const r=[Ry(e.shape),...$y(e.shape)],a={dtype:e.dtype,shape:r,dataId:e.dataId},s=[Ry(t),...$y(t)],o=new x_(s,r),i=[r],u=n.runWebGLProgram(o,[a],e.dtype,i,!0);return{dataId:u.dataId,shape:t,dtype:u.dtype}}(a,u,o)}const z_={kernelName:Hn,backendName:"webgl",kernelFunc:U_};function V_(e){const{inputs:t,attrs:n,backend:r}=e,{dim:a}=n,{input:s}=t,o=s.shape.length,i=s.shape.slice();let u=a;return a<0&&(Qe(-(o+1)<=a,(()=>`Axis must be in the interval [${-(o+1)}, ${o}]`)),u=o+a+1),i.splice(u,0,1),U_({inputs:{x:s},backend:r,attrs:{shape:i}})}const W_={kernelName:an,backendName:"webgl",kernelFunc:V_};class H_{constructor(e,t,n,r,a){this.variableNames=["A"],this.outputShape=[];const[s,o,i,u]=e;this.outputShape=[s,t,n,u];const l=[r&&t>1?o-1:o,r&&n>1?i-1:i],c=[r&&t>1?t-1:t,r&&n>1?n-1:n];let p;p=a?"(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n ${l[0]/c[0]},\n ${l[1]/c[1]});\n const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = ${p};\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n `}}class G_{constructor(e,t,n,r,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[s,o,i,u]=e;this.outputShape=[s,t,n,u];const l=[r&&t>1?o-1:o,r&&n>1?i-1:i],c=[r&&t>1?t-1:t,r&&n>1?n-1:n];let p;p=a?"(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n ${l[0]/c[0]},\n ${l[1]/c[1]},\n ${l[1]/c[1]});\n const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,\n ${i}.0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = ${p};\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < ${u-1};\n bool hasNextRow = coords.z < ${n-1};\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n `}}const j_={kernelName:jn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:o,size:i}=r,[u,l]=i,c=Ct().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new G_(a.shape,u,l,s,o):new H_(a.shape,u,l,s,o);return n.runWebGLProgram(c,[a],"float32")}};function K_(e){const{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}const q_={kernelName:mn,backendName:"webgl",kernelFunc:K_};function X_(e){const{inputs:t,backend:n}=e,{real:r,imag:a}=t,s=n.makeTensorInfo(r.shape,"complex64"),o=n.texData.get(s.dataId),i=K_({inputs:{x:r},backend:n}),u=K_({inputs:{x:a},backend:n});return o.complexTensorInfos={real:i,imag:u},s}class Y_{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=Ci(t,n),this.enableShapeUniforms=lb(this.outputShape.length),this.userCode=`\n float binaryOperation(float a, float b) {\n ${e}\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n `}}class Q_{constructor(e,t,n,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=Ci(t,n);const a=this.outputShape.length;this.enableShapeUniforms=lb(a);let s="";if(r)if(0===a||1===et(this.outputShape))s="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(s=`\n ${rb(a)} coords = getOutputCoords();\n `,1===a)this.enableShapeUniforms?s+="\n result.y = (coords + 1) >= outShape ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ":s+=`\n result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n `;else{const e=b_("coords",a);this.enableShapeUniforms?s+=`\n bool nextRowOutOfBounds =\n (${e[a-2]} + 1) >= outShape[${a} - 2];\n bool nextColOutOfBounds =\n (${e[a-1]} + 1) >= outShape[${a} - 1];\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `:s+=`\n bool nextRowOutOfBounds =\n (${e[a-2]} + 1) >= ${this.outputShape[a-2]};\n bool nextColOutOfBounds =\n (${e[a-1]} + 1) >= ${this.outputShape[a-1]};\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n `}this.userCode=`\n vec4 binaryOperation(vec4 a, vec4 b) {\n ${e}\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n ${s}\n\n setOutput(result);\n }\n `}}const J_="if (isnan(x)) return x;";function Z_({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:r}){return({inputs:a,backend:s})=>{const{x:o}=a,i=s,u=r||o.dtype;if(i.shouldExecuteOnCPU([o])&&null!=n){const e=i.texData.get(o.dataId),t=n(e.values,u);return i.makeTensorInfo(o.shape,u,t)}let l;return l=Ct().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&null!=t?new C_(o.shape,t):new I_(o.shape,e),i.runWebGLProgram(l,[o],u)}}function ex({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:r=!1,cpuKernelImpl:a,dtype:s}){return({inputs:o,backend:i})=>{const{a:u,b:l}=o,c=i;if(r&&"complex64"===u.dtype){const t=c.texData.get(u.dataId),n=c.texData.get(l.dataId),[r,a]=[[t.complexTensorInfos.real,n.complexTensorInfos.real],[t.complexTensorInfos.imag,n.complexTensorInfos.imag]].map((t=>{const[n,r]=t,a={dataId:n.dataId,dtype:n.dtype,shape:u.shape},s={dataId:r.dataId,dtype:r.dtype,shape:l.shape},o=new Y_(e,u.shape,l.shape);return c.runWebGLProgram(o,[a,s],Ka(n.dtype,r.dtype))})),s=X_({inputs:{real:r,imag:a},backend:c});return c.disposeIntermediateTensorInfo(r),c.disposeIntermediateTensorInfo(a),s}const p=s||Ka(u.dtype,l.dtype);if(("string"===u.dtype||"string"===l.dtype||c.shouldExecuteOnCPU([u,l]))&&null!=a){const e=c.texData.get(u.dataId).values,t=c.texData.get(l.dataId).values,n="string"===u.dtype?zd(e):e,r="string"===u.dtype?zd(t):t,[s,o]=a(u.shape,l.shape,n,r,p),i=c.makeTensorInfo(o,p);return c.texData.get(i.dataId).values=s,i}let h;return h=Ct().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&null!=t?new Q_(t,u.shape,l.shape,n):new Y_(e,u.shape,l.shape),c.runWebGLProgram(h,[u,l],p)}}function tx(e,t=!1){if("linear"===e)return"return x;";if("relu"===e)return t?"\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n":"if (isnan(x)) return x;\n return (x < 0.0) ? 0.0 : x;\n";if("elu"===e)return t?"\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n":"return (x >= 0.0) ? x : (exp(x) - 1.0);";if("relu6"===e)return t?"\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n":"if (isnan(x)) return x;\n return (x < 0.0) ? 0.0 : min(6.0, x);\n";if("prelu"===e)return t?"\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n":"return (a < 0.) ? b * a : a;";if("leakyrelu"===e)return t?"\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n":"return (a < 0.) ? b * a : a;";if("sigmoid"===e)return"return 1.0 / (1.0 + exp(-1.0 * x));";throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}const nx=ex({opSnippet:"return float(a != b);",cpuKernelImpl:Kb,dtype:"bool"});function rx(e){const{inputs:t,backend:n}=e,{input:r}=t;return K_({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.real},backend:n})}const ax={kernelName:Vt,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r,attrs:a}=t,{x:s}=n,{dtype:o}=a;if("complex64"===o){if("complex64"===s.dtype)return K_({inputs:{x:s},backend:r});const t=Tc(s.shape),n=e({inputs:{x:s},backend:r,attrs:{dtype:"float32"}}),a=X_({inputs:{real:n,imag:t},backend:r});return t.dispose(),r.disposeIntermediateTensorInfo(n),a}if("complex64"===s.dtype){const t=rx({inputs:{input:s},backend:r}),n=e({inputs:{x:t},backend:r,attrs:{dtype:o}});return r.disposeIntermediateTensorInfo(t),n}if(!pt(s.dtype,o)){const e=K_({inputs:{x:s},backend:r});return{dataId:e.dataId,shape:e.shape,dtype:o}}if(r.shouldExecuteOnCPU([s])){const e=r.texData.get(s.dataId).values,[t,n,a]=Eb(e,s.shape,s.dtype,o);return r.makeTensorInfo(t,n,a)}if("int32"===o)return function(e,t){const n=new I_(e.shape,"return float(int(x));"),r=t.runWebGLProgram(n,[e],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}(s,r);if("bool"===o){const e=r.makeTensorInfo([],"bool",lt("bool",1)),t=nx({inputs:{a:s,b:e},backend:r});return r.disposeIntermediateTensorInfo(e),t}throw new Error(`Error in Cast: failed to cast ${s.dtype} to ${o}`)}},sx=ex({opSnippet:"\nif (a == b) {\n return 1.0;\n};\nreturn a / b;",packedOpSnippet:"\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(a.x == b.x) {\n result.x = 1.;\n }\n if(a.y == b.y) {\n result.y = 1.;\n }\n if(a.z == b.z) {\n result.z = 1.;\n }\n if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n",checkOutOfBounds:!0}),ox={kernelName:en,backendName:"webgl",kernelFunc:sx};class ix{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const r=e.length,a=rb(r),s=t.map((e=>e[0])).join(","),o=t.map(((t,n)=>t[0]+e[n])).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?`\n ${a} start = ${a}(${s});\n ${a} end = ${a}(${o});\n\n void main() {\n ${a} outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(value);\n } else {\n ${a} coords = outC - start;\n setOutput(getX(${i}));\n }\n }\n `:`\n int start = ${s};\n int end = ${o};\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(value);\n } else {\n setOutput(getX(outC - start));\n }\n }\n `}}class ux{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const r=e.length,a=rb(r),s=t.map((e=>e[0])).join(","),o=t.map(((t,n)=>t[0]+e[n])).join(","),i=b_("rc",r),u=b_("source",r),l=`${i[r-1]} < ${this.outputShape[r-1]}`,c=1===r?"source":`vec2(${u.slice(-2).join()})`,p=[`${a} rc = outputLoc;`,`${i[r-1]} += 1;\n if(${l}) {\n `,1===r?"":`}\n rc = outputLoc;\n ${i[r-2]} += 1;\n if(${i[r-2]} < ${this.outputShape[r-2]}) {`,1===r?"":` ${i[r-1]} += 1;\n if(${l}) {`],h=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let d="";for(let e=0,t=1===r?2:4;e<t;e++)d+=`\n ${p[e]}\n if (${h}) {\n result[${e}] = float(value);\n } else {\n ${a} source = rc - start;\n result[${e}] = getChannel(getX(${u.join()}), ${c});\n }\n `;d+=1===r?"} ":"}}",this.userCode=`\n const ${a} start = ${a}(${s});\n const ${a} end = ${a}(${o});\n\n void main() {\n ${a} outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n ${d}\n setOutput(result);\n }\n `}}class lx{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode="\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}}const cx=e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{paddings:s,constantValue:o}=r;if(0===et(a.shape)){const e=s.map(((e,t)=>e[0]+a.shape[t]+e[1]));return function(e){const{backend:t,attrs:n}=e,{shape:r,value:a}=n;let{dtype:s}=n;if(s=s||ft(a),"string"===s){const e=ct(s,et(r));return e.fill(a),t.makeTensorInfo(r,s,e)}{const e=new lx(r,a),n=[[a]];return t.runWebGLProgram(e,[],s,n)}}({backend:n,attrs:{shape:e,value:o,dtype:a.dtype}})}const i=Ct().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new ux(a.shape,s,o):new ix(a.shape,s,o),u=[[o]];return n.runWebGLProgram(i,[a],a.dtype,u)},px={kernelName:Pn,backendName:"webgl",kernelFunc:cx};class hx{constructor(e,t=!1,n=null,r=!1,a=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const s=e.padInfo.top,o=e.padInfo.left,i=e.strideHeight,u=e.strideWidth,l=e.dilationHeight,c=e.dilationWidth,p=e.filterHeight,h=e.filterWidth,d=4*Math.floor(e.inChannels/4),f=e.inChannels%4,m="channelsLast"===e.dataFormat,g=m?1:2,y=m?2:3,b=m?3:1;let _="",x="";n&&(_=r?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:a?`float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`\n float activation(float x) {\n ${n}\n }\n `,x="result = activation(result);");const v=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${_}\n\n const ivec2 strides = ivec2(${i}, ${u});\n const ivec2 pads = ivec2(${s}, ${o});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[${b}];\n\n ivec2 xRCCorner =\n ivec2(coords[${g}], coords[${y}]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${p}; wR++) {\n int xR = xRCorner + wR * ${l};\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${h}; wC++) {\n int xC = xCCorner + wC * ${c};\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n for (int d1 = 0; d1 < ${d}; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if (${m}) {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if (${1===f}) {\n\n if (${m}) {\n dotProd +=\n getX(batch, xR, xC, ${d}) *\n getW(wR, wC, ${d}, d2);\n } else {\n dotProd +=\n getX(batch, ${d}, xR, xC) *\n getW(wR, wC, ${d}, d2);\n }\n\n } else if (${2===f}) {\n vec2 wValues = vec2(\n getW(wR, wC, ${d}, d2),\n getW(wR, wC, ${d} + 1, d2)\n );\n\n if (${m}) {\n vec2 xValues = vec2(\n getX(batch, xR, xC, ${d}),\n getX(batch, xR, xC, ${d} + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, ${d}, xR, xC),\n getX(batch, ${d} + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if (${3===f}) {\n vec3 wValues = vec3(\n getW(wR, wC, ${d}, d2),\n getW(wR, wC, ${d} + 1, d2),\n getW(wR, wC, ${d} + 2, d2)\n );\n\n if (${m}) {\n vec3 xValues = vec3(\n getX(batch, xR, xC, ${d}),\n getX(batch, xR, xC, ${d} + 1),\n getX(batch, xR, xC, ${d} + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, ${d}, xR, xC),\n getX(batch, ${d} + 1, xR, xC),\n getX(batch, ${d} + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n ${v}\n ${x}\n setOutput(result);\n }\n `}}class dx{constructor(e,t=!1,n=null,r=!1,a=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=lb(this.outputShape.length);const s=e.padInfo.left,o=e.strideWidth,i=e.dilationWidth,u=e.filterHeight,l=e.filterWidth,c=l;let p="\n int xR; int xC; int xCOffset;\n vec4 wTexel; vec4 previous; vec4 final;";for(let e=0;e<l;e++)p+=`\n vec4 xTexelC${2*e};\n int xTexelC${2*e}Ready;\n vec4 xTexelC${2*e+1};\n int xTexelC${2*e+1}Ready;\n vec4 xC${e};`;p+=`\n for (int r = 0; r < ${u}; r++) {\n for (int d1 = 0; d1 < ${e.inChannels}; d1 += 2) {\n `;for(let e=0;e<l;e++)p+=`\n xTexelC${2*e} = vec4(0.0);\n xTexelC${2*e}Ready = 0;\n xTexelC${2*e+1} = vec4(0.0);\n xTexelC${2*e+1}Ready = 0;\n xC${e} = vec4(0.0);`;p+="\n xR = xRCorner + r * dilations[0];\n if (xR >=0 && xR < inDims[0]) {\n ";for(let t=0;t<(c+1)/2;t++){const n=2*t;if(p+=`\n xC = xCCorner + ${n*i};\n `,1===o){if(n<l&&(s%2==1?(p+=`\n xCOffset = xC + 1;\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n `,p+=1===i&&n>0?`\n xC${n} = vec4(xTexelC${n-2}.zw, xTexelC${n}.xy);\n `:`\n xCOffset = xC + 1 - 2;\n\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n previous.zw = vec2(0.0);\n }\n\n xC${n} = vec4(previous.zw, xTexelC${n}.xy);\n } else {\n xC${n} = vec4(0.0, 0.0, xTexelC${n}.xy);\n }\n `):p+=`\n if (xC >= 0 && xC < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n\n xC${n} = xTexelC${n};\n `,n+1<l)){const e=s%2==0?Xe(i):i;i%2==0&&s%2==1||i%2!=0&&s%2!=1?(p+=`\n xCOffset = xC + imod(pads[1], 2) + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n+1}.zw = vec2(0.0);\n }\n xTexelC${n+1}Ready = 1;\n }\n `,p+=i>1?`\n xCOffset -= 2;\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n xC${n+1} = vec4(previous.zw, xTexelC${n+1}.xy);\n } else {\n xC${n+1} = vec4(0.0, 0.0, xTexelC${n+1}.xy);\n }\n `:`\n xC${n+1} = vec4(xTexelC${n}.zw, xTexelC${n+1}.xy);\n `):p+=1===e?`\n xC${n+1} = xTexelC${n};\n `:`\n xCOffset = xC + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n+1}.zw = vec2(0.0);\n }\n xTexelC${n+1}Ready = 1;\n }\n\n xC${n+1} = xTexelC${n+1};\n `}}else n<l&&(s%2==1?(p+=`\n xCOffset = xC + 1 - strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = getX(batch, xR, xCOffset, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+1} = getX(batch, xR, xC + 1, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xC + 2 >= inDims[1]) {\n xTexelC${n+1}.zw = vec2(0.0);\n }\n xTexelC${n+1}Ready = 1;\n }\n\n xC${n} = vec4(xTexelC${n}.zw, xTexelC${n+1}.zw);\n `,n+1<l&&(p+=`\n final = vec4(0.0);\n xCOffset = xC + 1 + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1]) {\n final = getX(batch, xR, xCOffset, d1);\n }\n xC${n+1} = vec4(xTexelC${n+1}.xy, final.xy);\n `)):(p+=`\n if(xC >= 0 && xC < inDims[1] && xTexelC${n}Ready == 0) {\n xTexelC${n} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${n}.zw = vec2(0.0);\n }\n xTexelC${n}Ready = 1;\n }\n\n xCOffset = xC + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\n xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${n+1}.zw = vec2(0.);\n }\n xTexelC${n+1}Ready = 1;\n }\n\n xC${n} = vec4(\n xTexelC${n}.xy, xTexelC${n+1}.xy);\n `,n+1<l&&(p+=`\n xC${n+1} = vec4(xTexelC${n}.zw, xTexelC${n+1}.zw);\n `)));n<l&&(p+=`\n wTexel = getW(r, ${n}, d1, d2);\n dotProd += xC${n}.xxzz * vec4(wTexel.xy, wTexel.xy);\n if(d1 + 1 < ${e.inChannels}) {\n dotProd += xC${n}.yyww * vec4(wTexel.zw, wTexel.zw);\n }\n `,n+1<l&&(p+=`\n wTexel = getW(r, ${n+1}, d1, d2);\n dotProd += xC${n+1}.xxzz * vec4(wTexel.xy, wTexel.xy);\n if(d1 + 1 < ${e.inChannels}) {\n dotProd += xC${n+1}.yyww * vec4(wTexel.zw, wTexel.zw);\n }\n `))}p+="\n }\n ",p+="\n }\n ",p+="\n }\n ";let h="",d="";n&&(h=r?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:a?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`vec4 activation(vec4 x) {\n ${n}\n }`,d="result = activation(result);");const f=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${h}\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.\n vec4 dotProd = vec4(0.000000000000001);\n\n ${p}\n\n vec4 result = dotProd - vec4(0.000000000000001);\n ${f}\n ${d}\n setOutput(result);\n }\n `}}class fx{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec4"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=e,this.enableShapeUniforms=lb(this.outputShape.length);const{dataFormat:n}=t,r=Vy(),a="channelsLast"===n,s=a?1:2,o=a?2:3,i=this.enableShapeUniforms?"if(blockIndex < outShape[2] && pos < outShape[1]) {":`if(blockIndex < ${e[2]} && pos < ${e[1]}) {`;let u="";for(let e=0;e<=1;e++)for(let t=0;t<=1;t++)u+=`\n blockIndex = rc.z + ${t};\n pos = rc.y + ${e};\n\n ${i}\n offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];\n d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);\n\n if(d0 < inputShape[${s}] && d0 >= 0) {\n // Use custom imod instead mod. On Intel GPU, mod may generate\n // unexpected value.\n // https://github.com/tensorflow/tfjs/issues/5447\n offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];\n d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /\n inChannels);\n\n if(d1 < inputShape[${o}] && d1 >= 0) {\n\n ch = imod(pos, inChannels);\n\n if (${a}) {\n innerDims = vec2(d1, ch);\n result[${2*e+t}] = getChannel(\n getA(rc.x, d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result[${2*e+t}] = getChannel(\n getA(rc.x, ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n `;this.userCode=`\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n ${u}\n\n ${r.output} = result;\n }\n `}}class mx{constructor(e,t,n,r=!1,a=!1,s=!1,o=null,i=!1,u=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=lb(this.outputShape.length);const l=r?e[1]:e[2],c=Math.ceil(l/2),p=r?"i * 2, rc.y":"rc.y, i * 2",h=a?"rc.z, i * 2":"i * 2, rc.z",d=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=a?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let m="",g="";o&&(m=i?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${o}\n }`:u?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${o}\n }`:`vec4 activation(vec4 x) {\n ${o}\n }`,g="result = activation(result);");const y=s?"result += getBiasAtOutCoords();":"";s&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),u&&this.variableNames.push("leakyreluAlpha");let b="rc.x",_="rc.x";e[0]<t[0]?b=`imod(rc.x, ${e[0]})`:t[0]<e[0]&&(_=`imod(rc.x, ${t[0]})`),this.userCode=`\n ${m}\n // Don't use uniform for sharedDimensionPacked for performance.\n const float sharedDimension = ${c}.0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n int batchA = ${b};\n int batchB = ${_};\n for (int i = 0; i < ${c}; i++) {\n vec4 a = getMatrixA(batchA, ${p});\n vec4 b = getMatrixB(batchB, ${h});\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += (${d[0]} * ${f[0]});\n result += (${d[1]} * ${f[1]});\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n ${y}\n\n ${g}\n\n setOutput(result);\n }\n `}}class gx{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Ci(t,n),this.userCode=`\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n ${e}\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n `}}const yx="return a * b;";function bx(e){const{inputs:t,backend:n}=e,{a:r,b:a}=t,s=Ka(r.dtype,a.dtype);if("complex64"===r.dtype){const e=n.texData.get(r.dataId),t=n.texData.get(a.dataId),s=new gx("return areal * breal - aimag * bimag;",r.shape,a.shape),o=new gx("return areal * bimag + aimag * breal;",r.shape,a.shape),i=[{dataId:e.complexTensorInfos.real.dataId,dtype:e.complexTensorInfos.real.dtype,shape:r.shape},{dataId:e.complexTensorInfos.imag.dataId,dtype:e.complexTensorInfos.imag.dtype,shape:r.shape},{dataId:t.complexTensorInfos.real.dataId,dtype:t.complexTensorInfos.real.dtype,shape:a.shape},{dataId:t.complexTensorInfos.imag.dataId,dtype:t.complexTensorInfos.imag.dtype,shape:a.shape}],u=n.runWebGLProgram(s,i,"float32"),l=n.runWebGLProgram(o,i,"float32"),c=X_({inputs:{real:u,imag:l},backend:n});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(l),c}if(n.shouldExecuteOnCPU([r,a])){const e=n.texData.get(r.dataId),t=n.texData.get(a.dataId),[o,i]=Gb(r.shape,a.shape,e.values,t.values,s),u=n.makeTensorInfo(i,s);return n.texData.get(u.dataId).values=o,u}let o;return o=Ct().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Q_(yx,r.shape,a.shape):new Y_(yx,r.shape,a.shape),n.runWebGLProgram(o,[r,a],s)}const _x={kernelName:An,backendName:"webgl",kernelFunc:bx};class xx{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:a,outSize:s}=e;this.outputShape=[r,s];const o=4*Math.floor(n/4),i=n%4;let u="sumValue += dot(values, ones);";if(null!=t){const e=1/t;u=`sumValue += dot(values * ${nt(e)?e.toPrecision(2):e}, ones);`}let l="";a%n>0&&(l=`\n if (inIdx < 0 || inIdx >= ${a}) {\n return 0.0;\n }\n `),this.userCode=`\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${l}\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${n};\n\n float sumValue = 0.0;\n\n for (int i = 0; i < ${o}; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n ${u}\n }\n\n int inIdx = inOffset + ${o};\n if (${1===i}) {\n vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\n\n ${u}\n } else if (${2===i}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1), 0.0, 0.0);\n\n ${u}\n } else if (${3===i}) {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2), 0.0);\n\n ${u}\n }\n setOutput(sumValue);\n }\n `}}class vx{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:a,outSize:s}=e;this.outputShape=[r,s];let o="0.0",i="";"prod"===t?o="1.0":"min"===t?(o="1.0 / 1e-20",i="min"):"max"===t&&(o="-1.0 / 1e-20",i="max");let u=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"sum"===t?u="sumValue":"prod"===t?u="prodValue":"all"===t?u="allValue":"any"===t&&(u="anyValue");const l=4*Math.floor(n/4),c=n%4;let p=`\n if (${"sum"===t}) {\n sumValue += dot(values, ones);\n } else if (${"prod"===t}) {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = ${i}(values, minMaxValue);\n if (${"min"===t} || ${"max"===t}) {\n minMaxValue = ${i}(values, minMaxValue);\n bvec4 isNaN = isnan(values);\n if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {\n minMaxValue = vec4(NAN);\n }\n }\n }\n `,h="vec4";"all"===t?(o="1.0",p="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",h="bvec4"):"any"===t&&(o="0.0",p="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",h="bvec4");let d="";a%n>0&&(d=`\n if (inIdx < 0 || inIdx >= ${a}) {\n return initializationValue;\n }\n `),this.userCode=`\n const float initializationValue = ${o};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n ${d}\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${n};\n\n vec4 minMaxValue = vec4(${o});\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < ${l}; i += 4) {\n int inIdx = inOffset + i;\n ${h} values = ${h}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n ${p}\n }\n\n int inIdx = inOffset + ${l};\n if (${1===c}) {\n ${h} values = ${h}(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${p}\n } else if (${2===c}) {\n ${h} values = ${h}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n ${p}\n } else if (${3===c}) {\n ${h} values = ${h}(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n ${p}\n }\n setOutput(${u});\n }\n `}}function wx(e,t,n,r){const a=function(e){const t=[];for(;0===t.length||1!==t[t.length-1].outSize;){const n=t.length?t[t.length-1].outSize:e[1],r=_d(n);t.push({inSize:n,windowSize:r,outSize:Math.ceil(n/r)})}return t}(e.shape);let s=e;for(let o=0;o<a.length;o++){const{inSize:i,windowSize:u,outSize:l}=a[o];let c,p;c="mean"===n?0===o?new xx({windowSize:u,inSize:i,batchSize:e.shape[0],outSize:l},i):new xx({windowSize:u,inSize:i,batchSize:e.shape[0],outSize:l}):new vx({windowSize:u,inSize:i,batchSize:e.shape[0],outSize:l},n),p=s,s=r.runWebGLProgram(c,[s],t),p.dataId!==e.dataId&&r.disposeIntermediateTensorInfo(p)}return s}class Tx{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[t[r]];this.outputShape=n,this.rank=n.length;const r=rb(this.rank),a=function(e){const t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t);for(let t=0;t<e.length;t++)r[e[t]]=n[t];return r.join()}(t);this.userCode=`\n void main() {\n ${r} resRC = getOutputCoords();\n setOutput(getA(${a}));\n }\n `}}class kx{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[t[r]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const r=rb(this.rank),a=y_("rc",this.rank),s=new Array(this.rank);for(let e=0;e<t.length;e++)s[t[e]]=a[e];const o=`vec2(${s.slice(-2).join()})`,i=`++${a[this.rank-1]} < ${n[this.rank-1]}`,u=`getChannel(getA(${s.join()}), ${o})`;this.userCode=`\n void main() {\n ${r} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result[0] = ${u};\n if(${i}) {\n result[1] = ${u};\n }\n --${a[this.rank-1]};\n if(++${a[this.rank-2]} < ${n[this.rank-2]}) {\n result[2] = ${u};\n if(${i}) {\n result[3] = ${u};\n }\n }\n setOutput(result);\n }\n `}}function Ix(e,t,n){const r=Ct().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new kx(e.shape,t):new Tx(e.shape,t);return n.runWebGLProgram(r,[e],e.dtype)}function Sx(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r;return function(e,t,n,r){const a=t,s=e.shape.length,o=it(a,e.shape);let i=o;const u=Cl(i,s),l=null!=u;let c=e;l&&(c=Ix(e,u,r),i=Rl(i.length,s)),Nl("sum",i,s);const[p,h]=Sl(c.shape,i);let d=p;n&&(d=El(p,o));const f=et(h),m=U_({inputs:{x:c},attrs:{shape:[et(e.shape)/f,f]},backend:r}),g=wx(m,Ka(e.dtype,"int32"),"sum",r),y=U_({inputs:{x:g},attrs:{shape:d},backend:r});return r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(g),l&&r.disposeIntermediateTensorInfo(c),y}(a,s,o,n)}function Ex(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{perm:s}=r,o=n,i=a.shape.length,u=new Array(i);for(let e=0;e<u.length;e++)u[e]=a.shape[s[e]];let l;if(o.shouldExecuteOnCPU([a])){const e=o.texData.get(a.dataId).values,t=m_(e,a.shape,a.dtype,s,u);l=o.makeTensorInfo(u,a.dtype),o.texData.get(l.dataId).values=t}else l=Ix(a,s,o);return l}function Nx({a:e,b:t,transposeA:n,transposeB:r,backend:a,bias:s=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:u=null}){const l=e.shape.length,c=t.shape.length,p=n?e.shape[l-2]:e.shape[l-1],h=r?t.shape[c-1]:t.shape[c-2],d=n?e.shape[l-1]:e.shape[l-2],f=r?t.shape[c-2]:t.shape[c-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=et(m),b=et(g),_=Ci(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([d,f]);Qe(p===h,(()=>`Error in matMul: inner shapes (${p}) and (${h}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${r} must match.`));const x=n?[y,p,d]:[y,d,p],v=r?[b,f,h]:[b,h,f],w=U_({inputs:{x:e},backend:a,attrs:{shape:x}}),T=U_({inputs:{x:t},backend:a,attrs:{shape:v}}),k=[w,T],I=Math.max(y,b),S=n?w.shape[1]:w.shape[2],E=null!=s,N=null!=o,C="leakyrelu"===u,A=null!=u?tx(u,!0):null;let R;if((1===d||1===f)&&S>1e3&&!1===(E||N||C||null!=A)){let e=w,t=T;n&&(e=Ex({inputs:{x:w},backend:a,attrs:{perm:[0,2,1]}}),k.push(e)),r&&(t=Ex({inputs:{x:T},backend:a,attrs:{perm:[0,2,1]}}),k.push(t));const s=1===f;let o=e;1!==f&&(o=U_({inputs:{x:e},backend:a,attrs:{shape:[I,S,1]}}),k.push(o));const i=1===f?2:1;let u=t;s&&(u=U_({inputs:{x:t},backend:a,attrs:{shape:[I,1,S]}}),k.push(u));const l=bx({inputs:{a:o,b:u},backend:a});R=Sx({inputs:{x:l},backend:a,attrs:{axis:i,keepDims:!0}}),k.push(l)}else{const u=Ka(e.dtype,t.dtype),l=new mx(x,v,[I,d,f],n,r,E,A,N,C),c=[w,T];if(null!=s&&c.push(s),N&&c.push(o),C){const e=a.makeTensorInfo([],"float32",va(i,"float32"));c.push(e),k.push(e)}R=a.runWebGLProgram(l,c,u)}const $=U_({inputs:{x:R},backend:a,attrs:{shape:_}});k.push(R);for(const e of k)a.disposeIntermediateTensorInfo(e);return $}function Cx(e,t){const n=e.length;return n>=3?t?[...e.slice(0,-3),e[n-3]*e[n-2],e[n-1]]:[...e.slice(0,-3),e[n-3],e[n-2]*e[n-1]]:!t&&1===n&&e[0]>1?[e[0],1]:null}function Ax({x:e,filter:t,convInfo:n,backend:r,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:o=0,activation:i=null}){const u=e.shape,l=r.texData.get(e.dataId),c=n.inChannels,p=u[0]*u[1]*u[2],h=n.outChannels,d="channelsLast"===n.dataFormat;let f;const m=[];if(null!=s){const e=Cx(s.shape,d);null!=e&&(s=U_({inputs:{x:s},backend:r,attrs:{shape:e}}),m.push(s))}if(null!=a){const e=Cx(a.shape,d);null!=e&&(a=U_({inputs:{x:a},backend:r,attrs:{shape:e}}),m.push(a))}if((1!==p&&1!==h||!(c>1e3))&&l.isPacked&&d&&null!=l.texture&&u[2]%2!=0&&tt(l.shape.slice(-3),u.slice(-3))){const c=u[0]*u[1]*(u[2]+1),p={dataId:e.dataId,shape:[1,c,n.inChannels],dtype:e.dtype},h=l.shape;l.shape=l.shape.slice(),l.shape[l.shape.length-2]++,Qe(Oy(l.shape,p.shape),(()=>`packed reshape ${l.shape} to ${p.shape} isn't free`));const d=U_({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}});m.push(d);const g=Nx({a:p,b:d,backend:r,transposeA:!1,transposeB:!1,bias:a,activation:i,preluActivationWeights:s,leakyreluAlpha:o}),y=r.texData.get(g.dataId);Qe(y.isPacked,(()=>"batchMatMul result is expected to be packed")),l.shape=h,y.shape=n.outShape,f=K_({inputs:{x:g},backend:r}),f.shape=n.outShape,m.push(g)}else{const u=n.outHeight*n.outWidth,l=U_({inputs:{x:e},backend:r,attrs:{shape:d?[n.batchSize,u,n.inChannels]:[n.batchSize,n.inChannels,u]}}),c=U_({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}}),p=Nx({a:d?l:c,b:d?c:l,transposeA:!d,transposeB:!1,backend:r,bias:a,activation:i,preluActivationWeights:s,leakyreluAlpha:o});f=U_({inputs:{x:p},backend:r,attrs:{shape:n.outShape}}),m.push(l),m.push(c),m.push(p)}for(const e of m)r.disposeIntermediateTensorInfo(e);return f}function Rx({x:e,filter:t,convInfo:n,backend:r,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:o=0,activation:i=null}){const{filterWidth:u,filterHeight:l,inChannels:c,outWidth:p,outHeight:h,dataFormat:d}=n,f="channelsLast"===d,m=u*l*c,g=h*p,y=[n.batchSize,m,g],b=[];if(null!=s){const e=Cx(s.shape,f);null!=e&&(s=U_({inputs:{x:s},backend:r,attrs:{shape:e}}),b.push(s))}if(null!=a){const e=Cx(a.shape,f);null!=e&&(a=U_({inputs:{x:a},backend:r,attrs:{shape:e}}),b.push(a))}const _=U_({inputs:{x:t},backend:r,attrs:{shape:[1,m,et(t.shape)/m]}});b.push(_);const x=new fx(y,n),v=[e.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],w=r.runWebGLProgram(x,[e],"float32",v),T=U_({inputs:{x:w},backend:r,attrs:{shape:y}});b.push(w),b.push(T);const k=null!=a,I=null!=s,S="leakyrelu"===i,E=i?tx(i,!0):null,N=new mx(f?T.shape:_.shape,f?_.shape:T.shape,f?[n.batchSize,g,n.outChannels]:[n.batchSize,n.outChannels,g],!0,!1,k,E,I,S),C=f?[T,_]:[_,T];if(a&&C.push(a),I&&C.push(s),S){const e=r.makeTensorInfo([],"float32",va(o,"float32"));C.push(e),b.push(e)}const A=r.runWebGLProgram(N,C,"float32"),R=U_({inputs:{x:A},backend:r,attrs:{shape:n.outShape}});b.push(A);for(const e of b)r.disposeIntermediateTensorInfo(e);return R}const $x={kernelName:jt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dataFormat:u,dilations:l,dimRoundingMode:c}=r,p=Eu(u),h=yu(a.shape,s.shape,o,l,i,c,!1,p);let d;if(1!==h.filterHeight||1!==h.filterWidth||1!==h.dilationHeight||1!==h.dilationWidth||1!==h.strideHeight||1!==h.strideWidth||"SAME"!==h.padInfo.type&&"VALID"!==h.padInfo.type)if(h.strideWidth<=2&&"channelsLast"===p&&Ct().getBool("WEBGL_EXP_CONV")){const e=new dx(h),t=[[h.padInfo.top,h.padInfo.left],[h.strideHeight,h.strideWidth],[h.dilationHeight,h.dilationWidth],[h.inHeight,h.inWidth]];d=n.runWebGLProgram(e,[a,s],"float32",t)}else if(Ct().getBool("WEBGL_CONV_IM2COL"))d=Rx({x:a,filter:s,convInfo:h,backend:n});else{const e=new hx(h);d=n.runWebGLProgram(e,[a,s],"float32")}else d=Ax({x:a,filter:s,convInfo:h,backend:n});const f=U_({inputs:{x:d},backend:n,attrs:{shape:h.outShape}});return n.disposeIntermediateTensorInfo(d),f}},Mx={kernelName:Er,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dataFormat:c,dilations:p,dimRoundingMode:h,activation:d,leakyreluAlpha:f}=r,m=Eu(c),g=yu(a.shape,s.shape,u,p,l,h,!1,m);let y;const b=[],_=null!=o,x=null!=i,v="leakyrelu"===d,w=()=>{const e=[a,s],t=(e,t)=>{if("NCHW"===t&&1===e.shape.length&&1!==e.shape[0]){const t=U_({inputs:{x:e},backend:n,attrs:{shape:[e.shape[0],1,1]}});return b.push(t),t}return e};if(_&&e.push(t(o,c)),x&&e.push(t(i,c)),v){const t=n.makeTensorInfo([],"float32",va(f,"float32"));e.push(t),b.push(t)}return e};if(1!==g.filterHeight||1!==g.filterWidth||1!==g.dilationHeight||1!==g.dilationWidth||1!==g.strideHeight||1!==g.strideWidth||"SAME"!==g.padInfo.type&&"VALID"!==g.padInfo.type)if(g.strideWidth<=2&&"channelsLast"===m&&Ct().getBool("WEBGL_EXP_CONV")){const e=d?tx(d,!0):null,t=new dx(g,_,e,x,v),r=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],a=w();y=n.runWebGLProgram(t,a,"float32",r)}else if(Ct().getBool("WEBGL_CONV_IM2COL"))y=Rx({x:a,filter:s,convInfo:g,backend:n,bias:o,activation:d,preluActivationWeights:i,leakyreluAlpha:f});else{const e=d?tx(d,!1):null,t=new hx(g,_,e,x,v),r=w();y=n.runWebGLProgram(t,r,"float32")}else y=Ax({x:a,filter:s,convInfo:g,backend:n,bias:o,activation:d,preluActivationWeights:i,leakyreluAlpha:f});const T=U_({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach((e=>n.disposeIntermediateTensorInfo(e))),T}};class Fx{constructor(e,t=!1,n=null,r=!1,a=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=lb(this.outputShape.length);const s=e.filterHeight,o=e.filterWidth,i=e.outChannels/e.inChannels;let u="",l="";n&&(u=r?`float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:a?`float activation(float a) {\n float b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`\n float activation(float x) {\n ${n}\n }\n `,l="result = activation(result);");const c=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${u}\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / ${i};\n int q = d2 - d1 * ${i};\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < ${s}; wR++) {\n int xR = xRCorner + wR * dilations[0];\n\n if (xR < 0 || xR >= inDims[0]) {\n continue;\n }\n\n for (int wC = 0; wC < ${o}; wC++) {\n int xC = xCCorner + wC * dilations[1];\n\n if (xC < 0 || xC >= inDims[1]) {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n\n float result = dotProd;\n ${c}\n ${l}\n setOutput(result);\n }\n `}}class Ox{constructor(e,t=!1,n=null,r=!1,a=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=lb(this.outputShape.length);const s=e.outChannels/e.inChannels,o=e.padInfo.left,i=e.strideWidth,u=e.dilationWidth,l=e.filterHeight,c=e.filterWidth,p=c;let h="\n int xR; int xC; int xCOffset;\n vec4 wTexel; vec4 previous; vec4 final;";for(let e=0;e<c;e++)h+=`\n vec4 xTexelC${2*e};\n int xTexelC${2*e}Ready;\n vec4 xTexelC${2*e+1};\n int xTexelC${2*e+1}Ready;\n vec4 xC${e};`;h+=`\n for (int r = 0; r < ${l}; r++) {\n `;for(let e=0;e<c;e++)h+=`\n xTexelC${2*e} = vec4(0.0);\n xTexelC${2*e}Ready = 0;\n xTexelC${2*e+1} = vec4(0.0);\n xTexelC${2*e+1}Ready = 0;\n xC${e} = vec4(0.0);`;h+="\n xR = xRCorner + r * dilations[0];\n if (xR >=0 && xR < inDims[0]) {\n ";for(let e=0;e<(p+1)/2;e++){const t=2*e;if(h+=`\n xC = xCCorner + ${t*u};\n `,1===i){if(t<c&&(o%2==1?(h+=`\n xCOffset = xC + 1;\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n `,h+=1===u&&t>0?`\n xC${t} = vec4(xTexelC${t-2}.zw, xTexelC${t}.xy);\n `:`\n xCOffset = xC + 1 - 2;\n\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n previous.zw = vec2(0.0);\n }\n\n xC${t} = vec4(previous.zw, xTexelC${t}.xy);\n } else {\n xC${t} = vec4(0.0, 0.0, xTexelC${t}.xy);\n }\n `):h+=`\n if (xC >= 0 && xC < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n\n xC${t} = xTexelC${t};\n `,t+1<c)){const e=o%2==0?Xe(u):u;u%2==0&&o%2==1||u%2!=0&&o%2!=1?(h+=`\n xCOffset = xC + imod(pads[1], 2) + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.0);\n }\n xTexelC${t+1}Ready = 1;\n }\n `,h+=u>1?`\n xCOffset -= 2;\n if (xCOffset >= 0 && xCOffset < inDims[1]) {\n previous = getX(batch, xR, xCOffset, d1);\n xC${t+1} = vec4(previous.zw, xTexelC${t+1}.xy);\n } else {\n xC${t+1} = vec4(0.0, 0.0, xTexelC${t+1}.xy);\n }\n `:`\n xC${t+1} = vec4(xTexelC${t}.zw, xTexelC${t+1}.xy);\n `):h+=1===e?`\n xC${t+1} = xTexelC${t};\n `:`\n xCOffset = xC + ${e};\n\n if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.0);\n }\n xTexelC${t+1}Ready = 1;\n }\n\n xC${t+1} = xTexelC${t+1};\n `}}else t<c&&(o%2==1?(h+=`\n xCOffset = xC + 1 - strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xCOffset, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n\n if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xC + 1, d1);\n // Need to manually clear unused channels in case\n // we're reading from recycled texture.\n if (xC + 2 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.0);\n }\n xTexelC${t+1}Ready = 1;\n }\n\n xC${t} = vec4(xTexelC${t}.zw, xTexelC${t+1}.zw);\n `,t+1<c&&(h+=`\n final = vec4(0.0);\n xCOffset = xC + 1 + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1]) {\n final = getX(batch, xR, xCOffset, d1);\n }\n xC${t+1} = vec4(xTexelC${t+1}.xy, final.xy);\n `)):(h+=`\n if(xC >= 0 && xC < inDims[1] && xTexelC${t}Ready == 0) {\n xTexelC${t} = getX(batch, xR, xC, d1);\n if (xC + 1 >= inDims[1]) {\n xTexelC${t}.zw = vec2(0.0);\n }\n xTexelC${t}Ready = 1;\n }\n\n xCOffset = xC + strides[1];\n if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n if (xCOffset + 1 >= inDims[1]) {\n xTexelC${t+1}.zw = vec2(0.);\n }\n xTexelC${t+1}Ready = 1;\n }\n\n xC${t} = vec4(\n xTexelC${t}.xy, xTexelC${t+1}.xy);\n `,t+1<c&&(h+=`\n xC${t+1} = vec4(xTexelC${t}.zw, xTexelC${t+1}.zw);\n `)));t<c&&(h+=`\n wTexel = getW(r, ${t}, d1, q);\n dotProd += xC${t} * vec4(wTexel.xz, wTexel.xz);\n `,t+1<c&&(h+=`\n wTexel = getW(r, ${t+1}, d1, q);\n dotProd += xC${t+1} * vec4(wTexel.xz, wTexel.xz);\n `))}h+="\n }\n ",h+="\n }\n ";let d="",f="";n&&(d=r?`vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n ${n}\n }`:a?`vec4 activation(vec4 a) {\n vec4 b = getLeakyreluAlphaAtOutCoords();\n ${n}\n }`:`vec4 activation(vec4 x) {\n ${n}\n }`,f="result = activation(result);");const m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n ${d}\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / ${s};\n int q = d2 - d1 * ${s};\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.\n vec4 dotProd = vec4(0.000000000000001);\n\n ${h}\n\n vec4 result = dotProd - vec4(0.000000000000001);\n ${m}\n ${f}\n setOutput(result);\n }\n `}}const Dx={kernelName:Nr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dilations:c,dimRoundingMode:p,activation:h,leakyreluAlpha:d}=r,f=[];let m=c;null==m&&(m=[1,1]),Qe(Iu(u,m),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${u} and dilations '${m}'`));const g=yu(a.shape,s.shape,u,m,l,p,!0),y=Ct().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,b=h?tx(h,y):null,_=[a,s],x=null!=o,v=null!=i,w="leakyrelu"===h;if(x&&_.push(o),v&&_.push(i),w){const e=n.makeTensorInfo([],"float32",va(d,"float32"));_.push(e),f.push(e)}let T;T=y?new Ox(g,x,b,v,w):new Fx(g,x,b,v,w);const k=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],I=n.runWebGLProgram(T,_,"float32",k);return f.forEach((e=>n.disposeIntermediateTensorInfo(e))),I}},Lx="return a + b;",Px=ex({opSnippet:Lx,packedOpSnippet:Lx,supportsComplex:!0,cpuKernelImpl:kb}),Bx={kernelName:Ft,backendName:"webgl",kernelFunc:Px},Ux={kernelName:rr,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,paddings:o}=r;Qe(a.shape.length<=4,(()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"));const i=s.reduce(((e,t)=>e*t)),u=[[0,0]];u.push(...o);for(let e=1+s.length;e<a.shape.length;++e)u.push([0,0]);const l=[],c=cx({inputs:{x:a},backend:n,attrs:{paddings:u,constantValue:0}}),p=vd(c.shape,s,i,!1),h=wd(p.length,s.length,!1),d=Td(c.shape,s,i,!1),f=U_({inputs:{x:c},backend:n,attrs:{shape:p}}),m=Ex({inputs:{x:f},backend:n,attrs:{perm:h}}),g=U_({inputs:{x:m},backend:n,attrs:{shape:d}});return l.push(c),l.push(f),l.push(m),l.forEach((e=>n.disposeIntermediateTensorInfo(e))),g}},zx={kernelName:Zt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dilations:u,dimRoundingMode:l}=r;let c=u;null==c&&(c=[1,1]),Qe(Iu(o,c),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`));const p=yu(a.shape,s.shape,o,c,i,l,!0);let h;h=Ct().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels==1?new Ox(p):new Fx(p);const d=[[p.padInfo.top,p.padInfo.left],[p.strideHeight,p.strideWidth],[p.dilationHeight,p.dilationWidth],[p.inHeight,p.inWidth]];return n.runWebGLProgram(h,[a,s],"float32",d)}};class Vx{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=rb(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const n=function(e){if(1===e)return"sourceLoc";if(e<=6)return Wx.slice(0,e).map((e=>"sourceLoc."+e)).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}(this.rank);let r;const a=e.map(((e,t)=>`sourceLoc.${Wx[t]} = start[${t}] + coords.${Wx[t]};`));r=`\n ${t} sourceLoc;\n ${t} coords = getOutputCoords();\n ${a.join("\n")}\n `,this.userCode=`\n void main() {\n ${r}\n setOutput(getSource(${n}));\n }\n `}}const Wx=["x","y","z","w","u","v"];class Hx{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const t=rb(this.rank),n=b_("coords",this.rank),r=b_("sourceLoc",this.rank),a=1===this.rank?"sourceLoc":`vec2(${r.slice(-2).join()})`,s=`getChannel(getSource(${r.join()}), ${a})`,o=`\n result.x = ${s};\n if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n ++${r[this.rank-1]};\n result.y = ${s};\n --${r[this.rank-1]};\n }\n `,i=1===this.rank?"":`\n --${n[this.rank-1]};\n if (++${n[this.rank-2]} < ${e[this.rank-2]}) {\n ++${r[this.rank-2]};\n result.z = ${s};\n if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n ++${r[this.rank-1]};\n result.w = ${s};\n }\n }\n `,u=this.rank<=4?`sourceLoc = coords +\n ${t}(${e.map(((e,t)=>`start[${t}]`)).join()});`:e.map(((e,t)=>`${r[t]} = ${n[t]} + start[${t}];`)).join("\n");this.userCode=`\n void main() {\n ${t} coords = getOutputCoords();\n ${t} sourceLoc;\n ${u}\n vec4 result = vec4(0.);\n ${o}\n ${i}\n setOutput(result);\n }\n `}}function Gx(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,size:o}=r,[i,u]=Xi(a,s,o);if(Li(a,i,u),0===et(u))return n.makeTensorInfo(u,a.dtype,[]);if(n.shouldExecuteOnCPU([a])||"string"===a.dtype){const e=n.texData.get(a.dataId),t=r_(e.values,i,u,a.shape,a.dtype);return n.makeTensorInfo(u,a.dtype,t)}const{isPacked:l}=n.texData.get(a.dataId),c=Ki(a.shape,i,u);if(l||!c){const e=Ct().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Hx(u):new Vx(u),t=[i];return n.runWebGLProgram(e,[a],a.dtype,t)}return n.uploadToGPU(a.dataId),function(e,t,n,r){const a=r.texData.get(e.dataId),s=r.makeTensorInfo(n,e.dtype),o=r.texData.get(s.dataId);Object.assign(o,a),o.refCount=1,o.shape=n,o.dtype=e.dtype;let i=qi(t,yt(e.shape));a.slice&&(i+=a.slice.flatOffset),o.slice={flatOffset:i,origDataId:a.slice&&a.slice.origDataId||e.dataId};const u=r.dataRefCount.get(o.slice.origDataId)||1;return r.dataRefCount.set(o.slice.origDataId,u+1),s}(a,i,u,n)}const jx={kernelName:Zn,backendName:"webgl",kernelFunc:Gx},Kx={kernelName:zt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,crops:o}=r;Qe(a.shape.length<=4,(()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"));const i=s.reduce(((e,t)=>e*t)),u=vd(a.shape,s,i),l=wd(u.length,s.length),c=Td(a.shape,s,i),p=kd(o,s.length),h=Id(c,o,s.length),d=[],f=U_({inputs:{x:a},backend:n,attrs:{shape:u}}),m=Ex({inputs:{x:f},backend:n,attrs:{perm:l}}),g=U_({inputs:{x:m},backend:n,attrs:{shape:c}}),y=Gx({inputs:{x:g},backend:n,attrs:{begin:p,size:h}});return d.push(f),d.push(m),d.push(g),d.forEach((e=>n.disposeIntermediateTensorInfo(e))),y}},qx=Z_({opSnippet:S_+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",packedOpSnippet:"\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n"}),Xx={kernelName:Kn,backendName:"webgl",kernelFunc:qx};class Yx{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const r=n.length,a=rb(n.length),s=rb(n.length);let o="";if(1===r)o="coords * strides + begin";else{let e=0;o=n.map(((t,r)=>(e++,1===n.length?`coords * strides[${r}] + begin[${r}]`:`coords[${e-1}] * strides[${r}] + begin[${r}]`))).join(",")}this.userCode=`\n ${a} begin = ${a}(${e});\n ${a} strides = ${a}(${t});\n\n void main() {\n ${s} coords = getOutputCoords();\n setOutput(getX(${o}));\n }\n `}}const Qx={kernelName:pr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,end:o,strides:i,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:h}=r,{finalShapeSparse:d,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:_,strides:x}=Yi(a.shape,s,o,i,u,l,c,p,h);let v;if(m)v=U_({inputs:{x:a},backend:n,attrs:{shape:f}});else if(g||y){Qe(a.shape.length>=1,(()=>`Input must have rank at least 1, got: ${a.shape.length}`));const e=Pi(b,_,x),t=Gx({inputs:{x:a},backend:n,attrs:{begin:b,size:e}});v=U_({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else if(n.shouldExecuteOnCPU([a])){const e=n.readSync(a.dataId),t=ju(a.shape,a.dtype,e),r=u_(d,t,x,b);v=n.makeTensorInfo(f,a.dtype,r.values)}else{const e=new Yx(b,x,d);v=n.runWebGLProgram(e,[a],a.dtype)}const w=U_({inputs:{x:v},backend:n,attrs:{shape:f}});return n.disposeIntermediateTensorInfo(v),w}};class Jx{constructor(e){this.outputShape=[],this.outputShape=dd(e,1),this.variableNames=e.map(((e,t)=>`T${t}`));const t=new Array(e.length-1);t[0]=e[0][1];for(let n=1;n<t.length;n++)t[n]=t[n-1]+e[n][1];const n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let e=1;e<t.length;e++){const r=t[e-1];n.push(`else if (yC < ${t[e]}) setOutput(getT${e}(yR, yC-${r}));`)}const r=t.length,a=t[t.length-1];n.push(`else setOutput(getT${r}(yR, yC-${a}));`),this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n ${n.join("\n ")}\n }\n `}}class Zx{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=dd(e,t);const n=this.outputShape,r=n.length,a=rb(r),s=b_("coords",r),o=["x","y","z","w","u","v"].slice(0,r);this.variableNames=e.map(((e,t)=>`T${t}`));const i=new Array(e.length-1);i[0]=e[0][t];for(let n=1;n<i.length;n++)i[n]=i[n-1]+e[n][t];const u=o[t],l=o.slice(-2),c=o.join();let p=`if (${u} < ${i[0]}) {\n return getChannel(\n getT0(${c}), vec2(${l.join()}));\n }`;for(let e=1;e<i.length;e++){const t=i[e-1];p+=`\n if (${u} < ${i[e]} && ${u} >= ${i[e-1]}) {\n return getChannel(\n getT${e}(${ev(o,u,t)}),\n vec2(${ev(l,u,t)}));\n }`}const h=i.length,d=i[i.length-1];p+=`\n return getChannel(\n getT${h}(${ev(o,u,d)}),\n vec2(${ev(l,u,d)}));`,this.userCode=`\n float getValue(${o.map((e=>"int "+e))}) {\n ${p}\n }\n\n void main() {\n ${a} coords = getOutputCoords();\n vec4 result = vec4(getValue(${s}), 0., 0., 0.);\n\n ${s[r-1]} = ${s[r-1]} + 1;\n if (${s[r-1]} < ${n[r-1]}) {\n result.g = getValue(${s});\n }\n\n ${s[r-2]} = ${s[r-2]} + 1;\n if (${s[r-2]} < ${n[r-2]}) {\n result.a = getValue(${s});\n }\n\n ${s[r-1]} = ${s[r-1]} - 1;\n if (${s[r-2]} < ${n[r-2]} &&\n ${s[r-1]} < ${n[r-1]}) {\n result.b = getValue(${s});\n }\n setOutput(result);\n }\n `}}function ev(e,t,n){const r=e.indexOf(t);return e.map(((e,t)=>t===r?`${e} - ${n}`:e)).join()}function tv(e,t,n){const r=e[0].dtype;if("complex64"===r){const r=e.map((e=>rx({inputs:{input:e},backend:n}))),a=e.map((e=>function(e){const{inputs:t,backend:n}=e,{input:r}=t;return K_({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.imag},backend:n})}({inputs:{input:e},backend:n}))),s=tv(r,t,n),o=tv(a,t,n),i=X_({inputs:{real:s,imag:o},backend:n});return r.forEach((e=>n.disposeIntermediateTensorInfo(e))),a.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(o),i}let a=n.shouldExecuteOnCPU(e);if("string"===r&&(a=!0),a){const a=e.map((e=>{const r=et(e.shape.slice(t));return U_({inputs:{x:e},backend:n,attrs:{shape:[-1,r]}})})),s=a.map((e=>({vals:n.readSync(e.dataId),shape:e.shape}))),o=dd(a.map((e=>e.shape)),1),i=1===a[0].shape[0],u=Cb(s,o,r,i),l=dd(e.map((e=>e.shape)),t),c=n.makeTensorInfo(l,r,u);return a.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}const s=e.filter((e=>et(e.shape)>0)),o=Ct().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&s[0].shape.length>1;if(1===s.length){const t=o?new I_(e[0].shape,N_):new C_(e[0].shape,N_);return n.runWebGLProgram(t,e,r)}const i=Ct().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(s.length>i){const e=[];for(let r=0;r<s.length;r+=i){const a=s.slice(r,r+i);e.push(tv(a,t,n))}const r=tv(e,t,n);for(const t of e)n.disposeIntermediateTensorInfo(t);return r}if(o){const e=new Zx(s.map((e=>e.shape)),t);return n.runWebGLProgram(e,s,r)}const{tensors2D:u,outShape:l}=function(e,t,n){const r=dd(e.map((e=>e.shape)),t),a=e.map((e=>U_({inputs:{x:e},attrs:{shape:[-1,et(e.shape.slice(t))]},backend:n})));return{tensors2D:a,outShape:r}}(s,t,n),c=new Jx(u.map((e=>e.shape))),p=n.runWebGLProgram(c,u,r);u.forEach((e=>n.disposeIntermediateTensorInfo(e)));const h=U_({inputs:{x:p},attrs:{shape:l},backend:n});return n.disposeIntermediateTensorInfo(p),h}function nv(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r,s=it(a,t[0].shape)[0];hd(t.map((e=>e.shape)),s);const o=dd(t.map((e=>e.shape)),s);if(0===et(o))return n.makeTensorInfo(o,t[0].dtype,[]);const i=t.filter((e=>et(e.shape)>0));return 1===i.length?K_({inputs:{x:i[0]},backend:n}):tv(i,s,n)}const rv={kernelName:Gt,backendName:"webgl",kernelFunc:nv},av={kernelName:Ln,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return V_({inputs:{input:t[0]},backend:n,attrs:{dim:a}});const s=t[0].shape,o=t[0].dtype;t.forEach((e=>{Je(s,e.shape,"All tensors passed to stack must have matching shapes"),Qe(o===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const i=[],u=nv({inputs:t.map((e=>{const t=V_({inputs:{input:e},backend:n,attrs:{dim:a}});return i.push(t),t})),backend:n,attrs:{axis:a}});return i.forEach((e=>n.disposeIntermediateTensorInfo(e))),u}};class sv{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,s="channelsLast"===e.dataFormat,o=t-1-e.padInfo.top,i=n-1-e.padInfo.left,u=s?1:2,l=s?2:3,c=s?3:1;this.userCode=`\n const ivec2 pads = ivec2(${o}, ${i});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[${c}];\n\n ivec2 dyCorner = ivec2(coords[${u}], coords[${l}]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < ${t}; wR++) {\n float dyR = float(dyRCorner + wR) / ${r}.0;\n\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = ${t} - 1 - wR;\n\n for (int wC = 0; wC < ${n}; wC++) {\n float dyC = float(dyCCorner + wC) / ${a}.0;\n\n if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = ${n} - 1 - wC;\n\n for (int d2 = 0; d2 < ${e.outChannels}; d2++) {\n\n if (${s}) {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n `}}const ov={kernelName:Kt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{inputShape:o,strides:i,pad:u,dataFormat:l,dimRoundingMode:c}=r,p=Eu(l),h=yu(o,s.shape,i,1,u,c,!1,p),d=new sv(h);return n.runWebGLProgram(d,[a,s],"float32")}},iv=Z_({opSnippet:S_+"\n return (x < 0.0) ? 0.0 : x;\n",packedOpSnippet:"\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n"}),uv={kernelName:Wn,backendName:"webgl",kernelFunc:iv},lv=Z_({opSnippet:J_+"\n return 1.0 / (1.0 + exp(-1.0 * x));\n",packedOpSnippet:"\n vec4 result = 1.0 / (1.0 + exp(-1.0 * x));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",cpuKernelImpl:t_}),cv={kernelName:er,backendName:"webgl",kernelFunc:lv};class pv{constructor(e,t,n,r,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[s,o,i,u]=e,[l]=t,[c,p]=n;this.outputShape=[l,c,p,u];const h="bilinear"===r?1:0,[d,f]=[o-1+".0",i-1+".0"],[m,g,y]=c>1?[""+(o-1)/(c-1),"(y2-y1) * height_ratio",`y1*${d} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${d}`],[b,_,x]=p>1?[""+(i-1)/(p-1),"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${f}`];this.userCode=`\n const float height_ratio = float(${m});\n const float width_ratio = float(${b});\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= ${s}) {\n return;\n }\n\n float height_scale = ${g};\n float width_scale = ${_};\n\n float in_y = ${y};\n if( in_y < 0.0 || in_y > ${d} ) {\n setOutput(float(${a}));\n return;\n }\n float in_x = ${x};\n if( in_x < 0.0 || in_x > ${f} ) {\n setOutput(float(${a}));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if(${h} == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n `}}const hv={kernelName:Qt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{image:a,boxes:s,boxInd:o}=t,{cropSize:i,method:u,extrapolationValue:l}=r,c=new pv(a.shape,s.shape,i,u,l);return n.runWebGLProgram(c,[a,s,o],"float32")}};class dv{constructor(e,t){this.variableNames=["x"];const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,1===n)return void(this.userCode=`\n void main() {\n int coord = getOutputCoords();\n setOutput(getX(${e[0]} - coord - 1));\n }\n `);const r=e.map(((n,r)=>(n=>-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - coords[${n}] - 1`:`coords[${n}]`)(r))).join(","),a=rb(n);this.userCode=`\n void main() {\n ${a} coords = getOutputCoords();\n setOutput(getX(${r}));\n }\n `}}class fv{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;const r=b_("rc",n),a=`${r[n-1]} + 1 < ${this.outputShape[n-1]}`,s=`${r[n-2]} + 1 < ${this.outputShape[n-2]}`,o=rb(n);function i(n){const r=e.map(((r,a)=>function(n,r){return-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - ${r[n]} - 1`:`${r[n]}`}(a,n)));return`getChannel(getX(${r.join(",")}), vec2(${r.slice(-2).join(",")}))`}this.userCode=1===n?`\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX(${e[0]} - rc - 1),\n ${e[0]} - rc - 1);\n if(${a}){\n result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),\n ${e[0]} - (rc + 1) - 1);\n }\n setOutput(result);\n }\n `:`\n void main() {\n ${o} rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = ${function(e){return i(e)}(r.slice())};\n if(${a}){\n result.g = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",i(e)}(r.slice())};\n }\n if(${s}) {\n result.b = ${function(e){return e[n-2]="("+e[n-2]+" + 1)",i(e)}(r.slice())};\n if(${a}) {\n result.a = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",e[n-2]="("+e[n-2]+" + 1)",i(e)}(r.slice())};\n }\n }\n setOutput(result);\n }\n `}}const mv={kernelName:qn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dims:s}=r,o=a.shape.length,i=it(s,a.shape);if(0===o)return K_({inputs:{x:a},backend:n});const u=Ct().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new fv(a.shape,i):new dv(a.shape,i);return n.runWebGLProgram(u,[a],a.dtype)}},gv="return a - b;",yv=ex({opSnippet:gv,packedOpSnippet:gv,supportsComplex:!0,cpuKernelImpl:h_}),bv={kernelName:mr,backendName:"webgl",kernelFunc:yv},_v={kernelName:vr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{value:a}=t;let{axis:s}=r;s<0&&(s+=a.shape.length);const o=a,i=o.shape.length,u=a.shape[s],l=new Array(i-1);let c=0;for(let e=0;e<i;e++)e!==s&&(l[c++]=o.shape[e]);const p=[],h=new Array(i).fill(0),d=o.shape.slice();d[s]=1;const f=new Array(u);for(let e=0;e<f.length;e++){h[s]=e;const t=Gx({inputs:{x:o},backend:n,attrs:{begin:h,size:d}}),r=U_({inputs:{x:t},backend:n,attrs:{shape:l}});f[e]=r,p.push(t)}return p.forEach((e=>n.disposeIntermediateTensorInfo(e))),f}};class xv{constructor(e,t,n){this.variableNames=["A"];const{windowSize:r,batchSize:a,outSize:s}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[a,s];const o="max"===t?">":"<",i=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * ${r};\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < ${r}; i++) {\n int inIdx = ${i};\n float candidate = getA(batch, inIdx);\n if (candidate ${o} bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n `}}class vv{constructor(e,t,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,Qe(e.length>2,(()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`));const a=e[e.length-1],s=Math.ceil(a/t);this.outputShape=e.slice(0,-1),s>1&&this.outputShape.push(s),r||this.variableNames.push("bestIndicesA");const o=this.outputShape,i=o.length,u=rb(i),l=b_("coords",i);let c,p;if(1===s){p=i+1;const e=rb(p);c=`\n ${e} sourceLocR = ${e}(${l.join()}, 0);\n ++${l[i-1]};\n ${e} sourceLocG = ${e}(${l.join()}, 0);\n ++${l[i-2]};\n ${e} sourceLocA = ${e}(${l.join()}, 0);\n --${l[i-1]};\n ${e} sourceLocB = ${e}(${l.join()}, 0);\n --${l[i-2]};`}else p=i,c=`\n ${u} sourceLocR = coords;\n ++${l[i-1]};\n ${u} sourceLocG = coords;\n ++${l[i-2]};\n ${u} sourceLocA = coords;\n --${l[i-1]};\n ${u} sourceLocB = coords;\n --${l[i-2]};`;const h=["x","y","z","w","u","v"].slice(0,p),d="."+h[p-1],f=h.map((e=>"int "+e)),m=b_("sourceLocR",p-1).concat("inIdx.r"),g=b_("sourceLocG",p-1).concat("inIdx.g"),y=b_("sourceLocB",p-1).concat("inIdx.b"),b=b_("sourceLocA",p-1).concat("inIdx.a"),_="max"===n?"greaterThan":"lessThan",x=r?"":`\n inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),\n getBestIndicesAChannel(${g.join()}),\n getBestIndicesAChannel(${y.join()}),\n getBestIndicesAChannel(${b.join()})));`,v=`vec4(\n getAChannel(${m.join()}),\n hasNextCol ? getAChannel(${g.join()}) : 0.,\n hasNextRow ? getAChannel(${y.join()}) : 0.,\n hasNextRow && hasNextCol ? getAChannel(${b.join()}) : 0.)`,w=r?"":`\n float getBestIndicesAChannel(${f.join()}) {\n return getChannel(getBestIndicesA(${h.join()}),\n vec2(${h.slice(-2).join()}));\n }`;this.userCode=`\n float getAChannel(${f.join()}) {\n return getChannel(getA(${h.join()}),\n vec2(${h.slice(-2).join()}));\n }\n ${w}\n void main() {\n ${u} coords = getOutputCoords();\n bool hasNextCol = ${l[i-1]} < ${o[i-1]-1};\n bool hasNextRow = ${l[i-2]} < ${o[i-2]-1};\n ${c}\n ivec4 srcIdx = ivec4(sourceLocR${d}, sourceLocG${d},\n sourceLocB${d}, sourceLocA${d}) * ${t};\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = ${v};\n\n for (int i = 0; i < ${t}; i++) {\n inIdx = srcIdx;\n ${x}\n vec4 candidate = ${v};\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4(${_}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n `}}function wv(e,t,n,r=null){let a=t.shape[0],s=t.shape[1];null!=r&&(a=r.shape[0],s=r.shape[1]);const o=_d(s),i={windowSize:o,inSize:s,batchSize:a,outSize:Math.ceil(s/o)},u=new xv(i,n,null==r),l=[t];null!=r&&l.push(r);const c=e.runWebGLProgram(u,l,"int32");if(1===c.shape[1])return c;const p=wv(e,t,n,c);return e.disposeIntermediateTensorInfo(c),p}function Tv(e,t,n,r=null){const a=null!=r?r.shape:t.shape,s=_d(a[a.length-1]),o=new vv(a,s,n,null==r),i=null==r?[t]:[t,r],u=e.runWebGLProgram(o,i,"int32");if(u.shape.length===t.shape.length){const r=Tv(e,t,n,u);return e.disposeIntermediateTensorInfo(u),r}return u}function kv(e,t,n,r){const a=[n];if(Nl("arg"+r.charAt(0).toUpperCase()+r.slice(1),a,t.shape.length),!Ct().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){const n=[],s=e.texData.get(t.dataId);let o=t;null!==s&&s.isPacked&&(o=e.unpackTensor(t),n.push(o));const[i,u]=Sl(o.shape,a),l=et(u),c=U_({inputs:{x:o},backend:e,attrs:{shape:[-1,l]}});n.push(c);const p=wv(e,c,r);n.push(p);const h=U_({inputs:{x:p},backend:e,attrs:{shape:i}});return n.forEach((t=>e.disposeIntermediateTensorInfo(t))),h}return Tv(e,t,r)}const Iv={kernelName:Pt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;let o=it(s,a.shape);const i=Cl(o,a.shape.length);let u=a;const l=[];null!=i&&(u=Ex({inputs:{x:a},backend:n,attrs:{perm:i}}),l.push(u),o=Rl(o.length,u.shape.length)),Nl("argMax",[o[0]],u.shape.length);const c=kv(n,u,o[0],"max");return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}},Sv={kernelName:Sn,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{keepDims:a,axis:s}=t,o=n,i=r.shape.length,u=it(s,r.shape);let l=u;const c=Cl(l,i),p=null!=c,h=o.shouldExecuteOnCPU([r]),d=[];let f=r;if(p){if(h){const e=o.texData.get(f.dataId).values,t=new Array(i);for(let e=0;e<t.length;e++)t[e]=r.shape[c[e]];const n=m_(e,r.shape,r.dtype,c,t);f=o.makeTensorInfo(t,r.dtype),o.texData.get(f.dataId).values=n}else f=Ix(r,c,o);d.push(f),l=Rl(l.length,i)}Nl("sum",l,i);const[m,g]=Sl(f.shape,l);let y=m;a&&(y=El(m,u));const b=function(e,t,n,r){const a=et(t),s=U_({inputs:{x:e},attrs:{shape:[et(e.shape)/a,a]},backend:r}),o=wx(s,"float32","mean",r),i=U_({inputs:{x:o},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(o),i}(f,g,y,o);for(const e of d)o.disposeIntermediateTensorInfo(e);return b}},Ev=Z_({opSnippet:J_+"\n return exp(x);\n",packedOpSnippet:"\n vec4 result = exp(x);\n bvec4 isNaN = isnan(x);\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",cpuKernelImpl:Rb,dtype:"float32"}),Nv={kernelName:sr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{dim:s}=r,o=it([s],a.shape),i=function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{reductionIndices:s,keepDims:o}=r,i=a.shape.length,u=it(s,a.shape);let l=u;const c=Cl(l,i),p=null!=c,h=n.shouldExecuteOnCPU([a]);let d=a;if(p){if(h){const e=n.texData.get(d.dataId).values,t=new Array(i);for(let e=0;e<t.length;e++)t[e]=a.shape[c[e]];const r=m_(e,a.shape,a.dtype,c,t);d=n.makeTensorInfo(t,a.dtype),n.texData.get(d.dataId).values=r}else d=Ix(a,c,n);l=Rl(l.length,i)}Nl("max",l,i);const[f,m]=Sl(d.shape,l);let g,y=f;if(o&&(y=El(f,u)),h){const e=n.texData.get(d.dataId).values,t=Vb(e,et(m),y,a.dtype);g=n.makeTensorInfo(y,a.dtype),n.texData.get(g.dataId).values=t}else g=function(e,t,n,r){const a=et(t),s=U_({inputs:{x:e},attrs:{shape:[et(e.shape)/a,a]},backend:r}),o=wx(s,e.dtype,"max",r),i=U_({inputs:{x:o},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(o),i}(d,m,y,n);return p&&n.disposeIntermediateTensorInfo(d),g}({inputs:{x:a},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),u=El(i.shape,o),l=U_({inputs:{x:i},backend:n,attrs:{shape:u}}),c=yv({inputs:{a,b:l},backend:n}),p=Ev({inputs:{x:c},backend:n}),h=Sx({inputs:{x:p},backend:n,attrs:{axis:o,keepDims:!1}}),d=U_({inputs:{x:h},backend:n,attrs:{shape:u}}),f=sx({inputs:{a:p,b:d},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(d),f}};class Cv{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode="\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}}class Av{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode="\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n }\n "}}const Rv={kernelName:Ht,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{clipValueMin:s,clipValueMax:o}=r;let i;i=Ct().getBool("WEBGL_PACK_CLIP")?new Av(a.shape):new Cv(a.shape);const u=[[s],[o]];return n.runWebGLProgram(i,[a],a.dtype,u)}};class $v{constructor(e,t,n,r=!1,a=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const s=e.filterWidth,o=e.strideHeight,i=e.strideWidth,u=e.dilationHeight,l=e.dilationWidth,c=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=e.padInfo.top,d=e.padInfo.left;this.outputShape=e.outShape;const f="avg"===t,m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let y="0.0";if(f||(y="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\n const ivec2 strides = ivec2(${o}, ${i});\n const ivec2 pads = ivec2(${h}, ${d});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < ${c};\n wR += ${u}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${p};\n wC += ${l}) {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= ${e.inWidth}) {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value ${t} currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = ${r?a?m:g:`wR * ${p} + wC`};\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n `)}let b=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(b="avgValue / max(count, 1.0)");const _=4*Math.floor(s/4),x=s%4,v=`\n if (${f}) {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n `;this.userCode=`\n const ivec2 strides = ivec2(${o}, ${i});\n const ivec2 pads = ivec2(${h}, ${d});\n const float initializationValue = ${y};\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= ${e.inWidth}) {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4(${y});\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < ${c};\n wR += ${u}) {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= ${e.inHeight}) {\n continue;\n }\n\n for (int wC = 0; wC < ${_}; wC += 4) {\n int xC = xCCorner + wC * ${l};\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${l}, d),\n getValue(batch, xR, xC + 2 * ${l}, d),\n getValue(batch, xR, xC + 3 * ${l}, d)\n );\n\n ${v}\n }\n\n int xC = xCCorner + ${_};\n if (${1===x}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n ${v}\n } else if (${2===x}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${l}, d),\n initializationValue,\n initializationValue\n );\n\n ${v}\n } else if (${3===x}) {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + ${l}, d),\n getValue(batch, xR, xC + 2 * ${l}, d),\n initializationValue\n );\n\n ${v}\n }\n }\n setOutput(${b});\n }\n `}}const Mv={kernelName:Bt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;!function(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&Qe("complex64"!==e.dtype,(()=>"avgPool does not support complex64 tensors in the WebGL backend."))}))}(a);const{filterSize:s,strides:o,pad:i,dimRoundingMode:u}=r;Qe(Iu(o,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '1'`));const l=gu(a.shape,s,o,1,i,u);if(1===l.filterWidth&&1===l.filterHeight&&tt(l.inShape,l.outShape))return K_({inputs:{x:a},backend:n});const c=new $v(l,"avg",!1);return n.runWebGLProgram(c,[a],"float32")}},Fv={kernelName:Ut,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a,b:s}=t,{transposeA:o,transposeB:i}=r;return Nx({a,b:s,transposeA:o,transposeB:i,backend:n})}},Ov={kernelName:Sr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a,b:s,bias:o,preluActivationWeights:i}=t,{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:p}=r;return Nx({a,b:s,transposeA:u,transposeB:l,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:p,activation:c})}};Or(Sg),Or(Eg),Or(_m),Or(Ag),Or(Rg),Or(Mg),Or(zg),Or(Hg),Or(Im),Or(Gg),Or(Wg),Or(jg),Or(Km),Or(Bg),Or(Kg),Or(Qg),Or(Jg),Or(Lg),Or(og),Or(mm),Or(Zg),Or(ey),Or(Xg),Or(vg),Or(ty),Or(ny),Or(ay),Or(lg),Or(sy),Or(iy),Or(uy),Or(ly),Or(L_),Or(z_),Or(W_),Or(j_),Or(ax),Or(ox),Or(px),Or($x),Or(Mx),Or(Dx),Or(Bx),Or(Ux),Or(zx),Or(Kx),Or(_x),Or(Xx),Or(Qx),Or(av),Or(ov),Or(uv),Or(cv),Or(q_),Or(hv),Or(mv),Or(rv),Or(bv),Or(_v),Or(Iv),Or(Sv),Or(jx),Or(Nv),Or(Rv),Or(Mv),Or(Fv),Or(Ov);var Dv={filename:""};function Lv(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(1===e.length){var n=e[0];if(m(n))return Pv(n,null);if(g(n)&&Object.getPrototypeOf(n)===Object.prototype){var r=Object.keys(n);return Pv(r.map((function(e){return n[e]})),r)}}if("function"==typeof e[e.length-1]){var a=e.pop();return Pv(e=1===e.length&&m(e[0])?e[0]:e,null).pipe(K((function(e){return a.apply(void 0,e)})))}return Pv(e,null)}function Pv(e,t){return new S((function(n){var r=e.length;if(0!==r)for(var a=new Array(r),s=0,o=0,i=function(i){var u=G(e[i]),l=!1;n.add(u.subscribe({next:function(e){l||(l=!0,o++),a[i]=e},error:function(e){return n.error(e)},complete:function(){++s!==r&&l||(o===r&&n.next(t?t.reduce((function(e,t,n){return e[t]=a[n],e}),{}):a),n.complete())}}))},u=0;u<r;u++)i(u);else n.complete()}))}var Bv="undefined"!=typeof window&&window,Uv="undefined"!=typeof self&&"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&self,zv=Bv||void 0!==_e&&_e||Uv;function Vv(e,t){return void 0===t&&(t=null),new Xv({method:"GET",url:e,headers:t})}function Wv(e,t,n){return new Xv({method:"POST",url:e,body:t,headers:n})}function Hv(e,t){return new Xv({method:"DELETE",url:e,headers:t})}function Gv(e,t,n){return new Xv({method:"PUT",url:e,body:t,headers:n})}function jv(e,t,n){return new Xv({method:"PATCH",url:e,body:t,headers:n})}var Kv=K((function(e,t){return e.response}));function qv(e,t){return Kv(new Xv({method:"GET",url:e,responseType:"json",headers:t}))}var Xv=function(e){function t(t){var n=e.call(this)||this,r={async:!0,createXHR:function(){return this.crossDomain?function(){if(zv.XMLHttpRequest)return new zv.XMLHttpRequest;if(zv.XDomainRequest)return new zv.XDomainRequest;throw new Error("CORS is not supported by your browser")}():function(){if(zv.XMLHttpRequest)return new zv.XMLHttpRequest;var e=void 0;try{for(var t=["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP.4.0"],n=0;n<3;n++)try{if(e=t[n],new zv.ActiveXObject(e))break}catch(e){}return new zv.ActiveXObject(e)}catch(e){throw new Error("XMLHttpRequest is not supported by your browser")}}()},crossDomain:!0,withCredentials:!1,headers:{},method:"GET",responseType:"json",timeout:0};if("string"==typeof t)r.url=t;else for(var a in t)t.hasOwnProperty(a)&&(r[a]=t[a]);return n.request=r,n}var n;return l(t,e),t.prototype._subscribe=function(e){return new Yv(e,this.request)},t.create=((n=function(e){return new t(e)}).get=Vv,n.post=Wv,n.delete=Hv,n.put=Gv,n.patch=jv,n.getJSON=qv,n),t}(S),Yv=function(e){function t(t,n){var r=e.call(this,t)||this;r.request=n,r.done=!1;var a=n.headers=n.headers||{};return n.crossDomain||r.getHeader(a,"X-Requested-With")||(a["X-Requested-With"]="XMLHttpRequest"),r.getHeader(a,"Content-Type")||zv.FormData&&n.body instanceof zv.FormData||void 0===n.body||(a["Content-Type"]="application/x-www-form-urlencoded; charset=UTF-8"),n.body=r.serializeBody(n.body,r.getHeader(n.headers,"Content-Type")),r.send(),r}return l(t,e),t.prototype.next=function(e){this.done=!0;var t,n=this,r=n.xhr,a=n.request,s=n.destination;try{t=new Qv(e,r,a)}catch(e){return s.error(e)}s.next(t)},t.prototype.send=function(){var e=this.request,t=this.request,n=t.user,r=t.method,a=t.url,s=t.async,o=t.password,i=t.headers,u=t.body;try{var l=this.xhr=e.createXHR();this.setupEvents(l,e),n?l.open(r,a,s,n,o):l.open(r,a,s),s&&(l.timeout=e.timeout,l.responseType=e.responseType),"withCredentials"in l&&(l.withCredentials=!!e.withCredentials),this.setHeaders(l,i),u?l.send(u):l.send()}catch(e){this.error(e)}},t.prototype.serializeBody=function(e,t){if(!e||"string"==typeof e)return e;if(zv.FormData&&e instanceof zv.FormData)return e;if(t){var n=t.indexOf(";");-1!==n&&(t=t.substring(0,n))}switch(t){case"application/x-www-form-urlencoded":return Object.keys(e).map((function(t){return encodeURIComponent(t)+"="+encodeURIComponent(e[t])})).join("&");case"application/json":return JSON.stringify(e);default:return e}},t.prototype.setHeaders=function(e,t){for(var n in t)t.hasOwnProperty(n)&&e.setRequestHeader(n,t[n])},t.prototype.getHeader=function(e,t){for(var n in e)if(n.toLowerCase()===t.toLowerCase())return e[n]},t.prototype.setupEvents=function(e,t){var n,r,a=t.progressSubscriber;function s(e){var t,n=s,r=n.subscriber,a=n.progressSubscriber,o=n.request;a&&a.error(e);try{t=new ew(this,o)}catch(e){t=e}r.error(t)}function o(e){}function i(e){var t=i,n=t.subscriber,r=t.progressSubscriber,a=t.request;if(4===this.readyState){var s=1223===this.status?204:this.status,o="text"===this.responseType?this.response||this.responseText:this.response;if(0===s&&(s=o?200:0),s<400)r&&r.complete(),n.next(e),n.complete();else{r&&r.error(e);var u=void 0;try{u=new Jv("ajax error "+s,this,a)}catch(e){u=e}n.error(u)}}}e.ontimeout=s,s.request=t,s.subscriber=this,s.progressSubscriber=a,e.upload&&"withCredentials"in e&&(a&&(n=function(e){n.progressSubscriber.next(e)},zv.XDomainRequest?e.onprogress=n:e.upload.onprogress=n,n.progressSubscriber=a),r=function(e){var t,n=r,a=n.progressSubscriber,s=n.subscriber,o=n.request;a&&a.error(e);try{t=new Jv("ajax error",this,o)}catch(e){t=e}s.error(t)},e.onerror=r,r.request=t,r.subscriber=this,r.progressSubscriber=a),e.onreadystatechange=o,o.subscriber=this,o.progressSubscriber=a,o.request=t,e.onload=i,i.subscriber=this,i.progressSubscriber=a,i.request=t},t.prototype.unsubscribe=function(){var t=this.done,n=this.xhr;!t&&n&&4!==n.readyState&&"function"==typeof n.abort&&n.abort(),e.prototype.unsubscribe.call(this)},t}(w),Qv=function(e,t,n){this.originalEvent=e,this.xhr=t,this.request=n,this.status=t.status,this.responseType=t.responseType||n.responseType,this.response=Zv(this.responseType,t)},Jv=function(){function e(e,t,n){return Error.call(this),this.message=e,this.name="AjaxError",this.xhr=t,this.request=n,this.status=t.status,this.responseType=t.responseType||n.responseType,this.response=Zv(this.responseType,t),this}return e.prototype=Object.create(Error.prototype),e}();function Zv(e,t){switch(e){case"json":return function(e){return"response"in e?e.responseType?e.response:JSON.parse(e.response||e.responseText||"null"):JSON.parse(e.responseText||"null")}(t);case"xml":return t.responseXML;default:return"response"in t?t.response:t.responseText}}var ew=function(e,t){return Jv.call(this,"ajax timeout",e,t),this.name="AjaxTimeoutError",this},tw=Xv.create,nw=Uint8Array,rw=Uint16Array,aw=Uint32Array,sw=new nw([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),ow=new nw([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),iw=new nw([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),uw=function(e,t){for(var n=new rw(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];var a=new aw(n[30]);for(r=1;r<30;++r)for(var s=n[r];s<n[r+1];++s)a[s]=s-n[r]<<5|r;return[n,a]},lw=uw(sw,2),cw=lw[0],pw=lw[1];cw[28]=258,pw[258]=28;for(var hw=uw(ow,0)[0],dw=new rw(32768),fw=0;fw<32768;++fw){var mw=(43690&fw)>>>1|(21845&fw)<<1;mw=(61680&(mw=(52428&mw)>>>2|(13107&mw)<<2))>>>4|(3855&mw)<<4,dw[fw]=((65280&mw)>>>8|(255&mw)<<8)>>>1}var gw=function(e,t,n){for(var r=e.length,a=0,s=new rw(t);a<r;++a)++s[e[a]-1];var o,i=new rw(t);for(a=0;a<t;++a)i[a]=i[a-1]+s[a-1]<<1;if(n){o=new rw(1<<t);var u=15-t;for(a=0;a<r;++a)if(e[a])for(var l=a<<4|e[a],c=t-e[a],p=i[e[a]-1]++<<c,h=p|(1<<c)-1;p<=h;++p)o[dw[p]>>>u]=l}else for(o=new rw(r),a=0;a<r;++a)e[a]&&(o[a]=dw[i[e[a]-1]++]>>>15-e[a]);return o},yw=new nw(288);for(fw=0;fw<144;++fw)yw[fw]=8;for(fw=144;fw<256;++fw)yw[fw]=9;for(fw=256;fw<280;++fw)yw[fw]=7;for(fw=280;fw<288;++fw)yw[fw]=8;var bw=new nw(32);for(fw=0;fw<32;++fw)bw[fw]=5;var _w=gw(yw,9,1),xw=gw(bw,5,1),vw=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},ww=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(7&t)&n},Tw=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},kw=function(e,t,n){(null==t||t<0)&&(t=0),(null==n||n>e.length)&&(n=e.length);var r=new(e instanceof rw?rw:e instanceof aw?aw:nw)(n-t);return r.set(e.subarray(t,n)),r},Iw=new nw(0),Sw=function(e,t){return e[t]|e[t+1]<<8},Ew=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},Nw=function(e,t){return Ew(e,t)+4294967296*Ew(e,t+4)};function Cw(e,t){return function(e,t,n){var r=e.length;if(!r||n&&!n.l&&r<5)return t||new nw(0);var a=!t||n,s=!n||n.i;n||(n={}),t||(t=new nw(3*r));var o,i=function(e){var n=t.length;if(e>n){var r=new nw(Math.max(2*n,e));r.set(t),t=r}},u=n.f||0,l=n.p||0,c=n.b||0,p=n.l,h=n.d,d=n.m,f=n.n,m=8*r;do{if(!p){n.f=u=ww(e,l,1);var g=ww(e,l+1,3);if(l+=3,!g){var y=e[(N=((o=l)/8|0)+(7&o&&1)+4)-4]|e[N-3]<<8,b=N+y;if(b>r){if(s)throw"unexpected EOF";break}a&&i(c+y),t.set(e.subarray(N,b),c),n.b=c+=y,n.p=l=8*b;continue}if(1==g)p=_w,h=xw,d=9,f=5;else{if(2!=g)throw"invalid block type";var _=ww(e,l,31)+257,x=ww(e,l+10,15)+4,v=_+ww(e,l+5,31)+1;l+=14;for(var w=new nw(v),T=new nw(19),k=0;k<x;++k)T[iw[k]]=ww(e,l+3*k,7);l+=3*x;var I=vw(T),S=(1<<I)-1,E=gw(T,I,1);for(k=0;k<v;){var N,C=E[ww(e,l,S)];if(l+=15&C,(N=C>>>4)<16)w[k++]=N;else{var A=0,R=0;for(16==N?(R=3+ww(e,l,3),l+=2,A=w[k-1]):17==N?(R=3+ww(e,l,7),l+=3):18==N&&(R=11+ww(e,l,127),l+=7);R--;)w[k++]=A}}var $=w.subarray(0,_),M=w.subarray(_);d=vw($),f=vw(M),p=gw($,d,1),h=gw(M,f,1)}if(l>m){if(s)throw"unexpected EOF";break}}a&&i(c+131072);for(var F=(1<<d)-1,O=(1<<f)-1,D=l;;D=l){var L=(A=p[Tw(e,l)&F])>>>4;if((l+=15&A)>m){if(s)throw"unexpected EOF";break}if(!A)throw"invalid length/literal";if(L<256)t[c++]=L;else{if(256==L){D=l,p=null;break}var P=L-254;if(L>264){var B=sw[k=L-257];P=ww(e,l,(1<<B)-1)+cw[k],l+=B}var U=h[Tw(e,l)&O],z=U>>>4;if(!U)throw"invalid distance";if(l+=15&U,M=hw[z],z>3&&(B=ow[z],M+=Tw(e,l)&(1<<B)-1,l+=B),l>m){if(s)throw"unexpected EOF";break}a&&i(c+131072);for(var V=c+P;c<V;c+=4)t[c]=t[c-M],t[c+1]=t[c+1-M],t[c+2]=t[c+2-M],t[c+3]=t[c+3-M];c=V}}n.l=p,n.p=D,n.b=c,p&&(u=1,n.m=d,n.d=h,n.n=f)}while(!u);return c==t.length?t:kw(t,0,c)}(e,t)}var Aw="undefined"!=typeof TextDecoder&&new TextDecoder;try{Aw.decode(Iw,{stream:!0})}catch(e){}function Rw(e,t){if(t){for(var n="",r=0;r<e.length;r+=16384)n+=String.fromCharCode.apply(null,e.subarray(r,r+16384));return n}if(Aw)return Aw.decode(e);var a=function(e){for(var t="",n=0;;){var r=e[n++],a=(r>127)+(r>223)+(r>239);if(n+a>e.length)return[t,kw(e,n-1)];a?3==a?(r=((15&r)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t+=String.fromCharCode(55296|r>>10,56320|1023&r)):t+=1&a?String.fromCharCode((31&r)<<6|63&e[n++]):String.fromCharCode((15&r)<<12|(63&e[n++])<<6|63&e[n++]):t+=String.fromCharCode(r)}}(e),s=a[0];if(a[1].length)throw"invalid utf-8 data";return s}var $w=function(e,t){return t+30+Sw(e,t+26)+Sw(e,t+28)},Mw=function(e,t,n){var r=Sw(e,t+28),a=Rw(e.subarray(t+46,t+46+r),!(2048&Sw(e,t+8))),s=t+46+r,o=Ew(e,t+20),i=n&&4294967295==o?Fw(e,s):[o,Ew(e,t+24),Ew(e,t+42)],u=i[0],l=i[1],c=i[2];return[Sw(e,t+10),u,l,a,s+Sw(e,t+30)+Sw(e,t+32),c]},Fw=function(e,t){for(;1!=Sw(e,t);t+=4+Sw(e,t+2));return[Nw(e,t+12),Nw(e,t+4),Nw(e,t+20)]};function Ow(e){for(var t={},n=e.length-22;101010256!=Ew(e,n);--n)if(!n||e.length-n>65558)throw"invalid zip file";var r=Sw(e,n+8);if(!r)return{};var a=Ew(e,n+16),s=4294967295==a;if(s){if(n=Ew(e,n-12),101075792!=Ew(e,n))throw"invalid zip file";r=Ew(e,n+32),a=Ew(e,n+48)}for(var o=0;o<r;++o){var i=Mw(e,a,s),u=i[0],l=i[1],c=i[2],p=i[3],h=i[4],d=i[5],f=$w(e,d);if(a=h,u){if(8!=u)throw"unknown compression type "+u;t[p]=Cw(e.subarray(f,f+l),new nw(c))}else t[p]=kw(e,f,f+l)}return t}function Dw(e){if(e)for(var t=0;t<e.length;t++)e[t]=~e[t];return e}var Lw=function(){function e(e,t){this.jsonModel=e,this.weights=t}return e.prototype.load=function(){return a(this,void 0,void 0,(function(){var e,t,n,r;return s(this,(function(a){switch(a.label){case 0:return e={modelTopology:this.jsonModel.modelTopology,format:this.jsonModel.format,generatedBy:this.jsonModel.generatedBy,convertedBy:this.jsonModel.convertedBy},null==this.jsonModel.weightsManifest?[3,2]:[4,this.loadWeights()];case 1:t=a.sent(),n=t[0],r=t[1],e.weightSpecs=n,e.weightData=r,a.label=2;case 2:return null!=this.jsonModel.trainingConfig&&(e.trainingConfig=this.jsonModel.trainingConfig),null!=this.jsonModel.userDefinedMetadata&&(e.userDefinedMetadata=this.jsonModel.userDefinedMetadata),[2,e]}}))}))},e.prototype.loadWeights=function(){return a(this,void 0,void 0,(function(){var e,t,n,r,a,o,i,u;return s(this,(function(s){for(e=[],t=[],n=0,r=this.jsonModel.weightsManifest;n<r.length;n++){for(a=r[n],o=0,i=a.paths;o<i.length;o++){if(u=i[o],!this.weights[u])throw new Error("Error loading weights: cannot find ".concat(u));e.push(this.weights[u])}t.push.apply(t,a.weights)}return[2,[t,this.toArrayBuffer(e)]]}))}))},e.prototype.toArrayBuffer=function(e){if(Array.isArray(e)){for(var t=0,n=0,r=e;n<r.length;n++)t+=r[n].length;for(var a=new ArrayBuffer(t),s=new Uint8Array(a),o=0,i=0,u=e;i<u.length;i++)o+=u[i].copy(s,o);return a}return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)},e}(),Pw=[],Bw=[],Uw="undefined"!=typeof Uint8Array?Uint8Array:Array,zw=!1;function Vw(){zw=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0,n=e.length;t<n;++t)Pw[t]=e[t],Bw[e.charCodeAt(t)]=t;Bw["-".charCodeAt(0)]=62,Bw["_".charCodeAt(0)]=63}function Ww(e,t,n){for(var r,a,s=[],o=t;o<n;o+=3)r=(e[o]<<16)+(e[o+1]<<8)+e[o+2],s.push(Pw[(a=r)>>18&63]+Pw[a>>12&63]+Pw[a>>6&63]+Pw[63&a]);return s.join("")}function Hw(e){var t;zw||Vw();for(var n=e.length,r=n%3,a="",s=[],o=16383,i=0,u=n-r;i<u;i+=o)s.push(Ww(e,i,i+o>u?u:i+o));return 1===r?(t=e[n-1],a+=Pw[t>>2],a+=Pw[t<<4&63],a+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],a+=Pw[t>>10],a+=Pw[t>>4&63],a+=Pw[t<<2&63],a+="="),s.push(a),s.join("")}function Gw(e,t,n,r,a){var s,o,i=8*a-r-1,u=(1<<i)-1,l=u>>1,c=-7,p=n?a-1:0,h=n?-1:1,d=e[t+p];for(p+=h,s=d&(1<<-c)-1,d>>=-c,c+=i;c>0;s=256*s+e[t+p],p+=h,c-=8);for(o=s&(1<<-c)-1,s>>=-c,c+=r;c>0;o=256*o+e[t+p],p+=h,c-=8);if(0===s)s=1-l;else{if(s===u)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,r),s-=l}return(d?-1:1)*o*Math.pow(2,s-r)}function jw(e,t,n,r,a,s){var o,i,u,l=8*s-a-1,c=(1<<l)-1,p=c>>1,h=23===a?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:s-1,f=r?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,o=c):(o=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-o))<1&&(o--,u*=2),(t+=o+p>=1?h/u:h*Math.pow(2,1-p))*u>=2&&(o++,u/=2),o+p>=c?(i=0,o=c):o+p>=1?(i=(t*u-1)*Math.pow(2,a),o+=p):(i=t*Math.pow(2,p-1)*Math.pow(2,a),o=0));a>=8;e[n+d]=255&i,d+=f,i/=256,a-=8);for(o=o<<a|i,l+=a;l>0;e[n+d]=255&o,d+=f,o/=256,l-=8);e[n+d-f]|=128*m}var Kw={}.toString,qw=Array.isArray||function(e){return"[object Array]"==Kw.call(e)};function Xw(){return Qw.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function Yw(e,t){if(Xw()<t)throw new RangeError("Invalid typed array length");return Qw.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=Qw.prototype:(null===e&&(e=new Qw(t)),e.length=t),e}function Qw(e,t,n){if(!(Qw.TYPED_ARRAY_SUPPORT||this instanceof Qw))return new Qw(e,t,n);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return eT(this,e)}return Jw(this,e,t,n)}function Jw(e,t,n,r){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?function(e,t,n,r){if(t.byteLength,n<0||t.byteLength<n)throw new RangeError("'offset' is out of bounds");if(t.byteLength<n+(r||0))throw new RangeError("'length' is out of bounds");return t=void 0===n&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,n):new Uint8Array(t,n,r),Qw.TYPED_ARRAY_SUPPORT?(e=t).__proto__=Qw.prototype:e=tT(e,t),e}(e,t,n,r):"string"==typeof t?function(e,t,n){if("string"==typeof n&&""!==n||(n="utf8"),!Qw.isEncoding(n))throw new TypeError('"encoding" must be a valid string encoding');var r=0|aT(t,n),a=(e=Yw(e,r)).write(t,n);return a!==r&&(e=e.slice(0,a)),e}(e,t,n):function(e,t){if(rT(t)){var n=0|nT(t.length);return 0===(e=Yw(e,n)).length||t.copy(e,0,0,n),e}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||(r=t.length)!=r?Yw(e,0):tT(e,t);if("Buffer"===t.type&&qw(t.data))return tT(e,t.data)}var r;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function Zw(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function eT(e,t){if(Zw(t),e=Yw(e,t<0?0:0|nT(t)),!Qw.TYPED_ARRAY_SUPPORT)for(var n=0;n<t;++n)e[n]=0;return e}function tT(e,t){var n=t.length<0?0:0|nT(t.length);e=Yw(e,n);for(var r=0;r<n;r+=1)e[r]=255&t[r];return e}function nT(e){if(e>=Xw())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Xw().toString(16)+" bytes");return 0|e}function rT(e){return!(null==e||!e._isBuffer)}function aT(e,t){if(rT(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return RT(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return $T(e).length;default:if(r)return RT(e).length;t=(""+t).toLowerCase(),r=!0}}function sT(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return xT(this,t,n);case"utf8":case"utf-8":return gT(this,t,n);case"ascii":return bT(this,t,n);case"latin1":case"binary":return _T(this,t,n);case"base64":return mT(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return vT(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function oT(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function iT(e,t,n,r,a){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)return-1;n=0}if("string"==typeof t&&(t=Qw.from(t,r)),rT(t))return 0===t.length?-1:uT(e,t,n,r,a);if("number"==typeof t)return t&=255,Qw.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):uT(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function uT(e,t,n,r,a){var s,o=1,i=e.length,u=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,i/=2,u/=2,n/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(a){var c=-1;for(s=n;s<i;s++)if(l(e,s)===l(t,-1===c?0:s-c)){if(-1===c&&(c=s),s-c+1===u)return c*o}else-1!==c&&(s-=s-c),c=-1}else for(n+u>i&&(n=i-u),s=n;s>=0;s--){for(var p=!0,h=0;h<u;h++)if(l(e,s+h)!==l(t,h)){p=!1;break}if(p)return s}return-1}function lT(e,t,n,r){n=Number(n)||0;var a=e.length-n;r?(r=Number(r))>a&&(r=a):r=a;var s=t.length;if(s%2!=0)throw new TypeError("Invalid hex string");r>s/2&&(r=s/2);for(var o=0;o<r;++o){var i=parseInt(t.substr(2*o,2),16);if(isNaN(i))return o;e[n+o]=i}return o}function cT(e,t,n,r){return MT(RT(t,e.length-n),e,n,r)}function pT(e,t,n,r){return MT(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function hT(e,t,n,r){return pT(e,t,n,r)}function dT(e,t,n,r){return MT($T(t),e,n,r)}function fT(e,t,n,r){return MT(function(e,t){for(var n,r,a,s=[],o=0;o<e.length&&!((t-=2)<0);++o)r=(n=e.charCodeAt(o))>>8,a=n%256,s.push(a),s.push(r);return s}(t,e.length-n),e,n,r)}function mT(e,t,n){return 0===t&&n===e.length?Hw(e):Hw(e.slice(t,n))}function gT(e,t,n){n=Math.min(e.length,n);for(var r=[],a=t;a<n;){var s,o,i,u,l=e[a],c=null,p=l>239?4:l>223?3:l>191?2:1;if(a+p<=n)switch(p){case 1:l<128&&(c=l);break;case 2:128==(192&(s=e[a+1]))&&(u=(31&l)<<6|63&s)>127&&(c=u);break;case 3:s=e[a+1],o=e[a+2],128==(192&s)&&128==(192&o)&&(u=(15&l)<<12|(63&s)<<6|63&o)>2047&&(u<55296||u>57343)&&(c=u);break;case 4:s=e[a+1],o=e[a+2],i=e[a+3],128==(192&s)&&128==(192&o)&&128==(192&i)&&(u=(15&l)<<18|(63&s)<<12|(63&o)<<6|63&i)>65535&&u<1114112&&(c=u)}null===c?(c=65533,p=1):c>65535&&(c-=65536,r.push(c>>>10&1023|55296),c=56320|1023&c),r.push(c),a+=p}return function(e){var t=e.length;if(t<=yT)return String.fromCharCode.apply(String,e);for(var n="",r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=yT));return n}(r)}Qw.TYPED_ARRAY_SUPPORT=void 0===_e.TYPED_ARRAY_SUPPORT||_e.TYPED_ARRAY_SUPPORT,Xw(),Qw.poolSize=8192,Qw._augment=function(e){return e.__proto__=Qw.prototype,e},Qw.from=function(e,t,n){return Jw(null,e,t,n)},Qw.TYPED_ARRAY_SUPPORT&&(Qw.prototype.__proto__=Uint8Array.prototype,Qw.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Qw[Symbol.species]),Qw.alloc=function(e,t,n){return function(e,t,n,r){return Zw(t),t<=0?Yw(e,t):void 0!==n?"string"==typeof r?Yw(e,t).fill(n,r):Yw(e,t).fill(n):Yw(e,t)}(null,e,t,n)},Qw.allocUnsafe=function(e){return eT(null,e)},Qw.allocUnsafeSlow=function(e){return eT(null,e)},Qw.isBuffer=function(e){return null!=e&&(!!e._isBuffer||FT(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&FT(e.slice(0,0))}(e))},Qw.compare=function(e,t){if(!rT(e)||!rT(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,a=0,s=Math.min(n,r);a<s;++a)if(e[a]!==t[a]){n=e[a],r=t[a];break}return n<r?-1:r<n?1:0},Qw.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},Qw.concat=function(e,t){if(!qw(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return Qw.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=Qw.allocUnsafe(t),a=0;for(n=0;n<e.length;++n){var s=e[n];if(!rT(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(r,a),a+=s.length}return r},Qw.byteLength=aT,Qw.prototype._isBuffer=!0,Qw.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)oT(this,t,t+1);return this},Qw.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)oT(this,t,t+3),oT(this,t+1,t+2);return this},Qw.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)oT(this,t,t+7),oT(this,t+1,t+6),oT(this,t+2,t+5),oT(this,t+3,t+4);return this},Qw.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?gT(this,0,e):sT.apply(this,arguments)},Qw.prototype.equals=function(e){if(!rT(e))throw new TypeError("Argument must be a Buffer");return this===e||0===Qw.compare(this,e)},Qw.prototype.inspect=function(){var e="";return this.length>0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),"<Buffer "+e+">"},Qw.prototype.compare=function(e,t,n,r,a){if(!rT(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;for(var s=(a>>>=0)-(r>>>=0),o=(n>>>=0)-(t>>>=0),i=Math.min(s,o),u=this.slice(r,a),l=e.slice(t,n),c=0;c<i;++c)if(u[c]!==l[c]){s=u[c],o=l[c];break}return s<o?-1:o<s?1:0},Qw.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},Qw.prototype.indexOf=function(e,t,n){return iT(this,e,t,n,!0)},Qw.prototype.lastIndexOf=function(e,t,n){return iT(this,e,t,n,!1)},Qw.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(n)?(n|=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var a=this.length-t;if((void 0===n||n>a)&&(n=a),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var s=!1;;)switch(r){case"hex":return lT(this,e,t,n);case"utf8":case"utf-8":return cT(this,e,t,n);case"ascii":return pT(this,e,t,n);case"latin1":case"binary":return hT(this,e,t,n);case"base64":return dT(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return fT(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},Qw.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var yT=4096;function bT(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(127&e[a]);return r}function _T(e,t,n){var r="";n=Math.min(e.length,n);for(var a=t;a<n;++a)r+=String.fromCharCode(e[a]);return r}function xT(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var a="",s=t;s<n;++s)a+=AT(e[s]);return a}function vT(e,t,n){for(var r=e.slice(t,n),a="",s=0;s<r.length;s+=2)a+=String.fromCharCode(r[s]+256*r[s+1]);return a}function wT(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function TT(e,t,n,r,a,s){if(!rT(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||t<s)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function kT(e,t,n,r){t<0&&(t=65535+t+1);for(var a=0,s=Math.min(e.length-n,2);a<s;++a)e[n+a]=(t&255<<8*(r?a:1-a))>>>8*(r?a:1-a)}function IT(e,t,n,r){t<0&&(t=4294967295+t+1);for(var a=0,s=Math.min(e.length-n,4);a<s;++a)e[n+a]=t>>>8*(r?a:3-a)&255}function ST(e,t,n,r,a,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function ET(e,t,n,r,a){return a||ST(e,0,n,4),jw(e,t,n,r,23,4),n+4}function NT(e,t,n,r,a){return a||ST(e,0,n,8),jw(e,t,n,r,52,8),n+8}Qw.prototype.slice=function(e,t){var n,r=this.length;if((e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e),Qw.TYPED_ARRAY_SUPPORT)(n=this.subarray(e,t)).__proto__=Qw.prototype;else{var a=t-e;n=new Qw(a,void 0);for(var s=0;s<a;++s)n[s]=this[s+e]}return n},Qw.prototype.readUIntLE=function(e,t,n){e|=0,t|=0,n||wT(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r},Qw.prototype.readUIntBE=function(e,t,n){e|=0,t|=0,n||wT(e,t,this.length);for(var r=this[e+--t],a=1;t>0&&(a*=256);)r+=this[e+--t]*a;return r},Qw.prototype.readUInt8=function(e,t){return t||wT(e,1,this.length),this[e]},Qw.prototype.readUInt16LE=function(e,t){return t||wT(e,2,this.length),this[e]|this[e+1]<<8},Qw.prototype.readUInt16BE=function(e,t){return t||wT(e,2,this.length),this[e]<<8|this[e+1]},Qw.prototype.readUInt32LE=function(e,t){return t||wT(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},Qw.prototype.readUInt32BE=function(e,t){return t||wT(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},Qw.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||wT(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r>=(a*=128)&&(r-=Math.pow(2,8*t)),r},Qw.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||wT(e,t,this.length);for(var r=t,a=1,s=this[e+--r];r>0&&(a*=256);)s+=this[e+--r]*a;return s>=(a*=128)&&(s-=Math.pow(2,8*t)),s},Qw.prototype.readInt8=function(e,t){return t||wT(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},Qw.prototype.readInt16LE=function(e,t){t||wT(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},Qw.prototype.readInt16BE=function(e,t){t||wT(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},Qw.prototype.readInt32LE=function(e,t){return t||wT(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},Qw.prototype.readInt32BE=function(e,t){return t||wT(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},Qw.prototype.readFloatLE=function(e,t){return t||wT(e,4,this.length),Gw(this,e,!0,23,4)},Qw.prototype.readFloatBE=function(e,t){return t||wT(e,4,this.length),Gw(this,e,!1,23,4)},Qw.prototype.readDoubleLE=function(e,t){return t||wT(e,8,this.length),Gw(this,e,!0,52,8)},Qw.prototype.readDoubleBE=function(e,t){return t||wT(e,8,this.length),Gw(this,e,!1,52,8)},Qw.prototype.writeUIntLE=function(e,t,n,r){e=+e,t|=0,n|=0,r||TT(this,e,t,n,Math.pow(2,8*n)-1,0);var a=1,s=0;for(this[t]=255&e;++s<n&&(a*=256);)this[t+s]=e/a&255;return t+n},Qw.prototype.writeUIntBE=function(e,t,n,r){e=+e,t|=0,n|=0,r||TT(this,e,t,n,Math.pow(2,8*n)-1,0);var a=n-1,s=1;for(this[t+a]=255&e;--a>=0&&(s*=256);)this[t+a]=e/s&255;return t+n},Qw.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||TT(this,e,t,1,255,0),Qw.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},Qw.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||TT(this,e,t,2,65535,0),Qw.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):kT(this,e,t,!0),t+2},Qw.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||TT(this,e,t,2,65535,0),Qw.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):kT(this,e,t,!1),t+2},Qw.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||TT(this,e,t,4,4294967295,0),Qw.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):IT(this,e,t,!0),t+4},Qw.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||TT(this,e,t,4,4294967295,0),Qw.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):IT(this,e,t,!1),t+4},Qw.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);TT(this,e,t,n,a-1,-a)}var s=0,o=1,i=0;for(this[t]=255&e;++s<n&&(o*=256);)e<0&&0===i&&0!==this[t+s-1]&&(i=1),this[t+s]=(e/o>>0)-i&255;return t+n},Qw.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);TT(this,e,t,n,a-1,-a)}var s=n-1,o=1,i=0;for(this[t+s]=255&e;--s>=0&&(o*=256);)e<0&&0===i&&0!==this[t+s+1]&&(i=1),this[t+s]=(e/o>>0)-i&255;return t+n},Qw.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||TT(this,e,t,1,127,-128),Qw.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},Qw.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||TT(this,e,t,2,32767,-32768),Qw.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):kT(this,e,t,!0),t+2},Qw.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||TT(this,e,t,2,32767,-32768),Qw.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):kT(this,e,t,!1),t+2},Qw.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||TT(this,e,t,4,2147483647,-2147483648),Qw.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):IT(this,e,t,!0),t+4},Qw.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||TT(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),Qw.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):IT(this,e,t,!1),t+4},Qw.prototype.writeFloatLE=function(e,t,n){return ET(this,e,t,!0,n)},Qw.prototype.writeFloatBE=function(e,t,n){return ET(this,e,t,!1,n)},Qw.prototype.writeDoubleLE=function(e,t,n){return NT(this,e,t,!0,n)},Qw.prototype.writeDoubleBE=function(e,t,n){return NT(this,e,t,!1,n)},Qw.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var a,s=r-n;if(this===e&&n<t&&t<r)for(a=s-1;a>=0;--a)e[a+t]=this[a+n];else if(s<1e3||!Qw.TYPED_ARRAY_SUPPORT)for(a=0;a<s;++a)e[a+t]=this[a+n];else Uint8Array.prototype.set.call(e,this.subarray(n,n+s),t);return s},Qw.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),1===e.length){var a=e.charCodeAt(0);a<256&&(e=a)}if(void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!Qw.isEncoding(r))throw new TypeError("Unknown encoding: "+r)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;var s;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(s=t;s<n;++s)this[s]=e;else{var o=rT(e)?e:RT(new Qw(e,r).toString()),i=o.length;for(s=0;s<n-t;++s)this[s+t]=o[s%i]}return this};var CT=/[^+\/0-9A-Za-z-_]/g;function AT(e){return e<16?"0"+e.toString(16):e.toString(16)}function RT(e,t){var n;t=t||1/0;for(var r=e.length,a=null,s=[],o=0;o<r;++o){if((n=e.charCodeAt(o))>55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&s.push(239,191,189);if(a=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function $T(e){return function(e){var t,n,r,a,s,o;zw||Vw();var i=e.length;if(i%4>0)throw new Error("Invalid string. Length must be a multiple of 4");s="="===e[i-2]?2:"="===e[i-1]?1:0,o=new Uw(3*i/4-s),r=s>0?i-4:i;var u=0;for(t=0,n=0;t<r;t+=4,n+=3)a=Bw[e.charCodeAt(t)]<<18|Bw[e.charCodeAt(t+1)]<<12|Bw[e.charCodeAt(t+2)]<<6|Bw[e.charCodeAt(t+3)],o[u++]=a>>16&255,o[u++]=a>>8&255,o[u++]=255&a;return 2===s?(a=Bw[e.charCodeAt(t)]<<2|Bw[e.charCodeAt(t+1)]>>4,o[u++]=255&a):1===s&&(a=Bw[e.charCodeAt(t)]<<10|Bw[e.charCodeAt(t+1)]<<4|Bw[e.charCodeAt(t+2)]>>2,o[u++]=a>>8&255,o[u++]=255&a),o}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(CT,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function MT(e,t,n,r){for(var a=0;a<r&&!(a+n>=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function FT(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function OT(e,t){var n=new ie(0),r=new ie(0),a=new ie(0),s=new ie(0),o=V([n,r,a,s]).pipe(K((function(e){return e.reduce((function(t,n){return t+n/e.length}),0)})));if("string"==typeof e){var i=function(e,t){return tw({url:e,method:"GET",responseType:"arraybuffer",async:!0,progressSubscriber:new w((function(e){return t.next(e.loaded/e.total)}),(function(e){}),(function(){return t.next(1)}))}).pipe(ue(2))}(e,n).pipe(pe((function(e){return DT(e.response)})),pe((function(e){return LT(e,t,r).pipe(K((function(t){return{jszip:e,config:t}})))})),pe((function(e){var t=e.jszip,n=e.config;return PT(t,n,a).pipe(K((function(e){return{jszip:t,config:n,jsonModel:e}})))})),pe((function(e){var t=e.jszip,n=e.config,r=e.jsonModel;return BT(t,r,s).pipe(K((function(e){return{config:n,jsonModel:r,weights:e}})))})),pe((function(e){var t=e.config,n=e.jsonModel,r=e.weights;return G(im(new Lw(n,r))).pipe(K((function(e){return{config:t,graphModel:e}})))})));return{model$:i,progress$:o}}return i=DT(e).pipe(pe((function(e){return LT(e,t,r).pipe(K((function(t){return{jszip:e,config:t}})))})),pe((function(e){var t=e.jszip,n=e.config;return PT(t,n,a).pipe(K((function(e){return{jszip:t,config:n,jsonModel:e}})))})),pe((function(e){var t=e.jszip,n=e.config,r=e.jsonModel;return BT(t,r,s).pipe(K((function(e){return{config:n,jsonModel:r,weights:e}})))})),pe((function(e){var t=e.config,n=e.jsonModel,r=e.weights;return G(im(new Lw(n,r))).pipe(K((function(e){return{config:t,graphModel:e}})))}))),{model$:i,progress$:o}}function DT(e){return j(Ow(new Uint8Array(e)))}function LT(e,t,n){return e[t]||(t=t.substring(0,t.lastIndexOf("."))+".json",e[t])?be((function(){return n.next(1),t.includes(".bin")?j(JSON.parse(Rw(Dw(e[t])))):j(JSON.parse(Rw(e[t])))})):Q("Unable to retrieve model config: ".concat(t," is missing"))}function PT(e,t,n){return t?e[t.filename]?be((function(){return n.next(1),j(JSON.parse(Rw(Dw(e[t.filename]))))})):Q("Error extracting model: ".concat(t.filename," is missing")):Q("Invalid model config")}function BT(e,t,n){if(!t)return Q("Unable to extract weights: model is undefined");if(!t.weightsManifest)return n.next(1),j({});for(var r=0,a=0,s=t.weightsManifest;a<s.length;a++){var o=s[a];r+=o.paths.length}for(var i=new Array(r).fill(0),u={},l=0,c=0,p=t.weightsManifest;c<p.length;c++)for(var h=function(t){if(!e[t])return{value:Q("Error extracting weight: ".concat(t," is missing"))};u[t]=be((function(){var a=e[t];return i[l]=1,n.next(i.reduce((function(e,t){return e+t}),0)/r),j(Dw(Qw.from(a,a.byteOffset,a.byteLength)))})),l++},d=0,f=(o=p[c]).paths;d<f.length;d++){var m=h(f[d]);if("object"==typeof m)return m.value}return Lv(u)}Rt.set("DEPRECATION_WARNINGS_ENABLED",!1),Rt.global.Math=Math,Rt.global.Float32Array=Float32Array,Ct().set("WEBGL_FORCE_F16_TEXTURES",!0);var UT,zT,VT,WT=function(){function e(){this._initialized=!1}return e.prototype.getWidth=function(){return this._modelConfig?this._modelConfig.inWidth:0},e.prototype.getHeight=function(){return this._modelConfig?this._modelConfig.inHeight:0},e.prototype.isInitialized=function(){return this._initialized},e.prototype.getOutput=function(){return this._cnnOutputData},e.prototype.initialize=function(e,n,r){return a(this,void 0,void 0,(function(){var a,o,i,u,l=this;return s(this,(function(s){switch(s.label){case 0:if(null==e)throw"Invalid parameter";return this.release(),this._videoManager=e,this._config=n?t(t({},Dv),n):Dv,a=OT(this._config.filename,"config.json"),o=a.model$,i=a.progress$,u=i.pipe(K((function(e){return r&&r(e)}))).subscribe(),[4,o.pipe(K((function(e){var t=e.config,n=e.graphModel;l._modelConfig=t,l._model=n;var r=Tc([1,l._modelConfig.inHeight,l._modelConfig.inWidth,l._modelConfig.inChannels]),a=l._model.predict(r,{batchSize:1,verbose:!0});Array.isArray(a)?a.forEach((function(e){e.dispose()})):a.dispose(),l._cnnOutput=Tc([1,l._modelConfig.inHeight,l._modelConfig.inWidth,1]),r.dispose(),l._initialized=!0})),Z((function(){return u.unsubscribe()}))).toPromise()];case 1:return s.sent(),[2]}}))}))},e.prototype.processSync=function(){var e;if(this._initialized){var t=this._videoManager.getLastBuffer();if(null!=t){var n,r=$i(t),a=od.resizeBilinear(r,[this._modelConfig.inHeight,this._modelConfig.inWidth]),s=fi(a,"float32"),o=Cu(s,[1,this._modelConfig.inHeight,this._modelConfig.inWidth,3]),i=Ol(255);if(4==this._modelConfig.inChannels){var u=Cu(this._cnnOutput,[1,this._modelConfig.inHeight,this._modelConfig.inWidth,1]),l=tu(o,i);n=Mu([l,u],3),l.dispose(),u.dispose()}else n=tu(o,i);var c,p=this._model.predict(n);c=Array.isArray(p)?p[2]:p,null===(e=this._cnnOutput)||void 0===e||e.dispose();var h=c.shape;if(h&&h[3]>1){var d=$p(c);this._cnnOutput=Ou(d,[0,0,0,1],[-1,-1,-1,1]),d.dispose(),this._cnnOutputData=this._cnnOutput.dataSync()}else this._cnnOutput=Xu(c,0,1),this._cnnOutputData=this._cnnOutput.dataSync();Array.isArray(p)?p.forEach((function(e){e.dispose()})):p.dispose(),r.dispose(),a.dispose(),s.dispose(),o.dispose(),i.dispose(),n.dispose()}else console.error("No video frame to process")}else console.error("Foot must be initialized to track")},e.prototype.release=function(){var e,t;null===(e=this._cnnOutput)||void 0===e||e.dispose(),null===(t=this._model)||void 0===t||t.dispose(),this._initialized=!1},e}(),HT=(UT="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0,function(e){var t,n,r;e=e||{},t||(t=void 0!==e?e:{}),t.ready=new Promise((function(e,t){n=e,r=t}));var a=Object.assign({},t),s="./this.program",o="";"undefined"!=typeof document&&document.currentScript&&(o=document.currentScript.src),UT&&(o=UT),o=0!==o.indexOf("blob:")?o.substr(0,o.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var i,u=t.print||console.log.bind(console),l=t.printErr||console.warn.bind(console);Object.assign(t,a),a=null,t.thisProgram&&(s=t.thisProgram),t.wasmBinary&&(i=t.wasmBinary),t.noExitRuntime,"object"!=typeof WebAssembly&&F("no native wasm support detected");var c,p,h,d,f,m,g,y,b,_=!1,x="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function v(e,t){for(var n=t+NaN,r=t;e[r]&&!(r>=n);)++r;if(16<r-t&&e.buffer&&x)return x.decode(e.subarray(t,r));for(n="";t<r;){var a=e[t++];if(128&a){var s=63&e[t++];if(192==(224&a))n+=String.fromCharCode((31&a)<<6|s);else{var o=63&e[t++];65536>(a=224==(240&a)?(15&a)<<12|s<<6|o:(7&a)<<18|s<<12|o<<6|63&e[t++])?n+=String.fromCharCode(a):(a-=65536,n+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else n+=String.fromCharCode(a)}return n}function w(e){return e?v(d,e):""}function T(e,t,n,r){if(!(0<r))return 0;var a=n;r=n+r-1;for(var s=0;s<e.length;++s){var o=e.charCodeAt(s);if(55296<=o&&57343>=o&&(o=65536+((1023&o)<<10)|1023&e.charCodeAt(++s)),127>=o){if(n>=r)break;t[n++]=o}else{if(2047>=o){if(n+1>=r)break;t[n++]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;t[n++]=224|o>>12}else{if(n+3>=r)break;t[n++]=240|o>>18,t[n++]=128|o>>12&63}t[n++]=128|o>>6&63}t[n++]=128|63&o}}return t[n]=0,n-a}function k(){var e=c.buffer;p=e,t.HEAP8=h=new Int8Array(e),t.HEAP16=f=new Int16Array(e),t.HEAP32=m=new Int32Array(e),t.HEAPU8=d=new Uint8Array(e),t.HEAPU16=new Uint16Array(e),t.HEAPU32=g=new Uint32Array(e),t.HEAPF32=y=new Float32Array(e),t.HEAPF64=b=new Float64Array(e)}var I=[],S=[],E=[];function N(){var e=t.preRun.shift();I.unshift(e)}var C,A,R,$=0,M=null;function F(e){throw t.onAbort&&t.onAbort(e),l(e="Aborted("+e+")"),_=!0,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),r(e),e}function O(){return C.startsWith("data:application/octet-stream;base64,")}if(C="libxzimgPoseEstimation.wasm",!O()){var D=C;C=t.locateFile?t.locateFile(D,o):o+D}function L(){var e=C;try{if(e==C&&i)return new Uint8Array(i);throw"both async and sync fetching of the wasm failed"}catch(e){F(e)}}function P(e){for(;0<e.length;)e.shift()(t)}function B(e){this.F=e-24,this.ta=function(e){g[this.F+4>>2]=e},this.oa=function(e){g[this.F+8>>2]=e},this.pa=function(){m[this.F>>2]=0},this.ma=function(){h[this.F+12>>0]=0},this.qa=function(){h[this.F+13>>0]=0},this.I=function(e,t){this.la(),this.ta(e),this.oa(t),this.pa(),this.ma(),this.qa()},this.la=function(){g[this.F+16>>2]=0}}var U=(e,t)=>{for(var n=0,r=e.length-1;0<=r;r--){var a=e[r];"."===a?e.splice(r,1):".."===a?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n;n--)e.unshift("..");return e},z=e=>{var t="/"===e.charAt(0),n="/"===e.substr(-1);return(e=U(e.split("/").filter((e=>!!e)),!t).join("/"))||t||(e="."),e&&n&&(e+="/"),(t?"/":"")+e},V=e=>{var t=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1);return e=t[0],t=t[1],e||t?(t&&(t=t.substr(0,t.length-1)),e+t):"."},W=e=>{if("/"===e)return"/";var t=(e=(e=z(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)};function H(){for(var e="",t=!1,n=arguments.length-1;-1<=n&&!t;n--){if("string"!=typeof(t=0<=n?arguments[n]:"/"))throw new TypeError("Arguments to path.resolve must be strings");if(!t)return"";e=t+"/"+e,t="/"===t.charAt(0)}return(t?"/":"")+(e=U(e.split("/").filter((e=>!!e)),!t).join("/"))||"."}function G(e,t){for(var n=0,r=0;r<e.length;++r){var a=e.charCodeAt(r);127>=a?n++:2047>=a?n+=2:55296<=a&&57343>=a?(n+=4,++r):n+=3}return e=T(e,n=Array(n+1),0,n.length),t&&(n.length=e),n}var j=[];function K(e,t){j[e]={input:[],m:[],J:t},ve(e,J)}var q,X,Y,Q,J={open:function(e){var t=j[e.node.P];if(!t)throw new ue(43);e.l=t,e.seekable=!1},close:function(e){e.l.J.M(e.l)},M:function(e){e.l.J.M(e.l)},read:function(e,t,n,r){if(!e.l||!e.l.J.ca)throw new ue(60);for(var a=0,s=0;s<r;s++){try{var o=e.l.J.ca(e.l)}catch(e){throw new ue(29)}if(void 0===o&&0===a)throw new ue(6);if(null==o)break;a++,t[n+s]=o}return a&&(e.node.timestamp=Date.now()),a},write:function(e,t,n,r){if(!e.l||!e.l.J.V)throw new ue(60);try{for(var a=0;a<r;a++)e.l.J.V(e.l,t[n+a])}catch(e){throw new ue(29)}return r&&(e.node.timestamp=Date.now()),a}},Z={ca:function(e){if(!e.input.length){var t=null;if("undefined"!=typeof window&&"function"==typeof window.prompt?null!==(t=window.prompt("Input: "))&&(t+="\n"):"function"==typeof readline&&null!==(t=readline())&&(t+="\n"),!t)return null;e.input=G(t,!0)}return e.input.shift()},V:function(e,t){null===t||10===t?(u(v(e.m,0)),e.m=[]):0!=t&&e.m.push(t)},M:function(e){e.m&&0<e.m.length&&(u(v(e.m,0)),e.m=[])}},ee={V:function(e,t){null===t||10===t?(l(v(e.m,0)),e.m=[]):0!=t&&e.m.push(t)},M:function(e){e.m&&0<e.m.length&&(l(v(e.m,0)),e.m=[])}},te={o:null,v:function(){return te.createNode(null,"/",16895,0)},createNode:function(e,t,n,r){if(24576==(61440&n)||4096==(61440&n))throw new ue(63);return te.o||(te.o={dir:{node:{B:te.h.B,s:te.h.s,K:te.h.K,N:te.h.N,ha:te.h.ha,ja:te.h.ja,ia:te.h.ia,ga:te.h.ga,R:te.h.R},stream:{D:te.i.D}},file:{node:{B:te.h.B,s:te.h.s},stream:{D:te.i.D,read:te.i.read,write:te.i.write,Y:te.i.Y,da:te.i.da,fa:te.i.fa}},link:{node:{B:te.h.B,s:te.h.s,L:te.h.L},stream:{}},Z:{node:{B:te.h.B,s:te.h.s},stream:xe}}),16384==(61440&(n=fe(e,t,n,r)).mode)?(n.h=te.o.dir.node,n.i=te.o.dir.stream,n.g={}):32768==(61440&n.mode)?(n.h=te.o.file.node,n.i=te.o.file.stream,n.j=0,n.g=null):40960==(61440&n.mode)?(n.h=te.o.link.node,n.i=te.o.link.stream):8192==(61440&n.mode)&&(n.h=te.o.Z.node,n.i=te.o.Z.stream),n.timestamp=Date.now(),e&&(e.g[t]=n,e.timestamp=n.timestamp),n},Ga:function(e){return e.g?e.g.subarray?e.g.subarray(0,e.j):new Uint8Array(e.g):new Uint8Array(0)},$:function(e,t){var n=e.g?e.g.length:0;n>=t||(t=Math.max(t,n*(1048576>n?2:1.125)>>>0),0!=n&&(t=Math.max(t,256)),n=e.g,e.g=new Uint8Array(t),0<e.j&&e.g.set(n.subarray(0,e.j),0))},ua:function(e,t){if(e.j!=t)if(0==t)e.g=null,e.j=0;else{var n=e.g;e.g=new Uint8Array(t),n&&e.g.set(n.subarray(0,Math.min(t,e.j))),e.j=t}},h:{B:function(e){var t={};return t.Fa=8192==(61440&e.mode)?e.id:1,t.Ia=e.id,t.mode=e.mode,t.Ka=1,t.uid=0,t.Ha=0,t.P=e.P,16384==(61440&e.mode)?t.size=4096:32768==(61440&e.mode)?t.size=e.j:40960==(61440&e.mode)?t.size=e.link.length:t.size=0,t.Ca=new Date(e.timestamp),t.Ja=new Date(e.timestamp),t.Ea=new Date(e.timestamp),t.ka=4096,t.Da=Math.ceil(t.size/t.ka),t},s:function(e,t){void 0!==t.mode&&(e.mode=t.mode),void 0!==t.timestamp&&(e.timestamp=t.timestamp),void 0!==t.size&&te.ua(e,t.size)},K:function(){throw le[44]},N:function(e,t,n,r){return te.createNode(e,t,n,r)},ha:function(e,t,n){if(16384==(61440&e.mode)){try{var r=de(t,n)}catch(e){}if(r)for(var a in r.g)throw new ue(55)}delete e.parent.g[e.name],e.parent.timestamp=Date.now(),e.name=n,t.g[n]=e,t.timestamp=e.parent.timestamp,e.parent=t},ja:function(e,t){delete e.g[t],e.timestamp=Date.now()},ia:function(e,t){var n,r=de(e,t);for(n in r.g)throw new ue(55);delete e.g[t],e.timestamp=Date.now()},ga:function(e){var t,n=[".",".."];for(t in e.g)e.g.hasOwnProperty(t)&&n.push(t);return n},R:function(e,t,n){return(e=te.createNode(e,t,41471,0)).link=n,e},L:function(e){if(40960!=(61440&e.mode))throw new ue(28);return e.link}},i:{read:function(e,t,n,r,a){var s=e.node.g;if(a>=e.node.j)return 0;if(8<(e=Math.min(e.node.j-a,r))&&s.subarray)t.set(s.subarray(a,a+e),n);else for(r=0;r<e;r++)t[n+r]=s[a+r];return e},write:function(e,t,n,r,a,s){if(t.buffer===h.buffer&&(s=!1),!r)return 0;if((e=e.node).timestamp=Date.now(),t.subarray&&(!e.g||e.g.subarray)){if(s)return e.g=t.subarray(n,n+r),e.j=r;if(0===e.j&&0===a)return e.g=t.slice(n,n+r),e.j=r;if(a+r<=e.j)return e.g.set(t.subarray(n,n+r),a),r}if(te.$(e,a+r),e.g.subarray&&t.subarray)e.g.set(t.subarray(n,n+r),a);else for(s=0;s<r;s++)e.g[a+s]=t[n+s];return e.j=Math.max(e.j,a+r),r},D:function(e,t,n){if(1===n?t+=e.position:2===n&&32768==(61440&e.node.mode)&&(t+=e.node.j),0>t)throw new ue(28);return t},Y:function(e,t,n){te.$(e.node,t+n),e.node.j=Math.max(e.node.j,t+n)},da:function(e,t,n,r,a){if(32768!=(61440&e.node.mode))throw new ue(43);if(e=e.node.g,2&a||e.buffer!==p){if((0<n||n+t<e.length)&&(e=e.subarray?e.subarray(n,n+t):Array.prototype.slice.call(e,n,n+t)),n=!0,F(),!(t=void 0))throw new ue(48);h.set(e,t)}else n=!1,t=e.byteOffset;return{F:t,Ba:n}},fa:function(e,t,n,r,a){if(32768!=(61440&e.node.mode))throw new ue(43);return 2&a||te.i.write(e,t,0,r,n,!1),0}}},ne=null,re={},ae=[],se=1,oe=null,ie=!0,ue=null,le={},ce=(e,t={})=>{if(!(e=H("/",e)))return{path:"",node:null};if(8<(t=Object.assign({ba:!0,W:0},t)).W)throw new ue(32);e=U(e.split("/").filter((e=>!!e)),!1);for(var n=ne,r="/",a=0;a<e.length;a++){var s=a===e.length-1;if(s&&t.parent)break;if(n=de(n,e[a]),r=z(r+"/"+e[a]),n.O&&(!s||s&&t.ba)&&(n=n.O.root),!s||t.aa)for(s=0;40960==(61440&n.mode);)if(n=Se(r),r=H(V(r),n),n=ce(r,{W:t.W+1}).node,40<s++)throw new ue(32)}return{path:r,node:n}},pe=e=>{for(var t;;){if(e===e.parent)return e=e.v.ea,t?"/"!==e[e.length-1]?e+"/"+t:e+t:e;t=t?e.name+"/"+t:e.name,e=e.parent}},he=(e,t)=>{for(var n=0,r=0;r<t.length;r++)n=(n<<5)-n+t.charCodeAt(r)|0;return(e+n>>>0)%oe.length},de=(e,t)=>{var n;if(n=(n=ye(e,"x"))?n:e.h.K?0:2)throw new ue(n,e);for(n=oe[he(e.id,t)];n;n=n.sa){var r=n.name;if(n.parent.id===e.id&&r===t)return n}return e.h.K(e,t)},fe=(e,t,n,r)=>(e=new Ve(e,t,n,r),t=he(e.parent.id,e.name),e.sa=oe[t],oe[t]=e),me={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},ge=e=>{var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},ye=(e,t)=>ie?0:!t.includes("r")||292&e.mode?t.includes("w")&&!(146&e.mode)||t.includes("x")&&!(73&e.mode)?2:0:2,be=(e,t)=>{try{return de(e,t),20}catch(e){}return ye(e,"wx")},_e=(e,t)=>(Y||((Y=function(){this.I={}}).prototype={},Object.defineProperties(Y.prototype,{object:{get:function(){return this.node},set:function(e){this.node=e}},flags:{get:function(){return this.I.flags},set:function(e){this.I.flags=e}},position:{get:function(){return this.I.position},set:function(e){this.I.position=e}}})),e=Object.assign(new Y,e),t=((e=0)=>{for(;4096>=e;e++)if(!ae[e])return e;throw new ue(33)})(t),e.A=t,ae[t]=e),xe={open:e=>{e.i=re[e.node.P].i,e.i.open&&e.i.open(e)},D:()=>{throw new ue(70)}},ve=(e,t)=>{re[e]={i:t}},we=(e,t)=>{var n="/"===t,r=!t;if(n&&ne)throw new ue(10);if(!n&&!r){var a=ce(t,{ba:!1});if(t=a.path,(a=a.node).O)throw new ue(10);if(16384!=(61440&a.mode))throw new ue(54)}t={type:e,La:{},ea:t,ra:[]},(e=e.v(t)).v=t,t.root=e,n?ne=e:a&&(a.O=t,a.v&&a.v.ra.push(t))},Te=(e,t,n)=>{var r=ce(e,{parent:!0}).node;if(!(e=W(e))||"."===e||".."===e)throw new ue(28);var a=be(r,e);if(a)throw new ue(a);if(!r.h.N)throw new ue(63);return r.h.N(r,e,t,n)},ke=(e,t,n)=>{void 0===n&&(n=t,t=438),Te(e,8192|t,n)},Ie=(e,t)=>{if(!H(e))throw new ue(44);var n=ce(t,{parent:!0}).node;if(!n)throw new ue(44);t=W(t);var r=be(n,t);if(r)throw new ue(r);if(!n.h.R)throw new ue(63);n.h.R(n,t,e)},Se=e=>{if(!(e=ce(e).node))throw new ue(44);if(!e.h.L)throw new ue(28);return H(pe(e.parent),e.h.L(e))},Ee=(e,n,r)=>{if(""===e)throw new ue(44);if("string"==typeof n){var a=me[n];if(void 0===a)throw Error("Unknown file open mode: "+n);n=a}if(r=64&n?4095&(void 0===r?438:r)|32768:0,"object"==typeof e)var s=e;else{e=z(e);try{s=ce(e,{aa:!(131072&n)}).node}catch(e){}}if(a=!1,64&n)if(s){if(128&n)throw new ue(20)}else s=Te(e,r,0),a=!0;if(!s)throw new ue(44);if(8192==(61440&s.mode)&&(n&=-513),65536&n&&16384!=(61440&s.mode))throw new ue(54);if(!a&&(r=s?40960==(61440&s.mode)?32:16384==(61440&s.mode)&&("r"!==ge(n)||512&n)?31:ye(s,ge(n)):44))throw new ue(r);if(512&n&&!a){if(!(r="string"==typeof(r=s)?ce(r,{aa:!0}).node:r).h.s)throw new ue(63);if(16384==(61440&r.mode))throw new ue(31);if(32768!=(61440&r.mode))throw new ue(28);if(a=ye(r,"w"))throw new ue(a);r.h.s(r,{size:0,timestamp:Date.now()})}return n&=-131713,(s=_e({node:s,path:pe(s),flags:n,seekable:!0,position:0,i:s.i,Aa:[],error:!1})).i.open&&s.i.open(s),!t.logReadFiles||1&n||(Q||(Q={}),e in Q||(Q[e]=1)),s},Ne=(e,t,n)=>{if(null===e.A)throw new ue(8);if(!e.seekable||!e.i.D)throw new ue(70);if(0!=n&&1!=n&&2!=n)throw new ue(28);e.position=e.i.D(e,t,n),e.Aa=[]},Ce=()=>{ue||((ue=function(e,t){this.node=t,this.va=function(e){this.C=e},this.va(e),this.message="FS error"}).prototype=Error(),ue.prototype.constructor=ue,[44].forEach((e=>{le[e]=new ue(e),le[e].stack="<generic error, no stack>"})))},Ae=(e,t,n)=>{e=z("/dev/"+e);var r=((e,t)=>{var n=0;return e&&(n|=365),t&&(n|=146),n})(!!t,!!n);X||(X=64);var a=X++<<8|0;ve(a,{open:e=>{e.seekable=!1},close:()=>{n&&n.buffer&&n.buffer.length&&n(10)},read:(e,n,r,a)=>{for(var s=0,o=0;o<a;o++){try{var i=t()}catch(e){throw new ue(29)}if(void 0===i&&0===s)throw new ue(6);if(null==i)break;s++,n[r+o]=i}return s&&(e.node.timestamp=Date.now()),s},write:(e,t,r,a)=>{for(var s=0;s<a;s++)try{n(t[r+s])}catch(e){throw new ue(29)}return a&&(e.node.timestamp=Date.now()),s}}),ke(e,r,a)},Re={},$e=void 0;function Me(){return m[($e+=4)-4>>2]}function Fe(e){if(!(e=ae[e]))throw new ue(8);return e}var Oe,De={};function Le(){if(!Oe){var e,t={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",_:s||"./this.program"};for(e in De)void 0===De[e]?delete t[e]:t[e]=De[e];var n=[];for(e in t)n.push(e+"="+t[e]);Oe=n}return Oe}function Pe(e){return 0==e%4&&(0!=e%100||0==e%400)}var Be=[31,29,31,30,31,30,31,31,30,31,30,31],Ue=[31,28,31,30,31,30,31,31,30,31,30,31];function ze(e,n,r,a){var s={string:e=>{var t=0;if(null!=e&&0!==e){var n=1+(e.length<<2);t=Xe(n),T(e,d,t,n)}return t},array:e=>{var t=Xe(e.length);return h.set(e,t),t}};e=t["_"+e];var o,i=[],u=0;if(a)for(var l=0;l<a.length;l++){var c=s[r[l]];c?(0===u&&(u=Ke()),i[l]=c(a[l])):i[l]=a[l]}return o=r=e.apply(null,i),0!==u&&qe(u),"string"===n?w(o):"boolean"===n?!!o:o}function Ve(e,t,n,r){e||(e=this),this.parent=e,this.v=e.v,this.O=null,this.id=se++,this.name=t,this.mode=n,this.h={},this.i={},this.P=r}"undefined"!=typeof TextDecoder&&new TextDecoder("utf-16le"),Object.defineProperties(Ve.prototype,{read:{get:function(){return 365==(365&this.mode)},set:function(e){e?this.mode|=365:this.mode&=-366}},write:{get:function(){return 146==(146&this.mode)},set:function(e){e?this.mode|=146:this.mode&=-147}}}),Ce(),oe=Array(4096),we(te,"/"),Te("/tmp",16895,0),Te("/home",16895,0),Te("/home/web_user",16895,0),(()=>{Te("/dev",16895,0),ve(259,{read:()=>0,write:(e,t,n,r)=>r}),ke("/dev/null",259),K(1280,Z),K(1536,ee),ke("/dev/tty",1280),ke("/dev/tty1",1536);var e=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return()=>(crypto.getRandomValues(e),e[0])}return()=>F("randomDevice")}();Ae("random",e),Ae("urandom",e),Te("/dev/shm",16895,0),Te("/dev/shm/tmp",16895,0)})(),(()=>{Te("/proc",16895,0);var e=Te("/proc/self",16895,0);Te("/proc/self/fd",16895,0),we({v:()=>{var t=fe(e,"fd",16895,73);return t.h={K:(e,t)=>{var n=ae[+t];if(!n)throw new ue(8);return(e={parent:null,v:{ea:"fake"},h:{L:()=>n.path}}).parent=e}},t}},"/proc/self/fd")})();var We={__assert_fail:function(e,t,n,r){F("Assertion failed: "+w(e)+", at: "+[t?w(t):"unknown filename",n,r?w(r):"unknown function"])},__cxa_allocate_exception:function(e){return He(e+24)+24},__cxa_throw:function(e,t,n){throw new B(e).I(t,n),e},__syscall_fcntl64:function(e,t,n){$e=n;try{var r=Fe(e);switch(t){case 0:var a=Me();return 0>a?-28:_e(r,a).A;case 1:case 2:case 6:case 7:return 0;case 3:return r.flags;case 4:return a=Me(),r.flags|=a,0;case 5:return a=Me(),f[a+0>>1]=2,0;case 16:case 8:default:return-28;case 9:return m[je()>>2]=28,-1}}catch(e){if(void 0===Re||!(e instanceof ue))throw e;return-e.C}},__syscall_ioctl:function(e,t,n){$e=n;try{var r=Fe(e);switch(t){case 21509:case 21505:case 21510:case 21511:case 21512:case 21506:case 21507:case 21508:case 21523:case 21524:return r.l?0:-59;case 21519:if(!r.l)return-59;var a=Me();return m[a>>2]=0;case 21520:return r.l?-28:-59;case 21531:if(e=a=Me(),!r.i.na)throw new ue(59);return r.i.na(r,t,e);default:return-28}}catch(e){if(void 0===Re||!(e instanceof ue))throw e;return-e.C}},__syscall_openat:function(e,t,n,r){$e=r;try{var a=t=w(t);if("/"===a.charAt(0))t=a;else{var s=-100===e?"/":Fe(e).path;if(0==a.length)throw new ue(44);t=z(s+"/"+a)}var o=r?Me():0;return Ee(t,n,o).A}catch(e){if(void 0===Re||!(e instanceof ue))throw e;return-e.C}},abort:function(){F("")},emscripten_memcpy_big:function(e,t,n){d.copyWithin(e,t,t+n)},emscripten_resize_heap:function(e){var t=d.length;if(2147483648<(e>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=t*(1+.2/n);r=Math.min(r,e+100663296);var a=Math;r=Math.max(e,r),a=a.min.call(a,2147483648,r+(65536-r%65536)%65536);e:{try{c.grow(a-p.byteLength+65535>>>16),k();var s=1;break e}catch(e){}s=void 0}if(s)return!0}return!1},environ_get:function(e,t){var n=0;return Le().forEach((function(r,a){var s=t+n;for(a=g[e+4*a>>2]=s,s=0;s<r.length;++s)h[a++>>0]=r.charCodeAt(s);h[a>>0]=0,n+=r.length+1})),0},environ_sizes_get:function(e,t){var n=Le();g[e>>2]=n.length;var r=0;return n.forEach((function(e){r+=e.length+1})),g[t>>2]=r,0},fd_close:function(e){try{var t=Fe(e);if(null===t.A)throw new ue(8);t.U&&(t.U=null);try{t.i.close&&t.i.close(t)}catch(e){throw e}finally{ae[t.A]=null}return t.A=null,0}catch(e){if(void 0===Re||!(e instanceof ue))throw e;return e.C}},fd_read:function(e,t,n,r){try{e:{var a=Fe(e);e=t;for(var s=t=0;s<n;s++){var o=g[e>>2],i=g[e+4>>2];e+=8;var u=a,l=o,c=i,p=void 0,d=h;if(0>c||0>p)throw new ue(28);if(null===u.A)throw new ue(8);if(1==(2097155&u.flags))throw new ue(8);if(16384==(61440&u.node.mode))throw new ue(31);if(!u.i.read)throw new ue(28);var f=void 0!==p;if(f){if(!u.seekable)throw new ue(70)}else p=u.position;var m=u.i.read(u,d,l,c,p);f||(u.position+=m);var y=m;if(0>y){var b=-1;break e}if(t+=y,y<i)break}b=t}return g[r>>2]=b,0}catch(e){if(void 0===Re||!(e instanceof ue))throw e;return e.C}},fd_seek:function(e,t,n,r,a){try{if(t=n+2097152>>>0<4194305-!!t?(t>>>0)+4294967296*n:NaN,isNaN(t))return 61;var s=Fe(e);return Ne(s,t,r),R=[s.position>>>0,(A=s.position,1<=+Math.abs(A)?0<A?(0|Math.min(+Math.floor(A/4294967296),4294967295))>>>0:~~+Math.ceil((A-+(~~A>>>0))/4294967296)>>>0:0)],m[a>>2]=R[0],m[a+4>>2]=R[1],s.U&&0===t&&0===r&&(s.U=null),0}catch(e){if(void 0===Re||!(e instanceof ue))throw e;return e.C}},fd_write:function(e,t,n,r){try{e:{var a=Fe(e);e=t;for(var s=t=0;s<n;s++){var o=g[e>>2],i=g[e+4>>2];e+=8;var u=a,l=o,c=i,p=void 0,d=h;if(0>c||0>p)throw new ue(28);if(null===u.A)throw new ue(8);if(0==(2097155&u.flags))throw new ue(8);if(16384==(61440&u.node.mode))throw new ue(31);if(!u.i.write)throw new ue(28);u.seekable&&1024&u.flags&&Ne(u,0,2);var f=void 0!==p;if(f){if(!u.seekable)throw new ue(70)}else p=u.position;var m=u.i.write(u,d,l,c,p,void 0);f||(u.position+=m);var y=m;if(0>y){var b=-1;break e}t+=y}b=t}return g[r>>2]=b,0}catch(e){if(void 0===Re||!(e instanceof ue))throw e;return e.C}},strftime_l:function(e,t,n,r){return function(e,t,n,r){function a(e,t,n){for(e="number"==typeof e?e.toString():e||"";e.length<t;)e=n[0]+e;return e}function s(e,t){return a(e,t,"0")}function o(e,t){function n(e){return 0>e?-1:0<e?1:0}var r;return 0===(r=n(e.getFullYear()-t.getFullYear()))&&0===(r=n(e.getMonth()-t.getMonth()))&&(r=n(e.getDate()-t.getDate())),r}function i(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function u(e){var t=e.G;for(e=new Date(new Date(e.H+1900,0,1).getTime());0<t;){var n=e.getMonth(),r=(Pe(e.getFullYear())?Be:Ue)[n];if(!(t>r-e.getDate())){e.setDate(e.getDate()+t);break}t-=r-e.getDate()+1,e.setDate(1),11>n?e.setMonth(n+1):(e.setMonth(0),e.setFullYear(e.getFullYear()+1))}return n=new Date(e.getFullYear()+1,0,4),t=i(new Date(e.getFullYear(),0,4)),n=i(n),0>=o(t,e)?0>=o(n,e)?e.getFullYear()+1:e.getFullYear():e.getFullYear()-1}var l=m[r+40>>2];for(var c in r={ya:m[r>>2],xa:m[r+4>>2],S:m[r+8>>2],X:m[r+12>>2],T:m[r+16>>2],H:m[r+20>>2],u:m[r+24>>2],G:m[r+28>>2],Ma:m[r+32>>2],wa:m[r+36>>2],za:l?w(l):""},n=w(n),l={"%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(c,"g"),l[c]);var p="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),d="January February March April May June July August September October November December".split(" ");for(c in l={"%a":function(e){return p[e.u].substring(0,3)},"%A":function(e){return p[e.u]},"%b":function(e){return d[e.T].substring(0,3)},"%B":function(e){return d[e.T]},"%C":function(e){return s((e.H+1900)/100|0,2)},"%d":function(e){return s(e.X,2)},"%e":function(e){return a(e.X,2," ")},"%g":function(e){return u(e).toString().substring(2)},"%G":function(e){return u(e)},"%H":function(e){return s(e.S,2)},"%I":function(e){return 0==(e=e.S)?e=12:12<e&&(e-=12),s(e,2)},"%j":function(e){for(var t=0,n=0;n<=e.T-1;t+=(Pe(e.H+1900)?Be:Ue)[n++]);return s(e.X+t,3)},"%m":function(e){return s(e.T+1,2)},"%M":function(e){return s(e.xa,2)},"%n":function(){return"\n"},"%p":function(e){return 0<=e.S&&12>e.S?"AM":"PM"},"%S":function(e){return s(e.ya,2)},"%t":function(){return"\t"},"%u":function(e){return e.u||7},"%U":function(e){return s(Math.floor((e.G+7-e.u)/7),2)},"%V":function(e){var t=Math.floor((e.G+7-(e.u+6)%7)/7);if(2>=(e.u+371-e.G-2)%7&&t++,t)53==t&&(4==(n=(e.u+371-e.G)%7)||3==n&&Pe(e.H)||(t=1));else{t=52;var n=(e.u+7-e.G-1)%7;(4==n||5==n&&Pe(e.H%400-1))&&t++}return s(t,2)},"%w":function(e){return e.u},"%W":function(e){return s(Math.floor((e.G+7-(e.u+6)%7)/7),2)},"%y":function(e){return(e.H+1900).toString().substring(2)},"%Y":function(e){return e.H+1900},"%z":function(e){var t=0<=(e=e.wa);return e=Math.abs(e)/60,(t?"+":"-")+String("0000"+(e/60*100+e%60)).slice(-4)},"%Z":function(e){return e.za},"%%":function(){return"%"}},n=n.replace(/%%/g,"\0\0"),l)n.includes(c)&&(n=n.replace(new RegExp(c,"g"),l[c](r)));return(c=G(n=n.replace(/\0\0/g,"%"),!1)).length>t?0:(h.set(c,e),c.length-1)}(e,t,n,r)}};!function(){function e(e){t.asm=e.exports,c=t.asm.memory,k(),S.unshift(t.asm.__wasm_call_ctors),$--,t.monitorRunDependencies&&t.monitorRunDependencies($),0==$&&M&&(e=M,M=null,e())}function n(t){e(t.instance)}function a(e){return(i||"function"!=typeof fetch?Promise.resolve().then((function(){return L()})):fetch(C,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+C+"'";return e.arrayBuffer()})).catch((function(){return L()}))).then((function(e){return WebAssembly.instantiate(e,s)})).then((function(e){return e})).then(e,(function(e){l("failed to asynchronously prepare wasm: "+e),F(e)}))}var s={env:We,wasi_snapshot_preview1:We};if($++,t.monitorRunDependencies&&t.monitorRunDependencies($),t.instantiateWasm)try{return t.instantiateWasm(s,e)}catch(e){return l("Module.instantiateWasm callback failed with error: "+e),!1}(i||"function"!=typeof WebAssembly.instantiateStreaming||O()||"function"!=typeof fetch?a(n):fetch(C,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,s).then(n,(function(e){return l("wasm streaming compile failed: "+e),l("falling back to ArrayBuffer instantiation"),a(n)}))}))).catch(r)}(),t.___wasm_call_ctors=function(){return(t.___wasm_call_ctors=t.asm.__wasm_call_ctors).apply(null,arguments)};var He=t._malloc=function(){return(He=t._malloc=t.asm.malloc).apply(null,arguments)};t._free=function(){return(t._free=t.asm.free).apply(null,arguments)},t._xzimgInitializeCamera=function(){return(t._xzimgInitializeCamera=t.asm.xzimgInitializeCamera).apply(null,arguments)},t._xzimgPoseEstimationInitializeFacePose=function(){return(t._xzimgPoseEstimationInitializeFacePose=t.asm.xzimgPoseEstimationInitializeFacePose).apply(null,arguments)},t._xzimgPoseEstimationInitialize=function(){return(t._xzimgPoseEstimationInitialize=t.asm.xzimgPoseEstimationInitialize).apply(null,arguments)},t._xzimgPoseEstimationRelease=function(){return(t._xzimgPoseEstimationRelease=t.asm.xzimgPoseEstimationRelease).apply(null,arguments)},t._xzimgPoseEstimationPrepareCrop=function(){return(t._xzimgPoseEstimationPrepareCrop=t.asm.xzimgPoseEstimationPrepareCrop).apply(null,arguments)},t._xzimgPoseEstimationEstimateFacePose=function(){return(t._xzimgPoseEstimationEstimateFacePose=t.asm.xzimgPoseEstimationEstimateFacePose).apply(null,arguments)},t._xzimgGetHeatmapsLocations=function(){return(t._xzimgGetHeatmapsLocations=t.asm.xzimgGetHeatmapsLocations).apply(null,arguments)},t._xzimgEstimateRigidPose=function(){return(t._xzimgEstimateRigidPose=t.asm.xzimgEstimateRigidPose).apply(null,arguments)},t._xzimgEstimateGetSimilarity=function(){return(t._xzimgEstimateGetSimilarity=t.asm.xzimgEstimateGetSimilarity).apply(null,arguments)},t._xzimgWarpAffine=function(){return(t._xzimgWarpAffine=t.asm.xzimgWarpAffine).apply(null,arguments)},t._xzimgMatchRecKeypsInit=function(){return(t._xzimgMatchRecKeypsInit=t.asm.xzimgMatchRecKeypsInit).apply(null,arguments)},t._xzimgMatchRecKeyps=function(){return(t._xzimgMatchRecKeyps=t.asm.xzimgMatchRecKeyps).apply(null,arguments)},t._xzimgEstimateInitNonRigidPose=function(){return(t._xzimgEstimateInitNonRigidPose=t.asm.xzimgEstimateInitNonRigidPose).apply(null,arguments)},t._xzimgEstimateNonRigidPose=function(){return(t._xzimgEstimateNonRigidPose=t.asm.xzimgEstimateNonRigidPose).apply(null,arguments)},t._xzimgEstimateBodyNonRigidPose=function(){return(t._xzimgEstimateBodyNonRigidPose=t.asm.xzimgEstimateBodyNonRigidPose).apply(null,arguments)},t._xzimgEstimateNonRigidPoseBase=function(){return(t._xzimgEstimateNonRigidPoseBase=t.asm.xzimgEstimateNonRigidPoseBase).apply(null,arguments)},t._xzimgEstimateGetNumVertices=function(){return(t._xzimgEstimateGetNumVertices=t.asm.xzimgEstimateGetNumVertices).apply(null,arguments)},t._xzimgEstimateGetDenseVertices=function(){return(t._xzimgEstimateGetDenseVertices=t.asm.xzimgEstimateGetDenseVertices).apply(null,arguments)},t._xzimgEstimateGetNumBlendShapes=function(){return(t._xzimgEstimateGetNumBlendShapes=t.asm.xzimgEstimateGetNumBlendShapes).apply(null,arguments)},t._xzimgEstimateGetBlendShapes=function(){return(t._xzimgEstimateGetBlendShapes=t.asm.xzimgEstimateGetBlendShapes).apply(null,arguments)},t._xzimgGeometryGetModelIntersection=function(){return(t._xzimgGeometryGetModelIntersection=t.asm.xzimgGeometryGetModelIntersection).apply(null,arguments)};var Ge,je=t.___errno_location=function(){return(je=t.___errno_location=t.asm.__errno_location).apply(null,arguments)},Ke=t.stackSave=function(){return(Ke=t.stackSave=t.asm.stackSave).apply(null,arguments)},qe=t.stackRestore=function(){return(qe=t.stackRestore=t.asm.stackRestore).apply(null,arguments)},Xe=t.stackAlloc=function(){return(Xe=t.stackAlloc=t.asm.stackAlloc).apply(null,arguments)};function Ye(){function e(){if(!Ge&&(Ge=!0,t.calledRun=!0,!_)){if(t.noFSInit||q||(q=!0,Ce(),t.stdin=t.stdin,t.stdout=t.stdout,t.stderr=t.stderr,t.stdin?Ae("stdin",t.stdin):Ie("/dev/tty","/dev/stdin"),t.stdout?Ae("stdout",null,t.stdout):Ie("/dev/tty","/dev/stdout"),t.stderr?Ae("stderr",null,t.stderr):Ie("/dev/tty1","/dev/stderr"),Ee("/dev/stdin",0),Ee("/dev/stdout",1),Ee("/dev/stderr",1)),ie=!1,P(S),n(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),t.postRun)for("function"==typeof t.postRun&&(t.postRun=[t.postRun]);t.postRun.length;){var e=t.postRun.shift();E.unshift(e)}P(E)}}if(!(0<$)){if(t.preRun)for("function"==typeof t.preRun&&(t.preRun=[t.preRun]);t.preRun.length;)N();P(I),0<$||(t.setStatus?(t.setStatus("Running..."),setTimeout((function(){setTimeout((function(){t.setStatus("")}),1),e()}),1)):e())}}if(t.___cxa_is_pointer_type=function(){return(t.___cxa_is_pointer_type=t.asm.__cxa_is_pointer_type).apply(null,arguments)},t.dynCall_jiji=function(){return(t.dynCall_jiji=t.asm.dynCall_jiji).apply(null,arguments)},t.dynCall_viijii=function(){return(t.dynCall_viijii=t.asm.dynCall_viijii).apply(null,arguments)},t.dynCall_iiiiij=function(){return(t.dynCall_iiiiij=t.asm.dynCall_iiiiij).apply(null,arguments)},t.dynCall_iiiiijj=function(){return(t.dynCall_iiiiijj=t.asm.dynCall_iiiiijj).apply(null,arguments)},t.dynCall_iiiiiijj=function(){return(t.dynCall_iiiiiijj=t.asm.dynCall_iiiiiijj).apply(null,arguments)},t.ccall=ze,t.cwrap=function(e,n,r,a){var s=(r=r||[]).every((e=>"number"===e||"boolean"===e));return"string"!==n&&s&&!a?t["_"+e]:function(){return ze(e,n,r,arguments)}},t.setValue=function(e,t,n="i8"){switch(n.endsWith("*")&&(n="*"),n){case"i1":case"i8":h[e>>0]=t;break;case"i16":f[e>>1]=t;break;case"i32":m[e>>2]=t;break;case"i64":R=[t>>>0,(A=t,1<=+Math.abs(A)?0<A?(0|Math.min(+Math.floor(A/4294967296),4294967295))>>>0:~~+Math.ceil((A-+(~~A>>>0))/4294967296)>>>0:0)],m[e>>2]=R[0],m[e+4>>2]=R[1];break;case"float":y[e>>2]=t;break;case"double":b[e>>3]=t;break;case"*":g[e>>2]=t;break;default:F("invalid type for setValue: "+n)}},t.getValue=function(e,t="i8"){switch(t.endsWith("*")&&(t="*"),t){case"i1":case"i8":return h[e>>0];case"i16":return f[e>>1];case"i32":case"i64":return m[e>>2];case"float":return y[e>>2];case"double":return b[e>>3];case"*":return g[e>>2];default:F("invalid type for getValue: "+t)}return null},M=function e(){Ge||Ye(),Ge||(M=e)},t.preInit)for("function"==typeof t.preInit&&(t.preInit=[t.preInit]);0<t.preInit.length;)t.preInit.pop()();return Ye(),e.ready});let GT;!function(e){e[e.float32=0]="float32",e[e.int32=1]="int32",e[e.bool=2]="bool",e[e.string=3]="string",e[e.complex64=4]="complex64"}(zT||(zT={})),function(e){e[e.linear=0]="linear",e[e.relu=1]="relu",e[e.relu6=2]="relu6",e[e.prelu=3]="prelu",e[e.leakyrelu=4]="leakyrelu",e[e.sigmoid=5]="sigmoid",e[e.elu=6]="elu"}(VT||(VT={}));const jT={kernelName:Sr,backendName:"wasm",setupFunc:function(e){GT=e.wasm.cwrap(Sr,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a,b:s,bias:o,preluActivationWeights:i}=t;if("float32"!==a.dtype||"float32"!==s.dtype)throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");const{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:p}=r,h=n.dataIdMap.get(a.dataId).id,d=n.dataIdMap.get(s.dataId).id;let f=0;if(null!=o){const e=n.dataIdMap.get(o.dataId);if(1!==e.shape.length)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${e.shape.length}.`);f=e.id}const m=null==i?0:n.dataIdMap.get(i.dataId).id,g=VT[c];if(null==g)throw new Error(`${c} activation not yet supported for FusedConv2D in the wasm backend.`);const y=u?a.shape[2]:a.shape[1],b=l?s.shape[1]:s.shape[2],_=Ci(a.shape.slice(0,-2),s.shape.slice(0,-2)),x=n.makeOutput([..._,y,b],a.dtype),v=n.dataIdMap.get(x.dataId).id,w=new Uint8Array(new Int32Array(a.shape).buffer),T=new Uint8Array(new Int32Array(s.shape).buffer);return GT(h,w,a.shape.length,d,T,s.shape.length,u,l,g,f,m,p||0,v),x}};function KT(e,t){let n;return{kernelName:e,backendName:"wasm",setupFunc:function(t){n=t.wasm.cwrap(e,null,["number","number","number"])},kernelFunc:function(e){const{backend:r,inputs:{x:a}}=e,s=r.dataIdMap.get(a.dataId).id,o=r.makeOutput(a.shape,t||a.dtype),i=r.dataIdMap.get(o.dataId).id;return 0===et(o.shape)||n(s,zT[a.dtype],i),o}}}const qT=KT("Abs");function XT(e,t,n){let r;return{kernelName:e,backendName:"wasm",setupFunc:function(t){r=t.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:a}=e,{a:s,b:o}=a,i=t.dataIdMap.get(s.dataId).id,u=t.dataIdMap.get(o.dataId).id,l=null!=n?n:s.dtype,c=Ci(s.shape,o.shape),p=t.makeOutput(c,l);if(0===et(c))return p;const h=new Uint8Array(new Int32Array(s.shape).buffer),d=new Uint8Array(new Int32Array(o.shape).buffer),f=t.dataIdMap.get(p.dataId).id;return r(i,h,s.shape.length,u,d,o.shape.length,zT[s.dtype],f),p}}}const YT=XT(Ft);let QT;const JT={kernelName:Ot,backendName:"wasm",setupFunc:function(e){QT=e.wasm.cwrap(Ot,null,["array","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n}=e,r=n.makeOutput(t[0].shape,t[0].dtype);if(0===et(r.shape))return r;const a=t.map((e=>n.dataIdMap.get(e.dataId).id)),s=new Uint8Array(new Int32Array(a).buffer),o=n.dataIdMap.get(r.dataId).id;return QT(s,a.length,zT[r.dtype],o),r}};function ZT(e){const{inputs:{x:t},backend:n}=e;if("string"===t.dtype)return ho(n.readSync(t.dataId),t.shape,t.dtype);const r=n.makeOutput(t.shape,t.dtype),a=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(r).set(a),r}const ek={kernelName:mn,backendName:"wasm",kernelFunc:ZT};let tk;function nk(e){const{inputs:t,backend:n,attrs:r}=e,[a,s]=function(e,t){const n=[],r=[];for(let a=0;a<e.length;++a)1!==e[a]&&n.push(e[a]),1!==e[t[a]]&&r.push(t[a]);for(let e=0;e<r.length;++e){let t=-1;for(let n=0;n<r.length;++n)r[n]>=e&&(-1===t||r[t]>r[n])&&(t=n);r[t]=e}return[n,r]}(t.x.shape,r.perm);let o=!0;for(let e=0;e<s.length;e++)s[e]!==e&&(o=!1);const i=function(e,t){const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[t[r]];return n}(t.x.shape,r.perm),u={dataId:t.x.dataId,shape:a,dtype:t.x.dtype};if(o){const e=ZT({inputs:t,backend:n});return e.shape=i,e}const l=n.makeOutput(i,u.dtype),c=n.dataIdMap.get(u.dataId).id,p=n.dataIdMap.get(l.dataId).id,h=new Uint8Array(new Int32Array(s).buffer),d=new Uint8Array(new Int32Array(u.shape).buffer);return tk(c,d,u.shape.length,zT[u.dtype],p,h,s.length),l}const rk={kernelName:xr,backendName:"wasm",kernelFunc:nk,setupFunc:function(e){tk=e.wasm.cwrap(xr,null,["number","array","number","number","number","array","number"])}};function ak(e,t,n){const r=e.shape,a=e.shape.length,s=it(t,r);let o=s;const i=Cl(o,a);let u=null,l=!1;if(null!=i){const t=new Array(a);for(let e=0;e<t.length;e++)t[e]=r[i[e]];o=Rl(o.length,a),u=nk({inputs:{x:e},attrs:{perm:i},backend:n});const s=n.dataIdMap.get(e.dataId).id;n.dataIdMap.get(u.dataId).id!==s&&(l=!0)}return{transposed:u,originalAxes:s,axes:o,inputWasTransposed:l}}let sk;const ok={kernelName:Dt,backendName:"wasm",setupFunc:function(e){sk=e.wasm.cwrap(Dt,null,["number, number, number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:a,keepDims:s}=r,{x:o}=n;let i=t.dataIdMap.get(o.dataId).id,u=o;const{transposed:l,axes:c,originalAxes:p,inputWasTransposed:h}=ak(o,a,t);h&&(u=l,i=t.dataIdMap.get(l.dataId).id),Nl("all",c,u.shape.length);const[d,f]=Sl(u.shape,c),m=et(f),g=t.makeOutput(d,o.dtype);if(0!==et(u.shape)){const e=t.dataIdMap.get(g.dataId).id;sk(i,m,e)}if(h&&t.disposeData(l.dataId),s){const e=El(g.shape,p);g.shape=e}return g}};let ik;const uk={kernelName:Lt,backendName:"wasm",setupFunc:function(e){ik=e.wasm.cwrap(Lt,null,["number, number, number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:a,keepDims:s}=r,{x:o}=n;let i=t.dataIdMap.get(o.dataId).id,u=o;const{transposed:l,axes:c,originalAxes:p,inputWasTransposed:h}=ak(o,a,t);h&&(u=l,i=t.dataIdMap.get(l.dataId).id),Nl("any",c,u.shape.length);const[d,f]=Sl(u.shape,c),m=et(f),g=t.makeOutput(d,o.dtype);if(0!==et(u.shape)){const e=t.dataIdMap.get(g.dataId).id;ik(i,m,e)}if(h&&t.disposeData(l.dataId),s){const e=El(g.shape,p);g.shape=e}return g}};let lk;const ck={kernelName:Pt,backendName:"wasm",kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:a}=r,{x:s}=n,o=t.dataIdMap.get(s.dataId).id;let i=o,u=s;const{transposed:l,axes:c,inputWasTransposed:p}=ak(s,a,t);if(p){const e=t.dataIdMap.get(l.dataId).id;e!==o&&(u=l,i=e)}const h=u.shape.slice(0,-1),d=t.makeOutput(h,"int32"),f=t.dataIdMap.get(d.dataId).id,m=et(d.shape),g=u.shape[c[0]];return lk(i,zT[u.dtype],m,g,f),p&&t.disposeData(l.dataId),d},setupFunc:function(e){lk=e.wasm.cwrap(Pt,null,["number","number","number","number","number"])}};let pk;const hk={kernelName:Bt,backendName:"wasm",setupFunc:function(e){pk=e.wasm.cwrap(Bt,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,a=t.x,s=r.dataIdMap.get(a.dataId).id,{filterSize:o,strides:i,pad:u,dimRoundingMode:l}=n,c=gu(a.shape,o,i,1,u,l),p=c.filterHeight,h=c.filterWidth,d=c.padInfo.top,f=c.padInfo.right,m=c.padInfo.bottom,g=c.padInfo.left,y=c.strideHeight,b=c.strideWidth,_=c.inChannels;if("channelsLast"!==c.dataFormat)throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);if(1!==c.dilationWidth||1!==c.dilationHeight)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${c.dilationHeight}, ${c.dilationWidth}].`);const x=r.makeOutput(c.outShape,"float32"),v=r.dataIdMap.get(x.dataId).id;return pk(s,a.shape[0],a.shape[1],a.shape[2],p,h,d,f,m,g,y,b,_,v),x}};function dk(e){const{inputs:t,attrs:n}=e,{x:r}=t,{shape:a}=n,s=et(r.shape),o=ot(a,s);return Qe(s===et(o),(()=>`new shape: ${o}, old shape: ${r.shape}. New shape and old shape must have the same number of elements.`)),e.backend.incRef(r.dataId),{dataId:r.dataId,shape:o,dtype:r.dtype}}const fk={kernelName:Hn,backendName:"wasm",kernelFunc:dk};let mk;const gk={kernelName:Ut,backendName:"wasm",setupFunc:function(e){mk=e.wasm.cwrap(Ut,null,["number","array","number","number","array","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a,b:s}=t,{transposeA:o,transposeB:i}=r;if("float32"!==a.dtype||"float32"!==s.dtype)throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");const u=a.shape.length,l=s.shape.length,c=o?a.shape[u-2]:a.shape[u-1],p=i?s.shape[l-1]:s.shape[l-2],h=o?a.shape[u-1]:a.shape[u-2],d=i?s.shape[l-2]:s.shape[l-1],f=a.shape.slice(0,-2),m=s.shape.slice(0,-2),g=et(f),y=et(m),b=Ci(a.shape.slice(0,-2),s.shape.slice(0,-2)).concat([h,d]);Qe(c===p,(()=>`Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${a.shape} and ${s.shape} and transposeA=${o} and transposeB=${i} must match.`));const _=i?[y,d,p]:[y,p,d],x=dk({inputs:{x:a},backend:n,attrs:{shape:o?[g,c,h]:[g,h,c]}}),v=dk({inputs:{x:s},backend:n,attrs:{shape:_}}),w=n.dataIdMap.get(x.dataId).id,T=n.dataIdMap.get(v.dataId).id,k=o?x.shape[2]:x.shape[1],I=i?v.shape[1]:v.shape[2],S=Math.max(g,y),E=n.makeOutput([S,k,I],x.dtype),N=n.dataIdMap.get(E.dataId).id,C=new Uint8Array(new Int32Array(x.shape).buffer),A=new Uint8Array(new Int32Array(v.shape).buffer);return mk(w,C,x.shape.length,T,A,v.shape.length,o,i,N),n.disposeData(x.dataId),n.disposeData(v.dataId),E.shape=b,E}};function yk(e){const{inputs:{x:t},attrs:{begin:n,size:r},backend:a}=e,[s,o]=Xi(t,n,r),i=Ki(t.shape,s,o),u=a.readSync(t.dataId),l=a.makeOutput(o,t.dtype),c=yt(t.shape),p=a.dataIdMap.get(l.dataId);if(i){const e=qi(s,c);return"string"===t.dtype?p.stringBytes=u.slice(e,e+et(o)):a.typedArrayFromHeap(l).set(u.subarray(e,e+et(o))),l}if("string"===t.dtype){const e=ig(u,s,o,t.shape,t.dtype);return p.stringBytes=e,l}const h=a.typedArrayFromHeap(l),d=t.shape.length;if(2===d)!function(e,t,n,r,a){let s=0;const o=r[0],i=r[1],u=o+a[0];for(let r=o;r<u;r++){const o=r*t+i;n.set(e.subarray(o,o+a[1]),s),s+=a[1]}}(u,c[0],h,s,o);else if(3===d)!function(e,t,n,r,a,s){let o=0;const i=a[0],u=a[1],l=a[2],c=i+s[0],p=u+s[1];for(let a=i;a<c;a++)for(let i=u;i<p;i++){const u=a*t+i*n+l;r.set(e.subarray(u,u+s[2]),o),o+=s[2]}}(u,c[0],c[1],h,s,o);else if(4===d)!function(e,t,n,r,a,s,o){let i=0;const u=s[0],l=s[1],c=s[2],p=u+o[0],h=l+o[1],d=c+o[2],f=s[3];for(let s=u;s<p;s++)for(let u=l;u<h;u++)for(let l=c;l<d;l++){const c=s*t+u*n+l*r+f;a.set(e.subarray(c,c+o[3]),i),i+=o[3]}}(u,c[0],c[1],c[2],h,s,o);else{const e=ig(u,s,o,t.shape,t.dtype);h.set(e)}return l}const bk={kernelName:Zn,backendName:"wasm",kernelFunc:yk},_k={kernelName:zt,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,crops:o}=r,i=s.reduce(((e,t)=>e*t)),u=vd(a.shape,s,i),l=wd(u.length,s.length),c=Td(a.shape,s,i),p=kd(o,s.length),h=Id(c,o,s.length),d=dk({inputs:{x:a},backend:n,attrs:{shape:u}}),f=nk({inputs:{x:d},backend:n,attrs:{perm:l}}),m=yk({inputs:{x:dk({inputs:{x:f},backend:n,attrs:{shape:c}})},backend:n,attrs:{begin:p,size:h}});return n.disposeData(d.dataId),n.disposeData(f.dataId),n.disposeData(d.dataId),m}};function xk(e){const{inputs:{x:t},attrs:{dtype:n},backend:r}=e,a=r.makeOutput(t.shape,n),s=r.typedArrayFromHeap(t);return r.typedArrayFromHeap(a).set(s),a}const vk={kernelName:Vt,backendName:"wasm",kernelFunc:xk},wk=KT(Wt);let Tk;const kk={kernelName:Ht,backendName:"wasm",setupFunc:function(e){Tk=e.wasm.cwrap(Ht,null,["number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{clipValueMin:s,clipValueMax:o}=r,i=n.dataIdMap.get(a.dataId).id,u=n.makeOutput(a.shape,a.dtype),l=n.dataIdMap.get(u.dataId).id;return Tk(i,s,o,l),u}};function Ik(e){const{inputs:t,backend:n}=e,r=it(e.attrs.axis,t[0].shape)[0];hd(t.map((e=>e.shape)),r);let a=dd(t.map((e=>e.shape)),r);const s=t.filter((e=>et(e.shape)>0));if(1===s.length)return ZT({inputs:{x:s[0]},backend:n});const o=n.makeOutput(a,t[0].dtype);if(0===et(a))return o;if("string"===s[0].dtype){const e=s.map((e=>{const t=et(e.shape.slice(r));return dk({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),i=e.map((e=>({vals:n.readSync(e.dataId),shape:e.shape})));a=dd(e.map((e=>e.shape)),1);const u=1===e[0].shape[0],l=Cm(i,a,t[0].dtype,u),c=dd(s.map((e=>e.shape)),r);return o.shape=c,n.dataIdMap.get(o.dataId).stringBytes=Vd(l),e.forEach((e=>n.disposeData(e.dataId))),o}const i=et(s[0].shape.slice(0,r));let u=0;const l=s.map((e=>{const t=et(e.shape.slice(r));return u+=t,t})),c=s.map((e=>n.typedArrayFromHeap(e))),p=n.typedArrayFromHeap(o);for(let e=0;e<i;e++){let t=e*u;for(let n=0;n<c.length;n++){const r=l[n],a=e*r,s=c[n].subarray(a,a+r);p.set(s,t),t+=r}}return o}const Sk={kernelName:Gt,backendName:"wasm",kernelFunc:Ik};let Ek;const Nk={kernelName:jt,backendName:"wasm",setupFunc:function(e){Ek=e.wasm.cwrap(jt,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:a,filter:s}=t,o=r.dataIdMap.get(a.dataId).id,i=r.dataIdMap.get(s.dataId).id,{strides:u,dilations:l,pad:c,dimRoundingMode:p,dataFormat:h}=n,d=Eu(h),f=yu(a.shape,s.shape,u,l,c,p,!1,d),m=f.filterHeight,g=f.filterWidth,y=f.padInfo.top,b=f.padInfo.right,_=f.padInfo.bottom,x=f.padInfo.left,v=f.dilationHeight,w=f.dilationWidth,T=f.strideHeight,k=f.strideWidth,I=f.inChannels,S=f.outChannels,E="SAME"===f.padInfo.type?1:0;if("channelsLast"!==f.dataFormat)throw new Error(`wasm backend Conv2D does not support dataFormat:'${f.dataFormat}'. Please use 'channelsLast'.`);const N=r.makeOutput(f.outShape,"float32"),C=r.dataIdMap.get(N.dataId).id;return Ek(o,a.shape[0],a.shape[1],a.shape[2],i,m,g,y,b,_,x,E,v,w,T,k,I,S,C),N}};let Ck;const Ak={kernelName:Kt,backendName:"wasm",setupFunc:function(e){Ck=e.wasm.cwrap(Kt,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{dy:a,filter:s}=n,{strides:o,pad:i,dataFormat:u,dimRoundingMode:l,inputShape:c}=r,p=Eu(u),h=yu(c,s.shape,o,1,i,l,!1,p),{batchSize:d,filterHeight:f,filterWidth:m,inChannels:g,inHeight:y,inWidth:b,outChannels:_,outHeight:x,outWidth:v,strideHeight:w,strideWidth:T}=h,k=f-1-h.padInfo.top,I=m-1-h.padInfo.left,S="channelsLast"===h.dataFormat,E=yt(h.inShape),N=yt(a.shape),[C,A,R]=yt(s.shape),$=E[0],M=S?E[1]:E[2],F=S?E[2]:1,O=S?1:E[1],D=N[0],L=S?N[1]:N[2],P=S?N[2]:1,B=S?1:N[1],U=t.makeOutput(h.inShape,"float32"),z=t.dataIdMap.get(U.dataId).id,V=t.dataIdMap.get(a.dataId).id,W=t.dataIdMap.get(s.dataId).id;return Ck(V,W,d,f,m,y,b,g,x,v,_,w,T,k,I,C,A,R,$,M,F,O,D,L,P,B,z),U}},Rk=KT("Cos"),$k=KT(qt);var Mk;let Fk;!function(e){e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest"}(Mk||(Mk={}));const Ok={kernelName:Qt,backendName:"wasm",setupFunc:function(e){Fk=e.wasm.cwrap(Qt,null,["number","number","number","number","array","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{method:a,extrapolationValue:s,cropSize:o}=r,{image:i,boxes:u,boxInd:l}=n,c=u.shape[0],[p,h]=o,d=[c,p,h,i.shape[3]];let f,m=t.dataIdMap.get(i.dataId);"float32"!==i.dtype&&(f=xk({backend:t,inputs:{x:i},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(f.dataId));const g=m.id,y=t.dataIdMap.get(u.dataId).id,b=t.dataIdMap.get(l.dataId).id,_=t.makeOutput(d,"float32"),x=t.dataIdMap.get(_.dataId).id,v=new Uint8Array(new Int32Array(i.shape).buffer);return Fk(g,y,b,c,v,p,h,Mk[a],s,x),null!=f&&t.disposeData(f.dataId),_}};let Dk;const Lk={kernelName:Xt,backendName:"wasm",setupFunc:function(e){Dk=e.wasm.cwrap(Xt,null,["number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,exclusive:o,reverse:i}=r,u=a.shape.length;Qe("float32"===a.dtype||"int32"===a.dtype,(()=>`cumprod does not support ${a.dtype} tensors in the WASM backend`));const l=Cl([s],u);let c=a;null!==l&&(c=nk({inputs:{x:a},attrs:{perm:l},backend:n}));const p=Rl(1,u)[0];Nl("cumprod",[p],u);const h=n.makeOutput(c.shape,c.dtype),d=c.shape[p],f=n.dataIdMap.get(c.dataId).id,m=n.dataIdMap.get(h.dataId).id;Dk(f,o?1:0,i?1:0,d,m,zT[a.dtype]);let g=h;return null!==l&&(g=nk({inputs:{x:h},attrs:{perm:Al(l)},backend:n}),n.disposeData(c.dataId),n.disposeData(h.dataId)),g}};let Pk;const Bk={kernelName:Yt,backendName:"wasm",setupFunc:function(e){Pk=e.wasm.cwrap(Yt,null,["number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,exclusive:o,reverse:i}=r,u=a.shape.length;Qe("float32"===a.dtype||"int32"===a.dtype,(()=>`cumsum does not support ${a.dtype} tensors in the WASM backend`));const l=Cl([s],u);let c=a;null!==l&&(c=nk({inputs:{x:a},attrs:{perm:l},backend:n}));const p=Rl(1,u)[0];Nl("cumsum",[p],u);const h=n.makeOutput(c.shape,c.dtype),d=c.shape[p],f=n.dataIdMap.get(c.dataId).id,m=n.dataIdMap.get(h.dataId).id;Pk(f,o?1:0,i?1:0,d,m,zT[a.dtype]);let g=h;return null!==l&&(g=nk({inputs:{x:h},attrs:{perm:Al(l)},backend:n}),n.disposeData(c.dataId),n.disposeData(h.dataId)),g}};let Uk;const zk={kernelName:Jt,backendName:"wasm",setupFunc:function(e){Uk=e.wasm.cwrap(Jt,null,["number","number","number","array","number","array","array","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{x:a}=n,{blockSize:s,dataFormat:o}=r,i=a.shape[0],u=("NHWC"===o?a.shape[1]:a.shape[2])*s,l=("NHWC"===o?a.shape[2]:a.shape[3])*s,c=("NHWC"===o?a.shape[3]:a.shape[1])/(s*s),p="NHWC"===o?[i,u,l,c]:[i,c,u,l],h=t.makeOutput(p,"float32"),d=t.dataIdMap.get(a.dataId).id,f=new Uint8Array(new Int32Array(yt(a.shape)).buffer),m=new Uint8Array(new Int32Array(p).buffer),g=new Uint8Array(new Int32Array(yt(p)).buffer),y=t.dataIdMap.get(h.dataId).id;return Uk(d,s,"NHWC"===o?1:0,f,a.shape.length-1,m,g,p.length,y),h}};let Vk;const Wk={kernelName:Zt,backendName:"wasm",setupFunc:function(e){Vk=e.wasm.cwrap(Zt,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:a,filter:s}=t,o=r.dataIdMap.get(a.dataId).id,i=r.dataIdMap.get(s.dataId).id,{strides:u,dilations:l,pad:c,dimRoundingMode:p}=n,h=null==l?[1,1]:l,d=yu(a.shape,s.shape,u,h,c,p,!0),f=d.filterHeight,m=d.filterWidth,g=d.padInfo.top,y=d.padInfo.right,b=d.padInfo.bottom,_=d.padInfo.left,x=d.dilationHeight,v=d.dilationWidth,w=d.strideHeight,T=d.strideWidth,k=d.inChannels,I=d.outChannels,S="SAME"===d.padInfo.type?1:0;if("channelsLast"!==d.dataFormat)throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${d.dataFormat}'. Please use 'channelsLast'.`);const E=r.makeOutput(d.outShape,"float32"),N=r.dataIdMap.get(E.dataId).id;return Vk(o,a.shape[0],a.shape[1],a.shape[2],i,f,m,g,y,b,_,S,x,v,w,T,k,I,N),E}},Hk=KT(tn),Gk=XT(nn,0,"bool"),jk=KT(rn,"float32");function Kk(e){const{inputs:t,attrs:n,backend:r}=e,{input:a}=t,{dim:s}=n,o=a.shape.length,i=a.shape.slice();let u=s;return s<0&&(Qe(-(o+1)<=s,(()=>`Axis must be in the interval [${-(o+1)}, ${o}]`)),u=o+s+1),i.splice(u,0,1),dk({inputs:{x:a},backend:r,attrs:{shape:i}})}const qk={kernelName:an,backendName:"wasm",kernelFunc:Kk};function Xk(e){const{attrs:{shape:t,value:n,dtype:r},backend:a}=e,s=a.makeOutput(t,r);return a.typedArrayFromHeap(s).fill(n),s}const Yk={kernelName:sn,backendName:"wasm",kernelFunc:Xk};let Qk;const Jk={kernelName:on,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n}=e,{image:r}=t,a=n.makeOutput(r.shape,r.dtype),s=n.dataIdMap.get(r.dataId).id,o=n.dataIdMap.get(a.dataId).id,[i,u,l,c]=r.shape;return Qk(s,i,u,l,c,o),a},setupFunc:function(e){Qk=e.wasm.cwrap(on,null,["number","number","number","number","number","number"])}},Zk=KT(un),eI=XT(ln);let tI;const nI={kernelName:cn,backendName:"wasm",setupFunc:function(e){tI=e.wasm.cwrap(cn,null,["number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{varianceEpsilon:a}=r,{x:s,mean:o,variance:i,offset:u,scale:l}=n,c=t.dataIdMap.get(s.dataId).id,p=t.dataIdMap.get(o.dataId).id,h=t.dataIdMap.get(i.dataId).id,d=null!=u?t.dataIdMap.get(u.dataId).id:0,f=null!=l?t.dataIdMap.get(l.dataId).id:0,m=t.makeOutput(s.shape,s.dtype);if(0===et(s.shape))return m;const g=t.dataIdMap.get(m.dataId).id;return tI(c,p,h,d,f,a,g),m}};let rI;const aI={kernelName:Er,backendName:"wasm",setupFunc:function(e){rI=e.wasm.cwrap(Er,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dilations:c,dataFormat:p,dimRoundingMode:h,activation:d,leakyreluAlpha:f}=n,m=yu(a.shape,s.shape,u,c,l,h),g=VT[d];if(null==g)throw new Error(`${d} activation not yet supported for FusedConv2D in the wasm backend.`);const y=r.dataIdMap.get(a.dataId).id,b=r.dataIdMap.get(s.dataId).id,_=m.outChannels;let x=0;if(null!=o){const e=r.dataIdMap.get(o.dataId);if(1!==e.shape.length)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${e.shape.length}.`);if(e.shape[0]!==_)throw new Error(`FusedConv2D bias shape (${e.shape}) does not match the number of output channels (${_})`);x=e.id}const v=m.filterHeight,w=m.filterWidth,T=m.padInfo.top,k=m.padInfo.right,I=m.padInfo.bottom,S=m.padInfo.left,E=m.dilationHeight,N=m.dilationWidth,C=m.strideHeight,A=m.strideWidth,R=m.inChannels,$="SAME"===m.padInfo.type?1:0,M=m.batchSize,F=m.inHeight,O=m.inWidth;if("NHWC"!==p)throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);const D=r.makeOutput(m.outShape,"float32"),L=r.dataIdMap.get(D.dataId).id,P=null==i?0:r.dataIdMap.get(i.dataId).id;return rI(y,M,F,O,b,v,w,x,T,k,I,S,$,E,N,C,A,R,_,g,P,f||0,L),D}};let sI;const oI={kernelName:Nr,backendName:"wasm",setupFunc:function(e){sI=e.wasm.cwrap(Nr,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dilations:c,dataFormat:p,dimRoundingMode:h,activation:d,leakyreluAlpha:f}=n,m=yu(a.shape,s.shape,u,c,l,h,!0),g=VT[d];if(null==g)throw new Error(`${d} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);const y=r.dataIdMap.get(a.dataId).id,b=r.dataIdMap.get(s.dataId).id,_=m.outChannels;let x=0;if(null!=o){const e=r.dataIdMap.get(o.dataId);if(1!==e.shape.length)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${e.shape.length}.`);if(e.shape[0]!==_)throw new Error(`FusedDepthwiseConv2D bias shape (${e.shape}) does not match the number of output channels (${_})`);x=e.id}const v=m.filterHeight,w=m.filterWidth,T=m.padInfo.top,k=m.padInfo.right,I=m.padInfo.bottom,S=m.padInfo.left,E=m.dilationHeight,N=m.dilationWidth,C=m.strideHeight,A=m.strideWidth,R=m.inChannels,$="SAME"===m.padInfo.type?1:0,M=m.batchSize,F=m.inHeight,O=m.inWidth;if("NHWC"!==p)throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);const D=r.makeOutput(m.outShape,"float32"),L=r.dataIdMap.get(D.dataId).id,P=null==i?0:r.dataIdMap.get(i.dataId).id;return sI(y,M,F,O,b,v,w,x,T,k,I,S,$,E,N,C,A,R,_,g,P,f||0,L),D}};let iI;const uI={kernelName:hn,backendName:"wasm",setupFunc:function(e){iI=e.wasm.cwrap(hn,null,["number","number","number","number","number","number","array","number"])},kernelFunc:function(e){const{backend:t,inputs:n}=e,{params:r,indices:a}=n,[s,o,i,u]=Mi(r,a),l=t.makeOutput(s,r.dtype);if(0===o)return l;const c=a.shape,p=c[c.length-1],h=t.dataIdMap.get(r.dataId).id,d=t.dataIdMap.get(a.dataId).id,f=new Uint8Array(new Int32Array(u).buffer),m=t.dataIdMap.get(l.dataId).id;return iI(h,zT[r.dtype],d,o,p,i,f,m),l}};let lI;const cI={kernelName:pn,backendName:"wasm",setupFunc:function(e){lI=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{x:a,indices:s}=n,{axis:o,batchDims:i}=r,u=it(o,a.shape)[0],l=t.readSync(s.dataId),c=a.shape[u];for(let e=0;e<l.length;++e){const t=l[e];Qe(t<=c-1&&t>=0,(()=>`GatherV2: the index value ${t} is not in [0, ${c-1}]`))}const p=Bd(a,s,u,i),h=dk({inputs:{x:a},attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]},backend:t}),d=et(s.shape),f=dk({inputs:{x:s},attrs:{shape:[p.batchSize,d/p.batchSize]},backend:t}),m=[p.batchSize,p.outerSize,d/p.batchSize,p.sliceSize],g=t.makeOutput(m,a.dtype);if(0===et(a.shape))return g;const y=h.shape.length-1,b=t.dataIdMap.get(h.dataId).id,_=t.dataIdMap.get(f.dataId).id,x=t.dataIdMap.get(g.dataId).id,v=new Uint8Array(new Int32Array(yt(h.shape)).buffer),w=new Uint8Array(new Int32Array(yt(m)).buffer);return lI(b,zT[a.dtype],v,y,_,p.batchSize,w,x),t.disposeData(h.dataId),t.disposeData(f.dataId),g.shape=p.outputShape,g}},pI=XT(dn,0,"bool"),hI=XT(fn,0,"bool"),dI=KT(gn,"bool");let fI;const mI={kernelName:yn,backendName:"wasm",setupFunc:function(e){fI=e.wasm.cwrap(yn,null,["number","number","number","number"])},kernelFunc:function(e){const{inputs:{x:t},attrs:{alpha:n},backend:r}=e,a=r.dataIdMap.get(t.dataId).id,s=r.makeOutput(t.shape,"float32");if(0!==et(t.shape)){const e=r.dataIdMap.get(s.dataId).id;fI(a,zT[t.dtype],n,e)}return s}},gI=XT(bn,0,"bool"),yI=XT(_n,0,"bool"),bI=KT("Log"),_I=XT(xn,0,"bool"),xI=KT(vn),vI=XT(wn,0,"bool"),wI=XT("LogicalXor",0,"bool");let TI;const kI={kernelName:Tn,backendName:"wasm",setupFunc:function(e){TI=e.wasm.cwrap(Tn,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{reductionIndices:a,keepDims:s}=r,{x:o}=n;let i=t.dataIdMap.get(o.dataId).id,u=o;const{transposed:l,axes:c,originalAxes:p,inputWasTransposed:h}=ak(o,a,t);h&&(u=l,i=t.dataIdMap.get(l.dataId).id),Nl("max",c,u.shape.length);const[d,f]=Sl(u.shape,c),m=et(f),g=t.makeOutput(d,o.dtype);if(0!==et(u.shape)){const e=t.dataIdMap.get(g.dataId).id;TI(i,zT[o.dtype],m,e)}if(h&&t.disposeData(l.dataId),s){const e=El(g.shape,p);g.shape=e}return g}},II=XT(kn);let SI;const EI={kernelName:In,backendName:"wasm",setupFunc:function(e){SI=e.wasm.cwrap(In,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,a=t.x,s=r.dataIdMap.get(a.dataId).id;Qe("float32"===a.dtype,(()=>`Error in MaxPool: only float32 input is supported. Got ${a.dtype}.`));const{filterSize:o,strides:i,pad:u,dimRoundingMode:l}=n,c=gu(a.shape,o,i,1,u,l),p=c.filterHeight,h=c.filterWidth,d=c.padInfo.top,f=c.padInfo.right,m=c.padInfo.bottom,g=c.padInfo.left,y=c.dilationHeight,b=c.dilationWidth,_=c.strideHeight,x=c.strideWidth,v=c.inChannels,w=c.outChannels;if("channelsLast"!==c.dataFormat)throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);const T=r.makeOutput(c.outShape,"float32"),k=r.dataIdMap.get(T.dataId).id;return SI(s,a.shape[0],a.shape[1],a.shape[2],p,h,d,f,m,g,y,b,_,x,v,w,k),T}};let NI;const CI={kernelName:Sn,backendName:"wasm",setupFunc:function(e){NI=e.wasm.cwrap(Sn,null,["number, number, number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:a,keepDims:s}=r,{x:o}=n,i=t.dataIdMap.get(o.dataId).id;let u=i,l=o;const{transposed:c,axes:p,originalAxes:h,inputWasTransposed:d}=ak(o,a,t);let f=p;if(d){const e=t.dataIdMap.get(c.dataId).id;e!==i&&(l=c,u=e,f=Rl(f.length,l.shape.length))}Nl("mean",f,l.shape.length);const[m,g]=Sl(l.shape,f),y=et(g);let b=l;"float32"!==l.dtype&&(b=xk({backend:t,inputs:{x:l},attrs:{dtype:"float32"}}),u=t.dataIdMap.get(b.dataId).id);const _=t.makeOutput(m,"float32");if(0!==et(l.shape)){const e=t.dataIdMap.get(_.dataId).id;NI(u,y,e)}if(d&&t.disposeData(c.dataId),s){const e=El(_.shape,h);_.shape=e}return"float32"!==l.dtype&&t.disposeData(b.dataId),_}};let AI;const RI={kernelName:En,backendName:"wasm",setupFunc:function(e){AI=e.wasm.cwrap(En,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:a,keepDims:s}=r,{x:o}=n,i=t.dataIdMap.get(o.dataId).id;let u=i,l=o;const{transposed:c,axes:p,originalAxes:h,inputWasTransposed:d}=ak(o,a,t);if(d){const e=t.dataIdMap.get(c.dataId).id;e!==i&&(l=c,u=e)}Nl("min",p,l.shape.length);const[f,m]=Sl(l.shape,p),g=et(m),y=t.makeOutput(f,l.dtype);if(0!==et(l.shape)){const e=t.dataIdMap.get(y.dataId).id;AI(u,zT[o.dtype],g,e)}if(d&&t.disposeData(c.dataId),s){const e=El(y.shape,h);y.shape=e}return y}},$I=XT(Nn);var MI;let FI;!function(e){e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric"}(MI||(MI={}));const OI={kernelName:Cn,backendName:"wasm",kernelFunc:function(e){const{inputs:{x:t},backend:n,attrs:{paddings:r,mode:a}}=e,s=r.map(((e,n)=>e[0]+t.shape[n]+e[1])),o=n.dataIdMap.get(t.dataId).id,i=n.makeOutput(s,t.dtype),u=n.dataIdMap.get(i.dataId).id,l=new Uint8Array(new Int32Array(t.shape).buffer),c=r.map((e=>e[0])),p=r.map((e=>e[1])),h=new Uint8Array(new Int32Array(c).buffer),d=new Uint8Array(new Int32Array(p).buffer);return FI(o,l,t.shape.length,zT[t.dtype],h,d,MI[a],u),i},setupFunc:function(e){FI=e.wasm.cwrap(Cn,null,["number","array","number","number","array","array","number","number"])}},DI=XT(An),LI=KT("Neg");function PI(e,t){const n=new Int32Array(e.wasm.HEAPU8.buffer,t,4),r=n[0],a=n[1],s=n[2],o=n[3];return e.wasm._free(t),{pSelectedIndices:r,selectedSize:a,pSelectedScores:s,pValidOutputs:o}}let BI;const UI={kernelName:$n,backendName:"wasm",setupFunc:function(e){BI=e.wasm.cwrap($n,"number",["number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{iouThreshold:a,maxOutputSize:s,scoreThreshold:o}=r,{boxes:i,scores:u}=n,l=t.dataIdMap.get(i.dataId).id,c=t.dataIdMap.get(u.dataId).id,p=BI(l,c,s,a,o),{pSelectedIndices:h,selectedSize:d,pSelectedScores:f,pValidOutputs:m}=PI(t,p);return t.wasm._free(f),t.wasm._free(m),t.makeOutput([d],"int32",h)}};let zI;const VI={kernelName:Mn,backendName:"wasm",setupFunc:function(e){zI=e.wasm.cwrap(Mn,"number",["number","number","number","number","number","bool"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{iouThreshold:a,maxOutputSize:s,scoreThreshold:o,padToMaxOutputSize:i}=r,{boxes:u,scores:l}=n,c=t.dataIdMap.get(u.dataId).id,p=t.dataIdMap.get(l.dataId).id,h=zI(c,p,s,a,o,i),{pSelectedIndices:d,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=PI(t,h);return t.wasm._free(m),[t.makeOutput([f],"int32",d),t.makeOutput([],"int32",g)]}};let WI;const HI={kernelName:Fn,backendName:"wasm",setupFunc:function(e){WI=e.wasm.cwrap(Fn,"number",["number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{iouThreshold:a,maxOutputSize:s,scoreThreshold:o,softNmsSigma:i}=r,{boxes:u,scores:l}=n,c=t.dataIdMap.get(u.dataId).id,p=t.dataIdMap.get(l.dataId).id,h=WI(c,p,s,a,o,i),{pSelectedIndices:d,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=PI(t,h);return t.wasm._free(g),[t.makeOutput([f],"int32",d),t.makeOutput([f],"float32",m)]}},GI=XT(Rn,0,"bool");let jI;const KI={kernelName:Dn,backendName:"wasm",setupFunc:function(e){jI=e.wasm.cwrap(Dn,null,["number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:a}=t,{dtype:s,depth:o,onValue:i,offValue:u}=r,l=n.makeOutput([...a.shape,o],s),c=n.dataIdMap.get(l.dataId).id,p=n.dataIdMap.get(a.dataId).id;return jI(p,o,i,u,c),l}},qI={kernelName:On,backendName:"wasm",kernelFunc:function(e){const{inputs:{x:t},backend:n}=e,r=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(r).fill(1),r}},XI={kernelName:Ln,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return Kk({inputs:{input:t[0]},backend:n,attrs:{dim:a}});const s=t[0].shape,o=t[0].dtype;t.forEach((e=>{Je(s,e.shape,"All tensors passed to stack must have matching shapes"),Qe(o===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const i=[],u=Ik({inputs:t.map((e=>{const t=Kk({inputs:{input:e},backend:n,attrs:{dim:a}});return i.push(t),t})),backend:n,attrs:{axis:a}});return i.forEach((e=>n.disposeData(e.dataId))),u}};let YI;const QI={kernelName:Pn,backendName:"wasm",kernelFunc:function(e){const{inputs:{x:t},backend:n,attrs:{paddings:r,constantValue:a}}=e,s=r.map(((e,n)=>e[0]+t.shape[n]+e[1]));if(0===et(t.shape))return Xk({backend:n,attrs:{shape:s,value:a,dtype:t.dtype}});const o=n.dataIdMap.get(t.dataId).id,i=n.makeOutput(s,t.dtype),u=n.dataIdMap.get(i.dataId).id,l=new Uint8Array(new Int32Array(t.shape).buffer),c=r.map((e=>e[0])),p=r.map((e=>e[1])),h=new Uint8Array(new Int32Array(c).buffer),d=new Uint8Array(new Int32Array(p).buffer);return YI(o,l,t.shape.length,zT[t.dtype],h,d,a,u),i},setupFunc:function(e){YI=e.wasm.cwrap(Pn,null,["number","array","number","number","array","array","number","number"])}},JI=XT("Pow");let ZI;const eS={kernelName:Bn,backendName:"wasm",setupFunc:function(e){ZI=e.wasm.cwrap(Bn,null,["number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r,alpha:a}=t,s=n.dataIdMap.get(r.dataId).id,o=n.dataIdMap.get(a.dataId).id;let i=s;const u=r;let l=u;"float32"!==u.dtype&&(l=xk({backend:n,inputs:{x:r},attrs:{dtype:"float32"}}),i=n.dataIdMap.get(l.dataId).id);const c=n.makeOutput(r.shape,"float32"),p=n.dataIdMap.get(c.dataId).id;return ZI(i,o,p),"float32"!==u.dtype&&n.disposeData(l.dataId),c}};let tS;const nS={kernelName:Un,backendName:"wasm",setupFunc:function(e){tS=e.wasm.cwrap(Un,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:a,keepDims:s}=r,{x:o}=n,i=t.dataIdMap.get(o.dataId).id;let u=i,l=o;const{transposed:c,axes:p,originalAxes:h,inputWasTransposed:d}=ak(o,a,t);let f=p;if(d){const e=t.dataIdMap.get(c.dataId).id;e!==i&&(l=c,u=e,f=Rl(f.length,l.shape.length))}Nl("prod",f,l.shape.length);const[m,g]=Sl(l.shape,f),y=et(g),b=t.makeOutput(m,l.dtype);if(0!==et(l.shape)){const e=t.dataIdMap.get(b.dataId).id;tS(u,y,zT[b.dtype],e)}if(d&&t.disposeData(c.dataId),s){const e=El(b.shape,h);b.shape=e}return b}},rS={kernelName:zn,backendName:"wasm",kernelFunc:e=>{const{backend:t,attrs:n}=e,{start:r,stop:a,step:s,dtype:o}=n,i=ng(r,a,s,o),u=t.makeOutput([i.length],o);return t.typedArrayFromHeap(u).set(i),u}},aS=XT(en),sS=KT(Vn),oS=KT(Wn),iS=KT(Kn);let uS;const lS={kernelName:jn,backendName:"wasm",setupFunc:function(e){uS=e.wasm.cwrap(jn,null,["number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{images:a}=n,{alignCorners:s,halfPixelCenters:o,size:i}=r,[u,l]=i,[c,p,h,d]=a.shape,f=[c,u,l,d];let m,g=t.dataIdMap.get(a.dataId);"float32"!==g.dtype&&(m=xk({backend:t,inputs:{x:a},attrs:{dtype:"float32"}}),g=t.dataIdMap.get(m.dataId));const y=g.id,b=t.makeOutput(f,"float32");if(0===et(a.shape))return b;const _=t.dataIdMap.get(b.dataId).id;return uS(y,c,p,h,d,u,l,s?1:0,o?1:0,_),null!=m&&t.disposeData(m.dataId),b}};let cS;const pS={kernelName:Gn,backendName:"wasm",setupFunc:function(e){cS=e.wasm.cwrap(Gn,null,["number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{images:a}=n,{alignCorners:s,halfPixelCenters:o,size:i}=r,[u,l]=i,[c,p,h,d]=a.shape,f=[c,u,l,d],m=t.makeOutput(f,"float32");if(0===et(a.shape))return m;let g,y=t.dataIdMap.get(a.dataId);"float32"!==y.dtype&&(g=xk({backend:t,inputs:{x:a},attrs:{dtype:"float32"}}),y=t.dataIdMap.get(g.dataId));const b=y.id,_=t.dataIdMap.get(m.dataId).id;return cS(b,c,p,h,d,u,l,s?1:0,o?1:0,_),null!=g&&t.disposeData(g.dataId),m}};let hS;const dS={kernelName:qn,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dims:s}=r,o=it(s,a.shape);if(0===a.shape.length)return ZT({inputs:{x:a},backend:n});const i=n.makeOutput(a.shape,a.dtype),u=n.dataIdMap.get(a.dataId).id,l=n.dataIdMap.get(i.dataId).id,c=new Uint8Array(new Int32Array(o).buffer),p=new Uint8Array(new Int32Array(a.shape).buffer);hS(u,c,o.length,p,a.shape.length,l);const h=dk({inputs:{x:i},attrs:{shape:a.shape},backend:n});return n.disposeData(i.dataId),h},setupFunc:function(e){hS=e.wasm.cwrap(qn,null,["number","array","number","array","number","number"])}};let fS;const mS={kernelName:Ir,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:a}=t,{radians:s,fillValue:o,center:i}=r,u=n.makeOutput(a.shape,a.dtype),l=n.dataIdMap.get(a.dataId).id,c=n.dataIdMap.get(u.dataId).id,[p,h,d,f]=a.shape,[m,g]=xd(i,h,d),y="number"==typeof o?[o,o,o,0===o?0:255]:[...o,255],b=new Uint8Array(new Int32Array(y).buffer);return fS(l,p,h,d,f,s,m,g,b,y.length,c),u},setupFunc:function(e){fS=e.wasm.cwrap(Ir,null,["number","number","number","number","number","number","number","number","array","number","number"])}},gS=KT(Xn),yS=KT(Yn);let bS;const _S={kernelName:Qn,backendName:"wasm",setupFunc:function(e){bS=e.wasm.cwrap(Qn,null,["number","number","number","number","number","number","array","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{indices:a,updates:s}=n,{shape:o}=r,i=t.makeOutput(o,s.dtype);if(0===et(o))return i;const{sliceRank:u,numUpdates:l,sliceSize:c,strides:p,outputSize:h}=Di(0,a,o),d=t.dataIdMap.get(a.dataId).id,f=t.dataIdMap.get(s.dataId).id,m=new Uint8Array(new Int32Array(p).buffer),g=t.dataIdMap.get(i.dataId).id;return bS(d,f,zT[s.dtype],u,l,c,m,h,g),i}};let xS;const vS={kernelName:Jn,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:r,t:a,e:s}=t,o=n.dataIdMap.get(r.dataId).id,i=n.dataIdMap.get(a.dataId).id,u=n.dataIdMap.get(s.dataId).id,l=n.makeOutput(a.shape,a.dtype),c=n.dataIdMap.get(l.dataId).id,p=r.shape.length,h=a.shape.length,d=0===p||p>1||1===h?1:et(a.shape.slice(1));return xS(o,i,u,d,c),l},setupFunc:function(e){xS=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}};let wS;const TS={kernelName:"Sigmoid",backendName:"wasm",setupFunc:function(e){wS=e.wasm.cwrap(er,null,["number","number"])},kernelFunc:function(e){const{backend:t,inputs:{x:n}}=e,r=t.dataIdMap.get(n.dataId).id,a=t.makeOutput(n.shape,n.dtype),s=t.dataIdMap.get(a.dataId).id;return 0===et(a.shape)||wS(r,s),a}},kS=KT("Sin");let IS;const SS={kernelName:sr,backendName:"wasm",setupFunc:function(e){IS=e.wasm.cwrap(sr,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:{logits:n},attrs:{dim:r}}=e,a=t.dataIdMap.get(n.dataId).id,s=t.makeOutput(n.shape,n.dtype),o=t.dataIdMap.get(s.dataId).id,i=n.shape[r],u=et(n.shape)/i;return 0===et(s.shape)||IS(a,o,i,u),s}},ES={kernelName:rr,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,paddings:o}=r,i=et(s),u=[[0,0]];u.push(...o);for(let e=1+s.length;e<a.shape.length;++e)u.push([0,0]);const l=QI.kernelFunc({inputs:{x:a},backend:n,attrs:{paddings:u,constantValue:0}}),c=vd(l.shape,s,i,!1),p=wd(c.length,s.length,!1),h=Td(l.shape,s,i,!1),d=dk({inputs:{x:l},backend:n,attrs:{shape:c}}),f=nk({inputs:{x:d},backend:n,attrs:{perm:p}}),m=dk({inputs:{x:f},backend:n,attrs:{shape:h}});return n.disposeData(l.dataId),n.disposeData(d.dataId),n.disposeData(f.dataId),m}};let NS;const CS={kernelName:or,backendName:"wasm",setupFunc:function(e){NS=e.wasm.cwrap("SparseFillEmptyRows","number",["number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n}=e,{indices:r,values:a,denseShape:s,defaultValue:o}=n,i=r.shape[0],u=r.shape[1],l=t.readSync(s.dataId)[0],c=[i+l,u],p=t.dataIdMap.get(r.dataId).id,h=t.dataIdMap.get(a.dataId).id,d=t.dataIdMap.get(o.dataId).id,f=t.makeOutput(c,r.dtype),m=t.dataIdMap.get(f.dataId).id,g=t.makeOutput(c.slice(0,1),a.dtype),y=t.dataIdMap.get(g.dataId).id,b=t.makeOutput([l],"bool"),_=t.dataIdMap.get(b.dataId).id,x=t.makeOutput([i],r.dtype),v=t.dataIdMap.get(x.dataId).id,w=t.makeOutput([4],"int32"),T=t.dataIdMap.get(w.dataId).id,k=NS(p,h,zT[a.dtype],i,l,u,d,m,y,_,v,T),I=t.readSync(w.dataId);let S;switch(I[0]){case 1:S=Ad(I[1]);break;case 2:S=Rd(I[1],I[2]);break;case 3:S=$d(I[1],I[2],I[3]);break;default:S=""}if(t.disposeData(w.dataId),S)throw t.disposeData(f.dataId),t.disposeData(g.dataId),t.disposeData(b.dataId),t.disposeData(x.dataId),new Error(S);let E=f,N=g;return k!==c[0]&&(E=yk({inputs:{x:f},attrs:{begin:0,size:[k,u]},backend:t}),N=yk({inputs:{x:g},attrs:{begin:0,size:k},backend:t}),t.disposeData(f.dataId),t.disposeData(g.dataId)),[E,N,b,x]}};let AS;const RS={kernelName:ir,backendName:"wasm",setupFunc:function(e){AS=e.wasm.cwrap(ir,null,["number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n}=e,{inputIndices:r,inputShape:a,newShape:s}=n;if(2!==r.shape.length)throw new Error(`Input indices should be a matrix but received shape\n ${r.shape}`);if(1!==a.shape.length)throw new Error(`Input shape should be a vector but received shape\n ${a.shape}`);if(1!==s.shape.length)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);const o=t.dataIdMap.get(r.dataId).id,i=t.dataIdMap.get(a.dataId).id,u=t.dataIdMap.get(s.dataId).id,l=r.shape[0],c=et(s.shape),p=t.makeOutput([l,c],r.dtype),h=t.dataIdMap.get(p.dataId).id,d=t.makeOutput([c],s.dtype),f=t.dataIdMap.get(d.dataId).id,m=t.makeOutput([3],"int32"),g=t.dataIdMap.get(m.dataId).id;AS(o,i,u,l,h,f,g);const y=t.readSync(m.dataId);let b;switch(y[0]){case 0:b=Md(y[1],y[2]);break;case 1:b=Fd(y[1],y[2]);break;case 2:b="reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero";break;case 3:b=Od(Array.from(t.readSync(a.dataId)),Array.from(t.readSync(d.dataId)));break;case 4:b=Dd(Array.from(t.readSync(a.dataId)),Array.from(t.readSync(d.dataId)));break;default:b=""}if(t.disposeData(m.dataId),b)throw t.disposeData(p.dataId),t.disposeData(d.dataId),new Error(b);return[p,d]}};let $S;function MS(e){$S=e.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function FS(e,t){const{backend:n,inputs:r}=e,{data:a,indices:s,segmentIds:o}=r,i=s.shape[0],u=n.readSync(o.dataId,i-1,i)[0],l=i>0?u+1:0;if(l<0)throw new Error("segment ids must be >= 0");const c=a.shape.slice();c[0]=l;const p=n.dataIdMap.get(a.dataId).id,h=n.dataIdMap.get(s.dataId).id,d=n.dataIdMap.get(o.dataId).id,f=n.makeOutput(c,a.dtype),m=n.dataIdMap.get(f.dataId).id,g=n.makeOutput([4],"int32"),y=n.dataIdMap.get(g.dataId).id;$S(p,zT[a.dtype],a.shape[0],h,d,m,y,t,0);const b=n.readSync(g.dataId);let _;switch(b[0]){case 0:_="segment ids must be >= 0";break;case 1:_="segment ids are not increasing";break;case 2:_=Ld(b[1],b[2]);break;case 3:_=Pd(b[1],b[2],b[3]);break;default:_=""}if(n.disposeData(g.dataId),_)throw n.disposeData(f.dataId),new Error(_);return f}const OS={kernelName:ur,backendName:"wasm",setupFunc:MS,kernelFunc:function(e){return FS(e,!0)}},DS={kernelName:lr,backendName:"wasm",setupFunc:MS,kernelFunc:function(e){return FS(e,!1)}},LS={kernelName:ar,backendName:"wasm",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:a}=t,{numOrSizeSplits:s,axis:o}=n,i=it(o,a.shape)[0],u=Cd(a,s,i),l=new Array(a.shape.length).fill(0),c=a.shape.slice();return u.map((e=>{const t=[...c];t[i]=e;const n=yk({inputs:{x:a},attrs:{begin:l,size:t},backend:r});return l[i]+=e,n}))}},PS=KT(tr),BS=KT("Square"),US=XT(cr);let zS;const VS={kernelName:Tr,backendName:"wasm",setupFunc:function(e){zS=e.wasm.cwrap(Tr,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{alpha:a}=r,{x:s}=n,o=t.dataIdMap.get(s.dataId).id,i=t.makeOutput(s.shape,s.dtype),u=t.dataIdMap.get(i.dataId).id;return zS(o,a,zT[s.dtype],u),i}};let WS;const HS={kernelName:pr,backendName:"wasm",setupFunc:function(e){WS=e.wasm.cwrap(pr,null,["number","array","number","array","array","array","array","array","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{x:a}=n,{begin:s,end:o,strides:i,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:h}=r,{finalShapeSparse:d,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:_,strides:x}=Yi(a.shape,s,o,i,u,l,c,p,h);let v;if(m)v=dk({inputs:{x:a},backend:t,attrs:{shape:f}});else if(g||y){Qe(a.shape.length>=1,(()=>`Input must have rank at least 1, got: ${a.shape.length}`));const e=Pi(b,_,x),n=yk({inputs:{x:a},backend:t,attrs:{begin:b,size:e}});v=dk({inputs:{x:n},backend:t,attrs:{shape:f}}),t.disposeData(n.dataId)}else{const e=t.makeOutput(d,"float32"),n=t.dataIdMap.get(a.dataId).id,r=new Uint8Array(new Int32Array(yt(a.shape)).buffer),s=new Uint8Array(new Int32Array(b).buffer),o=new Uint8Array(new Int32Array(_).buffer),i=new Uint8Array(new Int32Array(x).buffer),u=new Uint8Array(new Int32Array(d).buffer),l=new Uint8Array(new Int32Array(yt(d)).buffer),c=t.dataIdMap.get(e.dataId).id;WS(n,r,a.shape.length,s,o,i,u,l,d.length,c),v=dk({inputs:{x:e},backend:t,attrs:{shape:f}}),t.disposeData(e.dataId)}return v}},GS={kernelName:hr,backendName:"wasm",kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{data:a,dataSplits:s}=n,{separator:o,nGramWidths:i,leftPad:u,rightPad:l,padWidth:c,preserveShortSequences:p}=r,h=t.readSync(a.dataId),d=t.readSync(s.dataId),[f,m]=fg(h,d,o,i,u,l,c,p),g=t.makeOutput([f.length],"string");t.dataIdMap.get(g.dataId).stringBytes=f;const y=t.makeOutput(s.shape,"int32");return t.typedArrayFromHeap(y).set(m),[g,y]}},jS={kernelName:dr,backendName:"wasm",kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{input:a,delimiter:s}=n,{skipEmpty:o}=r,i=t.readSync(a.dataId),u=t.readSync(s.dataId),[l,c,p]=gg(i,u[0],o),h=c.length,d=t.makeOutput([h,2],"int32");t.typedArrayFromHeap(d).set(l);const f=t.makeOutput([h],"string");t.dataIdMap.get(f.dataId).stringBytes=c;const m=t.makeOutput([2],"int32");return t.typedArrayFromHeap(m).set(p),[d,f,m]}},KS={kernelName:fr,backendName:"wasm",kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{input:a}=n,{numBuckets:s}=r,o=yg(t.readSync(a.dataId),s),i=t.makeOutput(a.shape,"int32");return t.typedArrayFromHeap(i).set(o),i}},qS=XT(mr);let XS;const YS={kernelName:nr,backendName:"wasm",setupFunc:function(e){XS=e.wasm.cwrap(nr,null,["number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:a,keepDims:s}=r,{x:o}=n,i=t.dataIdMap.get(o.dataId).id;let u=i,l=o;const{transposed:c,axes:p,originalAxes:h,inputWasTransposed:d}=ak(o,a,t);let f=p;if(d){const e=t.dataIdMap.get(c.dataId).id;e!==i&&(l=c,u=e,f=Rl(f.length,l.shape.length))}Nl("sum",f,l.shape.length);const[m,g]=Sl(l.shape,f),y=et(g),b=t.makeOutput(m,l.dtype);if(0!==et(l.shape)){const e=t.dataIdMap.get(b.dataId).id;XS(u,y,zT[b.dtype],e)}if(d&&t.disposeData(c.dataId),s){const e=El(b.shape,h);b.shape=e}return b}},QS=KT("Tan"),JS=KT(gr);let ZS;const eE={kernelName:yr,backendName:"wasm",setupFunc:function(e){ZS=e.wasm.cwrap(yr,null,["number","array","number","array","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,s=n.dataIdMap.get(a.dataId).id,{reps:o}=r,i=new Array(a.shape.length);for(let e=0;e<i.length;e++)i[e]=a.shape[e]*o[e];const u=new Uint8Array(new Int32Array(a.shape).buffer),l=new Uint8Array(new Int32Array(i).buffer),c=n.makeOutput(i,a.dtype),p=n.dataIdMap.get(c.dataId).id;return ZS(s,u,a.shape.length,l,i.length,zT[c.dtype],p),c}};let tE;const nE={kernelName:br,backendName:"wasm",setupFunc:function(e){tE=e.wasm.cwrap(br,null,["number","array","number","number","number","bool","number","number"])},kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r}=e,{k:a,sorted:s}=n,o=t.dataIdMap.get(r.dataId).id,i=new Uint8Array(new Int32Array(r.shape).buffer),u=r.shape.slice();u[u.length-1]=a;const l=t.makeOutput(u,r.dtype),c=t.dataIdMap.get(l.dataId).id,p=t.makeOutput(u,"int32"),h=t.dataIdMap.get(p.dataId).id;return tE(o,i,r.shape.length,zT[r.dtype],a,s,c,h),[l,p]}};let rE;const aE={kernelName:_r,backendName:"wasm",setupFunc:function(e){rE=e.wasm.cwrap(_r,null,["number","number","bool","number","number","number","number","number","number","array","number","array","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{image:a,transforms:s}=n,{interpolation:o,fillMode:i,fillValue:u,outputShape:l}=r,[c,p,h,d]=a.shape,[f,m]=null!=l?l:[p,h],g=[c,f,m,d],y=new Uint8Array(new Int32Array(yt(a.shape)).buffer),b=new Uint8Array(new Int32Array(yt(g)).buffer),_=t.makeOutput(g,a.dtype),x=t.dataIdMap.get(_.dataId).id,v=t.dataIdMap.get(a.dataId).id,w=t.dataIdMap.get(s.dataId).id,T="nearest"===o?1:2;let k;switch(i){case"constant":default:k=1;break;case"reflect":k=2;break;case"wrap":k=3;break;case"nearest":k=4}return rE(v,w,s.shape[0]>1,c,f,m,d,h,p,y,a.shape.length-1,b,g.length-1,T,k,u,x),_}},sE={kernelName:vr,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{value:a}=t;let{axis:s}=r;s<0&&(s+=a.shape.length);const o=a.shape[s],i=a.shape.length,u=new Array(i-1);let l=0;for(let e=0;e<i;e++)e!==s&&(u[l++]=a.shape[e]);const c=new Array(o),p=new Array(i).fill(0),h=a.shape.slice();h[s]=1;for(let e=0;e<c.length;e++)p[s]=e,c[e]=yk({inputs:{x:a},attrs:{begin:p,size:h},backend:n});return c.map((({dataId:e,dtype:t})=>({dataId:e,dtype:t,shape:u})))}},oE={kernelName:wr,backendName:"wasm",kernelFunc:function(e){const{inputs:{x:t},backend:n}=e,r=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(r).fill(0),r}},iE=[jT,qT,YT,JT,ok,uk,ck,hk,gk,_k,vk,wk,kk,Sk,Nk,Ak,Rk,$k,Ok,Lk,Bk,zk,Wk,Hk,Gk,jk,qk,Yk,Jk,Zk,eI,nI,aI,oI,uI,cI,pI,hI,ek,dI,mI,gI,yI,bI,_I,xI,vI,wI,kI,II,EI,CI,RI,$I,OI,DI,LI,UI,VI,HI,GI,KI,qI,XI,QI,JI,eS,nS,rS,aS,sS,oS,iS,fk,lS,pS,dS,mS,gS,yS,_S,vS,TS,kS,bk,SS,ES,CS,RS,OS,DS,LS,PS,BS,US,VS,HS,GS,jS,KS,qS,YS,QS,JS,eE,nE,aE,rk,sE,oE];for(const e of iE)Or(e);const uE=Ct();uE.registerFlag("WASM_HAS_SIMD_SUPPORT",(async()=>{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,9,1,7,0,65,0,253,15,26,11]))}catch(e){return!1}})),uE.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",(async()=>{if(uE.get("IS_NODE"))return!1;try{return(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(e){return!1}}));var lE=Xc((function(e,t){var n=(()=>{var e="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0;return e=e||"/Users/kodbiro/Projects/GeometryTracking/xzimg-web-sdk/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out",function(t){function n(){return N.buffer!=$&&z(N.buffer),F}function r(){return N.buffer!=$&&z(N.buffer),O}function a(){return N.buffer!=$&&z(N.buffer),D}function s(){return N.buffer!=$&&z(N.buffer),L}var o,i,u,l=void 0!==(t=t||{})?t:{};l.ready=new Promise((function(e,t){o=e,i=t})),void 0!==He&&He.listeners&&(u={uncaughtException:He.listeners("uncaughtException"),unhandledRejection:He.listeners("unhandledRejection")});var c,p,h,d=Object.assign({},l),f=(e,t)=>{throw t},m="object"==typeof window,g="function"==typeof importScripts,y="object"==typeof He&&"object"==typeof He.versions&&"string"==typeof He.versions.node,b=l.ENVIRONMENT_IS_PTHREAD||!1,_="";function x(e){return l.locateFile?l.locateFile(e,_):_+e}if(y){var v=np,w=np;let e;_=g?w.dirname(_)+"/":"/Users/kodbiro/Projects/GeometryTracking/xzimg-web-sdk/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out/",c=(e,t)=>(e=ee(e)?new URL(e):w.normalize(e),v.readFileSync(e,t?void 0:"utf8")),h=e=>{var t=c(e,!0);return t.buffer||(t=new Uint8Array(t)),t},p=(e,t,n)=>{e=ee(e)?new URL(e):w.normalize(e),v.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},He.argv.length>1&&He.argv[1].replace(/\\/g,"/"),He.argv.slice(2),He.on("uncaughtException",(function(e){if(!(e instanceof re))throw e})),He.on("unhandledRejection",(function(e){throw e})),f=(e,t)=>{if(K())throw He.exitCode=e,t;!function(e){e instanceof re||E("exiting due to exception: "+e)}(t),He.exit(e)},l.inspect=function(){return"[Emscripten Module object]"};try{e=np}catch(e){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),e}qc.Worker=e.Worker}else(m||g)&&(g?_=self.location.href:"undefined"!=typeof document&&document.currentScript&&(_=document.currentScript.src),void 0!==e&&e&&(_=e),_=0!==_.indexOf("blob:")?_.substr(0,_.replace(/[?#].*/,"").lastIndexOf("/")+1):"",y||(c=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},g&&(h=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),p=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)}));y&&"undefined"==typeof performance&&(qc.performance=np.performance);var T=console.log.bind(console),k=console.warn.bind(console);y&&(T=e=>v.writeSync(1,e+"\n"),k=e=>v.writeSync(2,e+"\n"));var I,S=l.print||T,E=l.printErr||k;Object.assign(l,d),d=null,l.arguments&&l.arguments,l.thisProgram&&l.thisProgram,l.quit&&(f=l.quit),l.wasmBinary&&(I=l.wasmBinary);var N,C,A=l.noExitRuntime||!0;"object"!=typeof WebAssembly&&J("no native wasm support detected");var R,$,M,F,O,D,L,P=!1,B="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function U(e,t,n){for(var r=t+n,a=t;e[a]&&!(a>=r);)++a;if(a-t>16&&e.buffer&&B)return B.decode(e.buffer instanceof SharedArrayBuffer?e.slice(t,a):e.subarray(t,a));for(var s="";t<a;){var o=e[t++];if(128&o){var i=63&e[t++];if(192!=(224&o)){var u=63&e[t++];if((o=224==(240&o)?(15&o)<<12|i<<6|u:(7&o)<<18|i<<12|u<<6|63&e[t++])<65536)s+=String.fromCharCode(o);else{var l=o-65536;s+=String.fromCharCode(55296|l>>10,56320|1023&l)}}else s+=String.fromCharCode((31&o)<<6|i)}else s+=String.fromCharCode(o)}return s}function z(e){$=e,l.HEAP8=M=new Int8Array(e),l.HEAP16=new Int16Array(e),l.HEAP32=O=new Int32Array(e),l.HEAPU8=F=new Uint8Array(e),l.HEAPU16=new Uint16Array(e),l.HEAPU32=D=new Uint32Array(e),l.HEAPF32=new Float32Array(e),l.HEAPF64=L=new Float64Array(e)}b&&($=l.buffer);var V,W=l.INITIAL_MEMORY||16777216;if(b)N=l.wasmMemory,$=l.buffer;else if(l.wasmMemory)N=l.wasmMemory;else if(!((N=new WebAssembly.Memory({initial:W/65536,maximum:32768,shared:!0})).buffer instanceof SharedArrayBuffer))throw E("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"),y&&E("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");N&&($=N.buffer),W=$.byteLength,z($);var H=[],G=[],j=[];function K(){return A}function q(){b||le(G)}var X,Y=0,Q=null;function J(e){l.onAbort&&l.onAbort(e),E(e="Aborted("+e+")"),P=!0,R=1,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw i(t),t}function Z(e){return e.startsWith("data:application/octet-stream;base64,")}function ee(e){return e.startsWith("file://")}function te(e){try{if(e==X&&I)return new Uint8Array(I);if(h)return h(e);throw"both async and sync fetching of the wasm failed"}catch(e){J(e)}}Z(X="tfjs-backend-wasm-threaded-simd.wasm")||(X=x(X));var ne={};function re(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function ae(e){var t=ue.pthreads[e];t||J(void 0),ue.returnWorkerToPool(t)}function se(e){var t=ue.getNewWorker();if(!t)return 6;ue.runningWorkers.push(t),ue.pthreads[e.pthread_ptr]=t,t.pthread_ptr=e.pthread_ptr;var n={cmd:"run",start_routine:e.startRoutine,arg:e.arg,pthread_ptr:e.pthread_ptr};return t.runPthread=()=>{y&&t.ref(),t.postMessage(n,e.transferList),delete t.runPthread},t.loaded&&t.runPthread(),0}function oe(e){if(b)return ye(1,1,e);R=e,K()||(ue.terminateAllThreads(),l.onExit&&l.onExit(e),P=!0),f(e,new re(e))}var ie=function(e,t){if(R=e,!t&&b)throw ce(e),"unwind";oe(e)},ue={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init:function(){b?ue.initWorker():ue.initMainThread()},initMainThread:function(){for(var e=8;e--;)ue.allocateUnusedWorker()},initWorker:function(){A=!1},setExitStatus:function(e){R=e},terminateAllThreads:function(){for(var e of Object.values(ue.pthreads))ue.returnWorkerToPool(e);for(var e of ue.unusedWorkers)e.terminate();ue.unusedWorkers=[]},returnWorkerToPool:function(e){var t=e.pthread_ptr;delete ue.pthreads[t],ue.unusedWorkers.push(e),ue.runningWorkers.splice(ue.runningWorkers.indexOf(e),1),e.pthread_ptr=0,y&&e.unref(),De(t)},receiveObjectTransfer:function(e){},threadInitTLS:function(){ue.tlsInitFunctions.forEach((e=>e()))},loadWasmModuleToWorker:function(t,n){t.onmessage=e=>{var r,a=e.data,s=a.cmd;if(t.pthread_ptr&&(ue.currentProxiedOperationCallerThread=t.pthread_ptr),a.targetThread&&a.targetThread!=Ce()){var o=ue.pthreads[a.targetThread];return o?o.postMessage(a,a.transferList):E('Internal error! Worker sent a message "'+s+'" to target pthread '+a.targetThread+", but that thread no longer exists!"),void(ue.currentProxiedOperationCallerThread=void 0)}"processProxyingQueue"===s?me(a.queue):"spawnThread"===s?se(a):"cleanupThread"===s?ae(a.thread):"killThread"===s?function(e){var t=ue.pthreads[e];delete ue.pthreads[e],t.terminate(),De(e),ue.runningWorkers.splice(ue.runningWorkers.indexOf(t),1),t.pthread_ptr=0}(a.thread):"cancelThread"===s?(r=a.thread,ue.pthreads[r].postMessage({cmd:"cancel"})):"loaded"===s?(t.loaded=!0,y&&t.unref(),n&&n(t),t.runPthread&&t.runPthread()):"print"===s?S("Thread "+a.threadId+": "+a.text):"printErr"===s?E("Thread "+a.threadId+": "+a.text):"alert"===s?alert("Thread "+a.threadId+": "+a.text):"setimmediate"===a.target?t.postMessage(a):"callHandler"===s?l[a.handler](...a.args):s&&E("worker sent an unknown command "+s),ue.currentProxiedOperationCallerThread=void 0},t.onerror=e=>{throw E("worker sent an error! "+e.filename+":"+e.lineno+": "+e.message),e},y&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){})));var r=[];for(var a of["onExit","onAbort","print","printErr"])l.hasOwnProperty(a)&&r.push(a);t.postMessage({cmd:"load",handlers:r,urlOrBlob:l.mainScriptUrlOrBlob||e,wasmMemory:N,wasmModule:C})},allocateUnusedWorker:function(){var e,t=x("tfjs-backend-wasm-threaded-simd.worker.js");e=new Worker(t),ue.unusedWorkers.push(e)},getNewWorker:function(){return 0==ue.unusedWorkers.length&&(ue.allocateUnusedWorker(),ue.loadWasmModuleToWorker(ue.unusedWorkers[0])),ue.unusedWorkers.pop()}};function le(e){for(;e.length>0;)e.shift()(l)}function ce(e){if(b)return ye(2,0,e);try{ie(e)}catch(e){!function(e){if(e instanceof re||"unwind"==e)return R;f(1,e)}(e)}}l.PThread=ue,l.establishStackSpace=function(){var e=Ce(),t=r()[e+52>>2],n=r()[e+56>>2];Pe(t,t-n),Ue(t)};var pe,he=[];function de(e,t,n,r){return b?ye(3,1,e,t,n,r):fe(e,t,n,r)}function fe(e,t,n,r){if("undefined"==typeof SharedArrayBuffer)return E("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];if(b&&0===a.length)return de(e,t,n,r);var s={startRoutine:n,pthread_ptr:e,arg:r,transferList:a};return b?(s.cmd="spawnThread",postMessage(s,a),0):se(s)}function me(e){Atomics.store(r(),e>>2,1),Ce()&&Oe(e),Atomics.compareExchange(r(),e>>2,1,0)}function ge(e){ge.shown||(ge.shown={}),ge.shown[e]||(ge.shown[e]=1,y&&(e="warning: "+e),E(e))}function ye(e,t){var n=arguments.length-2,r=arguments;return function(e){var t=Be(),n=e();return Ue(t),n}((()=>{for(var a=n,o=ze(8*a),i=o>>3,u=0;u<n;u++){var l=r[2+u];s()[i+u]=l}return Re(e,a,o,t)}))}l.invokeEntryPoint=function(e,t){var n,r,a=((r=he[n=e])||(n>=he.length&&(he.length=n+1),he[n]=r=V.get(n)),r)(t);K()?ue.setExitStatus(a):Le(a)},l.executeNotifiedProxyingQueue=me,pe=y?()=>{var e=He.hrtime();return 1e3*e[0]+e[1]/1e6}:()=>performance.timeOrigin+performance.now();var be=[];function _e(e){try{return N.grow(e-$.byteLength+65535>>>16),z(N.buffer),1}catch(e){}}function xe(e){return b?ye(4,1,e):52}function ve(e,t,n,r,a){return b?ye(5,1,e,t,n,r,a):70}var we=[null,[],[]];function Te(e,t){var n=we[e];0===t||10===t?((1===e?S:E)(U(n,0)),n.length=0):n.push(t)}function ke(e,t,r,s){if(b)return ye(6,1,e,t,r,s);for(var o=0,i=0;i<r;i++){var u=a()[t>>2],l=a()[t+4>>2];t+=8;for(var c=0;c<l;c++)Te(e,n()[u+c]);o+=l}return a()[s>>2]=o,0}function Ie(e){return l["_"+e]}function Se(e,t,r,a,s){var o={string:e=>{var t=0;if(null!=e&&0!==e){var r=1+(e.length<<2);!function(e,t,r){!function(e,t,n,r){if(!(r>0))return 0;for(var a=n+r-1,s=0;s<e.length;++s){var o=e.charCodeAt(s);if(o>=55296&&o<=57343&&(o=65536+((1023&o)<<10)|1023&e.charCodeAt(++s)),o<=127){if(n>=a)break;t[n++]=o}else if(o<=2047){if(n+1>=a)break;t[n++]=192|o>>6,t[n++]=128|63&o}else if(o<=65535){if(n+2>=a)break;t[n++]=224|o>>12,t[n++]=128|o>>6&63,t[n++]=128|63&o}else{if(n+3>=a)break;t[n++]=240|o>>18,t[n++]=128|o>>12&63,t[n++]=128|o>>6&63,t[n++]=128|63&o}}t[n]=0}(e,n(),t,r)}(e,t=ze(r),r)}return t},array:e=>{var t=ze(e.length);return function(e,t){(N.buffer!=$&&z(N.buffer),M).set(e,t)}(e,t),t}},i=Ie(e),u=[],l=0;if(a)for(var c=0;c<a.length;c++){var p=o[r[c]];p?(0===l&&(l=Be()),u[c]=p(a[c])):u[c]=a[c]}return function(e){return 0!==l&&Ue(l),function(e){return"string"===t?(r=e)?U(n(),r,void 0):"":"boolean"===t?Boolean(e):e;var r}(e)}(i.apply(null,u))}ue.init();var Ee=[null,oe,ce,de,xe,ve,ke],Ne={__emscripten_init_main_thread_js:function(e){Ae(e,!g,1,!m),ue.threadInitTLS()},__emscripten_thread_cleanup:function(e){b?postMessage({cmd:"cleanupThread",thread:e}):ae(e)},__pthread_create_js:fe,_emscripten_default_pthread_stack_size:function(){return 65536},_emscripten_get_now_is_monotonic:function(){return!0},_emscripten_notify_task_queue:function(e,t,n,r){if(e==t)setTimeout((()=>me(r)));else if(b)postMessage({targetThread:e,cmd:"processProxyingQueue",queue:r});else{var a=ue.pthreads[e];if(!a)return;a.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},_emscripten_set_offscreencanvas_size:function(e,t,n){return-1},abort:function(){J("")},emscripten_check_blocking_allowed:function(){y||g||ge("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")},emscripten_date_now:function(){return Date.now()},emscripten_get_heap_max:function(){return 2147483648},emscripten_get_now:pe,emscripten_memcpy_big:function(e,t,r){n().copyWithin(e,t,t+r)},emscripten_num_logical_cores:function(){return y?np.cpus().length:navigator.hardwareConcurrency},emscripten_receive_on_main_thread_js:function(e,t,n){be.length=t;for(var r=n>>3,a=0;a<t;a++)be[a]=s()[r+a];return(e<0?ne[-e-1]:Ee[e]).apply(null,be)},emscripten_resize_heap:function(e){var t=n().length;if((e>>>=0)<=t)return!1;var r=2147483648;if(e>r)return!1;let a=(e,t)=>e+(t-e%t)%t;for(var s=1;s<=4;s*=2){var o=t*(1+.2/s);if(o=Math.min(o,e+100663296),_e(Math.min(r,a(Math.max(e,o),65536))))return!0}return!1},emscripten_unwind_to_js_event_loop:function(){throw"unwind"},exit:ie,fd_close:xe,fd_seek:ve,fd_write:ke,memory:N||l.wasmMemory};!function(){var e={env:Ne,wasi_snapshot_preview1:Ne};function t(e,t){var n,r,a=e.exports;if(l.asm=a,n=l.asm._emscripten_tls_init,ue.tlsInitFunctions.push(n),V=l.asm.__indirect_function_table,r=l.asm.__wasm_call_ctors,G.unshift(r),C=t,!b){var s=ue.unusedWorkers.length;ue.unusedWorkers.forEach((function(e){ue.loadWasmModuleToWorker(e,(function(){--s||function(e){if(Y--,l.monitorRunDependencies&&l.monitorRunDependencies(Y),0==Y&&Q){var t=Q;Q=null,t()}}()}))}))}}function n(e){t(e.instance,e.module)}function r(t){return function(){if(!I&&(m||g)){if("function"==typeof fetch&&!ee(X))return fetch(X,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+X+"'";return e.arrayBuffer()})).catch((function(){return te(X)}));if(p)return new Promise((function(e,t){p(X,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return te(X)}))}().then((function(t){return WebAssembly.instantiate(t,e)})).then((function(e){return e})).then(t,(function(e){E("failed to asynchronously prepare wasm: "+e),J(e)}))}if(b||(Y++,l.monitorRunDependencies&&l.monitorRunDependencies(Y)),l.instantiateWasm)try{return l.instantiateWasm(e,t)}catch(e){E("Module.instantiateWasm callback failed with error: "+e),i(e)}(I||"function"!=typeof WebAssembly.instantiateStreaming||Z(X)||ee(X)||y||"function"!=typeof fetch?r(n):fetch(X,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,e).then(n,(function(e){return E("wasm streaming compile failed: "+e),E("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(i)}(),l.___wasm_call_ctors=function(){return(l.___wasm_call_ctors=l.asm.__wasm_call_ctors).apply(null,arguments)},l._init=function(){return(l._init=l.asm.init).apply(null,arguments)},l._init_with_threads_count=function(){return(l._init_with_threads_count=l.asm.init_with_threads_count).apply(null,arguments)},l._get_threads_count=function(){return(l._get_threads_count=l.asm.get_threads_count).apply(null,arguments)},l._register_tensor=function(){return(l._register_tensor=l.asm.register_tensor).apply(null,arguments)},l._dispose_data=function(){return(l._dispose_data=l.asm.dispose_data).apply(null,arguments)},l._dispose=function(){return(l._dispose=l.asm.dispose).apply(null,arguments)},l._Abs=function(){return(l._Abs=l.asm.Abs).apply(null,arguments)},l._Add=function(){return(l._Add=l.asm.Add).apply(null,arguments)},l._AddN=function(){return(l._AddN=l.asm.AddN).apply(null,arguments)},l._All=function(){return(l._All=l.asm.All).apply(null,arguments)},l._Any=function(){return(l._Any=l.asm.Any).apply(null,arguments)},l._ArgMax=function(){return(l._ArgMax=l.asm.ArgMax).apply(null,arguments)},l._AvgPool=function(){return(l._AvgPool=l.asm.AvgPool).apply(null,arguments)},l._BatchMatMul=function(){return(l._BatchMatMul=l.asm.BatchMatMul).apply(null,arguments)},l._Ceil=function(){return(l._Ceil=l.asm.Ceil).apply(null,arguments)},l._ClipByValue=function(){return(l._ClipByValue=l.asm.ClipByValue).apply(null,arguments)},l._Conv2D=function(){return(l._Conv2D=l.asm.Conv2D).apply(null,arguments)},l._Conv2DBackpropInput=function(){return(l._Conv2DBackpropInput=l.asm.Conv2DBackpropInput).apply(null,arguments)},l._Cos=function(){return(l._Cos=l.asm.Cos).apply(null,arguments)},l._Cosh=function(){return(l._Cosh=l.asm.Cosh).apply(null,arguments)},l._CropAndResize=function(){return(l._CropAndResize=l.asm.CropAndResize).apply(null,arguments)},l._Cumprod=function(){return(l._Cumprod=l.asm.Cumprod).apply(null,arguments)},l._Cumsum=function(){return(l._Cumsum=l.asm.Cumsum).apply(null,arguments)},l._DepthToSpace=function(){return(l._DepthToSpace=l.asm.DepthToSpace).apply(null,arguments)},l._DepthwiseConv2dNative=function(){return(l._DepthwiseConv2dNative=l.asm.DepthwiseConv2dNative).apply(null,arguments)},l._Elu=function(){return(l._Elu=l.asm.Elu).apply(null,arguments)},l._Equal=function(){return(l._Equal=l.asm.Equal).apply(null,arguments)},l._Exp=function(){return(l._Exp=l.asm.Exp).apply(null,arguments)},l._FlipLeftRight=function(){return(l._FlipLeftRight=l.asm.FlipLeftRight).apply(null,arguments)},l._Floor=function(){return(l._Floor=l.asm.Floor).apply(null,arguments)},l._FloorDiv=function(){return(l._FloorDiv=l.asm.FloorDiv).apply(null,arguments)},l._FusedBatchNorm=function(){return(l._FusedBatchNorm=l.asm.FusedBatchNorm).apply(null,arguments)},l._FusedConv2D=function(){return(l._FusedConv2D=l.asm.FusedConv2D).apply(null,arguments)},l._FusedDepthwiseConv2D=function(){return(l._FusedDepthwiseConv2D=l.asm.FusedDepthwiseConv2D).apply(null,arguments)},l._Gather=function(){return(l._Gather=l.asm.Gather).apply(null,arguments)},l._GatherNd=function(){return(l._GatherNd=l.asm.GatherNd).apply(null,arguments)},l._Greater=function(){return(l._Greater=l.asm.Greater).apply(null,arguments)},l._GreaterEqual=function(){return(l._GreaterEqual=l.asm.GreaterEqual).apply(null,arguments)},l._IsNan=function(){return(l._IsNan=l.asm.IsNan).apply(null,arguments)},l._LeakyRelu=function(){return(l._LeakyRelu=l.asm.LeakyRelu).apply(null,arguments)},l._Less=function(){return(l._Less=l.asm.Less).apply(null,arguments)},l._LessEqual=function(){return(l._LessEqual=l.asm.LessEqual).apply(null,arguments)},l._Log=function(){return(l._Log=l.asm.Log).apply(null,arguments)},l._LogicalAnd=function(){return(l._LogicalAnd=l.asm.LogicalAnd).apply(null,arguments)},l._LogicalNot=function(){return(l._LogicalNot=l.asm.LogicalNot).apply(null,arguments)},l._LogicalOr=function(){return(l._LogicalOr=l.asm.LogicalOr).apply(null,arguments)},l._LogicalXor=function(){return(l._LogicalXor=l.asm.LogicalXor).apply(null,arguments)},l._Max=function(){return(l._Max=l.asm.Max).apply(null,arguments)},l._MaxPool=function(){return(l._MaxPool=l.asm.MaxPool).apply(null,arguments)},l._Maximum=function(){return(l._Maximum=l.asm.Maximum).apply(null,arguments)},l._Mean=function(){return(l._Mean=l.asm.Mean).apply(null,arguments)},l._Min=function(){return(l._Min=l.asm.Min).apply(null,arguments)},l._Minimum=function(){return(l._Minimum=l.asm.Minimum).apply(null,arguments)},l._MirrorPad=function(){return(l._MirrorPad=l.asm.MirrorPad).apply(null,arguments)},l._Multiply=function(){return(l._Multiply=l.asm.Multiply).apply(null,arguments)},l._Neg=function(){return(l._Neg=l.asm.Neg).apply(null,arguments)},l._NonMaxSuppressionV3=function(){return(l._NonMaxSuppressionV3=l.asm.NonMaxSuppressionV3).apply(null,arguments)},l._NonMaxSuppressionV4=function(){return(l._NonMaxSuppressionV4=l.asm.NonMaxSuppressionV4).apply(null,arguments)},l._NonMaxSuppressionV5=function(){return(l._NonMaxSuppressionV5=l.asm.NonMaxSuppressionV5).apply(null,arguments)},l._NotEqual=function(){return(l._NotEqual=l.asm.NotEqual).apply(null,arguments)},l._OneHot=function(){return(l._OneHot=l.asm.OneHot).apply(null,arguments)},l._PadV2=function(){return(l._PadV2=l.asm.PadV2).apply(null,arguments)},l._Pow=function(){return(l._Pow=l.asm.Pow).apply(null,arguments)},l._Prelu=function(){return(l._Prelu=l.asm.Prelu).apply(null,arguments)},l._Prod=function(){return(l._Prod=l.asm.Prod).apply(null,arguments)},l._RealDiv=function(){return(l._RealDiv=l.asm.RealDiv).apply(null,arguments)},l._Reciprocal=function(){return(l._Reciprocal=l.asm.Reciprocal).apply(null,arguments)},l._Relu=function(){return(l._Relu=l.asm.Relu).apply(null,arguments)},l._Relu6=function(){return(l._Relu6=l.asm.Relu6).apply(null,arguments)},l._ResizeBilinear=function(){return(l._ResizeBilinear=l.asm.ResizeBilinear).apply(null,arguments)},l._ResizeNearestNeighbor=function(){return(l._ResizeNearestNeighbor=l.asm.ResizeNearestNeighbor).apply(null,arguments)},l._Reverse=function(){return(l._Reverse=l.asm.Reverse).apply(null,arguments)},l._RotateWithOffset=function(){return(l._RotateWithOffset=l.asm.RotateWithOffset).apply(null,arguments)},l._Round=function(){return(l._Round=l.asm.Round).apply(null,arguments)},l._Rsqrt=function(){return(l._Rsqrt=l.asm.Rsqrt).apply(null,arguments)},l._ScatterNd=function(){return(l._ScatterNd=l.asm.ScatterNd).apply(null,arguments)},l._SelectV2=function(){return(l._SelectV2=l.asm.SelectV2).apply(null,arguments)},l._Sigmoid=function(){return(l._Sigmoid=l.asm.Sigmoid).apply(null,arguments)},l._Sin=function(){return(l._Sin=l.asm.Sin).apply(null,arguments)},l._Softmax=function(){return(l._Softmax=l.asm.Softmax).apply(null,arguments)},l._SparseFillEmptyRows=function(){return(l._SparseFillEmptyRows=l.asm.SparseFillEmptyRows).apply(null,arguments)},l._SparseReshape=function(){return(l._SparseReshape=l.asm.SparseReshape).apply(null,arguments)},l._SparseSegmentReduction=function(){return(l._SparseSegmentReduction=l.asm.SparseSegmentReduction).apply(null,arguments)},l._Sqrt=function(){return(l._Sqrt=l.asm.Sqrt).apply(null,arguments)},l._Square=function(){return(l._Square=l.asm.Square).apply(null,arguments)},l._SquaredDifference=function(){return(l._SquaredDifference=l.asm.SquaredDifference).apply(null,arguments)},l._Step=function(){return(l._Step=l.asm.Step).apply(null,arguments)},l._StridedSlice=function(){return(l._StridedSlice=l.asm.StridedSlice).apply(null,arguments)},l._Sub=function(){return(l._Sub=l.asm.Sub).apply(null,arguments)},l._Sum=function(){return(l._Sum=l.asm.Sum).apply(null,arguments)},l._Tan=function(){return(l._Tan=l.asm.Tan).apply(null,arguments)},l._Tanh=function(){return(l._Tanh=l.asm.Tanh).apply(null,arguments)},l._Tile=function(){return(l._Tile=l.asm.Tile).apply(null,arguments)},l._TopK=function(){return(l._TopK=l.asm.TopK).apply(null,arguments)},l._Transform=function(){return(l._Transform=l.asm.Transform).apply(null,arguments)},l._Transpose=function(){return(l._Transpose=l.asm.Transpose).apply(null,arguments)},l.__FusedMatMul=function(){return(l.__FusedMatMul=l.asm._FusedMatMul).apply(null,arguments)},l._malloc=function(){return(l._malloc=l.asm.malloc).apply(null,arguments)},l._free=function(){return(l._free=l.asm.free).apply(null,arguments)},l.__emscripten_tls_init=function(){return(l.__emscripten_tls_init=l.asm._emscripten_tls_init).apply(null,arguments)};var Ce=l._pthread_self=function(){return(Ce=l._pthread_self=l.asm.pthread_self).apply(null,arguments)};l.___errno_location=function(){return(l.___errno_location=l.asm.__errno_location).apply(null,arguments)};var Ae=l.__emscripten_thread_init=function(){return(Ae=l.__emscripten_thread_init=l.asm._emscripten_thread_init).apply(null,arguments)};l.__emscripten_thread_crashed=function(){return(l.__emscripten_thread_crashed=l.asm._emscripten_thread_crashed).apply(null,arguments)},l._emscripten_main_thread_process_queued_calls=function(){return(l._emscripten_main_thread_process_queued_calls=l.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},l._emscripten_main_browser_thread_id=function(){return(l._emscripten_main_browser_thread_id=l.asm.emscripten_main_browser_thread_id).apply(null,arguments)};var Re=l._emscripten_run_in_main_runtime_thread_js=function(){return(Re=l._emscripten_run_in_main_runtime_thread_js=l.asm.emscripten_run_in_main_runtime_thread_js).apply(null,arguments)};l._emscripten_dispatch_to_thread_=function(){return(l._emscripten_dispatch_to_thread_=l.asm.emscripten_dispatch_to_thread_).apply(null,arguments)};var $e,Me,Fe,Oe=l.__emscripten_proxy_execute_task_queue=function(){return(Oe=l.__emscripten_proxy_execute_task_queue=l.asm._emscripten_proxy_execute_task_queue).apply(null,arguments)},De=l.__emscripten_thread_free_data=function(){return(De=l.__emscripten_thread_free_data=l.asm._emscripten_thread_free_data).apply(null,arguments)},Le=l.__emscripten_thread_exit=function(){return(Le=l.__emscripten_thread_exit=l.asm._emscripten_thread_exit).apply(null,arguments)},Pe=l._emscripten_stack_set_limits=function(){return(Pe=l._emscripten_stack_set_limits=l.asm.emscripten_stack_set_limits).apply(null,arguments)},Be=l.stackSave=function(){return(Be=l.stackSave=l.asm.stackSave).apply(null,arguments)},Ue=l.stackRestore=function(){return(Ue=l.stackRestore=l.asm.stackRestore).apply(null,arguments)},ze=l.stackAlloc=function(){return(ze=l.stackAlloc=l.asm.stackAlloc).apply(null,arguments)};function Ve(e){if(!(Y>0)){if(b)return o(l),q(),void startWorker(l);!function(){if(l.preRun)for("function"==typeof l.preRun&&(l.preRun=[l.preRun]);l.preRun.length;)e=l.preRun.shift(),H.unshift(e);var e;le(H)}(),Y>0||(l.setStatus?(l.setStatus("Running..."),setTimeout((function(){setTimeout((function(){l.setStatus("")}),1),t()}),1)):t())}function t(){$e||($e=!0,l.calledRun=!0,P||(q(),o(l),l.onRuntimeInitialized&&l.onRuntimeInitialized(),function(){if(!b){if(l.postRun)for("function"==typeof l.postRun&&(l.postRun=[l.postRun]);l.postRun.length;)e=l.postRun.shift(),j.unshift(e);var e;le(j)}}()))}}if(l.dynCall_iijjiiii=function(){return(l.dynCall_iijjiiii=l.asm.dynCall_iijjiiii).apply(null,arguments)},l.dynCall_jiji=function(){return(l.dynCall_jiji=l.asm.dynCall_jiji).apply(null,arguments)},l.keepRuntimeAlive=K,l.wasmMemory=N,l.cwrap=function(e,t,n,r){var a=(n=n||[]).every((e=>"number"===e||"boolean"===e));return"string"!==t&&a&&!r?Ie(e):function(){return Se(e,t,n,arguments)}},l.ExitStatus=re,l.PThread=ue,Q=function e(){$e||Ve(),$e||(Q=e)},l.preInit)for("function"==typeof l.preInit&&(l.preInit=[l.preInit]);l.preInit.length>0;)l.preInit.pop()();if(Ve(),u&&(Me={uncaughtException:He.listeners("uncaughtException").filter((function(e){return!u.uncaughtException.indexOf(e)>-1})),unhandledRejection:He.listeners("unhandledRejection").filter((function(e){return!u.unhandledRejection.indexOf(e)>-1}))}),"undefined"!=typeof WasmBackendModule)Fe=WasmBackendModule;else{if(void 0===t)throw new Error("Could not find wasm module in post.js");Fe=t}if(Me){var We=Fe._dispose;Fe._dispose=function(){We(),Me.uncaughtException.forEach((function(e){He.removeListener("uncaughtException",e)})),Me.unhandledRejection.forEach((function(e){He.removeListener("unhandledRejection",e)}))}}return t.ready}})();e.exports=n})),cE=e({__proto__:null,default:lE},[lE]),pE=Xc((function(e,t){var n=(()=>{var e="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0;return e=e||"/Users/kodbiro/Projects/GeometryTracking/xzimg-web-sdk/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out",function(t){var n,r,a,s=void 0!==(t=t||{})?t:{};s.ready=new Promise((function(e,t){n=e,r=t})),void 0!==He&&He.listeners&&(a={uncaughtException:He.listeners("uncaughtException"),unhandledRejection:He.listeners("unhandledRejection")});var o,i,u,l=Object.assign({},s),c="object"==typeof window,p="function"==typeof importScripts,h="object"==typeof He&&"object"==typeof He.versions&&"string"==typeof He.versions.node,d="";if(h){var f=np,m=np;d=p?m.dirname(d)+"/":"/Users/kodbiro/Projects/GeometryTracking/xzimg-web-sdk/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out/",o=(e,t)=>(e=L(e)?new URL(e):m.normalize(e),f.readFileSync(e,t?void 0:"utf8")),u=e=>{var t=o(e,!0);return t.buffer||(t=new Uint8Array(t)),t},i=(e,t,n)=>{e=L(e)?new URL(e):m.normalize(e),f.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},He.argv.length>1&&He.argv[1].replace(/\\/g,"/"),He.argv.slice(2),He.on("uncaughtException",(function(e){if(!(e instanceof B))throw e})),He.on("unhandledRejection",(function(e){throw e})),s.inspect=function(){return"[Emscripten Module object]"}}else(c||p)&&(p?d=self.location.href:"undefined"!=typeof document&&document.currentScript&&(d=document.currentScript.src),e&&(d=e),d=0!==d.indexOf("blob:")?d.substr(0,d.replace(/[?#].*/,"").lastIndexOf("/")+1):"",o=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},p&&(u=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),i=(e,t,n)=>{var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?t(r.response):n()},r.onerror=n,r.send(null)});var g,y,b=s.print||console.log.bind(console),_=s.printErr||console.warn.bind(console);Object.assign(s,l),l=null,s.arguments&&s.arguments,s.thisProgram&&s.thisProgram,s.quit&&s.quit,s.wasmBinary&&(g=s.wasmBinary),s.noExitRuntime,"object"!=typeof WebAssembly&&O("no native wasm support detected");var x,v,w,T,k=!1,I="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function S(e,t,n){for(var r=t+n,a=t;e[a]&&!(a>=r);)++a;if(a-t>16&&e.buffer&&I)return I.decode(e.subarray(t,a));for(var s="";t<a;){var o=e[t++];if(128&o){var i=63&e[t++];if(192!=(224&o)){var u=63&e[t++];if((o=224==(240&o)?(15&o)<<12|i<<6|u:(7&o)<<18|i<<12|u<<6|63&e[t++])<65536)s+=String.fromCharCode(o);else{var l=o-65536;s+=String.fromCharCode(55296|l>>10,56320|1023&l)}}else s+=String.fromCharCode((31&o)<<6|i)}else s+=String.fromCharCode(o)}return s}function E(e){x=e,s.HEAP8=v=new Int8Array(e),s.HEAP16=new Int16Array(e),s.HEAP32=new Int32Array(e),s.HEAPU8=w=new Uint8Array(e),s.HEAPU16=new Uint16Array(e),s.HEAPU32=T=new Uint32Array(e),s.HEAPF32=new Float32Array(e),s.HEAPF64=new Float64Array(e)}s.INITIAL_MEMORY;var N,C,A=[],R=[],$=[],M=0,F=null;function O(e){s.onAbort&&s.onAbort(e),_(e="Aborted("+e+")"),k=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw r(t),t}function D(e){return e.startsWith("data:application/octet-stream;base64,")}function L(e){return e.startsWith("file://")}function P(e){try{if(e==N&&g)return new Uint8Array(g);if(u)return u(e);throw"both async and sync fetching of the wasm failed"}catch(e){O(e)}}function B(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function U(e){for(;e.length>0;)e.shift()(s)}function z(e){try{return y.grow(e-x.byteLength+65535>>>16),E(y.buffer),1}catch(e){}}D(N="tfjs-backend-wasm.wasm")||(C=N,N=s.locateFile?s.locateFile(C,d):d+C);var V=[null,[],[]];function W(e,t){var n=V[e];0===t||10===t?((1===e?b:_)(S(n,0)),n.length=0):n.push(t)}function H(e){return s["_"+e]}function G(e,t,n,r,a){var s={string:e=>{var t=0;if(null!=e&&0!==e){var n=1+(e.length<<2);!function(e,t,n){!function(e,t,n,r){if(!(r>0))return 0;for(var a=n+r-1,s=0;s<e.length;++s){var o=e.charCodeAt(s);if(o>=55296&&o<=57343&&(o=65536+((1023&o)<<10)|1023&e.charCodeAt(++s)),o<=127){if(n>=a)break;t[n++]=o}else if(o<=2047){if(n+1>=a)break;t[n++]=192|o>>6,t[n++]=128|63&o}else if(o<=65535){if(n+2>=a)break;t[n++]=224|o>>12,t[n++]=128|o>>6&63,t[n++]=128|63&o}else{if(n+3>=a)break;t[n++]=240|o>>18,t[n++]=128|o>>12&63,t[n++]=128|o>>6&63,t[n++]=128|63&o}}t[n]=0}(e,w,t,n)}(e,t=J(n),n)}return t},array:e=>{var t=J(e.length);return function(e,t){v.set(e,t)}(e,t),t}},o=H(e),i=[],u=0;if(r)for(var l=0;l<r.length;l++){var c=s[n[l]];c?(0===u&&(u=Y()),i[l]=c(r[l])):i[l]=r[l]}return function(e){return 0!==u&&Q(u),function(e){return"string"===t?(n=e)?S(w,n,void 0):"":"boolean"===t?Boolean(e):e;var n}(e)}(o.apply(null,i))}var j={abort:function(){O("")},emscripten_get_heap_max:function(){return 2147483648},emscripten_memcpy_big:function(e,t,n){w.copyWithin(e,t,t+n)},emscripten_resize_heap:function(e){var t=w.length,n=2147483648;if((e>>>=0)>n)return!1;let r=(e,t)=>e+(t-e%t)%t;for(var a=1;a<=4;a*=2){var s=t*(1+.2/a);if(s=Math.min(s,e+100663296),z(Math.min(n,r(Math.max(e,s),65536))))return!0}return!1},fd_close:function(e){return 52},fd_seek:function(e,t,n,r,a){return 70},fd_write:function(e,t,n,r){for(var a=0,s=0;s<n;s++){var o=T[t>>2],i=T[t+4>>2];t+=8;for(var u=0;u<i;u++)W(e,w[o+u]);a+=i}return T[r>>2]=a,0}};!function(){var e={env:j,wasi_snapshot_preview1:j};function t(e,t){var n,r=e.exports;s.asm=r,E((y=s.asm.memory).buffer),s.asm.__indirect_function_table,n=s.asm.__wasm_call_ctors,R.unshift(n),function(e){if(M--,s.monitorRunDependencies&&s.monitorRunDependencies(M),0==M&&F){var t=F;F=null,t()}}()}function n(e){t(e.instance)}function a(t){return function(){if(!g&&(c||p)){if("function"==typeof fetch&&!L(N))return fetch(N,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+N+"'";return e.arrayBuffer()})).catch((function(){return P(N)}));if(i)return new Promise((function(e,t){i(N,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return P(N)}))}().then((function(t){return WebAssembly.instantiate(t,e)})).then((function(e){return e})).then(t,(function(e){_("failed to asynchronously prepare wasm: "+e),O(e)}))}if(M++,s.monitorRunDependencies&&s.monitorRunDependencies(M),s.instantiateWasm)try{return s.instantiateWasm(e,t)}catch(e){_("Module.instantiateWasm callback failed with error: "+e),r(e)}(g||"function"!=typeof WebAssembly.instantiateStreaming||D(N)||L(N)||h||"function"!=typeof fetch?a(n):fetch(N,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,e).then(n,(function(e){return _("wasm streaming compile failed: "+e),_("falling back to ArrayBuffer instantiation"),a(n)}))}))).catch(r)}(),s.___wasm_call_ctors=function(){return(s.___wasm_call_ctors=s.asm.__wasm_call_ctors).apply(null,arguments)},s._init=function(){return(s._init=s.asm.init).apply(null,arguments)},s._init_with_threads_count=function(){return(s._init_with_threads_count=s.asm.init_with_threads_count).apply(null,arguments)},s._get_threads_count=function(){return(s._get_threads_count=s.asm.get_threads_count).apply(null,arguments)},s._register_tensor=function(){return(s._register_tensor=s.asm.register_tensor).apply(null,arguments)},s._dispose_data=function(){return(s._dispose_data=s.asm.dispose_data).apply(null,arguments)},s._dispose=function(){return(s._dispose=s.asm.dispose).apply(null,arguments)},s._Abs=function(){return(s._Abs=s.asm.Abs).apply(null,arguments)},s._Add=function(){return(s._Add=s.asm.Add).apply(null,arguments)},s._AddN=function(){return(s._AddN=s.asm.AddN).apply(null,arguments)},s._All=function(){return(s._All=s.asm.All).apply(null,arguments)},s._Any=function(){return(s._Any=s.asm.Any).apply(null,arguments)},s._ArgMax=function(){return(s._ArgMax=s.asm.ArgMax).apply(null,arguments)},s._AvgPool=function(){return(s._AvgPool=s.asm.AvgPool).apply(null,arguments)},s._BatchMatMul=function(){return(s._BatchMatMul=s.asm.BatchMatMul).apply(null,arguments)},s._Ceil=function(){return(s._Ceil=s.asm.Ceil).apply(null,arguments)},s._ClipByValue=function(){return(s._ClipByValue=s.asm.ClipByValue).apply(null,arguments)},s._Conv2D=function(){return(s._Conv2D=s.asm.Conv2D).apply(null,arguments)},s._Conv2DBackpropInput=function(){return(s._Conv2DBackpropInput=s.asm.Conv2DBackpropInput).apply(null,arguments)},s._Cos=function(){return(s._Cos=s.asm.Cos).apply(null,arguments)},s._Cosh=function(){return(s._Cosh=s.asm.Cosh).apply(null,arguments)},s._CropAndResize=function(){return(s._CropAndResize=s.asm.CropAndResize).apply(null,arguments)},s._Cumprod=function(){return(s._Cumprod=s.asm.Cumprod).apply(null,arguments)},s._Cumsum=function(){return(s._Cumsum=s.asm.Cumsum).apply(null,arguments)},s._DepthToSpace=function(){return(s._DepthToSpace=s.asm.DepthToSpace).apply(null,arguments)},s._DepthwiseConv2dNative=function(){return(s._DepthwiseConv2dNative=s.asm.DepthwiseConv2dNative).apply(null,arguments)},s._Elu=function(){return(s._Elu=s.asm.Elu).apply(null,arguments)},s._Equal=function(){return(s._Equal=s.asm.Equal).apply(null,arguments)},s._Exp=function(){return(s._Exp=s.asm.Exp).apply(null,arguments)},s._FlipLeftRight=function(){return(s._FlipLeftRight=s.asm.FlipLeftRight).apply(null,arguments)},s._Floor=function(){return(s._Floor=s.asm.Floor).apply(null,arguments)},s._FloorDiv=function(){return(s._FloorDiv=s.asm.FloorDiv).apply(null,arguments)},s._FusedBatchNorm=function(){return(s._FusedBatchNorm=s.asm.FusedBatchNorm).apply(null,arguments)},s._FusedConv2D=function(){return(s._FusedConv2D=s.asm.FusedConv2D).apply(null,arguments)},s._FusedDepthwiseConv2D=function(){return(s._FusedDepthwiseConv2D=s.asm.FusedDepthwiseConv2D).apply(null,arguments)},s._Gather=function(){return(s._Gather=s.asm.Gather).apply(null,arguments)},s._GatherNd=function(){return(s._GatherNd=s.asm.GatherNd).apply(null,arguments)},s._Greater=function(){return(s._Greater=s.asm.Greater).apply(null,arguments)},s._GreaterEqual=function(){return(s._GreaterEqual=s.asm.GreaterEqual).apply(null,arguments)},s._IsNan=function(){return(s._IsNan=s.asm.IsNan).apply(null,arguments)},s._LeakyRelu=function(){return(s._LeakyRelu=s.asm.LeakyRelu).apply(null,arguments)},s._Less=function(){return(s._Less=s.asm.Less).apply(null,arguments)},s._LessEqual=function(){return(s._LessEqual=s.asm.LessEqual).apply(null,arguments)},s._Log=function(){return(s._Log=s.asm.Log).apply(null,arguments)},s._LogicalAnd=function(){return(s._LogicalAnd=s.asm.LogicalAnd).apply(null,arguments)},s._LogicalNot=function(){return(s._LogicalNot=s.asm.LogicalNot).apply(null,arguments)},s._LogicalOr=function(){return(s._LogicalOr=s.asm.LogicalOr).apply(null,arguments)},s._LogicalXor=function(){return(s._LogicalXor=s.asm.LogicalXor).apply(null,arguments)},s._Max=function(){return(s._Max=s.asm.Max).apply(null,arguments)},s._MaxPool=function(){return(s._MaxPool=s.asm.MaxPool).apply(null,arguments)},s._Maximum=function(){return(s._Maximum=s.asm.Maximum).apply(null,arguments)},s._Mean=function(){return(s._Mean=s.asm.Mean).apply(null,arguments)},s._Min=function(){return(s._Min=s.asm.Min).apply(null,arguments)},s._Minimum=function(){return(s._Minimum=s.asm.Minimum).apply(null,arguments)},s._MirrorPad=function(){return(s._MirrorPad=s.asm.MirrorPad).apply(null,arguments)},s._Multiply=function(){return(s._Multiply=s.asm.Multiply).apply(null,arguments)},s._Neg=function(){return(s._Neg=s.asm.Neg).apply(null,arguments)},s._NonMaxSuppressionV3=function(){return(s._NonMaxSuppressionV3=s.asm.NonMaxSuppressionV3).apply(null,arguments)},s._NonMaxSuppressionV4=function(){return(s._NonMaxSuppressionV4=s.asm.NonMaxSuppressionV4).apply(null,arguments)},s._NonMaxSuppressionV5=function(){return(s._NonMaxSuppressionV5=s.asm.NonMaxSuppressionV5).apply(null,arguments)},s._NotEqual=function(){return(s._NotEqual=s.asm.NotEqual).apply(null,arguments)},s._OneHot=function(){return(s._OneHot=s.asm.OneHot).apply(null,arguments)},s._PadV2=function(){return(s._PadV2=s.asm.PadV2).apply(null,arguments)},s._Pow=function(){return(s._Pow=s.asm.Pow).apply(null,arguments)},s._Prelu=function(){return(s._Prelu=s.asm.Prelu).apply(null,arguments)},s._Prod=function(){return(s._Prod=s.asm.Prod).apply(null,arguments)},s._RealDiv=function(){return(s._RealDiv=s.asm.RealDiv).apply(null,arguments)},s._Reciprocal=function(){return(s._Reciprocal=s.asm.Reciprocal).apply(null,arguments)},s._Relu=function(){return(s._Relu=s.asm.Relu).apply(null,arguments)},s._Relu6=function(){return(s._Relu6=s.asm.Relu6).apply(null,arguments)},s._ResizeBilinear=function(){return(s._ResizeBilinear=s.asm.ResizeBilinear).apply(null,arguments)},s._ResizeNearestNeighbor=function(){return(s._ResizeNearestNeighbor=s.asm.ResizeNearestNeighbor).apply(null,arguments)},s._Reverse=function(){return(s._Reverse=s.asm.Reverse).apply(null,arguments)},s._RotateWithOffset=function(){return(s._RotateWithOffset=s.asm.RotateWithOffset).apply(null,arguments)},s._Round=function(){return(s._Round=s.asm.Round).apply(null,arguments)},s._Rsqrt=function(){return(s._Rsqrt=s.asm.Rsqrt).apply(null,arguments)},s._ScatterNd=function(){return(s._ScatterNd=s.asm.ScatterNd).apply(null,arguments)},s._SelectV2=function(){return(s._SelectV2=s.asm.SelectV2).apply(null,arguments)},s._Sigmoid=function(){return(s._Sigmoid=s.asm.Sigmoid).apply(null,arguments)},s._Sin=function(){return(s._Sin=s.asm.Sin).apply(null,arguments)},s._Softmax=function(){return(s._Softmax=s.asm.Softmax).apply(null,arguments)},s._SparseFillEmptyRows=function(){return(s._SparseFillEmptyRows=s.asm.SparseFillEmptyRows).apply(null,arguments)},s._SparseReshape=function(){return(s._SparseReshape=s.asm.SparseReshape).apply(null,arguments)},s._SparseSegmentReduction=function(){return(s._SparseSegmentReduction=s.asm.SparseSegmentReduction).apply(null,arguments)},s._Sqrt=function(){return(s._Sqrt=s.asm.Sqrt).apply(null,arguments)},s._Square=function(){return(s._Square=s.asm.Square).apply(null,arguments)},s._SquaredDifference=function(){return(s._SquaredDifference=s.asm.SquaredDifference).apply(null,arguments)},s._Step=function(){return(s._Step=s.asm.Step).apply(null,arguments)},s._StridedSlice=function(){return(s._StridedSlice=s.asm.StridedSlice).apply(null,arguments)},s._Sub=function(){return(s._Sub=s.asm.Sub).apply(null,arguments)},s._Sum=function(){return(s._Sum=s.asm.Sum).apply(null,arguments)},s._Tan=function(){return(s._Tan=s.asm.Tan).apply(null,arguments)},s._Tanh=function(){return(s._Tanh=s.asm.Tanh).apply(null,arguments)},s._Tile=function(){return(s._Tile=s.asm.Tile).apply(null,arguments)},s._TopK=function(){return(s._TopK=s.asm.TopK).apply(null,arguments)},s._Transform=function(){return(s._Transform=s.asm.Transform).apply(null,arguments)},s._Transpose=function(){return(s._Transpose=s.asm.Transpose).apply(null,arguments)},s.__FusedMatMul=function(){return(s.__FusedMatMul=s.asm._FusedMatMul).apply(null,arguments)},s._malloc=function(){return(s._malloc=s.asm.malloc).apply(null,arguments)},s._free=function(){return(s._free=s.asm.free).apply(null,arguments)},s.___errno_location=function(){return(s.___errno_location=s.asm.__errno_location).apply(null,arguments)};var K,q,X,Y=s.stackSave=function(){return(Y=s.stackSave=s.asm.stackSave).apply(null,arguments)},Q=s.stackRestore=function(){return(Q=s.stackRestore=s.asm.stackRestore).apply(null,arguments)},J=s.stackAlloc=function(){return(J=s.stackAlloc=s.asm.stackAlloc).apply(null,arguments)};function Z(e){function t(){K||(K=!0,s.calledRun=!0,k||(U(R),n(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),function(){if(s.postRun)for("function"==typeof s.postRun&&(s.postRun=[s.postRun]);s.postRun.length;)e=s.postRun.shift(),$.unshift(e);var e;U($)}()))}M>0||(function(){if(s.preRun)for("function"==typeof s.preRun&&(s.preRun=[s.preRun]);s.preRun.length;)e=s.preRun.shift(),A.unshift(e);var e;U(A)}(),M>0||(s.setStatus?(s.setStatus("Running..."),setTimeout((function(){setTimeout((function(){s.setStatus("")}),1),t()}),1)):t()))}if(s.dynCall_iijjiiii=function(){return(s.dynCall_iijjiiii=s.asm.dynCall_iijjiiii).apply(null,arguments)},s.dynCall_jiji=function(){return(s.dynCall_jiji=s.asm.dynCall_jiji).apply(null,arguments)},s.cwrap=function(e,t,n,r){var a=(n=n||[]).every((e=>"number"===e||"boolean"===e));return"string"!==t&&a&&!r?H(e):function(){return G(e,t,n,arguments)}},F=function e(){K||Z(),K||(F=e)},s.preInit)for("function"==typeof s.preInit&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();if(Z(),a&&(q={uncaughtException:He.listeners("uncaughtException").filter((function(e){return!a.uncaughtException.indexOf(e)>-1})),unhandledRejection:He.listeners("unhandledRejection").filter((function(e){return!a.unhandledRejection.indexOf(e)>-1}))}),void 0!==t)X=t;else{if("undefined"==typeof WasmBackendModuleThreadedSimd)throw new Error("Could not find wasm module in post.js");X=WasmBackendModuleThreadedSimd}if(q){var ee=X._dispose;X._dispose=function(){ee(),q.uncaughtException.forEach((function(e){He.removeListener("uncaughtException",e)})),q.unhandledRejection.forEach((function(e){He.removeListener("unhandledRejection",e)}))}}return t.ready}})();e.exports=n}));const hE=lE||cE,dE=pE||e({__proto__:null,default:pE},[pE]);class fE extends je{constructor(e){super(),this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(wE),TE=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new Ge(this,yi())}write(e,t,n){const r={id:this.dataIdNextNumber++};return this.move(r,e,t,n,1),r}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){const t=Ta();return e(),{kernelMs:Ta()-t}}move(e,t,n,r,a){const s=this.dataIdNextNumber++;if("string"===r){const o=t;return void this.dataIdMap.set(e,{id:s,stringBytes:o,shape:n,dtype:r,memoryOffset:null,refCount:a})}const o=et(n),i=o*ht(r),u=this.wasm._malloc(i);this.dataIdMap.set(e,{id:s,memoryOffset:u,shape:n,dtype:r,refCount:a}),this.wasm.tfjs.registerTensor(s,o,u),null!=t&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,i),u)}async read(e){return this.readSync(e)}readSync(e,t,n){const{memoryOffset:r,dtype:a,shape:s,stringBytes:o}=this.dataIdMap.get(e);if("string"===a)return null!=t&&0!==t||!(null==n||n>=o.length)?o.slice(t,n):o;t=t||0,n=n||et(s);const i=ht(a);return function(e,t){switch(t){case"float32":return new Float32Array(e);case"int32":return new Int32Array(e);case"bool":return new Uint8Array(e);default:throw new Error(`Unknown dtype ${t}`)}}(this.wasm.HEAPU8.slice(r+t*i,r+n*i).buffer,a)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){const n=this.dataIdMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;this.wasm._free(n.memoryOffset),this.wasm.tfjs.disposeData(n.id),this.dataIdMap.delete(e)}return!0}refCount(e){return this.dataIdMap.has(e)?this.dataIdMap.get(e).refCount:0}incRef(e){const t=this.dataIdMap.get(e);null!=t&&t.refCount++}floatPrecision(){return 32}getMemoryOffset(e){return this.dataIdMap.get(e).memoryOffset}dispose(){this.wasm.tfjs.dispose(),"PThread"in this.wasm&&this.wasm.PThread.terminateAllThreads(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(e,t,n){let r;if(null==n)r=this.write(null,e,t);else{const a=this.dataIdNextNumber++;r={id:a},this.dataIdMap.set(r,{id:a,memoryOffset:n,shape:e,dtype:t,refCount:1});const s=et(e);this.wasm.tfjs.registerTensor(a,s,n)}return{dataId:r,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:n}){const r=this.wasm.HEAPU8.buffer,{memoryOffset:a}=this.dataIdMap.get(n),s=et(e);switch(t){case"float32":return new Float32Array(r,a,s);case"int32":return new Int32Array(r,a,s);case"bool":return new Uint8Array(r,a,s);default:throw new Error(`Unknown dtype ${t}`)}}}function mE(e,t,n){let r="tfjs-backend-wasm.wasm";return e&&t?r="tfjs-backend-wasm-threaded-simd.wasm":e&&(r="tfjs-backend-wasm-simd.wasm"),null!=bE&&null!=bE[r]?bE[r]:n+r}const gE=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"];let yE=null,bE={},_E=!1,xE=!1;function vE(e,t=!1){if(_E)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPaths()` before you call `tf.setBackend()` or `tf.ready()`");if("string"==typeof e)yE=e;else{bE=e;const t=gE.filter((e=>null==bE[e]));if(t.length>0)throw new Error(`There were no entries found for the following binaries: ${t.join(",")}. Please either call setWasmPaths with a map providing a path for each binary, or with a string indicating the directory where all the binaries can be found.`)}xE=t}let wE=-1,TE=null;wi("wasm",(async()=>{const{wasm:e}=await async function(){const[e,t]=await Promise.all([Ct().getAsync("WASM_HAS_SIMD_SUPPORT"),Ct().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise(((n,r)=>{const a={locateFile:(n,r)=>{if(n.endsWith(".worker.js")){const e='"use strict";var Module={};var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads");var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",data=>onmessage({data:data}));var fs=require("fs");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,"utf8")+"//# sourceURL="+f)},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}var initializedJS=false;var pendingNotifiedProxyingQueues=[];function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+"\n");return}console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=(info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports};self.onunhandledrejection=e=>{throw e.reason??e};self.startWorker=instance=>{Module=instance;postMessage({"cmd":"loaded"})};self.onmessage=e=>{try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;for(const handler of e.data.handlers){Module[handler]=function(){postMessage({cmd:"callHandler",handler:handler,args:[...arguments]})}}Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob=="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module)}else if(e.data.cmd==="run"){Module["__emscripten_thread_init"](e.data.pthread_ptr,0,0,1);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInitTLS();if(!initializedJS){pendingNotifiedProxyingQueues.forEach(queue=>{Module["executeNotifiedProxyingQueue"](queue)});pendingNotifiedProxyingQueues=[];initializedJS=true}try{Module["invokeEntryPoint"](e.data.start_routine,e.data.arg)}catch(ex){if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["__emscripten_thread_exit"](ex.status)}}else{throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["__emscripten_thread_exit"](-1)}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processProxyingQueue"){if(initializedJS){Module["executeNotifiedProxyingQueue"](e.data.queue)}else{pendingNotifiedProxyingQueues.push(e.data.queue)}}else if(e.data.cmd){err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){if(Module["__emscripten_thread_crashed"]){Module["__emscripten_thread_crashed"]()}throw ex}};'.replace(/\n/g,"\\n"),t=new Blob([e],{type:"application/javascript"});return URL.createObjectURL(t)}return n.endsWith(".wasm")?mE(e,t,null!=yE?yE:r):r+n}};xE&&(a.instantiateWasm=function(e){return(t,n)=>(function(e,t){return Ct().platform.fetch(e,{credentials:"same-origin"})}(e).then((r=>{r.ok||t.env.a(`failed to load wasm binary file at '${e}'`),r.arrayBuffer().then((e=>{WebAssembly.instantiate(e,t).then((e=>{n(e.instance,e.module)}))}))})),{})}(mE(e,t,null!=yE?yE:"")));let s,o=!1;a.onAbort=()=>{o||_E||(_E=!0,r({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"}))},t&&e?(a.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+hE.toString()],{type:"text/javascript"}),s=hE(a)):s=dE(a),s.then((e=>{o=!0,_E=!1,e.tfjs={init:e.cwrap("init",null,[]),initWithThreadsCount:e.cwrap("init_with_threads_count",null,["number"]),getThreadsCount:e.cwrap("get_threads_count","number",[]),registerTensor:e.cwrap("register_tensor",null,["number","number","number"]),disposeData:e.cwrap("dispose_data",null,["number"]),dispose:e.cwrap("dispose",null,[])},n({wasm:e})})).catch(r)}))}();return new fE(e)}),2);var kE={modelFilename:"",featuresFilename:"",objContainer:"",fovY:50,detectScoreThs:.2,trackScoreThs:.4,footToDetect:"RIGHT_FOOT",filteringLevel:2,filteringShift:.5,validTrackedKeypThs:.2,trackedNumKeypsThs:3,activeIds:new Int32Array};function IE(e){return!!(void 0===e.outputNames||e.outputNames.length<1||e.outputNames.includes("heatmaps"))}function SE(e,t){for(var n=1e4,r=1e4,a=-1e4,s=-1e4,o=0;o<t;o++){var i=e[o],u=e[t+o];i>a&&(a=i),u>s&&(s=u),i<n&&(n=i),u<r&&(r=u)}return[Math.floor(n),Math.floor(a+1),Math.floor(r),Math.floor(s+1)]}function EE(e,t,n){for(var r=1e4,a=1e4,s=-1e4,o=-1e4,i=0;i<n;i++)if(t[i]>0){var u=e[i],l=e[n+i];u>s&&(s=u),l>o&&(o=l),u<r&&(r=u),l<a&&(a=l)}return[Math.floor(r),Math.floor(s+1),Math.floor(a),Math.floor(o+1)]}function NE(e,t){void 0===t&&(t=.1);for(var n=e.length,r=0,a=0,s=new Int32Array(n),o=0;o<n;o++)e[o]>t?(a+=1,s[o]=1,r+=e[o]):s[o]=0;return a>0?r/=a:r=0,{globalScore:r,visibilty:s,totalVisible:a}}function CE(e,t){void 0===t&&(t=.1);for(var n=e.length,r=new Int32Array(n),a=0;a<n;a++)e[a]>t?r[a]=1:r[a]=0;return r}function AE(e,t,n,r){void 0===n&&(n=""),void 0===r&&(r=new Int32Array([-1,-1]));var a=Float32Array.from(e),s=e.length/2;if(""!=n)if("left_right"==n)for(var o=0;o<s;o++)a[o]=r[1]-1-a[o];else if("up_down"==n)for(o=0;o<s;o++)a[o+s]=r[0]-1-a[o+s];for(o=0;o<s;o++){var i=a[o],u=a[o+s];a[o]=t[0]*i+t[1]*u+t[2],a[o+s]=t[3]*i+t[4]*u+t[5]}return a}function RE(e,t){if("UPPER-BODY"==e){if(15==t)return[13,14]}else if("FULL-BODY"==e){if(19==t)return[17,18]}else if("FACE"==e){if(68==t)return[36,45];if(19==t)return[8,13];if(21==t)return[10,15]}else if("HAND"==e){if(7==t)return[0,3];if(21==t)return[0,9];if(10==t)return[7,8];if(8==t)return[5,6];if(11==t)return[7,8];if(9==t)return[1,6]}else{if(5==t)return[1,2];if(14==t)return[1,7];if(20==t)return[2,12];if(7==t)return[0,6];if(19==t)return[10,15];if(9==t)return[1,6];if(23==t)return[0,14];if(181==t)return[30,163];if(44==t)return[19,37]}return console.time("==> (E) Incorrect number of vertices"),[0,1]}function $E(e,t){var n=t.length/2,r=RE(e,n),a=r[0],s=r[1],o=[t[a],t[a+n]],i=[t[s],t[s+n]],u=[(o[0]+i[0])/2,(o[1]+i[1])/2],l=-Math.atan2(o[1]-i[1],i[0]-o[0]);return[u[0],u[1],l]}function ME(e,t,n){for(var r=n[0],a=n[1],s=n[2],o=n[3],i=n[4],u=n[5],l=e.width,c=e.height,p=4*e.width,h=t.width,d=t.height,f=4*t.width,m=0;m<d;m++)for(var g=a*m+s,y=i*m+u,b=m*f,_=0;_<h;_++){var x=4*_,v=Math.floor(g),w=Math.floor(y),T=g-v,k=y-w,I=void 0,S=void 0;if(v>0&&v<l-1&&w>0&&w<c-1){for(var E=w*p+4*v,N=0;N<3;N++,E++){var C=e.data[E];I=C+T*(e.data[E+4]-C),S=e.data[E+p]+T*(e.data[E+p+4]-e.data[E+p]),t.data[b+x+N]=I+k*(S-I)}t.data[b+x+3]=255}else{for(N=0;N<3;N++)t.data[b+x+N]=0;t.data[b+x+3]=255}g+=r,y+=o}return t}var FE,OE=function(){function e(e,t){this.x=e,this.y=t}return e.prototype.Dist=function(e){return Math.sqrt((e.x-this.x)*(e.x-this.x)+(e.y-this.y)*(e.y-this.y))},e}(),DE=function(){function e(e,t){this.x=e,this.y=t}return e.prototype.Dist=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},e.CreateFromPoints=function(t,n){return new e(n.x-t.x,n.y-t.y)},e}(),LE=function(){function e(e,t,n,r){this.x=e,this.y=t,this.w=n,this.h=r}return e.prototype.Centre=function(){return new OE(this.x+this.w/2,this.y+this.h/2)},e.prototype.isPointInside=function(e){return e.x>=this.x&&e.x>=this.x&&e.x<this.x+this.w&&e.y<this.y+this.h},e}();function PE(e,t,n,r,a){void 0===a&&(a=.5);for(var s=e.length/2,o=EE(e,t,s),i=Math.max(o[1]-o[0],o[3]-o[2])/6,u=0;u<s;u++)if(t[u]<=0&&r[u]>0)e[u]=n[u],e[u+s]=n[u+s];else if(t[u]>0&&r[u]<=0);else if(t[u]>0&&r[u]>0){var l=Math.sqrt((n[u]-e[u])*(n[u]-e[u])+(n[u+s]-e[u+s])*(n[u+s]-e[u+s])),c=(1-a)*Math.exp(-.5*l*l/i);e[u]=c*n[u]+(1-c)*e[u],e[u+s]=c*n[u+s]+(1-c)*e[u+s]}return e}function BE(e,t,n,r,a,s,o){void 0===o&&(o=0);for(var i=e.length/2,u=new Float32Array(2*n.length),l=0;l<n.length;l++){var c=n[l];u[l]=e[c],u[l+n.length]=e[c+i]}var p=n.length,h=new OE(0,0);a.forEach((function(e){h.x+=u[e],h.y+=u[e+p]})),h.x/=a.length,h.y/=a.length;var d=r[0],f=r[1],m=new OE(u[d],u[d+p]),g=new OE(u[f],u[f+p]),y=-Math.atan2(g.y-m.y,m.x-g.x)+o,b=0;for(l=0;l<p;l++){var _=new OE(u[l],u[l+p]).Dist(h);_>b&&(b=_)}b*=2;var x=new LE(h.x-b/2,h.y-b/2,b,b),v=Math.cos(y),w=Math.sin(y);b=(x.w+s*x.w)/Math.max(t[0],t[1]);var T=t[1]/2,k=t[0]/2,I=h.x,S=h.y;return new Float32Array([v*b,-w*b,I-(v*b*T-w*b*k),w*b,v*b,S-(w*b*T+v*b*k)])}function UE(e,t){e.length;var n=function(e,t){var n=e.length/2,r=WE(n,t),a=r[0],s=r[1],o=[e[a],e[a+n]],i=[e[s],e[s+n]],u=[(o[0]+i[0])/2,(o[1]+i[1])/2],l=-Math.atan2(o[1]-i[1],i[0]-o[0]),c=Math.sqrt((o[0]-i[0])*(o[0]-i[0])+(o[1]-i[1])*(o[1]-i[1]));return[u[0],u[1],l,c]}(e,t),r=n[0],a=n[1],s=n[2],o=n[3],i=[Math.cos(s),Math.sin(s)],u=[-i[1],i[0]],l=o/1,c=o/2;return[r+i[0]*l+u[0]*c,a+i[1]*l+u[1]*c,r+i[0]*l-u[0]*c,a+i[1]*l-u[1]*c,r-i[0]*l-u[0]*c,a-i[1]*l-u[1]*c,r-i[0]*l+u[0]*c,a-i[1]*l+u[1]*c]}function zE(e,t,n){if(void 0===n&&(n=.1),6==e.length){for(var r=0,a=new Int32Array(3),s=0,o="RIGHT_FOOT"==t?3:0,i=o;i<o+3;i++)r+=e[i],e[i]>n&&(s+=1,a[i]=1);return{globalScore:r/=3,visibilty:a,totalVisible:s}}return NE(e,n)}function VE(e,t,n,r){var a=Float32Array.from(e),s=e.length/2;if(n)for(var o=0;o<s;o++)a[o+s]=r-1-a[o+s];for(o=0;o<s;o++){var i=a[o],u=a[o+s];a[o]=t[0]*i+t[1]*u+t[2],a[o+s]=t[3]*i+t[4]*u+t[5]}return a}function WE(e,t){if(void 0===t&&(t="face"),"face"==t){if(5==e)return[0,1];if(19==e)return[6,11];if(21==e)return[17,20];if(51==e)return[19,28];if(68==e)return[36,45];if(16==e)return[6,9]}return"eye"==t?[0,1]:6==e&&"RIGHT_FOOT"==t?[3,5]:6==e&&"LEFT_FOOT"==t?[0,2]:18!=e||"RIGHT_FOOT"!=t&&"LEFT_FOOT"!=t?13!=e||"RIGHT_FOOT"!=t&&"LEFT_FOOT"!=t?593!=e||"RIGHT_FOOT"!=t&&"LEFT_FOOT"!=t?200!=e||"RIGHT_FOOT"!=t&&"LEFT_FOOT"!=t?(console.error("no type or number of feature match"),[0,1]):[115,167]:[210,78]:[0,6]:[0,9]}function HE(e,t){var n=e.length/2,r=WE(n,t),a=r[0],s=r[1],o=[e[a],e[a+n]],i=[e[s],e[s+n]],u=[(o[0]+i[0])/2,(o[1]+i[1])/2],l=-Math.atan2(o[1]-i[1],i[0]-o[0]);return[u[0],u[1],l]}function GE(e,t,n){for(var r=n[0],a=n[1],s=n[2],o=n[3],i=n[4],u=n[5],l=e.width,c=e.height,p=4*e.width,h=t.width,d=t.height,f=4*t.width,m=0;m<d;m++)for(var g=a*m+s,y=i*m+u,b=m*f,_=0;_<h;_++){var x=4*_,v=Math.floor(g),w=Math.floor(y),T=g-v,k=y-w,I=void 0,S=void 0;if(v>0&&v<l-1&&w>0&&w<c-1){for(var E=w*p+4*v,N=0;N<3;N++,E++){var C=e.data[E];I=C+T*(e.data[E+4]-C),S=e.data[E+p]+T*(e.data[E+p+4]-e.data[E+p]),t.data[b+x+N]=I+k*(S-I)}t.data[b+x+3]=255}else{for(N=0;N<3;N++)t.data[b+x+N]=0;t.data[b+x+3]=255}g+=r,y+=o}return t}function jE(e,t,n,r,a,s){var o,i,u=e.length/2,l=0,c=0,p=0;6==u?(c=(o=HE(e,s))[0],l=o[1],p=o[2],SE("RIGHT_FOOT"==s?[e[3],e[4],e[5],e[3+u],e[4+u],e[5+u]]:[e[0],e[1],e[2],e[0+u],e[1+u],e[2+u]],3)):(c=(i=HE(e,s))[0],l=i[1],p=i[2],EE(e,t,u));var h=Math.cos(p),d=Math.sin(p),f=.5;200==u&&(f=.7);var m=WE(u,s),g=m[0],y=m[1],b=[e[g],e[g+u]],_=[e[y],e[y+u]],x=Math.sqrt((b[0]-_[0])*(b[0]-_[0])+(b[1]-_[1])*(b[1]-_[1])),v=(x+=f*x)/Math.max(r,n),w=(n-1)/2,T=(r-1)/2,k=c-(h*v*w-d*v*T),I=l-(d*v*w+h*v*T);if(null!=a){var S=Math.sqrt((k-a[2])*(k-a[2])+(I-a[5])*(I-a[5])),E=1;S>20&&(E=.1),S>=10&&S<=20&&(E=1-.09*(S-5)),k=(1-E)*k+E*a[2],I=(1-E)*I+E*a[5],p=Math.abs(p-a[6])>1?(1-E)*p-E*a[6]:(1-E)*p+E*a[6],v=(1-E)*v+E*a[7],h=Math.cos(p),d=Math.sin(p)}return[h*v,-d*v,k,d*v,h*v,I,p,v]}function KE(e,t){var n=t.length,r=e._malloc(4*n),a=r/4;return e.HEAPF32.subarray(a,a+n).set(t),r}function qE(e,t){var n=e._malloc(4*t.length);return e.HEAPF32.set(t,n/4),n}function XE(e,t,n){var r=new Float32Array(n),a=t/4;return r.set(e.HEAPF32.subarray(a,a+n)),r.slice()}function YE(e,t,n){var r=new Uint32Array(t.data.buffer),a=r.length,s=n/4;e.HEAPU32.subarray(s,s+a).set(r)}function QE(e,t,n,r){var a=e._malloc(28);return e.setValue(a,n,"i32"),e.setValue(a+4,r,"i32"),e.setValue(a+8,t,"i32"),e.setValue(a+12,0,"i32"),e.setValue(a+16,4,"i32"),e.setValue(a+20,0,"i32"),e.setValue(a+24,0,"i32"),a}function JE(e,t,n,r,a){var s=e.cwrap("xzimgMatchRecKeyps","number",["number","number","number","number","number"]),o=r.length/2;YE(e,t,n);for(var i=QE(e,n,t.width,t.height),u=qE(e,r),l=qE(e,r.slice()),c=e._malloc(4*o),p=0;p<o;p++)e.setValue(c+4*p,1,"float"),a.length>p&&0==a[p]&&e.setValue(c+4*p,-1,"float");var h=e._malloc(16);s(i,u,l,o,c,h);var d=XE(e,c,o),f=XE(e,l,r.length),m=XE(e,h,4);for(p=0;p<o;p++)0==d[p]&&(f[p]=r[p],f[p+o]=r[p+o]);return e._free(i),e._free(u),e._free(l),e._free(c),e._free(h),[f,m,d]}function ZE(e,t,n,r){var a=qE(e,t),s=qE(e,n),o=e._malloc(16);e.cwrap("xzimgEstimateGetSimilarity","number",["number","number","number","number"])(a,s,t.length/2,o);var i=XE(e,o,4);return e._free(a),e._free(s),e._free(o),i}function eN(e,t,n){void 0===n&&(n=null);for(var r=new Float32Array(2),a=e.length/2,s=0,o=0;o<a;o++)(null==n||n[o]>0)&&(r[0]+=t[o]-e[o],r[1]+=t[o+a]-e[o+a],s+=1);return s>0&&(r[0]/=s,r[1]/=s),r}function tN(e,t,n){var r,a,s,o,i;void 0===n&&(n=!0);var u=n?1:2;return r=function(e,t,n,r,a){void 0===a&&(a=1);var s=new Float32Array(r).fill(0),o=new Float32Array(2*r);if(1==a)for(var i=t*n,u=0;u<i;u++)for(var l=0;l<r;l++)(h=e[u*r+l])>s[l]&&(s[l]=h,o[l]=u%n,o[r+l]=Math.floor(u/n));else{var c=n*a;for(u=a;u<t;u+=a,c+=n*a)for(var p=a;p<n;p+=a)for(l=0;l<r;l++){var h;(h=e[(c+p)*r+l])>s[l]&&(s[l]=h,o[l]=p,o[r+l]=u)}}return[o,s]}(e,t[1],t[2],t[3],u),s=r[0],i=r[1],n?(a=function(e,t,n,r,a){for(var s=[-r*a-a,-r*a,-r*a+a,-a,0,a,r*a-a,r*a,r*a+a],o=new Float32Array(a),i=new Float32Array(2*a),u=0;u<a;u++){var l=t[u],c=t[a+u];i[u]=l,i[a+u]=c;var p=c*r*a+l*a+u,h=0;h=0;for(var d=0;d<9;d++)h+=e[p+s[d]];h/=9,o[u]=h;var f=Math.min(l+2,r-1),m=Math.max(l-2,0),g=Math.min(c+2,n-1),y=Math.max(c-2,0),b=0,_=0,x=c*r*a+m*a+u,v=c*r*a+f*a+u;for(d=0;d<9;d++)b+=e[x+s[d]],_+=e[v+s[d]];var w=2*(2*h-((b/=9)+(_/=9)));if(Math.abs(w)>1e-5){var T=2*(_-b)/w;i[u]+=T}var k=0,I=0,S=y*r*a+l*a+u,E=g*r*a+l*a+u;for(d=0;d<9;d++)k+=e[S+s[d]],I+=e[E+s[d]];w=2*(2*h-((k/=9)+(I/=9))),Math.abs(w)>1e-5&&(T=2*(I-k)/w,i[a+u]+=T)}return[i,o]}(e,s,t[1],t[2],t[3]),o=a[0],i=a[1]):o=s,[o,i]}function nN(e,t,n,r,a,s){var o=e.cwrap("xzimgGetHeatmapsLocations","number",["number","number","number","number","number","number","number","number"]),i=t[1]*t[2]*t[3],u=r/4;return e.HEAPF32.subarray(u,u+i).set(n),o(r,t[1],t[2],t[3],0,1,a,s),[new Float32Array(e.HEAPF32.buffer,a,2*t[3]),new Float32Array(e.HEAPF32.buffer,s,t[3])]}function rN(e,t){var n=new ie(0),r=n.asObservable();if("string"==typeof e)return{model$:a=tw({url:e,method:"GET",responseType:"text",async:!0,progressSubscriber:new w((function(e){return n.next(e.loaded/e.total)}),(function(e){}),(function(){return n.next(1)}))}).pipe(ue(2),K((function(e){return aN(e.response,t)}))),progress$:r};var a=be((function(){return n.next(1),j(aN(function(e){var t,n,r="",a=0,s=new Uint8Array(e);for(a=0;a<s.length;a++)if(s[a]<128)r+=String.fromCharCode(s[a]);else{s[a]<224?(t=(63&s[a])<<6,n=a+1):s[a]<240?(t=(31&s[a])<<12,n=a+2):s[a]<248?(t=(15&s[a])<<18,n=a+3):s[a]<252?(t=(7&s[a])<<24,n=a+4):(t=(3&s[a])<<30,n=a+5);do{t|=(127&s[++a])<<6*(n-a)}while(a!=n);r+=String.fromCharCode(t)}return r}(e),t))}));return{model$:a,progress$:r}}function aN(e,t){var n,r,a,s,o={vertices:new Float32Array,uvs:new Float32Array,faces:new Uint16Array},i=e.match(/^v\s+(-?\d+(?:\.\d+)?\s+){2}-?\d+(?:\.\d+)?$/gm);if(i){var u=i.map((function(e){var t=e.split(" ");return t.shift(),t.map((function(e){return+e}))})),l=(n=[]).concat.apply(n,u);o.vertices=new Float32Array(l)}var c=e.match(/^vt( -?\d+(\.\d+)?){2}$/gm);if(c){var p=c.map((function(e){var t=e.split(" ");return t.shift(),t.map((function(e){return+e}))})),h=(r=[]).concat.apply(r,p);o.uvs=new Float32Array(h)}var d=e.match(/^f( \d+\/\d*\/\d*){3}$/gm);if(d){var f=d.map((function(e){var t=e.split(" ");return t.shift(),[+t[0].split("/")[0]-1,+t[1].split("/")[0]-1,+t[2].split("/")[0]-1]})),m=(a=[]).concat.apply(a,f);if(o.faces=new Uint16Array(m),t){var g=d.map((function(e){var t=e.split(" ");return t.shift(),[+t[0].split("/")[1]-1,+t[1].split("/")[1]-1,+t[2].split("/")[1]-1]})),y=new Uint16Array((s=[]).concat.apply(s,g)),b=o.uvs;o.uvs=new Float32Array(b.length);for(var _=0;_<y.length;_++){var x=y[_],v=b[2*x],w=b[2*x+1],T=o.faces[_];o.uvs[2*T]=v,o.uvs[2*T+1]=w}}}if(t){for(_=0;_<o.faces.length;_+=3){var k=o.faces[_];o.faces[_]=o.faces[_+1],o.faces[_+1]=k}for(_=0;_<o.vertices.length;_+=3)o.vertices[_]=-o.vertices[_]}return o}!function(e){e.Detection="DETECTION",e.Detected="DETECTED",e.Tracking="TRACKING"}(FE||(FE={}));var sN,oN=function(){function e(e,t){this._trackingState=FE.Detection,this._type=0,this._R=Float32Array.from(e),this._t=Float32Array.from(t),this._trackingState=FE.Detection}return e.prototype.setTrackingState=function(e){this._trackingState=e},e.prototype.getTrackingState=function(){return this._trackingState},e.prototype.isDetected=function(){return this._trackingState==FE.Tracking},Object.defineProperty(e.prototype,"type",{get:function(){return this._type},set:function(e){this._type=e},enumerable:!1,configurable:!0}),e.prototype.setRt=function(e,t){this._R=e.slice(0),this._t=t.slice(0)},e.prototype.setR=function(e){this._R=e.slice(0)},e.prototype.R=function(){return this._R},e.prototype.t=function(){return this._t},e.prototype.getPosition=function(){return[this._t[0],this._t[1],this._t[2]]},e.prototype.getRotation=function(){return[[this._R[0],this._R[1],this._R[2]],[this._R[3],this._R[4],this._R[5]],[this._R[6],this._R[7],this._R[8]]]},e.prototype.getRot=function(){return this._R},e.prototype.updateRotation=function(e){this._R=Float32Array.from(e)},e.prototype.translate=function(e,t,n){this._t[0]+=e,this._t[1]+=t,this._t[2]+=n},e.prototype.reset=function(){this._R=new Float32Array([1,0,0,0,-1,0,0,0,-1]),this._t=new Float32Array([0,0,0])},e.prototype.det=function(){return this._R[0]*(this._R[4]*this._R[8]-this._R[7]*this._R[5])-this._R[3]*(this._R[1]*this._R[8]-this._R[7]*this._R[2])+this._R[6]*(this._R[1]*this._R[5]-this._R[4]*this._R[2])},e.convert3x3Mat=function(e){return new Float32Array([e[0][0],e[0][1],e[0][2],e[1][0],e[1][1],e[1][2],e[2][0],e[2][1],e[2][2]])},e.convert3x3Mat_t=function(e){return new Float32Array([e[0][0],e[1][0],e[2][0],e[0][1],e[1][1],e[2][1],e[0][2],e[1][3],e[2][2]])},e.getQuatFromRotMat=function(e){var t=new Float32Array(4);return t[0]=Math.sqrt(Math.max(0,1+e[0]+e[4]+e[8]))/2,t[1]=Math.sqrt(Math.max(0,1+e[0]-e[4]-e[8]))/2,t[2]=Math.sqrt(Math.max(0,1-e[0]+e[4]-e[8]))/2,t[3]=Math.sqrt(Math.max(0,1-e[0]-e[4]+e[8]))/2,t[1]=e[7]-e[5]<0?-Math.abs(t[1]):Math.abs(t[1]),t[2]=e[2]-e[6]<0?-Math.abs(t[2]):Math.abs(t[2]),t[3]=e[3]-e[1]<0?-Math.abs(t[3]):Math.abs(t[3]),t},e.getRotMatFromQuat=function(e){var t=new Float32Array(9);return t[0]=1-2*e[2]*e[2]-2*e[3]*e[3],t[1]=2*e[1]*e[2]-2*e[3]*e[0],t[2]=2*e[1]*e[3]+2*e[2]*e[0],t[3]=2*e[1]*e[2]+2*e[3]*e[0],t[4]=1-2*e[1]*e[1]-2*e[3]*e[3],t[5]=2*e[2]*e[3]-2*e[1]*e[0],t[6]=2*e[1]*e[3]-2*e[2]*e[0],t[7]=2*e[2]*e[3]+2*e[1]*e[0],t[8]=1-2*e[1]*e[1]-2*e[2]*e[2],t},e.slerp=function(e,t,n){var r,a,s=new Float32Array(4),o=e[1]*t[1]+e[2]*t[2]+e[3]*t[3]+e[0]*t[0],i=Math.abs(o);if(i>=.99999)r=1-n,a=n;else{var u=Math.acos(i),l=Math.sin(u);r=Math.sin((1-n)*u)/l,a=Math.sin(n*u)/l}return o<0&&(a=-a),s[1]=r*e[1]+a*t[1],s[2]=r*e[2]+a*t[2],s[3]=r*e[3]+a*t[3],s[0]=r*e[0]+a*t[0],s},e.getCameraMat=function(e,t,n){var r=n/2/Math.tan(e*Math.PI/180/2),a=r,s=(t-1)/2,o=(n-1)/2,i=new Float32Array(9);return i[0]=a,i[2]=s,i[4]=r,i[5]=o,i[8]=1,i},e.getCameraParams=function(e,t,n){var r=n/2/Math.tan(e*Math.PI/180/2);return[r,r,(t-1)/2,(n-1)/2]},e.MatMultVec=function(e,t){var n=new Float32Array(3);return n[0]=e[0]*t[0]+e[1]*t[1]+e[2]*t[2],n[1]=e[3]*t[0]+e[4]*t[1]+e[5]*t[2],n[2]=e[6]*t[0]+e[7]*t[1]+e[8]*t[2],n},e.MatMult=function(e,t){var n=new Float32Array(9);return n[0]=e[0]*t[0]+e[1]*t[3]+e[2]*t[6],n[1]=e[0]*t[1]+e[1]*t[4]+e[2]*t[7],n[2]=e[0]*t[2]+e[1]*t[5]+e[2]*t[8],n[3]=e[3]*t[0]+e[4]*t[3]+e[5]*t[6],n[4]=e[3]*t[1]+e[4]*t[4]+e[5]*t[7],n[5]=e[3]*t[2]+e[4]*t[5]+e[5]*t[8],n[6]=e[6]*t[0]+e[7]*t[3]+e[8]*t[6],n[7]=e[6]*t[1]+e[7]*t[4]+e[8]*t[7],n[8]=e[6]*t[2]+e[7]*t[5]+e[8]*t[8],n},e.prototype.project=function(t,n){for(var r=new Float32Array(t.length/3*2),a=0;a<t.length/3;a++){var s=e.MatMultVec(this._R,new Float32Array([t[3*a],t[3*a+1],t[3*a+2]])),o=new Float32Array(3);o[0]=s[0]+this._t[0],o[1]=s[1]+this._t[1],o[2]=s[2]+this._t[2];var i=n[6]*o[0]+n[7]*o[1]+n[8]*o[2];r[2*a]=(n[0]*o[0]+n[1]*o[1]+n[2]*o[2])/i,r[2*a+1]=(n[3]*o[0]+n[4]*o[1]+n[5]*o[2])/i}return r},e.prototype.transform=function(t,n){for(var r=new Float32Array(t.length/3*2),a=0;a<t.length/3;a++){var s=e.MatMultVec(this._R,new Float32Array([t[3*a],t[3*a+1],t[3*a+2]]));r[3*a+0]=s[0]+this._t[0],r[3*a+1]=s[1]+this._t[1],r[3*a+2]=s[2]+this._t[2]}return r},e.prototype.transformInv=function(t){var n=new Float32Array(3),r=new Float32Array([this._R[0],this._R[3],this._R[6],this._R[1],this._R[4],this._R[7],this._R[2],this._R[5],this._R[8]]),a=e.MatMultVec(r,t),s=e.MatMultVec(r,this._t);return n[0]=a[0]-s[0],n[1]=a[1]-s[1],n[2]=a[2]-s[2],n},e}(),iN=function(){function e(e){this.NB_BUFFERS=6,this._poses=[],this._nbFramesDelay=0,this._interpolation=0,this._filteringLevel=2,this._filterThreshold=-1,e>=0&&e<this.NB_BUFFERS?this._nbFramesDelay=this._nbFramesDelay:console.error("Invalid frames delay, delay must be less than ",this.NB_BUFFERS)}return e.prototype.setNbFramesDelay=function(e){this._nbFramesDelay=e},e.prototype.setInterpolation=function(e){this._interpolation=e},e.prototype.setFilteringLevel=function(e){this._filteringLevel=e},e.prototype.setFilterThreshold=function(e){this._filterThreshold=e},e.prototype.reset=function(){this._poses=[]},e.prototype.setPose=function(e){this._poses.length===this.NB_BUFFERS&&(this._poses=this._poses.slice(0,-1)),this._poses=o([e],this._poses,!0)},e.prototype.getPose=function(){return this._poses.length>0?this._nbFramesDelay<this._poses.length?this._poses[this._nbFramesDelay]:this._poses[this._poses.length-1]:null},e.prototype.getInterpolatedPoseAtDelay=function(e){if(e>0&&e+1<this._poses.length){var t=this._poses[e-1],n=this._poses[e],r=this._poses[e+1];if(t.getTrackingState()!==FE.Tracking||r.getTrackingState()!==FE.Tracking)return n;for(var a=oN.getQuatFromRotMat(t.R()),s=oN.getQuatFromRotMat(r.R()),o=oN.slerp(a,s,.5),i=oN.getRotMatFromQuat(o),u=t.t(),l=r.t(),c=new Float32Array(3),p=0;p<3;p++)c[p]=.5*u[p]+.5*l[p];var h=new oN(i,c);return h.setTrackingState(n.getTrackingState()),h.type=n.type,h}return this._poses.length>0?this.getPose():this.getLastPose()},e.prototype.dst=function(e,t){return Math.sqrt((e[0]-t[0])*(e[0]-t[0])+(e[1]-t[1])*(e[1]-t[1])+(e[2]-t[2])*(e[2]-t[2]))},e.prototype.mvts=function(e,t,n){return(this.dst(e,t)+this.dst(t,n))/2},e.prototype.getInterpolatedPose=function(){if(1==this._filteringLevel)return this.getInterpolatedPoseAtDelay(this._nbFramesDelay);if(2==this._filteringLevel){var e=this.getInterpolatedPoseAtDelay(this._nbFramesDelay-1),t=this.getInterpolatedPoseAtDelay(this._nbFramesDelay+1);if(null==e||null==t)return this.getInterpolatedPoseAtDelay(this._nbFramesDelay);if(e.getTrackingState()!==FE.Tracking||t.getTrackingState()!==FE.Tracking)return this.getInterpolatedPoseAtDelay(this._nbFramesDelay);var n=this._poses[this._nbFramesDelay],r=e.t(),a=t.t();if(this._filterThreshold>0){var s=this.dst(r,n.t()),o=this.dst(a,n.t());if(s>this._filterThreshold||o>this._filterThreshold)return n}for(var i=oN.getQuatFromRotMat(e.R()),u=oN.getQuatFromRotMat(t.R()),l=oN.slerp(i,u,this._interpolation),c=oN.getRotMatFromQuat(l),p=new Float32Array(3),h=0;h<3;h++)p[h]=(1-this._interpolation)*r[h]+this._interpolation*a[h];var d=new oN(c,p);return d.setTrackingState(n.getTrackingState()),d.type=n.type,d}return this.getLastPose()},e.prototype.updateDelay=function(e){e!=this._nbFramesDelay&&(e>=0&&e<this.NB_BUFFERS?this._nbFramesDelay=e:console.error("Invalid frames delay, delay must be less than ",this.NB_BUFFERS))},e.prototype.getLastPose=function(){return this._poses.length>0?this._poses[0]:null},e}();!function(e){e.Left="LEFT_FOOT",e.Right="RIGHT_FOOT",e.Both="BOTH_FOOT",e.Single="SINGLE_FOOT"}(sN||(sN={}));var uN,lN="config.bin",cN=function(){function e(){this._initialized=!1,this._currentWidth=0,this._currentHeight=0,this._trackingState=FE.Detection,this._useWasmForHeatmaps=!1,this._float_size=4,this._bufferHeatmaps=null,this._bufferKeypsDet=null,this._bufferFeatureScores=null,this._bufKeyps3D_R=null,this._bufKeyps3D_L=null,this._footToDetect=sN.Right,this._leftFootState=FE.Detection,this._rightFootState=FE.Detection,this._bufferKeypsTrack_L=null,this._bufferKeypsTrack_R=null,this._bufferHeatmaps_L=null,this._bufferHeatmaps_R=null,this._fastMovements_L=!1,this._fastMovements_R=!1,this._cnnOutputDataInvMask=null,this._trackHasHeatmaps=!0,this._debug=!1,this._debugInitialized=!1,this._reproj_t=15,this._reproj_fast_t=30,this._isDetected=!1}return e.prototype.getDebugImage=function(){return this._debugInitialized?this._debugImage:null},e.prototype.isDetected=function(){return this._isDetected},e.prototype.getPosition=function(e){void 0===e&&(e=sN.Right);var t=null;return(t=e==sN.Right?this._poseManager_R.getInterpolatedPose():this._poseManager_L.getInterpolatedPose())?t.getPosition():null},e.prototype.getRotation=function(e){void 0===e&&(e=sN.Right);var t=null;return(t=e==sN.Right?this._poseManager_R.getInterpolatedPose():this._poseManager_L.getInterpolatedPose())?t.getRotation():null},e.prototype.getPose=function(e){return void 0===e&&(e=sN.Right),e==sN.Right?this._pose_L:this._pose_R},e.prototype.getInterpolatedPose=function(e){return void 0===e&&(e=sN.Right),e==sN.Right?this._poseManager_R.getInterpolatedPose():this._poseManager_L.getInterpolatedPose()},e.prototype.isInitialized=function(){return this._initialized},e.prototype.initialize=function(e,n,r){var o,i,u,l;return a(this,void 0,void 0,(function(){var a,c,p,h,d,f,m,g,y,b,_,x,v=this;return s(this,(function(s){switch(s.label){case 0:if(null==e)throw"Invalid parameter";return this._config=n?t(t({},kE),n):kE,(null===(o=null==n?void 0:n.wasmBackend)||void 0===o?void 0:o.enable)?(vE({"tfjs-backend-wasm.wasm":null===(i=n.wasmBackend)||void 0===i?void 0:i.tfjsBackendWasmPath,"tfjs-backend-wasm-simd.wasm":null===(u=n.wasmBackend)||void 0===u?void 0:u.tfjsBackendWasmSimdPath,"tfjs-backend-wasm-threaded-simd.wasm":null===(l=n.wasmBackend)||void 0===l?void 0:l.tfjsBackendWasmThreadedPath}),[4,vi("wasm")]):[3,2];case 1:return s.sent(),[3,3];case 2:vi("webgl"),s.label=3;case 3:return this.release(),this._videoManager=e,"BOTH"!==this._config.footToDetect&&"BOTH_FEET"!==this._config.footToDetect||(this._footToDetect=sN.Both),this._poseManager_R=new iN(this._videoManager.getNbFramesDelay()),this._poseManager_R.setInterpolation(this._config.filteringShift),this._poseManager_R.setFilteringLevel(this._config.filteringLevel),this._poseManager_R.setFilterThreshold(.1),this._poseManager_L=new iN(this._videoManager.getNbFramesDelay()),this._poseManager_L.setInterpolation(this._config.filteringShift),this._poseManager_L.setFilteringLevel(this._config.filteringLevel),this._poseManager_L.setFilterThreshold(.1),a=new ie(0),c=G(HT({locateFile:function(e,t){return v._config.poseEstimationWasmFilename||t+e}})).pipe(me((function(){return a.next(1)}))),p=OT(this._config.modelFilename,lN),h=p.model$,d=p.progress$,f=OT(this._config.featuresFilename,lN),m=f.model$,g=f.progress$,y=rN(this._config.objContainer,!1),b=y.model$,_=y.progress$,x=V([a,d,g,_]).pipe(K((function(e){return e.reduce((function(t,n){return t+n/e.length}),0)})),K((function(e){return r&&r(e)}))).subscribe(),[4,Lv({poseModule:c,model:h,features:m,footObjModel:b}).pipe(K((function(e){var t;v._poseModule=e.poseModule,v._footObjModel=e.footObjModel,v._tfFootDetector=e.model.graphModel,v._footDetectorConfig=e.model.config,v._tfFootFeatures=e.features.graphModel,v._footFeaturesConfig=e.features.config,v._activeIds=v._config.activeIds;var n=Tc([1,v._footDetectorConfig.inHeight,v._footDetectorConfig.inWidth,3]),r=v._tfFootDetector.predict(n);v._footDetectorShape=r.shape,r.dataSync(),r.dispose(),n.dispose();var a=v._footDetectorConfig.outChannels;n=Tc([1,v._footFeaturesConfig.inHeight,v._footFeaturesConfig.inWidth,3]),(r=v._tfFootFeatures.predict(n))instanceof Array?r.forEach((function(e){return e.dispose()})):r.dispose(),n.dispose(),n=Tc([2,v._footFeaturesConfig.inHeight,v._footFeaturesConfig.inWidth,3]),(r=v._tfFootFeatures.predict(n))instanceof Array?r.forEach((function(e){return e.dispose()})):r.dispose(),n.dispose();var s=v._footFeaturesConfig.outChannels;if(v._footFeaturesConfig.outputNames&&v._footFeaturesConfig.numOutputs&&v._footFeaturesConfig.numOutputs>1)for(var o=0,i=0,u=v._footFeaturesConfig.outputNames;i<u.length;i++){var l=u[i];"heatmaps"==l?s=v._footFeaturesConfig.outputDims[3*o+2]:"coordinates"==l&&(s=v._footFeaturesConfig.outputDims[3*o+2]/2),o+=1}if(t=function(e,t){var n=Array.from(Array(t).keys());13==t&&(n=[54,210,295,415,416,425,463,582,644,721,726,730,813]),18==t&&(n=[54,210,295,406,415,416,417,423,425,463,518,582,644,657,721,726,730,813]);for(var r=n.length,a=new Float32Array(3*r),s=0;s<r;s++){var o=n[s];a[3*s]=e[3*o],a[3*s+1]=e[3*o+1],a[3*s+2]=e[3*o+2]}var i=new Float32Array(3*r);for(s=0;s<r;s++)i[3*s]=-a[3*s],i[3*s+1]=a[3*s+1],i[3*s+2]=a[3*s+2];return[a,i]}(v._footObjModel.vertices,s),v._rightKeyps3D=t[0],v._leftKeyps3D=t[1],v._bufKeyps3D_R=v._poseModule._malloc(v._rightKeyps3D.length*v._float_size),v._poseModule.HEAPF32.set(v._rightKeyps3D,v._bufKeyps3D_R/4),v._bufKeyps3D_L=v._poseModule._malloc(v._leftKeyps3D.length*v._float_size),v._poseModule.HEAPF32.set(v._leftKeyps3D,v._bufKeyps3D_L/4),v._footDetectorConfig.outWidth>1&&v._footDetectorConfig.outHeight>1){var c=a*v._footDetectorConfig.outWidth*v._footDetectorConfig.outHeight;v._bufferHeatmaps=v._poseModule._malloc(c*v._float_size)}v._footFeaturesConfig.outWidth>1&&v._footFeaturesConfig.outHeight>1&&(c=s*v._footFeaturesConfig.outWidth*v._footFeaturesConfig.outHeight,v._bufferHeatmaps_L=v._poseModule._malloc(c*v._float_size),v._bufferHeatmaps_R=v._poseModule._malloc(c*v._float_size)),v._bufferKeypsDet=v._poseModule._malloc(2*a*v._float_size),v._bufferKeypsTrack_L=v._poseModule._malloc(2*s*v._float_size),v._bufferKeypsTrack_R=v._poseModule._malloc(2*s*v._float_size),v._bufferFeatureScores=v._poseModule._malloc(s*v._float_size),v._pose_R=new oN(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0])),v._pose_L=new oN(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0])),v._trackHasHeatmaps=IE(v._footFeaturesConfig),v._initialized=!0})),Z((function(){return x.unsubscribe()}))).toPromise()];case 4:return s.sent(),[2]}}))}))},e.prototype.release=function(){this._initialized&&(this._poseModule._free(this._bufferHeatmaps),this._bufferHeatmaps_L&&this._poseModule._free(this._bufferHeatmaps_L),this._bufferHeatmaps_R&&this._poseModule._free(this._bufferHeatmaps_R),this._bufferKeypsDet&&this._poseModule._free(this._bufferKeypsDet),this._poseModule._free(this._bufferKeypsTrack_L),this._poseModule._free(this._bufferKeypsTrack_R),this._poseModule._free(this._bufferFeatureScores),this._poseModule._free(this._bufKeyps3D_R),this._poseModule._free(this._bufKeyps3D_L),this._hptrImageBuffer&&this._poseModule._free(this._hptrImageBuffer))},e.prototype.trackSync=function(e){var t;if(this._initialized){var n=this._videoManager.getVideoCanvas();n.width===this._currentWidth&&n.height===this._currentHeight||(this._currentWidth=n.width,this._currentHeight=n.height,t=oN.getCameraParams(this._config.fovY,this._currentWidth,this._currentHeight),this._fx=t[0],this._fy=t[1],this._cx=t[2],this._cy=t[3],this._poseModule.cwrap("xzimgInitializeCamera","number",["number","number","number"])(this._config.fovY,this._currentWidth,this._currentHeight)),this._poseManager_L.setNbFramesDelay(this._videoManager.getNbFramesDelay()),this._poseManager_R.setNbFramesDelay(this._videoManager.getNbFramesDelay());var r=e;null==e&&(r=this._videoManager.getLastBuffer()),null!=r?this.trackFootSync(r):console.error("No video frame to process")}else console.error("Foot must be initialized to track")},e.prototype.trackFootSync=function(e){var t=-1;if(this._rightFootState!=FE.Detection&&this._leftFootState!=FE.Detection){var n=this.trackBothFeetFeaturesSync(e,this._leftFootState,this._rightFootState,this._leftFootState==FE.Detected?this._initShape:this._leftFootRecShape,this._rightFootState==FE.Detected?this._initShape:this._rightFootRecShape,this._leftFootVis,this._rightFootVis,this._leftFootOcclusions,this._rightFootOcclusions),r=zE(n.scores_R,"RIGHT_FOOT",this._config.validTrackedKeypThs);this._rightFootRecShape=n.refinedFeatures_R,this._rightFootOcclusions=n.occlusions_R,this._rightFootVis=r.visibilty;var a=zE(n.scores_L,"LEFT_FOOT",this._config.validTrackedKeypThs);this._leftFootRecShape=n.refinedFeatures_L,this._leftFootOcclusions=n.occlusions_L,this._leftFootVis=a.visibilty;var s=this._config.trackScoreThs,o=this._reproj_t;this._fastMovements_R&&(o=this._reproj_fast_t);var i=this._rightFootRecShape.length/2,u=WE(i,"RIGHT_FOOT"),l=new LE(0,0,e.width,e.height),c=new OE((this._rightFootRecShape[u[0]]+this._rightFootRecShape[u[1]])/2,(this._rightFootRecShape[u[0]+i]+this._rightFootRecShape[u[1]+i])/2);l.isPointInside(c)&&this._rightFootVis[u[0]]&&this._rightFootVis[u[1]]&&r.globalScore>=s&&r.totalVisible>=this._config.trackedNumKeypsThs?(t=this.computePoseSync(this._rightFootState,"RIGHT_FOOT"),this._rightFootState=FE.Tracking,t>o&&(this._rightFootState=FE.Detection)):this._rightFootState=FE.Detection,s=this._config.trackScoreThs,this._fastMovements_L&&(s=.1),o=this._reproj_t,this._fastMovements_L&&(o=this._reproj_fast_t),u=WE(i,"LEFT_FOOT");var p=new OE((this._leftFootRecShape[u[0]]+this._leftFootRecShape[u[1]])/2,(this._leftFootRecShape[u[0]+i]+this._leftFootRecShape[u[1]+i])/2);l.isPointInside(p)&&this._leftFootVis[u[0]]&&this._leftFootVis[u[1]]&&a.globalScore>=s&&a.totalVisible>=this._config.trackedNumKeypsThs?(t=this.computePoseSync(this._leftFootState,"LEFT_FOOT"),this._leftFootState=FE.Tracking,t>o&&(this._leftFootState=FE.Detection)):this._leftFootState=FE.Detection,this._leftFootState==FE.Tracking&&this._rightFootState==FE.Tracking&&this.bothFeetSamePlace()&&(this._leftFootState=FE.Detection,this._rightFootState=FE.Detection)}else if(this._rightFootState!==FE.Detection&&this._leftFootState===FE.Detection){var h=this.trackFootFeaturesSync(e,this._rightFootState,this._rightFootState==FE.Detected?this._initShape:this._rightFootRecShape,this._rightFootVis,this._rightFootOcclusions,"RIGHT_FOOT");this._rightFootRecShape=h.refinedFeatures,this._rightFootOcclusions=h.occlusions,r=zE(h.scores,"RIGHT_FOOT",this._config.validTrackedKeypThs),this._rightFootVis=r.visibilty,s=this._config.trackScoreThs,o=this._reproj_t,this._fastMovements_R&&(o=this._reproj_fast_t),u=WE(this._rightFootRecShape.length/2,"RIGHT_FOOT"),this._rightFootVis[u[0]]&&this._rightFootVis[u[1]]&&r.globalScore>=s&&r.totalVisible>=this._config.trackedNumKeypsThs?(t=this.computePoseSync(this._rightFootState,"RIGHT_FOOT"),this._rightFootState=FE.Tracking,t>o&&(this._rightFootState=FE.Detection)):this._rightFootState=FE.Detection;var d=this.detectFeetSync(e);this._initShape=d.refinedFeatures,a=zE(d.scores,"LEFT_FOOT",this._config.detectScoreThs),r=zE(d.scores,"RIGHT_FOOT",this._config.detectScoreThs);var f=!1;if(!this._fastMovements_R&&null!=this._cnnOutputDataInvMask){var m=tN(this._cnnOutputDataInvMask,this._footDetectorShape,!1);m[0];var g=zE(_=m[1],"LEFT_FOOT",this._config.detectScoreThs),y=zE(_,"RIGHT_FOOT",this._config.detectScoreThs);r.globalScore>a.globalScore&&r.globalScore>y.globalScore+.1&&g.globalScore>y.globalScore&&(f=!0)}f&&r.globalScore>this._config.detectScoreThs?(this.invertFoot(),this._rightFootRecShape=d.refinedFeatures,this._rightFootState=FE.Detected):a.globalScore>=this._config.detectScoreThs&&(this._leftFootRecShape=d.refinedFeatures,this._leftFootState=FE.Detected)}else if(this._leftFootState!==FE.Detection&&this._rightFootState===FE.Detection){var b=this.trackFootFeaturesSync(e,this._leftFootState,this._leftFootState==FE.Detected?this._initShape:this._leftFootRecShape,this._leftFootVis,this._leftFootOcclusions,"LEFT_FOOT");if(this._leftFootRecShape=b.refinedFeatures,this._leftFootOcclusions=b.occlusions,a=zE(b.scores,"LEFT_FOOT",this._config.validTrackedKeypThs),this._leftFootVis=a.visibilty,s=this._config.trackScoreThs,o=this._reproj_t,this._fastMovements_L&&(o=this._reproj_fast_t),u=WE(this._leftFootRecShape.length/2,"LEFT_FOOT"),this._leftFootVis[u[0]]&&this._leftFootVis[u[1]]&&a.globalScore>=s&&a.totalVisible>=this._config.trackedNumKeypsThs?(t=this.computePoseSync(this._leftFootState,"LEFT_FOOT"),this._leftFootState=FE.Tracking,t>o&&(this._leftFootState=FE.Detection)):this._leftFootState=FE.Detection,d=this.detectFeetSync(e),this._initShape=d.refinedFeatures,r=zE(d.scores,"RIGHT_FOOT",this._config.detectScoreThs),a=zE(d.scores,"LEFT_FOOT",this._config.detectScoreThs),f=!1,!this._fastMovements_L&&null!=this._cnnOutputDataInvMask){var _,x=tN(this._cnnOutputDataInvMask,this._footDetectorShape,!1);x[0],g=zE(_=x[1],"LEFT_FOOT",this._config.detectScoreThs),y=zE(_,"RIGHT_FOOT",this._config.detectScoreThs),a.globalScore>r.globalScore&&a.globalScore>g.globalScore+.1&&y.globalScore>g.globalScore&&(f=!0)}f&&a.globalScore>this._config.detectScoreThs?(this.invertFoot(),this._leftFootRecShape=d.refinedFeatures,this._leftFootState=FE.Detected):r.globalScore>=this._config.detectScoreThs&&(this._rightFootRecShape=d.refinedFeatures,this._rightFootState=FE.Detected)}else if(this._leftFootState===FE.Detection||this._rightFootState===FE.Detection){var v=this.detectFeetSync(e);if(this._initShape=v.refinedFeatures,a=zE(v.scores,"LEFT_FOOT",this._config.detectScoreThs),r=zE(v.scores,"RIGHT_FOOT",this._config.detectScoreThs),a.globalScore>=this._config.detectScoreThs&&(this._leftFootState=FE.Detected),r.globalScore>=this._config.detectScoreThs&&(this._rightFootState=FE.Detected),this._rightFootState!=FE.Detection&&this._leftFootState!=FE.Detection&&this.bothFeetSamePlaceInit()&&(this._rightFootState==FE.Detected?this._rightFootState=FE.Detection:this._leftFootState=FE.Detection),this._leftFootState==FE.Detected||this._rightFootState==FE.Detected){this._leftFootRecShape=v.refinedFeatures,this._rightFootRecShape=v.refinedFeatures,this._fastMovements_L=!0,this._fastMovements_R=!0;var w=this._poseModule.cwrap("xzimgMatchRecKeypsInit","number",["number"]);null==this._hptrImageBuffer&&(this._hptrImageBuffer=this._poseModule._malloc(e.width*e.height*4)),YE(this._poseModule,e,this._hptrImageBuffer);var T=QE(this._poseModule,this._hptrImageBuffer,e.width,e.height);w(T),this._poseModule._free(T)}}this._leftFootState===FE.Detection&&(this._pose_L=new oN(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0]))),this._rightFootState==FE.Detection&&(this._pose_R=new oN(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0]))),this._pose_R.setTrackingState(this._rightFootState),this._pose_R.type=0,this._poseManager_R.setPose(this._pose_R),this._pose_L.setTrackingState(this._leftFootState),this._pose_L.type=1,this._poseManager_L.setPose(this._pose_L)},e.prototype.detectFeetSync=function(e){var t,n,r,a,s=function(e,t){var n,r;return{crop:e>t?[(r=0)/t,(n=(e-t)/2)/e,1,(e-n)/e]:[(r=(t-e)/2)/t,(n=0)/e,(t-r)/t,1],deltaY:r,deltaX:n}}(this._currentWidth,this._currentHeight),o=s.crop,i=s.deltaY,u=s.deltaX,l=$i(e),c=fi(l,"float32"),p=Cu(c,[1,this._currentHeight,this._currentWidth,3]),h=od.cropAndResize(p,[o],[0],[this._footDetectorConfig.inHeight,this._footDetectorConfig.inWidth]),d=Ol(255),f=tu(h,d),m=null;if(this._footToDetect==sN.Both&&(this._leftFootState===FE.Tracking||this._rightFootState===FE.Tracking)){var g=function(e,t,n,r,a,s,o,i){for(var u=e.length/2,l=new Float32Array(2*u),c=0;c<u;c++)l[c]=(e[c]-a)/o,l[c+u]=(e[c+u]-r)/s;for(var p=UE(l,i),h=p[0],d=p[1],f=p[2]-h,m=p[3]-d,g=p[6]-h,y=p[7]-d,b=f*f+m*m,_=g*g+y*y,x=new Float32Array(n*t),v=0;v<t;v++)for(var w=0;w<n;w++){var T=w-h,k=v-d,I=T*f+k*m,S=T*g+k*y;I>0&&S>0&&I<b&&S<_||(x[v*n+w]=1)}return x}(this._leftFootState===FE.Tracking?this._leftFootRecShape:this._rightFootRecShape,this._footDetectorConfig.inHeight,this._footDetectorConfig.inWidth,i,u,(this._currentHeight-2*i)/this._footDetectorConfig.inWidth,(this._currentWidth-2*u)/this._footDetectorConfig.inHeight,this._leftFootState===FE.Tracking?"LEFT_FOOT":"RIGHT_FOOT"),y=Hp(g,"float32");m=Cu(y,[1,this._footDetectorConfig.inHeight,this._footDetectorConfig.inWidth,1]),y.dispose()}var b=this._tfFootDetector.predict(f);if(null!=m){var _=lc(1,m),x=nu(b,_);this._cnnOutputDataInvMask=x.dataSync(),_.dispose(),x.dispose();var v=nu(b,m);b.dispose(),b=v,m.dispose()}var w,T,k=null!==(n=null==b?void 0:b.shape[3])&&void 0!==n?n:this._footDetectorConfig.outChannels,I=null!==(r=null==b?void 0:b.shape[1])&&void 0!==r?r:this._footDetectorConfig.outHeight,S=null!==(a=null==b?void 0:b.shape[2])&&void 0!==a?a:this._footDetectorConfig.outWidth;w=(t=tN(b.dataSync(),[1,I,S,k],!1))[0],T=t[1];var E=this._bufferKeypsDet/4;this._poseModule.HEAPF32.subarray(E,E+2*k).set(w),l.dispose(),c.dispose(),d.dispose(),h.dispose(),f.dispose(),p.dispose(),b.dispose();var N=Math.min(this._currentWidth,this._currentHeight),C=N/this._footDetectorConfig.inWidth,A=N/this._footDetectorConfig.inHeight;return this._simToImage_Det=function(e,t,n,r){var a=new Float32Array(6);return a[0]=r,a[1]=0,a[2]=t,a[3]=0,a[4]=n,a[5]=e,a}(i,u,A,C),{refinedFeatures:VE(w,this._simToImage_Det,!1,b.shape[1]),scores:T}},e.prototype.trackFootFeaturesSync=function(e,t,n,r,a,s){var o,i,u,l,c="LEFT_FOOT"==s?this._simToImage_L:this._simToImage_R;if(t!=FE.Detected){var p=Int32Array.from(r);this._activeIds.length>0&&(p.forEach((function(e,t){p[t]=0})),this._activeIds.forEach((function(e){p[e]=1})),r.forEach((function(e,t){0==e&&(p[t]=0)})),a&&a.forEach((function(e,t){e>0&&(r[t]=0)}))),i=(o=JE(this._poseModule,e,this._hptrImageBuffer,n,p))[0],u=o[1],l=o[2],Math.sqrt(u[2]*u[2]+u[3]*u[3])>10?"LEFT_FOOT"==s?this._fastMovements_L=!0:this._fastMovements_R=!0:"LEFT_FOOT"==s?this._fastMovements_L=!1:this._fastMovements_R=!1;var h=eN(n,i,l);"LEFT_FOOT"==s?this._pose_L.translate(h[0]*this._pose_L.t()[2]/this._fx,h[1]*this._pose_L.t()[2]/this._fy,0):"RIGHT_FOOT"==s&&this._pose_R.translate(h[0]*this._pose_R.t()[2]/this._fx,h[1]*this._pose_R.t()[2]/this._fy,0);for(var d=i.length/2,f=0;f<d;f++)i[f]=n[f]+h[0],i[f+d]=n[f+d]+h[1]}else i=n;c=jE(i,r,this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight,null,s);var m=new ImageData(this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight);m=GE(e,m,c),this._debug&&(this._debugInitialized=!0,this._debugImage=m,function(e,t,n,r){for(var a=new Uint8ClampedArray(e*t*4),s=e*t,o=0;o<s;o++){var i=4*o,u=4*o;a[u+0]=1*r[i+0],a[u+1]=1*r[i+1],a[u+2]=1*r[i+2],a[u+3]=255}new ImageData(a,t,e)}(this._footFeaturesConfig.inHeight,this._footFeaturesConfig.inWidth,0,m));var g=this.detectKeypointsSync([m],[s]),y=VE(g.coordinates[0],c,"LEFT_FOOT"==s,this._footFeaturesConfig.outHeight);return"LEFT_FOOT"==s?this._simToImage_L=c:this._simToImage_R=c,{refinedFeatures:y,scores:g.scores[0],occlusions:g.occlusions[0]}},e.prototype.detectKeypointsSync=function(e,t){for(var n=[],r=[],a=[],s=[],o=0,i=null,u=0,l=e;u<l.length;u++){var c=l[u],p=$i(c);s.push(p);var h=fi(p,"float32");s.push(h);var d=Cu(h,[1,this._footFeaturesConfig.inHeight,this._footFeaturesConfig.inWidth,3]);s.push(d);var f=Ol(255),m=tu(d,f);s.push(m),"LEFT_FOOT"==t[o]&&(m=gp(m,1),s.push(m)),i?(i=Mu([i,m]),s.push(i)):i=m,o+=1}if(null!=i){var g=[];if(this._footFeaturesConfig.numOutputs&&1!=this._footFeaturesConfig.numOutputs)for(var y=0,b=g=this._tfFootFeatures.predict(i);y<b.length;y++){var _=b[y];s.push(_)}else{var x=this._tfFootFeatures.predict(i);s.push(x),g.push(x)}for(var v=0,w=0,T=g;w<T.length;w++){x=T[w];for(var k=[],I=[],S=0,E=Yp(x,0);S<E.length;S++){var N=E[S];s.push(N);var C=Wl(N,0);s.push(C),k.push(N.dataSync()),I.push(C.shape)}if(this._footFeaturesConfig.outputNames&&"heatmaps"!=this._footFeaturesConfig.outputNames[v]){if(this._footFeaturesConfig.outputNames&&"coordinates"==this._footFeaturesConfig.outputNames[v])for(P=0;P<k.length;P++){for(var A=I[P][1]/2,R=new Float32Array(2*A),$=this._footFeaturesConfig.inHeight/2,M=this._footFeaturesConfig.inWidth/2,F=0;F<A;F++)R[F]=(k[P][F]+1)*M,R[F+A]=(k[P][F+A]+1)*$;n.push(R)}else if(this._footFeaturesConfig.outputNames&&"scores"==this._footFeaturesConfig.outputNames[v])for(P=0;P<k.length;P++){var O=I[P][1],D=new Float32Array(O);for(F=0;F<O;F++)D[F]=1/(1+Math.exp(-k[P][F]));r.push(D)}else if(this._footFeaturesConfig.outputNames&&"occlusions"==this._footFeaturesConfig.outputNames[v])for(P=0;P<k.length;P++){O=I[P][1];var L=new Float32Array(O);for(F=0;F<O;F++)L[F]=1/(1+Math.exp(-k[P][F]));a.push(L)}}else for(var P=0;P<k.length;P++){var B;B=this._useWasmForHeatmaps?nN(this._poseModule,I[P],k[P],"LEFT_FOOT"==t[P]?this._bufferHeatmaps_L:this._bufferHeatmaps_R,"LEFT_FOOT"==t[P]?this._bufferKeypsTrack_L:this._bufferKeypsTrack_R,this._bufferFeatureScores):tN(k[P],I[P],!1),n.push(B[0]),r.push(B[1]);var U=I[P][1]*I[P][2]*I[P][3],z="LEFT_FOOT"==t[P]?this._bufferHeatmaps_L/4:this._bufferHeatmaps_R/4;this._poseModule.HEAPF32.subarray(z,z+U).set(k[P])}v+=1}for(P=0;P<n.length;P++)A=n[P].length,z="LEFT_FOOT"==t[P]?this._bufferKeypsTrack_L/4:this._bufferKeypsTrack_R/4,this._poseModule.HEAPF32.subarray(z,z+2*A).set(n[P])}return s.forEach((function(e){return e.dispose()})),{coordinates:n,scores:r,occlusions:a}},e.prototype.trackBothFeetFeaturesSync=function(e,t,n,r,a,s,o,i,u){var l,c,p;if(t!=FE.Detected&&n!=FE.Detected){var h=r.length/2,d=new Int32Array(2*h);d.set(s),d.set(o,h);var f=null;i&&u&&((f=new Float32Array(2*h)).set(i),f.set(u,h));var m=Int32Array.from(d);this._activeIds.length>0&&(m.forEach((function(e,t){m[t]=0})),this._activeIds.forEach((function(e){m[e]=1,m[e+h]=1})),d.forEach((function(e,t){0==e&&(m[t]=0)})),f&&f.forEach((function(e,t){e>0&&(d[t]=0)})));var g=JE(this._poseModule,e,this._hptrImageBuffer,function(e,t){for(var n=e.length/2,r=t.length/2,a=n+r,s=new Float32Array(e.length+t.length),o=0;o<n;o++)s[o]=e[o],s[o+a]=e[o+n];for(o=0;o<r;o++)s[o+n]=t[o],s[o+a+n]=t[o+r];return s}(r,a),m),y=g[0];g[1];var b=g[2];l=function(e,t,n){var r=new Float32Array(2*t),a=new Float32Array(2*n),s=e.length/2;t+n!=s&&console.log("ERROR (separateShapes): shapes not correct dims");for(var o=0;o<t;o++)r[o]=e[o],r[o+t]=e[o+s];for(o=0;o<n;o++)a[o]=e[o+t],a[o+n]=e[o+s+t];return[r,a]}(y,h,h),c=l[0],p=l[1];var _=b.slice(0,h),x=b.slice(h,2*h),v=ZE(this._poseModule,r,c),w=ZE(this._poseModule,a,p);Math.sqrt(v[2]*v[2]+v[3]*v[3])>10?this._fastMovements_L=!0:this._fastMovements_L=!1,Math.sqrt(w[2]*w[2]+w[3]*w[3])>10?this._fastMovements_R=!0:this._fastMovements_R=!1;var T=eN(r,c,_);this._pose_L.translate(T[0]*this._pose_L.t()[2]/this._fx,T[1]*this._pose_L.t()[2]/this._fy,0);var k=eN(a,p,x);this._pose_R.translate(k[0]*this._pose_R.t()[2]/this._fx,k[1]*this._pose_R.t()[2]/this._fy,0);for(var I=p.length/2,S=0;S<I;S++)p[S]=a[S]+k[0],p[S+I]=a[S+I]+k[1],c[S]=r[S]+T[0],c[S+I]=r[S+I]+T[1]}else c=r,p=a;this._simToImage_L=jE(c,s,this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight,null,"LEFT_FOOT");var E=new ImageData(this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight);E=GE(e,E,this._simToImage_L),this._simToImage_R=jE(p,o,this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight,null,"RIGHT_FOOT");var N=new ImageData(this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight);N=GE(e,N,this._simToImage_R);var C=this.detectKeypointsSync([E,N],["LEFT_FOOT","RIGHT_FOOT"]),A=VE(C.coordinates[0],this._simToImage_L,!0,this._footFeaturesConfig.outHeight),R=VE(C.coordinates[1],this._simToImage_R,!1,this._footFeaturesConfig.outHeight);return t!=FE.Detected&&(A=PE(A,CE(C.scores[0],this._config.validTrackedKeypThs),c,s,.2)),n!=FE.Detected&&(R=PE(R,CE(C.scores[1],this._config.validTrackedKeypThs),p,o,.2)),{refinedFeatures_L:A,refinedFeatures_R:R,scores_L:C.scores[0],scores_R:C.scores[1],occlusions_L:C.occlusions[0],occlusions_R:C.occlusions[1]}},e.prototype.computePoseSync=function(e,t){var n=this,r=-1,a=this._poseModule.cwrap("xzimgEstimateRigidPose","number",["number","number","number","number","number","number","number","number","number","number","number","number"]);if(e==FE.Detected||e==FE.Tracking){var s=1;e==FE.Detected&&(s=0);var o=1;this._trackHasHeatmaps&&(o=3);var i=3;"LEFT_FOOT"!=t||this._fastMovements_L||(i=1),"RIGHT_FOOT"!=t||this._fastMovements_R||(i=1);var u=new Float32Array(18);"LEFT_FOOT"==t?(u.set(this._pose_L.R()),u.set(this._pose_L.t(),9)):(u.set(this._pose_R.R()),u.set(this._pose_R.t(),9));var l=KE(this._poseModule,u),c="LEFT_FOOT"==t?this._simToImage_L:this._simToImage_R,p=Float32Array.from([1,0,0,0,1,0]);this._trackHasHeatmaps&&(p=Float32Array.from(c.slice(0,6)),"LEFT_FOOT"==t&&(p[2]+=p[1]*(this._footFeaturesConfig.outWidth-1),p[5]+=p[4]*(this._footFeaturesConfig.outHeight-1),p[1]=-p[1],p[4]=-p[4]));var h=KE(this._poseModule,p),d=null,f=null,m=new Float32Array(2*this._activeIds.length),g=new Float32Array(3*this._activeIds.length),y="LEFT_FOOT"==t?this._leftFootRecShape:this._rightFootRecShape,b="LEFT_FOOT"==t?this._leftKeyps3D:this._rightKeyps3D,_=y.length/2;this._activeIds.length>0?(this._activeIds.forEach((function(e,t){m[t]=y[e],m[t+n._activeIds.length]=y[e+_]})),d=KE(this._poseModule,m),this._activeIds.forEach((function(e,t){g[3*t]=b[3*e],g[3*t+1]=b[3*e+1],g[3*t+2]=b[3*e+2]})),f=KE(this._poseModule,g),_=this._activeIds.length):(d=this._trackHasHeatmaps?"LEFT_FOOT"==t?this._bufferKeypsTrack_L:this._bufferKeypsTrack_R:KE(this._poseModule,y),f=KE(this._poseModule,"LEFT_FOOT"==t?this._leftKeyps3D:this._rightKeyps3D)),-1==(r=a("LEFT_FOOT"==t?this._bufferHeatmaps_L:this._bufferHeatmaps_R,this._footFeaturesConfig.outHeight,this._footFeaturesConfig.outWidth,_,0,h,d,f,s,o,i,l))&&(r=1e4),"LEFT_FOOT"==t?this._pose_L=new oN(new Float32Array(this._poseModule.HEAPF32.buffer,l,9),new Float32Array(this._poseModule.HEAPF32.buffer,l+9*this._float_size,3)):this._pose_R=new oN(new Float32Array(this._poseModule.HEAPF32.buffer,l,9),new Float32Array(this._poseModule.HEAPF32.buffer,l+9*this._float_size,3)),h&&this._poseModule._free(h),d&&!this._trackHasHeatmaps&&this._poseModule._free(d),f&&this._activeIds.length>0&&this._poseModule._free(f)}return r},e.prototype.invertFoot=function(){var e,t,n,r,a,s,o;e=[this._rightFootRecShape,this._leftFootRecShape],this._rightFootRecShape=e[0],this._rightFootRecShape=e[1],t=[this._pose_L,this._pose_R],this._pose_R=t[0],this._pose_L=t[1],n=[this._poseManager_L,this._poseManager_R],this._poseManager_R=n[0],this._poseManager_L=n[1],r=[this._simToImage_R,this._simToImage_L],this._simToImage_L=r[0],this._simToImage_R=r[1],a=[this._rightFootState,this._leftFootState],this._leftFootState=a[0],this._rightFootState=a[1],s=[this._rightFootVis,this._leftFootVis],this._leftFootVis=s[0],this._rightFootVis=s[1],o=[this._bufferHeatmaps_L,this._bufferHeatmaps_R],this._bufferHeatmaps_R=o[0],this._bufferHeatmaps_L=o[1]},e.prototype.dst=function(e,t,n,r){return Math.sqrt((e-n)*(e-n)+(t-r)*(t-r))},e.prototype.bothFeetSamePlaceInit=function(){var e=this._initShape.length/2,t=0;return t+=this.dst(this._initShape[0],this._initShape[e],this._initShape[4],this._initShape[4+e]),t+=this.dst(this._initShape[1],this._initShape[1+e],this._initShape[3],this._initShape[3+e]),(t+=this.dst(this._initShape[2],this._initShape[2+e],this._initShape[5],this._initShape[5+e]))/3<this.dst(this._initShape[0],this._initShape[e],this._initShape[2],this._initShape[2+e])/5},e.prototype.bothFeetSamePlace=function(){var e=UE(this._leftFootRecShape,"LEFT_FOOT"),t=e[0],n=e[1],r=e[2],a=e[3],s=e[4],o=e[5],i=e[6],u=e[7],l=UE(this._rightFootRecShape,"RIGHT_FOOT"),c=l[0],p=l[1],h=l[2],d=l[3],f=l[4],m=l[5],g=l[6],y=l[7],b=this.dst(t,n,i,u)/8;return this.dst(t,n,c,p)<b&&this.dst(r,a,h,d)<b&&this.dst(s,o,f,m)<b&&this.dst(i,u,g,y)<b},e.prototype.getKeypoints_L=function(){return this._leftFootRecShape},e.prototype.getKeypoints_R=function(){return this._rightFootRecShape},e.prototype.getScores_L=function(){return this._leftFootVis},e.prototype.getScores_R=function(){return this._rightFootVis},e.prototype.getOcclusion_L=function(){return this._leftFootOcclusions},e.prototype.getOcclusion_R=function(){return this._rightFootOcclusions},e}(),pN={modelFilename:"",featuresFilename:"",objContainer:"",fovY:50,detectScoreThs:.2,trackScoreThs:.4,geometryToDetect:"LAMBORGHINI",filteringLevel:2,filteringShift:.5,validDetectedKeypThs:.2,validTrackedKeypThs:.2,detectNumKeypsThs:3,trackedNumKeypsThs:3,normMode:"",reprojThs:25,activeIds:new Int32Array,computePose:!0,useWasmBackend:!0,subTrackerSymmetric:!1},hN=function(){function e(e,t){this.x=e,this.y=t}return e.prototype.Dist=function(e){return Math.sqrt((e.x-this.x)*(e.x-this.x)+(e.y-this.y)*(e.y-this.y))},e}();function dN(e,t){var n=Math.cos(t),r=Math.sin(t);return new Float32Array([n*e[0]-r*e[1],r*e[0]+n*e[1]])}function fN(e,t,n,r,a,s,o,i){void 0===i&&(i=[""]);for(var u=[],l=[],c=[],p=[],h=0,d=null,f=0,m=o;f<m.length;f++){var g=m[f],y=$i(g);p.push(y);var b=fi(y,"float32");p.push(b);var _=Cu(b,[1,t.inHeight,t.inWidth,3]);p.push(_);var x=Ol(255),v=tu(_,x);p.push(v),"left_right"!=i[h]&&"up_down"!=i[h]||(v=gp(v,"left_right"==i[h]?2:1),p.push(v)),d?(d=Mu([d,v]),p.push(d)):d=v,h+=1}if(null!=d){var w=[];if(t.numOutputs&&1!=t.numOutputs)for(var T=0,k=w=e.predict(d);T<k.length;T++){var I=k[T];p.push(I)}else{var S=e.predict(d);p.push(S),w.push(S)}for(var E=0,N=0,C=w;N<C.length;N++){S=C[N];for(var A=[],R=[],$=0,M=Yp(S,0);$<M.length;$++){var F=M[$];p.push(F);var O=Wl(F,0);p.push(O),A.push(F.dataSync()),R.push(O.shape)}if(t.outputNames&&"heatmaps"!=t.outputNames[E]){if(t.outputNames&&"coordinates"==t.outputNames[E])for(H=0;H<A.length;H++){for(var D=R[H][1]/2,L=new Float32Array(2*D),P=t.inHeight/2,B=t.inWidth/2,U=0;U<D;U++)L[U]=(A[H][U]+1)*B,L[U+D]=(A[H][U+D]+1)*P;u.push(L)}else if(t.outputNames&&"scores"==t.outputNames[E])if(t.outputTypes&&"logits"==t.outputTypes[E])for(H=0;H<A.length;H++){var z=R[H][1],V=new Float32Array(z);for(U=0;U<z;U++)V[U]=1/(1+Math.exp(-A[H][U]));l.push(V)}else for(H=0;H<A.length;H++){for(z=R[H][1],V=new Float32Array(z),U=0;U<z;U++)V[U]=A[H][U];l.push(V)}else if(t.outputNames&&"occlusions"==t.outputNames[E])if(t.outputTypes&&"logits"==t.outputTypes[E])for(H=0;H<A.length;H++){z=R[H][1];var W=new Float32Array(z);for(U=0;U<z;U++)W[U]=1/(1+Math.exp(-A[H][U]));c.push(W)}else for(H=0;H<A.length;H++){for(z=R[H][1],W=new Float32Array(z),U=0;U<z;U++)W[U]=A[H][U];c.push(W)}}else for(var H=0;H<A.length;H++){var G;G=n?nN(n,R[H],A[H],r[H],a[H],s[H]):tN(A[H],R[H],!0),u.push(G[0]),l.push(G[1])}E+=1}}return p.forEach((function(e){return e.dispose()})),{coordinates:u,scores:l,occlusions:c}}function mN(e){return e==uN.UpperBody||e==uN.FullBody}!function(e){e.Lamborghini="LAMBORGHINI",e.Horse="HORSE",e.WatsonCan="WATSON-CAN",e.MartellBottle="MARTELL-BOTTLE",e.Necklace="NECKLACE",e.Wrist="WRIST",e.Hand="HAND",e.UpperBody="UPPER-BODY",e.FullBody="FULL-BODY",e.CanKivisense="CAN-KIVISENSE",e.ToyTruck="TOY-TRUCK",e.Chivas="CHIVAS",e.ChivasLarge="CHIVAS-LARGE",e.Lion="LION",e.Bartender="BARTENDER",e.Wcbottle="WCBOTTLE",e.EQA="EQA",e.Face="FACE"}(uN||(uN={}));var gN="config.json",yN=function(){function e(){this._initialized=!1,this._nonRigidInitialized=!1,this._bufSubTrackerHmaps=null,this._bufSubTrackerHmapsSym=null,this._subTrackerCropKeyps=[],this._currentWidth=0,this._currentHeight=0,this._trackingState=FE.Detection,this._denseVertices=new Float32Array(0),this._bsCoefs=new Float32Array(0),this._geometryType=uN.Lamborghini,this._resetPose=!1,this._float_size=4,this._int_size=4,this._bufferHeatmaps=null,this._bufferKeypsDet=null,this._bufferFeatureScores=null,this._bufInOutPose=null,this._bufKeyps3D=null,this._bufMirroredKeyps3D=null,this._bufferKeypsTrack=null,this._bufferPdmModel=null,this._bufDenseVertices3D=null,this._bufModelTriangles=null,this._reprojError=0,this._hptrImageBuffer=null,this._fastMvt=!1,this._flipMode="",this._debug=!1,this._debugInitialized=!1,this.mean_t=0}return e.prototype.getDebugImage=function(){return this._debugInitialized?this._debugImage:null},e.prototype.isDetected=function(){return this._trackingState===FE.Tracking},e.prototype.getStatus=function(){return this._trackingState},e.prototype.getPosition=function(){var e=this._poseManager.getInterpolatedPose();return e?e.getPosition():null},e.prototype.getRotation=function(){var e=this._poseManager.getInterpolatedPose();return e?e.getRotation():null},e.prototype.getPose=function(){return this._pose},e.prototype.getVisibility=function(){return this._visibility},e.prototype.getKeypoints=function(){return this._keyps2D},e.prototype.getNumSubTracker=function(){return this._subTrackerKeyps?this._subTrackerKeyps.length:0},e.prototype.getSubTrackerKeyps=function(e){return this._subTrackerKeyps&&this._subTrackerKeyps.length>e?this._subTrackerKeyps[e]:new Float32Array(0)},e.prototype.getSubTrackerVisibility=function(e){return this._subTrackerScores&&this._subTrackerScores.length>e?this._subTrackerScores[e]:new Float32Array(0)},e.prototype.getReprojKeypoints=function(){return this._reprojKeyps2D},e.prototype.getKeypoints3D=function(){return this._keyps3D},e.prototype.getDenseKeypoints3D=function(){return this._denseVertices},e.prototype.getBlendShape=function(){return this._bsCoefs},e.prototype.getInterpolatedPose=function(){return this._poseManager.getInterpolatedPose()},e.prototype.isInitialized=function(){return this._initialized},e.prototype.isMirrored=function(){return""!=this._flipMode},e.prototype.getReprojError=function(){return this._reprojError},e.prototype.initialize=function(e,n,r){var o,i,u,l,c;return a(this,void 0,void 0,(function(){var a,p,h,d,f,m,g,y,b,_,x,v,T,k,I,S,E,N,C,A,R,$=this;return s(this,(function(s){switch(s.label){case 0:if(null==e)throw"Invalid parameter";return this._config=n?t(t({},pN),n):pN,(null===(o=null==n?void 0:n.wasmBackend)||void 0===o?void 0:o.enable)?(vE({"tfjs-backend-wasm.wasm":null===(i=n.wasmBackend)||void 0===i?void 0:i.tfjsBackendWasmPath,"tfjs-backend-wasm-simd.wasm":null===(u=n.wasmBackend)||void 0===u?void 0:u.tfjsBackendWasmSimdPath,"tfjs-backend-wasm-threaded-simd.wasm":null===(l=n.wasmBackend)||void 0===l?void 0:l.tfjsBackendWasmThreadedPath}),[4,vi("wasm")]):[3,2];case 1:return s.sent(),[3,3];case 2:vi("webgl"),s.label=3;case 3:return this.release(),this._videoManager=e,this._poseManager=new iN(this._videoManager.getNbFramesDelay()),this._poseManager.setInterpolation(this._config.filteringShift),this._poseManager.setFilteringLevel(this._config.filteringLevel),this._geometryType=function(e){if(e){if("LAMBORGHINI"===e)return uN.Lamborghini;if("HORSE"===e)return uN.Horse;if("WATSON-CAN"===e)return uN.WatsonCan;if("MARTELL-BOTTLE"===e)return uN.MartellBottle;if("NECKLACE"===e)return uN.Necklace;if("WRIST"===e)return uN.Wrist;if("HAND"===e)return uN.Hand;if("UPPER-BODY"===e)return uN.UpperBody;if("FULL-BODY"===e)return uN.FullBody;if("CAN-KIVISENSE"===e)return uN.CanKivisense;if("TOY-TRUCK"===e)return uN.ToyTruck;if("CHIVAS"===e)return uN.Chivas;if("CHIVAS-LARGE"===e)return uN.ChivasLarge;if("LION"===e)return uN.Lion;if("BARTENDER"===e)return uN.Bartender;if("WCBOTTLE"===e)return uN.Wcbottle;if("EQA"===e)return uN.EQA;if("FACE"===e)return uN.Face}return uN.Lamborghini}(this._config.geometryToDetect),a=new ie(0),p=G(HT({locateFile:function(e,t){return $._config.poseEstimationWasmFilename||t+e}})).pipe(me((function(){return a.next(1)}))),h=OT(this._config.modelFilename,gN),d=h.model$,f=h.progress$,m=OT(this._config.featuresFilename,gN),g=m.model$,y=m.progress$,_=new ie(0),"string"==typeof this._config.objContainer&&""===this._config.objContainer?(b=j({vertices:new Float32Array,uvs:new Float32Array,faces:new Uint16Array}),_.next(1)):(x=rN(this._config.objContainer,!1),v=x.model$,T=x.progress$,b=v,_=T),k=new ie(0),S="",this._config.pdmContainer?(E=this._config.pdmContainer,"string"==typeof this._config.pdmContainer&&(N=null===(c=this._config.pdmContainer)||void 0===c?void 0:c.replace(/\\/g,"/"),S=null==N?void 0:N.substring(N.lastIndexOf("/")+1,N.lastIndexOf("."))),I=function(e,t,n){return"string"==typeof e?tw({url:e,method:"GET",responseType:"arraybuffer",async:!0,progressSubscriber:new w((function(e){return n.next(.5*e.loaded/e.total)}),(function(e){}),(function(){return n.next(.5)}))}).pipe(ue(2),pe((function(e){return j(Ow(new Uint8Array(e.response)))})),pe((function(r){return r[t]?(n.next(1),j(r[t])):Q("File ".concat(t," not found in ").concat(e))}))):j(Ow(new Uint8Array(e))).pipe(pe((function(e){return e[t]?(n.next(1),j(e[t])):Q("File ".concat(t," not found"))})))}(E,this._config.pdmName?this._config.pdmName:S+".bin",k)):(k.next(1),I=j(null)),new ie(0),this._config.subTrackerFilename&&""!=this._config.subTrackerFilename?(A=OT(this._config.subTrackerFilename,gN),C=A.model$,A.progress$):C=j(null),R=V([a,f,k,y,_]).pipe(K((function(e){return e.reduce((function(t,n){return t+n/e.length}),0)})),K((function(e){return r&&r(e)}))).subscribe(),[4,Lv({poseModule:p,detectorModel:d,pdmModel:I,trackerModel:g,geometryObjModel:b,subTracker:C}).pipe(K((function(e){var t;$._poseModule=e.poseModule,$._geometryObjModel=e.geometryObjModel,$._tfKeypointsDetector=e.detectorModel.graphModel,$._detectorConfig=e.detectorModel.config,$._tfKeypointsTracker=e.trackerModel.graphModel,$._trackerConfig=e.trackerModel.config;var n=Tc([1,$._detectorConfig.inHeight,$._detectorConfig.inWidth,3]),r=$._tfKeypointsDetector.predict(n);$._detectorOutDims=r.shape,r.dispose(),$._detectorConfig.inHeight===$._trackerConfig.inHeight&&$._detectorConfig.inWidth===$._trackerConfig.inWidth||(n.dispose(),n=Tc([1,$._trackerConfig.inHeight,$._trackerConfig.inWidth,3])),(r=$._tfKeypointsTracker.predict(n))instanceof Array?($._debug&&r.forEach((function(e){return console.log(e.shape)})),r.forEach((function(e){return e.dispose()})),$._trackerOutDims=[1,$._trackerConfig.outHeight,$._trackerConfig.outWidth,$._trackerConfig.outChannels]):($._trackerOutDims=r.shape,r.dispose()),n.dispose(),$._debug&&(console.log($._detectorConfig),console.log($._trackerConfig),console.log("(DEBUG) XZIMG BACKEND",ts.backendName),console.log("_trackerOutDims",$._trackerOutDims)),$._activeIds=$._config.activeIds,$._trackHasHeatmaps=IE($._trackerConfig),t=function(e,t,n){if("NECKLACE"==t)return[r=new Float32Array([-1.982586,1.762905,-1.256474,-1.4803,.73489,-.059477,-.863695,.091572,.505433,-179e-6,-.518833,.632376,.863894,.089272,.503284,1.479377,.729931,-.063135,1.981941,1.7644,-1.255762]),new Float32Array([-1.982586,1.762905,-1.256474,1.981941,1.7644,-1.255762])];if("CAN-KIVISENSE"==t)return[r=new Float32Array([.11749199777841568,.3616040050983429,-.5216580033302307,.3387719988822937,.1726129949092865,-.5216580033302307,.059477999806404114,-.37553098797798157,-.5216580033302307,-.1752689927816391,-.3439840078353882,.5761319994926453,.3802120089530945,-0,-.3024890124797821,.3387719988822937,-.1726129949092865,-.3024890124797821,-.1726129949092865,-.3387719988822937,-.3024890124797821,-.3616029918193817,-.11749199777841568,-.3024890124797821,-.11749199777841568,.3616040050983429,-.3024890124797821,.3802120089530945,-0,-.08331900089979172,.22348299622535706,-.3075979948043823,-.08331900089979172,-.3075979948043823,-.22348299622535706,-.08331900089979172,.37553098797798157,-.059477999806404114,.1358499974012375,-0,-.3802120089530945,.1358499974012375,-.37553098797798157,-.059477999806404114,.1358499974012375,.059477999806404114,.37553098797798157,.1358499974012375,.3616040050983429,.11749199777841568,.3550190031528473,-.3616029918193817,-.11749199777841568,.3550190031528473,-.3616029918193817,.11749199777841568,.3550190031528473,-.11749199777841568,.3616029918193817,.3550190031528473]),new Float32Array([0,0,-.5991089940071106,0,-0,.6023629903793335])];if("TOY-TRUCK"==t)return[r=new Float32Array([-.11474676430225372,.06819115579128265,.12616248428821564,-3.9706208099232754e-7,-.14720511436462402,.28020843863487244,5.515660461696825e-8,-.3098587989807129,.08606547862291336,-.18071073293685913,-.27267926931381226,-.012890318408608437,3.1216436013892235e-7,.39625027775764465,.03189631924033165,.23052667081356049,.24702677130699158,.002463694429025054,.1103515625,.2759860157966614,.15902937948703766,.18071091175079346,-.27267909049987793,-.012890467420220375,-.23046159744262695,-.11318685114383698,.0017448731232434511,.23046180605888367,-.1131867840886116,.0017446735873818398,-.1103513240814209,.275985985994339,.15902943909168243,.22978469729423523,.383583128452301,-.09141343832015991,-.22978472709655762,.38358309864997864,-.09141325950622559,-.23052656650543213,.247026726603508,.002463878598064184,.11429085582494736,.06870604306459427,.12790152430534363,.11895161867141724,-.05556913837790489,.37969091534614563,.11927806586027145,.1806230992078781,.373945027589798,-.1189512312412262,-.05556917190551758,.3796910345554352,-.11927773058414459,.18062305450439453,.3739452064037323]),new Float32Array([5.515660461696825e-8,-.3098587989807129,.08606547862291336,3.1216436013892235e-7,.39625027775764465,.03189631924033165])];if("CHIVAS"==t)return[r=new Float32Array([-3.1930644239785977e-10,-15140265077207005e-22,5.86190128326416,0,-.9621832966804504,1.9865937232971191,1.1873104572296143,-.9285097718238831,.9833493232727051,1.1932897567749023,-.9253148436546326,-1.3412771224975586,0,.9153332114219666,2.9489502906799316,-1.5160919427871704,.8744217157363892,.3604915142059326,-3.4059355336069075e-9,.9318456053733826,.3808324337005615,0,.9403911828994751,1.5472331047058105,.8038088083267212,-.9315917491912842,-.4920954704284668,1.5160919427871704,.8744216561317444,.3604915142059326,-2.058072090148926,-.06387438625097275,-2.1172304153442383,2.0580718517303467,-.06387437880039215,-2.1172304153442383,1.1926252841949463,.9239217042922974,-.5218658447265625,-4.4702903601034905e-9,-.9262475371360779,2.8632278442382812,-.02674211747944355,-1.5987444257348216e-8,-3.3316898345947266,-1.3472687005996704,-.9158325791358948,.9859023094177246,1.6359063386917114,-.8202042579650879,-2.4852395057678223,-1.6359063386917114,-.8202041983604431,-2.4852395057678223,-1.2821598052978516,-.9170172810554504,-1.34637451171875,-1.2809302806854248,-.9167184233665466,-.529242992401123,-2.0578272342681885,-.06386483460664749,1.5451469421386719,1.6359063386917114,.8202039003372192,-2.485239267349243,-1.5809047222137451,.8463804721832275,-2.4669992923736572,.7743757367134094,-.04055686667561531,3.7609105110168457,-1.099993348121643,.9303679466247559,-1.3362138271331787,1.0999937057495117,.9303681254386902,-1.3362138271331787,-1.2809303998947144,.9167175889015198,-.529242753982544,-.7743757367134094,-.040556877851486206,3.760910987854004,2.0578272342681885,-.06386483460664749,1.5451469421386719]),new Float32Array([-.02674211747944355,-1.5987444257348216e-8,-3.3316898345947266,-3.1930644239785977e-10,-15140265077207005e-22,5.86190128326416])];if("CHIVAS-LARGE"==t)return[r=new Float32Array([-.7353339195251465,-9.039938504429301e-7,2.8790359497070312,.7353339195251465,-9.039938504429301e-7,2.8790359497070312,-1.0241641998291016,-1.0241650342941284,2.1618540287017822,1.1196224689483643,-.9188478589057922,2.1618540287017822,.14197710156440735,-1.4414118528366089,2.1618540287017822,-.14197710156440735,1.4414103031158447,2.1618545055389404,-.5879112482070923,.057907234877347946,4.713740348815918,.5879112482070923,.057907234877347946,4.713740348815918,.06999345868825912,.0023226356133818626,-2.3130407333374023,0,-.07499408721923828,6.051614284515381,.0008376236073672771,1.707755446434021,-1.6613836288452148,-1.3236799240112305,1.0878145694732666,-.10835576057434082,-1.086346983909607,-1.323068618774414,-.10257232189178467,1.3245174884796143,1.0878145694732666,-.10835576057434082,1.2116090059280396,-1.2100292444229126,-.10835611820220947,.8094201683998108,1.5145108699798584,.6681584119796753,-.953505277633667,1.427893042564392,.6681584119796753,-1.0888724327087402,-1.3264672756195068,.6710498332977295,1.2140388488769531,-1.2132492065429688,.6681579351425171,.49678289890289307,-1.6338136196136475,-.8848701119422913,.00010470295092090964,1.7187724113464355,1.0564154386520386,1.0838285684585571,-1.3177416324615479,-1.2731270790100098,1.0838285684585571,1.3218059539794922,-1.2731266021728516,-1.0823626518249512,1.3218059539794922,-1.2731266021728516,-.9479852914810181,-1.4177916049957275,-1.2630056142807007,.3440423905849457,-.6436600685119629,3.901371479034424,-.46299880743026733,-.5641732215881348,3.901371479034424]),new Float32Array([.06999345868825912,.0023226356133818626,-2.3130407333374023,0,-.07499408721923828,6.051614284515381])];if("LION"==t)return[r=new Float32Array([-.0022359604481607676,-.951945424079895,2.026939868927002,-.448139488697052,-.6012729406356812,-1.6381982564926147,-.5041450262069702,.4640916585922241,-1.7428531646728516,.5572898387908936,.4562094509601593,-1.7489975690841675,.4558115005493164,-.6014943718910217,-1.639726161956787,-.5527711510658264,-.9193709492683411,3.0056838989257812,.5723921656608582,-.9076480865478516,3.0084033012390137,.5884838104248047,.0083160400390625,1.280758261680603,-.6188563108444214,-.009009452536702156,1.2967206239700317,.030467068776488304,.4174400866031647,-.521793007850647,-1.5193467140197754,.0034290971234440804,-.37409281730651855,1.5193467140197754,.0034290971234440804,-.37409281730651855,.012890640646219254,-.8310151696205139,2.4351325035095215,1.5662710666656494,.9279237985610962,3.319540500640869,-1.5894092321395874,.8687598705291748,3.289144515991211,.3409583568572998,-.5160142183303833,1.274591088294983,-.3600188195705414,-.5107225775718689,1.2790225744247437,-1.097593903541565,.11527538299560547,-1.0057109594345093,1.1363357305526733,-.5465875864028931,-.971623957157135,.8704371452331543,.5547775626182556,.3597971200942993,3.982757734721787e-10,.5748654007911682,.7409988641738892,1.0960721969604492,.12153985351324081,-.9948496222496033,-1.1377226114273071,-.5433639287948608,-.9926916360855103,-.8704371452331543,.5547775626182556,.3597968816757202,0,-.5633412003517151,-.9722840189933777,0,-.5655208826065063,.37440025806427]),new Float32Array([.012890640646219254,-.8310151696205139,2.4351325035095215,0,-.5633412003517151,-.9722840189933777])];if("BARTENDER"==t)return[r=new Float32Array([-.20026133954524994,-.9737697839736938,2.17860746383667,.19603070616722107,-.9857503771781921,2.1616086959838867,.3260974586009979,.7099164128303528,.10108458995819092,-.37390175461769104,-.42527586221694946,1.0039399862289429,.3709491193294525,-.42527586221694946,1.0039399862289429,8438758959528059e-20,-1.101210594177246,1.7955349683761597,2949934116831766e-31,-.04326578229665756,-.5318827629089355,.4412812888622284,-.2815903127193451,-1.3385579586029053,.45793405175209045,.37141913175582886,-1.6536355018615723,-.4412812888622284,-.2815903127193451,-1.3385579586029053,-.45793405175209045,.37141913175582886,-1.6536355018615723,6788047923913078e-31,-.8192819952964783,.4206336736679077,-.9793461561203003,-.015334106981754303,1.7865675687789917,.9793461561203003,-.015334106981754303,1.7865675687789917,1.4873708486557007,.04833114147186279,-.3768104314804077,.4768085777759552,.1994880586862564,.9495226144790649,.7653667330741882,-.3627835810184479,.15018165111541748,.308129221200943,-.6489158868789673,.557608962059021,-.0002116243413183838,.49473923444747925,1.0336977243423462,-.5404940247535706,.19043265283107758,.8128713369369507,-.7657899260520935,-.3627835810184479,.15018165111541748,1.4484371035905497e-7,.3663712441921234,3.387472629547119,-1.2087160348892212,-.6443189978599548,3.0043344497680664,1.2087161540985107,-.6443195343017578,3.0043344497680664,6141737432960813e-31,-.8464082479476929,.10243535041809082,-.3249528408050537,.7104986310005188,.10016584396362305,-.303207665681839,-.9462416172027588,.5075775384902954,-.37667226791381836,-1.0658020973205566,.9869986772537231]),new Float32Array([2949934116831766e-31,-.04326578229665756,-.5318827629089355,1.4484371035905497e-7,.3663712441921234,3.387472629547119])];if("WCBOTTLE"==t)return[r=new Float32Array([-.013366899453103542,-2.9939471346551727e-7,-2.511009931564331,.6493963599205017,-.7673797011375427,-2.4501447677612305,.7540126442909241,.6627629399299622,-2.4501450061798096,-.9611459970474243,-.36033540964126587,-2.4501450061798096,.1477278769016266,.9964179992675781,1.9307010173797607,-.9568377137184143,-.35869666934013367,1.9307011365890503,-.01336702425032854,3.722930728145002e-7,2.314748764038086,.9344120025634766,.3603347837924957,.22589847445487976,-.027811311185359955,1.0138630867004395,1.6714674234390259,-.9710267186164856,.3331884741783142,1.0331839323043823,.627266526222229,.7859488129615784,1.035000205039978,-.6761305332183838,.7673797011375427,.22936050593852997,-.02781102992594242,1.0138623714447021,-1.587138056755066,-.027811311185359955,1.0138630867004395,.45858100056648254,-.9372201561927795,-.4008185565471649,-.006537972949445248,.5878132581710815,-.8109326958656311,-.27440735697746277,-.3465554714202881,-.9576587677001953,1.3840690851211548,.34696754813194275,-.9477792978286743,-.5884990096092224,-.8841753602027893,-.519440233707428,-.5891181230545044,-.346555233001709,-.9576594829559326,.418072372674942]),new Float32Array([-.013366899453103542,-2.9939471346551727e-7,-2.511009931564331,-.01336702425032854,3.722930728145002e-7,2.314748764038086])];if("EQA"==t)return[r=new Float32Array([-3.7749502658843994,-.9271571040153503,.04594746232032776,-3.777569055557251,.92264324426651,.04048970341682434,-3.7703702449798584,-1.2227396965026855,-.9106809496879578,-3.7990496158599854,1.1855655908584595,-.9073726534843445,3.811656951904297,1.3718937635421753,-.7763562798500061,3.8001205921173096,-1.3779062032699585,-.7809855341911316,-.4568534791469574,-1.0891674757003784,1.2122516632080078,-.4568534791469574,1.08638596534729,1.2122514247894287,2.6531293392181396,-.925976037979126,1.2379950284957886,2.648271083831787,.9270637631416321,1.2376376390457153,3.459774971008301,-1.3973642587661743,.466232568025589,3.459774971008301,1.3945828676223755,.46623218059539795,-.9480692744255066,.0011375703616067767,1.0669147968292236,-4.019203186035156,-.0013908070977777243,-.24615326523780823,3.3231399059295654,-.0013906551757827401,1.151373267173767,3.907538652420044,-.0012724152766168118,.11990431696176529,.35528019070625305,-1.5870187282562256,.2603841722011566,.5474950671195984,-1.151407241821289,1.2155274152755737,-1.341339349746704,-1.5719798803329468,-.9050094485282898,-1.420742154121399,-1.4566854238510132,.4212491512298584,.35528019070625305,1.5842370986938477,.2603837251663208,.5482162833213806,1.1495895385742188,1.2244428396224976,-1.341339349746704,1.5691980123519897,-.9050098657608032,-1.420742154121399,1.4539037942886353,.42124876379966736,2.0402863025665283,-1.592824101448059,.3434940576553345,1.582544207572937,-1.5713834762573242,-.836898148059845,2.047945737838745,1.584236979484558,.3409099578857422,1.582544207572937,1.5686016082763672,-.8368985652923584]),new Float32Array([-4.019203186035156,-.0013908070977777243,-.24615326523780823,3.907538652420044,-.0012724152766168118,.11990431696176529])];if("FACE"==t)return[r=new Float32Array([-9.037608623504639,2.355806514620781,-8.28516685962677,-8.81279444694519,-.11831151321530342,-7.542072296142578,-8.38990831375122,-2.418052017688751,-7.253487825393677,8.400188446044922,-2.424757957458496,-7.240226984024048,8.831642150878906,-.11823836714029312,-7.535887956619263,9.061289668083191,2.362936556339264,-8.284585356712341,-1.901270106434822,6.1033472418785095,1.311941035091877,1.9072290509939194,6.117302238941193,1.3117250353097916,-.0015033446252346039,4.03810042142868,1.5223239958286285,.0047621168196201324,2.571689784526825,2.513868987560272,.004333397373557091,1.2499050498008728,3.5467670559883118,-.0007506050169467926,-.2351544015109539,4.379635065793991,-1.5987120568752289,-1.6273340582847595,1.7652730643749237,.013800747692584991,-1.9495649933815002,2.5874924659729004,1.6161270439624786,-1.629391998052597,1.7741851210594177,-5.2972798347473145,3.732409954071045,-.8603600263595581,-2.2803800106048584,3.479170083999634,-.39132800698280334,2.189579963684082,3.4696600437164307,-.3517009913921356,5.284249782562256,3.7591500282287598,-.8421319723129272]),new Float32Array([])];if("HAND"==t){for(var r,a=((r=new Float32Array([3.57,6.02,0,6.68,8.76,.75,10.68,6.14,0,10.19,4.74,0,9.27,3.56,0,8.04,2.58,0,11.75,2.81,.01]))[12]+r[18])/2,s=(r[13]+r[19])/2,o=(r[14]+r[20])/2,i=0;i<r.length/3;i++)r[3*i]-=a,r[3*i+1]-=s,r[3*i+2]-=o;return[r,new Float32Array([3.57,6.02,0,10.19,4.74,0])]}var u=[],l=[];if("LAMBORGHINI"==t)u=[85,131,198,203,320,391,401,404,791,886,891,1008,1075,1085];else if("HORSE"==t)u=[12,15,264,352,360,845,1119,1316,1498,1872,2065,3146,4269,4273,4590,4593,7671,8034,8756,9119];else if("WATSON-CAN"==t)u=[335,1290,1330,2591,2669,2700,2822,3488,3613,5569,5574,5613,5639,5679,5685],l=[871,482];else if("MARTELL-BOTTLE"==t)u=[11,24,38,83,85,151,182,200,207,222,893,1646,1971,2013,2221,2229,2271,2309,2376,2444,2459,2725,2787,2792],l=[24,893];else if("NECKLACE"==t)u=[670,42,48,551,160,155,762],l=[640,762];else if("CAN-KIVISENSE"==t)u=[38,53,89,981,1006,1009,1019,1024,1034,1046,1052,1062,1087,1096,1105,1117,1124,1144,1148,1154],l=[1914,2725];else if("TOY-TRUCK"==t)u=[],l=[];else if("WRIST"==t&&(181==n||44==n)){if(u=[2,15,24,33,42,56,65,74,83,92,213,321,338,360,393,416,472,481,487,576,622,746,804,838,896,905,913,922,931,940,949,958,977,986,996,1005,1010,1019,1028,1037,1046,1055,1077,1086,1092,1101,1164,1173,1182,1267,1311,1321,1323,1346,1354,1372,1428,1451,1460,1468,1478,1503,1513,1554,1588,1597,1605,1641,1649,1692,1709,1735,1738,1762,1772,1789,1793,1819,1840,1850,1876,1894,1899,1921,1926,1935,1948,1953,1962,1971,1980,1989,2002,2007,2016,2025,2038,2056,2061,2083,2170,2435,2459,2513,2530,2594,2674,2718,2745,2748,2753,2772,2775,2791,2797,2803,2899,2905,2947,3003,3034,3084,3093,3109,3112,3128,3129,3136,3168,3175,3205,3208,3305,3323,3324,3331,3365,3368,3371,3374,3378,3386,3389,3392,3395,3398,3414,3418,3434,3437,3440,3443,3446,3462,3496,3509,3512,3689,3690,3691,3692,3693,3747,3748,3760,3764,3777,3778,3782,3783,3784,3787,3788,3792,3793,3797,3799,3800,3804,3805,3809],44==n){var c=[10,12,14,15,18,20,21,22,23,34,35,36,39,40,44,45,49,50,52,59,63,72,76,77,102,105,106,107,115,116,120,121,125,126,128,135,141,143,145,163,165,173,174,175];c.forEach((function(e,t){c[t]=u[e]})),console.log(c),u=c}l=[]}var p=u.length,h=new Float32Array(3*p);u.forEach((function(t,n){h[3*n]=e[3*t],h[3*n+1]=e[3*t+1],h[3*n+2]=e[3*t+2]}));var d=new Float32Array(3*l.length);return l.forEach((function(t,n){d[3*n]=e[3*t],d[3*n+1]=e[3*t+1],d[3*n+2]=e[3*t+2]})),[h,d]}($._geometryObjModel.vertices,$._geometryType,$._trackerConfig.outChannels),$._keypsVts=t[0],$._refKeypsVts=t[1];var a=Math.max($._detectorOutDims[1]*$._detectorOutDims[2]*$._detectorOutDims[3]);$._trackHasHeatmaps&&(a=Math.max($._detectorOutDims[1]*$._detectorOutDims[2]*$._detectorOutDims[3],$._trackerOutDims[1]*$._trackerOutDims[2]*$._trackerOutDims[3]));var s=Math.max($._detectorOutDims[3],$._trackerOutDims[3]);if($._bufferHeatmaps=$._poseModule._malloc(a*$._float_size),$._bufferKeypsDet=$._poseModule._malloc(2*$._detectorOutDims[3]*$._float_size),$._bufferKeypsTrack=$._poseModule._malloc(2*$._trackerOutDims[3]*$._float_size),$._bufferFeatureScores=$._poseModule._malloc(s*$._float_size),$._bufInOutPose=$._poseModule._malloc(21*$._float_size),e.pdmModel){var o=new Uint8Array(e.pdmModel);$._bufferPdmModel=$._poseModule._malloc(o.byteLength),$._poseModule.HEAPU8.set(o,$._bufferPdmModel);var i={rigid_pose:0,num_iterations:1,filter_strength:5,reg_w:10,fovy_d:50,width:640,height:480,num_features:$._geometryType==uN.Face?$._trackerOutDims[3]:-1,modelContent:$._bufferPdmModel,modelContentSize:o.byteLength,modelEncoding:$._geometryType==uN.Face?2:1,bsMode:0},u=$._poseModule._malloc(48);$._poseModule.setValue(u+0,i.rigid_pose,"i32"),$._poseModule.setValue(u+4,i.num_iterations,"i32"),$._poseModule.setValue(u+8,i.filter_strength,"i32"),$._poseModule.setValue(u+12,i.reg_w,"float"),$._poseModule.setValue(u+16,i.fovy_d,"float"),$._poseModule.setValue(u+20,i.width,"i32"),$._poseModule.setValue(u+24,i.height,"i32"),$._poseModule.setValue(u+28,i.num_features,"i32"),$._poseModule.setValue(u+32,i.modelContent,"*"),$._poseModule.setValue(u+36,i.modelContentSize,"i32"),$._poseModule.setValue(u+40,i.modelEncoding,"i32"),$._poseModule.setValue(u+44,i.bsMode,"i32");var l=$._poseModule.cwrap("xzimgPoseEstimationInitialize","number",["number"])(u);$._debug&&console.log("PDM initialisation: ",l),$._poseModule._free(u),$._poseModule._free($._bufferPdmModel),$._nonRigidInitialized=!0}else if(null==$._bufKeyps3D){$._bufKeyps3D=$._poseModule._malloc($._keypsVts.length*$._float_size),$._poseModule.HEAPF32.set($._keypsVts,$._bufKeyps3D/4);var c=Array.from($._keypsVts);c.forEach((function(e,t){t%3==0&&(c[t]=-c[t])})),$._bufMirroredKeyps3D=$._poseModule._malloc(c.length*$._float_size),$._poseModule.HEAPF32.set($._keypsVts,$._bufMirroredKeyps3D/4)}if(e.subTracker){$._tfSubTracker=e.subTracker.graphModel,$._subTrackerConfig=e.subTracker.config;var p=Tc([$._config.subTrackerSymmetric?2:1,$._subTrackerConfig.inHeight,$._subTrackerConfig.inWidth,3]),h=$._tfSubTracker.predict(p);$._subTrackerOutDims=h.shape,h.dispose(),p.dispose();var d=Math.max($._subTrackerOutDims[1]*$._subTrackerOutDims[2]*$._subTrackerOutDims[3]);if($._bufSubTrackerHmaps=$._poseModule._malloc(d*$._float_size),$._bufSubTrackerHmapsSym=$._poseModule._malloc(d*$._float_size),$._config.subTrackerObjectType){var f=$._geometryObjModel.faces.length/3;$._bufModelTriangles=$._poseModule._malloc(9*f*$._float_size);for(var m=new Float32Array(9*f),g=0;g<f;g++){var y=$._geometryObjModel.faces[3*g],b=$._geometryObjModel.faces[3*g+1],_=$._geometryObjModel.faces[3*g+2];m[9*g]=$._geometryObjModel.vertices[3*y],m[9*g+1]=$._geometryObjModel.vertices[3*y+1],m[9*g+2]=$._geometryObjModel.vertices[3*y+2],m[9*g+3]=$._geometryObjModel.vertices[3*b],m[9*g+4]=$._geometryObjModel.vertices[3*b+1],m[9*g+5]=$._geometryObjModel.vertices[3*b+2],m[9*g+6]=$._geometryObjModel.vertices[3*_],m[9*g+7]=$._geometryObjModel.vertices[3*_+1],m[9*g+8]=$._geometryObjModel.vertices[3*_+2]}$._poseModule.HEAPF32.set(m,$._bufModelTriangles/4)}}$._initialized=!0})),Z((function(){return R.unsubscribe()}))).toPromise()];case 4:return s.sent(),[2]}}))}))},e.prototype.release=function(){this._initialized&&(this._tfKeypointsDetector.dispose(),this._tfKeypointsTracker.dispose(),null!=this._bufferHeatmaps&&this._poseModule._free(this._bufferHeatmaps),this._bufferHeatmaps=null,null!=this._bufferKeypsDet&&this._poseModule._free(this._bufferKeypsDet),this._bufferKeypsDet=null,null!=this._bufferKeypsTrack&&this._poseModule._free(this._bufferKeypsTrack),this._bufferKeypsTrack=null,null!=this._bufferFeatureScores&&this._poseModule._free(this._bufferFeatureScores),this._bufferFeatureScores=null,null!=this._bufInOutPose&&this._poseModule._free(this._bufInOutPose),this._bufInOutPose=null,null!=this._bufKeyps3D&&this._poseModule._free(this._bufKeyps3D),this._bufKeyps3D=null,null!=this._bufMirroredKeyps3D&&this._poseModule._free(this._bufMirroredKeyps3D),this._bufMirroredKeyps3D=null,null!=this._hptrImageBuffer&&this._poseModule._free(this._hptrImageBuffer),this._hptrImageBuffer=null,this._bufDenseVertices3D&&this._poseModule._free(this._bufDenseVertices3D),this._bufDenseVertices3D=null,this._bufModelTriangles&&this._poseModule._free(this._bufModelTriangles),this._bufModelTriangles=null,this._poseModule.cwrap("xzimgPoseEstimationRelease")(),this._currentWidth=0,this._currentHeight=0,this._initialized=!1,this._nonRigidInitialized=!1,this._trackingState=FE.Detection,this._bufSubTrackerHmaps&&this._poseModule._free(this._bufSubTrackerHmaps),this._bufSubTrackerHmaps=null,this._bufSubTrackerHmapsSym&&this._poseModule._free(this._bufSubTrackerHmapsSym),this._bufSubTrackerHmapsSym=null)},e.prototype.trackSync=function(e){var t;if(this._initialized){var n=this._videoManager.getVideoCanvas();n.width===this._currentWidth&&n.height===this._currentHeight||(this._currentWidth=n.width,this._currentHeight=n.height,t=oN.getCameraParams(this._config.fovY,this._currentWidth,this._currentHeight),this._fx=t[0],this._fy=t[1],this._cx=t[2],this._cy=t[3],this._poseModule.cwrap("xzimgInitializeCamera","number",["number","number","number"])(this._config.fovY,this._currentWidth,this._currentHeight)),this._poseManager.setNbFramesDelay(this._videoManager.getNbFramesDelay());var r=e;null==e&&(r=this._videoManager.getLastBuffer()),null!=r?this.trackGeometrySync(r):console.error("No video frame to process")}else console.error("Geometry must be initialized to track")},e.prototype.trackGeometrySync=function(e){var t,n,r=this,a=mN(this._geometryType)||this._geometryType==uN.Wrist||this._geometryType==uN.Hand||this._geometryType==uN.Face;if(this._trackingState===FE.Detection){var s=this._poseModule.cwrap("xzimgMatchRecKeypsInit","number",["number"]);null==this._hptrImageBuffer&&(this._hptrImageBuffer=this._poseModule._malloc(e.width*e.height*4)),YE(this._poseModule,e,this._hptrImageBuffer);var o=QE(this._poseModule,this._hptrImageBuffer,e.width,e.height);s(o),this._poseModule._free(o);var i=this.detectGeometrySync(e),u=i.refinedFeatures,l=i.scores;this._keyps2D=u;var c=NE(l,this._config.validDetectedKeypThs);this._visibility=c.visibilty,this._trackingState=FE.Detection,c.totalVisible>=this._config.detectNumKeypsThs&&c.globalScore>=this._config.detectScoreThs&&(this._geometryType==uN.Wrist&&(this._flipMode="","left"==(t=this._keyps2D,n=c.visibilty,(9==t.length/2?n[0]&&n[1]?DE.CreateFromPoints(new OE(t[0],t[9]),new OE(t[1],t[10])):DE.CreateFromPoints(new OE(t[1],t[10]),new OE(t[6],t[15])):DE.CreateFromPoints(new OE(t[30],t[211]),new OE(t[163],t[344]))).x>0?"left":"right")&&(this._flipMode="up_down")),a?this._trackingState=FE.Detected:(this._reprojError=this.computePoseSync(this._trackingState,this._geometryType),this._reprojError>0&&this._reprojError<this._config.reprojThs&&(this._trackingState=FE.Detected)))}else{var p=this.trackGeometryFeaturesSync(e,this._trackingState,this._keyps2D,this._visibility,this._geometryType);this._keyps2D=p.imageFilteredKeyps,this._cropKeyps2D=p.cropKeyps,c=NE(p.scores,this._config.validTrackedKeypThs),this._visibility=c.visibilty;var h=RE(this._geometryType,this._keyps2D.length/2);if(this._debug&&(console.log("globalScore",c.globalScore),console.log("totalVisible",c.totalVisible)),this._visibility[h[0]]&&this._visibility[h[1]]&&c.totalVisible>=this._config.trackedNumKeypsThs&&c.globalScore>=this._config.trackScoreThs){if(this._config.computePose?(this._reprojError=this.computePoseSync(this._trackingState,this._geometryType),this._reprojError<=0||this._reprojError>this._config.reprojThs?this._trackingState=FE.Detection:this._trackingState=FE.Tracking):this._trackingState=FE.Tracking,this._tfSubTracker&&this._trackingState==FE.Tracking){this._debug&&console.log("tracking subgeomerty");var d=this.trackSubGeometrySync(e,this._keyps2D,this._visibility);if(this._subTrackerKeyps&&this._subTrackerKeyps.length>0?this._subTrackerKeyps.forEach((function(e,t){r._subTrackerKeyps[t]=PE(d.subTrackerKeyps[t],d.subTrackerVisibility[t],e,r._subTrackerVis[t],.1)})):this._subTrackerKeyps=d.subTrackerKeyps,this._subTrackerScores=d.subTrackerKeypsScores,this._subTrackerVis=d.subTrackerVisibility,"ear"==this._config.subTrackerObjectType){var f=new Float32Array([0,0,0]);f=this._pose.transformInv(f);for(var m=this._poseModule.cwrap("xzimgGeometryGetModelIntersection","number",["number","number","number","number"]),g=0;g<this._subTrackerKeyps.length;g++){var y=0==g?2:3,b=this._keypsVts[3*y]-1.45;1==g&&(b=this._keypsVts[3*y]+1.45);var _=this._keypsVts[3*y+1]-.38,x=this._keypsVts[3*y+2]-1.6,v=Math.sqrt((b-f[0])*(b-f[0])+(_-f[1])*(_-f[1])+(x-f[2])*(x-f[2])),w=new Float32Array([(b-f[0])/v,(_-f[1])/v,(x-f[2])/v]);this._debug&&(console.log("dir",w),console.log("camCenter",f),console.log("numTriangles",this._geometryObjModel.faces.length/3));var T=this._poseModule._malloc(3*this._float_size),k=T/4,I=this._poseModule.HEAPF32.subarray(k,k+3);I.set(f);var S=this._poseModule._malloc(3*this._float_size);k=S/4,(I=this._poseModule.HEAPF32.subarray(k,k+3)).set(w);var E=m(T,S,this._bufModelTriangles,this._geometryObjModel.faces.length/3);if(this._poseModule._free(T),this._poseModule._free(S),1==E){var N=PE(this._pose.project(new Float32Array([b,_,x]),oN.getCameraMat(this._config.fovY,this._currentWidth,this._currentHeight)),new Int32Array([1]),new Float32Array([this._subTrackerKeyps[g][3],this._subTrackerKeyps[g][7]]),new Int32Array([1]),.1);this._subTrackerKeyps[g][3]=N[0],this._subTrackerKeyps[g][7]=N[1]}}}}}else this._trackingState=FE.Detection}(this._trackingState===FE.Detection||this._trackingState===FE.Detected&&a)&&(this._pose=new oN(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0])),this._pose.setTrackingState(FE.Detection)),this._pose.setTrackingState(this._trackingState),this._poseManager.setPose(this._pose)},e.prototype.detectGeometrySync=function(e){var t,n,r,a=function(e,t){var n,r;return{crop:e>t?[(r=0)/t,(n=(e-t)/2)/e,1,(e-n)/e]:[(r=(t-e)/2)/t,(n=0)/e,(t-r)/t,1],deltaY:r,deltaX:n}}(this._currentWidth,this._currentHeight),s=a.crop,o=a.deltaY,i=a.deltaX,u=$i(e),l=fi(u,"float32"),c=Cu(l,[1,this._currentHeight,this._currentWidth,3]),p=od.cropAndResize(c,[s],[0],[this._detectorConfig.inHeight,this._detectorConfig.inWidth]),h=Ol(255),d=tu(p,h),f=this._tfKeypointsDetector.predict(d),m=f.dataSync(),g=this._poseModule.cwrap("xzimgGetHeatmapsLocations","number",["number","number","number","number","number","number","number","number"]),y=null!==(t=null==f?void 0:f.shape[3])&&void 0!==t?t:this._detectorConfig.outChannels,b=null!==(n=null==f?void 0:f.shape[1])&&void 0!==n?n:this._detectorConfig.outHeight,_=null!==(r=null==f?void 0:f.shape[2])&&void 0!==r?r:this._detectorConfig.outWidth,x=y*b*_,v=this._bufferHeatmaps/4;this._poseModule.HEAPF32.subarray(v,v+x).set(m),g(this._bufferHeatmaps,b,_,y,0,1,this._bufferKeypsDet,this._bufferFeatureScores);var w=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufferKeypsDet,2*y),T=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufferFeatureScores,y);u.dispose(),l.dispose(),h.dispose(),p.dispose(),d.dispose(),c.dispose(),f.dispose();var k=Math.min(this._currentWidth,this._currentHeight),I=k/this._detectorConfig.inWidth,S=k/this._detectorConfig.inHeight;return this._simCropToImage=function(e,t,n,r){var a=new Float32Array(6);return a[0]=r,a[1]=0,a[2]=t,a[3]=0,a[4]=n,a[5]=e,a}(o,i,S,I),{refinedFeatures:AE(w,this._simCropToImage),scores:T}},e.prototype.trackGeometryFeaturesSync=function(e,t,n,r,a){var s,o,i,u,l=Int32Array.from(r);this._activeIds.length>0&&(l.forEach((function(e,t){l[t]=0})),this._activeIds.forEach((function(e){l[e]=1})),r.forEach((function(e,t){0==e&&(l[t]=0)})));var c,p,h=new Float32Array([0,0]);if(t!=FE.Detected){if(o=(s=JE(this._poseModule,e,this._hptrImageBuffer,n,l))[0],i=s[1],u=s[2],Math.sqrt(i[2]*i[2]+i[3]*i[3])>10?this._fastMvt=!0:this._fastMvt=!1,a==uN.FullBody?[7,8,9,10,13,14,15,16].forEach((function(e){u[e]=0})):a==uN.UpperBody?[7,8,9,10].forEach((function(e){u[e]=0})):a==uN.Necklace?[1,2,3,4,5].forEach((function(e){u[e]=0})):this._activeIds.length>0&&this._activeIds.forEach((function(e){u[e]=0})),h=function(e,t,n,r,a,s,o){void 0===a&&(a=null);for(var i=new Float32Array(2),u=n.length/2,l=0,c=0;c<u;c++)(null==a||a[c]>0)&&(i[0]+=r[c]-n[c],i[1]+=r[c+u]-n[c+u],l+=1);l>0&&(i[0]/=l,i[1]/=l);var p=t/4,h=new Float32Array(18);return h.set(e.HEAPF32.subarray(p,p+18)),h[9]+=i[0]*h[11]/s,h[10]+=i[1]*h[11]/o,e.HEAPF32.set(h,t/4),i}(this._poseModule,this._bufInOutPose,n,o,u,this._fx,this._fy),a==uN.Necklace)for(var d=o.length/2,f=0;f<d;f++)o[f]=n[f]+h[0],o[f+d]=n[f+d]+h[1]}else o=n;if("WATSON-CAN"==a||"CAN-KIVISENSE"==a||"TOY-TRUCK"==a||"CHIVAS"==a||"CHIVAS-LARGE"==a||"LION"==a||"BARTENDER"==a||"WCBOTTLE"==a||"EQA"==a||"MARTELL-BOTTLE"==a){var m=this._pose.project(this._refKeypsVts,oN.getCameraMat(this._config.fovY,this._currentWidth,this._currentHeight));c=-Math.atan2(m[1]-m[3],m[2]-m[0]),"EQA"==a&&(c=0);var g=this._pose.project(this._keypsVts,oN.getCameraMat(this._config.fovY,this._currentWidth,this._currentHeight));for(p=new Float32Array(g.length),f=0;f<p.length/2;f++)p[f]=g[2*f],p[f+p.length/2]=g[2*f+1]}var y=Float32Array.from(n),b=o.length/2;for(f=0;f<b;f++)y[f]+=h[0],y[f+b]+=h[1];mN(a)?this._simCropToImage=function(e,t,n,r,a){var s,o,i,u=t.length/2,l=Array(5),c=new Array(5);if(7==u)l[0]=n[0]>0?1:0,c[0]=new hN(t[0],t[u]),l[1]=n[3]>0&&n[4]>0?1:0,c[1]=new hN((t[3]+t[4])/2,(t[3+u]+t[4+u])/2),l[2]=n[5]>0&&n[6]>0?1:0,c[2]=new hN((t[5]+t[6])/2,(t[5+u]+t[6+u])/2),l[3]=n[1]>0?1:0,c[3]=new hN(t[1],t[1+u]),l[4]=n[2]>0?1:0,c[4]=new hN(t[2],t[2+u]);else{var p=15==u?13:17,h=15==u?14:18;l[0]=n[0]>0?1:0,c[0]=new hN(t[0],t[u]),l[1]=n[p]>=0?1:0,c[1]=new hN(t[p],t[p+u]),l[2]=n[h]>=0?1:0,c[2]=new hN(t[h],t[h+u]),l[3]=n[1]>0?1:0,c[3]=new hN(t[1],t[1+u]),l[4]=n[2]>0?1:0,c[4]=new hN(t[2],t[2+u])}if("FULL-BODY"==e)if(l[1]>0&&l[2]>0)s=c[2],o=-Math.atan2(c[2].y-c[1].y,c[1].x-c[2].x),o+=Math.PI/2,i=2*c[2].Dist(c[1])*2.35;else if(l[0]>0&&l[1]>0)(s=c[1]).y+=2.24*(c[1].y-c[0].y),o=-Math.atan2(c[1].y-c[0].y,c[0].x-c[1].x),o+=Math.PI/2,i=2*c[0].Dist(c[1])*5.3;else if(l[0]>0&&l[2]>0)s=c[2],o=-Math.atan2(c[2].y-c[0].y,c[0].x-c[2].x),o+=Math.PI/2,i=2*c[0].Dist(c[2])*1.64;else{if(!(l[0]>0&&l[3]>0&&l[4]>0))return 0;var d=c[3].Dist(c[4]);(s=c[0]).y+=3*d,o=-Math.atan2(c[4].y-c[3].y,c[3].x-c[4].x),i=2*d*14}else if(console.log(l),l[1]>0&&l[2]>0)s=c[1],o=-Math.atan2(c[2].y-c[1].y,c[1].x-c[2].x),o+=Math.PI/2,i=2*c[2].Dist(c[1])*1.2;else if(l[0]>0&&l[1]>0)s=c[1],o=-Math.atan2(c[1].y-c[0].y,c[0].x-c[1].x),o+=Math.PI/2,i=2*c[0].Dist(c[1])*2.6;else if(l[0]>0&&l[2]>0)s=new hN(c[2].x+.75*(c[0].x-c[2].x),c[2].y+.75*(c[0].y-c[2].y)),o=-Math.atan2(c[2].y-c[0].y,c[0].x-c[2].x),o+=Math.PI/2,i=2*c[0].Dist(c[2])*.8;else{if(!(l[0]>0&&l[3]>0&&l[4]>0))return 0;d=c[3].Dist(c[4]),(s=c[0]).y+=5.5*d,o=-Math.atan2(c[4].y-c[3].y,c[3].x-c[4].x),i=2*d*11}for(var f=0,m=0;m<u;m++){var g=new hN(t[m],t[m+u]).Dist(s);n[m]>0&&g>f&&(f=g)}i=Math.max(i,2*f);var y=Math.cos(o),b=Math.sin(o),_=(i+.1*i)/Math.max(r[0],r[1]),x=(r[1]-1)/2,v=(r[0]-1)/2,w=s.x-(y*_*x-b*_*v),T=s.y-(b*_*x+y*_*v);if(null!=a){var k=.8;_=(1-k)*_+k*a[7],w=(1-k)*w+k*a[2],T=(1-k)*T+k*a[5],o=(1-k)*o+k*a[6],y=Math.cos(o),b=Math.sin(o)}return[y*_,-b*_,w,b*_,y*_,T,o,_]}(a,void 0===p?o:p,r,[this._trackerConfig.inWidth,this._trackerConfig.inHeight],t==FE.Detected||this._fastMvt?null:this._simCropToImage):a==uN.Face?this._simCropToImage=function(e,t,n,r,a){var s=e.length/2,o=EE(e,t,s),i=new OE((o[0]+o[1])/2,(o[2]+o[3])/2),u=0,l=0,c=.3;if(19==s||21==s){var p=[15,16,17,18];21==s&&(p=[17,18,19,20]),0!=t[17]&&0!=t[20]||(p=[18,19]),0!=t[18]&&0!=t[19]||(p=[17,20]),i=new OE(0,0),p.forEach((function(t){i.x+=e[t],i.y+=e[t+s]})),i.x/=p.length,i.y/=p.length;var h=new OE(e[8],e[8+s]),d=new OE(e[13],e[13+s]);21==s&&(h=new OE(e[10],e[10+s]),d=new OE(e[15],e[15+s])),l=1.57075-Math.atan2(d.y-h.y,h.x-d.x);for(var f=0;f<s;f++){var m=new OE(e[f],e[f+s]).Dist(i);t[f]>0&&m>u&&(u=m)}u*=2,c=.3}else{var g=27,y=62,b=66;22==s&&(g=9,y=18,b=20),24==s&&(g=9,y=20,b=22);var _=void 0;5==s?(_=new OE(.5*(e[0]+e[1]),.5*(e[0+s]+e[1+s])),y=3,b=4):_=new OE(e[g],e[g+s]);var x=new OE(.5*(e[y]+e[b]),.5*(e[y+s]+e[b+s]));if(l=1.57075-Math.atan2(x.y-_.y,_.x-x.x),u=Math.max(o[1]-o[0],o[3]-o[2]),a&&"face_center"==a){i=new OE((_.x+x.x)/2,(_.y+x.y)/2);var v=0;for(f=0;f<s;f++)m=new OE(e[f],e[f+s]).Dist(i),t[f]>0&&m>v&&(v=m);u=2*v}5==s&&(u=2*(o[1]-o[0])),22==s&&(c=.15)}var w=new LE(i.x-u/2,i.y-u/2,u,u),T=Math.cos(l),k=Math.sin(l),I=(w.w+c*w.w)/Math.max(n[0],n[1]),S=n[1]/2,E=n[0]/2,N=i.x-(T*I*S-k*I*E),C=i.y-(k*I*S+T*I*E);if(null!=r){var A=.8;N=A*N+(1-A)*r[2],C=A*C+(1-A)*r[5],I=.3*I+.7*r[7],Math.abs(l-r[6])<1&&(l=.3*l+.7*r[6]),T=Math.cos(l),k=Math.sin(l)}return[T*I,-k*I,N,k*I,T*I,C,l,I]}(void 0===p?y:p,r,[this._trackerConfig.inWidth,this._trackerConfig.inHeight],t==FE.Detected||this._fastMvt?null:this._simCropToImage,this._config.normMode):a==uN.Wrist?this._simCropToImage=function(e,t,n,r,a){var s=e.length/2,o=EE(e,t,s),i=RE("WRIST",s),u=i[0],l=i[1],c=[e[u],e[u+s]],p=[e[l],e[l+s]],h=-Math.atan2(p[1]-c[1],c[0]-p[0]),d=function(e,t,n){for(var r=e.length/2,a=new Float32Array(2*r),s=0;s<r;s++)if(t[s]>0){var o=dN(new Float32Array([e[s],e[s+r]]),n);a[s]=o[0],a[s+r]=o[1]}var i=EE(a,t,r);return Math.max(i[1]-i[0],i[3]-i[2])}(e,t,h),f=(o[1]+o[0])/2,m=(o[3]+o[2])/2;9==s&&(h=-Math.atan2(c[1]-p[1],p[0]-c[0]),h+=3.1415,!t[0]&&t[1]&&t[6]&&(f=e[1],m=e[10],d=2*Math.sqrt(Math.pow(e[6]-f,2)+Math.pow(e[15]-f,2))));var g=Math.cos(h),y=Math.sin(h),b=(d+=1*d)/Math.max(n[0],n[1]),_=n[1]/2,x=n[0]/2,v=f-(g*b*_-y*b*x),w=m-(y*b*_+g*b*x);if(null!=r){var T=.5;v=T*v+.5*r[2],w=T*w+.5*r[5],b=T*b+.5*r[7],Math.abs(h-r[6])<1&&(h=T*h+.5*r[6]),g=Math.cos(h),y=Math.sin(h)}return[g*b,-y*b,v,y*b,g*b,w,h,b]}(void 0===p?o:p,r,[this._trackerConfig.inWidth,this._trackerConfig.inHeight],t==FE.Detected||this._fastMvt?null:this._simCropToImage,this._config.normMode):a==uN.Hand?this._simCropToImage=function(e,t,n,r,a){var s=e.length/2,o=EE(e,t,s),i=Math.max(o[1]-o[0],o[3]-o[2]),u=$E("HAND",e),l=u[0],c=u[1],p=u[2];p+=3.1415,9==s?t[3]&&t[6]&&(l=.5*(e[3]+e[6]),c=.5*(e[3+s]+e[6+s]),t[1]&&(i=2*Math.sqrt(Math.pow(e[1]-l,2)+Math.pow(e[1+s]-l,2)))):(i=Math.max(o[1]-o[0],o[3]-o[2]),l=(o[1]+o[0])/2,c=(o[3]+o[2])/2);var h=Math.cos(p),d=Math.sin(p),f=(i+=1.2*i)/Math.max(n[0],n[1]),m=n[1]/2,g=n[0]/2,y=l-(h*f*m-d*f*g),b=c-(d*f*m+h*f*g);if(null!=r){var _=.9;y=_*y+(1-_)*r[2],b=_*b+(1-_)*r[5],f=.3*f+.7*r[7],Math.abs(p-r[6])<1&&(p=.3*p+.7*r[6]),h=Math.cos(p),d=Math.sin(p)}return[h*f,-d*f,y,d*f,h*f,b,p,f]}(void 0===p?o:p,r,[this._trackerConfig.inWidth,this._trackerConfig.inHeight],t==FE.Detected||this._fastMvt?null:this._simCropToImage,this._config.normMode):this._simCropToImage=function(e,t,n,r,a,s){var o,i,u=e.length/2;void 0===s&&((o=$E(a,e))[0],o[1],s=o[2]),i=SE(e,u);var l=Math.cos(s),c=Math.sin(s),p=Math.sqrt((i[1]-i[0])*(i[1]-i[0])+(i[3]-i[2])*(i[3]-i[2])),h=.3;"NECKLACE"==a&&(h=.5),"MARTEL-BOTTLE"==a&&(h=.2),"EQA"==a&&(h=.2),"BARTENDER"==a&&(h=.2);var d=(p+=h*p)/Math.max(n,t),f=(t-1)/2,m=(n-1)/2,g=(i[0]+i[1])/2-(l*d*f-c*d*m),y=(i[2]+i[3])/2-(c*d*f+l*d*m);if(null!=r){if("NECKLACE"==a){var b=.9;g=b*g+(1-b)*r[2],y=b*y+(1-b)*r[5],d=.3*d+.7*r[7],Math.abs(s-r[6])<1&&(s=.3*s+.7*r[6])}else{var _=Math.sqrt((g-r[2])*(g-r[2])+(y-r[5])*(y-r[5])),x=1;_>20&&(x=.1),_>=10&&_<=20&&(x=1-.09*(_-5)),g=(1-x)*g+x*r[2],y=(1-x)*y+x*r[5],s=Math.abs(s-r[6])>1?(1-x)*s-x*r[6]:(1-x)*s+x*r[6],d=(1-x)*d+x*r[7]}l=Math.cos(s),c=Math.sin(s)}return[l*d,-c*d,g,c*d,l*d,y,s,d]}(void 0===p?o:p,this._trackerConfig.inWidth,this._trackerConfig.inHeight,t==FE.Detected||this._fastMvt?null:this._simCropToImage,a,c);var _=new ImageData(this._trackerConfig.inWidth,this._trackerConfig.inHeight);_=ME(e,_,this._simCropToImage),this._debug&&t!=FE.Detected&&(this._debugInitialized=!0,this._debugImage=_);var x=fN(this._tfKeypointsTracker,this._trackerConfig,this._poseModule,[this._bufferHeatmaps],[this._bufferKeypsTrack],[this._bufferFeatureScores],[_],[this._flipMode]),v=AE(x.coordinates[0],this._simCropToImage,this._flipMode,new Int32Array([this._trackerConfig.outHeight,this._trackerConfig.outWidth]));if(t!=FE.Detected){var w=CE(x.scores[0],this._config.validTrackedKeypThs);if(a==uN.Face&&!this._nonRigidInitialized){var T=this._pose.project(this._keypsVts,oN.getCameraMat(this._config.fovY,this._currentWidth,this._currentHeight)),k=v.length/2;for(f=0;f<k;f++)0==w[f]&&(w[f]=1,v[f]=T[2*f],v[f+k]=T[2*f+1])}v=PE(v,w,o,r,.1)}return{imageFilteredKeyps:v,cropKeyps:x.coordinates[0],scores:x.scores[0]}},e.prototype.trackSubGeometrySync=function(e,t,n){var r=this;if(!(this._config.subTrackerCenterIds&&this._config.subTrackerAngleIds&&this._config.subTrackerIds&&this._config.subTrackerExtRatio))return{subTrackerKeyps:[new Float32Array(0)],subTrackerKeypsScores:[new Float32Array(0)],subTrackerVisibility:[new Int32Array(0)]};var a=BE(t,new Int32Array([this._subTrackerConfig.inWidth,this._subTrackerConfig.inHeight]),this._config.subTrackerIds,this._config.subTrackerAngleIds,this._config.subTrackerCenterIds,this._config.subTrackerExtRatio,this._config.subTrackerAngleShift),s=[a],o=[ME(e,new ImageData(this._subTrackerConfig.inWidth,this._subTrackerConfig.inHeight),a)];if(this._config.subTrackerSymmetric&&this._config.subTrackerSymmetricIds){var i=BE(t,new Int32Array([this._subTrackerConfig.inWidth,this._subTrackerConfig.inHeight]),this._config.subTrackerSymmetricIds,this._config.subTrackerAngleIds,this._config.subTrackerCenterIds,this._config.subTrackerExtRatio,this._config.subTrackerAngleShift);s=s.concat([i]);var u=new ImageData(this._subTrackerConfig.inWidth,this._subTrackerConfig.inHeight);o=o.concat([ME(e,u,i)])}var l=[""],c=[this._poseModule._malloc(2*this._subTrackerOutDims[3]*this._float_size)],p=[this._poseModule._malloc(this._subTrackerOutDims[3]*this._float_size)];this._config.subTrackerSymmetric&&(c=c.concat([this._poseModule._malloc(2*this._subTrackerOutDims[3]*this._float_size)]),p=p.concat([this._poseModule._malloc(this._subTrackerOutDims[3]*this._float_size)]),l=l.concat(["left_right"]));for(var h=fN(this._tfSubTracker,this._subTrackerConfig,null,[this._bufSubTrackerHmaps,this._bufSubTrackerHmapsSym],c,p,o,l),d=0;d<c.length;d++)this._poseModule._free(c[d]);for(d=0;d<p.length;d++)this._poseModule._free(p[d]);var f=[],m=[],g=[];return h.coordinates.forEach((function(e,t){m=m.concat([h.scores[t]]);var n=new Int32Array(h.scores[t].length);h.scores[t].forEach((function(e,t){n[t]=e>.25?1:0})),g=g.concat([n]),r._subTrackerCropKeyps&&r._subTrackerCropKeyps.length>t?r._subTrackerCropKeyps[t]=PE(e,n,r._subTrackerCropKeyps[t],r._subTrackerVis[t],.1):r._subTrackerCropKeyps=r._subTrackerCropKeyps.concat([e]);var a=AE(r._subTrackerCropKeyps[t],s[t],l[t],new Int32Array([r._subTrackerConfig.outHeight,r._subTrackerConfig.outWidth]));f=f.concat([a])})),{subTrackerKeyps:f,subTrackerKeypsScores:m,subTrackerVisibility:g}},e.prototype.computePoseSync=function(e,t){return this._nonRigidInitialized&&(mN(t)||t==uN.Wrist||t==uN.Face)?this.computeNonRigidPoseSync(e,t):this.computeRigidPoseSync(e,t)},e.prototype.computeRigidPoseSync=function(e,t){var n=this,r=-1,a=this._poseModule.cwrap("xzimgEstimateRigidPose","number",["number","number","number","number","number","number","number","number","number","number","number","number"]);if(e==FE.Detection){var s=0,o=0,i=t==uN.Necklace?3:0,u=1,l=[1,0,0,0,1,0],c=(h=this._poseModule._malloc(6*this._float_size))/4,p=this._poseModule.HEAPF32.subarray(c,c+6);return this._trackHasHeatmaps?p.set(this._simCropToImage.slice(0,6)):p.set(l),r=a(this._bufferHeatmaps,this._detectorOutDims[1],this._detectorOutDims[2],this._detectorOutDims[3],s,h,this._bufferKeypsDet,this.isMirrored()?this._bufMirroredKeyps3D:this._bufKeyps3D,o,i,u,this._bufInOutPose),this._pose=new oN(new Float32Array(this._poseModule.HEAPF32.buffer,this._bufInOutPose,9),new Float32Array(this._poseModule.HEAPF32.buffer,this._bufInOutPose+9*this._float_size,3)),r}if(e==FE.Detected||e==FE.Tracking){s=0,o=e!=FE.Tracking||this._resetPose?0:1,this._resetPose=!1,i=t==uN.Hand||t==uN.Necklace||t==uN.Lamborghini?3:1,u=t==uN.Hand||t==uN.Necklace||t==uN.Lamborghini?3:1,c=(h=this._poseModule._malloc(6*this._float_size))/4;var h,d=this._poseModule.HEAPF32.subarray(c,c+6);this._trackHasHeatmaps&&3==i?d.set(this._simCropToImage.slice(0,6)):(l=[1,0,0,0,1,0],d.set(l));var f=null,m=null,g=new Float32Array(2*this._activeIds.length),y=new Float32Array(3*this._activeIds.length),b=this._keyps2D.length/2;this._activeIds.length>0?(this._activeIds.forEach((function(e,t){g[t]=n._keyps2D[e],g[t+n._activeIds.length]=n._keyps2D[e+b]})),c=(f=this._poseModule._malloc(this._activeIds.length*this._float_size*2))/4,(d=this._poseModule.HEAPF32.subarray(c,c+2*this._activeIds.length)).set(g),this._activeIds.forEach((function(e,t){y[3*t]=n._keypsVts[3*e],n.isMirrored()&&(y[3*t]=-y[3*t]),y[3*t+1]=n._keypsVts[3*e+1],y[3*t+2]=n._keypsVts[3*e+2]})),c=(m=this._poseModule._malloc(this._activeIds.length*this._float_size*3))/4,(d=this._poseModule.HEAPF32.subarray(c,c+3*this._activeIds.length)).set(y),b=this._activeIds.length):(c=(f=this._poseModule._malloc(this._keyps2D.length*this._float_size))/4,(d=this._poseModule.HEAPF32.subarray(c,c+this._keyps2D.length)).set(this._keyps2D),2!=i&&3!=i||d.set(this._cropKeyps2D),m=this.isMirrored()?this._bufMirroredKeyps3D:this._bufKeyps3D),r=a(2==i||3==i?this._bufferHeatmaps:null,this._trackerOutDims[1],this._trackerOutDims[2],b,s,h,f,m,o,i,u,this._bufInOutPose);var _=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufInOutPose,9),x=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufInOutPose+9*this._float_size,3);this._pose=new oN(_,x);var v=this._pose.project(this._keypsVts,oN.getCameraMat(this._config.fovY,this._currentWidth,this._currentHeight));this._reprojKeyps2D=new Float32Array(v.length);for(var w=0;w<v.length/2;w++)this._reprojKeyps2D[w]=v[2*w],this._reprojKeyps2D[w+this._reprojKeyps2D.length/2]=v[2*w+1];if(t==uN.Necklace){var T=this._pose.getRot();T[5]>.35&&(console.log(T[2],T[5],T[8]),T[2]=0,T[5]=0,T[8]=-1,this._pose.updateRotation(T))}return this._keyps3D=this._pose.transform(this._keypsVts),this._debug&&console.log("reprojDist",r),f&&this._poseModule._free(f),m&&this._activeIds.length>0&&this._poseModule._free(m),h&&this._poseModule._free(h),r}return-1},e.prototype.computeNonRigidPoseSync=function(e,t){var n;n=mN(t)?this._poseModule.cwrap("xzimgEstimateBodyNonRigidPose","number",["number","number","number","number","number","number","number","number","number","number","number"]):this._poseModule.cwrap("xzimgEstimateNonRigidPoseBase","number",["number","number","number","number","number","number","number","number","number","number","number","number"]);var r,a=e==FE.Detected?1:0,s=this._trackerOutDims[3],o=(r=this._poseModule._malloc(this._keyps2D.length*this._float_size))/4;this._poseModule.HEAPF32.subarray(o,o+this._keyps2D.length).set(this._keyps2D);var i=this._poseModule._malloc(s*this._int_size),u=i/4;this._poseModule.HEAPF32.subarray(u,u+s).set(this._visibility),null==this._bufKeyps3D&&(this._bufKeyps3D=this._poseModule._malloc(s*this._float_size*3));var l=1e3;t==uN.Face&&(l=25),t==uN.Wrist&&(l=100);var c=performance.now(),p=n(a,r,s,i,5,l,this._config.reprojThs,.5,.75,.95,this._bufInOutPose,this._bufKeyps3D),h=performance.now();this.mean_t=.95*this.mean_t+.05*(h-c);var d=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufInOutPose,9),f=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufInOutPose+9*this._float_size,3);this._pose=new oN(d,f),this._keyps3D=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufKeyps3D,3*s),this._poseModule._free(r),this._poseModule._free(i);var m=this._poseModule.cwrap("xzimgEstimateGetNumVertices","number"),g=this._poseModule.cwrap("xzimgEstimateGetDenseVertices","number"),y=m();y>0&&(null==this._bufDenseVertices3D&&(this._bufDenseVertices3D=this._poseModule._malloc(y*this._float_size*3)),g(this._bufDenseVertices3D),this._denseVertices=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufDenseVertices3D,3*y));var b=this._poseModule.cwrap("xzimgEstimateGetNumBlendShapes","number"),_=this._poseModule.cwrap("xzimgEstimateGetBlendShapes","number"),x=b();if(x>0){var v=this._poseModule._malloc(x*this._float_size),w=_(v);this._debug&&console.log(w),this._bsCoefs=new Float32Array(this._poseModule.HEAPF32.buffer,v,x),this._poseModule._free(v)}return this._debug&&console.log(p),this._debug&&console.log(d),this._debug&&console.log(f),p},e}()})(),r})()));
|