deepar 5.6.19 → 5.6.21

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.
@@ -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:()=>jC,Geometry:()=>QC,Segmentation:()=>tT,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))}"function"==typeof SuppressedError&&SuppressedError;var i=function(){function e(e,t,n){this.NB_BUFFERS=5,this._videoFrames=[],this._nbFramesDelay=0,this._videoElement=e,null!==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(){return this._nbFramesDelay>0&&this._videoFrames.length>0?this._nbFramesDelay<this._videoFrames.length?this._videoFrames[this._nbFramesDelay]:this._videoFrames[this._videoFrames.length-1]:this.getLastBuffer()},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 w="function"==typeof Symbol?Symbol("rxSubscriber"):"@@rxSubscriber_"+Math.random(),v=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 k(s,n));break}default:s.syncErrorThrowable=!0,s.destination=new k(s,n,r,a)}return s}return l(t,e),t.prototype[w]=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}(_),k=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}(v),I="function"==typeof Symbol&&Symbol.observable||"@@observable";function T(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 v)return e;if(e[w])return e[w]()}return e||t||n?new v(e,t,n):new v(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 v?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[I]=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?T: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()}},A="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator",C=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 M=function(e){if(e&&"function"==typeof e[I])return r=e,function(e){var t=r[I]();if("function"!=typeof t.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return t.subscribe(e)};if(C(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[A])return t=e,function(e){for(var n=t[A]();;){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.")},F=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}(v),$=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}(v);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}(v);function P(e,t,n,r,a){if(void 0===a&&(a=new D(e,n,r)),!a.closed)return t instanceof S?t.subscribe(a):M(t)(a)}var L=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}(v);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 W={};function z(){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 V(n))}var V=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(W),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(P(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===W?--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}(L);function G(e,t){return t?function(e,t){if(null!=e){if(function(e){return e&&"function"==typeof e[I]}(e))return function(e,t){return new S((function(n){var r=new _;return r.add(t.schedule((function(){var a=e[I]();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(C(e))return B(e,t);if(function(e){return e&&"function"==typeof e[A]}(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[A](),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(M(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}(v),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}(v),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}(v),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[w]=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}(v);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 F(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=M(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}($);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}(v);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 we(){throw new Error("clearTimeout has not been defined")}var ve=xe,ke=we;function Ie(e){if(ve===setTimeout)return setTimeout(e,0);if((ve===xe||!ve)&&setTimeout)return ve=setTimeout,setTimeout(e,0);try{return ve(e,0)}catch(t){try{return ve.call(null,e,0)}catch(t){return ve.call(this,e,0)}}}"function"==typeof _e.setTimeout&&(ve=setTimeout),"function"==typeof _e.clearTimeout&&(ke=clearTimeout);var Te,Se=[],Ee=!1,Ne=-1;function Ae(){Ee&&Te&&(Ee=!1,Te.length?Se=Te.concat(Se):Ne=-1,Se.length&&Ce())}function Ce(){if(!Ee){var e=Ie(Ae);Ee=!0;for(var t=Se.length;t;){for(Te=Se,Se=[];++Ne<t;)Te&&Te[Ne].run();Ne=-1,t=Se.length}Te=null,Ee=!1,function(e){if(ke===clearTimeout)return clearTimeout(e);if((ke===we||!ke)&&clearTimeout)return ke=clearTimeout,clearTimeout(e);try{ke(e)}catch(t){try{return ke.call(null,e)}catch(t){return ke.call(this,e)}}}(e)}}function Re(e,t){this.fun=e,this.array=t}function Me(){}Re.prototype.run=function(){this.fun.apply(null,this.array)};var Fe=Me,$e=Me,Oe=Me,De=Me,Pe=Me,Le=Me,Be=Me,Ue=_e.performance||{},We=Ue.now||Ue.mozNow||Ue.msNow||Ue.oNow||Ue.webkitNow||function(){return(new Date).getTime()},ze=new Date,Ve={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||Ie(Ce)},title:"browser",browser:!0,env:{},argv:[],version:"",versions:{},on:Fe,addListener:$e,once:Oe,off:De,removeListener:Pe,removeAllListeners:Le,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*We.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-ze)/1e3}},He=Ve;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){return ct(e,t)}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=wt(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}function wt(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 vt(e){e.forEach((t=>{Qe(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function kt(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 It(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 Tt(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&&(At().getBool("IS_TEST")||At().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];At().getBool("IS_TEST")||At().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(Tt(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)}getString(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){const n=t.toLowerCase();return"true"===n||"false"===n?"true"===n:""+ +n===n?+n:t}(0,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 At(){return Rt}let Ct,Rt=null;function Mt(){if(null==Ct){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}Ct=e}return Ct}function Ft(e,t){const n=function(){const e=Mt();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 $t="Acos",Ot="Acosh",Dt="Add",Pt="AddN",Lt="All",Bt="Any",Ut="ArgMax",Wt="ArgMin",zt="Asin",Vt="Asinh",Ht="Atan",Gt="Atanh",jt="Atan2",Kt="AvgPool",qt="AvgPool3D",Xt="BatchMatMul",Yt="BatchToSpaceND",Qt="Bincount",Jt="BitwiseAnd",Zt="BroadcastArgs",en="Cast",tn="Ceil",nn="ClipByValue",rn="Concat",an="Conv2D",sn="Conv2DBackpropInput",on="Conv3D",un="Conv3DBackpropFilterV2",ln="Conv3DBackpropInputV2",cn="Cosh",pn="Cumprod",hn="Cumsum",dn="CropAndResize",fn="DenseBincount",mn="DepthToSpace",gn="DepthwiseConv2dNative",yn="Diag",bn="Dilation2D",_n="Dilation2DBackpropInput",xn="Dilation2DBackpropFilter",wn="RealDiv",vn="Elu",kn="EluGrad",In="Equal",Tn="Exp",Sn="ExpandDims",En="Expm1",Nn="Fill",An="FlipLeftRight",Cn="Floor",Rn="FloorDiv",Mn="FusedBatchNorm",Fn="GatherV2",$n="GatherNd",On="Greater",Dn="GreaterEqual",Pn="Identity",Ln="IsFinite",Bn="IsInf",Un="IsNan",Wn="LeakyRelu",zn="Less",Vn="LessEqual",Hn="LinSpace",Gn="Log1p",jn="LogicalAnd",Kn="LogicalNot",qn="LogicalOr",Xn="LRN",Yn="LRNGrad",Qn="Max",Jn="Maximum",Zn="MaxPool",er="MaxPool3D",tr="MaxPoolWithArgmax",nr="Mean",rr="Min",ar="Minimum",sr="MirrorPad",or="Multinomial",ir="Multiply",ur="NotEqual",lr="NonMaxSuppressionV3",cr="NonMaxSuppressionV4",pr="NonMaxSuppressionV5",hr="OnesLike",dr="OneHot",fr="Pack",mr="PadV2",gr="Prelu",yr="Prod",br="Range",_r="Reciprocal",xr="Relu",wr="Reshape",vr="ResizeNearestNeighbor",kr="ResizeNearestNeighborGrad",Ir="ResizeBilinear",Tr="ResizeBilinearGrad",Sr="Relu6",Er="Reverse",Nr="Round",Ar="Rsqrt",Cr="ScatterNd",Rr="TensorScatterUpdate",Mr="SearchSorted",Fr="Select",$r="Selu",Or="Slice",Dr="Sinh",Pr="Sign",Lr="Sigmoid",Br="Softplus",Ur="Sqrt",Wr="Sum",zr="SpaceToBatchND",Vr="SplitV",Hr="Softmax",Gr="SparseFillEmptyRows",jr="SparseReshape",Kr="SparseSegmentMean",qr="SparseSegmentSum",Xr="SparseToDense",Yr="SquaredDifference",Qr="StridedSlice",Jr="StringNGrams",Zr="StringSplit",ea="StringToHashBucketFast",ta="Sub",na="Tanh",ra="Tile",aa="TopK",sa="Transform",oa="Transpose",ia="Unique",ua="Unpack",la="ZerosLike",ca="Step",pa="FromPixels",ha="RotateWithOffset",da="_FusedMatMul",fa="FusedConv2D",ma="FusedDepthwiseConv2D";function ga(...e){At().getBool("IS_TEST")||At().getBool("PROD")||console.warn(...e)}const ya=Ft("kernelRegistry",(()=>new Map)),ba=Ft("gradRegistry",(()=>new Map));function _a(e,t){const n=ka(e,t);return ya.get(n)}function xa(e){return ba.get(e)}function wa(e){const t=ya.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 va(e){const{kernelName:t,backendName:n}=e,r=ka(t,n);ya.has(r)&&ga(`The kernel '${t}' for backend '${n}' is already registered`),ya.set(r,e)}function ka(e,t){return`${t}_${e}`}function Ia(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var Ta=Ea,Sa=null;try{Sa=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 Ea(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function Na(e){return!0===(e&&e.__isLong__)}Ea.prototype.__isLong__,Object.defineProperty(Ea.prototype,"__isLong__",{value:!0}),Ea.isLong=Na;var Aa={},Ca={};function Ra(e,t){var n,r,a;return t?(a=0<=(e>>>=0)&&e<256)&&(r=Ca[e])?r:(n=Fa(e,(0|e)<0?-1:0,!0),a&&(Ca[e]=n),n):(a=-128<=(e|=0)&&e<128)&&(r=Aa[e])?r:(n=Fa(e,e<0?-1:0,!1),a&&(Aa[e]=n),n)}function Ma(e,t){if(isNaN(e))return t?za:Wa;if(t){if(e<0)return za;if(e>=La)return Ka}else{if(e<=-Ba)return qa;if(e+1>=Ba)return ja}return e<0?Ma(-e,t).neg():Fa(e%Pa|0,e/Pa|0,t)}function Fa(e,t,n){return new Ea(e,t,n)}Ea.fromInt=Ra,Ea.fromNumber=Ma,Ea.fromBits=Fa;var $a=Math.pow;function Oa(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return Wa;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 Oa(e.substring(1),t,n).neg();for(var a=Ma($a(n,8)),s=Wa,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=Ma($a(n,i));s=s.mul(l).add(Ma(u))}else s=(s=s.mul(a)).add(Ma(u))}return s.unsigned=t,s}function Da(e,t){return"number"==typeof e?Ma(e,t):"string"==typeof e?Oa(e,t):Fa(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}Ea.fromString=Oa,Ea.fromValue=Da;var Pa=4294967296,La=Pa*Pa,Ba=La/2,Ua=Ra(1<<24),Wa=Ra(0);Ea.ZERO=Wa;var za=Ra(0,!0);Ea.UZERO=za;var Va=Ra(1);Ea.ONE=Va;var Ha=Ra(1,!0);Ea.UONE=Ha;var Ga=Ra(-1);Ea.NEG_ONE=Ga;var ja=Fa(-1,2147483647,!1);Ea.MAX_VALUE=ja;var Ka=Fa(-1,-1,!0);Ea.MAX_UNSIGNED_VALUE=Ka;var qa=Fa(0,-2147483648,!1);Ea.MIN_VALUE=qa;var Xa=Ea.prototype;Xa.toInt=function(){return this.unsigned?this.low>>>0:this.low},Xa.toNumber=function(){return this.unsigned?(this.high>>>0)*Pa+(this.low>>>0):this.high*Pa+(this.low>>>0)},Xa.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(qa)){var t=Ma(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=Ma($a(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}},Xa.getHighBits=function(){return this.high},Xa.getHighBitsUnsigned=function(){return this.high>>>0},Xa.getLowBits=function(){return this.low},Xa.getLowBitsUnsigned=function(){return this.low>>>0},Xa.getNumBitsAbs=function(){if(this.isNegative())return this.eq(qa)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&!(e&1<<t);t--);return 0!=this.high?t+33:t+1},Xa.isZero=function(){return 0===this.high&&0===this.low},Xa.eqz=Xa.isZero,Xa.isNegative=function(){return!this.unsigned&&this.high<0},Xa.isPositive=function(){return this.unsigned||this.high>=0},Xa.isOdd=function(){return!(1&~this.low)},Xa.isEven=function(){return!(1&this.low)},Xa.equals=function(e){return Na(e)||(e=Da(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low},Xa.eq=Xa.equals,Xa.notEquals=function(e){return!this.eq(e)},Xa.neq=Xa.notEquals,Xa.ne=Xa.notEquals,Xa.lessThan=function(e){return this.comp(e)<0},Xa.lt=Xa.lessThan,Xa.lessThanOrEqual=function(e){return this.comp(e)<=0},Xa.lte=Xa.lessThanOrEqual,Xa.le=Xa.lessThanOrEqual,Xa.greaterThan=function(e){return this.comp(e)>0},Xa.gt=Xa.greaterThan,Xa.greaterThanOrEqual=function(e){return this.comp(e)>=0},Xa.gte=Xa.greaterThanOrEqual,Xa.ge=Xa.greaterThanOrEqual,Xa.compare=function(e){if(Na(e)||(e=Da(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},Xa.comp=Xa.compare,Xa.negate=function(){return!this.unsigned&&this.eq(qa)?qa:this.not().add(Va)},Xa.neg=Xa.negate,Xa.add=function(e){Na(e)||(e=Da(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,Fa((c&=65535)<<16|(p&=65535),(u&=65535)<<16|(l&=65535),this.unsigned)},Xa.subtract=function(e){return Na(e)||(e=Da(e)),this.add(e.neg())},Xa.sub=Xa.subtract,Xa.multiply=function(e){if(this.isZero())return Wa;if(Na(e)||(e=Da(e)),Sa)return Fa(Sa.mul(this.low,this.high,e.low,e.high),Sa.get_high(),this.unsigned);if(e.isZero())return Wa;if(this.eq(qa))return e.isOdd()?qa:Wa;if(e.eq(qa))return this.isOdd()?qa:Wa;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(Ua)&&e.lt(Ua))return Ma(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,Fa((p&=65535)<<16|(h&=65535),(l&=65535)<<16|(c&=65535),this.unsigned)},Xa.mul=Xa.multiply,Xa.divide=function(e){if(Na(e)||(e=Da(e)),e.isZero())throw Error("division by zero");var t,n,r;if(Sa)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?Fa((this.unsigned?Sa.div_u:Sa.div_s)(this.low,this.high,e.low,e.high),Sa.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?za:Wa;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return za;if(e.gt(this.shru(1)))return Ha;r=za}else{if(this.eq(qa))return e.eq(Va)||e.eq(Ga)?qa:e.eq(qa)?Va:(t=this.shr(1).div(e).shl(1)).eq(Wa)?e.isNegative()?Va:Ga:(n=this.sub(e.mul(t)),r=t.add(n.div(e)));if(e.eq(qa))return this.unsigned?za:Wa;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=Wa}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:$a(2,a-48),o=Ma(t),i=o.mul(e);i.isNegative()||i.gt(n);)i=(o=Ma(t-=s,this.unsigned)).mul(e);o.isZero()&&(o=Va),r=r.add(o),n=n.sub(i)}return r},Xa.div=Xa.divide,Xa.modulo=function(e){return Na(e)||(e=Da(e)),Sa?Fa((this.unsigned?Sa.rem_u:Sa.rem_s)(this.low,this.high,e.low,e.high),Sa.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},Xa.mod=Xa.modulo,Xa.rem=Xa.modulo,Xa.not=function(){return Fa(~this.low,~this.high,this.unsigned)},Xa.and=function(e){return Na(e)||(e=Da(e)),Fa(this.low&e.low,this.high&e.high,this.unsigned)},Xa.or=function(e){return Na(e)||(e=Da(e)),Fa(this.low|e.low,this.high|e.high,this.unsigned)},Xa.xor=function(e){return Na(e)||(e=Da(e)),Fa(this.low^e.low,this.high^e.high,this.unsigned)},Xa.shiftLeft=function(e){return Na(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Fa(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):Fa(0,this.low<<e-32,this.unsigned)},Xa.shl=Xa.shiftLeft,Xa.shiftRight=function(e){return Na(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Fa(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):Fa(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},Xa.shr=Xa.shiftRight,Xa.shiftRightUnsigned=function(e){if(Na(e)&&(e=e.toInt()),0==(e&=63))return this;var t=this.high;return e<32?Fa(this.low>>>e|t<<32-e,t>>>e,this.unsigned):Fa(32===e?t:t>>>e-32,0,this.unsigned)},Xa.shru=Xa.shiftRightUnsigned,Xa.shr_u=Xa.shiftRightUnsigned,Xa.toSigned=function(){return this.unsigned?Fa(this.low,this.high,!1):this},Xa.toUnsigned=function(){return this.unsigned?this:Fa(this.low,this.high,!0)},Xa.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},Xa.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]},Xa.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]},Ea.fromBytes=function(e,t,n){return n?Ea.fromBytesLE(e,t):Ea.fromBytesBE(e,t)},Ea.fromBytesLE=function(e,t){return new Ea(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},Ea.fromBytesBE=function(e,t){return new Ea(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};const Ya=Ta||e({__proto__:null,default:Ta},[Ta]);function Qa(e){return Ya.fromString(e,!0,16)}const Ja=Qa("c3a5c85c97cb3127"),Za=Qa("b492b66fbe98f273"),es=Qa("9ae16a3b2f90404f");function ts(e){return e.xor(e.shru(47))}function ns(e,t,n){const r=e.slice(t,t+n);return Ya.fromBytes(Array.from(r),!0,!0)}function rs(e,t){return ns(e,t,8)}function as(e,t){return ns(e,t,4)}function ss(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function os(e,t,n=Qa("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 is(e,t,n,r){return function(e,t,n,r,a,s){a=a.add(e),s=ss(s.add(a).add(r),21);const o=a;return a=(a=a.add(t)).add(n),s=s.add(ss(a,44)),[a.add(r),s.add(o)]}(rs(e,t),rs(e,t+8),rs(e,t+16),rs(e,t+24),n,r)}function us(e,t=e.length){const n=Ya.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=es.add(2*t),r=rs(e,0).add(es),a=rs(e,t-8);return os(ss(a,37).mul(n).add(r),ss(r,25).add(a).mul(n),n)}if(t>=4){const n=es.add(2*t);return os(as(e,0).shl(3).add(t),as(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),r=t+(e[t-1]<<2);return ts(es.mul(n).xor(Ja.mul(r))).mul(es)}return es}(e,t):function(e,t=e.length){const n=es.add(2*t),r=rs(e,0).mul(Za),a=rs(e,8),s=rs(e,t-8).mul(n),o=rs(e,t-16).mul(es);return os(ss(r.add(a),43).add(ss(s,30)).add(o),r.add(ss(a.add(es),18)).add(s),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=es.add(2*t),r=rs(e,0).mul(es),a=rs(e,8),s=rs(e,t-8).mul(n),o=rs(e,t-16).mul(es),i=ss(r.add(a),43).add(ss(s,30)).add(o),u=os(i,r.add(ss(a.add(es),18)).add(s),n),l=rs(e,16).mul(n),c=rs(e,24),p=i.add(rs(e,t-32)).mul(n),h=u.add(rs(e,t-24)).mul(n);return os(ss(l.add(c),43).add(ss(p,30)).add(h),l.add(ss(c.add(r),18)).add(p),n)}(e,t);let r=n,a=n.mul(Za).add(113),s=ts(a.mul(es).add(113)).mul(es),o=[Ya.UZERO,Ya.UZERO],i=[Ya.UZERO,Ya.UZERO];r=r.mul(es).add(rs(e,0));let u=0;const l=64*(t-1>>6),c=l+(t-1&63)-63;do{r=ss(r.add(a).add(o[0]).add(rs(e,u+8)),37).mul(Za),a=ss(a.add(o[1]).add(rs(e,u+48)),42).mul(Za),r=r.xor(i[1]),a=a.add(o[0]).add(rs(e,u+40)),s=ss(s.add(i[0]),33).mul(Za),o=is(e,u,o[1].mul(Za),r.add(i[0])),i=is(e,u+32,s.add(i[1]),a.add(rs(e,u+16))),[s,r]=[r,s],u+=64}while(u!==l);const p=Za.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=ss(r.add(a).add(o[0]).add(rs(e,u+8)),37).mul(p),a=ss(a.add(o[1]).add(rs(e,u+48)),42).mul(p),r=r.xor(i[1].mul(9)),a=a.add(o[0].mul(9).add(rs(e,u+40))),s=ss(s.add(i[0]),33).mul(p),o=is(e,u,o[1].mul(p),r.add(i[0])),i=is(e,u+32,s.add(i[1]),a.add(rs(e,u+16))),[s,r]=[r,s],os(os(o[0],i[0],p).add(ts(a).mul(Ja)).add(s),os(o[1],i[1],p).add(r),p)}function ls(e,t){return"string"===t?hs(e):cs([e],t)}function cs(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=ms(e)),At().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 ps(){return At().platform.now()}function hs(e,t="utf-8"){return t=t||"utf-8",At().platform.encode(e,t)}function ds(e,t="utf-8"){return t=t||"utf-8",At().platform.decode(e,t)}function fs(e){return null!=At().platform.isTypedArray?At().platform.isTypedArray(e):Ia(e)}function ms(e,t=[],n=!1){if(null==t&&(t=[]),"boolean"==typeof e||"number"==typeof e||"string"==typeof e||Tt(e)||null==e||fs(e)&&n)t.push(e);else if(Array.isArray(e)||fs(e))for(let r=0;r<e.length;++r)ms(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++)ms(e[a],t,n)}return t}class gs{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new bs)}profileKernel(e,t,n){let r;const a=()=>{r=n()};let s;const o=ps();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(a);else{a();for(const e of r)e.dataSync();s=Promise.resolve({kernelMs:ps()-o})}if(At().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<r.length;t++){const n=r[t];n.data().then((t=>{ys(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 ys(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 bs{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 _s(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?ks(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],xs(u[t+e],0,n).length)}return o}(e,t,n,a),o=t.length,i=vs(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 xs(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?ws(e):parseFloat(e.toFixed(7)).toString(),at(r,t)}function ws(e){return 0===e?"false":"true"}function vs(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?[xs(ks(e)[0],0,n)]:"bool"===n?[ws(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=ks(r),s=ks(s)),["["+r.map(((e,t)=>xs(e,a[t],n))).join(", ")+", ..., "+s.map(((e,t)=>xs(e,a[i-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?ks(e):Array.from(e)).map(((e,t)=>xs(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(...vs(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(...vs(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(...vs(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 ks(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class Is{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 Ts().makeTensor(this.values,this.shape,this.dtype)}}let Ts=null,Ss=null;class Es{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 Ss.buffer(this.shape,this.dtype,e)}bufferSync(){return Ss.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=Ts().read(this.dataId);if("string"===this.dtype){const t=await e;try{return t.map((e=>ds(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(),Ts().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=Ts().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>ds(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 Ts().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),Ts().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Ss.print(this,e)}clone(){return this.throwIfDisposed(),Ss.clone(this)}toString(e=!1){return _s(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Ss.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Ts().makeVariable(this,e,t,n)}}function Ns(){return Ft("Tensor",(()=>Es))}Object.defineProperty(Es,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),Ns();class As extends Es{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`);Ts().disposeTensor(this),this.dataId=e.dataId,Ts().incRef(this,null)}dispose(){Ts().disposeVariable(this),this.isDisposedInternal=!0}}var Cs,Rs,Ms,Fs,$s;Object.defineProperty(As,Symbol.hasInstance,{value:e=>e instanceof Es&&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"}(Cs||(Cs={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(Rs||(Rs={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(Ms||(Ms={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(Fs||(Fs={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}($s||($s={}));const Os={float32:Fs,int32:Rs,bool:Ms,complex64:$s};function Ds(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Os[e][t]}function Ps(e){return null!=e&&"object"==typeof e&&"texture"in e&&e.texture instanceof WebGLTexture}function Ls(e){return"undefined"!=typeof GPUBuffer&&null!=e&&"object"==typeof e&&"buffer"in e&&e.buffer instanceof GPUBuffer}function Bs(e,t){if(e.dtype===t.dtype)return[e,t];const n=Ds(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function Us(e){const t=[];return Ws(e,t,new Set),t}function Ws(e,t,n){if(null==e)return;if(e instanceof Es)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),Ws(r,t,n))}}function zs(e){return null!=e.kernelName}class Vs{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 Hs{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Vs}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?(ga(`${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 gs(this.backendInstance),!0}setupRegisteredKernels(){wa(this.backendName).forEach((e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){wa(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,ga(`Initialization of backend ${e} failed`),ga(n.stack||n.message)),!1)));return this.pendingBackendInit=r,{success:r,asyncInit:!0}}}catch(t){return ga(`Initialization of backend ${e} failed`),ga(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 Hs.nextTensorId++}nextVariableId(){return Hs.nextVariableId++}clone(e){const t=js.runKernel(Pn,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e};return js.runKernel(en,t,{dtype:"float32"})}})),[],{}),t}runKernel(e,t,n){if(null==this.backendName&&this.backend,null==_a(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=zs(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(zs(e)){const{kernelName:t,inputs:a,attrs:s}=e;null==this.backendName&&this.backend;const u=_a(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=zs(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=xa(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=>hs(e))));const s=r.write(a,t,n),o=new Es(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 Es(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 As(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 As||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=xa(e);null!=i&&(r=i.gradFunc),null!=r&&(o.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],r=wt(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=Us(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 Es,(()=>"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 js.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)),Ks);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 Es)),(()=>"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 Es,(()=>"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 Es)),(()=>"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=ps(),n=await this.backend.time(e);return n.wallMs=ps()-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 Vs;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 Gs(){const e=Mt();if(null==e._tfengine){const t=new Et(e);e._tfengine=new Hs(t)}var t;return t=e._tfengine.ENV,Rt=t,Ts=()=>e._tfengine,e._tfengine}Hs.nextTensorId=0,Hs.nextVariableId=0;const js=Gs();function Ks(e,t){const n={a:e,b:t};return js.runKernel(Dt,n)}function qs(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 Xs(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}const Ys=At();Ys.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.")})),Ys.registerFlag("IS_BROWSER",(()=>Xs())),Ys.registerFlag("IS_NODE",(()=>void 0!==He&&void 0!==He.versions&&void 0!==He.versions.node)),Ys.registerFlag("IS_CHROME",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor))),Ys.registerFlag("IS_SAFARI",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor))),Ys.registerFlag("PROD",(()=>!1)),Ys.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(()=>Ys.getBool("DEBUG"))),Ys.registerFlag("DEPRECATION_WARNINGS_ENABLED",(()=>!0)),Ys.registerFlag("IS_TEST",(()=>!1)),Ys.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",(()=>Ys.getBool("DEBUG"))),Ys.registerFlag("WRAP_TO_IMAGEBITMAP",(()=>!1)),Ys.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",(()=>!1)),Ys.registerFlag("USE_SETTIMEOUTCUSTOM",(()=>!1));var Qs=[],Js=[],Zs="undefined"!=typeof Uint8Array?Uint8Array:Array,eo=!1;function to(){eo=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0;t<64;++t)Qs[t]=e[t],Js[e.charCodeAt(t)]=t;Js["-".charCodeAt(0)]=62,Js["_".charCodeAt(0)]=63}function no(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(Qs[(a=r)>>18&63]+Qs[a>>12&63]+Qs[a>>6&63]+Qs[63&a]);return s.join("")}function ro(e){var t;eo||to();for(var n=e.length,r=n%3,a="",s=[],o=16383,i=0,u=n-r;i<u;i+=o)s.push(no(e,i,i+o>u?u:i+o));return 1===r?(t=e[n-1],a+=Qs[t>>2],a+=Qs[t<<4&63],a+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],a+=Qs[t>>10],a+=Qs[t>>4&63],a+=Qs[t<<2&63],a+="="),s.push(a),s.join("")}function ao(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 so(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 oo={}.toString,io=Array.isArray||function(e){return"[object Array]"==oo.call(e)};function uo(){return co.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function lo(e,t){if(uo()<t)throw new RangeError("Invalid typed array length");return co.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=co.prototype:(null===e&&(e=new co(t)),e.length=t),e}function co(e,t,n){if(!(co.TYPED_ARRAY_SUPPORT||this instanceof co))return new co(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 fo(this,e)}return po(this,e,t,n)}function po(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),co.TYPED_ARRAY_SUPPORT?(e=t).__proto__=co.prototype:e=mo(e,t),e}(e,t,n,r):"string"==typeof t?function(e,t,n){if("string"==typeof n&&""!==n||(n="utf8"),!co.isEncoding(n))throw new TypeError('"encoding" must be a valid string encoding');var r=0|bo(t,n),a=(e=lo(e,r)).write(t,n);return a!==r&&(e=e.slice(0,a)),e}(e,t,n):function(e,t){if(yo(t)){var n=0|go(t.length);return 0===(e=lo(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?lo(e,0):mo(e,t);if("Buffer"===t.type&&io(t.data))return mo(e,t.data)}var r;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function ho(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 fo(e,t){if(ho(t),e=lo(e,t<0?0:0|go(t)),!co.TYPED_ARRAY_SUPPORT)for(var n=0;n<t;++n)e[n]=0;return e}function mo(e,t){var n=t.length<0?0:0|go(t.length);e=lo(e,n);for(var r=0;r<n;r+=1)e[r]=255&t[r];return e}function go(e){if(e>=uo())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+uo().toString(16)+" bytes");return 0|e}function yo(e){return!(null==e||!e._isBuffer)}function bo(e,t){if(yo(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 Go(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return jo(e).length;default:if(r)return Go(e).length;t=(""+t).toLowerCase(),r=!0}}function _o(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 $o(this,t,n);case"utf8":case"utf-8":return Co(this,t,n);case"ascii":return Mo(this,t,n);case"latin1":case"binary":return Fo(this,t,n);case"base64":return Ao(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Oo(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function xo(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function wo(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=co.from(t,r)),yo(t))return 0===t.length?-1:vo(e,t,n,r,a);if("number"==typeof t)return t&=255,co.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):vo(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function vo(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 ko(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 Io(e,t,n,r){return Ko(Go(t,e.length-n),e,n,r)}function To(e,t,n,r){return Ko(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function So(e,t,n,r){return To(e,t,n,r)}function Eo(e,t,n,r){return Ko(jo(t),e,n,r)}function No(e,t,n,r){return Ko(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 Ao(e,t,n){return 0===t&&n===e.length?ro(e):ro(e.slice(t,n))}function Co(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<=Ro)return String.fromCharCode.apply(String,e);for(var n="",r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=Ro));return n}(r)}co.TYPED_ARRAY_SUPPORT=void 0===_e.TYPED_ARRAY_SUPPORT||_e.TYPED_ARRAY_SUPPORT,uo(),co.poolSize=8192,co._augment=function(e){return e.__proto__=co.prototype,e},co.from=function(e,t,n){return po(null,e,t,n)},co.TYPED_ARRAY_SUPPORT&&(co.prototype.__proto__=Uint8Array.prototype,co.__proto__=Uint8Array),co.alloc=function(e,t,n){return function(e,t,n,r){return ho(t),t<=0?lo(e,t):void 0!==n?"string"==typeof r?lo(e,t).fill(n,r):lo(e,t).fill(n):lo(e,t)}(null,e,t,n)},co.allocUnsafe=function(e){return fo(null,e)},co.allocUnsafeSlow=function(e){return fo(null,e)},co.isBuffer=function(e){return null!=e&&(!!e._isBuffer||qo(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&qo(e.slice(0,0))}(e))},co.compare=function(e,t){if(!yo(e)||!yo(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},co.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}},co.concat=function(e,t){if(!io(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return co.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=co.allocUnsafe(t),a=0;for(n=0;n<e.length;++n){var s=e[n];if(!yo(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(r,a),a+=s.length}return r},co.byteLength=bo,co.prototype._isBuffer=!0,co.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)xo(this,t,t+1);return this},co.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)xo(this,t,t+3),xo(this,t+1,t+2);return this},co.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)xo(this,t,t+7),xo(this,t+1,t+6),xo(this,t+2,t+5),xo(this,t+3,t+4);return this},co.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?Co(this,0,e):_o.apply(this,arguments)},co.prototype.equals=function(e){if(!yo(e))throw new TypeError("Argument must be a Buffer");return this===e||0===co.compare(this,e)},co.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+">"},co.prototype.compare=function(e,t,n,r,a){if(!yo(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},co.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},co.prototype.indexOf=function(e,t,n){return wo(this,e,t,n,!0)},co.prototype.lastIndexOf=function(e,t,n){return wo(this,e,t,n,!1)},co.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 ko(this,e,t,n);case"utf8":case"utf-8":return Io(this,e,t,n);case"ascii":return To(this,e,t,n);case"latin1":case"binary":return So(this,e,t,n);case"base64":return Eo(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return No(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},co.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Ro=4096;function Mo(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 Fo(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 $o(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+=Ho(e[s]);return a}function Oo(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 Do(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 Po(e,t,n,r,a,s){if(!yo(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 Lo(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 Bo(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 Uo(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 Wo(e,t,n,r,a){return a||Uo(e,0,n,4),so(e,t,n,r,23,4),n+4}function zo(e,t,n,r,a){return a||Uo(e,0,n,8),so(e,t,n,r,52,8),n+8}co.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),co.TYPED_ARRAY_SUPPORT)(n=this.subarray(e,t)).__proto__=co.prototype;else{var a=t-e;n=new co(a,void 0);for(var s=0;s<a;++s)n[s]=this[s+e]}return n},co.prototype.readUIntLE=function(e,t,n){e|=0,t|=0,n||Do(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r},co.prototype.readUIntBE=function(e,t,n){e|=0,t|=0,n||Do(e,t,this.length);for(var r=this[e+--t],a=1;t>0&&(a*=256);)r+=this[e+--t]*a;return r},co.prototype.readUInt8=function(e,t){return t||Do(e,1,this.length),this[e]},co.prototype.readUInt16LE=function(e,t){return t||Do(e,2,this.length),this[e]|this[e+1]<<8},co.prototype.readUInt16BE=function(e,t){return t||Do(e,2,this.length),this[e]<<8|this[e+1]},co.prototype.readUInt32LE=function(e,t){return t||Do(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},co.prototype.readUInt32BE=function(e,t){return t||Do(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},co.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||Do(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},co.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||Do(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},co.prototype.readInt8=function(e,t){return t||Do(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},co.prototype.readInt16LE=function(e,t){t||Do(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},co.prototype.readInt16BE=function(e,t){t||Do(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},co.prototype.readInt32LE=function(e,t){return t||Do(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},co.prototype.readInt32BE=function(e,t){return t||Do(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},co.prototype.readFloatLE=function(e,t){return t||Do(e,4,this.length),ao(this,e,!0,23,4)},co.prototype.readFloatBE=function(e,t){return t||Do(e,4,this.length),ao(this,e,!1,23,4)},co.prototype.readDoubleLE=function(e,t){return t||Do(e,8,this.length),ao(this,e,!0,52,8)},co.prototype.readDoubleBE=function(e,t){return t||Do(e,8,this.length),ao(this,e,!1,52,8)},co.prototype.writeUIntLE=function(e,t,n,r){e=+e,t|=0,n|=0,r||Po(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},co.prototype.writeUIntBE=function(e,t,n,r){e=+e,t|=0,n|=0,r||Po(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},co.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||Po(this,e,t,1,255,0),co.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},co.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||Po(this,e,t,2,65535,0),co.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Lo(this,e,t,!0),t+2},co.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||Po(this,e,t,2,65535,0),co.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Lo(this,e,t,!1),t+2},co.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||Po(this,e,t,4,4294967295,0),co.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):Bo(this,e,t,!0),t+4},co.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||Po(this,e,t,4,4294967295,0),co.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Bo(this,e,t,!1),t+4},co.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);Po(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},co.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);Po(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},co.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||Po(this,e,t,1,127,-128),co.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},co.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||Po(this,e,t,2,32767,-32768),co.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Lo(this,e,t,!0),t+2},co.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||Po(this,e,t,2,32767,-32768),co.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Lo(this,e,t,!1),t+2},co.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||Po(this,e,t,4,2147483647,-2147483648),co.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):Bo(this,e,t,!0),t+4},co.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||Po(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),co.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Bo(this,e,t,!1),t+4},co.prototype.writeFloatLE=function(e,t,n){return Wo(this,e,t,!0,n)},co.prototype.writeFloatBE=function(e,t,n){return Wo(this,e,t,!1,n)},co.prototype.writeDoubleLE=function(e,t,n){return zo(this,e,t,!0,n)},co.prototype.writeDoubleBE=function(e,t,n){return zo(this,e,t,!1,n)},co.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||!co.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},co.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&&!co.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=yo(e)?e:Go(new co(e,r).toString()),i=o.length;for(s=0;s<n-t;++s)this[s+t]=o[s%i]}return this};var Vo=/[^+\/0-9A-Za-z-_]/g;function Ho(e){return e<16?"0"+e.toString(16):e.toString(16)}function Go(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 jo(e){return function(e){var t,n,r,a,s,o;eo||to();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 Zs(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=Js[e.charCodeAt(t)]<<18|Js[e.charCodeAt(t+1)]<<12|Js[e.charCodeAt(t+2)]<<6|Js[e.charCodeAt(t+3)],o[u++]=a>>16&255,o[u++]=a>>8&255,o[u++]=255&a;return 2===s?(a=Js[e.charCodeAt(t)]<<2|Js[e.charCodeAt(t+1)]>>4,o[u++]=255&a):1===s&&(a=Js[e.charCodeAt(t)]<<10|Js[e.charCodeAt(t+1)]<<4|Js[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(Vo,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Ko(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 qo(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function Xo(e,t){let n=e;if(fs(e))return"string"===t?[]:[e.length];if(Ps(e)){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if(Ls(e))return[e.buffer.size/(null==t?4:ht(t))];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||fs(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&At().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Yo(e,r,[]),r}function Yo(e,t,n){if(n=n||[],!Array.isArray(e)&&!fs(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)Yo(e[t],r,n.concat(t))}function Qo(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 Jo(e,t,n,r="numeric"){if(e instanceof Ns())return Qo(r,e.dtype,t,n),e;let a=ft(e);if("string"!==a&&["bool","int32","float32"].indexOf(r)>=0&&(a=r),Qo(r,a,t,n),null==e||!fs(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=Xo(e,a);fs(e)||Array.isArray(e)||(e=[e]);const o="string"!==a?cs(e,a):ms(e,[],!0);return js.makeTensor(o,s,a)}function Zo(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)=>Jo(e,`${t}[${a}]`,n,r)))}const ei="__op";function ti(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+=ei;const a=(...e)=>{js.startScope(n);try{const t=r(...e);return Tt(t)&&console.error("Cannot return a Promise inside of tidy."),js.endScope(t),t}catch(e){throw js.endScope(null),e}};return Object.defineProperty(a,"name",{value:n,configurable:!0}),a}const ni=ti({complex_:function(e,t){const n=Jo(e,"real","complex"),r=Jo(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 js.runKernel("Complex",a)}});function ri(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(Ls(e)||Ps(e)){if("float32"!==r&&"int32"!==r)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${r}.`);return js.backend.createTensorFromGPUData(e,t||n,r)}if(!fs(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){vt(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 fs(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==r?cs(e,r):ms(e,[],!0),js.makeTensor(e,t,r)}function ai(e,t,n){return ri(e,t,Xo(e,n),n)}const si={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};class oi{static join(e){return new oi(e).slice()}constructor(e){if(this.shards=[],this.previousShardIndex=0,null==e)return;if(e instanceof Array||(e=[e]),0===(e=e.map((e=>fs(e)?e.buffer:e))).length)return;this.bufferUniformSize=e[0].byteLength;let t=0;for(let n=0;n<e.length;n++){const r=e[n];n!==e.length-1&&r.byteLength!==this.bufferUniformSize&&(this.bufferUniformSize=void 0);const a=t+r.byteLength;this.shards.push({buffer:r,start:t,end:a}),t=a}0===this.shards.length&&(this.byteLength=0),this.byteLength=this.shards[this.shards.length-1].end}slice(e=0,t=this.byteLength){if(0===this.shards.length)return new ArrayBuffer(0);if(e=isNaN(Number(e))?0:e,t=isNaN(Number(t))?0:t,e=Math.max(0,e),(t=Math.min(this.byteLength,t))<=e)return new ArrayBuffer(0);const n=this.findShardForByte(e);if(-1===n)throw new Error(`Could not find start shard for byte ${e}`);const r=new ArrayBuffer(t-e),a=new Uint8Array(r);let s=0;for(let r=n;r<this.shards.length;r++){const n=this.shards[r],o=e+s-n.start,i=s,u=Math.min(t,n.end)-n.start,l=new Uint8Array(n.buffer,o,u-o);if(a.set(l,i),s+=l.length,t<n.end)break}return r}findShardForByte(e){if(0===this.shards.length||e<0||e>=this.byteLength)return-1;if(null!=this.bufferUniformSize)return this.previousShardIndex=Math.floor(e/this.bufferUniformSize),this.previousShardIndex;function t(t){return e<t.start?-1:e>=t.end?1:0}if(0===t(this.shards[this.previousShardIndex]))return this.previousShardIndex;const n=function(e,t){let n=0,r=e.length;for(;n<=r;){const a=Math.floor((r-n)/2)+n,s=t(e[a]);if(0===s)return a;s<0?r=a:n=a+1}return-1}(this.shards,t);return-1===n?-1:(this.previousShardIndex=n,this.previousShardIndex)}}function ii(){return js}function ui(e,t){return js.tidy(e,t)}function li(e){Us(e).forEach((e=>e.dispose()))}function ci(e){return js.keep(e)}function pi(e){return js.setBackend(e)}function hi(){return js.backendName}function di(e,t,n=1){return js.registerBackend(e,t,n)}function fi(e,t){const n=new oi(e),r={};let a=0;for(const e of t){const t=mi(e,((e,t)=>n.slice(a+e,a+t)));r[e.name]=yi(e,n.slice(a,a+t)),a+=t}return r}function mi(e,t){const n=et(e.shape);let r;if("quantization"in e){const t=e.quantization;r=si[t.dtype]}else{if("string"===e.dtype){let e=0;for(let r=0;r<n;r++)e+=4+new Uint32Array(t(e,e+4))[0];return e}r=si[e.dtype]}return n*r}async function gi(e,t){const n=et(e.shape);let r;if("quantization"in e){const t=e.quantization;r=si[t.dtype]}else{if("string"===e.dtype){let e=0;for(let r=0;r<n;r++)e+=4+new Uint32Array(await t(e,e+4))[0];return e}r=si[e.dtype]}return n*r}function yi(e,t){const n=e.name,r=e.dtype,a=e.shape,s=et(a);let o,i=0;if("quantization"in e){const a=e.quantization;if("uint8"===a.dtype||"uint16"===a.dtype){if(!("min"in a)||!("scale"in a))throw new Error(`Weight ${e.name} with quantization ${a.dtype} doesn't have corresponding metadata min and scale.`)}else{if("float16"!==a.dtype)throw new Error(`Weight ${e.name} has unknown quantization dtype ${a.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);if("float32"!==r)throw new Error(`Weight ${e.name} is quantized with ${a.dtype} which only supports weights of type float32 not ${r}.`)}const u=si[a.dtype],l="uint8"===a.dtype?new Uint8Array(t):new Uint16Array(t);if("float32"===r)if("uint8"===a.dtype||"uint16"===a.dtype){o=new Float32Array(l.length);for(let e=0;e<l.length;e++){const t=l[e];o[e]=t*a.scale+a.min}}else{if("float16"!==a.dtype)throw new Error(`Unsupported quantization type ${a.dtype} for weight type float32.`);{const e=function(){const e=function(){const e=e=>{let t=e<<13,n=0;for(;!(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)}}();o=e(l)}}else{if("int32"!==r)throw new Error(`Unsupported dtype in weight '${n}': ${r}`);if("uint8"!==a.dtype&&"uint16"!==a.dtype)throw new Error(`Unsupported quantization type ${a.dtype} for weight type int32.`);o=new Int32Array(l.length);for(let e=0;e<l.length;e++){const t=l[e];o[e]=Math.round(t*a.scale+a.min)}}i+=s*u}else if("string"===r){const n=et(e.shape);o=[];for(let e=0;e<n;e++){const e=new Uint32Array(t.slice(i,i+4))[0];i+=4;const n=new Uint8Array(t.slice(i,i+e));o.push(n),i+=e}}else{const e=si[r];if("float32"===r)o=new Float32Array(t);else if("int32"===r)o=new Int32Array(t);else{if("bool"!==r){if("complex64"===r){o=new Float32Array(t);const e=new Float32Array(o.length/2),n=new Float32Array(o.length/2);for(let t=0;t<e.length;t++)e[t]=o[2*t],n[t]=o[2*t+1];const r=ai(e,a,"float32"),s=ai(n,a,"float32"),i=ni(r,s);return r.dispose(),s.dispose(),i}throw new Error(`Unsupported dtype in weight '${n}': ${r}`)}o=new Uint8Array(t)}i+=s*e}return ai(o,a,r)}async function bi(e,t,n){let r=new Uint8Array(t);for(;r.byteLength<n;){const{done:t,value:a}=await e.read();if(t&&null==a){const e=n-r.byteLength;throw new Error(`Reader is done but ${e} bytes are still expected`)}const s=new Uint8Array(r.length+a.byteLength);s.set(r,0),s.set(new Uint8Array(a),r.length),r=s}return r.buffer}async function _i(e,t){const n={},r=e.getReader();let a=new ArrayBuffer(0);for(const e of t){const t=await gi(e,(async(e,t)=>(a=await bi(r,a,t),a.slice(e,t))));a=await bi(r,a,t);const s=a.slice(0,t);a=a.slice(t);const o=yi(e,s);if(n[e.name]=o,"webgpu"===hi()){const e=js.backend;"uploadToGPU"in e&&et(o.shape)>=At().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")&&e.uploadToGPU(o.dataId)}}return n}function xi(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 wi=void 0!==co&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function vi(e){return wi?co.byteLength(e,"utf8"):new Blob([e]).size}function ki(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function Ii(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 Ti(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 Si(e,t){let n,r;return null!=e.weightsManifest&&([n,r]=await t(e.weightsManifest)),Ti(e,n,r)}function Ei(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:vi(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:vi(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:new oi(e.weightData).byteLength}}function Ni(e){const t=[];for(const n of e)t.push(...n.weights);return t}class Ai{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==Ai.instance&&(Ai.instance=new Ai),Ai.instance}static registerSaveRouter(e){Ai.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Ai.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Ai.getHandlers(e,"save")}static getLoadHandlers(e,t){return Ai.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[];return("load"===t?Ai.getInstance().loadRouters:Ai.getInstance().saveRouters).forEach((t=>{const a=t(e,n);null!==a&&r.push(a)})),r}}const Ci="tensorflowjs",Ri="models_store",Mi="model_info_store";function Fi(){if(!At().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 $i(e){const t=e.result;t.createObjectStore(Ri,{keyPath:"modelPath"}),t.createObjectStore(Mi,{keyPath:"modelPath"})}class Oi{constructor(e){if(this.indexedDB=Fi(),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(Ci,1);r.onupgradeneeded=()=>$i(r),r.onsuccess=()=>{const a=r.result;if(null==t){const t=a.transaction(Ri,"readonly"),r=t.objectStore(Ri).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{t.weightData=oi.join(t.weightData);const r=Ei(t),s=a.transaction(Mi,"readwrite");let o,i,u=s.objectStore(Mi);try{o=u.put({modelPath:this.modelPath,modelArtifactsInfo:r})}catch(e){return n(e)}o.onsuccess=()=>{i=a.transaction(Ri,"readwrite");const o=i.objectStore(Ri);let l;try{l=o.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:r})}catch(e){return n(e)}l.onsuccess=()=>e({modelArtifactsInfo:r}),l.onerror=e=>{u=s.objectStore(Mi);const t=u.delete(this.modelPath);t.onsuccess=()=>(a.close(),n(l.error)),t.onerror=e=>(a.close(),n(l.error))}},o.onerror=e=>(a.close(),n(o.error)),s.oncomplete=()=>{null==i?a.close():i.oncomplete=()=>a.close()}}},r.onerror=e=>n(r.error)}))}}Oi.URL_SCHEME="indexeddb://";const Di=e=>{return At().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Oi.URL_SCHEME)?(t=e.slice(Oi.URL_SCHEME.length),new Oi(t)):null;var t};Ai.registerSaveRouter(Di),Ai.registerLoadRouter(Di);class Pi{constructor(){this.indexedDB=Fi()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open(Ci,1);n.onupgradeneeded=()=>$i(n),n.onsuccess=()=>{const r=n.result,a=r.transaction(Mi,"readonly"),s=a.objectStore(Mi).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(Oi.URL_SCHEME)?t.slice(Oi.URL_SCHEME.length):t,new Promise(((t,n)=>{const r=this.indexedDB.open(Ci,1);r.onupgradeneeded=()=>$i(r),r.onsuccess=()=>{const a=r.result,s=a.transaction(Mi,"readwrite"),o=s.objectStore(Mi),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(Ri,"readwrite");const r=u.objectStore(Ri).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 Li="/",Bi="tensorflowjs_models",Ui="info",Wi="model_topology",zi="weight_specs",Vi="weight_data",Hi="model_metadata";function Gi(e){return{info:[Bi,e,Ui].join(Li),topology:[Bi,e,Wi].join(Li),weightSpecs:[Bi,e,zi].join(Li),weightData:[Bi,e,Vi].join(Li),modelMetadata:[Bi,e,Hi].join(Li)}}function ji(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function Ki(e){const t=e.split(Li);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Li)}class qi{constructor(e){if(!At().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=Gi(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=Ei(e),a=oi.join(e.weightData);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(wi)return co.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)}(a));const s={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(s)),{modelArtifactsInfo:r}}catch(e){throw ji(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(wi){const t=co.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}}qi.URL_SCHEME="localstorage://";const Xi=e=>{return At().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(qi.URL_SCHEME)?(t=e.slice(qi.URL_SCHEME.length),new qi(t)):null;var t};Ai.registerSaveRouter(Xi),Ai.registerLoadRouter(Xi);class Yi{constructor(){Qe(At().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=Bi+Li,n=Li+Ui;for(let r=0;r<this.LS.length;++r){const a=this.LS.key(r);a.startsWith(t)&&a.endsWith(n)&&(e[Ki(a)]=JSON.parse(this.LS.getItem(a)))}return e}async removeModel(e){var t;const n=Gi(e=(t=e).startsWith(qi.URL_SCHEME)?t.slice(qi.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 ji(n),r}}function Qi(e){return new Promise((e=>setTimeout(e))).then(e)}class Ji{constructor(e){if(!At().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Ji.URL_SCHEME)&&(e=e.slice(Ji.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=oi.join(e.weightData),n=window.URL.createObjectURL(new Blob([t],{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 t=Ii(e,[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}]),r=window.URL.createObjectURL(new Blob([JSON.stringify(t)],{type:"application/json"})),a=null==this.modelJsonAnchor?document.createElement("a"):this.modelJsonAnchor;if(a.download=this.modelJsonFileName,a.href=r,await Qi((()=>a.dispatchEvent(new MouseEvent("click")))),null!=e.weightData){const e=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor;e.download=this.weightDataFileName,e.href=n,await Qi((()=>e.dispatchEvent(new MouseEvent("click"))))}return{modelArtifactsInfo:Ei(e)}}}}Ji.URL_SCHEME="downloads://";class Zi{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=Si(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,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=>ki(e.name))),r={};for(const a of e)a.paths.forEach((e=>{const a=ki(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 eu(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 tu(e,t){null==t&&(t={});const n=null==t.fetchFunc?At().platform.fetch:t.fetchFunc,r=e.map((e=>n(e,t.requestInit,{isBinary:!0}))),a=(null==t.onProgress?await Promise.all(r):await eu(r,t.onProgress,0,.5)).map((e=>e.arrayBuffer()));return null==t.onProgress?await Promise.all(a):await eu(a,t.onProgress,.5,1)}function nu(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=si[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,r=new oi(c.slice(h,h+n));s[e].forEach((e=>{const t=fi(r.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(const e in t)p[e]=t[e]})),h+=n})),p}}Ai.registerSaveRouter((e=>At().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ji.URL_SCHEME)?function(e="model"){return new Ji(e)}(e.slice(Ji.URL_SCHEME.length)):null));class ru{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,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=At().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||{},this.loadOptions=t}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=Ii(e,[{paths:["./model.weights.bin"],weights:e.weightSpecs}]);if(t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData){const n=oi.join(e.weightData);t.body.append("model.weights.bin",new Blob([n],{type:"application/octet-stream"}),"model.weights.bin")}const r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:Ei(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async loadModelJSON(){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 t}async load(){return this.loadOptions.streamWeights?this.loadStream():Si(await this.loadModelJSON(),(e=>this.loadWeights(e)))}async loadStream(){const e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),n=Ni(e.weightsManifest);return Object.assign(Object.assign({},e),{weightSpecs:n,getWeightStream:()=>function(e,t){var n;const r=null==t.fetchFunc?At().platform.fetch:t.fetchFunc;let a,s=0;return null===(n=t.onProgress)||void 0===n||n.call(t,0),new ReadableStream({pull:async n=>{for(var o;s<e.length;){if(!a){const n=(await r(e[s],t.requestInit,{isBinary:!0})).body;a=n.getReader()}const{done:i,value:u}=await a.read();if(!i)return void n.enqueue(u);s++,a=void 0,null===(o=t.onProgress)||void 0===o||o.call(t,s/e.length)}n.close()}})}(t,this.loadOptions)})}async getWeightUrls(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=[],o=[];for(const t of e)for(const e of t.paths)null!=this.weightUrlConverter?o.push(this.weightUrlConverter(e)):s.push(a+e+r);return this.weightUrlConverter&&s.push(...await Promise.all(o)),s}async loadWeights(e){const t=await this.getWeightUrls(e);return[Ni(e),await tu(t,this.loadOptions)]}}function au(e){return null!=e.match(ru.URL_SCHEME_REGEX)}ru.URL_SCHEME_REGEX=/^https?:\/\//;const su=(e,t)=>{if("undefined"==typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every((e=>au(e))):au(e),n)return ou(e,t)}return null};function ou(e,t){return new ru(e,t)}Ai.registerSaveRouter(su),Ai.registerLoadRouter(su);class iu{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class uu{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class lu{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function cu(e,t,n,r){return 1===arguments.length?null!=e.modelTopology||null!=e.weightSpecs?new iu(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 iu({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 iu({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r}))}const pu="://";class hu{constructor(){this.managers={}}static getInstance(){return null==hu.instance&&(hu.instance=new hu),hu.instance}static registerManager(e,t){Qe(null!=e,(()=>"scheme must not be undefined or null.")),e.endsWith(pu)&&(e=e.slice(0,e.indexOf(pu))),Qe(e.length>0,(()=>"scheme must not be an empty string."));const n=hu.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=hu.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(hu.getInstance().managers)}}function du(e){if(-1===e.indexOf(pu))throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${hu.getSchemes().join(",")}`);return{scheme:e.split(pu)[0],path:e.split(pu)[1]}}async function fu(e,t,n=!1){Qe(e!==t,(()=>`Old path and new path are the same: '${e}'`));const r=Ai.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=Ai.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=du(e).scheme,u=du(e).path,l=i===du(e).scheme,c=await a.load();n&&l&&await hu.getManager(i).removeModel(u);const p=await o.save(c);return n&&!l&&await hu.getManager(i).removeModel(u),p.modelArtifactsInfo}var mu=Object.freeze({__proto__:null,browserFiles:function(e){return new Zi(e)},browserHTTPRequest:function(e,t){return ou(e,t)},CompositeArrayBuffer:oi,concatenateArrayBuffers:function(e){return oi.join(e)},decodeWeights:fi,decodeWeightsStream:_i,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:xi(await Promise.all(r)),specs:n}},fromMemory:function(e,t,n,r){return new lu(cu(...arguments))},fromMemorySync:cu,getLoadHandlers:(e,t)=>Ai.getLoadHandlers(e,t),getModelArtifactsForJSON:Si,getModelArtifactsForJSONSync:Ti,getModelArtifactsInfoForJSON:Ei,getSaveHandlers:e=>Ai.getSaveHandlers(e),getWeightSpecs:Ni,http:ou,isHTTPScheme:au,loadWeights:async function(e,t="",n,r){return nu((e=>tu(e,{requestInit:r})))(e,t,n)},registerLoadRouter:e=>Ai.registerLoadRouter(e),registerSaveRouter:e=>Ai.registerSaveRouter(e),weightsLoaderFactory:nu,withSaveHandler:function(e){return new uu(e)},withSaveHandlerSync:function(e){return new uu(e)},copyModel:async function(e,t){return fu(e,t,!1)},listModels:async function(){const e=hu.getSchemes(),t={};for(const n of e){const e=await hu.getManager(n).listModels();for(const r in e)t[n+pu+r]=e[r]}return t},moveModel:async function(e,t){return fu(e,t,!0)},removeModel:async function(e){const t=du(e);return hu.getManager(t.scheme).removeModel(t.path)}});const gu=ti({cast_:function(e,t){const n=Jo(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 js.runKernel(en,r,a)}}),yu=ti({matMul_:function(e,t,n=!1,r=!1){let a=Jo(e,"a","matMul"),s=Jo(t,"b","matMul");[a,s]=Bs(a,s);const o={a,b:s},i={transposeA:n,transposeB:r};return js.runKernel(Xt,o,i)}}),bu=ti({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:Jo(e,"indices","oneHot","int32")},o={dtype:a,depth:t,onValue:n,offValue:r};return js.runKernel(dr,s,o)}}),_u=ti({imag_:function(e){const t={input:Jo(e,"input","imag")};return js.runKernel("Imag",t)}}),xu=ti({neg_:function(e){const t={x:Jo(e,"x","neg")};return js.runKernel("Neg",t)}}),wu=ti({real_:function(e){const t={input:Jo(e,"input","real")};return js.runKernel("Real",t)}}),vu=ti({transpose_:function(e,t,n){const r=Jo(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?ui((()=>{let e=wu(r),t=_u(r);return e=js.runKernel(oa,{x:e},s),t=js.runKernel(oa,{x:t},s),n&&(t=xu(t)),ni(e,t)})):js.runKernel(oa,a,s)}});function ku(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 Iu(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 Tu(e,t){const n=Math.max(e.length,t.length),r=new Array(n);for(let a=0;a<n;a++){let s=e[e.length-a-1];null==s&&(s=1);let o=t[t.length-a-1];if(null==o&&(o=1),1===s)r[n-a-1]=o;else if(1===o)r[n-a-1]=s;else{if(s!==o)throw Error(`Operands could not be broadcast together with shapes ${e} and ${t}.`);r[n-a-1]=s}}return r}function Su(e,t,n){if(Ze(e),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");const r=Xo(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 ri(e,t,r,n)}let Eu;const Nu=ti({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!=_a(pa,js.backendName)){const n={pixels:e},r={numChannels:t};return js.runKernel(pa,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==Eu)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.");Eu=new OffscreenCanvas(1,1).getContext("2d")}else Eu=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});Eu.canvas.width=u,Eu.canvas.height=l,Eu.drawImage(e,0,0,u,l),c=Eu.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 Su(p,[l,u,t],"int32")}});function Au(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 Cu(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 Ru(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}`)}Cu(n,t,e)}function Mu(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 Fu(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 $u(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 Ou(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 Du(e,t,n){return n<=e?n:n-(t-1)}function Pu(e,t){const n=[];for(let r=0;r<e;r++)n.push(t+r);return n}function Lu(e,t,n,r,a){const s=[...a],o=Pu(n,t);for(let a=0;a<s.length;a++)if(o.indexOf(a)>-1)s[a]=0;else{const o=Du(t,n,a);let i=r[o];e&1<<o&&(i=0),s[a]=i}return s}function Bu(e,t,n,r,a){const s=[...a],o=Pu(n,t);for(let a=0;a<s.length;a++)if(o.indexOf(a)>-1)s[a]=Number.MAX_SAFE_INTEGER;else{const o=Du(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 Uu(e,t,n){let r=e[t];return(n&1<<t||null==r)&&(r=1),r}function Wu(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 zu(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 Vu(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 Hu(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 Gu(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 ju(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&&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&&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]=Ku(h.begin[t],0,h.strides[t],r,a,s),h.end[t]=Ku(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 Ku(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 qu=Object.freeze({__proto__:null,assertParamsValid:Fu,maskToAxes:function(e){const t=[];let n=0;for(;e>0;)1&e&&t.push(n),e/=2,n++;return t},computeOutShape:$u,stridesWithElidedDims:Ou,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=Lu(o,u,l,r,e),p=Bu(i,u,l,a,e),h=Ou(s,u,l,e)}else for(let t=0;t<l;t++)c[t]=Wu(o,r,s,e,t,u),p[t]=zu(i,a,s,e,t,u),h[t]=Uu(s,t,u);return{begin:c,end:p,strides:h}},startIndicesWithElidedDims:Lu,stopIndicesWithElidedDims:Bu,stridesForAxis:Uu,startForAxis:Wu,stopForAxis:zu,isSliceContinous:Vu,computeFlatOffset:Hu,parseSliceParams:Gu,sliceInfo:ju});const Xu=ti({add_:function(e,t){let n=Jo(e,"a","add"),r=Jo(t,"b","add");[n,r]=Bs(n,r);const a={a:n,b:r};return js.runKernel(Dt,a)}}),Yu=ti({floorDiv_:function(e,t){let n=Jo(e,"a","floorDiv"),r=Jo(t,"b","floorDiv");[n,r]=Bs(n,r);const a={a:n,b:r};return js.runKernel(Rn,a)}}),Qu=ti({div_:function(e,t){let n=Jo(e,"a","div"),r=Jo(t,"b","div");if([n,r]=Bs(n,r),"int32"===n.dtype&&"int32"===r.dtype)return Yu(n,r);const a={a:n,b:r};return js.runKernel(wn,a,{})}}),Ju=ti({mul_:function(e,t){let n=Jo(e,"a","mul"),r=Jo(t,"b","mul");[n,r]=Bs(n,r);const a={a:n,b:r};return js.runKernel(ir,a)}}),Zu=ti({abs_:function(e){const t=Jo(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return js.runKernel("ComplexAbs",e)}{const e={x:t};return js.runKernel("Abs",e)}}}),el=ti({acos_:function(e){const t={x:Jo(e,"x","acos")};return js.runKernel($t,t)}}),tl=ti({acosh_:function(e){const t={x:Jo(e,"x","acosh")};return js.runKernel(Ot,t)}}),nl=ti({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)=>Jo(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 js.runKernel(Pt,r)}}),rl=ti({all_:function(e,t=null,n=!1){const r={x:Jo(e,"x","all","bool")},a={axis:t,keepDims:n};return js.runKernel(Lt,r,a)}}),al=ti({any_:function(e,t=null,n=!1){const r={x:Jo(e,"x","any","bool")},a={axis:t,keepDims:n};return js.runKernel(Bt,r,a)}}),sl=ti({argMax_:function(e,t=0){const n={x:Jo(e,"x","argMax")},r={axis:t};return js.runKernel(Ut,n,r)}}),ol=ti({argMin_:function(e,t=0){const n={x:Jo(e,"x","argMin")},r={axis:t};return js.runKernel(Wt,n,r)}}),il=ti({asin_:function(e){const t={x:Jo(e,"x","asin")};return js.runKernel(zt,t)}}),ul=ti({asinh_:function(e){const t={x:Jo(e,"x","asinh")};return js.runKernel(Vt,t)}}),ll=ti({atan_:function(e){const t={x:Jo(e,"x","atan")};return js.runKernel(Ht,t)}}),cl=ti({atan2_:function(e,t){let n=Jo(e,"a","atan2"),r=Jo(t,"b","atan2");[n,r]=Bs(n,r);const a={a:n,b:r};return js.runKernel(jt,a)}}),pl=ti({atanh_:function(e){const t={x:Jo(e,"x","atanh")};return js.runKernel(Gt,t)}});function hl(e,t,n,r,a="NHWC",s){return ml(e,[...t,e[3]],n,s,r,null,null,Tl(a))}function dl(e,t,n,r,a,s,o="channelsLast"){const[i,u]=bl(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 ml(e,l,n,r,a,s,!1,o)}function fl(e,t,n,r,a,s,o="NDHWC"){const[i,u,l]=_l(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 gl(e,c,n,r,a,!1,p,s)}function ml(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]=bl(n),[y,b]=bl(r),_=xl(h,y),x=xl(d,b),{padInfo:w,outHeight:v,outWidth:k}=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=yl(e,t,n));const s=e[1];return[wl((e[0]-t+2*r)/n+1,a),wl((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=wl((t-s+h+d)/r+1,i),p=wl((n-o+f+m)/a+1,i)}}return{padInfo:l,outHeight:c,outWidth:p}}(a,l,c,m,g,_,x,s,i),I=o?f*p:f;let T;return"channelsFirst"===i?T=[u,I,v,k]:"channelsLast"===i&&(T=[u,v,k,I]),{batchSize:u,dataFormat:i,inHeight:l,inWidth:c,inChannels:p,outHeight:v,outWidth:k,outChannels:I,padInfo:w,strideHeight:m,strideWidth:g,filterHeight:h,filterWidth:d,effectiveFilterHeight:_,effectiveFilterWidth:x,dilationHeight:y,dilationWidth:b,inShape:e,outShape:T,filterShape:t}}function gl(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,_]=_l(n),[x,w,v]=_l(r),k=xl(d,x),I=xl(f,w),T=xl(m,v),{padInfo:S,outDepth:E,outHeight:N,outWidth:A}=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=yl(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]=wl((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,_,k,I,T,i),C=s?g*h:g;let R;return"channelsFirst"===o?R=[u,C,E,N,A]:"channelsLast"===o&&(R=[u,E,N,A,C]),{batchSize:u,dataFormat:o,inDepth:l,inHeight:c,inWidth:p,inChannels:h,outDepth:E,outHeight:N,outWidth:A,outChannels:C,padInfo:S,strideDepth:y,strideHeight:b,strideWidth:_,filterDepth:d,filterHeight:f,filterWidth:m,effectiveFilterDepth:k,effectiveFilterHeight:I,effectiveFilterWidth:T,dilationDepth:x,dilationHeight:w,dilationWidth:v,inShape:e,outShape:R,filterShape:t}}function yl(e,t,n,r=1){const a=xl(t,r);return Math.floor((e[0]*(n-1)-n+a)/2)}function bl(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function _l(e){return"number"==typeof e?[e,e,e]:e}function xl(e,t){return t<=1?e:e+(e-1)*(t-1)}function wl(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 vl(e){const[t,n,r]=bl(e);return 1===t&&1===n&&1===r}function kl(e,t){return vl(e)||vl(t)}function Il(e){return bl(e).every((e=>e>0))}function Tl(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function Sl(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 El=ti({reshape_:function(e,t){const n={x:Jo(e,"x","reshape","string_or_numeric")},r={shape:t};return js.runKernel(wr,n,r)}}),Nl=ti({avgPool_:function(e,t,n,r,a){const s=Jo(e,"x","avgPool","float32");Qe(kl(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=El(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}.`)),Sl("avgPool",r,a);const u={x:o},l={filterSize:t,strides:n,pad:r,dimRoundingMode:a};let c=js.runKernel(Kt,u,l);return c=gu(c,s.dtype),i?El(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),Al=ti({avgPool3d_:function(e,t,n,r,a,s="NDHWC"){const o=Jo(e,"x","avgPool3d","float32");let i=o,u=!1;4===o.rank&&(u=!0,i=El(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}'`)),Sl("avgPool3d",r,a);const l={x:i},c={filterSize:t,strides:n,pad:r,dimRoundingMode:a,dataFormat:s};let p=js.runKernel(qt,l,c);return p=gu(p,i.dtype),u?El(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}}),Cl=ti({clone_:function(e){const t={x:Jo(e,"x","clone","string_or_numeric")};return js.runKernel(Pn,t)}}),Rl=ti({concat_:function(e,t=0){Qe(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=Zo(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 Cl(n[0]);const r=n,a={axis:t};return js.runKernel(rn,r,a)}}),Ml=ti({sigmoid_:function(e){const t={x:Jo(e,"x","sigmoid","float32")};return js.runKernel(Lr,t)}}),Fl=ti({slice_:function(e,t,n){const r=Jo(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 js.runKernel(Or,a,s)}}),$l=ti({tanh_:function(e){const t={x:Jo(e,"x","tanh","float32")};return js.runKernel(na,t)}}),Ol=ti({basicLSTMCell_:function(e,t,n,r,a,s){const o=Jo(e,"forgetBias","basicLSTMCell"),i=Jo(t,"lstmKernel","basicLSTMCell"),u=Jo(n,"lstmBias","basicLSTMCell"),l=Jo(r,"data","basicLSTMCell"),c=Jo(a,"c","basicLSTMCell"),p=Jo(s,"h","basicLSTMCell"),h=Rl([l,p],1),d=yu(h,i),f=Xu(d,u),m=f.shape[0],g=f.shape[1]/4,y=[m,g],b=Fl(f,[0,0],y),_=Fl(f,[0,g],y),x=Fl(f,[0,2*g],y),w=Fl(f,[0,3*g],y),v=Xu(Ju(Ml(b),$l(_)),Ju(c,Ml(Xu(o,x))));return[v,Ju($l(v),Ml(w))]}}),Dl=ti({batchToSpaceND_:function(e,t,n){const r=Jo(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 js.runKernel(Yt,s,o)}}),Pl=ti({batchNorm_:function(e,t,n,r,a,s){null==s&&(s=.001);const o=Jo(e,"x","batchNorm"),i=Jo(t,"mean","batchNorm"),u=Jo(n,"variance","batchNorm");let l,c;null!=a&&(l=Jo(a,"scale","batchNorm")),null!=r&&(c=Jo(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?El(e,[1,1,1,e.size]):2===e.rank?El(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?El(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=js.runKernel(Mn,h,d);return El(f,o.shape)}}),Ll=ti({batchNorm2d_:function(e,t,n,r,a,s){const o=Jo(e,"x","batchNorm"),i=Jo(t,"mean","batchNorm"),u=Jo(n,"variance","batchNorm");let l,c;return null!=a&&(l=Jo(a,"scale","batchNorm")),null!=r&&(c=Jo(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}.`)),Pl(o,i,u,c,l,s)}}),Bl=ti({batchNorm3d_:function(e,t,n,r,a,s){const o=Jo(e,"x","batchNorm"),i=Jo(t,"mean","batchNorm"),u=Jo(n,"variance","batchNorm");let l,c;return null!=a&&(l=Jo(a,"scale","batchNorm")),null!=r&&(c=Jo(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}.`)),Pl(o,i,u,c,l,s)}}),Ul=ti({batchNorm4d_:function(e,t,n,r,a,s){const o=Jo(e,"x","batchNorm"),i=Jo(t,"mean","batchNorm"),u=Jo(n,"variance","batchNorm");let l,c;return null!=a&&(l=Jo(a,"scale","batchNorm")),null!=r&&(c=Jo(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}.`)),Pl(o,i,u,c,l,s)}}),Wl=ti({bincount_:function(e,t,n){const r=Jo(e,"x","bincount"),a=Jo(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 js.runKernel(Qt,s,o)}}),zl=ti({bitwiseAnd_:function(e,t){const n=Jo(e,"x","bitwiseAnd"),r=Jo(t,"y","bitwiseAnd");if(!tt(n.shape,r.shape))throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${n.shape}, y: ${r.shape}`);if("int32"!==n.dtype||"int32"!==r.dtype)throw new Error(`BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${n.dtype} and type of y: ${r.dtype}`);const a={a:n,b:r};return js.runKernel(Jt,a)}}),Vl=ti({broadcastArgs_:function(e,t){const n=Jo(e,"s0","broadcastArgs","int32"),r=Jo(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 js.runKernel(Zt,a)}}),Hl=ti({broadcastTo_:function(e,t){let n=Jo(e,"broadcastTo","x");const r=n.shape;if(vt(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=El(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 Cl(n);const i={x:n},u={reps:s};return js.runKernel(ra,i,u)}});function Gl(e,t="float32",n){return t=t||"float32",vt(e),new Is(e,t,n)}const jl=ti({ceil_:function(e){const t={x:Jo(e,"x","ceil","float32")};return js.runKernel(tn,t)}});function Kl(e,t,n){vt(e);const r={shape:e,value:t,dtype:n=n||ft(t)};return js.runKernel(Nn,{},r)}const ql=ti({clipByValue_:function(e,t,n){const r=Jo(e,"x","clipByValue");if(Qe(t<=n,(()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`)),t===n)return Kl(r.shape,t,r.dtype);const a={x:r},s={clipValueMin:t,clipValueMax:n};return js.runKernel(nn,a,s)}}),Xl=ti({concat1d_:function(e){return Rl(e,0)}}),Yl=ti({concat2d_:function(e,t){return Rl(e,t)}}),Ql=ti({concat3d_:function(e,t){return Rl(e,t)}}),Jl=ti({concat4d_:function(e,t){return Rl(e,t)}}),Zl=ti({conv2d_:function(e,t,n,r,a="NHWC",s=[1,1],o){const i=Jo(e,"x","conv2d","float32"),u=Jo(t,"filter","conv2d","float32");let l=i,c=!1;3===i.rank&&(c=!0,l=El(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}.`)),Sl("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(kl(n,s),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`)),Qe(Il(s),(()=>"Error in conv2D: Dilated rates should be larger than 0.")),Qe(Il(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=js.runKernel(an,h,d);return c?El(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),ec=ti({conv1d_:function(e,t,n,r,a="NWC",s=1,o){const i=Jo(e,"x","conv1d"),u=Jo(t,"filter","conv1d");let l=i,c=!1;2===i.rank&&(c=!0,l=El(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}.`)),Sl("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(kl(n,s),(()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${s}'`)),Qe(Il(s),(()=>"Error in conv1D: Dilated rates should be larger than 0.")),Qe(Il(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=El(u,[1,u.shape[0],u.shape[1],u.shape[2]]),h=El(l,[l.shape[0],1,l.shape[1],l.shape[2]]),d=Zl(h,p,[1,n],r,"NHWC",[1,s],o);return El(d,c?[d.shape[2],d.shape[3]]:[d.shape[0],d.shape[2],d.shape[3]])}}),tc=ti({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=El(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]}.`)),Sl("conv2dDerInput",a,o);const h={dy:u,filter:n},d={strides:r,pad:a,dataFormat:s,dimRoundingMode:o,inputShape:i},f=js.runKernel(sn,h,d);return l?El(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),nc=ti({conv2dTranspose_:function(e,t,n,r,a,s){const o=Jo(e,"x","conv2dTranspose"),i=Jo(t,"filter","conv2dTranspose");return tc(n,o,i,r,a,"NHWC",s)}}),rc=ti({conv3d_:function(e,t,n,r,a="NDHWC",s=[1,1,1]){const o=Jo(e,"x","conv3d"),i=Jo(t,"filter","conv3d");let u=o,l=!1;4===o.rank&&(l=!0,u=El(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(kl(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(Il(s),(()=>"Error in conv3D: Dilated rates should be larger than 0.")),Qe(Il(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=js.runKernel(on,c,p);return l?El(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}}),ac=ti({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=El(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=js.runKernel(ln,c,p);return i?El(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}}),sc=ti({conv3dTranspose_:function(e,t,n,r,a){const s=Jo(e,"x","conv3dTranspose"),o=Jo(t,"filter","conv3dTranspose");return ac(n,s,o,r,a)}}),oc=ti({cos_:function(e){const t={x:Jo(e,"x","cos","float32")};return js.runKernel("Cos",t)}}),ic=ti({cosh_:function(e){const t={x:Jo(e,"x","cosh","float32")};return js.runKernel(cn,t)}}),uc=ti({cumprod_:function(e,t=0,n=!1,r=!1){const a={x:Jo(e,"x","cumprod")},s={axis:t,exclusive:n,reverse:r};return js.runKernel(pn,a,s)}}),lc=ti({cumsum_:function(e,t=0,n=!1,r=!1){const a={x:Jo(e,"x","cumsum")},s={axis:t,exclusive:n,reverse:r};return js.runKernel(hn,a,s)}}),cc=ti({denseBincount_:function(e,t,n,r=!1){const a=Jo(e,"x","denseBincount"),s=Jo(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 js.runKernel(fn,o,i)}}),pc=ti({depthToSpace_:function(e,t,n="NHWC"){const r=Jo(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 js.runKernel(mn,i,u)}}),hc=ti({depthwiseConv2d_:function(e,t,n,r,a="NHWC",s=[1,1],o){const i=Jo(e,"x","depthwiseConv2d","float32"),u=Jo(t,"filter","depthwiseConv2d","float32");let l=i,c=!1;3===i.rank&&(c=!0,l=El(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]}.`)),Sl("depthwiseConv2d",r,o);const h={x:l,filter:u},d={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o},f=js.runKernel(gn,h,d);return c?El(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),dc=ti({diag_:function(e){const t={x:Jo(e,"x","diag")};return js.runKernel(yn,t)}}),fc=ti({dilation2d_:function(e,t,n,r,a=[1,1],s="NHWC"){const o=Jo(e,"x","dilation2d"),i=Jo(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=El(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=js.runKernel(bn,c,p);return l?El(h,[h.shape[1],h.shape[2],h.shape[3]]):h}}),mc=ti({equal_:function(e,t){let n=Jo(e,"a","equal","string_or_numeric"),r=Jo(t,"b","equal","string_or_numeric");[n,r]=Bs(n,r),Tu(n.shape,r.shape);const a={a:n,b:r};return js.runKernel(In,a)}}),gc=ti({where_:function(e,t,n){const r=Jo(t,"a","where"),a=Jo(n,"b","where"),s=Jo(e,"condition","where","bool"),o=Tu(Tu(s.shape,r.shape),a.shape),i={condition:Hl(s,o),t:Hl(r,o),e:Hl(a,o)};return js.runKernel(Fr,i)}}),yc=ti({zerosLike_:function(e){const t={x:Jo(e,"x","zerosLike")};return js.runKernel(la,t)}}),bc=ti({divNoNan_:function(e,t){let n=Jo(e,"a","div"),r=Jo(t,"b","div");[n,r]=Bs(n,r);const a=Qu(n,r),s=yc(a),o=mc(r,s);return gc(o,s,a)}}),_c=ti({dot_:function(e,t){const n=Jo(e,"t1","dot"),r=Jo(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=El(n,[1,-1]),t=El(r,[-1,1]),a=yu(e,t);return El(a,[])}if(1===n.rank&&2===r.rank){const e=El(n,[1,-1]),t=El(r,[r.shape[0],r.shape[1]]),a=yu(e,t);return El(a,[a.size])}if(2===n.rank&&1===r.rank){const e=El(r,[-1,1]),t=yu(n,e);return El(t,[t.size])}{const e=El(r,[r.shape[0],r.shape[1]]);return yu(n,e)}}}),xc=ti({einsum_:function(e,...t){const n=t.map(((e,t)=>Jo(e,`tensors${t}`,"einsum"))),r={equation:e};return js.runKernel("Einsum",n,r)}}),wc=ti({elu_:function(e){const t={x:Jo(e,"x","elu","float32")};return js.runKernel(vn,t)}}),vc=ti({ensureShape_:function(e,t){const n=Jo(e,"x","ensureShape","string_or_numeric");if(!function(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(null!==e[n]&&null!==t[n]&&e[n]!==t[n])return!1;return!0}(n.shape,t))throw new Error(`EnsureShape: Shape of tensor ${n.shape} is not compatible with expected shape ${t}`);return e}}),kc=ti({erf_:function(e){let t=Jo(e,"x","erf");Qe("int32"===t.dtype||"float32"===t.dtype,(()=>"Input dtype must be `int32` or `float32`.")),"int32"===t.dtype&&(t=gu(t,"float32"));const n={x:t};return js.runKernel("Erf",n)}});function Ic(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function Tc(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 Sc(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 Ec(e,t){return Tc(e,t.map((e=>1)),t)}function Nc(e,t,n){Qe(Ic(t,n),(()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`))}function Ac(e,t){if(Ic(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 Cc(e){return e.map(((e,t)=>[t,e])).sort(((e,t)=>e[1]-t[1])).map((e=>e[0]))}function Rc(e,t){const n=[];for(let r=t-e;r<t;++r)n.push(r);return n}const Mc=ti({max_:function(e,t=null,n=!1){const r={x:Jo(e,"x","max")},a={reductionIndices:t,keepDims:n};return js.runKernel(Qn,r,a)}}),Fc=ti({min_:function(e,t=null,n=!1){const r={x:Jo(e,"x","min")},a={axis:t,keepDims:n};return js.runKernel(rr,r,a)}}),$c=ti({pow_:function(e,t){let n=Jo(e,"base","pow"),r=Jo(t,"exp","pow");[n,r]=Bs(n,r);const a={a:n,b:r};return js.runKernel("Pow",a)}});function Oc(e,t){if((fs(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&&fs(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return ri(e,[],[],t)}const Dc=ti({sqrt_:function(e){const t={x:Jo(e,"x","sqrt","float32")};return js.runKernel(Ur,t)}}),Pc=ti({square_:function(e){const t=Jo(e,"x","square");return js.runKernel("Square",{x:t},{})}}),Lc=ti({sum_:function(e,t=null,n=!1){let r=Jo(e,"x","sum");"bool"===r.dtype&&(r=gu(r,"int32"));const a={x:r},s={axis:t,keepDims:n};return js.runKernel(Wr,a,s)}});function Bc(e,t,n=null){if(0===e.rank)return Zu(e);if(1!==e.rank&&null===n)return Bc(El(e,[-1]),t,n);if(1===e.rank||"number"==typeof n||Array.isArray(n)&&1===n.length){if(1===t)return Lc(Zu(e),n);if(t===1/0)return Mc(Zu(e),n);if(t===-1/0)return Fc(Zu(e),n);if("euclidean"===t||2===t)return Dc(Lc($c(Zu(e),Oc(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&2===n.length){if(1===t)return Mc(Lc(Zu(e),n[0]),n[1]-1);if(t===1/0)return Mc(Lc(Zu(e),n[1]),n[0]);if(t===-1/0)return Fc(Lc(Zu(e),n[1]),n[0]);if("fro"===t||"euclidean"===t)return Dc(Lc(Pc(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const Uc=ti({norm_:function(e,t="euclidean",n=null,r=!1){const a=Bc(e=Jo(e,"x","norm"),t,n);let s=a.shape;if(r){const t=it(n,e.shape);s=Ec(a.shape,t)}return El(a,s)}}),Wc=ti({euclideanNorm_:function(e,t=null,n=!1){return Uc(e,"euclidean",t,n)}}),zc=ti({exp_:function(e){const t={x:Jo(e,"x","exp")};return js.runKernel(Tn,t)}}),Vc=ti({expandDims_:function(e,t=0){const n=Jo(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 js.runKernel(Sn,r,a)}}),Hc=ti({expm1_:function(e){const t={x:Jo(e,"x","expm1")};return js.runKernel(En,t)}}),Gc=ti({tile_:function(e,t){const n=Jo(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 js.runKernel(ra,r,a)}}),jc=ti({eye_:function(e,t,n,r="float32"){null==t&&(t=e);const a=Gl([e,t],r),s=e<=t?e:t;for(let e=0;e<s;++e)a.set(1,e,e);const o=El(a.toTensor(),[e,t]);if(null==n)return o;if(1===n.length)return Gc(Vc(o,0),[n[0],1,1]);if(2===n.length)return Gc(Vc(Vc(o,0),0),[n[0],n[1],1,1]);if(3===n.length)return Gc(Vc(Vc(Vc(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.`)}}),Kc=ti({floor_:function(e){const t={x:Jo(e,"x","floor","float32")};return js.runKernel(Cn,t)}}),qc=ti({gather_:function(e,t,n=0,r=0){const a={x:Jo(e,"x","gather"),indices:Jo(t,"indices","gather","int32")},s={axis:n,batchDims:r};return js.runKernel(Fn,a,s)}}),Xc=ti({greater_:function(e,t){let n=Jo(e,"a","greater","string_or_numeric"),r=Jo(t,"b","greater","string_or_numeric");[n,r]=Bs(n,r),Tu(n.shape,r.shape);const a={a:n,b:r};return js.runKernel(On,a)}}),Yc=ti({greaterEqual_:function(e,t){let n=Jo(e,"a","greaterEqual","string_or_numeric"),r=Jo(t,"b","greaterEqual","string_or_numeric");[n,r]=Bs(n,r),Tu(n.shape,r.shape);const a={a:n,b:r};return js.runKernel(Dn,a)}}),Qc=ti({isFinite_:function(e){const t={x:Jo(e,"x","isFinite")};return js.runKernel(Ln,t)}}),Jc=ti({isInf_:function(e){const t={x:Jo(e,"x","isInf")};return js.runKernel(Bn,t)}}),Zc=ti({isNaN_:function(e){const t={x:Jo(e,"x","isNaN")};return js.runKernel(Un,t)}}),ep=ti({leakyRelu_:function(e,t=.2){const n={x:Jo(e,"x","leakyRelu")},r={alpha:t};return js.runKernel(Wn,n,r)}}),tp=ti({less_:function(e,t){let n=Jo(e,"a","less","string_or_numeric"),r=Jo(t,"b","less","string_or_numeric");[n,r]=Bs(n,r),Tu(n.shape,r.shape);const a={a:n,b:r};return js.runKernel(zn,a)}}),np=ti({lessEqual_:function(e,t){let n=Jo(e,"a","lessEqual","string_or_numeric"),r=Jo(t,"b","lessEqual","string_or_numeric");[n,r]=Bs(n,r),Tu(n.shape,r.shape);const a={a:n,b:r};return js.runKernel(Vn,a)}}),rp=ti({localResponseNormalization_:function(e,t=5,n=1,r=1,a=.5){const s=Jo(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=El(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=js.runKernel(Xn,u,l);return i?El(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),ap=ti({log_:function(e){const t={x:Jo(e,"x","log","float32")};return js.runKernel("Log",t)}}),sp=ti({log1p_:function(e){const t={x:Jo(e,"x","log1p")};return js.runKernel(Gn,t)}});function op(e){return js.customGrad(e)}const ip=ti({softplus_:function(e){const t={x:Jo(e,"x","softplus")};return js.runKernel(Br,t)}}),up=ti({logSigmoid_:function(e){const t=Jo(e,"x","logSigmoid"),n=op((e=>({value:xu(ip(xu(e))),gradFunc:t=>Ju(t,Ml(xu(e)))})));return n(t)}}),lp=ti({sub_:function(e,t){let n=Jo(e,"a","sub"),r=Jo(t,"b","sub");[n,r]=Bs(n,r);const a={a:n,b:r};return js.runKernel(ta,a)}}),cp=ti({logSoftmax_:function(e,t=-1){const n=Jo(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=op(((e,n)=>{const r=Mc(e,t,!0),a=lp(e,r),s=lp(gu(a,"float32"),ap(Lc(zc(a),t,!0)));return n([s]),{value:s,gradFunc:(e,n)=>{const[r]=n,a=zc(r);return lp(e,Ju(Lc(e,t,!0),a))}}}));return r(n)}}),pp=ti({logSumExp_:function(e,t=null,n=!1){const r=Jo(e,"x","logSumExp"),a=it(t,r.shape),s=Mc(r,a,!0),o=lp(r,s),i=zc(o),u=Lc(i,a),l=ap(u),c=Xu(El(s,l.shape),l);if(n){const e=Ec(c.shape,a);return El(c,e)}return c}}),hp=ti({logicalAnd_:function(e,t){const n=Jo(e,"a","logicalAnd","bool"),r=Jo(t,"b","logicalAnd","bool");Tu(n.shape,r.shape);const a={a:n,b:r};return js.runKernel(jn,a)}}),dp=ti({logicalNot_:function(e){const t={x:Jo(e,"x","logicalNot","bool")};return js.runKernel(Kn,t)}}),fp=ti({logicalOr_:function(e,t){const n=Jo(e,"a","logicalOr","bool"),r=Jo(t,"b","logicalOr","bool");Tu(n.shape,r.shape);const a={a:n,b:r};return js.runKernel(qn,a)}}),mp=ti({logicalXor_:function(e,t){const n=Jo(e,"a","logicalXor","bool"),r=Jo(t,"b","logicalXor","bool");return Tu(n.shape,r.shape),hp(fp(e,t),dp(hp(e,t)))}}),gp=2147483648,yp=ti({searchSorted_:function(e,t,n="left"){const r=Jo(e,"sortedSequence","searchSorted"),a=Jo(t,"values","searchSorted"),s=r.shape[r.shape.length-1],o=a.shape[a.shape.length-1],i=El(r,[-1,s]),u=El(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)>=gp)throw new Error("values tensor size must less than 2147483648");if(i.shape[1]>=gp)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 js.runKernel(Mr,l,c)}}),bp=ti({maxPool_:function(e,t,n,r,a){const s=Jo(e,"x","maxPool");let o=s,i=!1;3===s.rank&&(i=!0,o=El(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(kl(n,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`)),Sl("maxPool",r,a);const u={x:o},l={filterSize:t,strides:n,pad:r,dimRoundingMode:a},c=js.runKernel(Zn,u,l);return i?El(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),_p=ti({maxPool3d_:function(e,t=[1,1,1],n,r,a,s="NDHWC"){const o=Jo(e,"x","maxPool3d");let i=o,u=!1;4===o.rank&&(u=!0,i=El(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}`)),Sl("maxPool3d",r,a);const l={x:i},c={filterSize:t,strides:n,pad:r,dimRoundingMode:a,dataFormat:s},p=js.runKernel(er,l,c);return u?El(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}}),xp=ti({maxPoolWithArgmax_:function(e,t,n,r,a=!1){const s={x:Jo(e,"x","maxPoolWithArgmax")},o={filterSize:t,strides:n,pad:r,includeBatchInIndex:a},i=js.runKernel(tr,s,o);return{result:i[0],indexes:i[1]}}}),wp=ti({maximum_:function(e,t){let n=Jo(e,"a","maximum"),r=Jo(t,"b","maximum");[n,r]=Bs(n,r),"bool"===n.dtype&&(n=gu(n,"int32"),r=gu(r,"int32")),Tu(n.shape,r.shape);const a={a:n,b:r};return js.runKernel(Jn,a)}}),vp=ti({mean_:function(e,t=null,n=!1){const r={x:Jo(e,"x","mean")},a={axis:t,keepDims:n};return js.runKernel(nr,r,a)}});function kp(e,t="float32"){if(vt(e),"complex64"===t){const t=kp(e,"float32"),n=kp(e,"float32");return ni(t,n)}const n=wt(et(e),t);return js.makeTensor(n,e,t)}function Ip(e,t="float32"){if(vt(e),"complex64"===t){const t=Ip(e,"float32"),n=kp(e,"float32");return ni(t,n)}const n=xt(et(e),t);return js.makeTensor(n,e,t)}const Tp=ti({minimum_:function(e,t){let n=Jo(e,"a","minimum"),r=Jo(t,"b","minimum");[n,r]=Bs(n,r),"bool"===n.dtype&&(n=gu(n,"int32"),r=gu(r,"int32")),Tu(n.shape,r.shape);const a={a:n,b:r};return js.runKernel(ar,a)}}),Sp=ti({mirrorPad_:function(e,t,n){Qe("reflect"===n||"symmetric"===n,(()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`));const r=Jo(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 js.runKernel(sr,o,s)}}),Ep=ti({mod_:function(e,t){let n=Jo(e,"a","mod"),r=Jo(t,"b","mod");[n,r]=Bs(n,r);const a={a:n,b:r};return js.runKernel("Mod",a)}}),Np=ti({moments_:function(e,t=null,n=!1){const r=it(t,(e=Jo(e,"x","moments")).shape),a=vp(e,r,n);let s=a.shape;n||(s=Ec(a.shape,r));const o=Pc(lp(gu(e,"float32"),El(a,s)));return{mean:a,variance:vp(o,r,n)}}}),Ap=ti({multiRNNCell_:function(e,t,n,r){const a=Jo(t,"data","multiRNNCell"),s=Zo(n,"c","multiRNNCell"),o=Zo(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]}}),Cp=ti({multinomial_:function(e,t,n,r=!1){const a=Jo(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?El(a,[1,-1]):a},u={numSamples:t,seed:n,normalized:r},l=js.runKernel(or,i,u);return 1===o?El(l,[l.size]):l}}),Rp=ti({notEqual_:function(e,t){let n=Jo(e,"a","notEqual","string_or_numeric"),r=Jo(t,"b","notEqual","string_or_numeric");[n,r]=Bs(n,r),Tu(n.shape,r.shape);const a={a:n,b:r};return js.runKernel(ur,a)}}),Mp=ti({onesLike_:function(e){const t={x:Jo(e,"x","onesLike")};return js.runKernel(hr,t)}}),Fp=ti({outerProduct_:function(e,t){const n=Jo(e,"v1","outerProduct"),r=Jo(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=El(n,[-1,1]),s=El(r,[1,-1]);return yu(a,s)}}),$p=ti({pad_:function(e,t,n=0){const r=Jo(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 js.runKernel(mr,s,a)}}),Op=ti({pad1d_:function(e,t,n=0){return Qe(2===t.length,(()=>"Invalid number of paddings. Must be length of 2.")),$p(e,[t],n)}}),Dp=ti({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.")),$p(e,t,n)}}),Pp=ti({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.")),$p(e,t,n)}}),Lp=ti({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.")),$p(e,t,n)}}),Bp=ti({spaceToBatchND_:function(e,t,n){const r=Jo(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 js.runKernel(zr,a,s)}}),Up=ti({pool_:function(e,t,n,r,a,s,o){null==a&&(a=[1,1]),null==s&&(s=1),0===r&&(r="valid");const i=Jo(e,"x","maxPool");let u=i,l=!1;3===i.rank&&(l=!0,u=El(i,[1,i.shape[0],i.shape[1],i.shape[2]])),Qe(kl(s,a),(()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${a}'`));const c=dl(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:Bp(u,p,f),b=("avg"===n?()=>Nl(y,t,s,g,o):()=>bp(y,t,s,g,o))(),_=d?b:Dl(b,p,m);return l?El(_,[_.shape[1],_.shape[2],_.shape[3]]):_}}),Wp=ti({prelu_:function(e,t){const n={x:Jo(e,"x","prelu"),alpha:Jo(t,"alpha","prelu")};return js.runKernel(gr,n)}});function zp(e,t=!1){console.log(e.toString(t))}const Vp=ti({prod_:function(e,t=null,n=!1){let r=Jo(e,"x","prod");"bool"===r.dtype&&(r=gu(r,"int32"));const a={x:r},s={axis:t,keepDims:n};return js.runKernel(yr,a,s)}}),Hp=ti({raggedGather_:function(e,t,n,r){const a=e.map(((e,t)=>Jo(e,`tensors${t}`,"raggedGather","int32"))),s={paramsNestedSplits:a,paramsDenseValues:Jo(t,"paramsDenseValues","raggedGather"),indices:Jo(n,"indices","raggedGather","int32")},o={outputRaggedRank:r},i=js.runKernel("RaggedGather",s,o);return{outputNestedSplits:i.slice(0,i.length-1),outputDenseValues:i[i.length-1]}}}),Gp=ti({raggedRange_:function(e,t,n){const r=Jo(e,"starts","raggedRange"),a={starts:r,limits:Jo(t,"limits","raggedRange",r.dtype),deltas:Jo(n,"deltas","raggedRange",r.dtype)},s=js.runKernel("RaggedRange",a);return{rtNestedSplits:s[0],rtDenseValues:s[1]}}}),jp=ti({raggedTensorToTensor_:function(e,t,n,r,a){const s=Jo(e,"shape","raggedTensorToTensor","int32"),o=Jo(t,"values","raggedTensorToTensor"),i=Jo(n,"defaultValue","raggedTensorToTensor",o.dtype),u=r.map(((e,t)=>Jo(e,`tensors${t}`,"raggedTensorToTensor","int32"))),l={shape:s,values:o,defaultValue:i,rowPartitionTensors:u},c={rowPartitionTypes:a};return js.runKernel("RaggedTensorToTensor",l,c)}}),Kp=ti({rand_:function(e,t,n){vt(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 js.makeTensor(a,e,n)}});var qp="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==n.g?n.g:"undefined"!=typeof self?self:{};function Xp(e){var t={exports:{}};return e(t,t.exports),t.exports}var Yp=Xp((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)})),Qp=Xp((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)})),Jp=Xp((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)})),Zp=Xp((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)})),eh=Xp((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)})),th=Xp((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)})),nh=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:{}})),rh=Xp((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=nh}catch(e){}}else r["seed"+o]=p}("undefined"!=typeof self?self:qp,[],Math)}));rh.alea=Yp,rh.xor128=Qp,rh.xorwow=Jp,rh.xorshift7=Zp,rh.xor4096=eh,rh.tychei=th;var ah=rh;class sh{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=ah.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 oh{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const a=r||Math.random();this.randu=ah.alea(a.toString()),this.randn=new sh(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 ih{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=ah.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const uh=ti({randomGamma_:function(e,t,n=1,r="float32",a){if(vt(e),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error(`Unsupported data type ${r}`);const s=new oh(t,n,r,a),o=Gl(e,r);for(let e=0;e<o.values.length;e++)o.values[e]=s.nextValue();return o.toTensor()}}),lh=ti({randomNormal_:function(e,t=0,n=1,r,a){if(vt(e),null!=r&&"bool"===r)throw new Error(`Unsupported data type ${r}`);const s=new sh(t,n,r,!1,a),o=Gl(e,r);for(let e=0;e<o.values.length;e++)o.values[e]=s.nextValue();return o.toTensor()}}),ch=ti({randomStandardNormal_:function(e,t,n){if(null!=t&&"bool"===t)throw new Error(`Unsupported data type ${t}`);return lh(e,0,1,t,n)}}),ph=ti({randomUniform_:function(e,t=0,n=1,r="float32",a){vt(e);const s=Gl(e,r),o=new ih(t,n,null,a);for(let e=0;e<s.values.length;e++)s.values[e]=o.nextValue();return s.toTensor()}}),hh=ti({randomUniformInt_:function(e,t,n,r){return ph(e,t,n,"int32",r)}});function dh(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 js.runKernel(br,{},a)}const fh=ti({reciprocal_:function(e){const t={x:Jo(e,"x","reciprocal")};return js.runKernel(_r,t)}}),mh=ti({relu_:function(e){const t={x:Jo(e,"x","relu")};return js.runKernel(xr,t)}}),gh=ti({relu6_:function(e){const t={x:Jo(e,"x","relu6")};return js.runKernel(Sr,t)}}),yh=ti({reverse_:function(e,t){const n={x:Jo(e,"x","reverse")},r={dims:t};return js.runKernel(Er,n,r)}}),bh=ti({reverse1d_:function(e){const t=Jo(e,"x","reverse");return Qe(1===t.rank,(()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`)),yh(t,0)}}),_h=ti({reverse2d_:function(e,t){const n=Jo(e,"x","reverse");return Qe(2===n.rank,(()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`)),yh(n,t)}}),xh=ti({reverse3d_:function(e,t){const n=Jo(e,"x","reverse");return Qe(3===n.rank,(()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`)),yh(n,t)}}),wh=ti({reverse4d_:function(e,t){const n=Jo(e,"x","reverse");return Qe(4===n.rank,(()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`)),yh(n,t)}}),vh=ti({round_:function(e){const t={x:Jo(e,"x","round")};return js.runKernel(Nr,t)}}),kh=ti({rsqrt_:function(e){const t={x:Jo(e,"x","rsqrt","float32")};return js.runKernel(Ar,t)}}),Ih=ti({selu_:function(e){const t={x:Jo(e,"x","selu")};return js.runKernel($r,t)}}),Th=ti({separableConv2d_:function(e,t,n,r,a,s=[1,1],o="NHWC"){const i=Jo(e,"x","separableConv2d"),u=Jo(t,"depthwiseFilter","separableConv2d"),l=Jo(n,"pointwiseFilter","separableConv2d");let c=i,p=!1;if(3===i.rank&&(p=!0,c=El(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=hc(c,u,r,a,o,s),m=Zl(f,l,1,"valid",o);return p?El(m,[m.shape[1],m.shape[2],m.shape[3]]):m}}),Sh=ti({sign_:function(e){const t={x:Jo(e,"x","sign")};return js.runKernel(Pr,t)}}),Eh=ti({sin_:function(e){const t={x:Jo(e,"x","sin","float32")};return js.runKernel("Sin",t)}}),Nh=ti({sinh_:function(e){const t={x:Jo(e,"x","sinh")};return js.runKernel(Dr,t)}}),Ah=ti({slice1d_:function(e,t,n){const r=Jo(e,"x","slice1d");return Qe(1===r.rank,(()=>`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`)),Fl(r,[t],[n])}}),Ch=ti({slice2d_:function(e,t,n){const r=Jo(e,"x","slice2d");return Qe(2===r.rank,(()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`)),Fl(r,t,n)}}),Rh=ti({slice3d_:function(e,t,n){const r=Jo(e,"x","slice3d");return Qe(3===r.rank,(()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`)),Fl(r,t,n)}}),Mh=ti({slice4d_:function(e,t,n){const r=Jo(e,"x","slice4d");return Qe(4===r.rank,(()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`)),Fl(r,t,n)}}),Fh=ti({softmax_:function(e,t=-1){const n=Jo(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 js.runKernel(Hr,r,a)}}),$h=ti({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 js.runKernel("FFT",t)}}),Oh=ti({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 js.runKernel("IFFT",t)}}),Dh=ti({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let r;if(t<=2){const a=El(e,[n,t]);r=Oh(a)}else{const a=[n,2*(t-1)],s=El(wu(e),[n,t]),o=El(_u(e),[n,t]),i=yh(Fl(s,[0,1],[n,t-2]),1),u=Ju(yh(Fl(o,[0,1],[n,t-2]),1),Oc(-1)),l=Rl([s,i],1),c=Rl([o,u],1),p=El(ni(l,c),[a[0],a[1]]);r=Oh(p)}if(r=wu(r),3===e.rank&&0!==e.shape[0]){const t=r,n=e.shape[0];r=El(r,[n,r.shape[0]/n,r.shape[1]]),t.dispose()}return r}}),Ph=ti({split_:function(e,t,n=0){const r={x:Jo(e,"x","split")},a={numOrSizeSplits:t,axis:n};return js.runKernel(Vr,r,a)}}),Lh=ti({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=Fl(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=Rl([e,kp(r)],e.shape.length-1),n=t}else a=e;const s=yc(a),o=El(ni(a,s),[r,n]),i=$h(o),u=Math.floor(n/2)+1,l=wu(i),c=_u(i),p=Ph(l,[u,n-u],l.shape.length-1),h=Ph(c,[u,n-u],c.shape.length-1),d=a.shape.slice();return d[a.shape.length-1]=u,El(ni(p[0],h[0]),d)}}),Bh=ti({squaredDifference_:function(e,t){let n=Jo(e,"a","squaredDifference"),r=Jo(t,"b","squaredDifference");[n,r]=Bs(n,r),Tu(n.shape,r.shape);const a={a:n,b:r};return js.runKernel(Yr,a,{})}}),Uh=ti({squeeze_:function(e,t){const n=Jo(e,"x","squeeze","string_or_numeric");return El(n,ut(n.shape,t).newShape)}}),Wh=ti({stack_:function(e,t=0){const n=Zo(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 js.runKernel(fr,r,a)}}),zh=ti({step_:function(e,t=0){const n={x:Jo(e,"x","step")},r={alpha:t};return js.runKernel(ca,n,r)}}),Vh=ti({stridedSlice_:function(e,t,n,r,a=0,s=0,o=0,i=0,u=0){const l={x:Jo(e,"x","stridedSlice","string_or_numeric")},c={begin:t,end:n,strides:r,beginMask:a,endMask:s,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:u};return js.runKernel(Qr,l,c)}}),Hh=ti({tan_:function(e){const t={x:Jo(e,"x","tan","float32")};return js.runKernel("Tan",t)}});function Gh(e,t){Ze(e);const n=Xo(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return ri(e,null,n,t)}function jh(e,t,n){if(Ze(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const r=Xo(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 ri(e,t,r,n)}const Kh=ti({tensorScatterUpdate_:function(e,t,n){const r=Jo(e,"tensor","tensorScatterupdate"),a=Jo(t,"indices","tensorScatterupdate","int32"),s=Jo(n,"updates","tensorScatterupdate");if(Ru(s,a,r.shape),r.dtype!==s.dtype)throw new Error(`tensor and updates must have the same dtype, instead they are ${r.dtype} and ${s.dtype}.`);const o={tensor:r,indices:a,updates:s};return js.runKernel(Rr,o,{})}}),qh=ti({topk_:function(e,t=1,n=!0){const r=Jo(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]=js.runKernel(aa,s,o);return{values:i,indices:u}}}),Xh=ti({truncatedNormal_:function(e,t=0,n=1,r,a){if(vt(e),null!=r&&"bool"===r)throw new Error("Unsupported data type $ { dtype }");const s=new sh(t,n,r,!0,a),o=Gl(e,r);for(let e=0;e<o.values.length;e++)o.values[e]=s.nextValue();return o.toTensor()}}),Yh=ti({unique_:function(e,t=0){const n=Jo(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]=js.runKernel(ia,r,a);return{values:s,indices:o}}}),Qh=ti({unsortedSegmentSum_:function(e,t,n){const r=Jo(e,"x","unsortedSegmentSum"),a=Jo(t,"segmentIds","unsortedSegmentSum","int32");Qe(nt(n),(()=>"numSegments must be of dtype int"));const s={x:r,segmentIds:a},o={numSegments:n};return js.runKernel("UnsortedSegmentSum",s,o)}}),Jh=ti({unstack_:function(e,t=0){const n=Jo(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 js.runKernel(ua,r,a)}});function Zh(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const r=Gl(e,"int32"),a=Gl([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 ed=async function(e){const t=Jo(e,"condition","whereAsync","bool"),n=await t.data(),r=Zh(t.shape,n);return e!==t&&t.dispose(),r},td=ti({movingAverage_:function(e,t,n,r,a=!0){const s=Jo(e,"v","movingAverage"),o=Jo(t,"x","movingAverage"),i=Jo(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=Oc(1),p=lp(c,i);let h=Ju(lp(o,s),p);if(a){Qe(null!=r,(()=>"When using zeroDebias: true, step is required."));const e=Jo(r,"step","movingAverage");h=Qu(h,lp(c,$c(i,e)))}return Xu(s,h)}}),nd=ti({scatterND_:function(e,t,n){vt(n);const r=Jo(e,"indices","scatterND","int32"),a=Jo(t,"updates","scatterND");Ru(a,r,n);const s={indices:r,updates:a},o={shape:n};return js.runKernel(Cr,s,o)}}),rd=ti({sparseToDense_:function(e,t,n,r=0){vt(n);const a=Jo(e,"sparseIndices","sparseToDense","int32"),s=Jo(t,"sparseValues","sparseToDense","string_or_numeric"),o=Jo(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 js.runKernel(Xr,i,u)}}),ad=ti({gatherND_:function(e,t){const n=Jo(t,"indices","gatherND","int32"),r={params:Jo(e,"x","gatherND","string_or_numeric"),indices:n};return js.runKernel($n,r)}}),sd=ti({dropout_:function(e,t,n,r){const a=Jo(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 Es?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=Qu(Kc(Xu(ph(s,0,1,"float32",r),o)),o);return Ju(a,i)}});function od(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function id(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 Gh(a,"float32")}const ud=ti({conv2DBackpropFilter_:function(e,t,n,r,a,s="NHWC",o){let i=e;3===e.rank&&(i=El(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u=t;3===u.rank&&(u=El(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]}).`)),Sl("conv2dDerFilter",a,o);const p={x:i,dy:u},h={strides:r,pad:a,dataFormat:s,dimRoundingMode:o,filterShape:n};return js.runKernel("Conv2DBackpropFilter",p,h)}});function ld(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return Ju(e,zh(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function cd(e,t){let n=t;const r=Iu(e.shape,t.shape);return r.length>0&&(n=Lc(n,r)),El(n,e.shape)}function pd(e,t,n,r){if("linear"===t)return e;if("relu"===t)return mh(e);if("elu"===t)return wc(e);if("relu6"===t)return gh(e);if("prelu"===t)return Wp(e,n);if("leakyrelu"===t)return ep(e,r);if("sigmoid"===t)return Ml(e);throw new Error(`Unknown fused activation ${t}.`)}const hd=(e,t)=>!(e>0)||"linear"===t,dd=ti({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===hd(js.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=Zl(e,t,n,r,a,s,o);return null!=i&&(p=Xu(p,i)),pd(p,u,l,c)}const p=Jo(e,"x","conv2d","float32"),h=Jo(t,"filter","conv2d","float32");let d=p,f=!1;3===p.rank&&(f=!0,d=El(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}.`)),Sl("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(kl(n,s),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`));const g=ml(d.shape,h.shape,n,s,r,o);let y,b;if(null!=i&&(y=Jo(i,"bias","fused conv2d"),[y]=Bs(y,p),"NHWC"===a?Tu(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{Tu(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=Jo(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=ld(e,l,u);Qe(vl(s),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`));const h=[tc(i.shape,p,o,n,r),ud(i,p,o.shape,n,r)];if(null!=c){const e=cd(c,p);h.push(e)}return h},x={x:d,filter:h,bias:y,preluActivationWeights:b},w={strides:n,pad:r,dataFormat:a,dilations:s,dimRoundingMode:o,activation:u,leakyreluAlpha:c};if(null==i){const e=op(((e,t,n)=>{let r=js.runKernel(fa,x,w);return n([t,e,r]),f&&(r=El(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:_}}));return e(d,h)}{const e=op(((e,t,n,r)=>{let a=js.runKernel(fa,x,w);return r([t,e,a,n]),f&&(a=El(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:_}}));return e(d,h,y)}}}),fd=ti({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,r,a,s=[1,1],o){let i=e;3===e.rank&&(i=El(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u=t;3===u.rank&&(u=El(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 js.runKernel("DepthwiseConv2dNativeBackpropFilter",l,c)}}),md=ti({depthwiseConv2dNativeBackpropInput_:function(e,t,n,r,a,s=[1,1],o){let i=t,u=!1;3===t.rank&&(u=!0,i=El(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=js.runKernel("DepthwiseConv2dNativeBackpropInput",l,c);return u?El(p,[p.shape[1],p.shape[2],p.shape[3]]):p}}),gd=ti({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===hd(js.state.gradientDepth,u)){let p=hc(e,t,n,r,a,s,o);return null!=i&&(p=Xu(p,i)),pd(p,u,l,c)}const p=Jo(e,"x","depthwiseConv2d","float32"),h=Jo(t,"filter","depthwiseConv2d","float32");let d=p,f=!1;3===p.rank&&(f=!0,d=El(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(kl(n,s),(()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`)),Sl("fused depthwiseConv2d",r,o);const m=ml(d.shape,h.shape,n,s,r,o,!0);let g,y;null!=i&&(g=Jo(i,"bias","fused conv2d"),[g]=Bs(g,p),Tu(m.outShape,g.shape)),null!=l&&(y=Jo(l,"prelu weights","fused depthwiseConv2d"));const b=(e,t)=>{Qe(vl(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=ld(e,l,u),h=md(i.shape,p,a,n,r,s,o),d=fd(i,p,a.shape,n,r,s,o);return null!=c?[h,d,cd(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=op(((e,t,n)=>{let r=js.runKernel(ma,_,x);return n([t,e,r]),f&&(r=El(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:b}}));return e(d,h)}{const e=op(((e,t,n,r)=>{let a=js.runKernel(ma,_,x);return r([t,e,a,n]),f&&(a=El(a,[a.shape[1],a.shape[2],a.shape[3]])),{value:a,gradFunc:b}}));return e(d,h,g)}}}),yd=ti({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:a,activation:s="linear",preluActivationWeights:o,leakyreluAlpha:i=.2}){if(!1===hd(js.state.gradientDepth,s)){let u=yu(e,t,n,r);return null!=a&&(u=Xu(u,a)),pd(u,s,o,i)}let u=Jo(e,"a","fused matMul"),l=Jo(t,"b","fused matMul");[u,l]=Bs(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=Tu(u.shape.slice(0,-2),l.shape.slice(0,-2)).concat([h,d]),_=El(u,n?[g,c,h]:[g,h,c]),x=El(l,r?[y,d,p]:[y,p,d]);let w,v;null!=a&&(w=Jo(a,"bias","fused matMul"),[w]=Bs(w,u),Tu(b,w.shape)),null!=o&&(v=Jo(o,"prelu weights","fused matMul"));const k=(e,t)=>{const[o,i,u,l]=t,c=ld(El(e,u.shape),u,s);let p,h;return n||r?!n&&r?(p=yu(c,i,!1,!1),h=yu(c,o,!0,!1)):n&&!r?(p=yu(i,c,!1,!0),h=yu(o,c,!1,!1)):(p=yu(i,c,!0,!0),h=yu(c,o,!0,!0)):(p=yu(c,i,!1,!0),h=yu(o,c,!0,!1)),null!=a?[p,h,cd(l,c)]:[p,h]},I={a:_,b:x,bias:w,preluActivationWeights:v},T={transposeA:n,transposeB:r,activation:s,leakyreluAlpha:i};if(null==a){const e=op(((e,t,n)=>{const r=js.runKernel(da,I,T);return n([e,t,r]),{value:El(r,b),gradFunc:k}}));return e(_,x)}{const e=op(((e,t,n,r)=>{const a=js.runKernel(da,I,T);return r([e,t,a,n]),{value:El(a,b),gradFunc:k}}));return e(_,x,w)}}});var bd=Object.freeze({__proto__:null,conv2d:dd,depthwiseConv2d:gd,matMul:yd});const _d=ti({hammingWindow_:function(e){return id(e,.54,.46)}}),xd=ti({hannWindow_:function(e){return id(e,.5,.5)}}),wd=ti({frame_:function(e,t,n,r=!1,a=0){let s=0;const o=[];for(;s+t<=e.size;)o.push(Fl(e,s,t)),s+=n;if(r)for(;s<e.size;){const r=s+t-e.size,i=Rl([Fl(e,s,t-r),Kl([r],a)]);o.push(i),s+=n}return 0===o.length?jh([],[0,t]):El(Rl(o),[o.length,t])}}),vd=ti({stft_:function(e,t,n,r,a=xd){null==r&&(r=od(t));const s=wd(e,t,n),o=Ju(s,a(t));return Lh(o,r)}}),kd=ti({cropAndResize_:function(e,t,n,r,a="bilinear",s=0){const o=Jo(e,"image","cropAndResize"),i=Jo(t,"boxes","cropAndResize","float32"),u=Jo(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 js.runKernel(dn,c,p)}}),Id=ti({flipLeftRight_:function(e){const t=Jo(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 js.runKernel(An,n,{})}}),Td=ti({grayscaleToRGB_:function(e){const t=Jo(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,Gc(t,a)}}),Sd=ti({rgbToGrayscale_:function(e){const t=Jo(e,"image","RGBToGrayscale"),n=t.rank-1,r=t.shape[n];Qe(t.rank>=2,(()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`)),Qe(3===r,(()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${r}.`));const a=t.dtype,s=gu(t,"float32"),o=Gh([.2989,.587,.114]);let i;switch(t.rank){case 2:i=xc("ij,j->i",s,o);break;case 3:i=xc("ijk,k->ij",s,o);break;case 4:i=xc("ijkl,l->ijk",s,o);break;case 5:i=xc("ijklm,m->ijkl",s,o);break;case 6:i=xc("ijklmn,n->ijklm",s,o);break;default:throw new Error("Not a valid tensor rank.")}return i=Vc(i,-1),gu(i,a)}}),Ed=ti({rotateWithOffset_:function(e,t,n=0,r=.5){const a=Jo(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 js.runKernel(ha,s,o)}});function Nd(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 Ad=ti({nonMaxSuppression_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY){const s=Jo(e,"boxes","nonMaxSuppression","float32"),o=Jo(t,"scores","nonMaxSuppression","float32"),i=Nd(s,o,n,r,a),u={maxOutputSize:n=i.maxOutputSize,iouThreshold:r=i.iouThreshold,scoreThreshold:a=i.scoreThreshold};return js.runKernel(lr,{boxes:s,scores:o},u)}});function Cd(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||Rd)}(e,t,n),a=r<0?-(r+1):r;e.splice(a,0,t)}function Rd(e,t){return e>t?1:e<t?-1:0}function Md(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(Od);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=Fd(e,s,p[n]);if(o>=r){i=!0;break}if(t.score=t.score*$d(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&&Cd(l,t,Od))}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 Fd(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 $d(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function Od(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const Dd=ti({nonMaxSuppressionWithScore_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=0){const o=Jo(e,"boxes","nonMaxSuppression"),i=Jo(t,"scores","nonMaxSuppression"),u=Nd(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=js.runKernel(pr,l,c);return{selectedIndices:p[0],selectedScores:p[1]}}}),Pd=ti({nonMaxSuppressionPadded_:function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=!1){const o=Jo(e,"boxes","nonMaxSuppression"),i=Jo(t,"scores","nonMaxSuppression"),u=Nd(o,i,n,r,a,null),l={boxes:o,scores:i},c={maxOutputSize:u.maxOutputSize,iouThreshold:u.iouThreshold,scoreThreshold:u.scoreThreshold,padToMaxOutputSize:s},p=js.runKernel(cr,l,c);return{selectedIndices:p[0],validOutputs:p[1]}}}),Ld=ti({resizeBilinear_:function(e,t,n=!1,r=!1){const a=Jo(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=El(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const i={images:s},u={alignCorners:n,halfPixelCenters:r,size:t},l=js.runKernel(Ir,i,u);return o?El(l,[l.shape[1],l.shape[2],l.shape[3]]):l}}),Bd=ti({resizeNearestNeighbor_:function(e,t,n=!1,r=!1){const a=Jo(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=El(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const i={images:s},u={alignCorners:n,halfPixelCenters:r,size:t},l=js.runKernel(vr,i,u);return o?El(l,[l.shape[1],l.shape[2],l.shape[3]]):l}}),Ud=ti({threshold_:function(e,t="binary",n=!1,r=.5){const a=Jo(e,"image","threshold"),s=a.shape[0]*a.shape[1];let o,i,u,l,c=Ju(Gh([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]=Ph(a,[1,1,1],-1);const e=Ju(o,.2989),t=Ju(i,.587),n=Ju(u,.114);l=Xu(Xu(e,t),n)}else l=e;"otsu"===t&&(c=function(e,t){let n,r,a,s,o,i,u=Gh([-1]),l=Gh([0]),c=Gh([0]);for(let p=0;p<e.size-1;p++){n=Fl(e,0,p+1),r=Fl(e,p+1),o=Qu(Lc(n),t),i=Qu(Lc(r),t);const h=Lc(Ju(n,dh(0,n.size)));a=Qu(h,Lc(n));const d=Kl(r.shape,n.size),f=Xu(dh(0,r.size),d),m=Ju(r,f);s=Qu(Lc(m),Lc(r));const g=lp(a,s),y=lp(a,s),b=Ju(o,i);c=Ju(Ju(b,g),y);const _=Xc(c,l);l=gc(_,c,l),u=gc(_,Gh([p]),u)}return u}(Wl(gu(vh(l),"int32"),ai([]),256),s));const p=n?np(l,c):Xc(l,c);return gu(Ju(p,255),"int32")}}),Wd=ti({transform_:function(e,t,n="nearest",r="constant",a=0,s){const o=Jo(e,"image","transform","float32"),i=Jo(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 js.runKernel(sa,u,l)}}),zd=ti({bandPart_:function(e,t,n){const r=Jo(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);let i,u;"number"==typeof t?(Qe(t%1==0,(()=>`bandPart(): numLower must be an integer, got ${t}.`)),Qe(t<=s,(()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`)),i=Jo(t<0?s:t,"numLower","bandPart")):(Qe("int32"===t.dtype,(()=>"bandPart(): numLower's dtype must be an int32.")),i=gc(tp(t,0),s,Tp(t,s))),"number"==typeof n?(Qe(n%1==0,(()=>`bandPart(): numUpper must be an integer, got ${n}.`)),Qe(n<=o,(()=>`bandPart(): numUpper (${n}) must not be greater than the number of columns (${o}).`)),u=Jo(n<0?o:n,"numUpper","bandPart")):(Qe("int32"===n.dtype,(()=>"bandPart(): numUpper's dtype must be an int32.")),u=gc(tp(n,0),o,Tp(n,o)));const l=El(dh(0,s,1,"int32"),[-1,1]),c=dh(0,o,1,"int32"),p=lp(l,c),h=hp(np(p,i),Yc(p,xu(u))),d=kp([s,o],r.dtype);return El(Wh(Jh(El(r,[-1,s,o])).map((e=>gc(h,e,d)))),a)}}),Vd=ti({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=Ph(e,e.shape[0],0).map((e=>Uh(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(js.tidy((()=>{let e=r[t];if(t>0)for(let r=0;r<t;++r){const t=Ju(Lc(Ju(n[r],e)),n[r]);e=lp(e,t)}return Qu(e,Uc(e,"euclidean"))})));return t?Wh(n,0):n}});function Hd(e,t=!1){return js.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=jc(n),s=Cl(e);const o=jh([[1]],[1,1]);let i=Cl(o);const u=n>=r?r:n;for(let e=0;e<u;++e){const t=s,u=i,l=a;[i,s,a]=js.tidy((()=>{const t=Fl(s,[e,e],[n-e,1]),u=Uc(t),l=Fl(s,[e,e],[1,1]),c=gc(Xc(l,0),jh([[-1]]),jh([[1]])),p=lp(l,Ju(c,u)),h=Qu(t,p);i=1===h.shape[0]?Cl(o):Rl([o,Fl(h,[1,0],[h.shape[0]-1,h.shape[1]])],0);const d=xu(Qu(yu(c,p),u)),f=Fl(s,[e,0],[n-e,r]),m=Ju(d,i),g=vu(i);if(0===e)s=lp(f,yu(m,yu(g,f)));else{const t=lp(f,yu(m,yu(g,f)));s=Rl([Fl(s,[0,0],[e,r]),t],0)}const y=vu(m),b=Fl(a,[0,e],[n,a.shape[1]-e]);if(0===e)a=lp(b,yu(yu(b,i),y));else{const t=lp(b,yu(yu(b,i),y));a=Rl([Fl(a,[0,0],[n,e]),t],1)}return[i,s,a]})),li([t,u,l])}return!t&&n>r&&(a=Fl(a,[0,0],[n,r]),s=Fl(s,[0,0],[r,r])),[a,s]}))}const Gd=ti({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 Hd(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),r=Jh(El(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),a=[],s=[];return r.forEach((e=>{const[n,r]=Hd(e,t);a.push(n),s.push(r)})),[El(Wh(a,0),e.shape),El(Wh(s,0),e.shape)]}}});var jd;!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"}(jd||(jd={}));const Kd=ti({computeWeightedLoss_:function(e,t,n=jd.SUM_BY_NONZERO_WEIGHTS){const r=Jo(e,"losses","computeWeightedLoss");let a=null;null!=t&&(a=Jo(t,"weights","computeWeightedLoss"));const s=null==a?r:Ju(r,a);if(n===jd.NONE)return s;if(n===jd.SUM)return Lc(s);if(n===jd.MEAN){if(null==a)return vp(s);{const e=r.size/a.size,t=Qu(Lc(s),Lc(a));return e>1?Qu(t,Oc(e)):t}}if(n===jd.SUM_BY_NONZERO_WEIGHTS){if(null==a)return Qu(Lc(s),Oc(r.size));{const e=Ju(a,Ip(r.shape)),t=gu(Lc(Rp(e,Oc(0))),"float32");return Qu(Lc(s),t)}}throw Error(`Unknown reduction: ${n}`)}}),qd=ti({absoluteDifference_:function(e,t,n,r=jd.SUM_BY_NONZERO_WEIGHTS){const a=Jo(e,"labels","absoluteDifference"),s=Jo(t,"predictions","absoluteDifference");let o=null;null!=n&&(o=Jo(n,"weights","absoluteDifference")),Je(a.shape,s.shape,"Error in absoluteDifference: ");const i=Zu(lp(a,s));return Kd(i,o,r)}}),Xd=ti({cosineDistance_:function(e,t,n,r,a=jd.SUM_BY_NONZERO_WEIGHTS){const s=Jo(e,"labels","cosineDistance"),o=Jo(t,"predictions","cosineDistance");let i=null;null!=r&&(i=Jo(r,"weights","cosineDistance")),Je(s.shape,o.shape,"Error in cosineDistance: ");const u=Oc(1),l=lp(u,Lc(Ju(s,o),n,!0));return Kd(l,i,a)}}),Yd=ti({hingeLoss_:function(e,t,n,r=jd.SUM_BY_NONZERO_WEIGHTS){let a=Jo(e,"labels","hingeLoss");const s=Jo(t,"predictions","hingeLoss");let o=null;null!=n&&(o=Jo(n,"weights","hingeLoss")),Je(a.shape,s.shape,"Error in hingeLoss: ");const i=Oc(1);a=lp(Ju(Oc(2),a),i);const u=mh(lp(i,Ju(a,s)));return Kd(u,o,r)}}),Qd=ti({huberLoss_:function(e,t,n,r=1,a=jd.SUM_BY_NONZERO_WEIGHTS){const s=Jo(e,"labels","huberLoss"),o=Jo(t,"predictions","huberLoss");let i=null;null!=n&&(i=Jo(n,"weights","huberLoss")),Je(s.shape,o.shape,"Error in huberLoss: ");const u=Oc(r),l=Zu(lp(o,s)),c=Tp(l,u),p=lp(l,c),h=Xu(Ju(Oc(.5),Pc(c)),Ju(u,p));return Kd(h,i,a)}}),Jd=ti({logLoss_:function(e,t,n,r=1e-7,a=jd.SUM_BY_NONZERO_WEIGHTS){const s=Jo(e,"labels","logLoss"),o=Jo(t,"predictions","logLoss");let i=null;null!=n&&(i=Jo(n,"weights","logLoss")),Je(s.shape,o.shape,"Error in logLoss: ");const u=Oc(1),l=Oc(r),c=xu(Ju(s,ap(Xu(o,l)))),p=Ju(lp(u,s),ap(Xu(lp(u,o),l))),h=lp(c,p);return Kd(h,i,a)}}),Zd=ti({meanSquaredError_:function(e,t,n,r=jd.SUM_BY_NONZERO_WEIGHTS){const a=Jo(e,"labels","meanSquaredError"),s=Jo(t,"predictions","meanSquaredError");let o=null;null!=n&&(o=Jo(n,"weights","meanSquaredError")),Je(a.shape,s.shape,"Error in meanSquaredError: ");const i=Bh(a,s);return Kd(i,o,r)}}),ef=ti({sigmoidCrossEntropy_:function(e,t,n,r=0,a=jd.SUM_BY_NONZERO_WEIGHTS){let s=Jo(e,"multiClassLabels","sigmoidCrossEntropy");const o=Jo(t,"logits","sigmoidCrossEntropy");let i=null;if(null!=n&&(i=Jo(n,"weights","sigmoidCrossEntropy")),Je(s.shape,o.shape,"Error in sigmoidCrossEntropy: "),r>0){const e=Oc(r),t=Oc(1),n=Oc(.5);s=Xu(Ju(s,lp(t,e)),Ju(n,e))}const u=function(e,t){const n=Jo(e,"labels","sigmoidCrossEntropyWithLogits"),r=Jo(t,"logits","sigmoidCrossEntropyWithLogits");Je(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const a=mh(r),s=Ju(r,n),o=sp(zc(xu(Zu(r))));return Xu(lp(a,s),o)}(s,o);return Kd(u,i,a)}}),tf=ti({softmaxCrossEntropy_:function(e,t,n,r=0,a=jd.SUM_BY_NONZERO_WEIGHTS){let s=Jo(e,"onehotLabels","softmaxCrossEntropy");const o=Jo(t,"logits","softmaxCrossEntropy");let i=null;if(null!=n&&(i=Jo(n,"weights","softmaxCrossEntropy")),Je(s.shape,o.shape,"Error in softmaxCrossEntropy: "),r>0){const e=Oc(r),t=Oc(1),n=Oc(s.shape[1]);s=Xu(Ju(s,lp(t,e)),Qu(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=op(((e,t,r)=>{const a=pp(t,[n],!0),s=lp(gu(t,"float32"),a);r([e,s]);const o=xu(Ju(s,e));return{value:Lc(o,[n]),gradFunc:(e,t)=>{const[r,a]=t,s=Ec(e.shape,[n]);return[Ju(El(e,s),lp(gu(r,"float32"),zc(a))),Ju(El(e,s),lp(zc(a),gu(r,"float32")))]}}}));return r(e,t)}(s,o);return Kd(u,i,a)}}),nf=ti({sparseFillEmptyRows_:function(e,t,n,r){const a=Jo(e,"indices","sparseFillEmptyRows","int32"),s=Jo(t,"values","sparseFillEmptyRows"),o=Jo(n,"denseShape","sparseFillEmptyRows","int32"),i=Jo(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=js.runKernel(Gr,u);return{outputIndices:l[0],outputValues:l[1],emptyRowIndicator:l[2],reverseIndexMap:l[3]}}}),rf=ti({sparseReshape_:function(e,t,n){const r=Jo(e,"inputIndices","sparseReshape","int32"),a=Jo(t,"inputShape","sparseReshape","int32"),s=Jo(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=js.runKernel(jr,o);return{outputIndices:i[0],outputShape:i[1]}}}),af=ti({sparseSegmentMean_:function(e,t,n){const r=Jo(e,"data","sparseSegmentMean"),a=Jo(t,"indices","sparseSegmentMean","int32"),s=Jo(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 js.runKernel(Kr,o)}}),sf=ti({sparseSegmentSum_:function(e,t,n){const r=Jo(e,"data","sparseSegmentSum"),a=Jo(t,"indices","sparseSegmentSum","int32"),s=Jo(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 js.runKernel(qr,o)}}),of=ti({stringNGrams_:function(e,t,n,r,a,s,o,i){const u=Jo(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=Jo(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=js.runKernel(Jr,p,c);return{nGrams:h[0],nGramsSplits:h[1]}}}),uf={fft:$h,ifft:Oh,rfft:Lh,irfft:Dh},lf={hammingWindow:_d,hannWindow:xd,frame:wd,stft:vd},cf={flipLeftRight:Id,grayscaleToRGB:Td,resizeNearestNeighbor:Bd,resizeBilinear:Ld,rgbToGrayscale:Sd,rotateWithOffset:Ed,cropAndResize:kd,nonMaxSuppression:Ad,nonMaxSuppressionAsync:async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY){const s=Jo(e,"boxes","nonMaxSuppressionAsync"),o=Jo(t,"scores","nonMaxSuppressionAsync"),i=Nd(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 Md(e,t,n,r,a,0)}(l,c,n,r,a);return s!==e&&s.dispose(),o!==t&&o.dispose(),Gh(p,"int32")},nonMaxSuppressionWithScore:Dd,nonMaxSuppressionWithScoreAsync:async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=0){const o=Jo(e,"boxes","nonMaxSuppressionAsync"),i=Jo(t,"scores","nonMaxSuppressionAsync"),u=Nd(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 Md(e,t,n,r,a,s,!0)}(c,p,n,r,a,s);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Gh(h,"int32"),selectedScores:Gh(d)}},nonMaxSuppressionPadded:Pd,nonMaxSuppressionPaddedAsync:async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY,s=!1){const o=Jo(e,"boxes","nonMaxSuppressionAsync"),i=Jo(t,"scores","nonMaxSuppressionAsync"),u=Nd(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 Md(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:Gh(f,"int32"),validOutputs:Oc(m,"int32")}},threshold:Ud,transform:Wd},pf={bandPart:zd,gramSchmidt:Vd,qr:Gd},hf={absoluteDifference:qd,computeWeightedLoss:Kd,cosineDistance:Xd,hingeLoss:Yd,huberLoss:Qd,logLoss:Jd,meanSquaredError:Zd,sigmoidCrossEntropy:ef,softmaxCrossEntropy:tf},df={sparseFillEmptyRows:nf,sparseReshape:rf,sparseSegmentMean:af,sparseSegmentSum:sf},ff={stringNGrams:of,stringSplit:ti({stringSplit_:function(e,t,n=!0){const r=Jo(e,"input","stringSplit","string"),a=Jo(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=js.runKernel(Zr,o,s);return{indices:i[0],values:i[1],shape:i[2]}}}),stringToHashBucketFast:ti({stringToHashBucketFast_:function(e,t){const n=Jo(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 js.runKernel(ea,a,r)}}),staticRegexReplace:ti({staticRegexReplace_:function(e,t,n,r=!0){const a=Jo(e,"input","staticRegexReplace","string"),s={pattern:t,rewrite:n,replaceGlobal:r};return js.runKernel("StaticRegexReplace",{x:a},s)}})},mf="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:e=>e();function gf(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 yf(e,t){const n=e[0].slice();for(let r=1;r<e.length;r++)n[t]+=e[r][t];return n}var bf;function _f(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 xf(e){const t={FIRST_DIM_SIZE:bf.FIRST_DIM_SIZE,VALUE_ROWIDS:bf.VALUE_ROWIDS,ROW_LENGTHS:bf.ROW_LENGTHS,ROW_SPLITS:bf.ROW_SPLITS,ROW_LIMITS:bf.ROW_LIMITS,ROW_STARTS:bf.ROW_STARTS},n=[];for(const r of e){if(!(r in t))break;n.push(t[r])}return n}function wf(e){return 0===e.length?0:e[0]===bf.FIRST_DIM_SIZE?e.length-1:e.length}function vf(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 kf(e){return e<=30?e:gt(e,Math.floor(Math.sqrt(e)))}function If(e,t,n){return[n*("number"==typeof e?e:e[0]),t*("number"==typeof e?e:e[1])]}function Tf(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 Sf(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 Ef(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 Nf(e,t){const n=[0];for(let r=0;r<t;++r)n.push(e[r][0]);return n}function Af(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 Cf(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"}(bf||(bf={}));const Rf=/->/g;function Mf(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 Ff(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 $f(e){return`Received SparseTensor with denseShape[0] = 0 but\n indices.shape[0] = ${e}`}function Of(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function Df(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function Pf(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function Lf(e,t){return`size ${e} must be non-negative, not ${t}`}function Bf(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 Uf(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 Wf(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function zf(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}function Vf(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 Hf=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:Vf});function Gf(e){try{return e.map((e=>ds(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function jf(e){return e.map((e=>hs(e)))}var Kf=Object.freeze({__proto__:null,slice_util:qu,segment_util:Hf,fromUint8ToStringArray:Gf,fromStringArrayToUint8:jf,upcastType:Ds,axesAreInnerMostDims:Ic,combineLocations:Tc,computeOutAndReduceShapes:Sc,expandShapeToKeepDim:Ec,assertAxesAreInnerMostDims:Nc,getAxesPermutation:Ac,getUndoAxesPermutation:Cc,getInnerMostAxes:Rc,getBroadcastDims:ku,getReductionAxes:Iu,assertAndGetBroadcastShape:Tu,assertParamsConsistent:gf,computeOutShape:yf,computeDilation2DInfo:hl,computePool2DInfo:dl,computePool3DInfo:fl,computeConv2DInfo:ml,computeConv3DInfo:gl,computeDefaultPad:yl,tupleValuesAreOne:vl,eitherStridesOrDilationsAreOne:kl,stridesOrDilationsArePositive:Il,convertConv2DDataFormat:Tl,checkPadOnDimRoundingMode:Sl,getFusedDyActivation:ld,getFusedBiasGradient:cd,applyActivation:pd,shouldFuse:hd,get RowPartitionType(){return bf},combineRaggedTensorToTensorShapes:_f,getRowPartitionTypesHelper:xf,getRaggedRank:wf,validateDefaultValueShape:vf,PARALLELIZE_THRESHOLD:30,computeOptimalWindowSize:kf,getImageCenter:If,getReshaped:Tf,getPermuted:Sf,getReshapedPermuted:Ef,getSliceBeginCoords:Nf,getSliceSize:Af,prepareAndValidate:Au,validateUpdateShape:Cu,validateInput:Ru,calculateShapes:Mu,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:ga,log:function(...e){At().getBool("IS_TEST")||At().getBool("PROD")||console.log(...e)},mergeRealAndImagArrays:Cf,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(Rf,"").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=Mf(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:Ff,getSparseFillEmptyRowsIndicesDenseShapeMismatch:$f,getSparseFillEmptyRowsNegativeIndexErrorMessage:Of,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:Df,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:Pf,getSparseReshapeNegativeOutputDimErrorMessage:Lf,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:function(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"},getSparseReshapeInputOutputMultipleErrorMessage:Bf,getSparseReshapeInputOutputMismatchErrorMessage:Uf,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:function(){return"segment ids must be >= 0"},getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:function(){return"segment ids are not increasing"},getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:Wf,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:zf});class qf{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&&At().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 Ia(e)}}if(At().get("IS_BROWSER")){At().setPlatform("browser",new qf);try{hu.registerManager(qi.URL_SCHEME,new Yi)}catch(e){}try{hu.registerManager(Oi.URL_SCHEME,new Pi)}catch(e){}}let Xf;var Yf,Qf;At().get("IS_NODE")&&!At().get("IS_BROWSER")&&At().setPlatform("node",new class{constructor(){this.util=n(345),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=At().global.fetch?At().global.fetch(e,t):(null==Xf&&(Xf=n(683)),Xf(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)}}),Gs(),Ss={buffer:Gl,cast:gu,clone:Cl,print:zp},At().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"}(Yf||(Yf={})),function(e){var t;(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"}(Qf||(Qf={}));const Jf={};function Zf(e){return Jf[e]}function em(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,i=e<0?t.inputNames.length+e:e;if("tensor"===s.type)return tm(t.inputNames[i],n,r,a);if("tensors"===s.type){const s=t.inputs.slice(e,o),i=t.inputNames.slice(e,o).filter(((e,t)=>{var n;return"NoOp"!==(null===(n=s[t])||void 0===n?void 0:n.op)}));return i.map((e=>tm(e,n,r,a)))}const u=tm(t.inputNames[i],n,r,a),l=u.dataSync();return"number"===s.type?l[0]:_t(u.shape,l)}const o=t.attrParams[e];return o&&o.value}function tm(e,t,n,r){const[a,s]=sm(e,n);if(null!=r){const e=r.getHashTableHandleByName(a);if(null!=e)return e}const o=n.currentContextIds.find((e=>!!t[am(a,e)]));return void 0!==o?t[am(a,o)][s]:void 0}function nm(e,t,n){return t[am(e,n.currentContextId)]}function rm(e,t){const[n,r,a]=sm(e,t);return[am(n,t&&t.currentContextId),r,a]}function am(e,t){return t?`${e}-${t}`:e}function sm(e,t){if(""===e)return["",0,void 0];const n=null!=t&&null!=t.parseNodeNameCache;if(n){const n=t.parseNodeNameCache.get(e);if(null!=n)return n}const r=e.split(":");let a;if(1===r.length)a=[e,0,void 0];else{const e=r[0],t=3===r.length?r[1]:void 0;a=[e,Number(r[r.length-1]),t]}return n&&t.parseNodeNameCache.set(e,a),a}function om(e,t,n){let r=em("pad",e,t,n);if("explicit"===r){r=em("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 im(e){return e.kept?e:Cl(e)}var um=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}]}]}),lm=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:"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}]},{tfOpName:"IsFinite",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsInf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),cm=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"}]}]}),pm=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"}]}]}),hm=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:"RandomUniformInt",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number"},{tfName:"maxval",name:"maxval",type:"number"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,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"}]}]}),dm=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}]}]}),fm=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"}]}]}),mm=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"}]}]}),gm=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"}]}]}),ym=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"}]}]}),bm=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}]},{tfOpName:"BitwiseAnd",category:"logical",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}]}]}),_m=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"}]},{tfOpName:"MatrixBandPart",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"numLower",type:"tensor"},{start:1,name:"numUpper",type:"tensor"}]}]}),xm=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"}]}]}),wm=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"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{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"}]}]}),vm=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}]},{tfOpName:"TensorScatterUpdate",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"values",type:"tensor"}]}]}),km=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"}]}]}),Im=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}]}]}),Tm=Object.freeze({__proto__:null,json:[{tfOpName:"StaticRegexReplace",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"pattern",name:"pattern",type:"string"},{tfName:"rewrite",name:"rewrite",type:"string"},{tfName:"replace_global",name:"replaceGlobal",type:"bool"}]},{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"}]}]}),Sm=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:"EnsureShape",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 Em{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[].concat(...[um,lm,cm,pm,hm,dm,fm,mm,gm,ym,bm,_m,xm,wm,vm,km,Im,Tm,Sm].map((e=>e.json)));this.opMappers=e.reduce(((e,t)=>(e[t.tfOpName]=t,e)),{})}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]=rm(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]=rm(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]=rm(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=Zf(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=Am(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Am(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":a=Bm(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Bm(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":a=Rm(e.attr,n.tfName,n.defaultValue||0),void 0===a&&n.tfDeprecatedName&&(a=Rm(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":a=Lm(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Lm(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":a=Cm(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Cm(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":a=Wm(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Wm(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":a=Pm(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Pm(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":a=Um(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Um(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":a=$m(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=$m(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":a=Om(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Om(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":a=Fm(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Fm(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]=rm(e.name),n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Mm(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]=rm(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]=rm(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 Nm(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){const t=At().global;if(void 0!==t.atob)return t.atob(e);if(void 0!==co)return new co(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 Am(e,t,n,r=!1){const a=e[t];return null!=a?Nm(a.s,r):n}function Cm(e,t,n){const r=e[t];return r?r.b:n}function Rm(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 Mm(e){switch("string"==typeof e&&(e=Yf[e]),e){case Yf.DT_FLOAT:case Yf.DT_HALF:return"float32";case Yf.DT_INT32:case Yf.DT_INT64:case Yf.DT_INT8:case Yf.DT_UINT8:return"int32";case Yf.DT_BOOL:return"bool";case Yf.DT_DOUBLE:return"float32";case Yf.DT_STRING:return"string";case Yf.DT_COMPLEX64:case Yf.DT_COMPLEX128:return"complex64";default:return null}}function Fm(e,t,n){const r=e[t];return r&&r.func?r.func.name:n}function $m(e,t,n){const r=e[t];return r&&r.type?Mm(r.type):n}function Om(e,t,n){const r=e[t];return r&&r.list&&r.list.type?r.list.type.map((e=>Mm(e))):n}function Dm(e){if(!e.unknownRank)return null!=e.dim?e.dim.map((e=>"number"==typeof e.size?e.size:parseInt(e.size,10))):[]}function Pm(e,t,n){const r=e[t];return r&&r.shape?Dm(r.shape):n}function Lm(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 Bm(e,t,n,r=!1){const a=e[t];return a&&a.list&&a.list.s?a.list.s.map((e=>Nm(e,r))):n}function Um(e,t,n){const r=e[t];return r&&r.list&&r.list.shape?r.list.shape.map((e=>Dm(e))):n}function Wm(e,t,n){const r=e[t];return r&&r.list&&r.list.b?r.list.b:n}class zm{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 tm(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(null!=n.tensor)return tm(e,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return Rm(this.node.rawAttrs,e,t);if(null!=n.s)return Am(this.node.rawAttrs,e,t);if(null!=n.b)return Cm(this.node.rawAttrs,e,t);if(null!=n.shape)return Pm(this.node.rawAttrs,e,t);if(null!=n.type)return $m(this.node.rawAttrs,e,t);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return Lm(this.node.rawAttrs,e,t);if(null!=n.list.s)return Bm(this.node.rawAttrs,e,t);if(null!=n.list.shape)return Um(this.node.rawAttrs,e,t);if(null!=n.list.b)return Wm(this.node.rawAttrs,e,t);if(null!=n.list.type)return Om(this.node.rawAttrs,e,t)}return t}}var Vm=Object.freeze({__proto__:null,abs:Zu,acos:el,acosh:tl,add:Xu,addN:nl,all:rl,any:al,argMax:sl,argMin:ol,asin:il,asinh:ul,atan:ll,atan2:cl,atanh:pl,avgPool:Nl,avgPool3d:Al,basicLSTMCell:Ol,batchToSpaceND:Dl,batchNorm:Pl,batchNorm2d:Ll,batchNorm3d:Bl,batchNorm4d:Ul,bincount:Wl,bitwiseAnd:zl,broadcastArgs:Vl,broadcastTo:Hl,buffer:Gl,cast:gu,ceil:jl,clipByValue:ql,clone:Cl,complex:ni,concat:Rl,concat1d:Xl,concat2d:Yl,concat3d:Ql,concat4d:Jl,conv1d:ec,conv2d:Zl,conv2dTranspose:nc,conv3d:rc,conv3dTranspose:sc,cos:oc,cosh:ic,cumprod:uc,cumsum:lc,denseBincount:cc,depthToSpace:pc,depthwiseConv2d:hc,diag:dc,dilation2d:fc,div:Qu,divNoNan:bc,dot:_c,einsum:xc,elu:wc,ensureShape:vc,equal:mc,erf:kc,euclideanNorm:Wc,exp:zc,expandDims:Vc,expm1:Hc,eye:jc,fill:Kl,floor:Kc,floorDiv:Yu,gather:qc,greater:Xc,greaterEqual:Yc,imag:_u,isFinite:Qc,isInf:Jc,isNaN:Zc,leakyRelu:ep,less:tp,lessEqual:np,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 js.runKernel(Hn,{},r)},localResponseNormalization:rp,log:ap,log1p:sp,logSigmoid:up,logSoftmax:cp,logSumExp:pp,logicalAnd:hp,logicalNot:dp,logicalOr:fp,logicalXor:mp,lowerBound:function(e,t){return yp(e,t,"left")},matMul:yu,max:Mc,maxPool:bp,maxPool3d:_p,maxPoolWithArgmax:xp,maximum:wp,mean:vp,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=Jo(e,"x","meshgrid",e instanceof Es?e.dtype:"float32");if(void 0===t)return[r];let a=Jo(t,"y","meshgrid",t instanceof Es?t.dtype:"float32");const s=et(r.shape),o=et(a.shape);return"xy"===n?(r=El(r,[1,-1]),a=El(a,[-1,1]),[yu(Ip([o,1],r.dtype),r),yu(a,Ip([1,s],a.dtype))]):(r=El(r,[-1,1]),a=El(a,[1,-1]),[yu(r,Ip([1,o],r.dtype)),yu(Ip([s,1],a.dtype),a)])},min:Fc,minimum:Tp,mirrorPad:Sp,mod:Ep,moments:Np,mul:Ju,multiRNNCell:Ap,multinomial:Cp,neg:xu,notEqual:Rp,oneHot:bu,ones:Ip,onesLike:Mp,outerProduct:Fp,pad:$p,pad1d:Op,pad2d:Dp,pad3d:Pp,pad4d:Lp,pool:Up,pow:$c,prelu:Wp,print:zp,prod:Vp,raggedGather:Hp,raggedRange:Gp,raggedTensorToTensor:jp,rand:Kp,randomGamma:uh,randomNormal:lh,randomStandardNormal:ch,randomUniform:ph,randomUniformInt:hh,range:dh,real:wu,reciprocal:fh,relu:mh,relu6:gh,reshape:El,reverse:yh,reverse1d:bh,reverse2d:_h,reverse3d:xh,reverse4d:wh,round:vh,rsqrt:kh,scalar:Oc,selu:Ih,separableConv2d:Th,setdiff1dAsync:async function(e,t){const n=Jo(e,"x","setdiff1d"),r=Jo(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 Is([i],n.dtype),l=new Is([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:Ml,sign:Sh,sin:Eh,sinh:Nh,slice:Fl,slice1d:Ah,slice2d:Ch,slice3d:Rh,slice4d:Mh,softmax:Fh,softplus:ip,spaceToBatchND:Bp,fft:$h,ifft:Oh,irfft:Dh,rfft:Lh,split:Ph,sqrt:Dc,square:Pc,squaredDifference:Bh,squeeze:Uh,stack:Wh,step:zh,stridedSlice:Vh,sub:lp,sum:Lc,tan:Hh,tanh:$l,tensor:ai,tensor1d:Gh,tensor2d:jh,tensor3d:Su,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=Xo(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 ri(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=Xo(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 ri(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=Xo(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 ri(e,t=t||r,r,n)},tensorScatterUpdate:Kh,tile:Gc,topk:qh,truncatedNormal:Xh,unique:Yh,unsortedSegmentSum:Qh,unstack:Jh,upperBound:function(e,t){return yp(e,t,"right")},variable:function(e,t=!0,n,r){return js.makeVariable(e,t,n,r)},where:gc,whereAsync:ed,zeros:kp,zerosLike:yc,op:ti,OP_SCOPE_SUFFIX:ei,booleanMaskAsync:async function(e,t,n){const r=Jo(e,"tensor","boolMask"),a=Jo(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=El(r,l),p=El(a,[-1]),h=await ed(p),d=Uh(h,[1]),f=qc(c,d,s);return e!==r&&r.dispose(),t!==a&&a.dispose(),d.dispose(),c.dispose(),p.dispose(),h.dispose(),f},transpose:vu,norm:Uc,movingAverage:td,scatterND:nd,searchSorted:yp,sparseToDense:rd,gatherND:ad,dropout:sd,enclosingPowerOfTwo:od,cosineWindow:id,inTopKAsync:async function(e,t,n=1){const r=Jo(e,"predictions","inTopK"),a=Jo(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(),ai(c,a.shape,"bool")},image:cf,linalg:pf,losses:hf,spectral:uf,fused:bd,signal:lf,sparse:df,string:ff});function Hm(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 Gm(e){return"number"!=typeof e&&!e.some((e=>e<0))}function jm(e,t,n){let r=Km(e,n);const a=!Gm(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=Km(e.shape,r)})),!Gm(r))throw new Error(`Non-fully-defined elementShape: ${r}`);return r}function Km(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 qm{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=Oc(0),ci(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),Hm(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,ci(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 ai([],[0].concat(this.elementShape));const n=this.readMany(e);return Hm(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),Wh(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 ai([],[0].concat(this.elementShape));const t=[];for(let e=0;e<this.size();e++)t.push(e);const n=this.readMany(t);return Hm(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Rl(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,Jh(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=[];ui((()=>{t=El(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]=El(Fl(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 Xm{get id(){return this.idTensor.id}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}`);Hm(t,e.shape,"TensorList shape mismatch: "),ci(e)})),this.idTensor=Oc(0),this.maxNumElements=r,ci(this.idTensor)}copy(){return new Xm([...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.`);Hm(e,this.elementShape,"TensorList shape mismatch: ");const r=jm(this.elementShape,this.tensors,e);return ui((()=>{const e=this.tensors.map((e=>El(e,r)));return Wh(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=jm(this.elementShape,this.tensors,e),r=this.tensors.pop();return r.kept=!1,Hm(r.shape,e,"TensorList shape mismatch: "),El(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(Hm(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");ci(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 Xm([],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.`);Hm(this.tensors[e].shape,t,"TensorList shape mismatch: ");const r=jm(this.elementShape,this.tensors,t);return El(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.`);Hm(this.elementShape,t.shape,"TensorList shape mismatch: "),ci(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}`);Hm(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());const r=jm(this.elementShape,this.tensors,n);return 0===e.length?ai([],[0].concat(r)):ui((()=>{const t=e.map((e=>El(this.tensors[e],r)));return Wh(t,0)}))}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Hm(this.elementShape,t,"TensorList shape mismatch: ");const n=jm(this.elementShape,this.tensors,t);return 0===this.size()?ai([],[0].concat(n)):ui((()=>{const e=this.tensors.map((e=>El(e,n)));return Rl(e,0)}))}}function Ym(e,t,n){const[r,a]=em("fusedOps",e,t,n),s="biasadd"===r,o=!s,i="prelu"===a,u="fusedbatchnorm"===r,l=em("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=em("strides",e,t,n),p=om(e,t,n),h=em("dataFormat",e,t,n).toUpperCase(),d=em("dilations",e,t,n);let[f,m]=em("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:em("leakyreluAlpha",e,t,n)}}function Qm(e,t,n){return{boxes:em("boxes",e,t,n),scores:em("scores",e,t,n),maxOutputSize:em("maxOutputSize",e,t,n),iouThreshold:em("iouThreshold",e,t,n),scoreThreshold:em("scoreThreshold",e,t,n),softNmsSigma:em("softNmsSigma",e,t,n)}}class Jm{get id(){return this.handle.id}constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=Oc(0),this.tensorMap=new Map,ci(this.handle)}clearAndClose(){this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Oc(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(),ui((()=>{const e=Jh(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];ci(a),this.tensorMap.set(r,a)}return this.handle}))}async find(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return ui((()=>{const e=[];for(let r=0;r<n.length;r++){const a=n[r],s=this.findWithDefault(a,t);e.push(s)}return Wh(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 Zm(e,t,n,r,a=ui){const s=((e,t,n)=>{switch(e.category){case"arithmetic":return a((()=>((e,t,n,r=Vm)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[r.add(em("a",e,t,n),em("b",e,t,n))];case"AddN":return[r.addN(em("tensors",e,t,n))];case"FloorMod":case"Mod":return[r.mod(em("a",e,t,n),em("b",e,t,n))];case"Mul":return[r.mul(em("a",e,t,n),em("b",e,t,n))];case"RealDiv":case"Div":return[r.div(em("a",e,t,n),em("b",e,t,n))];case"DivNoNan":return[r.divNoNan(em("a",e,t,n),em("b",e,t,n))];case"FloorDiv":return[r.floorDiv(em("a",e,t,n),em("b",e,t,n))];case"Sub":return[r.sub(em("a",e,t,n),em("b",e,t,n))];case"Minimum":return[r.minimum(em("a",e,t,n),em("b",e,t,n))];case"Maximum":return[r.maximum(em("a",e,t,n),em("b",e,t,n))];case"Pow":return[r.pow(em("a",e,t,n),em("b",e,t,n))];case"SquaredDifference":return[r.squaredDifference(em("a",e,t,n),em("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=Vm)=>{switch(e.op){case"Abs":case"ComplexAbs":return[r.abs(em("x",e,t,n))];case"Acos":return[r.acos(em("x",e,t,n))];case"Acosh":return[r.acosh(em("x",e,t,n))];case"Asin":return[r.asin(em("x",e,t,n))];case"Asinh":return[r.asinh(em("x",e,t,n))];case"Atan":return[r.atan(em("x",e,t,n))];case"Atan2":return[r.atan2(em("x",e,t,n),em("y",e,t,n))];case"Atanh":return[r.atanh(em("x",e,t,n))];case"Ceil":return[r.ceil(em("x",e,t,n))];case"Complex":return[r.complex(em("real",e,t,n),em("imag",e,t,n))];case"Cos":return[r.cos(em("x",e,t,n))];case"Cosh":return[r.cosh(em("x",e,t,n))];case"Elu":return[r.elu(em("x",e,t,n))];case"Erf":return[r.erf(em("x",e,t,n))];case"Exp":return[r.exp(em("x",e,t,n))];case"Expm1":return[r.expm1(em("x",e,t,n))];case"Floor":return[r.floor(em("x",e,t,n))];case"Log":return[r.log(em("x",e,t,n))];case"Log1p":return[r.log1p(em("x",e,t,n))];case"Imag":return[r.imag(em("x",e,t,n))];case"Neg":return[r.neg(em("x",e,t,n))];case"Reciprocal":return[r.reciprocal(em("x",e,t,n))];case"Real":return[r.real(em("x",e,t,n))];case"Relu":return[r.relu(em("x",e,t,n))];case"Round":return[r.round(em("x",e,t,n))];case"Selu":return[r.selu(em("x",e,t,n))];case"Sigmoid":return[r.sigmoid(em("x",e,t,n))];case"Sin":return[r.sin(em("x",e,t,n))];case"Sign":return[r.sign(em("x",e,t,n))];case"Sinh":return[r.sinh(em("x",e,t,n))];case"Softplus":return[r.softplus(em("x",e,t,n))];case"Sqrt":return[r.sqrt(em("x",e,t,n))];case"Square":return[r.square(em("x",e,t,n))];case"Tanh":return[r.tanh(em("x",e,t,n))];case"Tan":return[r.tan(em("x",e,t,n))];case"ClipByValue":return[r.clipByValue(em("x",e,t,n),em("clipValueMin",e,t,n),em("clipValueMax",e,t,n))];case"Relu6":return[r.relu6(em("x",e,t,n))];case"Rsqrt":return[r.rsqrt(tm(e.inputNames[0],t,n))];case"LeakyRelu":return[r.leakyRelu(em("x",e,t,n),em("alpha",e,t,n))];case"Prelu":return[r.prelu(em("x",e,t,n),em("alpha",e,t,n))];case"IsNan":return[r.isNaN(tm(e.inputNames[0],t,n))];case"IsInf":return[r.isInf(tm(e.inputNames[0],t,n))];case"IsFinite":return[r.isFinite(tm(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=em("thenBranch",e,t,n),a=em("elseBranch",e,t,n),s=em("cond",e,t,n),o=em("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=em("body",e,t,n),a=em("cond",e,t,n),s=em("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[im(em("pred",e,t,n))];case"Switch":{const r=em("pred",e,t,n);let a=em("data",e,t,n);return a.kept||(a=im(a)),(await r.data())[0]?[void 0,a]:[a,void 0]}case"Merge":{const r=e.inputNames.find((e=>void 0!==tm(e,t,n)));return r?[im(tm(r,t,n))]:void 0}case"Enter":{const r=em("frameName",e,t,n),a=em("tensor",e,t,n);return n.enterFrame(r),[im(a)]}case"Exit":{const r=em("tensor",e,t,n);return n.exitFrame(),[im(r)]}case"NextIteration":{const r=em("tensor",e,t,n);return n.nextIteration(),[im(r)]}case"TensorArrayV3":{const r=em("size",e,t,n),a=em("dtype",e,t,n),s=em("elementShape",e,t,n),o=em("dynamicSize",e,t,n),i=em("clearAfterRead",e,t,n),u=em("identicalElementShapes",e,t,n),l=em("name",e,t,n),c=new qm(l,a,r,s,u,o,i);return n.addTensorArray(c),[c.idTensor,Oc(1)]}case"TensorArrayWriteV3":{const r=em("tensorArrayId",e,t,n),a=em("index",e,t,n),s=em("tensor",e,t,n),o=n.getTensorArray(r.id);return o.write(a,s),[o.idTensor]}case"TensorArrayReadV3":{const r=em("tensorArrayId",e,t,n),a=em("index",e,t,n);return[n.getTensorArray(r.id).read(a)]}case"TensorArrayGatherV3":{const r=em("tensorArrayId",e,t,n),a=em("indices",e,t,n),s=em("dtype",e,t,n);return[n.getTensorArray(r.id).gather(a,s)]}case"TensorArrayScatterV3":{const r=em("tensorArrayId",e,t,n),a=em("indices",e,t,n),s=em("tensor",e,t,n),o=n.getTensorArray(r.id);return o.scatter(a,s),[o.idTensor]}case"TensorArrayConcatV3":{const r=em("tensorArrayId",e,t,n),a=n.getTensorArray(r.id),s=em("dtype",e,t,n);return[a.concat(s)]}case"TensorArraySplitV3":{const r=em("tensorArrayId",e,t,n),a=em("tensor",e,t,n),s=em("lengths",e,t,n),o=n.getTensorArray(r.id);return o.split(s,a),[o.idTensor]}case"TensorArraySizeV3":{const r=em("tensorArrayId",e,t,n);return[Oc(n.getTensorArray(r.id).size(),"int32")]}case"TensorArrayCloseV3":{const r=em("tensorArrayId",e,t,n),a=n.getTensorArray(r.id);return a.clearAndClose(),[a.idTensor]}case"TensorListSetItem":{const r=em("tensorListId",e,t,n),a=em("index",e,t,n),s=em("tensor",e,t,n),o=n.getTensorList(r.id);return o.setItem(a,s),[o.idTensor]}case"TensorListGetItem":{const r=em("tensorListId",e,t,n),a=em("index",e,t,n),s=em("elementShape",e,t,n),o=em("elementDType",e,t,n);return[n.getTensorList(r.id).getItem(a,s,o)]}case"TensorListScatterV2":case"TensorListScatter":{const r=em("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 Xm([],n,e.dtype,r),o=Jh(e,0);return t.forEach(((e,t)=>{s.setItem(e,o[t])})),s}(em("tensor",e,t,n),r,em("elementShape",e,t,n),em("numElements",e,t,n));return n.addTensorList(a),[a.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const r=em("elementShape",e,t,n),a=em("elementDType",e,t,n);let s;s="TensorListReserve"===e.op?"numElements":"maxNumElements";const o=em(s,e,t,n),i=function(e,t,n,r){return new Xm([],e,t,r)}(r,a,0,"TensorListReserve"===e.op?-1:o);return n.addTensorList(i),[i.idTensor]}case"TensorListGather":{const r=em("tensorListId",e,t,n),a=em("indices",e,t,n),s=em("elementShape",e,t,n),o=em("elementDType",e,t,n);return[n.getTensorList(r.id).gather(a,o,s)]}case"TensorListStack":{const r=em("tensorListId",e,t,n),a=em("elementShape",e,t,n),s=em("elementDType",e,t,n),o=em("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}`);Hm(e.shape.slice(1),t,"TensorList shape mismatch: ");const a=Jh(e);return new Xm(a,t,r)}(em("tensor",e,t,n),em("elementShape",e,t,n),em("elementDType",e,t,n));return n.addTensorList(r),[r.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const r=em("tensorListId",e,t,n),a=n.getTensorList(r.id),s=em("dtype",e,t,n),o=em("elementShape",e,t,n);return[a.concat(s,o)]}case"TensorListPushBack":{const r=em("tensorListId",e,t,n),a=em("tensor",e,t,n),s=n.getTensorList(r.id);return s.pushBack(a),[s.idTensor]}case"TensorListPopBack":{const r=em("tensorListId",e,t,n),a=em("elementShape",e,t,n),s=em("elementDType",e,t,n);return[n.getTensorList(r.id).popBack(a,s)]}case"TensorListSplit":{const r=em("tensor",e,t,n),a=em("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=Km(e.shape.slice(1),n),o=0===r?0:e.size/r,i=ui((()=>{const n=[];e=El(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]=El(Fl(e,i,u),s)}return e.dispose(),n})),u=new Xm([],n,e.dtype,t.length);for(let e=0;e<i.length;e++)u.setItem(e,i[e]);return u}(r,em("lengths",e,t,n),a);return n.addTensorList(s),[s.idTensor]}case"TensorListLength":{const r=em("tensorListId",e,t,n);return[Oc(n.getTensorList(r.id).size(),"int32")]}case"TensorListResize":{const r=em("tensorListId",e,t,n),a=em("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=Vm)=>{switch(e.op){case"Conv1D":{const a=em("stride",e,t,n),s=em("pad",e,t,n),o=em("dataFormat",e,t,n).toUpperCase(),i=em("dilation",e,t,n);return[r.conv1d(em("x",e,t,n),em("filter",e,t,n),a,s,o,i)]}case"Conv2D":{const a=em("strides",e,t,n),s=om(e,t,n),o=em("dataFormat",e,t,n).toUpperCase(),i=em("dilations",e,t,n);return[r.conv2d(em("x",e,t,n),em("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}=Ym(e,t,n);return[r.fused.conv2d({x:em("x",e,t,n),filter:em("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}=Ym(e,t,n);return[r.fused.depthwiseConv2d({x:em("x",e,t,n),filter:em("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=em("outputShape",e,t,n),s=em("strides",e,t,n),o=om(e,t,n);return[r.conv2dTranspose(em("x",e,t,n),em("filter",e,t,n),a,[s[1],s[2]],o)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const a=em("strides",e,t,n),s=om(e,t,n),o=em("dilations",e,t,n),i=em("dataFormat",e,t,n).toUpperCase();return[r.depthwiseConv2d(em("input",e,t,n),em("filter",e,t,n),[a[1],a[2]],s,i,[o[1],o[2]])]}case"Conv3D":{const a=em("strides",e,t,n),s=em("pad",e,t,n),o=em("dataFormat",e,t,n).toUpperCase(),i=em("dilations",e,t,n);return[r.conv3d(em("x",e,t,n),em("filter",e,t,n),[a[1],a[2],a[3]],s,o,[i[1],i[2],i[3]])]}case"AvgPool":{const a=em("strides",e,t,n),s=em("pad",e,t,n),o=em("kernelSize",e,t,n);return[r.avgPool(em("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s)]}case"MaxPool":{const a=em("strides",e,t,n),s=em("pad",e,t,n),o=em("kernelSize",e,t,n);return[r.maxPool(em("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s)]}case"MaxPoolWithArgmax":{const a=em("strides",e,t,n),s=em("pad",e,t,n),o=em("kernelSize",e,t,n),i=em("includeBatchInIndex",e,t,n),{result:u,indexes:l}=r.maxPoolWithArgmax(em("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s,i);return[u,l]}case"AvgPool3D":{const a=em("strides",e,t,n),s=em("pad",e,t,n),o=em("kernelSize",e,t,n);return[r.avgPool3d(em("x",e,t,n),[o[1],o[2],o[3]],[a[1],a[2],a[3]],s)]}case"MaxPool3D":{const a=em("strides",e,t,n),s=em("pad",e,t,n),o=em("kernelSize",e,t,n);return[r.maxPool3d(em("x",e,t,n),[o[1],o[2],o[3]],[a[1],a[2],a[3]],s)]}case"Dilation2D":{const a=em("strides",e,t,n),s=em("pad",e,t,n),o=em("dilations",e,t,n),i=a[1],u=a[2],l=o[1],c=o[2];return[r.dilation2d(em("x",e,t,n),em("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=Vm)=>{switch(e.op){case"Fill":{const a=em("shape",e,t,n),s=em("dtype",e,t,n),o=em("value",e,t,n);return[r.fill(a,o,s)]}case"LinSpace":{const a=em("start",e,t,n),s=em("stop",e,t,n),o=em("num",e,t,n);return[r.linspace(a,s,o)]}case"Multinomial":{const a=em("logits",e,t,n),s=em("numSamples",e,t,n),o=em("seed",e,t,n);return[r.multinomial(a,s,o)]}case"OneHot":{const a=em("indices",e,t,n),s=em("depth",e,t,n),o=em("onValue",e,t,n),i=em("offValue",e,t,n),u=em("dtype",e,t,n);return[r.oneHot(a,s,o,i,u)]}case"Ones":return[r.ones(em("shape",e,t,n),em("dtype",e,t,n))];case"OnesLike":return[r.onesLike(em("x",e,t,n))];case"RandomStandardNormal":return[r.randomStandardNormal(em("shape",e,t,n),em("dtype",e,t,n),em("seed",e,t,n))];case"RandomUniform":return[r.randomUniform(em("shape",e,t,n),em("minval",e,t,n),em("maxval",e,t,n),em("dtype",e,t,n))];case"RandomUniformInt":return[r.randomUniformInt(em("shape",e,t,n),em("minval",e,t,n),em("maxval",e,t,n),em("seed",e,t,n))];case"Range":{const a=em("start",e,t,n),s=em("stop",e,t,n),o=em("step",e,t,n);return[r.range(a,s,o,em("dtype",e,t,n))]}case"TruncatedNormal":{const a=em("shape",e,t,n),s=em("mean",e,t,n),o=em("stdDev",e,t,n),i=em("seed",e,t,n);return[r.truncatedNormal(a,s,o,em("dtype",e,t,n),i)]}case"Zeros":return[r.zeros(em("shape",e,t,n),em("dtype",e,t,n))];case"ZerosLike":return[r.zerosLike(em("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=Vm)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u,softNmsSigma:l}=Qm(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}=Qm(e,t,n),l=em("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}=Qm(e,t,n);return[await a.image.nonMaxSuppressionAsync(r,s,o,i,u)]}case"Where":{const r=a.cast(em("condition",e,t,n),"bool"),s=[await a.whereAsync(r)];return r.dispose(),s}case"ListDiff":return a.setdiff1dAsync(em("x",e,t,n),em("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=Vm)=>{switch(e.op){case"LowerBound":{const a=em("sortedSequence",e,t,n),s=em("values",e,t,n);return[r.lowerBound(a,s)]}case"TopKV2":{const a=em("x",e,t,n),s=em("k",e,t,n),o=em("sorted",e,t,n),i=r.topk(a,s,o);return[i.values,i.indices]}case"UpperBound":{const a=em("sortedSequence",e,t,n),s=em("values",e,t,n);return[r.upperBound(a,s)]}case"Unique":{const a=em("x",e,t,n),s=r.unique(a);return[s.values,s.indices]}case"UniqueV2":{const a=em("x",e,t,n),s=em("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=Vm)=>{switch(e.op){case"ResizeBilinear":{const a=em("images",e,t,n),s=em("size",e,t,n),o=em("alignCorners",e,t,n),i=em("halfPixelCenters",e,t,n);return[r.image.resizeBilinear(a,[s[0],s[1]],o,i)]}case"ResizeNearestNeighbor":{const a=em("images",e,t,n),s=em("size",e,t,n),o=em("alignCorners",e,t,n),i=em("halfPixelCenters",e,t,n);return[r.image.resizeNearestNeighbor(a,[s[0],s[1]],o,i)]}case"CropAndResize":{const a=em("image",e,t,n),s=em("boxes",e,t,n),o=em("boxInd",e,t,n),i=em("cropSize",e,t,n),u=em("method",e,t,n),l=em("extrapolationValue",e,t,n);return[r.image.cropAndResize(a,s,o,i,u,l)]}case"ImageProjectiveTransformV3":{const a=em("images",e,t,n),s=em("transforms",e,t,n),o=em("outputShape",e,t,n),i=em("fillValue",e,t,n),u=em("interpolation",e,t,n),l=em("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=Vm)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const a=em("default",e,t,n);return[tm(e.name,t,n)||a];case"Placeholder":return[tm(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":case"Snapshot":return[im(em("x",e,t,n))];case"IdentityN":return em("x",e,t,n).map((e=>im(e)));case"Shape":return[r.tensor1d(em("x",e,t,n).shape,"int32")];case"ShapeN":return em("x",e,t,n).map((e=>r.tensor1d(e.shape)));case"Size":return[r.scalar(em("x",e,t,n).size,"int32")];case"Rank":return[r.scalar(em("x",e,t,n).rank,"int32")];case"NoOp":return[r.scalar(1)];case"Print":const s=em("x",e,t,n),o=em("data",e,t,n),i=em("message",e,t,n),u=em("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=Vm)=>{switch(e.op){case"Equal":return[r.equal(em("a",e,t,n),em("b",e,t,n))];case"NotEqual":return[r.notEqual(em("a",e,t,n),em("b",e,t,n))];case"Greater":return[r.greater(em("a",e,t,n),em("b",e,t,n))];case"GreaterEqual":return[r.greaterEqual(em("a",e,t,n),em("b",e,t,n))];case"Less":return[r.less(em("a",e,t,n),em("b",e,t,n))];case"LessEqual":return[r.lessEqual(em("a",e,t,n),em("b",e,t,n))];case"LogicalAnd":return[r.logicalAnd(em("a",e,t,n),em("b",e,t,n))];case"LogicalNot":return[r.logicalNot(em("a",e,t,n))];case"LogicalOr":return[r.logicalOr(em("a",e,t,n),em("b",e,t,n))];case"Select":case"SelectV2":return[r.where(em("condition",e,t,n),em("a",e,t,n),em("b",e,t,n))];case"BitwiseAnd":return[r.bitwiseAnd(em("a",e,t,n),em("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=Vm)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[r.matMul(em("a",e,t,n),em("b",e,t,n),em("transposeA",e,t,n),em("transposeB",e,t,n))];case"Einsum":return[r.einsum(em("equation",e,t,n),...em("tensors",e,t,n))];case"Transpose":return[r.transpose(em("x",e,t,n),em("perm",e,t,n))];case"_FusedMatMul":const[a,s]=em("fusedOps",e,t,n),o="biasadd"===a,i="prelu"===s,u=em("numArgs",e,t,n),l=em("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]=em("args",e,t,n);return[r.fused.matMul({a:em("a",e,t,n),b:em("b",e,t,n),transposeA:em("transposeA",e,t,n),transposeB:em("transposeB",e,t,n),bias:c,activation:s,preluActivationWeights:p,leakyreluAlpha:l})];case"MatrixBandPart":return[r.linalg.bandPart(em("a",e,t,n),em("numLower",e,t,n),em("numUpper",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"normalization":return a((()=>((e,t,n,r=Vm)=>{switch(e.op){case"EuclideanNorm":return[r.euclideanNorm(em("x",e,t,n),em("axis",e,t,n),em("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[r.batchNorm(em("x",e,t,n),em("mean",e,t,n),em("variance",e,t,n),em("offset",e,t,n),em("scale",e,t,n),em("epsilon",e,t,n))];case"LRN":return[r.localResponseNormalization(em("x",e,t,n),em("radius",e,t,n),em("bias",e,t,n),em("alpha",e,t,n),em("beta",e,t,n))];case"Softmax":return[r.softmax(em("x",e,t,n))];case"LogSoftmax":return[r.logSoftmax(em("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"ragged":return a((()=>((e,t,n,r=Vm)=>{switch(e.op){case"RaggedGather":{const{outputNestedSplits:a,outputDenseValues:s}=r.raggedGather(em("paramsNestedSplits",e,t,n),em("paramsDenseValues",e,t,n),em("indices",e,t,n),em("outputRaggedRank",e,t,n));return a.concat(s)}case"RaggedRange":{const{rtNestedSplits:a,rtDenseValues:s}=r.raggedRange(em("starts",e,t,n),em("limits",e,t,n),em("splits",e,t,n));return[a,s]}case"RaggedTensorToTensor":return[r.raggedTensorToTensor(em("shape",e,t,n),em("values",e,t,n),em("defaultValue",e,t,n),em("rowPartitionTensors",e,t,n),em("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=Vm)=>{switch(e.op){case"Max":{const a=em("axis",e,t,n),s=em("keepDims",e,t,n);return[r.max(em("x",e,t,n),a,s)]}case"Mean":{const a=em("axis",e,t,n),s=em("keepDims",e,t,n);return[r.mean(em("x",e,t,n),a,s)]}case"Min":{const a=em("axis",e,t,n),s=em("keepDims",e,t,n);return[r.min(em("x",e,t,n),a,s)]}case"Sum":{const a=em("axis",e,t,n),s=em("keepDims",e,t,n);return[r.sum(em("x",e,t,n),a,s)]}case"All":{const a=em("axis",e,t,n),s=em("keepDims",e,t,n);return[r.all(em("x",e,t,n),a,s)]}case"Any":{const a=em("axis",e,t,n),s=em("keepDims",e,t,n);return[r.any(em("x",e,t,n),a,s)]}case"ArgMax":{const a=em("axis",e,t,n);return[r.argMax(em("x",e,t,n),a)]}case"ArgMin":{const a=em("axis",e,t,n);return[r.argMin(em("x",e,t,n),a)]}case"Prod":{const a=em("axis",e,t,n),s=em("keepDims",e,t,n);return[r.prod(em("x",e,t,n),a,s)]}case"Cumprod":{const a=em("axis",e,t,n),s=em("exclusive",e,t,n),o=em("reverse",e,t,n);return[r.cumprod(em("x",e,t,n),a,s,o)]}case"Cumsum":{const a=em("axis",e,t,n),s=em("exclusive",e,t,n),o=em("reverse",e,t,n);return[r.cumsum(em("x",e,t,n),a,s,o)]}case"Bincount":const a=em("x",e,t,n),s=em("weights",e,t,n),o=em("size",e,t,n);return[r.bincount(a,s,o)];case"DenseBincount":{const a=em("x",e,t,n),s=em("weights",e,t,n),o=em("size",e,t,n),i=em("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=Vm)=>{switch(e.op){case"ConcatV2":case"Concat":{const a=em("n",e,t,n),s=em("axis",e,t,n);let o=em("tensors",e,t,n);return o=o.slice(0,a),[r.concat(o,s)]}case"Gather":{const a=em("x",e,t,n),s=em("indices",e,t,n);return[r.gather(a,r.cast(s,"int32"),0)]}case"GatherV2":{const a=em("axis",e,t,n),s=em("batchDims",e,t,n),o=em("x",e,t,n),i=em("indices",e,t,n);return[r.gather(o,r.cast(i,"int32"),a,s)]}case"Reverse":{const a=em("dims",e,t,n),s=[];for(let e=0;e<a.length;e++)a[e]&&s.push(e);const o=em("x",e,t,n);return[r.reverse(o,s)]}case"ReverseV2":{const a=em("axis",e,t,n),s=em("x",e,t,n);return[r.reverse(s,a)]}case"Slice":{const a=em("begin",e,t,n),s=em("size",e,t,n);return[r.slice(em("x",e,t,n),a,s)]}case"StridedSlice":{const a=em("begin",e,t,n),s=em("end",e,t,n),o=em("strides",e,t,n),i=em("beginMask",e,t,n),u=em("endMask",e,t,n),l=em("ellipsisMask",e,t,n),c=em("newAxisMask",e,t,n),p=em("shrinkAxisMask",e,t,n),h=em("x",e,t,n);return[r.stridedSlice(h,a,s,o,i,u,l,c,p)]}case"Pack":return ui((()=>{const a=em("axis",e,t,n),s=em("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=em("axis",e,t,n),s=em("tensor",e,t,n);return r.unstack(s,a)}case"Tile":{const a=em("reps",e,t,n);return[r.tile(em("x",e,t,n),a)]}case"Split":case"SplitV":{const a=em("axis",e,t,n),s=em("numOrSizeSplits",e,t,n),o=em("x",e,t,n);return r.split(o,s,a)}case"ScatterNd":{const a=em("indices",e,t,n),s=em("values",e,t,n),o=em("shape",e,t,n);return[r.scatterND(a,s,o)]}case"GatherNd":{const a=em("x",e,t,n),s=em("indices",e,t,n);return[r.gatherND(a,s)]}case"SparseToDense":{const a=em("sparseIndices",e,t,n),s=em("outputShape",e,t,n),o=em("sparseValues",e,t,n),i=em("defaultValue",e,t,n);return[r.sparseToDense(a,o,s,o.dtype===i.dtype?i:r.cast(i,o.dtype))]}case"TensorScatterUpdate":{const a=em("indices",e,t,n),s=em("values",e,t,n),o=em("tensor",e,t,n);return[r.tensorScatterUpdate(o,a,s)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"sparse":return a((()=>((e,t,n,r=Vm)=>{switch(e.op){case"SparseFillEmptyRows":{const{outputIndices:a,outputValues:s,emptyRowIndicator:o,reverseIndexMap:i}=r.sparse.sparseFillEmptyRows(em("indices",e,t,n),em("values",e,t,n),em("denseShape",e,t,n),em("defaultValue",e,t,n));return[a,s,o,i]}case"SparseReshape":{const{outputIndices:a,outputShape:s}=r.sparse.sparseReshape(em("inputIndices",e,t,n),em("inputShape",e,t,n),em("newShape",e,t,n));return[a,s]}case"SparseSegmentMean":return[r.sparse.sparseSegmentMean(em("data",e,t,n),em("indices",e,t,n),em("segmentIds",e,t,n))];case"SparseSegmentSum":return[r.sparse.sparseSegmentSum(em("data",e,t,n),em("indices",e,t,n),em("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=Vm)=>{switch(e.op){case"FFT":return[r.fft(em("x",e,t,n))];case"IFFT":return[r.ifft(em("x",e,t,n))];case"RFFT":return[r.rfft(em("x",e,t,n))];case"IRFFT":return[r.irfft(em("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=Vm)=>{switch(e.op){case"StaticRegexReplace":return[r.string.staticRegexReplace(em("input",e,t,n),em("pattern",e,t,n),em("rewrite",e,t,n),em("replaceGlobal",e,t,n))];case"StringNGrams":{const{nGrams:a,nGramsSplits:s}=r.string.stringNGrams(em("data",e,t,n),em("dataSplits",e,t,n),em("separator",e,t,n),em("nGramWidths",e,t,n),em("leftPad",e,t,n),em("rightPad",e,t,n),em("padWidth",e,t,n),em("preserveShortSequences",e,t,n));return[a,s]}case"StringSplit":{const{indices:a,values:s,shape:o}=r.string.stringSplit(em("input",e,t,n),em("delimiter",e,t,n),em("skipEmpty",e,t,n));return[a,s,o]}case"StringToHashBucketFast":return[r.string.stringToHashBucketFast(em("input",e,t,n),em("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=Vm)=>{switch(e.op){case"Cast":return[r.cast(em("x",e,t,n),em("dtype",e,t,n))];case"ExpandDims":{const a=em("axis",e,t,n);return[r.expandDims(em("x",e,t,n),a)]}case"Squeeze":{const a=em("axis",e,t,n);return[r.squeeze(em("x",e,t,n),a)]}case"Reshape":return[r.reshape(em("x",e,t,n),em("shape",e,t,n))];case"EnsureShape":return[r.ensureShape(em("x",e,t,n),em("shape",e,t,n))];case"MirrorPad":return[r.mirrorPad(em("x",e,t,n),em("padding",e,t,n),em("mode",e,t,n))];case"PadV2":case"Pad":return[r.pad(em("x",e,t,n),em("padding",e,t,n),em("constantValue",e,t,n))];case"SpaceToBatchND":{const a=em("blockShape",e,t,n),s=em("paddings",e,t,n);return[r.spaceToBatchND(em("x",e,t,n),a,s)]}case"BatchToSpaceND":{const a=em("blockShape",e,t,n),s=em("crops",e,t,n);return[r.batchToSpaceND(em("x",e,t,n),a,s)]}case"DepthToSpace":{const a=em("blockSize",e,t,n),s=em("dataFormat",e,t,n).toUpperCase();return[r.depthToSpace(em("x",e,t,n),a,s)]}case"BroadcastTo":return[r.broadcastTo(em("x",e,t,n),em("shape",e,t,n))];case"BroadcastArgs":return[r.broadcastArgs(em("s0",e,t,n),em("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=em("keyDType",e,t,n),s=em("valueDType",e,t,n),o=new Jm(a,s);return r.addHashTable(e.name,o),[o.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{const a=em("tableHandle",e,t,n,r),s=em("keys",e,t,n),o=em("values",e,t,n),i=r.getHashTableById(a.id);return[await i.import(s,o)]}case"LookupTableFind":case"LookupTableFindV2":{const a=em("tableHandle",e,t,n,r),s=em("keys",e,t,n),o=em("defaultValue",e,t,n),i=r.getHashTableById(a.id);return[await i.find(s,o)]}case"LookupTableSize":case"LookupTableSizeV2":{const a=em("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=Zf(e.op);if(s&&s.customExecutor)return s.customExecutor(new zm(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 Tt(s)?s.then((e=>[].concat(e))):[].concat(s)}class eg{constructor(e={},t={},n={},r={},a){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=r,this.parseNodeNameCache=a,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 tg(e,t,n,r){const a=new Set,s=[];let o=null,i=null;const u=new Set,l=new Set(Object.keys(e).map((e=>sm(e)[0])));r=r||[];const c=new Set(r.map((e=>sm(e.name)[0]))),p=[...t];for(;p.length>0;){const e=p.pop();(og(e)||ig(e)||ug(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]&&(l.has(e.name)||c.has(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}}class ng extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}}const rg=new Set(["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"]),ag=new Set(["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"]),sg=new Set(["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"]);function og(e){return rg.has(e.op)}function ig(e){return ag.has(e.op)}function ug(e){return sg.has(e.op)}class lg{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)),{})}constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this.parseNodeNameCache=new Map,this._weightMap={},this.SEPARATOR=",",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 lg(e.functions[t],this)}))}getCompilationKey(e,t){const n=e.map((e=>e.name)).sort(),r=t.map((e=>e.name)).sort();return n.join(this.SEPARATOR)+"--"+r.join(this.SEPARATOR)}compile(e,t){const n=tg(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}]`)}const o=function(e,t){const{usedNodes:n,inputs:r}=t,a=Object.keys(r).map((e=>sm(e)[0])).map((t=>e.nodes[t])),s=e.initNodes||[],o=e=>n.has("string"==typeof e?e:e.name);function i(e){return[...new Map(e.map((e=>[e.name,e]))).values()]}const u=i([...a,...e.weights,...s]).filter(o),l=i([...u,...Object.values(e.nodes)]).filter(o),c=new Map(l.map((e=>[e.name,e]))),p={};for(const e of l){p[e.name]=p[e.name]||0;for(const t of e.children)o(t)||(p[t.name]=Number.POSITIVE_INFINITY),p[t.name]=(p[t.name]||0)+1}const h=Object.entries(p).filter((([,e])=>0===e)).map((([e])=>e)),d=[...h];for(;h.length>0;){const e=h.pop(),t=c.get(e);for(const e of t.children.filter(o))0==--p[e.name]&&(d.push(e.name),h.push(e.name))}const f=function(e,t){const n=new Map(e.map((e=>[e.name,e]))),r=t.map((e=>e.name)),a=new Set(r);for(;r.length>0;){const e=r.pop(),t=n.get(e);for(const e of t.children)n.has(e.name)&&!a.has(e.name)&&(a.add(e.name),r.push(e.name))}return e.filter((e=>a.has(e.name)))}(d.map((e=>c.get(e))),u);return function(e,t){const n=new Map(e.map(((e,t)=>[e.name,t]))),r=new Set(t.map((e=>e.name))),a=e=>r.has("string"==typeof e?e:e.name),s=new Set(e.map((e=>e.name))),o=e=>s.has("string"==typeof e?e:e.name);for(const t of e){for(const e of t.children.filter(o)){if(!n.has(e.name))throw new ng(`Child ${e.name} of node ${t.name} is unreachable.`);if(n.get(t.name)>n.get(e.name))throw new ng(`Node ${t.name} is scheduled to run after its child ${e.name}.`)}if(!a(t))for(const e of t.inputs){if(!n.has(e.name))throw new ng(`Input ${e.name} of node ${t.name} is unreachable.`);if(n.get(e.name)>n.get(t.name))throw new ng(`Node ${t.name} is scheduled to run before its input ${e.name}.`)}}}(f,u),f}(this.graph,n),i=function(e){const t=new Map(e.map(((e,t)=>[e.name,t]))),n=Number.MAX_SAFE_INTEGER,r=e.map(((e,t)=>og(e)?n:t)),a=e=>{const n=r[t.get(e.name)];return null==n?-1:n},s=e.map(((e,t)=>e.children.map(a).reduce(((e,t)=>Math.max(e,t)),r[t]))),o=new Map;for(let t=0;t<e.length;++t){const r=s[t];if(r===n)continue;const a=e[t],i=e[r];o.has(i.name)||o.set(i.name,[]),o.get(i.name).push(a)}return o}(o);return{orderedNodes:o,nodeLiveUntilMap:i}}cloneAndKeepTensor(e){if(null==e)return null;const t=e.clone();return ci(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[sm(e)[0]])),a=t.map((e=>sm(e)[0])),s=new Set(a);let o=a.map((e=>this.graph.nodes[e]));0===o.length&&(o=this._outputs);const i=this.getCompilationKey(r,o);let u=this.compiledMap.get(i);null==u&&(u=this.compile(e,o),this.compiledMap.set(i,u));try{this.keepIntermediateTensors=At().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const l={},c={};return ui((()=>{const n=new eg(this.weightMap,l,c,this.functionExecutorMap,this.parseNodeNameCache),r=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(e).forEach((t=>{const[a,s]=sm(t,n),o=[];o[s]=e[t],r[a]=o,this.keepIntermediateTensors&&(this.clonedTensorsMap[a]=this.cloneTensorList(o))}));const a=this.getFrozenTensorIds(r),{orderedNodes:o,nodeLiveUntilMap:i}=u;for(const e of o){if(r[e.name])continue;const t=Zm(e,r,n,this._resourceManager);if(Tt(t))throw new Error(`The execution of the op '${e.op}' returned a promise. Please use model.executeAsync() instead.`);r[e.name]=t,this.keepIntermediateTensors&&(this.clonedTensorsMap[e.name]=this.cloneTensorList(t)),this.checkTensorForDisposalWithNodeLiveUntilInfo(e,r,n,a,s,i.get(e.name))}return null==this.parent&&n.dispose(a),t.map((e=>tm(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){if(!og(t)&&!s.has(e)){for(const r of n[e])null!=r&&(o[r.id]=(o[r.id]||0)+t.children.length);for(const e of t.inputs){if(og(e))continue;const t=nm(e.name,n,r);if(null!=t)for(const e of t){if(!e||e.kept||a.has(e.id))continue;const t=o[e.id];1===t?(e.dispose(),delete o[e.id]):null!=t&&o[e.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(e,t,n,r,a,s){function o(e){return og(e)||a.has(e.name)}if(!og(e)&&null!=s)for(const e of s){if(o(e))continue;const a=nm(e.name,t,n);for(const e of a)!e||e.kept||r.has(e.id)||e.dispose()}}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=At().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const s=new eg(this.weightMap,r,a,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));const o=await this.executeWithControlFlow(e,s,t,n),i=t.map((e=>tm(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[sm(e)[0]])),o=n.map((e=>sm(e)[0])),i=new Set(o);let u=o.map((e=>this.graph.nodes[e]));0===u.length&&(u=this._outputs);const{usedNodes:l,missingInputs:c,dynamicNode:p,syncInputs:h}=tg(e,u,this.weightMap,this._initNodes),d=[...s,...this.graph.weights,...this._initNodes||[]].map((e=>({node:e,contexts:t.currentContext}))),f=Object.assign({},this.weightMap);Object.keys(e).forEach((t=>{const[n,r]=sm(t),a=[];a[r]=e[t],f[n]=a}));const m={},g=this.getFrozenTensorIds(f),y={};for(;d.length>0;){const e=this.processStack(s,d,t,f,y,g,i,m,l);await Promise.all(e)}null!=p||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 b=u.filter((e=>!og(e)&&!tm(e.name,f,t))).map((e=>e.name));if(b.length>0){let e="";throw null!=p&&(e=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${h}]`),new Error(`Cannot compute the outputs [${b}] from the provided inputs [${a}]. Consider providing the following inputs: [${c}]. ${e}`)}return f}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&&em("isConstant",e.node,r,n)&&([c]=rm(e.node.name,n)),null==r[e.node.name]){const p=Zm(e.node,r,n,this._resourceManager);c||([c]=rm(e.node.name,n));const h=n.currentContext;Tt(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]=rm(e.name,n);!a[o]&&s.has(e.name)&&("Merge"===e.op?e.inputNames.some((e=>!!tm(e,r,n)))&&(a[o]=!0,t.push({contexts:n.currentContext,node:e})):e.inputNames.every((e=>!!tm(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]=sm(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]=sm(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]=sm(e);if(!this.graph.nodes[t])throw new Error(`The output '${e}' is not found in the graph`)}))}}class cg{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 pg{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}constructor(e,t={},n=mu){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=n,null==t&&(this.loadOptions={}),this.resourceManager=new cg}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 Tt(e)?e.then((e=>null==e.getWeightStream?this.loadSync(e):this.loadStreaming(e))):this.loadSync(e)}loadSync(e){const t=this.io.decodeWeights(e.weightData,e.weightSpecs);return this.loadWithWeightMap(e,t)}async loadStreaming(e){if(null==e.getWeightStream)throw new Error("Model artifacts missing streamWeights function");const t=await _i(e.getWeightStream(),e.weightSpecs);return this.loadWithWeightMap(e,t)}loadWithWeightMap(e,t){this.artifacts=e;const n=this.artifacts.modelTopology;let r=this.artifacts.signature;if(null!=this.artifacts.userDefinedMetadata){const e=this.artifacts.userDefinedMetadata;null!=e.signature&&(r=e.signature),null!=e.structuredOutputKeys&&(this.structuredOutputKeys=e.structuredOutputKeys)}if(this.signature=r,this.version=`${n.versions.producer}.${n.versions.minConsumer}`,this.executor=new lg(Em.Instance.transformGraph(n,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(t),this.executor.resourceManager=this.resourceManager,null!=e.modelInitializer&&null!=e.modelInitializer.node){const t=Em.Instance.transformGraph(e.modelInitializer);this.initializer=new lg(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 Es?[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 Es||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&&li(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}}async function hg(e,t={},n=mu){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 pg(e,t,n);return await r.load(),r}function dg(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 fg=Zh;class mg extends je{nextDataId(){return mg.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new Ge(this,ii())}write(e,t,n){this.firstUse&&(this.firstUse=!1,At().get("IS_NODE")&&ga("\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=>hs(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?Cf(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=>ds(e)));return Gl(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Gl(e.shape,e.dtype,t)}makeOutput(e,t,n){return ii().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=ps();return e(),{kernelMs:ps()-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){dg([e],"where");const t=this.readSync(e.dataId);return fg(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}function gg(e){return(t,n,r,a,s)=>{const o=Tu(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=ku(t,o),m=ku(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=It(t,i,u),s=n.slice(-c);f.forEach((e=>s[e]=0));const o=kt(s,c,h),g=n.slice(-p);m.forEach((e=>g[e]=0));const y=kt(g,p,d);l[t]=e(r[o],a[y])}return[l,o]}}function yg(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 bg(e,t,n="float32"){if("complex64"===n)return yg({inputs:{real:bg(e,t,"float32"),imag:bg(e,t,"float32")},backend:e});const r=wt(et(t),n);return e.makeTensorInfo(t,n,r)}function _g(e){const{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}mg.nextDataId=0;const xg={kernelName:Pn,backendName:"cpu",kernelFunc:_g};function wg(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 vg(e,t,n,r){if("int32"===r)return[t,"int32",Int32Array.from(e)];if("bool"===r){const r=cs([0],n),[a,s]=gg(((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 kg(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dtype:s}=r;if("complex64"===s){if("complex64"===a.dtype)return _g({inputs:{x:a},backend:n});const e=bg(n,a.shape,a.dtype),t=kg({inputs:{x:a},backend:n,attrs:{dtype:"float32"}}),r=yg({inputs:{real:t,imag:e},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),r}if("complex64"===a.dtype){const e=wg({inputs:{input:a},backend:n}),t=kg({inputs:{x:e},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(e),t}if(!pt(a.dtype,s)){const e=_g({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]=vg(o,a.shape,a.dtype,s);return n.makeTensorInfo(i,u,l)}const Ig={kernelName:en,backendName:"cpu",kernelFunc:kg};function Tg(e,t,n,r){return null==n?({inputs:n,backend:a})=>{const{a:s,b:o}=n,i=a;dg([s,o],e);const u=i.data.get(s.dataId).values,l=i.data.get(o.dataId).values,c="string"===s.dtype?Gf(u):u,p="string"===s.dtype?Gf(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=kg({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=kg({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),w=yg({inputs:{real:_,imag:x},backend:i});return i.disposeIntermediateTensorInfo(e),i.disposeIntermediateTensorInfo(c),i.disposeIntermediateTensorInfo(_),i.disposeIntermediateTensorInfo(x),w}{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 Sg(e){return(t,n,r,a,s,o)=>{const i=Tu(t,n),u=et(i),l=i.length,c=yt(i),p=lt("float32",u),h=lt("float32",u),d=ku(t,i),f=ku(n,i),m=Cf(r,a),g=Cf(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=It(t,l,c),r=n.slice(-y);d.forEach((e=>r[e]=0));const a=kt(r,y,b),s=n.slice(-_);f.forEach((e=>s[e]=0));const o=kt(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 Eg=gg(((e,t)=>e+t)),Ng=Sg(((e,t,n,r)=>({real:e+n,imag:t+r}))),Ag=Tg(Dt,Eg,Ng),Cg={kernelName:Dt,backendName:"cpu",kernelFunc:Ag},Rg=gg(((e,t)=>e&t));function Mg(e){return(t,n,r)=>{const a=ct(n,t.length);for(let n=0;n<t.length;++n)a[n]=e(t[n],r);return a}}function Fg(e,t,n){return $g(e,Mg(t),n)}function $g(e,t,n){return({inputs:r,attrs:a,backend:s})=>{const{x:o}=r;dg(o,e);const i=s,u=i.data.get(o.dataId).values;let l;if("string"===o.dtype){if(!Array.isArray(u))throw new Error("String tensor's value was not an instance of Array");l=Gf(u)}else l=u;const c=n||o.dtype,p=t(l,c,a);return i.makeTensorInfo(o.shape,c,p)}}const Og=Mg((e=>Math.ceil(e)));function Dg(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?Gf(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 Pg=gg(((e,t)=>e===t?1:0)),Lg=Mg((e=>Math.exp(e))),Bg=$g(Tn,Lg,"float32"),Ug=Mg((e=>Math.expm1(e))),Wg=Mg((e=>Math.floor(e))),zg=gg(((e,t)=>Math.floor(e/t))),Vg=gg(((e,t)=>e>t?1:0)),Hg=gg(((e,t)=>e>=t?1:0)),Gg=gg(((e,t)=>e<t?1:0)),jg=gg(((e,t)=>e<=t?1:0)),Kg=Mg((e=>Math.log(e)));function qg(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 Xg=gg(((e,t)=>Math.max(e,t))),Yg=gg(((e,t)=>Math.min(e,t))),Qg=gg(((e,t)=>e*t)),Jg=Sg(((e,t,n,r)=>({real:e*n-t*r,imag:e*r+t*n}))),Zg=Tg(ir,Qg,Jg),ey={kernelName:ir,backendName:"cpu",kernelFunc:Zg},ty=gg(((e,t)=>e!==t?1:0));function ny(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=It(t,s,i),a=new Array(n.length);for(let e=0;e<a.length;e++)a[e]=n[r[e]];l[kt(a,s,u)]=e[t]}return l}function ry(e){const{inputs:t,attrs:n,backend:r}=e,{x:a}=t,{perm:s}=n;dg(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=ny(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 ay(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 sy=bf;class oy{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=xf(l),this.raggedRank=wf(this.rowPartitionTypes)}getRowPartitionTypeByDimension(e){return this.rowPartitionTypes[0]===sy.FIRST_DIM_SIZE?this.rowPartitionTypes[e+1]:this.rowPartitionTypes[e]}getRowPartitionTensor(e){return this.rowPartitionTypes[0]===sy.FIRST_DIM_SIZE?this.rowPartitionValues[e+1]:this.rowPartitionValues[e]}getMaxWidth(e){const t=this.getRowPartitionTensor(e-1);switch(this.getRowPartitionTypeByDimension(e-1)){case sy.VALUE_ROWIDS:return oy.getMaxWidthValueRowID(t);case sy.ROW_SPLITS:return oy.getMaxWidthRowSplit(t);default:throw new Error(`Cannot handle partition type ${sy[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 uy(e,n)}calculateOutputSize(e){const t=this.valuesShape;vf(this.defaultValueShape,t);const n=this.tensorShapeFromTensor(this.shape,this.shapeShape),r=_f(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 sy.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(a,t,n,r);case sy.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: ${sy[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 sy.FIRST_DIM_SIZE:return e[0];case sy.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case sy.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${sy[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=uy(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;ui((()=>{const t=El(l,e),n=Hl(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);iy(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;)iy(s.slice(h*i),l,i),++h;r<0?(c=e+1,p=h):(c=e,p=h,h=p+1)}else++h}}}function iy(e,t,n){for(let r=0;r<n;r++)e[r]=t[r]}function uy(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 ly(e,t,n,r){if(e===t||e<t&&n<0||t<e&&n>1)return wt(0,r);const a=wt(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 cy=Mg((e=>1/Math.sqrt(e))),py=Mg((e=>1/(1+Math.exp(-e)))),hy=Fg(Lr,(e=>1/(1+Math.exp(-e)))),dy={kernelName:Lr,backendName:"cpu",kernelFunc:hy};function fy(e,t,n,r,a){const s=Vu(r,t,n),o=et(n),i=yt(r);if(s){const n=Hu(t,i);return"string"===a?e.slice(n,n+o):e.subarray(n,n+o)}const u=Gl(r,a,"string"===a?Gf(e):e),l=Gl(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?jf(l.values):l.values}function my(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,size:o}=r;dg(a,"slice");const[i,u]=Gu(a,s,o);Fu(a,i,u);const l=fy(n.data.get(a.dataId).values,i,u,a.shape,a.dtype);return n.makeTensorInfo(u,a.dtype,l)}const gy={kernelName:Or,backendName:"cpu",kernelFunc:my},yy=Mg((e=>Math.sqrt(e))),by=gg(((e,t)=>{const n=e-t;return n*n})),_y=Mg(((e,t)=>{const{pattern:n,replaceGlobal:r,rewrite:a}=t;return e.replace(new RegExp(n,r?"g":""),a)}));function xy(e,t,n,r){const a=Gl(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 wy{constructor(e,t,n,r,a,s){this.separator=hs(e),this.nGramWidths=t,this.leftPad=hs(n),this.rightPad=hs(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 vy(e,t,n,r,a,s,o,i){return new wy(n,r,a,s,o,i).compute(e,t)}function ky(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 Iy(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;ky(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 Ty(e,t){const n=ct("int32",e.length);for(let r=0;r<e.length;++r)n[r]=us(e[r]).modulo(t).getLowBitsUnsigned();return n}const Sy=gg(((e,t)=>e-t)),Ey=Sg(((e,t,n,r)=>({real:e-n,imag:t-r}))),Ny=Tg(ta,Sy,Ey),Ay={kernelName:ta,backendName:"cpu",kernelFunc:Ny},Cy=(e,t)=>{const n=t.value-e.value;return 0===n?e.index-t.index:n};function Ry(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);Ry(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),Cy(e[r],a)>0&&Ye(e,n,r);s<o;){for(Ye(e,s,o),s++,o--;Cy(e[s],a)<0;)s+=1;for(;Cy(e[o],a)>0;)o-=1}0===Cy(e[n],a)?Ye(e,n,o):(o+=1,Ye(e,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}}function My(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=new Map,i=new Int32Array(n[a]),u=new Is(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(",")}const r=o.get(n);if(null!=r)i[t]=r;else{const e=o.size;o.set(n,e),i[t]=e,l.push(t)}}const p=s.slice();p[1]=o.size;const h=new Is(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}}var Fy=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:Eg,bincountImpl:function(e,t,n,r,a){const s=et(r),o=wt(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=Gl([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},bitwiseAndImpl:Rg,castImpl:vg,ceilImpl:Og,concatImpl:Dg,equalImpl:Pg,expImpl:Lg,expm1Impl:Ug,floorImpl:Wg,floorDivImpl:zg,gatherNdImpl:function(e,t,n,r,a,s,o,i,u){const l=Gl([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=Gl(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:Vg,greaterEqualImpl:Hg,lessImpl:Gg,lessEqualImpl:jg,linSpaceImpl:function(e,t,n){const r=(t-e)/(n-1),a=wt(n,"float32");a[0]=e;for(let e=1;e<a.length;e++)a[e]=a[e-1]+r;return a},logImpl:Kg,maxImpl:qg,maximumImpl:Xg,minimumImpl:Yg,multiplyImpl:Qg,negImpl:function(e,t,n){const r=ls(-1,n);return Qg([],t,r,e,n)},notEqualImpl:ty,prodImpl:function(e,t,n,r){const[a,s]=Sc(e,r),o=Ds(t,"int32"),i=wt(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=It(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=ay(t,2)[1],i=ay(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 oy(e,t,n,r,a,s,o,i,u,l).compute()},rangeImpl:ly,rsqrtImpl:cy,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 Gl(n,t.dtype);const d=u instanceof Is?u:Gl(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:py,sliceImpl:fy,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($f(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(Of(t,n));if(n>=u)throw new Error(Df(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(Pf(c,e));c=e,u.push(1)}else{if(t<0)throw new Error(Lf(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(Bf(r,u));u[c]=e}if(et(u)!==s)throw new Error(Uf(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(Wf(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(zf(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:yy,squaredDifferenceImpl:by,staticRegexReplaceImpl:_y,stridedSliceImpl:xy,stringNGramsImpl:vy,stringSplitImpl:Iy,stringToHashBucketFastImpl:Ty,subImpl:Sy,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=Gl(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&&(Ry(o,r),o=o.slice(0,r)),a&&o.sort(Cy);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,[Gl(c,n,u),Gl(c,"int32",l)]},transposeImpl:ny,uniqueImpl:My});function $y(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}}di("cpu",(()=>new mg),1);const Oy={kernelName:wr,backendName:"cpu",kernelFunc:$y},Dy={kernelName:Ir,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:o,size:i}=r;dg(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],w=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?w*(e+.5)-.5:w*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)}},Py=gg(((e,t)=>e/t)),Ly=Tg(wn,Py),By={kernelName:wn,backendName:"cpu",kernelFunc:Ly},Uy={kernelName:mr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{paddings:s,constantValue:o}=r;dg(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[kt(It(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 Wy(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;dg([a,s],"conv2d");const p=Tl(u),h=ml(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 Is(h.outShape,a.dtype),w=yt(a.shape),v=yt(s.shape),k=w[0],I=_?w[1]:w[2],T=_?w[2]:1,S=_?1:w[1],E=x.strides[0],N=_?x.strides[1]:x.strides[2],A=_?x.strides[2]:1,C=_?1:x.strides[1],R=n.data.get(a.dataId).values,M=n.data.get(s.dataId).values,F=x.values;for(let e=0;e<h.batchSize;++e){const t=e*k,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*v[0],o=t+n*I;for(let e=0;e<h.outWidth;++e){const t=r+e*A,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*T;let i=s+e*v[1];for(let e=0;e<h.inChannels;++e){const n=R[a+e*S];for(let e=0;e<h.outChannels;++e)F[t+e*C]+=n*M[i+e];i+=h.outChannels}}}}}}return n.makeTensorInfo(x.shape,x.dtype,F)}const zy={kernelName:an,backendName:"cpu",kernelFunc:Wy},Vy=Fg(vn,(e=>e>=0?e:Math.exp(e)-1)),Hy=gg(((e,t)=>e<0?t*e:e)),Gy=Fg(xr,(e=>Math.max(0,e))),jy={kernelName:xr,backendName:"cpu",kernelFunc:Gy},Ky=Fg(Sr,(e=>Math.min(Math.max(0,e),6))),qy={kernelName:Sr,backendName:"cpu",kernelFunc:Ky};function Xy(e,t,n,r,a){if("linear"===n)return _g({inputs:{x:t},backend:e});if("relu"===n)return Gy({inputs:{x:t},backend:e});if("elu"===n)return Vy({inputs:{x:t},backend:e});if("relu6"===n)return Ky({inputs:{x:t},backend:e});if("prelu"===n)return function(e){const{inputs:t,backend:n}=e,{x:r,alpha:a}=t;dg([r,a],"prelu");const s=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values,[i,u]=Hy(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;dg([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 hy({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}const Yy={kernelName:fa,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=Wy({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=$y({inputs:{x:o},backend:n,attrs:{shape:[o.shape[0],1,1]}});m=Ag({inputs:{a:m,b:e},backend:n}),n.disposeIntermediateTensorInfo(e)}else m=Ag({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=$y({inputs:{x:i},backend:n,attrs:{shape:[i.shape[0],1,1]}});m=Xy(n,m,d,e,f),n.disposeIntermediateTensorInfo(e)}else m=Xy(n,m,d,i,f);n.disposeIntermediateTensorInfo(e)}return m}};function Qy(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dilations:u,dimRoundingMode:l}=r;dg([a,s],"depthwiseConv2DNative");const c=yt(a.shape),p=yt(s.shape);let h=u;null==h&&(h=[1,1]),Qe(kl(o,h),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${h}'`));const d=ml(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,w=d.outChannels/d.inChannels,v=new Is(d.outShape,a.dtype),k=n.data.get(a.dataId).values,I=n.data.get(s.dataId).values,T=v.values;for(let e=0;e<d.batchSize;++e){const t=e*c[0],n=e*v.strides[0];for(let e=0;e<d.outHeight;++e){const r=n+e*v.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*v.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=k[i+e];for(let e=0;e<w;++e)T[u+e]+=t*I[l+e];u+=w,l+=w}}}}}}return n.makeTensorInfo(v.shape,v.dtype,v.values)}const Jy={kernelName:gn,backendName:"cpu",kernelFunc:Qy},Zy={kernelName:ma,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=Qy({inputs:{x:a,filter:s},backend:n,attrs:{strides:u,pad:l,dataFormat:c,dilations:p,dimRoundingMode:h}});if(o){const e=m;m=Ag({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(e)}if(d){const e=m;m=Xy(n,m,d,i,f),n.disposeIntermediateTensorInfo(e)}return m}},eb={kernelName:zr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,paddings:o}=r;dg([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=Uy.kernelFunc({inputs:{x:a},backend:n,attrs:{paddings:u,constantValue:0}}),c=Tf(l.shape,s,i,!1),p=Sf(c.length,s.length,!1),h=Ef(l.shape,s,i,!1),d=$y({inputs:{x:l},backend:n,attrs:{shape:c}}),f=ry({inputs:{x:d},backend:n,attrs:{perm:p}}),m=$y({inputs:{x:f},backend:n,attrs:{shape:h}});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),m}},tb={kernelName:Yt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,crops:o}=r;dg([a],"batchToSpaceND");const i=s.reduce(((e,t)=>e*t)),u=Tf(a.shape,s,i),l=Sf(u.length,s.length),c=Ef(a.shape,s,i),p=Nf(o,s.length),h=Af(c,o,s.length),d=$y({inputs:{x:a},backend:n,attrs:{shape:u}}),f=ry({inputs:{x:d},backend:n,attrs:{perm:l}}),m=$y({inputs:{x:f},backend:n,attrs:{shape:c}}),g=my({inputs:{x:m},backend:n,attrs:{begin:p,size:h}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}},nb={kernelName:Qr,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;dg(a,"stridedSlice");const{finalShapeSparse:d,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:b,end:_,strides:x}=ju(a.shape,s,o,i,u,l,c,p,h);let w;if(m)w=$y({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=$u(b,_,x),t=my({inputs:{x:a},backend:n,attrs:{begin:b,size:e}});w=$y({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else{const e=xy(d,n.bufferSync(a),x,b);w=n.makeTensorInfo(f,e.dtype,e.values)}return w}};function rb(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r,s=it(a,t[0].shape)[0];gf(t.map((e=>e.shape)),s);let o=yf(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 _g({inputs:{x:i[0]},backend:n});if("complex64"===i[0].dtype){const e=i.map((e=>wg({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=rb({inputs:e,backend:n,attrs:{axis:s}}),a=rb({inputs:t,backend:n,attrs:{axis:s}}),o=yg({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 $y({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),l=u.map((e=>({vals:n.data.get(e.dataId).values,shape:e.shape})));o=yf(u.map((e=>e.shape)),1);const c=1===u[0].shape[0],p=Dg(l,o,t[0].dtype,c),h=yf(i.map((e=>e.shape)),s),d=n.makeTensorInfo(h,t[0].dtype,p);return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}const ab={kernelName:rn,backendName:"cpu",kernelFunc:rb};function sb(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),$y({inputs:{x:a},backend:n,attrs:{shape:i}})}const ob={kernelName:fr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return sb({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=rb({inputs:t.map((e=>{const t=sb({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}},ib={kernelName:sn,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;dg([a,s],"conv2dBackpropInput");const p=yt(s.shape),h=yt(a.shape);let d=Tl(l);const f=ml(o,s.shape,i,1,u,c,!1,d),m=new Is(f.inShape,"float32"),g=m.values,y=n.data.get(a.dataId).values,b=n.data.get(s.dataId).values,[_,x,w]=p,{batchSize:v,filterHeight:k,filterWidth:I,inChannels:T,inHeight:S,inWidth:E,outChannels:N,outHeight:A,outWidth:C,strideHeight:R,strideWidth:M}=f;d=f.dataFormat;const F=k-1-f.padInfo.top,$=I-1-f.padInfo.left,O="channelsLast"===d,D=m.strides[0],P=O?m.strides[1]:m.strides[2],L=O?m.strides[2]:1,B=O?1:m.strides[1],U=h[0],W=O?h[1]:h[2],z=O?h[2]:1,V=O?1:h[1];for(let e=0;e<v;++e)for(let t=0;t<T;++t)for(let n=0;n<S;++n){const r=n-F,a=Math.max(0,Math.ceil(r/R)),s=Math.min(A,(k+r)/R);for(let o=0;o<E;++o){const i=o-$,u=Math.max(0,Math.ceil(i/M)),l=Math.min(C,(I+i)/M);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+W*n+z*r,o=_*(k-1-a)+x*(I-1-(r*M-i))+w*t;for(let e=0;e<N;++e)c+=y[s+V*e]*b[o+e]}}g[D*e+P*n+L*o+B*t]=c}}return n.makeTensorInfo(m.shape,m.dtype,m.values)}},ub={kernelName:dn,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=Gl([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,w=yt(a.shape),v=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*v[2]+t*v[1]+e*v[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*v[2]+t*v[1]+e*v[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*w[2]+n*w[1]+o*w[0];const l=x[s];s=r+m*w[2]+n*w[1]+o*w[0];const c=x[s];s=r+p*w[2]+a*w[1]+o*w[0];const h=x[s];s=r+m*w[2]+a*w[1]+o*w[0];const d=l+(c-l)*b,f=h+(x[s]-h)*b;s=r+u*v[2]+t*v[1]+e*v[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*v[2]+t*v[1]+e*v[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*w[2]+u*w[1]+o*w[0],s=r+n*v[2]+t*v[1]+e*v[0];y.values[s]=x[a]}}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}},lb={kernelName:Er,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dims:s}=r;dg(a,"reverse");const o=a.shape.length,i=it(s,a.shape);if(0===o)return _g({inputs:{x:a},backend:n});const u=new Is(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)}},cb={kernelName:ua,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=my({inputs:{x:a},backend:n,attrs:{begin:c,size:p}});h[e]=$y({inputs:{x:t},backend:n,attrs:{shape:u}}),n.disposeIntermediateTensorInfo(t)}return h}},pb={kernelName:Ut,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;dg(a,"argMax");let o=it(s,a.shape);const i=Ac(o,a.shape.length);let u=a;const l=[];null!=i&&(u=ry({inputs:{x:a},backend:n,attrs:{perm:i}}),l.push(u),o=Rc(o.length,u.shape.length)),o=[o[0]],Nc("argMax",o,u.shape.length);const[c,p]=Sc(u.shape,o),h=wt(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 hb(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r;let i;dg(a,"sum"),i="bool"===a.dtype?kg({inputs:{x:a},backend:n,attrs:{dtype:"int32"}}):_g({inputs:{x:a},backend:n});const u=i.shape.length,l=it(s,i.shape),c=Ac(l,u);let p=l,h=i;null!=c&&(h=ry({inputs:{x:i},backend:n,attrs:{perm:c}}),p=Rc(p.length,u)),Nc("sum",p,h.shape.length);const[d,f]=Sc(h.shape,p);let m=bg(n,d,Ds(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=$y({inputs:{x:m},backend:n,attrs:{shape:Ec(m.shape,l)}}),n.disposeIntermediateTensorInfo(e)}return n.disposeIntermediateTensorInfo(i),null!=c&&n.disposeIntermediateTensorInfo(h),m}const db={kernelName:nr,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(Sc(a.shape,i)[1]),l=[],c=n.makeTensorInfo([],"float32",new Float32Array([u]));l.push(c);const p=kg({inputs:{x:a},backend:n,attrs:{dtype:"float32"}});l.push(p);const h=Ly({inputs:{a:p,b:c},backend:n});l.push(h);const d=hb({inputs:{x:h},backend:n,attrs:{axis:s,keepDims:o}});return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}},fb={kernelName:Hr,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=Ac(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=ny(d,u,a.dtype,h,e),p=Rc(p.length,l),u=e}dg(a,"max"),Nc("max",p,l);const[f,m]=Sc(u,p),g=qg(d,et(m),f,a.dtype),y=i.write(g,f,a.dtype);let b=f;return o&&(b=Ec(f,c)),{dataId:y,shape:b,dtype:a.dtype}}({inputs:{x:a},backend:n,attrs:{reductionIndices:u,keepDims:!1}}),c=Ec(l.shape,u),p=$y({inputs:{x:l},backend:n,attrs:{shape:c}}),h=Ny({inputs:{a,b:p},backend:n}),d=Bg({inputs:{x:h},backend:n}),f=hb({inputs:{x:d},backend:n,attrs:{axis:u,keepDims:!1}}),m=$y({inputs:{x:f},backend:n,attrs:{shape:c}}),g=Ly({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}},mb=Fg(nn,((e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e})),gb={kernelName:nn,backendName:"cpu",kernelFunc:mb},yb={kernelName:Kt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;dg(a,"avgPool");const{filterSize:s,strides:o,pad:i,dimRoundingMode:u}=r;Qe(kl(o,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '1'`));const l=dl(a.shape,s,o,1,i,u);let c;if(1===l.filterWidth&&1===l.filterHeight&&tt(l.inShape,l.outShape))c=_g({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=Gl(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),w=Math.min(a.inHeight,c+y),v=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<w;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[v+n*_+t]=y/b}}}return m}(e,a.shape,a.dtype,t,l);c=n.makeTensorInfo(l.outShape,a.dtype,r.values)}return c}},bb={kernelName:Xt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a,b:s}=t,{transposeA:o,transposeB:i}=r;dg([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=Tu(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=$y({inputs:{x:a},backend:n,attrs:{shape:o?[g,c,h]:[g,h,c]}}),w=$y({inputs:{x:s},backend:n,attrs:{shape:_}}),v=o?x.shape[1]:x.shape[2],k=o?x.shape[2]:x.shape[1],I=i?w.shape[1]:w.shape[2],T=Math.max(g,y),S=n.data.get(x.dataId).values,E=n.data.get(w.dataId).values,N=yt(x.shape),A=yt(w.shape),[C,R,M]=o?[N[0],1,N[1]]:[N[0],N[1],1],[F,$,O]=i?[1,A[1],A[0]]:[A[1],1,A[0]],D=k*I,P=Gl([T,k,I],x.dtype),L=P.values,B=n.blockSize;for(let e=0;e<T;e++){const t=e%g,n=e%y;for(let r=0;r<k;r+=B){const a=Math.min(r+B,k);for(let s=0;s<I;s+=B){const o=Math.min(s+B,I);for(let i=0;i<v;i+=B){const u=Math.min(i+B,v);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*C+l*R+e*M]*E[e*F+r*$+n*O];L[e*D+(l*I+r)]+=a}}}}}return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(w),n.makeTensorInfo(b,P.dtype,P.values)}},_b={},xb={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function wb(e,t){if(!(e in _b)||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(At().getBool("IS_SAFARI")||"undefined"==typeof OffscreenCanvas||2!==e){if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}return new OffscreenCanvas(300,150)}(e):t;return n.addEventListener("webglcontextlost",(t=>{t.preventDefault(),delete _b[e]}),!1),At().getBool("SOFTWARE_WEBGL_ENABLED")&&(xb.failIfMajorPerformanceCaveat=!1),1===e?n.getContext("webgl",xb)||n.getContext("experimental-webgl",xb):n.getContext("webgl2",xb)}(e,t);if(null===n)return console.log("Could not get context for WebGL version",e),null;_b[e]=n}const n=_b[e];return null==n||n.isContextLost()?(delete _b[e],wb(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),_b[e])}var vb,kb,Ib;function Tb(e,t){return[t,e]}function Sb(e){const t=et(e);return rt(Math.ceil(t/4))}function Eb(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function Nb(e,t){const n=e;let r,a,s,o,i,u,l,c,p,h;return 2===At().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 Ab(e,t){const n=t();return At().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 Cb(e){return!!(At().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||5.96e-8<Math.abs(e)&&Math.abs(e)<65504)}function Rb(e,t){return Bb(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"}(vb||(vb={})),function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"}(kb||(kb={})),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"}(Ib||(Ib={}));const Mb=/ERROR: [0-9]+:([0-9]+):/g;function Fb(e,t){const n=Mb.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 $b(e,t){if(Ab(e,(()=>e.validateProgram(t))),!1===e.getProgramParameter(t,e.VALIDATE_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function Ob(e,t,n,r,a,s,o){const i=e.getAttribLocation(t,n);return-1!==i&&(Ab(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,r))),Ab(e,(()=>e.vertexAttribPointer(i,a,e.FLOAT,!1,s,o))),Ab(e,(()=>e.enableVertexAttribArray(i))),!0)}function Db(e,t,n){Ab(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,n))),Ab(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)))}function Pb(e,t){Ab(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,t))),Ab(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)))}function Lb(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 Bb(e,t,n){const r=Ab(e,(()=>t()));if(null==r)throw new Error(n);return r}function Ub(e,t=2){return et(e.slice(0,e.length-t))}function Wb(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 zb(e){let t=[1,1,1];return 0===e.length||1===e.length&&1===e[0]||(t=[Ub(e),...Wb(e)]),t}function Vb(e){return e%2==0}function Hb(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[e.length-1],r=t[t.length-1];if(n===r)return!0;if(Vb(n)&&Vb(r)&&(1===e[0]||1===t[0]))return!0}return e[1]===t[1]&&Vb(e[0])&&Vb(t[0])}let Gb,jb;function Kb(e,t){return null!=e.getExtension(t)}function qb(e){try{if(null!=wb(e))return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function Xb(e){const t=Nb(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 Yb=At();function Qb(){let e,t,n,r,a,s,o,i,u,l;return 2===At().getNumber("WEBGL_VERSION")?(e="#version 300 es",t="in",n="out",r="in",a="texture",s="outputColor",o="out vec4 outputColor;",i=At().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 Jb(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 Zb(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 e_(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`}Yb.registerFlag("HAS_WEBGL",(()=>Yb.getNumber("WEBGL_VERSION")>0)),Yb.registerFlag("WEBGL_VERSION",(()=>qb(2)?2:qb(1)?1:0)),Yb.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",(()=>!1)),Yb.registerFlag("WEBGL_BUFFER_SUPPORTED",(()=>2===Yb.get("WEBGL_VERSION"))),Yb.registerFlag("WEBGL_CPU_FORWARD",(()=>!0)),Yb.registerFlag("WEBGL_FORCE_F16_TEXTURES",(()=>!1)),Yb.registerFlag("WEBGL_PACK",(()=>Yb.getBool("HAS_WEBGL"))),Yb.registerFlag("WEBGL_PACK_NORMALIZATION",(()=>Yb.getBool("WEBGL_PACK"))),Yb.registerFlag("WEBGL_PACK_CLIP",(()=>Yb.getBool("WEBGL_PACK"))),Yb.registerFlag("WEBGL_PACK_DEPTHWISECONV",(()=>Yb.getBool("WEBGL_PACK"))),Yb.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(()=>Yb.getBool("WEBGL_PACK"))),Yb.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(()=>Yb.getBool("WEBGL_PACK"))),Yb.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(()=>Yb.getBool("WEBGL_PACK"))),Yb.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(()=>Yb.getBool("WEBGL_PACK"))),Yb.registerFlag("WEBGL_PACK_REDUCE",(()=>Yb.getBool("WEBGL_PACK"))),Yb.registerFlag("WEBGL_LAZILY_UNPACK",(()=>Yb.getBool("WEBGL_PACK"))),Yb.registerFlag("WEBGL_CONV_IM2COL",(()=>Yb.getBool("WEBGL_PACK"))),Yb.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE",(()=>Yb.getBool("WEBGL_PACK"))),Yb.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(()=>function(e){if(null==Gb){const t=wb(e);Gb=t.getParameter(t.MAX_TEXTURE_SIZE)}return Gb}(Yb.getNumber("WEBGL_VERSION")))),Yb.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(()=>function(e){if(null==jb){const t=wb(e);jb=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,jb)}(Yb.getNumber("WEBGL_VERSION")))),Yb.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(()=>{const e=Yb.getNumber("WEBGL_VERSION");return 0===e?0:function(e){if(0===e)return 0;let t;const n=wb(e);return t=Kb(n,"EXT_disjoint_timer_query_webgl2")&&2===e?2:Kb(n,"EXT_disjoint_timer_query")?1:0,t}(e)})),Yb.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(()=>Yb.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!qs())),Yb.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(()=>function(e){if(0===e)return!1;const t=wb(e);if(1===e){if(!Kb(t,"OES_texture_float"))return!1}else if(!Kb(t,"EXT_color_buffer_float"))return!1;return Xb(t)}(Yb.getNumber("WEBGL_VERSION")))),Yb.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(()=>!Yb.getBool("WEBGL_FORCE_F16_TEXTURES")&&Yb.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))),Yb.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(()=>function(e){if(0===e)return!1;const t=wb(e);if(1!==e){if(Kb(t,"EXT_color_buffer_float"))return Xb(t);const e="EXT_color_buffer_half_float";if(Kb(t,e)){const n=t.getExtension(e);return function(e,t){const n=Nb(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!!Kb(t,"OES_texture_float")&&!!Kb(t,"WEBGL_color_buffer_float")&&Xb(t)}(Yb.getNumber("WEBGL_VERSION")))),Yb.registerFlag("WEBGL_FENCE_API_ENABLED",(()=>{return 2===(e=Yb.getNumber("WEBGL_VERSION"))&&null!=wb(e).fenceSync;var e})),Yb.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(()=>Yb.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0)),Yb.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",(()=>-1),(e=>{if("number"!=typeof e)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but got ${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}.`)})),Yb.registerFlag("WEBGL_FLUSH_THRESHOLD",(()=>qs()?1:-1),(e=>{if("number"!=typeof e)throw new Error(`WEBGL_FLUSH_THRESHOLD must be a number but got ${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}.`)})),Yb.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",(()=>128)),Yb.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",(()=>!1)),Yb.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",(()=>1e5)),Yb.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",(()=>128)),Yb.registerFlag("WEBGL_EXP_CONV",(()=>!1)),Yb.registerFlag("SOFTWARE_WEBGL_ENABLED",(()=>Yb.getBool("IS_TEST"))),Yb.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",(()=>1/0)),Yb.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",(()=>!1)),Yb.registerFlag("WEBGL2_ISNAN_CUSTOM",(()=>!1)),Yb.registerFlag("ENGINE_COMPILE_ONLY",(()=>!1));const t_="\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:n_}=Kf;function r_(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}=d_(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?s_(e,r):a_(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=n_(e.shapeInfo.logicalShape,t.logicalShape),u=h_(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=h_(u),c=n_(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=Qb(),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 ${o_}\n ${i_}\n ${u_}\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 ${Zb(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n`;const r=Jb(["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 ${Zb(["r","c","d","d2"],e)}\n return ivec4(r, c, d, d2);\n }\n `;const r=Jb(["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=Jb(["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=Jb(["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+=l_),[p,u,c,a,l,s,n.userCode].join("\n")}function a_(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=c_(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 ${p_(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=c_(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 ${a_(f_(e,u),t)}\n float ${a}(int row, int col) {\n return ${a}(${m_(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 ${p_(e)}\n }\n `;const l=s[0],c=s[1],p=c_(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 ${a_(f_(e,l),t)}\n float ${a}(int row, int col, int depth) {\n return ${a}(${m_(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 ${p_(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=c_(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 ${a_(f_(e,u),t)}\n float ${a}(int row, int col, int depth, int depth2) {\n return ${a}(${m_(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 ${p_(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=c_(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 ${a_(f_(e,u))}\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n return ${r}(${m_(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 ${p_(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 + ${c_(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 ${a_(f_(e,a))}\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return ${r}(${m_(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 ${p_(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 + ${c_(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 s_(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 ${Qb().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=Qb();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=Qb();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 ${s_(f_(e,n.slice(1)),t)}\n vec4 ${a}(int b, int row, int col) {\n return ${a}(${m_(s,r)});\n }\n `}const i=Qb();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=Qb();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 o_="\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",i_="\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",u_="\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",l_="\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 c_(e){return`offset${e}`}function p_(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 h_(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 d_(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 f_(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function m_(e,t){return t.map((t=>e[t])).join(", ")}function g_(e,t,n){const r=[],a=[];let s,o,i,u=null,l=null;l=e.getUniformLocation(n,"NAN",!1),1===At().getNumber("WEBGL_VERSION")&&(u=e.getUniformLocation(n,"INFINITY",!1));const c=!1;for(const a of t.variableNames){const s={name:a,uniform:e.getUniformLocation(n,a,c),offset:e.getUniformLocation(n,`offset${a}`,c)};t.enableShapeUniforms&&(s.shape=e.getUniformLocation(n,`${a}Shape`,c),s.texShape=e.getUniformLocation(n,`${a}TexShape`,c)),r.push(s)}if(t.enableShapeUniforms&&(s=e.getUniformLocation(n,"outShape",c),i=e.getUniformLocation(n,"outShapeStrides",c),o=e.getUniformLocation(n,"outTexShape",c)),t.customUniforms)for(const r of t.customUniforms)a.push(e.getUniformLocation(n,r.name,c));return{variablesLocations:r,customUniformLocations:a,infLoc:u,nanLoc:l,outShapeLocation:s,outShapeStridesLocation:i,outTexShapeLocation:o}}function y_(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 b_(e){return At().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}class __{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=vb.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=Qb();this.outputShape=e,this.enableShapeUniforms=b_(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?Zb(["r","c","d"],e):Jb(["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 x_{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=vb.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=Qb();this.outputShape=e,this.enableShapeUniforms=b_(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?Zb(["r","c","d"],e):Jb(["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 w_{constructor(e){this.variableNames=["A"],this.outTexUsage=kb.DOWNLOAD;const t=Qb();this.outputShape=e,this.userCode=`\n ${t_}\n\n void main() {\n float x = getAAtOutCoords();\n ${t.output} = encode_float(x);\n }\n `}}class v_{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=kb.DOWNLOAD;const t=Qb();this.outputShape=e,this.userCode=`\n ${t_}\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 k_={R:0,G:1,B:2,A:3};class I_{constructor(e,t=!1,n="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const r=Qb();this.outputShape=e,this.enableShapeUniforms=b_(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[${k_[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":e_(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 T_{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=Qb();this.outputShape=e,this.enableShapeUniforms=b_(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":e_(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 S_(e,t,n,r,a,s){!function(e,t){const n=At().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 Bb(e,(()=>e.createTexture()),"Unable to create WebGLTexture.")}(e),i=e.TEXTURE_2D;return Ab(e,(()=>e.bindTexture(i,o))),Ab(e,(()=>e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE))),Ab(e,(()=>e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE))),Ab(e,(()=>e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST))),Ab(e,(()=>e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST))),1===At().getNumber("WEBGL_VERSION")?Ab(e,(()=>e.texImage2D(i,0,r,t,n,0,a,s,null))):Ab(e,(()=>e.texStorage2D(i,1,r,t,n))),Ab(e,(()=>e.bindTexture(e.TEXTURE_2D,null))),{texture:o,texShape:[n,t]}}function E_(e){return e.internalFormatFloat}function N_(e){return e.internalFormatHalfFloat}function A_(e){return e.downloadTextureFormat}function C_(e){return e.internalFormatPackedFloat}function R_(e){return e.internalFormatPackedHalfFloat}class M_{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];const t=At().getNumber("WEBGL_VERSION");if(null!=e?(this.gl=e,function(e,t){_b[e]=t}(t,e)):this.gl=wb(t),e=this.gl,2===At().getNumber("WEBGL_VERSION")){const t=e;this.createVertexArray=()=>Ab(t,(()=>t.createVertexArray())),this.bindVertexArray=e=>Ab(t,(()=>t.bindVertexArray(e))),this.deleteVertexArray=e=>Ab(t,(()=>t.deleteVertexArray(e))),this.getVertexArray=()=>Ab(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=()=>Ab(e,(()=>t.createVertexArrayOES())),this.bindVertexArray=n=>Ab(e,(()=>t.bindVertexArrayOES(n))),this.deleteVertexArray=n=>Ab(e,(()=>t.deleteVertexArrayOES(n))),this.getVertexArray=()=>Ab(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===At().getNumber("WEBGL_VERSION")){const e="OES_texture_float",t="OES_texture_half_float";if(this.textureFloatExtension=Rb(this.gl,e),Kb(this.gl,t))this.textureHalfFloatExtension=Rb(this.gl,t);else if(At().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),Kb(this.gl,r))this.colorBufferHalfFloatExtension=Rb(this.gl,r);else if(At().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",Kb(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!Kb(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=Bb(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return Ab(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),Ab(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=Bb(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return Ab(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n))),Ab(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 Bb(e,(()=>e.createFramebuffer()),"Unable to create WebGLFramebuffer.")}(this.gl),this.textureConfig=Nb(this.gl,this.textureHalfFloatExtension)}get debug(){return At().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;Ab(e,(()=>e.finish())),Ab(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,null))),Ab(e,(()=>e.deleteFramebuffer(this.framebuffer))),Ab(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,null))),Ab(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null))),Ab(e,(()=>e.deleteBuffer(this.indexBuffer))),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=Tb(t,n);return S_(e,a,s,E_(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]=Tb(t,n);return S_(e,a,s,N_(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]=Tb(t,n);return S_(e,a,s,A_(r),e.RGBA,e.UNSIGNED_BYTE)}(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),function(e,t,n){Ab(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),n.data instanceof Uint8Array?2===At().getNumber("WEBGL_VERSION")?Ab(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data))):Ab(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data))):2===At().getNumber("WEBGL_VERSION")?Ab(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n))):Ab(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n))),Ab(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;Ab(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===At().getNumber("WEBGL_VERSION")?Ab(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGBA,i,o))):Ab(e,(()=>e.texImage2D(e.TEXTURE_2D,0,u,n,r,0,e.RGBA,i,o))),Ab(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]=Eb(t,n);return S_(e,a,s,R_(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]=Eb(t,n);return S_(e,a,s,C_(r),e.RGBA,e.FLOAT)}(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Pb(this.gl,this.framebuffer),this.outputTexture=null),Ab(this.gl,(()=>this.gl.deleteTexture(e)))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>function(e,t,n,r){const[a,s]=Tb(t,n),o=new Uint8Array(t*n*4);return Ab(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]=Eb(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();Ab(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,a)));const s=16*t*n;return Ab(e,(()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ))),Ab(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0))),Ab(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(At().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 At().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,At().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 Ab(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=Qb();return function(e,t){const n=Bb(e,(()=>e.createShader(e.VERTEX_SHADER)),"Unable to create vertex WebGLShader.");if(Ab(e,(()=>e.shaderSource(n,t))),Ab(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 Bb(e,(()=>e.createProgram()),"Unable to create WebGLProgram.")}(t);Ab(t,(()=>t.attachShader(n,this.vertexShader))),Ab(t,(()=>t.attachShader(n,e))),function(e,t){if(Ab(e,(()=>e.linkProgram(t))),!At().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);const r=Object.assign(n,{vao:this.createVertexArray()});return this.debug&&$b(t,r),r}buildVao(e){this.setProgram(e),this.bindVertexArray(e.vao);const t=this.gl;Ab(t,(()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer))),function(e,t,n){Ab(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),Ob(e,t,"clipSpacePos",n,3,20,0)&&Ob(e,t,"uv",n,2,20,12)}(t,e,this.vertexBuffer)}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&(Ab(this.gl,(()=>this.gl.deleteProgram(e))),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,null!=this.program&&this.debug&&$b(this.gl,this.program),Ab(this.gl,(()=>this.gl.useProgram(e)))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?function(e,t,n){return Bb(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(),Ab(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){Ab(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),Ab(e,(()=>e.activeTexture(e.TEXTURE0+n))),Ab(e,(()=>e.bindTexture(e.TEXTURE_2D,t)))}(e,t,r))),Ab(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]=Eb(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&&$b(this.gl,this.program),Lb(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()}Ab(e,(()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),Ab(this.gl,(()=>this.gl.finish()))}getQueryTimerExtension(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=Rb(this.gl,2===At().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===At().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===At().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,At().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")))),this.getQueryTime(e,At().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 At().platform&&(n=At().platform.setTimeoutCustom.bind(At().platform)),st((()=>(this.pollItems(),0===this.itemsToPoll.length)),(()=>0),null,n)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),Db(this.gl,e,this.framebuffer),this.debug&&Lb(this.gl)}unbindTextureToFrameBuffer(){null!=this.outputTexture?(Db(this.gl,this.outputTexture,this.framebuffer),this.debug&&Lb(this.gl)):Pb(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;Db(r,e,this.framebuffer),this.debug&&Lb(r),this.outputTexture=e,Ab(r,(()=>r.viewport(0,0,t,n))),Ab(r,(()=>r.scissor(0,0,t,n)))}setOutputMatrixWriteRegionDriver(e,t,n,r){this.throwIfDisposed(),Ab(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:F_,bincountImpl:$_,bincountReduceImpl:O_,bitwiseAndImpl:D_,castImpl:P_,ceilImpl:L_,concatImpl:B_,equalImpl:U_,expImpl:W_,expm1Impl:z_,floorImpl:V_,gatherNdImpl:H_,gatherV2Impl:G_,greaterImpl:j_,greaterEqualImpl:K_,lessImpl:q_,lessEqualImpl:X_,linSpaceImpl:Y_,logImpl:Q_,maxImpl:J_,maximumImpl:Z_,minimumImpl:ex,multiplyImpl:tx,negImpl:nx,notEqualImpl:rx,prodImpl:ax,raggedGatherImpl:sx,raggedRangeImpl:ox,raggedTensorToTensorImpl:ix,rangeImpl:ux,rsqrtImpl:lx,scatterImpl:cx,sigmoidImpl:px,simpleAbsImpl:hx,sliceImpl:dx,sparseFillEmptyRowsImpl:fx,sparseReshapeImpl:mx,sparseSegmentReductionImpl:gx,sqrtImpl:yx,staticRegexReplaceImpl:bx,stridedSliceImpl:_x,stringNGramsImpl:xx,stringSplitImpl:wx,stringToHashBucketFastImpl:vx,subImpl:kx,tileImpl:Ix,topKImpl:Tx,transposeImpl:Sx,uniqueImpl:Ex}=Fy;function Nx(e,t){return["x","y","z","w","u","v"].slice(0,t).map((t=>`${e}.${t}`))}function Ax(e,t){return 1===t?[e]:Nx(e,t)}class Cx{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=b_(this.outputShape.length),0===this.rank)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{const e=Ax("rc",this.rank),t=h_(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 Rx{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=b_(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"):Jb(["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":e_(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 Mx{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.usedTextures={},this.logEnabled=!1}acquireTexture(e,t,n){const r=$x(t,n),a=Ox(e,r,n);a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]);const s=Fx(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].pop();return this.usedTextures[a].push(e),e}let o;return r===Ib.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===Ib.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===Ib.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===Ib.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===Ib.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=$x(n,r),s=Ox(t,a,r);s in this.freeTextures||(this.freeTextures[s]=[]);const o=Fx(t,a,this.gpgpu.gl,this.gpgpu.textureConfig,r),i=At().getNumber("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&&u.indexOf(e);if(null==l||l<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u[l]=u[u.length-1],u.pop(),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 Fx(e,t,n,r,a){const s=function(e,t){switch(e){case Ib.PACKED_2X2_FLOAT32:return C_(t);case Ib.PACKED_2X2_FLOAT16:return R_(t);case Ib.UNPACKED_FLOAT32:return E_(t);case Ib.UNPACKED_FLOAT16:return N_(t);case Ib.PACKED_4X1_UNSIGNED_BYTE:return A_(t);default:throw new Error(`Unknown physical texture type ${e}`)}}(t,r);let o;if(a){const[t,n]=Eb(e[0],e[1]);o=t*n}else{const[t,n]=Tb(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 $x(e,t){if(e===kb.UPLOAD)return Ib.PACKED_2X2_FLOAT32;if(e===kb.RENDER||null==e)return function(e){return At().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Ib.PACKED_2X2_FLOAT32:Ib.UNPACKED_FLOAT32:e?Ib.PACKED_2X2_FLOAT16:Ib.UNPACKED_FLOAT16}(t);if(e===kb.DOWNLOAD||e===kb.PIXELS)return Ib.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function Ox(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class Dx{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=b_(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 Px="if (isnan(x)) return x;",Lx="return abs(x);",Bx="return x;";class Ux{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=b_(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 Wx{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=b_(this.outputShape.length);const t=e.length,n=Ax("rc",t),r=h_(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 zx=Zh,Vx={},Hx=At().getNumber("CPU_HANDOFF_SIZE_THRESHOLD");class Gx extends je{nextDataId(){return Gx.nextDataId++}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,!At().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(null!=e){if(e instanceof M_)t=e;else{const n=wb(At().getNumber("WEBGL_VERSION"),e);t=new M_(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{const e=wb(At().getNumber("WEBGL_VERSION"));t=new M_(e),this.binaryCache=((n=At().getNumber("WEBGL_VERSION"))in Vx||(Vx[n]={}),Vx[n]),this.gpgpuCreatedLocally=!0}var n;this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new Mx(this.gpgpu),this.numMBBeforeWarning=null==At().global.screen?1024:At().global.screen.height*At().global.screen.width*window.devicePixelRatio*600/1024/1024,this.texData=new Ge(this,ii())}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=zb(t),l=new I_(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((At().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||At().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:kb.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(At().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:kb.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 Ux(o,Bx):new Dx(o,Bx);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=ps()),c="complex64"===r?Cf(this.readSync(a.real.dataId),this.readSync(a.imag.dataId)):this.getValuesFromTexture(e),u&&(this.downloadWaitMs+=ps()-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 Ux(r,Bx):new Dx(r,Bx);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(At().getBool("DEBUG")&&!At().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===At().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&&At().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);const t=this.texData.get(u.dataId);c=this.gpgpu.createBufferFromTexture(t.texture.texture,...Sb(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=Cf(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;Ab(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)&&ii().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 Ux(a,Bx):new Dx(a,Bx);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=ii().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=>ds(e)));return Gl(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Gl(e.shape,e.dtype,t)}checkNumericalProblems(e){if(null!=e)for(let t=0;t<e.length;t++){const n=e[t];if(!Cb(n)){if(At().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(At().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const n=this.decode(e),r=this.texData.get(n.dataId),s=this.gpgpu.downloadMatrixFromPackedTexture(r.texture.texture,...Sb(t)).subarray(0,a);return this.disposeIntermediateTensorInfo(n),s}const s=At().getBool("WEBGL_PACK")&&!0===r,o=s?zb(t):t,i=s?new v_(o):new w_(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 At().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=ms(this.activeTimers.map((e=>e.query))).filter((e=>null!=e)),s=ms(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(At().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 At().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:ps(),endMs:null}}endTimer(e){return At().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=ps(),e)}async getQueryTime(e){if(At().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=Hx){return At().getBool("WEBGL_CPU_FORWARD")&&e.every((e=>null==this.texData.get(e.dataId).texture&&et(e.shape)<t))}getGPGPUContext(){return this.gpgpu}where(e){ga("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return zx(e.shape,t)}packedUnaryOp(e,t,n){const r=new Ux(e.shape,t),a=this.compileAndRun(r,[e],n);return ii().makeTensorFromTensorInfo(a)}abs(e){if(this.shouldExecuteOnCPU([e])&&"complex64"!==e.dtype){const t=hx(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,t)}if(At().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Lx,e.dtype);const t=new Dx(e.shape,Lx),n=this.compileAndRun(t,[e]);return ii().makeTensorFromTensorInfo(n)}makeTensorInfo(e,t,n){let r;if("string"===t&&null!=n&&n.length>0&&dt(n[0])){const a=n.map((e=>hs(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 ii().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,n),this)}unpackTensor(e){const t=new Wx(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new Cx(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const n=[Ub(e.shape),...Wb(e.shape)],r={dtype:e.dtype,shape:n,dataId:e.dataId},a=[Ub(t),...Wb(t)],s=new Rx(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=zb(a);let i;i=r?new x_(o):new __(o);const u=[null!=t?t:Sb(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===vb.DENSE){const t=null!=s?s:Sb(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)<=At().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&&!Hb(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}=d_(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=ku(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+`${At().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=r_(a,o,t),u=function(e,t){const n=Bb(e,(()=>e.createShader(e.FRAGMENT_SHADER)),"Unable to create fragment WebGLShader.");if(Ab(e,(()=>e.shaderSource(n,t))),Ab(e,(()=>e.compileShader(n))),At().get("ENGINE_COMPILE_ONLY"))return n;if(!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw Fb(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}(e.gl,i),l=e.createProgram(u);return At().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:u,source:i,webGLProgram:l,inShapeInfos:s,outShapeInfo:o,variablesLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:(e.buildVao(l),Object.assign({program:t,fragmentShader:u,source:i,webGLProgram:l,inShapeInfos:s,outShapeInfo:o},g_(e,t,l)))}(this.gpgpu,e,l,c))),d=null!=this.activeTimers;let f;d&&(f=this.startTimer()),At().get("ENGINE_COMPILE_ONLY")||function(e,t,n,r,a){t.program.enableShapeUniforms||(y_(t.inShapeInfos,n),y_([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),e.bindVertexArray(t.webGLProgram.vao),1===At().getNumber("WEBGL_VERSION")&&null!==t.infLoc&&e.gl.uniform1f(t.infLoc,1/0),null!==t.nanLoc&&e.gl.uniform1f(t.nanLoc,NaN);for(let r=0;r<n.length;++r){const a=n[r],{uniform:s,offset:o,shape:i,texShape:u}=t.variablesLocations[r];if(i){const{uniformShape:n}=d_(t.program.packedInputs,a.shape,a.texData.texShape);switch(n.length){case 1:e.gl.uniform1iv(i,new Int32Array(n));break;case 2:e.gl.uniform2iv(i,new Int32Array(n));break;case 3:e.gl.uniform3iv(i,new Int32Array(n));break;case 4:e.gl.uniform4iv(i,new Int32Array(n))}}if(u&&e.gl.uniform2i(u,a.texData.texShape[0],a.texData.texShape[1]),null!=s)if(a.isUniform)if(et(a.shape)<2)e.gl.uniform1f(s,a.uniformValues[0]);else{let t=a.uniformValues;t instanceof Float32Array||(t=new Float32Array(t)),e.gl.uniform1fv(s,t)}else null!=a.texData.slice&&null!=o&&e.gl.uniform1i(o,a.texData.slice.flatOffset),e.setInputMatrixTexture(a.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))}}if(t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,r.texData.texShape[0],r.texData.texShape[1]),t.program.customUniforms&&a)for(let n=0;n<t.program.customUniforms.length;++n){const r=t.program.customUniforms[n],s=t.customUniformLocations[n],o=a[n];if("float"===r.type)e.gl.uniform1fv(s,o);else if("vec2"===r.type)e.gl.uniform2fv(s,o);else if("vec3"===r.type)e.gl.uniform3fv(s,o);else if("vec4"===r.type)e.gl.uniform4fv(s,o);else if("int"===r.type)e.gl.uniform1iv(s,o);else if("ivec2"===r.type)e.gl.uniform2iv(s,o);else if("ivec3"===r.type)e.gl.uniform3iv(s,o);else{if("ivec4"!==r.type)throw Error(`uniform type ${r.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=At().getNumber("WEBGL_FLUSH_THRESHOLD");if(m>0){const e=ps();e-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=e)}if(!At().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||(At().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=ui((()=>{if(!At().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=At().getBool("DEBUG");At().set("DEBUG",!1);const t=this.abs(Oc(1e-8)).dataSync()[0];if(At().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=ps());let c=t.texShape;if(null==c&&(c=function(e,t=!1){let n=At().getNumber("WEBGL_MAX_TEXTURE_SIZE"),r=At().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");if(r===1/0&&At().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=Ub(e);let n=2,r=2;e.length&&([n,r]=Wb(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=zb(n);let s,o=c[1],p=c[0];const h=a instanceof Uint8Array||a instanceof Uint8ClampedArray;!i&&h||([o,p]=Eb(c[0],c[1])),s=i?new T_(e,h):new I_(e,h);const d=h?[p,o]:c,f=this.makeTensorInfo(d,r),m=this.texData.get(f.dataId);m.usage=h?kb.PIXELS:kb.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,At().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+=ps()-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=>mf((()=>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 Fb(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.values(this.binaryCache)){this.gpgpu.buildVao(e.webGLProgram);const{variablesLocations:t,customUniformLocations:n,infLoc:r,nanLoc:a,outShapeLocation:s,outShapeStridesLocation:o,outTexShapeLocation:i}=g_(this.gpgpu,e.program,e.webGLProgram);e.variablesLocations=t,e.customUniformLocations=n,e.infLoc=r,e.nanLoc=a,e.outShapeLocation=s,e.outShapeStridesLocation=o,e.outTexShapeLocation=i}}createTensorFromGPUData(e,t,n){e.channels=e.channels||"RGBA";const{texture:r,height:a,width:s,channels:o}=e,i=ii().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 ii().makeTensorFromDataId(u,t,n,i)}}Gx.nextDataId=0,Xs()&&di("webgl",(()=>new Gx),2);class jx{constructor(e){this.variableNames=["A"];const t=Qb(),[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 Kx{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=Qb(),[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 qx={kernelName:pa,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=At().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");null!=Xx&&e===Yx||(Yx=e,Xx=document.createElement("canvas").getContext("2d",{willReadFrequently:Yx})),Xx.canvas.width=u,Xx.canvas.height=l,Xx.drawImage(a,0,0,u,l),a=Xx.canvas}const h=n.makeTensorInfo(c,"int32");n.texData.get(h.dataId).usage=kb.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(h.dataId),a);const d=At().getBool("WEBGL_PACK")?new Kx(p):new jx(p),f=n.runWebGLProgram(d,[h],"int32");return n.disposeData(h.dataId),f}};let Xx,Yx=At().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function Qx(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||Hb(a.shape,u)||null!==c.texture&&Hb(c.shape,u)?(o.incRef(a.dataId),{dataId:a.dataId,shape:u,dtype:a.dtype}):function(e,t,n){const r=[Ub(e.shape),...Wb(e.shape)],a={dtype:e.dtype,shape:r,dataId:e.dataId},s=[Ub(t),...Wb(t)],o=new Rx(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 Jx={kernelName:wr,backendName:"webgl",kernelFunc:Qx};function Zx(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),Qx({inputs:{x:s},backend:r,attrs:{shape:i}})}const ew={kernelName:Sn,backendName:"webgl",kernelFunc:Zx};class tw{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 nw{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 rw={kernelName:Ir,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=At().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new nw(a.shape,u,l,s,o):new tw(a.shape,u,l,s,o);return n.runWebGLProgram(c,[a],"float32")}};function aw(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 sw={kernelName:Pn,backendName:"webgl",kernelFunc:aw};function ow(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=aw({inputs:{x:r},backend:n}),u=aw({inputs:{x:a},backend:n});return o.complexTensorInfos={real:i,imag:u},s}class iw{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=Tu(t,n),this.enableShapeUniforms=b_(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 uw{constructor(e,t,n,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=Tu(t,n);const a=this.outputShape.length;this.enableShapeUniforms=b_(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 ${h_(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=Ax("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 lw="if (isnan(x)) return x;";function cw({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=At().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&null!=t?new Ux(o.shape,t):new Dx(o.shape,e),i.runWebGLProgram(l,[o],u)}}function pw({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 iw(e,u.shape,l.shape);return c.runWebGLProgram(o,[a,s],Ds(n.dtype,r.dtype))})),s=ow({inputs:{real:r,imag:a},backend:c});return c.disposeIntermediateTensorInfo(r),c.disposeIntermediateTensorInfo(a),s}const p=s||Ds(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?Gf(e):e,r="string"===u.dtype?Gf(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=At().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&null!=t?new uw(t,u.shape,l.shape,n):new iw(e,u.shape,l.shape),c.runWebGLProgram(h,[u,l],p)}}function hw(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 dw=pw({opSnippet:"return float(a != b);",cpuKernelImpl:rx,dtype:"bool"});function fw(e){const{inputs:t,backend:n}=e,{input:r}=t;return aw({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.real},backend:n})}const mw={kernelName:en,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 aw({inputs:{x:s},backend:r});const t=kp(s.shape),n=e({inputs:{x:s},backend:r,attrs:{dtype:"float32"}}),a=ow({inputs:{real:n,imag:t},backend:r});return t.dispose(),r.disposeIntermediateTensorInfo(n),a}if("complex64"===s.dtype){const t=fw({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=aw({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]=P_(e,s.shape,s.dtype,o);return r.makeTensorInfo(t,n,a)}if("int32"===o)return function(e,t){const n=new Dx(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=dw({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}`)}},gw=pw({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}),yw={kernelName:wn,backendName:"webgl",kernelFunc:gw};class bw{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=h_(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 _w{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=h_(r),s=t.map((e=>e[0])).join(","),o=t.map(((t,n)=>t[0]+e[n])).join(","),i=Ax("rc",r),u=Ax("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 xw{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 ww=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 xw(r,a),n=[[a]];return t.runWebGLProgram(e,[],s,n)}}({backend:n,attrs:{shape:e,value:o,dtype:a.dtype}})}const i=At().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new _w(a.shape,s,o):new bw(a.shape,s,o),u=[[o]];return n.runWebGLProgram(i,[a],a.dtype,u)},vw={kernelName:mr,backendName:"webgl",kernelFunc:ww};class kw{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 w=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 ${w}\n ${x}\n setOutput(result);\n }\n `}}class Iw{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=b_(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 Tw{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=b_(this.outputShape.length);const{dataFormat:n}=t,r=Qb(),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 Sw{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=b_(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 Ew{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Tu(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 Nw="return a * b;";function Aw(e){const{inputs:t,backend:n}=e,{a:r,b:a}=t,s=Ds(r.dtype,a.dtype);if("complex64"===r.dtype){const e=n.texData.get(r.dataId),t=n.texData.get(a.dataId),s=new Ew("return areal * breal - aimag * bimag;",r.shape,a.shape),o=new Ew("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=ow({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]=tx(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=At().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new uw(Nw,r.shape,a.shape):new iw(Nw,r.shape,a.shape),n.runWebGLProgram(o,[r,a],s)}const Cw={kernelName:ir,backendName:"webgl",kernelFunc:Aw};class Rw{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 Mw{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 Fw(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=kf(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 Rw({windowSize:u,inSize:i,batchSize:e.shape[0],outSize:l},i):new Rw({windowSize:u,inSize:i,batchSize:e.shape[0],outSize:l}):new Mw({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 $w{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=h_(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 Ow{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=h_(this.rank),a=Nx("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 Dw(e,t,n){const r=At().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ow(e.shape,t):new $w(e.shape,t);return n.runWebGLProgram(r,[e],e.dtype)}function Pw(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=Ac(i,s),l=null!=u;let c=e;l&&(c=Dw(e,u,r),i=Rc(i.length,s)),Nc("sum",i,s);const[p,h]=Sc(c.shape,i);let d=p;n&&(d=Ec(p,o));const f=et(h),m=Qx({inputs:{x:c},attrs:{shape:[et(e.shape)/f,f]},backend:r}),g=Fw(m,Ds(e.dtype,"int32"),"sum",r),y=Qx({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 Lw(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=Sx(e,a.shape,a.dtype,s,u);l=o.makeTensorInfo(u,a.dtype),o.texData.get(l.dataId).values=t}else l=Dw(a,s,o);return l}function Bw({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),_=Tu(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],w=r?[b,f,h]:[b,h,f],v=Qx({inputs:{x:e},backend:a,attrs:{shape:x}}),k=Qx({inputs:{x:t},backend:a,attrs:{shape:w}}),I=[v,k],T=Math.max(y,b),S=n?v.shape[1]:v.shape[2],E=null!=s,N=null!=o,A="leakyrelu"===u,C=null!=u?hw(u,!0):null;let R;if((1===d||1===f)&&S>1e3&&!1===(E||N||A||null!=C)){let e=v,t=k;n&&(e=Lw({inputs:{x:v},backend:a,attrs:{perm:[0,2,1]}}),I.push(e)),r&&(t=Lw({inputs:{x:k},backend:a,attrs:{perm:[0,2,1]}}),I.push(t));const s=1===f;let o=e;1!==f&&(o=Qx({inputs:{x:e},backend:a,attrs:{shape:[T,S,1]}}),I.push(o));const i=1===f?2:1;let u=t;s&&(u=Qx({inputs:{x:t},backend:a,attrs:{shape:[T,1,S]}}),I.push(u));const l=Aw({inputs:{a:o,b:u},backend:a});R=Pw({inputs:{x:l},backend:a,attrs:{axis:i,keepDims:!0}}),I.push(l)}else{const u=Ds(e.dtype,t.dtype),l=new Sw(x,w,[T,d,f],n,r,E,C,N,A),c=[v,k];if(null!=s&&c.push(s),N&&c.push(o),A){const e=a.makeTensorInfo([],"float32",ls(i,"float32"));c.push(e),I.push(e)}R=a.runWebGLProgram(l,c,u)}const M=Qx({inputs:{x:R},backend:a,attrs:{shape:_}});I.push(R);for(const e of I)a.disposeIntermediateTensorInfo(e);return M}function Uw(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 Ww({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=Uw(s.shape,d);null!=e&&(s=Qx({inputs:{x:s},backend:r,attrs:{shape:e}}),m.push(s))}if(null!=a){const e=Uw(a.shape,d);null!=e&&(a=Qx({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(Hb(l.shape,p.shape),(()=>`packed reshape ${l.shape} to ${p.shape} isn't free`));const d=Qx({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}});m.push(d);const g=Bw({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=aw({inputs:{x:g},backend:r}),f.shape=n.outShape,m.push(g)}else{const u=n.outHeight*n.outWidth,l=Qx({inputs:{x:e},backend:r,attrs:{shape:d?[n.batchSize,u,n.inChannels]:[n.batchSize,n.inChannels,u]}}),c=Qx({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}}),p=Bw({a:d?l:c,b:d?c:l,transposeA:!d,transposeB:!1,backend:r,bias:a,activation:i,preluActivationWeights:s,leakyreluAlpha:o});f=Qx({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 zw({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=Uw(s.shape,f);null!=e&&(s=Qx({inputs:{x:s},backend:r,attrs:{shape:e}}),b.push(s))}if(null!=a){const e=Uw(a.shape,f);null!=e&&(a=Qx({inputs:{x:a},backend:r,attrs:{shape:e}}),b.push(a))}const _=Qx({inputs:{x:t},backend:r,attrs:{shape:[1,m,et(t.shape)/m]}});b.push(_);const x=new Tw(y,n),w=[e.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],v=r.runWebGLProgram(x,[e],"float32",w),k=Qx({inputs:{x:v},backend:r,attrs:{shape:y}});b.push(v),b.push(k);const I=null!=a,T=null!=s,S="leakyrelu"===i,E=i?hw(i,!0):null,N=new Sw(f?k.shape:_.shape,f?_.shape:k.shape,f?[n.batchSize,g,n.outChannels]:[n.batchSize,n.outChannels,g],!0,!1,I,E,T,S),A=f?[k,_]:[_,k];if(a&&A.push(a),T&&A.push(s),S){const e=r.makeTensorInfo([],"float32",ls(o,"float32"));A.push(e),b.push(e)}const C=r.runWebGLProgram(N,A,"float32"),R=Qx({inputs:{x:C},backend:r,attrs:{shape:n.outShape}});b.push(C);for(const e of b)r.disposeIntermediateTensorInfo(e);return R}const Vw={kernelName:an,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=Tl(u),h=ml(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&&At().getBool("WEBGL_EXP_CONV")){const e=new Iw(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(At().getBool("WEBGL_CONV_IM2COL"))d=zw({x:a,filter:s,convInfo:h,backend:n});else{const e=new kw(h);d=n.runWebGLProgram(e,[a,s],"float32")}else d=Ww({x:a,filter:s,convInfo:h,backend:n});const f=Qx({inputs:{x:d},backend:n,attrs:{shape:h.outShape}});return n.disposeIntermediateTensorInfo(d),f}},Hw={kernelName:fa,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=Tl(c),g=ml(a.shape,s.shape,u,p,l,h,!1,m);let y;const b=[],_=null!=o,x=null!=i,w="leakyrelu"===d,v=()=>{const e=[a,s],t=(e,t)=>{if("NCHW"===t&&1===e.shape.length&&1!==e.shape[0]){const t=Qx({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)),w){const t=n.makeTensorInfo([],"float32",ls(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&&At().getBool("WEBGL_EXP_CONV")){const e=d?hw(d,!0):null,t=new Iw(g,_,e,x,w),r=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],a=v();y=n.runWebGLProgram(t,a,"float32",r)}else if(At().getBool("WEBGL_CONV_IM2COL"))y=zw({x:a,filter:s,convInfo:g,backend:n,bias:o,activation:d,preluActivationWeights:i,leakyreluAlpha:f});else{const e=d?hw(d,!1):null,t=new kw(g,_,e,x,w),r=v();y=n.runWebGLProgram(t,r,"float32")}else y=Ww({x:a,filter:s,convInfo:g,backend:n,bias:o,activation:d,preluActivationWeights:i,leakyreluAlpha:f});const k=Qx({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach((e=>n.disposeIntermediateTensorInfo(e))),k}};class Gw{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=b_(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 jw{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=b_(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 Kw={kernelName:ma,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(kl(u,m),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${u} and dilations '${m}'`));const g=ml(a.shape,s.shape,u,m,l,p,!0),y=At().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,b=h?hw(h,y):null,_=[a,s],x=null!=o,w=null!=i,v="leakyrelu"===h;if(x&&_.push(o),w&&_.push(i),v){const e=n.makeTensorInfo([],"float32",ls(d,"float32"));_.push(e),f.push(e)}let k;k=y?new jw(g,x,b,w,v):new Gw(g,x,b,w,v);const I=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],T=n.runWebGLProgram(k,_,"float32",I);return f.forEach((e=>n.disposeIntermediateTensorInfo(e))),T}},qw="return a + b;",Xw=pw({opSnippet:qw,packedOpSnippet:qw,supportsComplex:!0,cpuKernelImpl:F_}),Yw={kernelName:Dt,backendName:"webgl",kernelFunc:Xw},Qw={kernelName:zr,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=ww({inputs:{x:a},backend:n,attrs:{paddings:u,constantValue:0}}),p=Tf(c.shape,s,i,!1),h=Sf(p.length,s.length,!1),d=Ef(c.shape,s,i,!1),f=Qx({inputs:{x:c},backend:n,attrs:{shape:p}}),m=Lw({inputs:{x:f},backend:n,attrs:{perm:h}}),g=Qx({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}},Jw={kernelName:gn,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(kl(o,c),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`));const p=ml(a.shape,s.shape,o,c,i,l,!0);let h;h=At().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels==1?new jw(p):new Gw(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 Zw{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=h_(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const n=function(e){if(1===e)return"sourceLoc";if(e<=6)return ev.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.${ev[t]} = start[${t}] + coords.${ev[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 ev=["x","y","z","w","u","v"];class tv{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=h_(this.rank),n=Ax("coords",this.rank),r=Ax("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 nv(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,size:o}=r,[i,u]=Gu(a,s,o);if(Fu(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=dx(e.values,i,u,a.shape,a.dtype);return n.makeTensorInfo(u,a.dtype,t)}const{isPacked:l}=n.texData.get(a.dataId),c=Vu(a.shape,i,u);if(l||!c){const e=At().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new tv(u):new Zw(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=Hu(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 rv={kernelName:Or,backendName:"webgl",kernelFunc:nv},av={kernelName:Yt,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=Tf(a.shape,s,i),l=Sf(u.length,s.length),c=Ef(a.shape,s,i),p=Nf(o,s.length),h=Af(c,o,s.length),d=[],f=Qx({inputs:{x:a},backend:n,attrs:{shape:u}}),m=Lw({inputs:{x:f},backend:n,attrs:{perm:l}}),g=Qx({inputs:{x:m},backend:n,attrs:{shape:c}}),y=nv({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}},sv=cw({opSnippet:Px+"\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"}),ov={kernelName:Sr,backendName:"webgl",kernelFunc:sv};class iv{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const r=n.length,a=h_(n.length),s=h_(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 uv={kernelName:Qr,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}=ju(a.shape,s,o,i,u,l,c,p,h);let w;if(m)w=Qx({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=$u(b,_,x),t=nv({inputs:{x:a},backend:n,attrs:{begin:b,size:e}});w=Qx({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else if(n.shouldExecuteOnCPU([a])){const e=n.readSync(a.dataId),t=Gl(a.shape,a.dtype,e),r=_x(d,t,x,b);w=n.makeTensorInfo(f,a.dtype,r.values)}else{const e=new iv(b,x,d);w=n.runWebGLProgram(e,[a],a.dtype)}const v=Qx({inputs:{x:w},backend:n,attrs:{shape:f}});return n.disposeIntermediateTensorInfo(w),v}};class lv{constructor(e){this.outputShape=[],this.outputShape=yf(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 cv{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=yf(e,t);const n=this.outputShape,r=n.length,a=h_(r),s=Ax("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}(${pv(o,u,t)}),\n vec2(${pv(l,u,t)}));\n }`}const h=i.length,d=i[i.length-1];p+=`\n return getChannel(\n getT${h}(${pv(o,u,d)}),\n vec2(${pv(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 pv(e,t,n){const r=e.indexOf(t);return e.map(((e,t)=>t===r?`${e} - ${n}`:e)).join()}function hv(e,t,n){const r=e[0].dtype;if("complex64"===r){const r=e.map((e=>fw({inputs:{input:e},backend:n}))),a=e.map((e=>function(e){const{inputs:t,backend:n}=e,{input:r}=t;return aw({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.imag},backend:n})}({inputs:{input:e},backend:n}))),s=hv(r,t,n),o=hv(a,t,n),i=ow({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 Qx({inputs:{x:e},backend:n,attrs:{shape:[-1,r]}})})),s=a.map((e=>({vals:n.readSync(e.dataId),shape:e.shape}))),o=yf(a.map((e=>e.shape)),1),i=1===a[0].shape[0],u=B_(s,o,r,i),l=yf(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=At().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&s[0].shape.length>1;if(1===s.length){const t=o?new Dx(e[0].shape,Bx):new Ux(e[0].shape,Bx);return n.runWebGLProgram(t,e,r)}const i=At().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(hv(a,t,n))}const r=hv(e,t,n);for(const t of e)n.disposeIntermediateTensorInfo(t);return r}if(o){const e=new cv(s.map((e=>e.shape)),t);return n.runWebGLProgram(e,s,r)}const{tensors2D:u,outShape:l}=function(e,t,n){const r=yf(e.map((e=>e.shape)),t),a=e.map((e=>Qx({inputs:{x:e},attrs:{shape:[-1,et(e.shape.slice(t))]},backend:n})));return{tensors2D:a,outShape:r}}(s,t,n),c=new lv(u.map((e=>e.shape))),p=n.runWebGLProgram(c,u,r);u.forEach((e=>n.disposeIntermediateTensorInfo(e)));const h=Qx({inputs:{x:p},attrs:{shape:l},backend:n});return n.disposeIntermediateTensorInfo(p),h}function dv(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r,s=it(a,t[0].shape)[0];gf(t.map((e=>e.shape)),s);const o=yf(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?aw({inputs:{x:i[0]},backend:n}):hv(i,s,n)}const fv={kernelName:rn,backendName:"webgl",kernelFunc:dv},mv={kernelName:fr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return Zx({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=dv({inputs:t.map((e=>{const t=Zx({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 gv{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 `}}class yv{constructor(e){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=e.inShape,this.enableShapeUniforms=b_(this.outputShape.length);const t=e.filterHeight,n=e.filterWidth,r=t-1-e.padInfo.top,a=n-1-e.padInfo.left;this.userCode=`\n const ivec2 pads = ivec2(${r}, ${a});\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n\n ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n vec4 result = vec4(0.);\n for (int wR = 0; wR < ${t}; wR++) {\n float dyR = float(dyRCorner + wR) / strides[0];\n if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n int wRPerm = ${t} - 1 - wR;\n\n for (int wC = 0; wC < ${n}; wC++) {\n int wCPerm = ${n} - 1 - wC;\n\n float dyC = float(dyCCorner + wC) / strides[1];\n bool idyCVal = (dyC >= 0.0) && (dyC < ${e.outWidth}.0)\n && (fract(dyC) == 0.0);\n int idyC = int(dyC);\n\n float dyC2 = float(dyCCorner + wC + 1) / strides[1];\n bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${e.outWidth}.0)\n && (fract(dyC2) == 0.0);\n int idyC2 = int(dyC2);\n\n if (idyCVal && idyCVal2) {\n for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {\n vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\n vec4 dySample = getDy(batch, idyR, idyC, d2);\n vec4 dySample2 = (idyC / 2 == idyC2 / 2) ?\n dySample : getDy(batch, idyR, idyC2, d2);\n\n vec2 dyValue = mod(float(idyC), 2.) == 0. ?\n dySample.xy : dySample.zw;\n result.xy += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n\n dyValue = mod(float(idyC2), 2.) == 0. ?\n dySample2.xy : dySample2.zw;\n result.zw += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n }\n } else if (idyCVal) {\n for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {\n vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\n vec4 dySample = getDy(batch, idyR, idyC, d2);\n vec2 dyValue = mod(float(idyC), 2.) == 0. ?\n dySample.xy : dySample.zw;\n result.xy += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n }\n } else if (idyCVal2) {\n for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {\n vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\n vec4 dySample = getDy(batch, idyR, idyC2, d2);\n vec2 dyValue = mod(float(idyC2), 2.) == 0. ?\n dySample.xy : dySample.zw;\n result.zw += vec2(dot(dyValue, wValue.xy),\n dot(dyValue, wValue.zw));\n }\n }\n }\n }\n setOutput(result);\n }\n `}}const bv={kernelName:sn,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=Tl(l),h=ml(o,s.shape,i,1,u,c,!1,p);if(At().getBool("WEBGL_PACK_CONV2DTRANSPOSE")&&"channelsLast"===p){const e=[[h.strideHeight,h.strideWidth]],t=new yv(h);return n.runWebGLProgram(t,[a,s],"float32",e)}{const e=new gv(h);return n.runWebGLProgram(e,[a,s],"float32")}}},_v=cw({opSnippet:Px+"\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"}),xv={kernelName:xr,backendName:"webgl",kernelFunc:_v},wv=cw({opSnippet:lw+"\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:px}),vv={kernelName:Lr,backendName:"webgl",kernelFunc:wv};class kv{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 Iv={kernelName:dn,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 kv(a.shape,s.shape,i,u,l);return n.runWebGLProgram(c,[a,s,o],"float32")}};class Tv{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=h_(n);this.userCode=`\n void main() {\n ${a} coords = getOutputCoords();\n setOutput(getX(${r}));\n }\n `}}class Sv{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=Ax("rc",n),a=`${r[n-1]} + 1 < ${this.outputShape[n-1]}`,s=`${r[n-2]} + 1 < ${this.outputShape[n-2]}`,o=h_(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 Ev={kernelName:Er,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 aw({inputs:{x:a},backend:n});const u=At().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Sv(a.shape,i):new Tv(a.shape,i);return n.runWebGLProgram(u,[a],a.dtype)}},Nv="return a - b;",Av=pw({opSnippet:Nv,packedOpSnippet:Nv,supportsComplex:!0,cpuKernelImpl:kx}),Cv={kernelName:ta,backendName:"webgl",kernelFunc:Av},Rv={kernelName:ua,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=nv({inputs:{x:o},backend:n,attrs:{begin:h,size:d}}),r=Qx({inputs:{x:t},backend:n,attrs:{shape:l}});f[e]=r,p.push(t)}return p.forEach((e=>n.disposeIntermediateTensorInfo(e))),f}};class Mv{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 Fv{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=h_(i),l=Ax("coords",i);let c,p;if(1===s){p=i+1;const e=h_(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=Ax("sourceLocR",p-1).concat("inIdx.r"),g=Ax("sourceLocG",p-1).concat("inIdx.g"),y=Ax("sourceLocB",p-1).concat("inIdx.b"),b=Ax("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()})));`,w=`vec4(\n getAChannel(${m.join()}),\n hasNextCol ? getAChannel(${g.join()}) : 0.,\n hasNextRow ? getAChannel(${y.join()}) : 0.,\n hasNextRow && hasNextCol ? getAChannel(${b.join()}) : 0.)`,v=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 ${v}\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 = ${w};\n\n for (int i = 0; i < ${t}; i++) {\n inIdx = srcIdx;\n ${x}\n vec4 candidate = ${w};\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 $v(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=kf(s),i={windowSize:o,inSize:s,batchSize:a,outSize:Math.ceil(s/o)},u=new Mv(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=$v(e,t,n,c);return e.disposeIntermediateTensorInfo(c),p}function Ov(e,t,n,r=null){const a=null!=r?r.shape:t.shape,s=kf(a[a.length-1]),o=new Fv(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=Ov(e,t,n,u);return e.disposeIntermediateTensorInfo(u),r}return u}function Dv(e,t,n,r){const a=[n];if(Nc("arg"+r.charAt(0).toUpperCase()+r.slice(1),a,t.shape.length),!At().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]=Sc(o.shape,a),l=et(u),c=Qx({inputs:{x:o},backend:e,attrs:{shape:[-1,l]}});n.push(c);const p=$v(e,c,r);n.push(p);const h=Qx({inputs:{x:p},backend:e,attrs:{shape:i}});return n.forEach((t=>e.disposeIntermediateTensorInfo(t))),h}return Ov(e,t,r)}const Pv={kernelName:Ut,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=Ac(o,a.shape.length);let u=a;const l=[];null!=i&&(u=Lw({inputs:{x:a},backend:n,attrs:{perm:i}}),l.push(u),o=Rc(o.length,u.shape.length)),Nc("argMax",[o[0]],u.shape.length);const c=Dv(n,u,o[0],"max");return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}},Lv={kernelName:nr,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=Ac(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=Sx(e,r.shape,r.dtype,c,t);f=o.makeTensorInfo(t,r.dtype),o.texData.get(f.dataId).values=n}else f=Dw(r,c,o);d.push(f),l=Rc(l.length,i)}Nc("sum",l,i);const[m,g]=Sc(f.shape,l);let y=m;a&&(y=Ec(m,u));const b=function(e,t,n,r){const a=et(t),s=Qx({inputs:{x:e},attrs:{shape:[et(e.shape)/a,a]},backend:r}),o=Fw(s,"float32","mean",r),i=Qx({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}},Bv=cw({opSnippet:lw+"\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:W_,dtype:"float32"}),Uv={kernelName:Hr,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=Ac(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=Sx(e,a.shape,a.dtype,c,t);d=n.makeTensorInfo(t,a.dtype),n.texData.get(d.dataId).values=r}else d=Dw(a,c,n);l=Rc(l.length,i)}Nc("max",l,i);const[f,m]=Sc(d.shape,l);let g,y=f;if(o&&(y=Ec(f,u)),h){const e=n.texData.get(d.dataId).values,t=J_(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=Qx({inputs:{x:e},attrs:{shape:[et(e.shape)/a,a]},backend:r}),o=Fw(s,e.dtype,"max",r),i=Qx({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=Ec(i.shape,o),l=Qx({inputs:{x:i},backend:n,attrs:{shape:u}}),c=Av({inputs:{a,b:l},backend:n}),p=Bv({inputs:{x:c},backend:n}),h=Pw({inputs:{x:p},backend:n,attrs:{axis:o,keepDims:!1}}),d=Qx({inputs:{x:h},backend:n,attrs:{shape:u}}),f=gw({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 Wv{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 zv{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 Vv={kernelName:nn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{clipValueMin:s,clipValueMax:o}=r;let i;i=At().getBool("WEBGL_PACK_CLIP")?new zv(a.shape):new Wv(a.shape);const u=[[s],[o]];return n.runWebGLProgram(i,[a],a.dtype,u)}};class Hv{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,w=`\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 ${w}\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 ${w}\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 ${w}\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 ${w}\n }\n }\n setOutput(${b});\n }\n `}}const Gv={kernelName:Kt,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(kl(o,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '1'`));const l=dl(a.shape,s,o,1,i,u);if(1===l.filterWidth&&1===l.filterHeight&&tt(l.inShape,l.outShape))return aw({inputs:{x:a},backend:n});const c=new Hv(l,"avg",!1);return n.runWebGLProgram(c,[a],"float32")}},jv={kernelName:Xt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a,b:s}=t,{transposeA:o,transposeB:i}=r;return Bw({a,b:s,transposeA:o,transposeB:i,backend:n})}},Kv={kernelName:da,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 Bw({a,b:s,transposeA:u,transposeB:l,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:p,activation:c})}};va(Oy),va(Dy),va(Ig),va(By),va(Uy),va(zy),va(Yy),va(Zy),va(Cg),va(eb),va(Jy),va(tb),va(ey),va(qy),va(nb),va(ob),va(ib),va(jy),va(dy),va(xg),va(ub),va(lb),va(ab),va(Ay),va(cb),va(pb),va(db),va(gy),va(fb),va(gb),va(yb),va(bb),va(qx),va(Jx),va(ew),va(rw),va(mw),va(yw),va(vw),va(Vw),va(Hw),va(Kw),va(Yw),va(Qw),va(Jw),va(av),va(Cw),va(ov),va(uv),va(mv),va(bv),va(xv),va(vv),va(sw),va(Iv),va(Ev),va(fv),va(Cv),va(Rv),va(Pv),va(Lv),va(rv),va(Uv),va(Vv),va(Gv),va(jv),va(Kv);var qv={filename:""};function Xv(){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 Yv(n,null);if(g(n)&&Object.getPrototypeOf(n)===Object.prototype){var r=Object.keys(n);return Yv(r.map((function(e){return n[e]})),r)}}if("function"==typeof e[e.length-1]){var a=e.pop();return Yv(e=1===e.length&&m(e[0])?e[0]:e,null).pipe(K((function(e){return a.apply(void 0,e)})))}return Yv(e,null)}function Yv(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 Qv="undefined"!=typeof window&&window,Jv="undefined"!=typeof self&&"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&self,Zv=Qv||void 0!==_e&&_e||Jv;function ek(e,t){return void 0===t&&(t=null),new ik({method:"GET",url:e,headers:t})}function tk(e,t,n){return new ik({method:"POST",url:e,body:t,headers:n})}function nk(e,t){return new ik({method:"DELETE",url:e,headers:t})}function rk(e,t,n){return new ik({method:"PUT",url:e,body:t,headers:n})}function ak(e,t,n){return new ik({method:"PATCH",url:e,body:t,headers:n})}var sk=K((function(e,t){return e.response}));function ok(e,t){return sk(new ik({method:"GET",url:e,responseType:"json",headers:t}))}var ik=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 uk(e,this.request)},t.create=((n=function(e){return new t(e)}).get=ek,n.post=tk,n.delete=nk,n.put=rk,n.patch=ak,n.getJSON=ok,n),t}(S),uk=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 lk(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 hk(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 ck("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 ck("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}(v),lk=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=pk(this.responseType,t)},ck=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=pk(this.responseType,t),this}return e.prototype=Object.create(Error.prototype),e}();function pk(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 hk=function(e,t){return ck.call(this,"ajax timeout",e,t),this.name="AjaxTimeoutError",this},dk=ik.create,fk=Uint8Array,mk=Uint16Array,gk=Uint32Array,yk=new fk([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]),bk=new fk([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]),_k=new fk([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),xk=function(e,t){for(var n=new mk(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];var a=new gk(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]},wk=xk(yk,2),vk=wk[0],kk=wk[1];vk[28]=258,kk[258]=28;for(var Ik=xk(bk,0)[0],Tk=new mk(32768),Sk=0;Sk<32768;++Sk){var Ek=(43690&Sk)>>>1|(21845&Sk)<<1;Ek=(61680&(Ek=(52428&Ek)>>>2|(13107&Ek)<<2))>>>4|(3855&Ek)<<4,Tk[Sk]=((65280&Ek)>>>8|(255&Ek)<<8)>>>1}var Nk=function(e,t,n){for(var r=e.length,a=0,s=new mk(t);a<r;++a)++s[e[a]-1];var o,i=new mk(t);for(a=0;a<t;++a)i[a]=i[a-1]+s[a-1]<<1;if(n){o=new mk(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[Tk[p]>>>u]=l}else for(o=new mk(r),a=0;a<r;++a)e[a]&&(o[a]=Tk[i[e[a]-1]++]>>>15-e[a]);return o},Ak=new fk(288);for(Sk=0;Sk<144;++Sk)Ak[Sk]=8;for(Sk=144;Sk<256;++Sk)Ak[Sk]=9;for(Sk=256;Sk<280;++Sk)Ak[Sk]=7;for(Sk=280;Sk<288;++Sk)Ak[Sk]=8;var Ck=new fk(32);for(Sk=0;Sk<32;++Sk)Ck[Sk]=5;var Rk=Nk(Ak,9,1),Mk=Nk(Ck,5,1),Fk=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},$k=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(7&t)&n},Ok=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},Dk=function(e,t,n){(null==t||t<0)&&(t=0),(null==n||n>e.length)&&(n=e.length);var r=new(e instanceof mk?mk:e instanceof gk?gk:fk)(n-t);return r.set(e.subarray(t,n)),r},Pk=new fk(0),Lk=function(e,t){return e[t]|e[t+1]<<8},Bk=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},Uk=function(e,t){return Bk(e,t)+4294967296*Bk(e,t+4)};function Wk(e,t){return function(e,t,n){var r=e.length;if(!r||n&&!n.l&&r<5)return t||new fk(0);var a=!t||n,s=!n||n.i;n||(n={}),t||(t=new fk(3*r));var o,i=function(e){var n=t.length;if(e>n){var r=new fk(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=$k(e,l,1);var g=$k(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=Rk,h=Mk,d=9,f=5;else{if(2!=g)throw"invalid block type";var _=$k(e,l,31)+257,x=$k(e,l+10,15)+4,w=_+$k(e,l+5,31)+1;l+=14;for(var v=new fk(w),k=new fk(19),I=0;I<x;++I)k[_k[I]]=$k(e,l+3*I,7);l+=3*x;var T=Fk(k),S=(1<<T)-1,E=Nk(k,T,1);for(I=0;I<w;){var N,A=E[$k(e,l,S)];if(l+=15&A,(N=A>>>4)<16)v[I++]=N;else{var C=0,R=0;for(16==N?(R=3+$k(e,l,3),l+=2,C=v[I-1]):17==N?(R=3+$k(e,l,7),l+=3):18==N&&(R=11+$k(e,l,127),l+=7);R--;)v[I++]=C}}var M=v.subarray(0,_),F=v.subarray(_);d=Fk(M),f=Fk(F),p=Nk(M,d,1),h=Nk(F,f,1)}if(l>m){if(s)throw"unexpected EOF";break}}a&&i(c+131072);for(var $=(1<<d)-1,O=(1<<f)-1,D=l;;D=l){var P=(C=p[Ok(e,l)&$])>>>4;if((l+=15&C)>m){if(s)throw"unexpected EOF";break}if(!C)throw"invalid length/literal";if(P<256)t[c++]=P;else{if(256==P){D=l,p=null;break}var L=P-254;if(P>264){var B=yk[I=P-257];L=$k(e,l,(1<<B)-1)+vk[I],l+=B}var U=h[Ok(e,l)&O],W=U>>>4;if(!U)throw"invalid distance";if(l+=15&U,F=Ik[W],W>3&&(B=bk[W],F+=Ok(e,l)&(1<<B)-1,l+=B),l>m){if(s)throw"unexpected EOF";break}a&&i(c+131072);for(var z=c+L;c<z;c+=4)t[c]=t[c-F],t[c+1]=t[c+1-F],t[c+2]=t[c+2-F],t[c+3]=t[c+3-F];c=z}}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:Dk(t,0,c)}(e,t)}var zk="undefined"!=typeof TextDecoder&&new TextDecoder;try{zk.decode(Pk,{stream:!0})}catch(e){}function Vk(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(zk)return zk.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,Dk(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 Hk=function(e,t){return t+30+Lk(e,t+26)+Lk(e,t+28)},Gk=function(e,t,n){var r=Lk(e,t+28),a=Vk(e.subarray(t+46,t+46+r),!(2048&Lk(e,t+8))),s=t+46+r,o=Bk(e,t+20),i=n&&4294967295==o?jk(e,s):[o,Bk(e,t+24),Bk(e,t+42)],u=i[0],l=i[1],c=i[2];return[Lk(e,t+10),u,l,a,s+Lk(e,t+30)+Lk(e,t+32),c]},jk=function(e,t){for(;1!=Lk(e,t);t+=4+Lk(e,t+2));return[Uk(e,t+12),Uk(e,t+4),Uk(e,t+20)]};function Kk(e){for(var t={},n=e.length-22;101010256!=Bk(e,n);--n)if(!n||e.length-n>65558)throw"invalid zip file";var r=Lk(e,n+8);if(!r)return{};var a=Bk(e,n+16),s=4294967295==a;if(s){if(n=Bk(e,n-12),101075792!=Bk(e,n))throw"invalid zip file";r=Bk(e,n+32),a=Bk(e,n+48)}for(var o=0;o<r;++o){var i=Gk(e,a,s),u=i[0],l=i[1],c=i[2],p=i[3],h=i[4],d=i[5],f=Hk(e,d);if(a=h,u){if(8!=u)throw"unknown compression type "+u;t[p]=Wk(e.subarray(f,f+l),new fk(c))}else t[p]=Dk(e,f,f+l)}return t}function qk(e){if(e)for(var t=0;t<e.length;t++)e[t]=~e[t];return e}var Xk=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}(),Yk=[],Qk=[],Jk="undefined"!=typeof Uint8Array?Uint8Array:Array,Zk=!1;function eI(){Zk=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0;t<64;++t)Yk[t]=e[t],Qk[e.charCodeAt(t)]=t;Qk["-".charCodeAt(0)]=62,Qk["_".charCodeAt(0)]=63}function tI(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(Yk[(a=r)>>18&63]+Yk[a>>12&63]+Yk[a>>6&63]+Yk[63&a]);return s.join("")}function nI(e){var t;Zk||eI();for(var n=e.length,r=n%3,a="",s=[],o=16383,i=0,u=n-r;i<u;i+=o)s.push(tI(e,i,i+o>u?u:i+o));return 1===r?(t=e[n-1],a+=Yk[t>>2],a+=Yk[t<<4&63],a+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],a+=Yk[t>>10],a+=Yk[t>>4&63],a+=Yk[t<<2&63],a+="="),s.push(a),s.join("")}function rI(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 aI(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 sI={}.toString,oI=Array.isArray||function(e){return"[object Array]"==sI.call(e)};function iI(){return lI.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function uI(e,t){if(iI()<t)throw new RangeError("Invalid typed array length");return lI.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=lI.prototype:(null===e&&(e=new lI(t)),e.length=t),e}function lI(e,t,n){if(!(lI.TYPED_ARRAY_SUPPORT||this instanceof lI))return new lI(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 hI(this,e)}return cI(this,e,t,n)}function cI(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),lI.TYPED_ARRAY_SUPPORT?(e=t).__proto__=lI.prototype:e=dI(e,t),e}(e,t,n,r):"string"==typeof t?function(e,t,n){if("string"==typeof n&&""!==n||(n="utf8"),!lI.isEncoding(n))throw new TypeError('"encoding" must be a valid string encoding');var r=0|gI(t,n),a=(e=uI(e,r)).write(t,n);return a!==r&&(e=e.slice(0,a)),e}(e,t,n):function(e,t){if(mI(t)){var n=0|fI(t.length);return 0===(e=uI(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?uI(e,0):dI(e,t);if("Buffer"===t.type&&oI(t.data))return dI(e,t.data)}var r;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function pI(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 hI(e,t){if(pI(t),e=uI(e,t<0?0:0|fI(t)),!lI.TYPED_ARRAY_SUPPORT)for(var n=0;n<t;++n)e[n]=0;return e}function dI(e,t){var n=t.length<0?0:0|fI(t.length);e=uI(e,n);for(var r=0;r<n;r+=1)e[r]=255&t[r];return e}function fI(e){if(e>=iI())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+iI().toString(16)+" bytes");return 0|e}function mI(e){return!(null==e||!e._isBuffer)}function gI(e,t){if(mI(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 VI(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return HI(e).length;default:if(r)return VI(e).length;t=(""+t).toLowerCase(),r=!0}}function yI(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 MI(this,t,n);case"utf8":case"utf-8":return NI(this,t,n);case"ascii":return CI(this,t,n);case"latin1":case"binary":return RI(this,t,n);case"base64":return EI(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return FI(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function bI(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function _I(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=lI.from(t,r)),mI(t))return 0===t.length?-1:xI(e,t,n,r,a);if("number"==typeof t)return t&=255,lI.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):xI(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function xI(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 wI(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 vI(e,t,n,r){return GI(VI(t,e.length-n),e,n,r)}function kI(e,t,n,r){return GI(function(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function II(e,t,n,r){return kI(e,t,n,r)}function TI(e,t,n,r){return GI(HI(t),e,n,r)}function SI(e,t,n,r){return GI(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 EI(e,t,n){return 0===t&&n===e.length?nI(e):nI(e.slice(t,n))}function NI(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<=AI)return String.fromCharCode.apply(String,e);for(var n="",r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=AI));return n}(r)}lI.TYPED_ARRAY_SUPPORT=void 0===_e.TYPED_ARRAY_SUPPORT||_e.TYPED_ARRAY_SUPPORT,iI(),lI.poolSize=8192,lI._augment=function(e){return e.__proto__=lI.prototype,e},lI.from=function(e,t,n){return cI(null,e,t,n)},lI.TYPED_ARRAY_SUPPORT&&(lI.prototype.__proto__=Uint8Array.prototype,lI.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&lI[Symbol.species]),lI.alloc=function(e,t,n){return function(e,t,n,r){return pI(t),t<=0?uI(e,t):void 0!==n?"string"==typeof r?uI(e,t).fill(n,r):uI(e,t).fill(n):uI(e,t)}(null,e,t,n)},lI.allocUnsafe=function(e){return hI(null,e)},lI.allocUnsafeSlow=function(e){return hI(null,e)},lI.isBuffer=function(e){return null!=e&&(!!e._isBuffer||jI(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&jI(e.slice(0,0))}(e))},lI.compare=function(e,t){if(!mI(e)||!mI(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},lI.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}},lI.concat=function(e,t){if(!oI(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return lI.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=lI.allocUnsafe(t),a=0;for(n=0;n<e.length;++n){var s=e[n];if(!mI(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(r,a),a+=s.length}return r},lI.byteLength=gI,lI.prototype._isBuffer=!0,lI.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)bI(this,t,t+1);return this},lI.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)bI(this,t,t+3),bI(this,t+1,t+2);return this},lI.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)bI(this,t,t+7),bI(this,t+1,t+6),bI(this,t+2,t+5),bI(this,t+3,t+4);return this},lI.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?NI(this,0,e):yI.apply(this,arguments)},lI.prototype.equals=function(e){if(!mI(e))throw new TypeError("Argument must be a Buffer");return this===e||0===lI.compare(this,e)},lI.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+">"},lI.prototype.compare=function(e,t,n,r,a){if(!mI(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},lI.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},lI.prototype.indexOf=function(e,t,n){return _I(this,e,t,n,!0)},lI.prototype.lastIndexOf=function(e,t,n){return _I(this,e,t,n,!1)},lI.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 wI(this,e,t,n);case"utf8":case"utf-8":return vI(this,e,t,n);case"ascii":return kI(this,e,t,n);case"latin1":case"binary":return II(this,e,t,n);case"base64":return TI(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return SI(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},lI.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var AI=4096;function CI(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 RI(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 MI(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+=zI(e[s]);return a}function FI(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 $I(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 OI(e,t,n,r,a,s){if(!mI(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 DI(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 PI(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 LI(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 BI(e,t,n,r,a){return a||LI(e,0,n,4),aI(e,t,n,r,23,4),n+4}function UI(e,t,n,r,a){return a||LI(e,0,n,8),aI(e,t,n,r,52,8),n+8}lI.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),lI.TYPED_ARRAY_SUPPORT)(n=this.subarray(e,t)).__proto__=lI.prototype;else{var a=t-e;n=new lI(a,void 0);for(var s=0;s<a;++s)n[s]=this[s+e]}return n},lI.prototype.readUIntLE=function(e,t,n){e|=0,t|=0,n||$I(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r},lI.prototype.readUIntBE=function(e,t,n){e|=0,t|=0,n||$I(e,t,this.length);for(var r=this[e+--t],a=1;t>0&&(a*=256);)r+=this[e+--t]*a;return r},lI.prototype.readUInt8=function(e,t){return t||$I(e,1,this.length),this[e]},lI.prototype.readUInt16LE=function(e,t){return t||$I(e,2,this.length),this[e]|this[e+1]<<8},lI.prototype.readUInt16BE=function(e,t){return t||$I(e,2,this.length),this[e]<<8|this[e+1]},lI.prototype.readUInt32LE=function(e,t){return t||$I(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},lI.prototype.readUInt32BE=function(e,t){return t||$I(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},lI.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||$I(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},lI.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||$I(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},lI.prototype.readInt8=function(e,t){return t||$I(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},lI.prototype.readInt16LE=function(e,t){t||$I(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},lI.prototype.readInt16BE=function(e,t){t||$I(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},lI.prototype.readInt32LE=function(e,t){return t||$I(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},lI.prototype.readInt32BE=function(e,t){return t||$I(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},lI.prototype.readFloatLE=function(e,t){return t||$I(e,4,this.length),rI(this,e,!0,23,4)},lI.prototype.readFloatBE=function(e,t){return t||$I(e,4,this.length),rI(this,e,!1,23,4)},lI.prototype.readDoubleLE=function(e,t){return t||$I(e,8,this.length),rI(this,e,!0,52,8)},lI.prototype.readDoubleBE=function(e,t){return t||$I(e,8,this.length),rI(this,e,!1,52,8)},lI.prototype.writeUIntLE=function(e,t,n,r){e=+e,t|=0,n|=0,r||OI(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},lI.prototype.writeUIntBE=function(e,t,n,r){e=+e,t|=0,n|=0,r||OI(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},lI.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||OI(this,e,t,1,255,0),lI.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},lI.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||OI(this,e,t,2,65535,0),lI.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):DI(this,e,t,!0),t+2},lI.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||OI(this,e,t,2,65535,0),lI.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):DI(this,e,t,!1),t+2},lI.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||OI(this,e,t,4,4294967295,0),lI.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):PI(this,e,t,!0),t+4},lI.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||OI(this,e,t,4,4294967295,0),lI.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):PI(this,e,t,!1),t+4},lI.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);OI(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},lI.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);OI(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},lI.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||OI(this,e,t,1,127,-128),lI.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},lI.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||OI(this,e,t,2,32767,-32768),lI.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):DI(this,e,t,!0),t+2},lI.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||OI(this,e,t,2,32767,-32768),lI.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):DI(this,e,t,!1),t+2},lI.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||OI(this,e,t,4,2147483647,-2147483648),lI.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):PI(this,e,t,!0),t+4},lI.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||OI(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),lI.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):PI(this,e,t,!1),t+4},lI.prototype.writeFloatLE=function(e,t,n){return BI(this,e,t,!0,n)},lI.prototype.writeFloatBE=function(e,t,n){return BI(this,e,t,!1,n)},lI.prototype.writeDoubleLE=function(e,t,n){return UI(this,e,t,!0,n)},lI.prototype.writeDoubleBE=function(e,t,n){return UI(this,e,t,!1,n)},lI.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||!lI.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},lI.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&&!lI.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=mI(e)?e:VI(new lI(e,r).toString()),i=o.length;for(s=0;s<n-t;++s)this[s+t]=o[s%i]}return this};var WI=/[^+\/0-9A-Za-z-_]/g;function zI(e){return e<16?"0"+e.toString(16):e.toString(16)}function VI(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 HI(e){return function(e){var t,n,r,a,s,o;Zk||eI();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 Jk(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=Qk[e.charCodeAt(t)]<<18|Qk[e.charCodeAt(t+1)]<<12|Qk[e.charCodeAt(t+2)]<<6|Qk[e.charCodeAt(t+3)],o[u++]=a>>16&255,o[u++]=a>>8&255,o[u++]=255&a;return 2===s?(a=Qk[e.charCodeAt(t)]<<2|Qk[e.charCodeAt(t+1)]>>4,o[u++]=255&a):1===s&&(a=Qk[e.charCodeAt(t)]<<10|Qk[e.charCodeAt(t+1)]<<4|Qk[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(WI,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function GI(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 jI(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function KI(e,t){var n=new ie(0),r=new ie(0),a=new ie(0),s=new ie(0),o=z([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 dk({url:e,method:"GET",responseType:"arraybuffer",async:!0,progressSubscriber:new v((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 qI(e.response)})),pe((function(e){return XI(e,t,r).pipe(K((function(t){return{jszip:e,config:t}})))})),pe((function(e){var t=e.jszip,n=e.config;return YI(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 QI(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(hg(new Xk(n,r))).pipe(K((function(e){return{config:t,graphModel:e}})))})));return{model$:i,progress$:o}}return i=qI(e).pipe(pe((function(e){return XI(e,t,r).pipe(K((function(t){return{jszip:e,config:t}})))})),pe((function(e){var t=e.jszip,n=e.config;return YI(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 QI(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(hg(new Xk(n,r))).pipe(K((function(e){return{config:t,graphModel:e}})))}))),{model$:i,progress$:o}}function qI(e){return j(Kk(new Uint8Array(e)))}function XI(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(Vk(qk(e[t])))):j(JSON.parse(Vk(e[t])))})):Q("Unable to retrieve model config: ".concat(t," is missing"))}function YI(e,t,n){return t?e[t.filename]?be((function(){return n.next(1),j(JSON.parse(Vk(qk(e[t.filename]))))})):Q("Error extracting model: ".concat(t.filename," is missing")):Q("Invalid model config")}function QI(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(qk(lI.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 Xv(u)}Rt.set("DEPRECATION_WARNINGS_ENABLED",!1),Rt.global.Math=Math,Rt.global.Float32Array=Float32Array,At().set("WEBGL_FORCE_F16_TEXTURES",!0);var JI,ZI,eT,tT=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({},qv),n):qv,a=KI(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=kp([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=kp([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=Nu(t),a=cf.resizeBilinear(r,[this._modelConfig.inHeight,this._modelConfig.inWidth]),s=gu(a,"float32"),o=El(s,[1,this._modelConfig.inHeight,this._modelConfig.inWidth,3]),i=Oc(255);if(4==this._modelConfig.inChannels){var u=El(this._cnnOutput,[1,this._modelConfig.inHeight,this._modelConfig.inWidth,1]),l=Qu(o,i);n=Rl([l,u],3),l.dispose(),u.dispose()}else n=Qu(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=Fh(c);this._cnnOutput=Fl(d,[0,0,0,1],[-1,-1,-1,1]),d.dispose(),this._cnnOutputData=this._cnnOutput.dataSync()}else this._cnnOutput=ql(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}(),nT=(JI="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),JI&&(o=JI),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&&$("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 w(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 v(e){return e?w(d,e):""}function k(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 I(){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 T=[],S=[],E=[];function N(){var e=t.preRun.shift();T.unshift(e)}var A,C,R,M=0,F=null;function $(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 A.startsWith("data:application/octet-stream;base64,")}if(A="libxzimgPoseEstimation.wasm",!O()){var D=A;A=t.locateFile?t.locateFile(D,o):o+D}function P(){var e=A;try{if(e==A&&i)return new Uint8Array(i);throw"both async and sync fetching of the wasm failed"}catch(e){$(e)}}function L(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},W=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},z=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):"."},V=e=>{if("/"===e)return"/";var t=(e=(e=W(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=k(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},we(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(w(e.m,0)),e.m=[]):0!=t&&e.m.push(t)},M:function(e){e.m&&0<e.m.length&&(u(w(e.m,0)),e.m=[])}},ee={V:function(e,t){null===t||10===t?(l(w(e.m,0)),e.m=[]):0!=t&&e.m.push(t)},M:function(e){e.m&&0<e.m.length&&(l(w(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,$(),!(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=W(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(z(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 ze(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)}},we=(e,t)=>{re[e]={i:t}},ve=(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))},ke=(e,t,n)=>{var r=ce(e,{parent:!0}).node;if(!(e=V(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)},Ie=(e,t,n)=>{void 0===n&&(n=t,t=438),ke(e,8192|t,n)},Te=(e,t)=>{if(!H(e))throw new ue(44);var n=ce(t,{parent:!0}).node;if(!n)throw new ue(44);t=V(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=W(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=ke(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=[]},Ae=()=>{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>"})))},Ce=(e,t,n)=>{e=W("/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;we(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}}),Ie(e,r,a)},Re={},Me=void 0;function Fe(){return m[(Me+=4)-4>>2]}function $e(e){if(!(e=ae[e]))throw new ue(8);return e}var Oe,De={};function Pe(){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 Le(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 We(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),k(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?v(o):"boolean"===n?!!o:o}function ze(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(ze.prototype,{read:{get:function(){return!(365&~this.mode)},set:function(e){e?this.mode|=365:this.mode&=-366}},write:{get:function(){return!(146&~this.mode)},set:function(e){e?this.mode|=146:this.mode&=-147}}}),Ae(),oe=Array(4096),ve(te,"/"),ke("/tmp",16895,0),ke("/home",16895,0),ke("/home/web_user",16895,0),(()=>{ke("/dev",16895,0),we(259,{read:()=>0,write:(e,t,n,r)=>r}),Ie("/dev/null",259),K(1280,Z),K(1536,ee),Ie("/dev/tty",1280),Ie("/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()=>$("randomDevice")}();Ce("random",e),Ce("urandom",e),ke("/dev/shm",16895,0),ke("/dev/shm/tmp",16895,0)})(),(()=>{ke("/proc",16895,0);var e=ke("/proc/self",16895,0);ke("/proc/self/fd",16895,0),ve({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 Ve={__assert_fail:function(e,t,n,r){$("Assertion failed: "+v(e)+", at: "+[t?v(t):"unknown filename",n,r?v(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){Me=n;try{var r=$e(e);switch(t){case 0:var a=Fe();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=Fe(),r.flags|=a,0;case 5:return a=Fe(),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){Me=n;try{var r=$e(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=Fe();return m[a>>2]=0;case 21520:return r.l?-28:-59;case 21531:if(e=a=Fe(),!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){Me=r;try{var a=t=v(t);if("/"===a.charAt(0))t=a;else{var s=-100===e?"/":$e(e).path;if(0==a.length)throw new ue(44);t=W(s+"/"+a)}var o=r?Fe():0;return Ee(t,n,o).A}catch(e){if(void 0===Re||!(e instanceof ue))throw e;return-e.C}},abort:function(){$("")},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),I();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 Pe().forEach((function(r,a){var s=t+n;for(a=g[e+4*a>>2]=s,s=0;s<r.length;++s)h[0|a++]=r.charCodeAt(s);h[0|a]=0,n+=r.length+1})),0},environ_sizes_get:function(e,t){var n=Pe();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=$e(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=$e(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=$e(e);return Ne(s,t,r),R=[s.position>>>0,(C=s.position,1<=+Math.abs(C)?0<C?(0|Math.min(+Math.floor(C/4294967296),4294967295))>>>0:~~+Math.ceil((C-+(~~C>>>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=$e(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(!(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=(Le(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?v(l):""},n=v(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+=(Le(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&&Le(e.H)||(t=1));else{t=52;var n=(e.u+7-e.G-1)%7;(4==n||5==n&&Le(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,I(),S.unshift(t.asm.__wasm_call_ctors),M--,t.monitorRunDependencies&&t.monitorRunDependencies(M),0==M&&F&&(e=F,F=null,e())}function n(t){e(t.instance)}function a(e){return(i||"function"!=typeof fetch?Promise.resolve().then((function(){return P()})):fetch(A,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+A+"'";return e.arrayBuffer()})).catch((function(){return P()}))).then((function(e){return WebAssembly.instantiate(e,s)})).then((function(e){return e})).then(e,(function(e){l("failed to asynchronously prepare wasm: "+e),$(e)}))}var s={env:Ve,wasi_snapshot_preview1:Ve};if(M++,t.monitorRunDependencies&&t.monitorRunDependencies(M),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(A,{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,Ae(),t.stdin=t.stdin,t.stdout=t.stdout,t.stderr=t.stderr,t.stdin?Ce("stdin",t.stdin):Te("/dev/tty","/dev/stdin"),t.stdout?Ce("stdout",null,t.stdout):Te("/dev/tty","/dev/stdout"),t.stderr?Ce("stderr",null,t.stderr):Te("/dev/tty1","/dev/stderr"),Ee("/dev/stdin",0),Ee("/dev/stdout",1),Ee("/dev/stderr",1)),ie=!1,L(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)}L(E)}}if(!(0<M)){if(t.preRun)for("function"==typeof t.preRun&&(t.preRun=[t.preRun]);t.preRun.length;)N();L(T),0<M||(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=We,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 We(e,n,r,arguments)}},t.setValue=function(e,t,n="i8"){switch(n.endsWith("*")&&(n="*"),n){case"i1":case"i8":h[0|e]=t;break;case"i16":f[e>>1]=t;break;case"i32":m[e>>2]=t;break;case"i64":R=[t>>>0,(C=t,1<=+Math.abs(C)?0<C?(0|Math.min(+Math.floor(C/4294967296),4294967295))>>>0:~~+Math.ceil((C-+(~~C>>>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:$("invalid type for setValue: "+n)}},t.getValue=function(e,t="i8"){switch(t.endsWith("*")&&(t="*"),t){case"i1":case"i8":return h[0|e];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:$("invalid type for getValue: "+t)}return null},F=function e(){Ge||Ye(),Ge||(F=e)},t.preInit)for("function"==typeof t.preInit&&(t.preInit=[t.preInit]);0<t.preInit.length;)t.preInit.pop()();return Ye(),e.ready});let rT;!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"}(ZI||(ZI={})),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"}(eT||(eT={}));const aT={kernelName:da,backendName:"wasm",setupFunc:function(e){rT=e.wasm.cwrap(da,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=eT[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],_=Tu(a.shape.slice(0,-2),s.shape.slice(0,-2)),x=n.makeOutput([..._,y,b],a.dtype),w=n.dataIdMap.get(x.dataId).id,v=new Uint8Array(new Int32Array(a.shape).buffer),k=new Uint8Array(new Int32Array(s.shape).buffer);return rT(h,v,a.shape.length,d,k,s.shape.length,u,l,g,f,m,p||0,w),x}};function sT(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,ZI[a.dtype],i),o}}}const oT=sT("Abs"),iT=sT($t),uT=sT(Ot);function lT(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=Tu(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,ZI[s.dtype],f),p}}}const cT=lT(Dt);let pT;const hT={kernelName:Pt,backendName:"wasm",setupFunc:function(e){pT=e.wasm.cwrap(Pt,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 pT(s,a.length,ZI[r.dtype],o),r}};function dT(e){const{inputs:{x:t},backend:n}=e;if("string"===t.dtype)return ai(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 fT={kernelName:Pn,backendName:"wasm",kernelFunc:dT};let mT;function gT(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=dT({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 mT(c,d,u.shape.length,ZI[u.dtype],p,h,s.length),l}const yT={kernelName:oa,backendName:"wasm",kernelFunc:gT,setupFunc:function(e){mT=e.wasm.cwrap(oa,null,["number","array","number","number","number","array","number"])}};function bT(e,t,n){const r=e.shape,a=e.shape.length,s=it(t,r);let o=s;const i=Ac(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=Rc(o.length,a),u=gT({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 _T;const xT={kernelName:Lt,backendName:"wasm",setupFunc:function(e){_T=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}=bT(o,a,t);h&&(u=l,i=t.dataIdMap.get(l.dataId).id),Nc("all",c,u.shape.length);const[d,f]=Sc(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;_T(i,m,e)}if(h&&t.disposeData(l.dataId),s){const e=Ec(g.shape,p);g.shape=e}return g}};let wT;const vT={kernelName:Bt,backendName:"wasm",setupFunc:function(e){wT=e.wasm.cwrap(Bt,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}=bT(o,a,t);h&&(u=l,i=t.dataIdMap.get(l.dataId).id),Nc("any",c,u.shape.length);const[d,f]=Sc(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;wT(i,m,e)}if(h&&t.disposeData(l.dataId),s){const e=Ec(g.shape,p);g.shape=e}return g}};function kT(e){let t;return{kernelName:e,backendName:"wasm",setupFunc:function(n){t=n.wasm.cwrap(e,null,["number","number","number","number","number"])},kernelFunc:function(e){const{backend:n,inputs:r,attrs:a}=e,{axis:s}=a,{x:o}=r,i=n.dataIdMap.get(o.dataId).id;let u=i,l=o;const{transposed:c,axes:p,inputWasTransposed:h}=bT(o,s,n);if(h){const e=n.dataIdMap.get(c.dataId).id;e!==i&&(l=c,u=e)}const d=l.shape.slice(0,-1),f=n.makeOutput(d,"int32"),m=n.dataIdMap.get(f.dataId).id,g=et(f.shape),y=l.shape[p[0]];return t(u,ZI[l.dtype],g,y,m),h&&n.disposeData(c.dataId),f}}}const IT=kT(Ut),TT=kT(Wt),ST=sT(zt),ET=sT(Vt),NT=sT(Ht),AT=lT(jt),CT=sT(Gt);let RT;const MT={kernelName:Kt,backendName:"wasm",setupFunc:function(e){RT=e.wasm.cwrap(Kt,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=dl(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"),w=r.dataIdMap.get(x.dataId).id;return RT(s,a.shape[0],a.shape[1],a.shape[2],p,h,d,f,m,g,y,b,_,w),x}};let FT;const $T={kernelName:qt,backendName:"wasm",setupFunc:function(e){FT=e.wasm.cwrap("AvgPool3D",null,["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,backend:n,attrs:r}=e,{x:a}=t,{filterSize:s,strides:o,pad:i,dimRoundingMode:u,dataFormat:l}=r,c=fl(a.shape,s,o,1,i,u,l),p=n.makeOutput(c.outShape,a.dtype);return FT(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(p.dataId).id,c.batchSize,c.inChannels,c.inDepth,c.inHeight,c.inWidth,c.outDepth,c.outHeight,c.outWidth,c.strideDepth,c.strideHeight,c.strideWidth,c.dilationDepth,c.dilationHeight,c.dilationWidth,c.effectiveFilterDepth,c.effectiveFilterHeight,c.effectiveFilterWidth,c.padInfo.front,c.padInfo.top,c.padInfo.left),p}};let OT;const DT={kernelName:"AvgPool3DGrad",backendName:"wasm",setupFunc:function(e){OT=e.wasm.cwrap("AvgPool3DGrad",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"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,{filterSize:o,strides:i,pad:u,dimRoundingMode:l}=r,c=fl(s.shape,o,i,1,u,l),p=n.makeOutput(s.shape,s.dtype);return OT(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(p.dataId).id,c.batchSize,c.inChannels,c.inDepth,c.inHeight,c.inWidth,c.outDepth,c.outHeight,c.outWidth,c.strideDepth,c.strideHeight,c.strideWidth,c.dilationDepth,c.dilationHeight,c.dilationWidth,c.effectiveFilterDepth,c.effectiveFilterHeight,c.effectiveFilterWidth,c.padInfo.front,c.padInfo.top,c.padInfo.left,c.filterDepth,c.filterHeight,c.filterWidth),p}};let PT;const LT={kernelName:"AvgPoolGrad",backendName:"wasm",setupFunc:function(e){PT=e.wasm.cwrap("AvgPoolGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,{filterSize:o,strides:i,pad:u}=r,l=dl(s.shape,o,i,1,u),c=n.makeOutput(s.shape,s.dtype);return PT(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(c.dataId).id,l.batchSize,l.inChannels,l.inHeight,l.inWidth,l.outHeight,l.outWidth,l.strideHeight,l.strideWidth,l.dilationHeight,l.dilationWidth,l.effectiveFilterHeight,l.effectiveFilterWidth,l.padInfo.top,l.padInfo.left,l.filterHeight,l.filterWidth),c}};function BT(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 UT={kernelName:wr,backendName:"wasm",kernelFunc:BT};let WT;const zT={kernelName:Xt,backendName:"wasm",setupFunc:function(e){WT=e.wasm.cwrap(Xt,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=Tu(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=BT({inputs:{x:a},backend:n,attrs:{shape:o?[g,c,h]:[g,h,c]}}),w=BT({inputs:{x:s},backend:n,attrs:{shape:_}}),v=n.dataIdMap.get(x.dataId).id,k=n.dataIdMap.get(w.dataId).id,I=o?x.shape[2]:x.shape[1],T=i?w.shape[1]:w.shape[2],S=Math.max(g,y),E=n.makeOutput([S,I,T],x.dtype),N=n.dataIdMap.get(E.dataId).id,A=new Uint8Array(new Int32Array(x.shape).buffer),C=new Uint8Array(new Int32Array(w.shape).buffer);return WT(v,A,x.shape.length,k,C,w.shape.length,o,i,N),n.disposeData(x.dataId),n.disposeData(w.dataId),E.shape=b,E}};function VT(e){const{inputs:{x:t},attrs:{begin:n,size:r},backend:a}=e,[s,o]=Gu(t,n,r),i=Vu(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=Hu(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=fy(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=fy(u,s,o,t.shape,t.dtype);h.set(e)}return l}const HT={kernelName:Or,backendName:"wasm",kernelFunc:VT},GT={kernelName:Yt,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=Tf(a.shape,s,i),l=Sf(u.length,s.length),c=Ef(a.shape,s,i),p=Nf(o,s.length),h=Af(c,o,s.length),d=BT({inputs:{x:a},backend:n,attrs:{shape:u}}),f=gT({inputs:{x:d},backend:n,attrs:{perm:l}}),m=BT({inputs:{x:f},backend:n,attrs:{shape:c}}),g=VT({inputs:{x:m},backend:n,attrs:{begin:p,size:h}});return n.disposeData(d.dataId),n.disposeData(f.dataId),n.disposeData(m.dataId),g}};let jT;const KT={kernelName:Qt,backendName:"wasm",setupFunc:function(e){jT=e.wasm.cwrap(Qt,null,["number","number","boolean","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{x:a,weights:s}=n,{size:o}=r,i=0!==s.shape.reduce(((e,t)=>e*t),1),u=1===a.shape.length?[o]:[a.shape[0],o],l=t.makeOutput(u,s.dtype);function c(e){return t.dataIdMap.get(e.dataId).id}return jT(c(a),o,i,c(s),ZI[s.dtype],c(l)),l}},qT=lT(Jt),XT={kernelName:Zt,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n}=e,{s0:r,s1:a}=t,s=n.typedArrayFromHeap(r),o=n.typedArrayFromHeap(a),i=Tu(Array.from(s),Array.from(o));return n.makeOutput([i.length],"int32",void 0,new Int32Array(i))}};function YT(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 QT={kernelName:en,backendName:"wasm",kernelFunc:YT},JT=sT(tn);let ZT;const eS={kernelName:nn,backendName:"wasm",setupFunc:function(e){ZT=e.wasm.cwrap(nn,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 ZT(i,s,o,l),u}};function tS(e){const{inputs:t,backend:n}=e,r=it(e.attrs.axis,t[0].shape)[0];gf(t.map((e=>e.shape)),r);let a=yf(t.map((e=>e.shape)),r);const s=t.filter((e=>et(e.shape)>0));if(1===s.length)return dT({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 BT({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),i=e.map((e=>({vals:n.readSync(e.dataId),shape:e.shape})));a=yf(e.map((e=>e.shape)),1);const u=1===e[0].shape[0],l=Dg(i,a,t[0].dtype,u),c=yf(s.map((e=>e.shape)),r);return o.shape=c,n.dataIdMap.get(o.dataId).stringBytes=jf(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 nS={kernelName:rn,backendName:"wasm",kernelFunc:tS};let rS;const aS={kernelName:an,backendName:"wasm",setupFunc:function(e){rS=e.wasm.cwrap(an,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=Tl(h),f=ml(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,w=f.dilationHeight,v=f.dilationWidth,k=f.strideHeight,I=f.strideWidth,T=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"),A=r.dataIdMap.get(N.dataId).id;return rS(o,a.shape[0],a.shape[1],a.shape[2],i,m,g,y,b,_,x,E,w,v,k,I,T,S,A),N}};let sS;const oS={kernelName:sn,backendName:"wasm",setupFunc:function(e){sS=e.wasm.cwrap(sn,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=Tl(u),h=ml(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:w,strideHeight:v,strideWidth:k}=h,I=f-1-h.padInfo.top,T=m-1-h.padInfo.left,S="channelsLast"===h.dataFormat,E=yt(h.inShape),N=yt(a.shape),[A,C,R]=yt(s.shape),M=E[0],F=S?E[1]:E[2],$=S?E[2]:1,O=S?1:E[1],D=N[0],P=S?N[1]:N[2],L=S?N[2]:1,B=S?1:N[1],U=t.makeOutput(h.inShape,"float32"),W=t.dataIdMap.get(U.dataId).id,z=t.dataIdMap.get(a.dataId).id,V=t.dataIdMap.get(s.dataId).id;return sS(z,V,d,f,m,y,b,g,x,w,_,v,k,I,T,A,C,R,M,F,$,O,D,P,L,B,W),U}};let iS;const uS={kernelName:on,backendName:"wasm",setupFunc:function(e){iS=e.wasm.cwrap(on,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"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dilations:u}=r;if("float32"!==a.dtype)throw new Error(`Tensor x must have dtype float32, got ${a.dtype}`);if("float32"!==s.dtype)throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);const l=gl(a.shape,s.shape,o,u,i),c=n.makeOutput(l.outShape,a.dtype);return iS(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(c.dataId).id,l.batchSize,l.inDepth,l.inHeight,l.inWidth,l.inChannels,l.outDepth,l.outHeight,l.outWidth,l.outChannels,l.strideDepth,l.strideHeight,l.strideWidth,l.dilationDepth,l.dilationHeight,l.dilationWidth,l.filterDepth,l.filterHeight,l.filterWidth,l.padInfo.front,l.padInfo.top,l.padInfo.left),c}};let lS;const cS={kernelName:un,backendName:"wasm",setupFunc:function(e){lS=e.wasm.cwrap(un,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"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:o,pad:i,filterShape:u}=r;if("float32"!==a.dtype)throw new Error(`Tensor dy must have dtype float32, got ${a.dtype}`);if("float32"!==s.dtype)throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);const l=gl(a.shape,u,o,1,i),c=n.makeOutput(l.filterShape,s.dtype);return lS(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(c.dataId).id,l.batchSize,l.inDepth,l.inHeight,l.inWidth,l.inChannels,l.outDepth,l.outHeight,l.outWidth,l.outChannels,l.strideDepth,l.strideHeight,l.strideWidth,l.dilationDepth,l.dilationHeight,l.dilationWidth,l.filterDepth,l.filterHeight,l.filterWidth,l.padInfo.front,l.padInfo.top,l.padInfo.left),c}};let pS;const hS={kernelName:ln,backendName:"wasm",setupFunc:function(e){pS=e.wasm.cwrap(ln,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"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{pad:o,strides:i,inputShape:u}=r;if("float32"!==a.dtype)throw new Error(`Tensor dy must have dtype float32, got ${a.dtype}`);if("float32"!==s.dtype)throw new Error(`Tensor filter must have dtype float32, got ${s.dtype}`);const l=gl(u,s.shape,i,1,o),c=n.makeOutput(l.inShape,a.dtype);return pS(n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(c.dataId).id,l.batchSize,l.inDepth,l.inHeight,l.inWidth,l.inChannels,l.outDepth,l.outHeight,l.outWidth,l.outChannels,l.strideDepth,l.strideHeight,l.strideWidth,l.dilationDepth,l.dilationHeight,l.dilationWidth,l.filterDepth,l.filterHeight,l.filterWidth,l.padInfo.front,l.padInfo.top,l.padInfo.left),c}},dS=sT("Cos"),fS=sT(cn);var mS;let gS;!function(e){e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest"}(mS||(mS={}));const yS={kernelName:dn,backendName:"wasm",setupFunc:function(e){gS=e.wasm.cwrap(dn,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=YT({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,w=new Uint8Array(new Int32Array(i.shape).buffer);return gS(g,y,b,c,w,p,h,mS[a],s,x),null!=f&&t.disposeData(f.dataId),_}};let bS;const _S={kernelName:pn,backendName:"wasm",setupFunc:function(e){bS=e.wasm.cwrap(pn,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=Ac([s],u);let c=a;null!==l&&(c=gT({inputs:{x:a},attrs:{perm:l},backend:n}));const p=Rc(1,u)[0];Nc("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;bS(f,o?1:0,i?1:0,d,m,ZI[a.dtype]);let g=h;return null!==l&&(g=gT({inputs:{x:h},attrs:{perm:Cc(l)},backend:n}),n.disposeData(c.dataId),n.disposeData(h.dataId)),g}};let xS;const wS={kernelName:hn,backendName:"wasm",setupFunc:function(e){xS=e.wasm.cwrap(hn,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=Ac([s],u);let c=a;null!==l&&(c=gT({inputs:{x:a},attrs:{perm:l},backend:n}));const p=Rc(1,u)[0];Nc("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;xS(f,o?1:0,i?1:0,d,m,ZI[a.dtype]);let g=h;return null!==l&&(g=gT({inputs:{x:h},attrs:{perm:Cc(l)},backend:n}),n.disposeData(c.dataId),n.disposeData(h.dataId)),g}};let vS;const kS={kernelName:fn,backendName:"wasm",setupFunc:function(e){vS=e.wasm.cwrap("DenseBincount",null,["number","array","number","number","boolean","number","number","boolean","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{x:a,weights:s}=n,{size:o,binaryOutput:i}=r,u=0!==s.shape.reduce(((e,t)=>e*t),1),l=1===a.shape.length?[o]:[a.shape[0],o],c=t.makeOutput(l,s.dtype);function p(e){return t.dataIdMap.get(e.dataId).id}return vS(p(a),new Uint8Array(new Int32Array(a.shape).buffer),a.shape.length,o,u,p(s),ZI[s.dtype],i,p(c)),c}};let IS;const TS={kernelName:mn,backendName:"wasm",setupFunc:function(e){IS=e.wasm.cwrap(mn,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 IS(d,s,"NHWC"===o?1:0,f,a.shape.length-1,m,g,p.length,y),h}};let SS;const ES={kernelName:gn,backendName:"wasm",setupFunc:function(e){SS=e.wasm.cwrap(gn,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=ml(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,w=d.dilationWidth,v=d.strideHeight,k=d.strideWidth,I=d.inChannels,T=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 SS(o,a.shape[0],a.shape[1],a.shape[2],i,f,m,g,y,b,_,S,x,w,v,k,I,T,N),E}};let NS;const AS={kernelName:yn,backendName:"wasm",setupFunc:function(e){NS=e.wasm.cwrap("Diag",null,["number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,a=et(r.shape),s=n.makeOutput([...r.shape,...r.shape],r.dtype);return NS(n.dataIdMap.get(r.dataId).id,ZI[r.dtype],a,n.dataIdMap.get(s.dataId).id),s}};let CS;const RS={kernelName:bn,backendName:"wasm",setupFunc:function(e){CS=e.wasm.cwrap(bn,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dilations:u}=r;if(a.dtype!==s.dtype)throw new Error(`Dilation2D error: x must have the same dtype as filter. Got ${a.dtype} and ${s.dtype}`);const l=hl(a.shape,s.shape,o,i,"NHWC",u),c=n.makeOutput(l.outShape,a.dtype);return CS(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(c.dataId).id,ZI[a.dtype],l.batchSize,l.inChannels,l.inHeight,l.inWidth,l.outHeight,l.outWidth,l.strideHeight,l.strideWidth,l.dilationHeight,l.dilationWidth,l.filterHeight,l.filterWidth,l.padInfo.top,l.padInfo.left),c}};let MS;const FS={kernelName:xn,backendName:"wasm",setupFunc:function(e){MS=e.wasm.cwrap(xn,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,backend:n,attrs:r}=e,{x:a,filter:s,dy:o}=t,{strides:i,pad:u,dilations:l}=r;if(a.dtype!==s.dtype||a.dtype!==o.dtype)throw new Error(`Dilation2DBackpropFilter error: x must have the same dtype as filter and dy. Got ${a.dtype}, ${s.dtype}, and ${o.dtype}`);const c=hl(a.shape,s.shape,i,u,"NHWC",l),p=n.makeOutput(s.shape,s.dtype);return MS(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(o.dataId).id,n.dataIdMap.get(p.dataId).id,ZI[a.dtype],c.batchSize,c.inChannels,c.inHeight,c.inWidth,c.outHeight,c.outWidth,c.strideHeight,c.strideWidth,c.dilationHeight,c.dilationWidth,c.filterHeight,c.filterWidth,c.padInfo.top,c.padInfo.left),p}};let $S;const OS={kernelName:_n,backendName:"wasm",setupFunc:function(e){$S=e.wasm.cwrap(_n,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,backend:n,attrs:r}=e,{x:a,filter:s,dy:o}=t,{strides:i,pad:u,dilations:l}=r;if(a.dtype!==s.dtype||a.dtype!==o.dtype)throw new Error(`Dilation2DBackpropInput error: x must have the same dtype as filter and dy. Got ${a.dtype}, ${s.dtype}, and ${o.dtype}`);const c=hl(a.shape,s.shape,i,u,"NHWC",l),p=n.makeOutput(a.shape,a.dtype);return $S(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(o.dataId).id,n.dataIdMap.get(p.dataId).id,ZI[a.dtype],c.batchSize,c.inChannels,c.inHeight,c.inWidth,c.outHeight,c.outWidth,c.strideHeight,c.strideWidth,c.dilationHeight,c.dilationWidth,c.filterHeight,c.filterWidth,c.padInfo.top,c.padInfo.left),p}},DS=sT(vn);let PS;const LS={kernelName:kn,backendName:"wasm",setupFunc:function(e){PS=e.wasm.cwrap(kn,null,["number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n}=e,{dy:r,y:a}=t,s=n.makeOutput(a.shape,"float32"),o=e=>n.dataIdMap.get(e.dataId).id;return PS(o(a),o(r),o(s)),s}},BS=lT(In,0,"bool"),US=sT("Erf"),WS=sT(Tn,"float32");function zS(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),BT({inputs:{x:a},backend:r,attrs:{shape:i}})}const VS={kernelName:Sn,backendName:"wasm",kernelFunc:zS},HS=sT(En,"float32");function GS(e){const{attrs:{shape:t,value:n},backend:r}=e;let{attrs:{dtype:a}}=e;a=a||ft(n);const s=r.makeOutput(t,a);return r.typedArrayFromHeap(s).fill(n),s}const jS={kernelName:Nn,backendName:"wasm",kernelFunc:GS};let KS;const qS={kernelName:An,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 KS(s,i,u,l,c,o),a},setupFunc:function(e){KS=e.wasm.cwrap(An,null,["number","number","number","number","number","number"])}},XS=sT(Cn),YS=lT(Rn);let QS;const JS={kernelName:Mn,backendName:"wasm",setupFunc:function(e){QS=e.wasm.cwrap(Mn,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 QS(c,p,h,d,f,a,g),m}};let ZS;const eE={kernelName:fa,backendName:"wasm",setupFunc:function(e){ZS=e.wasm.cwrap(fa,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=ml(a.shape,s.shape,u,c,l,h),g=eT[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 w=m.filterHeight,v=m.filterWidth,k=m.padInfo.top,I=m.padInfo.right,T=m.padInfo.bottom,S=m.padInfo.left,E=m.dilationHeight,N=m.dilationWidth,A=m.strideHeight,C=m.strideWidth,R=m.inChannels,M="SAME"===m.padInfo.type?1:0,F=m.batchSize,$=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"),P=r.dataIdMap.get(D.dataId).id,L=null==i?0:r.dataIdMap.get(i.dataId).id;return ZS(y,F,$,O,b,w,v,x,k,I,T,S,M,E,N,A,C,R,_,g,L,f||0,P),D}};let tE;const nE={kernelName:ma,backendName:"wasm",setupFunc:function(e){tE=e.wasm.cwrap(ma,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=ml(a.shape,s.shape,u,c,l,h,!0),g=eT[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 w=m.filterHeight,v=m.filterWidth,k=m.padInfo.top,I=m.padInfo.right,T=m.padInfo.bottom,S=m.padInfo.left,E=m.dilationHeight,N=m.dilationWidth,A=m.strideHeight,C=m.strideWidth,R=m.inChannels,M="SAME"===m.padInfo.type?1:0,F=m.batchSize,$=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"),P=r.dataIdMap.get(D.dataId).id,L=null==i?0:r.dataIdMap.get(i.dataId).id;return tE(y,F,$,O,b,w,v,x,k,I,T,S,M,E,N,A,C,R,_,g,L,f||0,P),D}};let rE;const aE={kernelName:$n,backendName:"wasm",setupFunc:function(e){rE=e.wasm.cwrap($n,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]=Au(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 rE(h,ZI[r.dtype],d,o,p,i,f,m),l}};let sE;const oE={kernelName:Fn,backendName:"wasm",setupFunc:function(e){sE=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=Vf(a,s,u,i),h=BT({inputs:{x:a},attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]},backend:t}),d=et(s.shape),f=BT({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,w=new Uint8Array(new Int32Array(yt(h.shape)).buffer),v=new Uint8Array(new Int32Array(yt(m)).buffer);return sE(b,ZI[a.dtype],w,y,_,p.batchSize,v,x),t.disposeData(h.dataId),t.disposeData(f.dataId),g.shape=p.outputShape,g}},iE=lT(On,0,"bool"),uE=lT(Dn,0,"bool"),lE=sT(Ln,"bool"),cE=sT(Bn,"bool"),pE=sT(Un,"bool");let hE;const dE={kernelName:Wn,backendName:"wasm",setupFunc:function(e){hE=e.wasm.cwrap(Wn,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;hE(a,ZI[t.dtype],n,e)}return s}},fE=lT(zn,0,"bool"),mE=lT(Vn,0,"bool");let gE;const yE={kernelName:Hn,backendName:"wasm",setupFunc:function(e){gE=e.wasm.cwrap(Hn,null,["number","number","number","number"])},kernelFunc:function(e){const{attrs:t,backend:n}=e,{start:r,stop:a,num:s}=t,o=Math.floor(s),i=n.makeOutput([o],"float32");return gE(n.dataIdMap.get(i.dataId).id,r,a,o),i}},bE=sT("Log"),_E=sT(Gn),xE=lT(jn,0,"bool"),wE=sT(Kn),vE=lT(qn,0,"bool"),kE=lT("LogicalXor",0,"bool");let IE;const TE={kernelName:Xn,backendName:"wasm",setupFunc:function(e){IE=e.wasm.cwrap(Xn,null,["number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{depthRadius:s,bias:o,alpha:i,beta:u}=r;if("float32"!==a.dtype)throw new Error("LRN error: x must have dtype float32");const l=n.makeOutput(a.shape,a.dtype);return IE(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(l.dataId).id,a.shape[3],s,o,i,u),l}};let SE;const EE={kernelName:Yn,backendName:"wasm",setupFunc:function(e){SE=e.wasm.cwrap(Yn,null,["number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,y:s,dy:o}=t,{depthRadius:i,bias:u,alpha:l,beta:c}=r;if("float32"!==a.dtype||"float32"!==s.dtype||"float32"!==o.dtype)throw new Error("LRNGrad error: x, y, and dy must have dtype float32");const p=n.makeOutput(a.shape,a.dtype);return SE(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(o.dataId).id,n.dataIdMap.get(p.dataId).id,o.shape[3],i,u,l,c),p}};let NE;const AE={kernelName:Qn,backendName:"wasm",setupFunc:function(e){NE=e.wasm.cwrap(Qn,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}=bT(o,a,t);h&&(u=l,i=t.dataIdMap.get(l.dataId).id),Nc("max",c,u.shape.length);const[d,f]=Sc(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;NE(i,ZI[o.dtype],m,e)}if(h&&t.disposeData(l.dataId),s){const e=Ec(g.shape,p);g.shape=e}return g}},CE=lT(Jn);let RE;const ME={kernelName:Zn,backendName:"wasm",setupFunc:function(e){RE=e.wasm.cwrap(Zn,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=dl(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,w=c.inChannels,v=c.outChannels;if("channelsLast"!==c.dataFormat)throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);const k=r.makeOutput(c.outShape,"float32"),I=r.dataIdMap.get(k.dataId).id;return RE(s,a.shape[0],a.shape[1],a.shape[2],p,h,d,f,m,g,y,b,_,x,w,v,I),k}};let FE;const $E={kernelName:er,backendName:"wasm",setupFunc:function(e){FE=e.wasm.cwrap("MaxPool3D",null,["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,backend:n,attrs:r}=e,{x:a}=t,{filterSize:s,strides:o,pad:i,dimRoundingMode:u,dataFormat:l}=r,c=fl(a.shape,s,o,1,i,u,l),p=n.makeOutput(c.outShape,a.dtype);return FE(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(p.dataId).id,c.batchSize,c.inChannels,c.inDepth,c.inHeight,c.inWidth,c.outDepth,c.outHeight,c.outWidth,c.strideDepth,c.strideHeight,c.strideWidth,c.dilationDepth,c.dilationHeight,c.dilationWidth,c.effectiveFilterDepth,c.effectiveFilterHeight,c.effectiveFilterWidth,c.padInfo.front,c.padInfo.top,c.padInfo.left),p}};let OE;const DE={kernelName:"MaxPool3DGrad",backendName:"wasm",setupFunc:function(e){OE=e.wasm.cwrap("MaxPool3DGrad",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,backend:n,attrs:r}=e,{dy:a,input:s}=t,{filterSize:o,strides:i,pad:u,dimRoundingMode:l}=r,c=fl(s.shape,o,i,1,u,l),p=n.makeOutput(s.shape,s.dtype);return OE(n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(p.dataId).id,c.batchSize,c.inChannels,c.inDepth,c.inHeight,c.inWidth,c.outDepth,c.outHeight,c.outWidth,c.strideDepth,c.strideHeight,c.strideWidth,c.dilationDepth,c.dilationHeight,c.dilationWidth,c.effectiveFilterDepth,c.effectiveFilterHeight,c.effectiveFilterWidth,c.padInfo.front,c.padInfo.top,c.padInfo.left),p}};let PE;const LE={kernelName:"MaxPoolGrad",backendName:"wasm",setupFunc:function(e){PE=e.wasm.cwrap("MaxPoolGrad",null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,{filterSize:o,strides:i,pad:u,dimRoundingMode:l}=r,c=dl(s.shape,o,i,1,u,l),p=n.makeOutput(s.shape,s.dtype);return PE(n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(p.dataId).id,c.batchSize,c.inChannels,c.inHeight,c.inWidth,c.outHeight,c.outWidth,c.strideHeight,c.strideWidth,c.dilationHeight,c.dilationWidth,c.effectiveFilterHeight,c.effectiveFilterWidth,c.padInfo.top,c.padInfo.left),p}};let BE;const UE={kernelName:tr,backendName:"wasm",setupFunc:function(e){BE=e.wasm.cwrap("MaxPoolWithArgmax",null,["number","number","number","number","boolean","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{filterSize:s,strides:o,pad:i,includeBatchInIndex:u}=r;Qe(4===a.shape.length,(()=>`Error in maxPool: input must be rank 4 but got rank ${a.shape.length}.`));const l=[1,1];Qe(kl(o,l),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${l}'`));const c=dl(a.shape,s,o,[1,1],i),p=n.makeOutput(c.outShape,a.dtype),h=n.makeOutput(c.outShape,"int32");return BE(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(p.dataId).id,n.dataIdMap.get(h.dataId).id,ZI[a.dtype],u,c.batchSize,c.inChannels,c.inHeight,c.inWidth,c.outHeight,c.outWidth,c.strideHeight,c.strideWidth,c.dilationHeight,c.dilationWidth,c.effectiveFilterHeight,c.effectiveFilterWidth,c.padInfo.top,c.padInfo.left),[p,h]}};let WE;const zE={kernelName:nr,backendName:"wasm",setupFunc:function(e){WE=e.wasm.cwrap(nr,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}=bT(o,a,t);let f=p;if(d){const e=t.dataIdMap.get(c.dataId).id;e!==i&&(l=c,u=e,f=Rc(f.length,l.shape.length))}Nc("mean",f,l.shape.length);const[m,g]=Sc(l.shape,f),y=et(g);let b=l;"float32"!==l.dtype&&(b=YT({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;WE(u,y,e)}if(d&&t.disposeData(c.dataId),s){const e=Ec(_.shape,h);_.shape=e}return"float32"!==l.dtype&&t.disposeData(b.dataId),_}};let VE;const HE={kernelName:rr,backendName:"wasm",setupFunc:function(e){VE=e.wasm.cwrap(rr,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}=bT(o,a,t);if(d){const e=t.dataIdMap.get(c.dataId).id;e!==i&&(l=c,u=e)}Nc("min",p,l.shape.length);const[f,m]=Sc(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;VE(u,ZI[o.dtype],g,e)}if(d&&t.disposeData(c.dataId),s){const e=Ec(y.shape,h);y.shape=e}return y}},GE=lT(ar);var jE;let KE;!function(e){e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric"}(jE||(jE={}));const qE={kernelName:sr,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 KE(o,l,t.shape.length,ZI[t.dtype],h,d,jE[a],u),i},setupFunc:function(e){KE=e.wasm.cwrap(sr,null,["number","array","number","number","array","array","number","number"])}};let XE;function YE(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)||XE(a,o,i,u),s}const QE={kernelName:Hr,backendName:"wasm",setupFunc:function(e){XE=e.wasm.cwrap(Hr,null,["number","number","number","number"])},kernelFunc:YE};let JE;const ZE={kernelName:or,backendName:"wasm",setupFunc:function(e){JE=e.wasm.cwrap(or,null,["number","number","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{numSamples:s,seed:o,normalized:i}=r;if("float32"!==a.dtype)throw new Error(`Tensor logits must have dtype float32, got ${a.dtype}`);const u=i?a:YE({inputs:{logits:a},backend:n,attrs:{dim:a.shape.length-1}}),[l,c]=u.shape,p=n.makeOutput([l,s],"int32");return JE(n.dataIdMap.get(u.dataId).id,l,c,s,o,n.dataIdMap.get(p.dataId).id),i||n.disposeData(u.dataId),p}},eN=lT("Mod"),tN=lT(ir),nN=sT("Neg");function rN(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 aN;const sN={kernelName:lr,backendName:"wasm",setupFunc:function(e){aN=e.wasm.cwrap(lr,"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=aN(l,c,s,a,o),{pSelectedIndices:h,selectedSize:d,pSelectedScores:f,pValidOutputs:m}=rN(t,p);return t.wasm._free(f),t.wasm._free(m),t.makeOutput([d],"int32",h)}};let oN;const iN={kernelName:cr,backendName:"wasm",setupFunc:function(e){oN=e.wasm.cwrap(cr,"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=oN(c,p,s,a,o,i),{pSelectedIndices:d,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=rN(t,h);return t.wasm._free(m),[t.makeOutput([f],"int32",d),t.makeOutput([],"int32",g)]}};let uN;const lN={kernelName:pr,backendName:"wasm",setupFunc:function(e){uN=e.wasm.cwrap(pr,"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=uN(c,p,s,a,o,i),{pSelectedIndices:d,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=rN(t,h);return t.wasm._free(g),[t.makeOutput([f],"int32",d),t.makeOutput([f],"float32",m)]}},cN=lT(ur,0,"bool");let pN;const hN={kernelName:dr,backendName:"wasm",setupFunc:function(e){pN=e.wasm.cwrap(dr,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 pN(p,o,i,u,c),l}},dN={kernelName:hr,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}},fN={kernelName:fr,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return zS({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=tS({inputs:t.map((e=>{const t=zS({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 mN;const gN={kernelName:mr,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 GS({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 mN(o,l,t.shape.length,ZI[t.dtype],h,d,a,u),i},setupFunc:function(e){mN=e.wasm.cwrap(mr,null,["number","array","number","number","array","array","number","number"])}},yN=lT("Pow");let bN;const _N={kernelName:gr,backendName:"wasm",setupFunc:function(e){bN=e.wasm.cwrap(gr,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=YT({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 bN(i,o,p),"float32"!==u.dtype&&n.disposeData(l.dataId),c}};let xN;const wN={kernelName:yr,backendName:"wasm",setupFunc:function(e){xN=e.wasm.cwrap(yr,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}=bT(o,a,t);let f=p;if(d){const e=t.dataIdMap.get(c.dataId).id;e!==i&&(l=c,u=e,f=Rc(f.length,l.shape.length))}Nc("prod",f,l.shape.length);const[m,g]=Sc(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;xN(u,y,ZI[b.dtype],e)}if(d&&t.disposeData(c.dataId),s){const e=Ec(b.shape,h);b.shape=e}return b}},vN={kernelName:br,backendName:"wasm",kernelFunc:e=>{const{backend:t,attrs:n}=e,{start:r,stop:a,step:s,dtype:o}=n,i=ly(r,a,s,o),u=t.makeOutput([i.length],o);return t.typedArrayFromHeap(u).set(i),u}},kN=lT(wn),IN=sT(_r),TN=sT(xr),SN=sT(Sr);let EN;const NN={kernelName:Ir,backendName:"wasm",setupFunc:function(e){EN=e.wasm.cwrap(Ir,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=YT({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 EN(y,c,p,h,d,u,l,s?1:0,o?1:0,_),null!=m&&t.disposeData(m.dataId),b}};let AN;const CN={kernelName:Tr,backendName:"wasm",setupFunc:function(e){AN=e.wasm.cwrap(Tr,null,["number","number","number","array","array","boolean"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a,dy:s}=t,{alignCorners:o}=r,i=n.makeOutput(a.shape,"float32");let u,l=n.dataIdMap.get(a.dataId);return"float32"!==l.dtype&&(u=YT({backend:n,inputs:{x:a},attrs:{dtype:"float32"}}),l=n.dataIdMap.get(u.dataId)),AN(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(i.dataId).id,new Uint8Array(new Int32Array(a.shape).buffer),new Uint8Array(new Int32Array(s.shape).buffer),o),null!=u&&n.disposeData(u.dataId),i}};let RN;const MN={kernelName:vr,backendName:"wasm",setupFunc:function(e){RN=e.wasm.cwrap(vr,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=YT({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 RN(b,c,p,h,d,u,l,s?1:0,o?1:0,_),null!=g&&t.disposeData(g.dataId),m}};let FN;const $N={kernelName:kr,backendName:"wasm",setupFunc:function(e){FN=e.wasm.cwrap(kr,null,["number","number","number","array","array","boolean"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a,dy:s}=t,{alignCorners:o}=r,i=n.makeOutput(a.shape,"float32");let u,l=n.dataIdMap.get(a.dataId);return"float32"!==l.dtype&&(u=YT({backend:n,inputs:{x:a},attrs:{dtype:"float32"}}),l=n.dataIdMap.get(u.dataId)),FN(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(i.dataId).id,new Uint8Array(new Int32Array(a.shape).buffer),new Uint8Array(new Int32Array(s.shape).buffer),o),null!=u&&n.disposeData(u.dataId),i}};let ON;const DN={kernelName:Er,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 dT({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);ON(u,c,o.length,p,a.shape.length,l);const h=BT({inputs:{x:i},attrs:{shape:a.shape},backend:n});return n.disposeData(i.dataId),h},setupFunc:function(e){ON=e.wasm.cwrap(Er,null,["number","array","number","array","number","number"])}};let PN;const LN={kernelName:ha,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]=If(i,h,d),y="number"==typeof o?[o,o,o,0===o?0:255]:[...o,255],b=new Uint8Array(new Int32Array(y).buffer);return PN(l,p,h,d,f,s,m,g,b,y.length,c),u},setupFunc:function(e){PN=e.wasm.cwrap(ha,null,["number","number","number","number","number","number","number","number","array","number","number"])}},BN=sT(Nr),UN=sT(Ar);let WN;const zN={kernelName:Cr,backendName:"wasm",setupFunc:function(e){WN=e.wasm.cwrap(Cr,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}=Mu(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 WN(d,f,ZI[s.dtype],u,l,c,m,h,g),i}};let VN;const HN={kernelName:Mr,backendName:"wasm",setupFunc:function(e){VN=e.wasm.cwrap(Mr,null,["number","number","number","number","number","number","bool","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sortedSequence:a,values:s}=t,{side:o}=r;if(a.dtype!==s.dtype)throw new Error(`SearchSorted error: sorted_sequence must have the same dtype as values. Got ${a.dtype} and ${s.dtype}`);const i=n.makeOutput(s.shape,"int32");function u(e){return n.dataIdMap.get(e.dataId).id}return VN(u(a),u(s),a.shape[0],a.shape[1],s.shape[1],ZI[a.dtype],"left"===o,u(i)),i}};let GN;const jN={kernelName:Fr,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 GN(o,i,u,d,c),l},setupFunc:function(e){GN=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}},KN=sT($r);let qN;const XN={kernelName:"Sigmoid",backendName:"wasm",setupFunc:function(e){qN=e.wasm.cwrap(Lr,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)||qN(r,s),a}},YN=sT(Pr),QN=sT("Sin"),JN=sT(Dr),ZN=sT(Br),eA={kernelName:zr,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=gN.kernelFunc({inputs:{x:a},backend:n,attrs:{paddings:u,constantValue:0}}),c=Tf(l.shape,s,i,!1),p=Sf(c.length,s.length,!1),h=Ef(l.shape,s,i,!1),d=BT({inputs:{x:l},backend:n,attrs:{shape:c}}),f=gT({inputs:{x:d},backend:n,attrs:{perm:p}}),m=BT({inputs:{x:f},backend:n,attrs:{shape:h}});return n.disposeData(l.dataId),n.disposeData(d.dataId),n.disposeData(f.dataId),m}};let tA;const nA={kernelName:Gr,backendName:"wasm",setupFunc:function(e){tA=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),w=t.dataIdMap.get(x.dataId).id,v=t.makeOutput([4],"int32"),k=t.dataIdMap.get(v.dataId).id,I=tA(p,h,ZI[a.dtype],i,l,u,d,m,y,_,w,k),T=t.readSync(v.dataId);let S;switch(T[0]){case 1:S=$f(T[1]);break;case 2:S=Of(T[1],T[2]);break;case 3:S=Df(T[1],T[2],T[3]);break;default:S=""}if(t.disposeData(v.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 I!==c[0]&&(E=VT({inputs:{x:f},attrs:{begin:0,size:[I,u]},backend:t}),N=VT({inputs:{x:g},attrs:{begin:0,size:I},backend:t}),t.disposeData(f.dataId),t.disposeData(g.dataId)),[E,N,b,x]}};let rA;const aA={kernelName:jr,backendName:"wasm",setupFunc:function(e){rA=e.wasm.cwrap(jr,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;rA(o,i,u,l,h,f,g);const y=t.readSync(m.dataId);let b;switch(y[0]){case 0:b=Pf(y[1],y[2]);break;case 1:b=Lf(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=Bf(Array.from(t.readSync(a.dataId)),Array.from(t.readSync(d.dataId)));break;case 4:b=Uf(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 sA;function oA(e){sA=e.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function iA(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;sA(p,ZI[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:_=Wf(b[1],b[2]);break;case 3:_=zf(b[1],b[2],b[3]);break;default:_=""}if(n.disposeData(g.dataId),_)throw n.disposeData(f.dataId),new Error(_);return f}const uA={kernelName:Kr,backendName:"wasm",setupFunc:oA,kernelFunc:function(e){return iA(e,!0)}},lA={kernelName:qr,backendName:"wasm",setupFunc:oA,kernelFunc:function(e){return iA(e,!1)}};let cA;const pA={kernelName:Xr,backendName:"wasm",setupFunc:function(e){cA=e.wasm.cwrap(Xr,null,["number","number","number","number","number","number","number","number","array","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{sparseIndices:a,sparseValues:s,defaultValue:o}=n,{outputShape:i}=r,u=t.makeOutput(i,o.dtype);if(0===et(i))return u;const{sliceRank:l,numUpdates:c,sliceSize:p,strides:h,outputSize:d}=Mu(0,a,i),f=t.dataIdMap.get(a.dataId).id,m=t.dataIdMap.get(s.dataId).id,g=t.dataIdMap.get(o.dataId).id,y=new Uint8Array(new Int32Array(h).buffer),b=t.dataIdMap.get(u.dataId).id;return cA(f,m,s.shape.length,g,ZI[o.dtype],l,c,p,y,d,b),u}},hA={kernelName:Vr,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=Ff(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=VT({inputs:{x:a},attrs:{begin:l,size:t},backend:r});return l[i]+=e,n}))}},dA=sT(Ur),fA=sT("Square"),mA=lT(Yr);let gA;const yA={kernelName:ca,backendName:"wasm",setupFunc:function(e){gA=e.wasm.cwrap(ca,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 gA(o,a,ZI[s.dtype],u),i}};let bA;const _A={kernelName:Qr,backendName:"wasm",setupFunc:function(e){bA=e.wasm.cwrap(Qr,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}=ju(a.shape,s,o,i,u,l,c,p,h);let w;if(m)w=BT({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=$u(b,_,x),n=VT({inputs:{x:a},backend:t,attrs:{begin:b,size:e}});w=BT({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;bA(n,r,a.shape.length,s,o,i,u,l,d.length,c),w=BT({inputs:{x:e},backend:t,attrs:{shape:f}}),t.disposeData(e.dataId)}return w}},xA={kernelName:Jr,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]=vy(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]}},wA={kernelName:Zr,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]=Iy(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]}},vA={kernelName:ea,backendName:"wasm",kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{input:a}=n,{numBuckets:s}=r,o=Ty(t.readSync(a.dataId),s),i=t.makeOutput(a.shape,"int32");return t.typedArrayFromHeap(i).set(o),i}},kA=lT(ta);let IA;const TA={kernelName:Wr,backendName:"wasm",setupFunc:function(e){IA=e.wasm.cwrap(Wr,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}=bT(o,a,t);let f=p;if(d){const e=t.dataIdMap.get(c.dataId).id;e!==i&&(l=c,u=e,f=Rc(f.length,l.shape.length))}Nc("sum",f,l.shape.length);const[m,g]=Sc(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;IA(u,y,ZI[b.dtype],e)}if(d&&t.disposeData(c.dataId),s){const e=Ec(b.shape,h);b.shape=e}return b}},SA=sT("Tan"),EA=sT(na);let NA;const AA={kernelName:Rr,backendName:"wasm",setupFunc:function(e){NA=e.wasm.cwrap(Rr,null,["number","number","number","number","number","number","array","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{tensor:a,indices:s,updates:o}=n,i=t.makeOutput(a.shape,a.dtype);if(0===et(a.shape))return i;const{sliceRank:u,numUpdates:l,sliceSize:c,strides:p,outputSize:h}=Mu(0,s,a.shape),d=t.dataIdMap.get(s.dataId).id,f=t.dataIdMap.get(o.dataId).id,m=t.dataIdMap.get(a.dataId).id,g=new Uint8Array(new Int32Array(p).buffer),y=t.dataIdMap.get(i.dataId).id;return NA(d,f,ZI[o.dtype],u,l,c,g,h,y,m),i}};let CA;const RA={kernelName:ra,backendName:"wasm",setupFunc:function(e){CA=e.wasm.cwrap(ra,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 CA(s,u,a.shape.length,l,i.length,ZI[c.dtype],p),c}};let MA;const FA={kernelName:aa,backendName:"wasm",setupFunc:function(e){MA=e.wasm.cwrap(aa,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 MA(o,i,r.shape.length,ZI[r.dtype],a,s,c,h),[l,p]}};let $A;const OA={kernelName:sa,backendName:"wasm",setupFunc:function(e){$A=e.wasm.cwrap(sa,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,w=t.dataIdMap.get(a.dataId).id,v=t.dataIdMap.get(s.dataId).id,k="nearest"===o?1:2;let I;switch(i){case"constant":default:I=1;break;case"reflect":I=2;break;case"wrap":I=3;break;case"nearest":I=4}return $A(w,v,s.shape[0]>1,c,f,m,d,h,p,y,a.shape.length-1,b,g.length-1,k,I,u,x),_}},DA={kernelName:ia,backendName:"wasm",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{axis:a}=n,{x:s}=t,{outputValues:o,outputShape:i,indices:u}=My(r.readSync(s.dataId),a,s.shape,s.dtype);return[r.makeOutput(i,s.dtype,void 0,o),r.makeOutput([u.length],"int32",void 0,u)]}},PA={kernelName:ua,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]=VT({inputs:{x:a},attrs:{begin:p,size:h},backend:n});return c.map((({dataId:e,dtype:t})=>({dataId:e,dtype:t,shape:u})))}},LA={kernelName:la,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}},BA=[aT,oT,iT,uT,cT,hT,xT,vT,IT,TT,ST,ET,NT,AT,CT,MT,LT,$T,DT,zT,GT,KT,qT,XT,QT,JT,eS,nS,aS,oS,uS,cS,hS,dS,fS,yS,_S,wS,kS,TS,ES,AS,RS,FS,OS,DS,LS,BS,US,WS,VS,HS,jS,qS,XS,YS,JS,eE,nE,aE,oE,iE,uE,fT,lE,cE,pE,dE,fE,mE,yE,_E,bE,xE,wE,vE,kE,TE,EE,AE,CE,ME,$E,DE,LE,UE,zE,HE,GE,qE,ZE,eN,tN,nN,sN,iN,lN,cN,hN,dN,fN,gN,yN,_N,wN,vN,kN,IN,TN,SN,UT,NN,CN,MN,$N,DN,LN,BN,UN,zN,HN,jN,KN,XN,YN,QN,JN,HT,QE,ZN,eA,nA,aA,uA,lA,pA,hA,dA,fA,mA,yA,_A,xA,wA,vA,kA,TA,SA,EA,AA,RA,FA,OA,yT,DA,PA,LA];for(const e of BA)va(e);const UA=At();UA.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}})),UA.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",(async()=>{if(UA.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 WA=Xp((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!=M&&W(N.buffer),$}function r(){return N.buffer!=M&&W(N.buffer),O}function a(){return N.buffer!=M&&W(N.buffer),D}function s(){return N.buffer!=M&&W(N.buffer),P}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 w=nh,v=nh;let e;_=g?v.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):v.normalize(e),w.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):v.normalize(e),w.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=nh}catch(e){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),e}qp.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&&(qp.performance=nh.performance);var k=console.log.bind(console),I=console.warn.bind(console);y&&(k=e=>w.writeSync(1,e+"\n"),I=e=>w.writeSync(2,e+"\n"));var T,S=l.print||k,E=l.printErr||I;Object.assign(l,d),d=null,l.arguments&&l.arguments,l.thisProgram&&l.thisProgram,l.quit&&(f=l.quit),l.wasmBinary&&(T=l.wasmBinary);var N,A,C=l.noExitRuntime||!0;"object"!=typeof WebAssembly&&J("no native wasm support detected");var R,M,F,$,O,D,P,L=!1,B="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function U(e,t,n){for(var r=(t>>>=0)+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 W(e){M=e,l.HEAP8=F=new Int8Array(e),l.HEAP16=new Int16Array(e),l.HEAP32=O=new Int32Array(e),l.HEAPU8=$=new Uint8Array(e),l.HEAPU16=new Uint16Array(e),l.HEAPU32=D=new Uint32Array(e),l.HEAPF32=new Float32Array(e),l.HEAPF64=P=new Float64Array(e)}b&&(M=l.buffer);var z,V=l.INITIAL_MEMORY||16777216;if(b)N=l.wasmMemory,M=l.buffer;else if(l.wasmMemory)N=l.wasmMemory;else if(!((N=new WebAssembly.Memory({initial:V/65536,maximum:65536,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&&(M=N.buffer),V=M.byteLength,W(M);var H=[],G=[],j=[];function K(){return C}function q(){b||le(G)}var X,Y=0,Q=null;function J(e){l.onAbort&&l.onAbort(e),E(e="Aborted("+e+")"),L=!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&&T)return new Uint8Array(T);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),L=!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(){C=!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!=Ae()){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:A})},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=Ae(),t=r()[e+52>>>2],n=r()[e+56>>>2];Le(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),Ae()&&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=We(8*a),i=o>>3,u=0;u<n;u++){var l=r[2+u];s()[i+u>>>0]=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=z.get(n)),r)(t);K()?ue.setExitStatus(a):Pe(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-M.byteLength+65535>>>16),W(N.buffer),1}catch(e){}}function xe(e){return b?ye(4,1,e):52}function we(e,t,n,r,a){return b?ye(5,1,e,t,n,r,a):70}var ve=[null,[],[]];function ke(e,t){var n=ve[e];0===t||10===t?((1===e?S:E)(U(n,0)),n.length=0):n.push(t)}function Ie(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++)ke(e,n()[u+c>>>0]);o+=l}return a()[s>>>2]=o,0}function Te(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>>>=0)+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++>>>0]=o}else if(o<=2047){if(n+1>=a)break;t[n++>>>0]=192|o>>6,t[n++>>>0]=128|63&o}else if(o<=65535){if(n+2>=a)break;t[n++>>>0]=224|o>>12,t[n++>>>0]=128|o>>6&63,t[n++>>>0]=128|63&o}else{if(n+3>=a)break;t[n++>>>0]=240|o>>18,t[n++>>>0]=128|o>>12&63,t[n++>>>0]=128|o>>6&63,t[n++>>>0]=128|63&o}}t[n>>>0]=0}(e,n(),t,r)}(e,t=We(r),r)}return t},array:e=>{var t=We(e.length);return function(e,t){(N.buffer!=M&&W(N.buffer),F).set(e,t>>>0)}(e,t),t}},i=Te(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,(r>>>=0)?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,we,Ie],Ne={__emscripten_init_main_thread_js:function(e){Ce(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 4294901760},emscripten_get_now:pe,emscripten_memcpy_big:function(e,t,r){n().copyWithin(e>>>0,t>>>0,t+r>>>0)},emscripten_num_logical_cores:function(){return y?nh.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>>>0];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=4294901760;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:we,fd_write:Ie,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),z=l.asm.__indirect_function_table,r=l.asm.__wasm_call_ctors,G.unshift(r),A=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(!T&&(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)}(T||"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._Acos=function(){return(l._Acos=l.asm.Acos).apply(null,arguments)},l._Acosh=function(){return(l._Acosh=l.asm.Acosh).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._ArgMin=function(){return(l._ArgMin=l.asm.ArgMin).apply(null,arguments)},l._Asin=function(){return(l._Asin=l.asm.Asin).apply(null,arguments)},l._Asinh=function(){return(l._Asinh=l.asm.Asinh).apply(null,arguments)},l._Atan=function(){return(l._Atan=l.asm.Atan).apply(null,arguments)},l._Atan2=function(){return(l._Atan2=l.asm.Atan2).apply(null,arguments)},l._Atanh=function(){return(l._Atanh=l.asm.Atanh).apply(null,arguments)},l._AvgPool=function(){return(l._AvgPool=l.asm.AvgPool).apply(null,arguments)},l._AvgPool3D=function(){return(l._AvgPool3D=l.asm.AvgPool3D).apply(null,arguments)},l._AvgPool3DGrad=function(){return(l._AvgPool3DGrad=l.asm.AvgPool3DGrad).apply(null,arguments)},l._AvgPoolGrad=function(){return(l._AvgPoolGrad=l.asm.AvgPoolGrad).apply(null,arguments)},l._BatchMatMul=function(){return(l._BatchMatMul=l.asm.BatchMatMul).apply(null,arguments)},l._Bincount=function(){return(l._Bincount=l.asm.Bincount).apply(null,arguments)},l._BitwiseAnd=function(){return(l._BitwiseAnd=l.asm.BitwiseAnd).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._Conv3D=function(){return(l._Conv3D=l.asm.Conv3D).apply(null,arguments)},l._Conv3DBackpropFilterV2=function(){return(l._Conv3DBackpropFilterV2=l.asm.Conv3DBackpropFilterV2).apply(null,arguments)},l._Conv3DBackpropInputV2=function(){return(l._Conv3DBackpropInputV2=l.asm.Conv3DBackpropInputV2).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._DenseBincount=function(){return(l._DenseBincount=l.asm.DenseBincount).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._Diag=function(){return(l._Diag=l.asm.Diag).apply(null,arguments)},l._Dilation2D=function(){return(l._Dilation2D=l.asm.Dilation2D).apply(null,arguments)},l._Dilation2DBackpropFilter=function(){return(l._Dilation2DBackpropFilter=l.asm.Dilation2DBackpropFilter).apply(null,arguments)},l._Dilation2DBackpropInput=function(){return(l._Dilation2DBackpropInput=l.asm.Dilation2DBackpropInput).apply(null,arguments)},l._Elu=function(){return(l._Elu=l.asm.Elu).apply(null,arguments)},l._EluGrad=function(){return(l._EluGrad=l.asm.EluGrad).apply(null,arguments)},l._Equal=function(){return(l._Equal=l.asm.Equal).apply(null,arguments)},l._Erf=function(){return(l._Erf=l.asm.Erf).apply(null,arguments)},l._Exp=function(){return(l._Exp=l.asm.Exp).apply(null,arguments)},l._Expm1=function(){return(l._Expm1=l.asm.Expm1).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._IsFinite=function(){return(l._IsFinite=l.asm.IsFinite).apply(null,arguments)},l._IsInf=function(){return(l._IsInf=l.asm.IsInf).apply(null,arguments)},l._IsNan=function(){return(l._IsNan=l.asm.IsNan).apply(null,arguments)},l._LRN=function(){return(l._LRN=l.asm.LRN).apply(null,arguments)},l._LRNGrad=function(){return(l._LRNGrad=l.asm.LRNGrad).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._LinSpace=function(){return(l._LinSpace=l.asm.LinSpace).apply(null,arguments)},l._Log=function(){return(l._Log=l.asm.Log).apply(null,arguments)},l._Log1p=function(){return(l._Log1p=l.asm.Log1p).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._MaxPool3D=function(){return(l._MaxPool3D=l.asm.MaxPool3D).apply(null,arguments)},l._MaxPool3DGrad=function(){return(l._MaxPool3DGrad=l.asm.MaxPool3DGrad).apply(null,arguments)},l._MaxPoolGrad=function(){return(l._MaxPoolGrad=l.asm.MaxPoolGrad).apply(null,arguments)},l._MaxPoolWithArgmax=function(){return(l._MaxPoolWithArgmax=l.asm.MaxPoolWithArgmax).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._Mod=function(){return(l._Mod=l.asm.Mod).apply(null,arguments)},l._Multinomial=function(){return(l._Multinomial=l.asm.Multinomial).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._ResizeBilinearGrad=function(){return(l._ResizeBilinearGrad=l.asm.ResizeBilinearGrad).apply(null,arguments)},l._ResizeNearestNeighbor=function(){return(l._ResizeNearestNeighbor=l.asm.ResizeNearestNeighbor).apply(null,arguments)},l._ResizeNearestNeighborGrad=function(){return(l._ResizeNearestNeighborGrad=l.asm.ResizeNearestNeighborGrad).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._SearchSorted=function(){return(l._SearchSorted=l.asm.SearchSorted).apply(null,arguments)},l._SelectV2=function(){return(l._SelectV2=l.asm.SelectV2).apply(null,arguments)},l._Selu=function(){return(l._Selu=l.asm.Selu).apply(null,arguments)},l._Sigmoid=function(){return(l._Sigmoid=l.asm.Sigmoid).apply(null,arguments)},l._Sign=function(){return(l._Sign=l.asm.Sign).apply(null,arguments)},l._Sin=function(){return(l._Sin=l.asm.Sin).apply(null,arguments)},l._Sinh=function(){return(l._Sinh=l.asm.Sinh).apply(null,arguments)},l._Softmax=function(){return(l._Softmax=l.asm.Softmax).apply(null,arguments)},l._Softplus=function(){return(l._Softplus=l.asm.Softplus).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._SparseToDense=function(){return(l._SparseToDense=l.asm.SparseToDense).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._TensorScatterUpdate=function(){return(l._TensorScatterUpdate=l.asm.TensorScatterUpdate).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 Ae=l._pthread_self=function(){return(Ae=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 Ce=l.__emscripten_thread_init=function(){return(Ce=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 Me,Fe,$e,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)},Pe=l.__emscripten_thread_exit=function(){return(Pe=l.__emscripten_thread_exit=l.asm._emscripten_thread_exit).apply(null,arguments)},Le=l._emscripten_stack_set_limits=function(){return(Le=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)},We=l.stackAlloc=function(){return(We=l.stackAlloc=l.asm.stackAlloc).apply(null,arguments)};function ze(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(){Me||(Me=!0,l.calledRun=!0,L||(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?Te(e):function(){return Se(e,t,n,arguments)}},l.ExitStatus=re,l.PThread=ue,Q=function e(){Me||ze(),Me||(Q=e)},l.preInit)for("function"==typeof l.preInit&&(l.preInit=[l.preInit]);l.preInit.length>0;)l.preInit.pop()();if(ze(),u&&(Fe={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)$e=WasmBackendModule;else{if(void 0===t)throw new Error("Could not find wasm module in post.js");$e=t}if(Fe){var Ve=$e._dispose;$e._dispose=function(){Ve(),Fe.uncaughtException.forEach((function(e){He.removeListener("uncaughtException",e)})),Fe.unhandledRejection.forEach((function(e){He.removeListener("unhandledRejection",e)}))}}return t.ready}})();e.exports=n})),zA=e({__proto__:null,default:WA},[WA]),VA=Xp((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=nh,m=nh;d=p?m.dirname(d)+"/":"/Users/kodbiro/Projects/GeometryTracking/xzimg-web-sdk/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out/",o=(e,t)=>(e=P(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=P(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,w,v,k,I=!1,T="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function S(e,t,n){for(var r=(t>>>=0)+n,a=t;e[a]&&!(a>=r);)++a;if(a-t>16&&e.buffer&&T)return T.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=w=new Int8Array(e),s.HEAP16=new Int16Array(e),s.HEAP32=new Int32Array(e),s.HEAPU8=v=new Uint8Array(e),s.HEAPU16=new Uint16Array(e),s.HEAPU32=k=new Uint32Array(e),s.HEAPF32=new Float32Array(e),s.HEAPF64=new Float64Array(e)}s.INITIAL_MEMORY;var N,A,C=[],R=[],M=[],F=0,$=null;function O(e){s.onAbort&&s.onAbort(e),_(e="Aborted("+e+")"),I=!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 P(e){return e.startsWith("file://")}function L(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 W(e){try{return y.grow(e-x.byteLength+65535>>>16),E(y.buffer),1}catch(e){}}D(N="tfjs-backend-wasm.wasm")||(A=N,N=s.locateFile?s.locateFile(A,d):d+A);var z=[null,[],[]];function V(e,t){var n=z[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>>>=0)+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++>>>0]=o}else if(o<=2047){if(n+1>=a)break;t[n++>>>0]=192|o>>6,t[n++>>>0]=128|63&o}else if(o<=65535){if(n+2>=a)break;t[n++>>>0]=224|o>>12,t[n++>>>0]=128|o>>6&63,t[n++>>>0]=128|63&o}else{if(n+3>=a)break;t[n++>>>0]=240|o>>18,t[n++>>>0]=128|o>>12&63,t[n++>>>0]=128|o>>6&63,t[n++>>>0]=128|63&o}}t[n>>>0]=0}(e,v,t,n)}(e,t=J(n),n)}return t},array:e=>{var t=J(e.length);return function(e,t){w.set(e,t>>>0)}(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,(n>>>=0)?S(v,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 4294901760},emscripten_memcpy_big:function(e,t,n){v.copyWithin(e>>>0,t>>>0,t+n>>>0)},emscripten_resize_heap:function(e){var t=v.length,n=4294901760;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),W(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=k[t>>>2],i=k[t+4>>>2];t+=8;for(var u=0;u<i;u++)V(e,v[o+u>>>0]);a+=i}return k[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(F--,s.monitorRunDependencies&&s.monitorRunDependencies(F),0==F&&$){var t=$;$=null,t()}}()}function n(e){t(e.instance)}function a(t){return function(){if(!g&&(c||p)){if("function"==typeof fetch&&!P(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 L(N)}));if(i)return new Promise((function(e,t){i(N,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return L(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(F++,s.monitorRunDependencies&&s.monitorRunDependencies(F),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)||P(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._Acos=function(){return(s._Acos=s.asm.Acos).apply(null,arguments)},s._Acosh=function(){return(s._Acosh=s.asm.Acosh).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._ArgMin=function(){return(s._ArgMin=s.asm.ArgMin).apply(null,arguments)},s._Asin=function(){return(s._Asin=s.asm.Asin).apply(null,arguments)},s._Asinh=function(){return(s._Asinh=s.asm.Asinh).apply(null,arguments)},s._Atan=function(){return(s._Atan=s.asm.Atan).apply(null,arguments)},s._Atan2=function(){return(s._Atan2=s.asm.Atan2).apply(null,arguments)},s._Atanh=function(){return(s._Atanh=s.asm.Atanh).apply(null,arguments)},s._AvgPool=function(){return(s._AvgPool=s.asm.AvgPool).apply(null,arguments)},s._AvgPool3D=function(){return(s._AvgPool3D=s.asm.AvgPool3D).apply(null,arguments)},s._AvgPool3DGrad=function(){return(s._AvgPool3DGrad=s.asm.AvgPool3DGrad).apply(null,arguments)},s._AvgPoolGrad=function(){return(s._AvgPoolGrad=s.asm.AvgPoolGrad).apply(null,arguments)},s._BatchMatMul=function(){return(s._BatchMatMul=s.asm.BatchMatMul).apply(null,arguments)},s._Bincount=function(){return(s._Bincount=s.asm.Bincount).apply(null,arguments)},s._BitwiseAnd=function(){return(s._BitwiseAnd=s.asm.BitwiseAnd).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._Conv3D=function(){return(s._Conv3D=s.asm.Conv3D).apply(null,arguments)},s._Conv3DBackpropFilterV2=function(){return(s._Conv3DBackpropFilterV2=s.asm.Conv3DBackpropFilterV2).apply(null,arguments)},s._Conv3DBackpropInputV2=function(){return(s._Conv3DBackpropInputV2=s.asm.Conv3DBackpropInputV2).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._DenseBincount=function(){return(s._DenseBincount=s.asm.DenseBincount).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._Diag=function(){return(s._Diag=s.asm.Diag).apply(null,arguments)},s._Dilation2D=function(){return(s._Dilation2D=s.asm.Dilation2D).apply(null,arguments)},s._Dilation2DBackpropFilter=function(){return(s._Dilation2DBackpropFilter=s.asm.Dilation2DBackpropFilter).apply(null,arguments)},s._Dilation2DBackpropInput=function(){return(s._Dilation2DBackpropInput=s.asm.Dilation2DBackpropInput).apply(null,arguments)},s._Elu=function(){return(s._Elu=s.asm.Elu).apply(null,arguments)},s._EluGrad=function(){return(s._EluGrad=s.asm.EluGrad).apply(null,arguments)},s._Equal=function(){return(s._Equal=s.asm.Equal).apply(null,arguments)},s._Erf=function(){return(s._Erf=s.asm.Erf).apply(null,arguments)},s._Exp=function(){return(s._Exp=s.asm.Exp).apply(null,arguments)},s._Expm1=function(){return(s._Expm1=s.asm.Expm1).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._IsFinite=function(){return(s._IsFinite=s.asm.IsFinite).apply(null,arguments)},s._IsInf=function(){return(s._IsInf=s.asm.IsInf).apply(null,arguments)},s._IsNan=function(){return(s._IsNan=s.asm.IsNan).apply(null,arguments)},s._LRN=function(){return(s._LRN=s.asm.LRN).apply(null,arguments)},s._LRNGrad=function(){return(s._LRNGrad=s.asm.LRNGrad).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._LinSpace=function(){return(s._LinSpace=s.asm.LinSpace).apply(null,arguments)},s._Log=function(){return(s._Log=s.asm.Log).apply(null,arguments)},s._Log1p=function(){return(s._Log1p=s.asm.Log1p).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._MaxPool3D=function(){return(s._MaxPool3D=s.asm.MaxPool3D).apply(null,arguments)},s._MaxPool3DGrad=function(){return(s._MaxPool3DGrad=s.asm.MaxPool3DGrad).apply(null,arguments)},s._MaxPoolGrad=function(){return(s._MaxPoolGrad=s.asm.MaxPoolGrad).apply(null,arguments)},s._MaxPoolWithArgmax=function(){return(s._MaxPoolWithArgmax=s.asm.MaxPoolWithArgmax).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._Mod=function(){return(s._Mod=s.asm.Mod).apply(null,arguments)},s._Multinomial=function(){return(s._Multinomial=s.asm.Multinomial).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._ResizeBilinearGrad=function(){return(s._ResizeBilinearGrad=s.asm.ResizeBilinearGrad).apply(null,arguments)},s._ResizeNearestNeighbor=function(){return(s._ResizeNearestNeighbor=s.asm.ResizeNearestNeighbor).apply(null,arguments)},s._ResizeNearestNeighborGrad=function(){return(s._ResizeNearestNeighborGrad=s.asm.ResizeNearestNeighborGrad).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._SearchSorted=function(){return(s._SearchSorted=s.asm.SearchSorted).apply(null,arguments)},s._SelectV2=function(){return(s._SelectV2=s.asm.SelectV2).apply(null,arguments)},s._Selu=function(){return(s._Selu=s.asm.Selu).apply(null,arguments)},s._Sigmoid=function(){return(s._Sigmoid=s.asm.Sigmoid).apply(null,arguments)},s._Sign=function(){return(s._Sign=s.asm.Sign).apply(null,arguments)},s._Sin=function(){return(s._Sin=s.asm.Sin).apply(null,arguments)},s._Sinh=function(){return(s._Sinh=s.asm.Sinh).apply(null,arguments)},s._Softmax=function(){return(s._Softmax=s.asm.Softmax).apply(null,arguments)},s._Softplus=function(){return(s._Softplus=s.asm.Softplus).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._SparseToDense=function(){return(s._SparseToDense=s.asm.SparseToDense).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._TensorScatterUpdate=function(){return(s._TensorScatterUpdate=s.asm.TensorScatterUpdate).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,I||(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(),M.unshift(e);var e;U(M)}()))}F>0||(function(){if(s.preRun)for("function"==typeof s.preRun&&(s.preRun=[s.preRun]);s.preRun.length;)e=s.preRun.shift(),C.unshift(e);var e;U(C)}(),F>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)}},$=function e(){K||Z(),K||($=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 HA=WA||zA,GA=VA||e({__proto__:null,default:VA},[VA]);class jA extends je{constructor(e){super(),this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(eC),tC=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new Ge(this,ii())}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=ps();return e(),{kernelMs:ps()-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)>>>0;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,r){let a;if(null==n)a=this.write(null!=r?r:null,e,t);else{const r=this.dataIdNextNumber++;a={id:r},this.dataIdMap.set(a,{id:r,memoryOffset:n,shape:e,dtype:t,refCount:1});const s=et(e);this.wasm.tfjs.registerTensor(r,s,n)}return{dataId:a,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 KA(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!=YA&&null!=YA[r]?YA[r]:n+r}const qA=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"];let XA=null,YA={},QA=!1,JA=!1;function ZA(e,t=!1){if(QA)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)XA=e;else{YA=e;const t=qA.filter((e=>null==YA[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.`)}JA=t}let eC=-1,tC=null;di("wasm",(async()=>{const{wasm:e}=await async function(){const[e,t]=await Promise.all([At().getAsync("WASM_HAS_SIMD_SUPPORT"),At().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")?KA(e,t,null!=XA?XA:r):r+n}};JA&&(a.instantiateWasm=function(e){return(t,n)=>(function(e,t){return At().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)}))}))})),{})}(KA(e,t,null!=XA?XA:"")));let s,o=!1;a.onAbort=()=>{o||QA||(QA=!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 = "+HA.toString()],{type:"text/javascript"}),s=HA(a)):s=GA(a),s.then((e=>{o=!0,QA=!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 jA(e)}),2);var nC={modelFilename:"",featuresFilename:"",objContainer:"",fovY:50,detectScoreThs:.2,trackScoreThs:.4,footToDetect:"RIGHT_FOOT",filteringLevel:2,filteringShift:.5,validTrackedKeypThs:.2,trackedNumKeypsThs:3,activeIds:new Int32Array};function rC(e){return!!(void 0===e.outputNames||e.outputNames.length<1||e.outputNames.includes("heatmaps"))}function aC(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 sC(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 oC(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 iC(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 uC(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 lC(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 cC(e,t){var n=t.length/2,r=lC(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 pC(e){var t=new Float32Array(6);t[0]=1,t[4]=1;var n=e[0]*e[4]-e[1]*e[3];if(0!=n){n=1/n,t[0]=n*e[4],t[1]=-n*e[1],t[3]=-n*e[3],t[4]=n*e[0];var r=e[2],a=e[5];t[2]=-(t[0]*r+t[1]*a),t[5]=-(t[3]*r+t[4]*a)}return t}function hC(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*_,w=Math.floor(g),v=Math.floor(y),k=g-w,I=y-v,T=void 0,S=void 0;if(w>0&&w<l-1&&v>0&&v<c-1){for(var E=v*p+4*w,N=0;N<3;N++,E++){var A=e.data[E];T=A+k*(e.data[E+4]-A),S=e.data[E+p]+k*(e.data[E+p+4]-e.data[E+p]),t.data[b+x+N]=T+I*(S-T)}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 dC(e,t,n,r,a){for(var s=a[0],o=a[1],i=a[2],u=a[3],l=a[4],c=a[5],p=t[1],h=t[0],d=t[1],f=r[1],m=r[0],g=r[1],y=0;y<m;y++)for(var b=o*y+i,_=l*y+c,x=y*g,w=0;w<f;w++){var v=Math.floor(b),k=Math.floor(_),I=b-v,T=_-k,S=void 0,E=void 0;if(v>0&&v<p-1&&k>0&&k<h-1){var N=k*d+v,A=e[N];S=A+I*(e[N+1]-A),E=e[N+d]+I*(e[N+d+1]-e[N+d]),n[x+w]=S+T*(E-S)}else n[x+w]=0;b+=s,_+=u}return n}var fC,mC=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}(),gC=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}(),yC=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 mC(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 bC(e,t,n,r,a){void 0===a&&(a=.5);for(var s=e.length/2,o=sC(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 _C(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 mC(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 mC(u[d],u[d+p]),g=new mC(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 mC(u[l],u[l+p]).Dist(h);_>b&&(b=_)}b*=2;var x=new yC(h.x-b/2,h.y-b/2,b,b),w=Math.cos(y),v=Math.sin(y);b=(x.w+s*x.w)/Math.max(t[0],t[1]);var k=t[1]/2,I=t[0]/2,T=h.x,S=h.y;return new Float32Array([w*b,-v*b,T-(w*b*k-v*b*I),v*b,w*b,S-(v*b*k+w*b*I)])}function xC(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 wC(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=xC(new Float32Array([e[s],e[s+r]]),n);a[s]=o[0],a[s+r]=o[1]}var i=sC(a,t,r);return Math.max(i[1]-i[0],i[3]-i[2])}function vC(e,t){e.length;var n=function(e,t){var n=e.length/2,r=TC(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 kC(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 oC(e,n)}function IC(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 TC(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?15!=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 with size:",e),[0,1]):[115,167]:[210,78]:[9,11]:[9,6]:[0,9]}function SC(e,t){var n=e.length/2,r=TC(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 EC(e,t,n,r,a){void 0===a&&(a=.5);for(var s=e.length/2,o=sC(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*(1-a)/(1+Math.exp(4*l-i/2));e[u]=c*n[u]+(1-c)*e[u],e[u+s]=c*n[u+s]+(1-c)*e[u+s]}return e}function NC(e,t,n,r,a,s,o,i,u){var l,c;void 0===o&&(o=""),void 0===i&&(i=.7),void 0===u&&(u=0);var p=e.length/2,h=null,d=0,f=0,m=0,g=TC(p,s),y=g[0],b=g[1],_=[e[y],e[y+p]],x=[e[b],e[b+p]],w=Math.sqrt((_[0]-x[0])*(_[0]-x[0])+(_[1]-x[1])*(_[1]-x[1]));6==p?(f=(l=SC(e,s))[0],d=l[1],m=l[2],h=aC("RIGHT_FOOT"==s?[e[3],e[4],e[5],e[3+p],e[4+p],e[5+p]]:[e[0],e[1],e[2],e[0+p],e[1+p],e[2+p]],3),m+=u):(f=(c=SC(e,s))[0],d=c[1],m=c[2],h=sC(e,t,p),m+=u,"oriented_bbox_size"==o&&(f=(h[1]+h[0])/2,d=(h[3]+h[2])/2,t&&(w=wC(e,t,-m))));var v=Math.cos(m),k=Math.sin(m),I=(w+=i*w)/Math.max(r,n),T=(n-1)/2,S=(r-1)/2,E=f-(v*I*T-k*I*S),N=d-(k*I*T+v*I*S);if(null!=a){var A=Math.sqrt((E-a[2])*(E-a[2])+(N-a[5])*(N-a[5])),C=1;A>20&&(C=.1),A>=10&&A<=20&&(C=1-.09*(A-5)),E=(1-C)*E+C*a[2],N=(1-C)*N+C*a[5],m=Math.abs(m-a[6])>1?(1-C)*m-C*a[6]:(1-C)*m+C*a[6],I=(1-C)*I+C*a[7],v=Math.cos(m),k=Math.sin(m)}return[v*I,-k*I,E,k*I,v*I,N,m,I]}function AC(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 CC(e,t){var n=e._malloc(4*t.length);return e.HEAPF32.set(t,n/4),n}function RC(e,t,n){var r=new Float32Array(n),a=t/4;return r.set(e.HEAPF32.subarray(a,a+n)),r.slice()}function MC(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 FC(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 $C(e,t,n,r,a){var s=e.cwrap("xzimgMatchRecKeyps","number",["number","number","number","number","number"]),o=r.length/2;MC(e,t,n);for(var i=FC(e,n,t.width,t.height),u=CC(e,r),l=CC(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=RC(e,c,o),f=RC(e,l,r.length),m=RC(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 OC(e,t,n,r){var a=CC(e,t),s=CC(e,n),o=e._malloc(16);e.cwrap("xzimgEstimateGetSimilarity","number",["number","number","number","number"])(a,s,t.length/2,o);var i=RC(e,o,4);return e._free(a),e._free(s),e._free(o),i}function DC(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 PC(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,w=c*r*a+f*a+u;for(d=0;d<9;d++)b+=e[x+s[d]],_+=e[w+s[d]];var v=2*(2*h-((b/=9)+(_/=9)));if(Math.abs(v)>1e-5){var k=2*(_-b)/v;i[u]+=k}var I=0,T=0,S=y*r*a+l*a+u,E=g*r*a+l*a+u;for(d=0;d<9;d++)I+=e[S+s[d]],T+=e[E+s[d]];v=2*(2*h-((I/=9)+(T/=9))),Math.abs(v)>1e-5&&(k=2*(T-I)/v,i[a+u]+=k)}return[i,o]}(e,s,t[1],t[2],t[3]),o=a[0],i=a[1]):o=s,[o,i]}function LC(e,t,n,r,a,s,o,i){void 0===i&&(i=[""]);for(var u,l,c,p,h,d,f,m,g,y=[],b=[],_=[],x=[],w=[],v=0,k=null,I=0,T=o;I<T.length;I++){var S=T[I],E=Nu(S);w.push(E);var N=gu(E,"float32");w.push(N);var A=El(N,[1,t.inHeight,t.inWidth,3]);w.push(A);var C=Oc(255),R=Qu(A,C);w.push(R),"left_right"!=i[v]&&"up_down"!=i[v]||(R=yh(R,"left_right"==i[v]?2:1),w.push(R)),k?(k=Rl([k,R]),w.push(k)):k=R,v+=1}if(null!=k){var M=[];if(t.numOutputs&&1!=t.numOutputs)for(var F=0,$=M=e.predict(k);F<$.length;F++){var O=$[F];w.push(O)}else{var D=e.predict(k);w.push(D),M.push(D)}for(var P=0,L=0,B=M;L<B.length;L++){D=B[L];for(var U=[],W=[],z=0,V=Jh(D,0);z<V.length;z++){var H=V[z];w.push(H);var G=Vc(H,0);w.push(G),U.push(H.dataSync()),W.push(G.shape)}if(t.outputNames&&"heatmaps"!=t.outputNames[P]){if(t.outputNames&&"masks"==t.outputNames[P])for(ee=0;ee<U.length;ee++)x.push(U[ee]);else if(t.outputNames&&"coordinates"==t.outputNames[P])for(ee=0;ee<U.length;ee++){for(var j=W[ee][1]/2,K=new Float32Array(2*j),q=t.inHeight/2,X=t.inWidth/2,Y=0;Y<j;Y++)K[Y]=(U[ee][Y]+1)*X,K[Y+j]=(U[ee][Y+j]+1)*q;y.push(K)}else if(t.outputNames&&"scores"==t.outputNames[P])if(t.outputTypes&&"logits"==t.outputTypes[P])for(ee=0;ee<U.length;ee++){var Q=W[ee][1],J=new Float32Array(Q);for(Y=0;Y<Q;Y++)J[Y]=1/(1+Math.exp(-U[ee][Y]));b.push(J)}else for(ee=0;ee<U.length;ee++){for(Q=W[ee][1],J=new Float32Array(Q),Y=0;Y<Q;Y++)J[Y]=U[ee][Y];b.push(J)}else if(t.outputNames&&"occlusions"==t.outputNames[P])if(t.outputTypes&&"logits"==t.outputTypes[P])for(ee=0;ee<U.length;ee++){Q=W[ee][1];var Z=new Float32Array(Q);for(Y=0;Y<Q;Y++)Z[Y]=1/(1+Math.exp(-U[ee][Y]));_.push(Z)}else for(ee=0;ee<U.length;ee++){for(Q=W[ee][1],Z=new Float32Array(Q),Y=0;Y<Q;Y++)Z[Y]=U[ee][Y];_.push(Z)}}else for(var ee=0;ee<U.length;ee++){var te=void 0;n?(u=n,l=W[ee],c=U[ee],p=r[ee],h=a[ee],d=s[ee],f=void 0,f=u.cwrap("xzimgGetHeatmapsLocations","number",["number","number","number","number","number","number","number","number"]),m=l[1]*l[2]*l[3],g=p/4,u.HEAPF32.subarray(g,g+m).set(c),f(p,l[1],l[2],l[3],0,1,h,d),te=[new Float32Array(u.HEAPF32.buffer,h,2*l[3]),new Float32Array(u.HEAPF32.buffer,d,l[3])]):te=PC(U[ee],W[ee],!0),y.push(te[0]),b.push(te[1])}P+=1}}return w.forEach((function(e){return e.dispose()})),{coordinates:y,scores:b,occlusions:_,masks:x}}function BC(e,t){var n=new ie(0),r=n.asObservable();if("string"==typeof e)return{model$:a=dk({url:e,method:"GET",responseType:"text",async:!0,progressSubscriber:new v((function(e){return n.next(e.loaded/e.total)}),(function(e){}),(function(){return n.next(1)}))}).pipe(ue(2),K((function(e){return UC(e.response,t)}))),progress$:r};var a=be((function(){return n.next(1),j(UC(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 UC(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[_],w=b[2*x],v=b[2*x+1],k=o.faces[_];o.uvs[2*k]=w,o.uvs[2*k+1]=v}}}if(t){for(_=0;_<o.faces.length;_+=3){var I=o.faces[_];o.faces[_]=o.faces[_+1],o.faces[_+1]=I}for(_=0;_<o.vertices.length;_+=3)o.vertices[_]=-o.vertices[_]}return o}!function(e){e.Detection="DETECTION",e.Detected="DETECTED",e.Tracking="TRACKING"}(fC||(fC={}));var WC,zC=function(){function e(e,t){this._trackingState=fC.Detection,this._type=0,this._R=Float32Array.from(e),this._t=Float32Array.from(t),this._trackingState=fC.Detection}return e.prototype.setTrackingState=function(e){this._trackingState=e},e.prototype.getTrackingState=function(){return this._trackingState},e.prototype.isDetected=function(){return this._trackingState==fC.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}(),VC=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()!==fC.Tracking||r.getTrackingState()!==fC.Tracking)return n;for(var a=zC.getQuatFromRotMat(t.R()),s=zC.getQuatFromRotMat(r.R()),o=zC.slerp(a,s,.5),i=zC.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 zC(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()!==fC.Tracking||t.getTrackingState()!==fC.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=zC.getQuatFromRotMat(e.R()),u=zC.getQuatFromRotMat(t.R()),l=zC.slerp(i,u,this._interpolation),c=zC.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 zC(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"}(WC||(WC={}));var HC,GC="config.bin",jC=function(){function e(){this._initialized=!1,this._currentWidth=0,this._currentHeight=0,this._trackingState=fC.Detection,this._useWasmForHeatmaps=!1,this._float_size=4,this._bufferHeatmaps=null,this._bufferKeypsDet=null,this._bufRightScores=null,this._bufLeftScores=null,this._bufKeyps3D_R=null,this._bufKeyps3D_L=null,this._footToDetect=WC.Right,this._leftFootState=fC.Detection,this._rightFootState=fC.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._useRecursiveFilter=!0,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=WC.Right);var t=null;return(t=e==WC.Right?this._poseManager_R.getInterpolatedPose():this._poseManager_L.getInterpolatedPose())?t.getPosition():null},e.prototype.getRotation=function(e){void 0===e&&(e=WC.Right);var t=null;return(t=e==WC.Right?this._poseManager_R.getInterpolatedPose():this._poseManager_L.getInterpolatedPose())?t.getRotation():null},e.prototype.getPose=function(e){return void 0===e&&(e=WC.Right),e==WC.Right?this._pose_L:this._pose_R},e.prototype.getMask=function(e,t){var n=new Float32Array(e*t),r=[this._footFeaturesConfig.outHeight,this._footFeaturesConfig.outWidth];if(this._rightFootState==fC.Tracking&&this._leftFootState==fC.Tracking){var a=Float32Array.from(this._simToImage_L),s=Float32Array.from(this._simToImage_R),o=e/this._currentWidth,i=t/this._currentHeight;a[0]=o*a[0],a[1]=o*a[1],a[3]=i*a[3],a[4]=i*a[4],a[2]=o*a[2],a[5]=i*a[5],(a=pC(a))[3]=-a[3],a[4]=-a[4],a[5]=-a[5]+(r[0]-1),s[0]=o*s[0],s[1]=o*s[1],s[3]=i*s[3],s[4]=i*s[4],s[2]=o*s[2],s[5]=i*s[5],s=pC(s),this._leftFootMask&&this._rightFootMask&&function(e,t,n,r,a,s,o){for(var i=s[0],u=s[1],l=s[2],c=s[3],p=s[4],h=s[5],d=o[0],f=o[1],m=o[2],g=o[3],y=o[4],b=o[5],_=n[1],x=n[0],w=n[1],v=a[1],k=a[0],I=a[1],T=0;T<k;T++)for(var S=u*T+l,E=p*T+h,N=f*T+m,A=y*T+b,C=T*I,R=0;R<v;R++){var M=Math.floor(S),F=Math.floor(E),$=S-M,O=E-F,D=void 0,P=0,L=0;M>0&&M<_-1&&F>0&&F<x-1&&(P=(D=(U=e[B=F*w+M])+$*(e[B+1]-U))+O*(e[B+w]+$*(e[B+w+1]-e[B+w])-D),L=Math.abs(x/2-E),L/=x/2,L=1/(1+Math.exp(30*L-20))),$=N-(M=Math.floor(N)),O=A-(F=Math.floor(A));var B,U,W=0,z=0;M>0&&M<_-1&&F>0&&F<x-1&&(W=(D=(U=t[B=F*w+M])+$*(t[B+1]-U))+O*(t[B+w]+$*(t[B+w+1]-t[B+w])-D),z=Math.abs(x/2-A),z/=x/2,z=1/(1+Math.exp(30*z-20)));var V=z+L;r[C+R]=V>0?Math.max(L*P,z*W):0,S+=i,E+=c,N+=d,A+=g}}(this._leftFootMask,this._rightFootMask,new Float32Array(r),n,new Float32Array([t,e]),a,s)}else if(this._rightFootState==fC.Tracking){var u=Float32Array.from(this._simToImage_R);o=e/this._currentWidth,i=t/this._currentHeight,u[0]=o*u[0],u[1]=o*u[1],u[3]=i*u[3],u[4]=i*u[4],u[2]=o*u[2],u[5]=i*u[5],u=pC(u),this._rightFootMask&&dC(this._rightFootMask,new Float32Array(r),n,new Float32Array([t,e]),u)}else this._leftFootState==fC.Tracking&&(u=Float32Array.from(this._simToImage_L),o=e/this._currentWidth,i=t/this._currentHeight,u[0]=o*u[0],u[1]=o*u[1],u[3]=i*u[3],u[4]=i*u[4],u[2]=o*u[2],u[5]=i*u[5],(u=pC(u))[3]=-u[3],u[4]=-u[4],u[5]=-u[5]+(r[0]-1),this._leftFootMask&&dC(this._leftFootMask,new Float32Array(r),n,new Float32Array([t,e]),u));return n},e.prototype.getInterpolatedPose=function(e){return void 0===e&&(e=WC.Right),e==WC.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,w=this;return s(this,(function(s){switch(s.label){case 0:if(null==e)throw"Invalid parameter";return this._config=n?t(t({},nC),n):nC,(null===(o=null==n?void 0:n.wasmBackend)||void 0===o?void 0:o.enable)?(ZA({"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,pi("wasm")]):[3,2];case 1:return s.sent(),[3,3];case 2:pi("webgl"),s.label=3;case 3:return this.release(),this._videoManager=e,"BOTH"!==this._config.footToDetect&&"BOTH_FEET"!==this._config.footToDetect||(this._footToDetect=WC.Both),this._poseManager_R=new VC(this._videoManager.getNbFramesDelay()),this._poseManager_R.setInterpolation(this._config.filteringShift),this._poseManager_R.setFilteringLevel(this._config.filteringLevel),this._poseManager_L=new VC(this._videoManager.getNbFramesDelay()),this._poseManager_L.setInterpolation(this._config.filteringShift),this._poseManager_L.setFilteringLevel(this._config.filteringLevel),a=new ie(0),c=G(nT({locateFile:function(e,t){return w._config.poseEstimationWasmFilename||t+e}})).pipe(me((function(){return a.next(1)}))),p=KI(this._config.modelFilename,GC),h=p.model$,d=p.progress$,f=KI(this._config.featuresFilename,GC),m=f.model$,g=f.progress$,y=BC(this._config.objContainer,!1),b=y.model$,_=y.progress$,x=z([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,Xv({poseModule:c,model:h,features:m,footObjModel:b}).pipe(K((function(e){var t;w._poseModule=e.poseModule,w._footObjModel=e.footObjModel,w._tfFootDetector=e.model.graphModel,w._footDetectorConfig=e.model.config,w._tfFootFeatures=e.features.graphModel,w._footFeaturesConfig=e.features.config,w._activeIds=w._config.activeIds;var n=kp([1,w._footDetectorConfig.inHeight,w._footDetectorConfig.inWidth,3]),r=w._tfFootDetector.predict(n);w._footDetectorShape=r.shape,r.dataSync(),r.dispose(),n.dispose();var a=w._footDetectorConfig.outChannels;n=kp([1,w._footFeaturesConfig.inHeight,w._footFeaturesConfig.inWidth,3]),(r=w._tfFootFeatures.predict(n))instanceof Array?r.forEach((function(e){return e.dispose()})):r.dispose(),n.dispose(),n=kp([2,w._footFeaturesConfig.inHeight,w._footFeaturesConfig.inWidth,3]),(r=w._tfFootFeatures.predict(n))instanceof Array?r.forEach((function(e){return e.dispose()})):r.dispose(),n.dispose();var s=w._footFeaturesConfig.outChannels;if(w._footFeaturesConfig.outputNames&&w._footFeaturesConfig.numOutputs&&w._footFeaturesConfig.numOutputs>1)for(var o=0,i=0,u=w._footFeaturesConfig.outputNames;i<u.length;i++){var l=u[i];"heatmaps"==l?s=w._footFeaturesConfig.outputDims[3*o+2]:"coordinates"==l&&(s=w._footFeaturesConfig.outputDims[3*o+2]/2),o+=1}if(t=function(e,t){var n=[];if(13==t)n=[[20],[40],[45],[47],[50,141],[67],[69],[95],[132,177],[157],[160],[164],[189]];else if(15==t)n=[[20],[40],[45,166],[47],[50,141],[67],[33,69],[171,192],[132,177],[157],[39,160],[164],[189],[26],[186]];else if(18==t)for(var r=[54,210,295,406,415,416,417,423,425,463,518,582,644,657,721,726,730,813],a=0;a<t;a++)n.push([r[a]]);else for(a=0;a<t;a++)n.push([a]);var s=new Float32Array(3*t),o=function(t){var r=n[t];Array.isArray(r)&&(r.forEach((function(n){s[3*t]+=e[3*n],s[3*t+1]+=e[3*n+1],s[3*t+2]+=e[3*n+2]})),s[3*t]/=r.length,s[3*t+1]/=r.length,s[3*t+2]/=r.length)};for(a=0;a<t;a++)o(a);var i=new Float32Array(3*t);for(a=0;a<t;a++)i[3*a]=-s[3*a],i[3*a+1]=s[3*a+1],i[3*a+2]=s[3*a+2];return[s,i]}(w._footObjModel.vertices,s),w._rightKeyps3D=t[0],w._leftKeyps3D=t[1],w._bufKeyps3D_R=w._poseModule._malloc(w._rightKeyps3D.length*w._float_size),w._poseModule.HEAPF32.set(w._rightKeyps3D,w._bufKeyps3D_R/4),w._bufKeyps3D_L=w._poseModule._malloc(w._leftKeyps3D.length*w._float_size),w._poseModule.HEAPF32.set(w._leftKeyps3D,w._bufKeyps3D_L/4),w._footDetectorConfig.outWidth>1&&w._footDetectorConfig.outHeight>1){var c=a*w._footDetectorConfig.outWidth*w._footDetectorConfig.outHeight;w._bufferHeatmaps=w._poseModule._malloc(c*w._float_size)}w._footFeaturesConfig.outWidth>1&&w._footFeaturesConfig.outHeight>1&&(c=s*w._footFeaturesConfig.outWidth*w._footFeaturesConfig.outHeight,w._bufferHeatmaps_L=w._poseModule._malloc(c*w._float_size),w._bufferHeatmaps_R=w._poseModule._malloc(c*w._float_size)),w._bufferKeypsDet=w._poseModule._malloc(2*a*w._float_size),w._bufferKeypsTrack_L=w._poseModule._malloc(2*s*w._float_size),w._bufferKeypsTrack_R=w._poseModule._malloc(2*s*w._float_size),w._bufRightScores=w._poseModule._malloc(s*w._float_size),w._bufLeftScores=w._poseModule._malloc(s*w._float_size),w._pose_R=new zC(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0])),w._pose_L=new zC(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0])),w._trackHasHeatmaps=rC(w._footFeaturesConfig),w._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._bufRightScores),this._poseModule._free(this._bufLeftScores),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=e;null==e&&(n=this._videoManager.getLastBuffer()),null!=n?(n.width===this._currentWidth&&n.height===this._currentHeight||(this._currentWidth=n.width,this._currentHeight=n.height,t=zC.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()),this.trackFootSync(n)):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!=fC.Detection&&this._leftFootState!=fC.Detection){var n=this.trackFeetFeaturesSync(e,this._leftFootState,this._rightFootState,this._leftFootState==fC.Detected?this._initShape:this._leftFootRecShape,this._rightFootState==fC.Detected?this._initShape:this._rightFootRecShape,this._leftFootVis,this._rightFootVis,this._leftFootOcclusions,this._rightFootOcclusions),r=kC(n.scores_R,"RIGHT_FOOT",this._config.validTrackedKeypThs);this._rightFootRecShape=n.refinedFeatures_R,this._rightFootOcclusions=n.occlusions_R,this._rightFootVis=r.visibilty,this._rightFootMask=n.mask_R;var a=kC(n.scores_L,"LEFT_FOOT",this._config.validTrackedKeypThs);this._leftFootRecShape=n.refinedFeatures_L,this._leftFootOcclusions=n.occlusions_L,this._leftFootVis=a.visibilty,this._leftFootMask=n.mask_L;var s=this._config.trackScoreThs,o=this._reproj_t;this._fastMovements_R&&(o=this._reproj_fast_t);var i=this._rightFootRecShape.length/2,u=TC(i,"RIGHT_FOOT"),l=new yC(0,0,e.width,e.height),c=new mC((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=fC.Tracking,t>o&&(this._rightFootState=fC.Detection)):this._rightFootState=fC.Detection,s=this._config.trackScoreThs,this._fastMovements_L&&(s=.1),o=this._reproj_t,this._fastMovements_L&&(o=this._reproj_fast_t),u=TC(i,"LEFT_FOOT");var p=new mC((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=fC.Tracking,t>o&&(this._leftFootState=fC.Detection)):this._leftFootState=fC.Detection,this._leftFootState==fC.Tracking&&this._rightFootState==fC.Tracking&&this.bothFeetSamePlace()&&(this._leftFootState=fC.Detection,this._rightFootState=fC.Detection)}else if(this._rightFootState!==fC.Detection&&this._leftFootState===fC.Detection){var h=this.trackFootFeaturesSync(e,this._rightFootState,this._rightFootState==fC.Detected?this._initShape:this._rightFootRecShape,this._rightFootVis,this._rightFootOcclusions,"RIGHT_FOOT");this._rightFootRecShape=h.refinedFeatures,this._rightFootOcclusions=h.occlusions,this._rightFootMask=h.mask,r=kC(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=TC(this._rightFootRecShape.length/2,"RIGHT_FOOT"),r.globalScore>=s&&r.totalVisible>=this._config.trackedNumKeypsThs?(t=this.computePoseSync(this._rightFootState,"RIGHT_FOOT"),this._rightFootState=fC.Tracking,t>o&&(this._rightFootState=fC.Detection)):this._rightFootState=fC.Detection;var d=this.detectFeetSync(e);this._initShape=d.refinedFeatures,a=kC(d.scores,"LEFT_FOOT",this._config.detectScoreThs),r=kC(d.scores,"RIGHT_FOOT",this._config.detectScoreThs);var f=!1;if(!this._fastMovements_R&&null!=this._cnnOutputDataInvMask){var m=PC(this._cnnOutputDataInvMask,this._footDetectorShape,!1);m[0];var g=kC(_=m[1],"LEFT_FOOT",this._config.detectScoreThs),y=kC(_,"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=fC.Detected):a.globalScore>=this._config.detectScoreThs&&(this._leftFootRecShape=d.refinedFeatures,this._leftFootState=fC.Detected)}else if(this._leftFootState!==fC.Detection&&this._rightFootState===fC.Detection){var b=this.trackFootFeaturesSync(e,this._leftFootState,this._leftFootState==fC.Detected?this._initShape:this._leftFootRecShape,this._leftFootVis,this._leftFootOcclusions,"LEFT_FOOT");if(this._leftFootRecShape=b.refinedFeatures,this._leftFootOcclusions=b.occlusions,this._leftFootMask=b.mask,a=kC(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=TC(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=fC.Tracking,t>o&&(this._leftFootState=fC.Detection)):this._leftFootState=fC.Detection,d=this.detectFeetSync(e),this._initShape=d.refinedFeatures,r=kC(d.scores,"RIGHT_FOOT",this._config.detectScoreThs),a=kC(d.scores,"LEFT_FOOT",this._config.detectScoreThs),f=!1,!this._fastMovements_L&&null!=this._cnnOutputDataInvMask){var _,x=PC(this._cnnOutputDataInvMask,this._footDetectorShape,!1);x[0],g=kC(_=x[1],"LEFT_FOOT",this._config.detectScoreThs),y=kC(_,"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=fC.Detected):r.globalScore>=this._config.detectScoreThs&&(this._rightFootRecShape=d.refinedFeatures,this._rightFootState=fC.Detected)}else if(this._leftFootState===fC.Detection||this._rightFootState===fC.Detection){var w=this.detectFeetSync(e);if(this._initShape=w.refinedFeatures,a=kC(w.scores,"LEFT_FOOT",this._config.detectScoreThs),r=kC(w.scores,"RIGHT_FOOT",this._config.detectScoreThs),a.globalScore>=this._config.detectScoreThs&&(this._leftFootState=fC.Detected),r.globalScore>=this._config.detectScoreThs&&(this._rightFootState=fC.Detected),this._rightFootState!=fC.Detection&&this._leftFootState!=fC.Detection&&this.bothFeetSamePlaceInit()&&(this._rightFootState==fC.Detected?this._rightFootState=fC.Detection:this._leftFootState=fC.Detection),this._leftFootState==fC.Detected||this._rightFootState==fC.Detected){this._leftFootRecShape=w.refinedFeatures,this._rightFootRecShape=w.refinedFeatures,this._fastMovements_L=!0,this._fastMovements_R=!0;var v=this._poseModule.cwrap("xzimgMatchRecKeypsInit","number",["number"]);null==this._hptrImageBuffer&&(this._hptrImageBuffer=this._poseModule._malloc(e.width*e.height*4)),MC(this._poseModule,e,this._hptrImageBuffer);var k=FC(this._poseModule,this._hptrImageBuffer,e.width,e.height);v(k),this._poseModule._free(k)}}this._leftFootState===fC.Detection&&(this._pose_L=new zC(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0]))),this._rightFootState==fC.Detection&&(this._pose_R=new zC(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=Nu(e),c=gu(l,"float32"),p=El(c,[1,this._currentHeight,this._currentWidth,3]),h=cf.cropAndResize(p,[o],[0],[this._footDetectorConfig.inHeight,this._footDetectorConfig.inWidth]),d=Oc(255),f=Qu(h,d),m=null;if(this._footToDetect==WC.Both&&(this._leftFootState===fC.Tracking||this._rightFootState===fC.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=vC(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),w=0;w<t;w++)for(var v=0;v<n;v++){var k=v-h,I=w-d,T=k*f+I*m,S=k*g+I*y;T>0&&S>0&&T<b&&S<_||(x[w*n+v]=1)}return x}(this._leftFootState===fC.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===fC.Tracking?"LEFT_FOOT":"RIGHT_FOOT"),y=Gh(g,"float32");m=El(y,[1,this._footDetectorConfig.inHeight,this._footDetectorConfig.inWidth,1]),y.dispose()}var b=this._tfFootDetector.predict(f);if(null!=m){var _=lp(1,m),x=Ju(b,_);this._cnnOutputDataInvMask=x.dataSync(),_.dispose(),x.dispose();var w=Ju(b,m);b.dispose(),b=w,m.dispose()}var v,k,I=null!==(n=null==b?void 0:b.shape[3])&&void 0!==n?n:this._footDetectorConfig.outChannels,T=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;v=(t=PC(b.dataSync(),[1,T,S,I],!1))[0],k=t[1];var E=this._bufferKeypsDet/4;this._poseModule.HEAPF32.subarray(E,E+2*I).set(v),l.dispose(),c.dispose(),d.dispose(),h.dispose(),f.dispose(),p.dispose(),b.dispose();var N=Math.min(this._currentWidth,this._currentHeight),A=N/this._footDetectorConfig.inWidth,C=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,C,A),{refinedFeatures:IC(v,this._simToImage_Det,!1,b.shape[1]),scores:k}},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(this._useRecursiveFilter&&t!=fC.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>.5&&(r[t]=0)}))),i=(o=$C(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=DC(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++)n[f]=n[f]+h[0],n[f+d]=n[f+d]+h[1]}else i=n;c=NC(n,r,this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight,null,s,this._footFeaturesConfig.normSizeMode?this._footFeaturesConfig.normSizeMode:"",this._footFeaturesConfig.normExtRatio?this._footFeaturesConfig.normExtRatio:.7,this._footFeaturesConfig.normAngleShift?this._footFeaturesConfig.normAngleShift:0);var m=new ImageData(this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight);m=hC(e,m,c);var g=LC(this._tfFootFeatures,this._footFeaturesConfig,this._poseModule,"LEFT_FOOT"==s?[this._bufferHeatmaps_L]:[this._bufferHeatmaps_R],"LEFT_FOOT"==s?[this._bufferKeypsTrack_L]:[this._bufferKeypsTrack_R],[this._bufRightScores],[m],"LEFT_FOOT"==s?["up_down"]:[""]),y=IC(g.coordinates[0],c,"LEFT_FOOT"==s,this._footFeaturesConfig.outHeight);if("LEFT_FOOT"==s?this._simToImage_L=c:this._simToImage_R=c,this._useRecursiveFilter&&t!=fC.Detected){var b=iC(g.scores[0],this._config.validTrackedKeypThs);y=EC(y,b,i,b,0)}return{refinedFeatures:y,scores:g.scores[0],occlusions:g.occlusions[0],mask:g.masks.length>0?g.masks[0]:new Float32Array([])}},e.prototype.trackFeetFeaturesSync=function(e,t,n,r,a,s,o,i,u){var l,c,p;if(this._useRecursiveFilter&&t!=fC.Detected&&n!=fC.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>.5&&(d[t]=0)})));var g=$C(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),w=OC(this._poseModule,r,c),v=OC(this._poseModule,a,p);Math.sqrt(w[2]*w[2]+w[3]*w[3])>10?this._fastMovements_L=!0:this._fastMovements_L=!1,Math.sqrt(v[2]*v[2]+v[3]*v[3])>10?this._fastMovements_R=!0:this._fastMovements_R=!1;var k=DC(r,c,_);this._pose_L.translate(k[0]*this._pose_L.t()[2]/this._fx,k[1]*this._pose_L.t()[2]/this._fy,0);var I=DC(a,p,x);this._pose_R.translate(I[0]*this._pose_R.t()[2]/this._fx,I[1]*this._pose_R.t()[2]/this._fy,0);for(var T=p.length/2,S=0;S<T;S++)a[S]=a[S]+I[0],a[S+T]=a[S+T]+I[1],r[S]=r[S]+k[0],r[S+T]=r[S+T]+k[1]}else c=r,p=a;this._simToImage_L=NC(r,s,this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight,null,"LEFT_FOOT",this._footFeaturesConfig.normSizeMode?this._footFeaturesConfig.normSizeMode:"",this._footFeaturesConfig.normExtRatio?this._footFeaturesConfig.normExtRatio:.7,this._footFeaturesConfig.normAngleShift?this._footFeaturesConfig.normAngleShift:0);var E=new ImageData(this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight);E=hC(e,E,this._simToImage_L),this._simToImage_R=NC(a,o,this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight,null,"RIGHT_FOOT",this._footFeaturesConfig.normSizeMode?this._footFeaturesConfig.normSizeMode:"",this._footFeaturesConfig.normExtRatio?this._footFeaturesConfig.normExtRatio:.7,this._footFeaturesConfig.normAngleShift?this._footFeaturesConfig.normAngleShift:0);var N=new ImageData(this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight);N=hC(e,N,this._simToImage_R),this._debug&&n!=fC.Detected&&(this._debugInitialized=!0,this._debugImage=N,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,N));var A=LC(this._tfFootFeatures,this._footFeaturesConfig,this._poseModule,[this._bufferHeatmaps_L,this._bufferHeatmaps_R],[this._bufferKeypsTrack_L,this._bufferKeypsTrack_R],[this._bufRightScores,this._bufLeftScores],[E,N],["up_down",""]),C=IC(A.coordinates[0],this._simToImage_L,!0,this._footFeaturesConfig.outHeight),R=IC(A.coordinates[1],this._simToImage_R,!1,this._footFeaturesConfig.outHeight);return this._useRecursiveFilter&&t!=fC.Detected&&(C=EC(C,iC(A.scores[0],this._config.validTrackedKeypThs),c,s,0)),this._useRecursiveFilter&&n!=fC.Detected&&(R=EC(R,iC(A.scores[1],this._config.validTrackedKeypThs),p,o,0)),{refinedFeatures_L:C,refinedFeatures_R:R,scores_L:A.scores[0],scores_R:A.scores[1],occlusions_L:A.occlusions[0],occlusions_R:A.occlusions[1],mask_L:A.masks.length>0?A.masks[0]:new Float32Array([]),mask_R:A.masks.length>1?A.masks[1]:new Float32Array([])}},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==fC.Detected||e==fC.Tracking){var s=1;e==fC.Detected&&(s=0);var o=3;"LEFT_FOOT"!=t||this._fastMovements_L||(o=1),"RIGHT_FOOT"!=t||this._fastMovements_R||(o=1);var i=new Float32Array(18);"LEFT_FOOT"==t?(i.set(this._pose_L.R()),i.set(this._pose_L.t(),9)):(i.set(this._pose_R.R()),i.set(this._pose_R.t(),9));var u=AC(this._poseModule,i),l=("LEFT_FOOT"==t?this._simToImage_L:this._simToImage_R,Float32Array.from([1,0,0,0,1,0]));this._trackHasHeatmaps;var c=AC(this._poseModule,l),p=null,h=null,d=new Float32Array(2*this._activeIds.length),f=new Float32Array(3*this._activeIds.length),m="LEFT_FOOT"==t?this._leftFootRecShape:this._rightFootRecShape,g="LEFT_FOOT"==t?this._leftKeyps3D:this._rightKeyps3D,y=m.length/2;this._activeIds.length>0?(this._activeIds.forEach((function(e,t){d[t]=m[e],d[t+n._activeIds.length]=m[e+y]})),p=AC(this._poseModule,d),this._activeIds.forEach((function(e,t){f[3*t]=g[3*e],f[3*t+1]=g[3*e+1],f[3*t+2]=g[3*e+2]})),h=AC(this._poseModule,f),y=this._activeIds.length):(p=AC(this._poseModule,m),h=AC(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,y,0,c,p,h,s,1,o,u))&&(r=1e4),"LEFT_FOOT"==t?this._pose_L=new zC(new Float32Array(this._poseModule.HEAPF32.buffer,u,9),new Float32Array(this._poseModule.HEAPF32.buffer,u+9*this._float_size,3)):this._pose_R=new zC(new Float32Array(this._poseModule.HEAPF32.buffer,u,9),new Float32Array(this._poseModule.HEAPF32.buffer,u+9*this._float_size,3)),c&&this._poseModule._free(c),p&&this._poseModule._free(p),h&&this._activeIds.length>0&&this._poseModule._free(h)}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=vC(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=vC(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}(),KC={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},qC=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 XC(e){return e==HC.UpperBody||e==HC.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"}(HC||(HC={}));var YC="config.json",QC=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=fC.Detection,this._denseVertices=new Float32Array(0),this._bsCoefs=new Float32Array(0),this._geometryType=HC.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===fC.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.isMirrored=function(){return""!=this._flipMode},e.prototype.getMask=function(e,t){var n=new Float32Array(e*t),r=[this._trackerConfig.outHeight,this._trackerConfig.outWidth],a=Float32Array.from(this._simCropToImage),s=e/this._currentWidth,o=t/this._currentHeight;return a[0]=s*a[0],a[1]=s*a[1],a[3]=o*a[3],a[4]=o*a[4],a[2]=s*a[2],a[5]=o*a[5],a=pC(a),this.isMirrored()&&(a[3]=-a[3],a[4]=-a[4],a[5]=-a[5]+(r[0]-1)),this._objectMask&&dC(this._objectMask,new Float32Array(r),n,new Float32Array([t,e]),a),n},e.prototype.getInterpolatedPose=function(){return this._poseManager.getInterpolatedPose()},e.prototype.isInitialized=function(){return this._initialized},e.prototype.getReprojError=function(){return this._reprojError},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,w,k,I,T,S,E,N=this;return s(this,(function(s){switch(s.label){case 0:if(null==e)throw"Invalid parameter";return this._config=n?t(t({},KC),n):KC,(null===(o=null==n?void 0:n.wasmBackend)||void 0===o?void 0:o.enable)?(ZA({"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,pi("wasm")]):[3,2];case 1:return s.sent(),[3,3];case 2:pi("webgl"),s.label=3;case 3:return this.release(),this._videoManager=e,this._poseManager=new VC(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 HC.Lamborghini;if("HORSE"===e)return HC.Horse;if("WATSON-CAN"===e)return HC.WatsonCan;if("MARTELL-BOTTLE"===e)return HC.MartellBottle;if("NECKLACE"===e)return HC.Necklace;if("WRIST"===e)return HC.Wrist;if("HAND"===e)return HC.Hand;if("UPPER-BODY"===e)return HC.UpperBody;if("FULL-BODY"===e)return HC.FullBody;if("CAN-KIVISENSE"===e)return HC.CanKivisense;if("TOY-TRUCK"===e)return HC.ToyTruck;if("CHIVAS"===e)return HC.Chivas;if("CHIVAS-LARGE"===e)return HC.ChivasLarge;if("LION"===e)return HC.Lion;if("BARTENDER"===e)return HC.Bartender;if("WCBOTTLE"===e)return HC.Wcbottle;if("EQA"===e)return HC.EQA;if("FACE"===e)return HC.Face}return HC.Lamborghini}(this._config.geometryToDetect),a=new ie(0),c=G(nT({locateFile:function(e,t){return N._config.poseEstimationWasmFilename||t+e}})).pipe(me((function(){return a.next(1)}))),p=KI(this._config.modelFilename,YC),h=p.model$,d=p.progress$,f=KI(this._config.featuresFilename,YC),m=f.model$,g=f.progress$,b=new ie(0),"string"==typeof this._config.objContainer&&""===this._config.objContainer?(y=j({vertices:new Float32Array,uvs:new Float32Array,faces:new Uint16Array}),b.next(1)):(_=BC(this._config.objContainer,!1),x=_.model$,w=_.progress$,y=x,b=w),k=new ie(0),this._config.pdmContainer?(A=this._config.pdmContainer,C=k,I="string"==typeof A?dk({url:A,method:"GET",responseType:"arraybuffer",async:!0,progressSubscriber:new v((function(e){return C.next(.5*e.loaded/e.total)}),(function(e){}),(function(){return C.next(.5)}))}).pipe(ue(2),pe((function(e){return j(Kk(new Uint8Array(e.response)))})),pe((function(e){var t=Object.keys(e);return t.length>1&&console.warn("XZIMG: Tried to load zip file that has these files inside: ".concat(t,". Only one file is expected.")),C.next(1),j(e[t[0]])}))):j(Kk(new Uint8Array(A))).pipe(pe((function(e){var t=Object.keys(e);return t.length>1&&console.warn("XZIMG: Tried to load zip file that has these files inside: ".concat(t,". Only one file is expected.")),C.next(1),j(e[t[0]])})))):(k.next(1),I=j(null)),new ie(0),this._config.subTrackerFilename&&""!=this._config.subTrackerFilename?(S=KI(this._config.subTrackerFilename,YC),T=S.model$,S.progress$):T=j(null),E=z([a,d,k,g,b]).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,Xv({poseModule:c,detectorModel:h,pdmModel:I,trackerModel:m,geometryObjModel:y,subTracker:T}).pipe(K((function(e){var t;N._poseModule=e.poseModule,N._geometryObjModel=e.geometryObjModel,N._tfKeypointsDetector=e.detectorModel.graphModel,N._detectorConfig=e.detectorModel.config,N._tfKeypointsTracker=e.trackerModel.graphModel,N._trackerConfig=e.trackerModel.config;var n=kp([1,N._detectorConfig.inHeight,N._detectorConfig.inWidth,3]),r=N._tfKeypointsDetector.predict(n);N._detectorOutDims=r.shape,r.dispose(),N._detectorConfig.inHeight===N._trackerConfig.inHeight&&N._detectorConfig.inWidth===N._trackerConfig.inWidth||(n.dispose(),n=kp([1,N._trackerConfig.inHeight,N._trackerConfig.inWidth,3])),(r=N._tfKeypointsTracker.predict(n))instanceof Array?(N._debug&&r.forEach((function(e){return console.log(e.shape)})),r.forEach((function(e){return e.dispose()})),N._trackerOutDims=[1,N._trackerConfig.outHeight,N._trackerConfig.outWidth,N._trackerConfig.outChannels]):(N._trackerOutDims=r.shape,r.dispose()),n.dispose(),N._debug&&(console.log(N._detectorConfig),console.log(N._trackerConfig),console.log("(DEBUG) XZIMG BACKEND",hi()),console.log("_trackerOutDims",N._trackerOutDims)),N._activeIds=N._config.activeIds,N._trackHasHeatmaps=rC(N._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]}(N._geometryObjModel.vertices,N._geometryType,N._trackerConfig.outChannels),N._keypsVts=t[0],N._refKeypsVts=t[1];var a=Math.max(N._detectorOutDims[1]*N._detectorOutDims[2]*N._detectorOutDims[3]);N._trackHasHeatmaps&&(a=Math.max(N._detectorOutDims[1]*N._detectorOutDims[2]*N._detectorOutDims[3],N._trackerOutDims[1]*N._trackerOutDims[2]*N._trackerOutDims[3]));var s=Math.max(N._detectorOutDims[3],N._trackerOutDims[3]);if(N._bufferHeatmaps=N._poseModule._malloc(a*N._float_size),N._bufferKeypsDet=N._poseModule._malloc(2*N._detectorOutDims[3]*N._float_size),N._bufferKeypsTrack=N._poseModule._malloc(2*N._trackerOutDims[3]*N._float_size),N._bufferFeatureScores=N._poseModule._malloc(s*N._float_size),N._bufInOutPose=N._poseModule._malloc(21*N._float_size),e.pdmModel){var o=new Uint8Array(e.pdmModel);N._bufferPdmModel=N._poseModule._malloc(o.byteLength),N._poseModule.HEAPU8.set(o,N._bufferPdmModel);var i={rigid_pose:0,num_iterations:1,filter_strength:5,reg_w:10,fovy_d:50,width:640,height:480,num_features:N._geometryType==HC.Face?N._trackerOutDims[3]:-1,modelContent:N._bufferPdmModel,modelContentSize:o.byteLength,modelEncoding:N._geometryType==HC.Face?2:1,bsMode:0},u=N._poseModule._malloc(48);N._poseModule.setValue(u+0,i.rigid_pose,"i32"),N._poseModule.setValue(u+4,i.num_iterations,"i32"),N._poseModule.setValue(u+8,i.filter_strength,"i32"),N._poseModule.setValue(u+12,i.reg_w,"float"),N._poseModule.setValue(u+16,i.fovy_d,"float"),N._poseModule.setValue(u+20,i.width,"i32"),N._poseModule.setValue(u+24,i.height,"i32"),N._poseModule.setValue(u+28,i.num_features,"i32"),N._poseModule.setValue(u+32,i.modelContent,"*"),N._poseModule.setValue(u+36,i.modelContentSize,"i32"),N._poseModule.setValue(u+40,i.modelEncoding,"i32"),N._poseModule.setValue(u+44,i.bsMode,"i32");var l=N._poseModule.cwrap("xzimgPoseEstimationInitialize","number",["number"])(u);N._debug&&console.log("PDM initialisation: ",l),N._poseModule._free(u),N._poseModule._free(N._bufferPdmModel),N._nonRigidInitialized=!0}else if(null==N._bufKeyps3D){N._bufKeyps3D=N._poseModule._malloc(N._keypsVts.length*N._float_size),N._poseModule.HEAPF32.set(N._keypsVts,N._bufKeyps3D/4);var c=Array.from(N._keypsVts);c.forEach((function(e,t){t%3==0&&(c[t]=-c[t])})),N._bufMirroredKeyps3D=N._poseModule._malloc(c.length*N._float_size),N._poseModule.HEAPF32.set(N._keypsVts,N._bufMirroredKeyps3D/4)}if(e.subTracker){N._tfSubTracker=e.subTracker.graphModel,N._subTrackerConfig=e.subTracker.config;var p=kp([N._config.subTrackerSymmetric?2:1,N._subTrackerConfig.inHeight,N._subTrackerConfig.inWidth,3]),h=N._tfSubTracker.predict(p);N._subTrackerOutDims=h.shape,h.dispose(),p.dispose();var d=Math.max(N._subTrackerOutDims[1]*N._subTrackerOutDims[2]*N._subTrackerOutDims[3]);if(N._bufSubTrackerHmaps=N._poseModule._malloc(d*N._float_size),N._bufSubTrackerHmapsSym=N._poseModule._malloc(d*N._float_size),N._config.subTrackerObjectType){var f=N._geometryObjModel.faces.length/3;N._bufModelTriangles=N._poseModule._malloc(9*f*N._float_size);for(var m=new Float32Array(9*f),g=0;g<f;g++){var y=N._geometryObjModel.faces[3*g],b=N._geometryObjModel.faces[3*g+1],_=N._geometryObjModel.faces[3*g+2];m[9*g]=N._geometryObjModel.vertices[3*y],m[9*g+1]=N._geometryObjModel.vertices[3*y+1],m[9*g+2]=N._geometryObjModel.vertices[3*y+2],m[9*g+3]=N._geometryObjModel.vertices[3*b],m[9*g+4]=N._geometryObjModel.vertices[3*b+1],m[9*g+5]=N._geometryObjModel.vertices[3*b+2],m[9*g+6]=N._geometryObjModel.vertices[3*_],m[9*g+7]=N._geometryObjModel.vertices[3*_+1],m[9*g+8]=N._geometryObjModel.vertices[3*_+2]}N._poseModule.HEAPF32.set(m,N._bufModelTriangles/4)}}N._initialized=!0})),Z((function(){return E.unsubscribe()}))).toPromise()];case 4:return s.sent(),[2]}var A,C}))}))},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=fC.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=e;null==e&&(n=this._videoManager.getLastBuffer()),null!=n?(n.width===this._currentWidth&&n.height===this._currentHeight||(this._currentWidth=n.width,this._currentHeight=n.height,t=zC.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()),this.trackGeometrySync(n)):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=XC(this._geometryType)||this._geometryType==HC.Wrist||this._geometryType==HC.Hand||this._geometryType==HC.Face;if(this._trackingState===fC.Detection){var s=this._poseModule.cwrap("xzimgMatchRecKeypsInit","number",["number"]);null==this._hptrImageBuffer&&(this._hptrImageBuffer=this._poseModule._malloc(e.width*e.height*4)),MC(this._poseModule,e,this._hptrImageBuffer);var o=FC(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=oC(l,this._config.validDetectedKeypThs);this._visibility=c.visibilty,this._trackingState=fC.Detection,c.totalVisible>=this._config.detectNumKeypsThs&&c.globalScore>=this._config.detectScoreThs&&(this._geometryType==HC.Wrist&&(this._flipMode="","left"==(t=this._keyps2D,n=c.visibilty,(9==t.length/2?n[0]&&n[1]?gC.CreateFromPoints(new mC(t[0],t[9]),new mC(t[1],t[10])):gC.CreateFromPoints(new mC(t[1],t[10]),new mC(t[6],t[15])):gC.CreateFromPoints(new mC(t[30],t[211]),new mC(t[163],t[344]))).x>0?"left":"right")&&(this._flipMode="up_down")),a?this._trackingState=fC.Detected:(this._reprojError=this.computePoseSync(this._trackingState,this._geometryType),this._reprojError>0&&this._reprojError<this._config.reprojThs&&(this._trackingState=fC.Detected)))}else{var p=this.trackGeometryFeaturesSync(e,this._trackingState,this._keyps2D,this._visibility,this._geometryType);this._keyps2D=p.imageFilteredKeyps,this._cropKeyps2D=p.cropKeyps,this._objectMask=p.mask,c=oC(p.scores,this._config.validTrackedKeypThs),this._visibility=c.visibilty;var h=lC(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=fC.Detection:this._trackingState=fC.Tracking):this._trackingState=fC.Tracking,this._tfSubTracker&&this._trackingState==fC.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]=bC(d.subTrackerKeyps[t],d.subTrackerVisibility[t],e,r._subTrackerVis[t],0)})):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,w=Math.sqrt((b-f[0])*(b-f[0])+(_-f[1])*(_-f[1])+(x-f[2])*(x-f[2])),v=new Float32Array([(b-f[0])/w,(_-f[1])/w,(x-f[2])/w]);this._debug&&(console.log("dir",v),console.log("camCenter",f),console.log("numTriangles",this._geometryObjModel.faces.length/3));var k=this._poseModule._malloc(3*this._float_size),I=k/4,T=this._poseModule.HEAPF32.subarray(I,I+3);T.set(f);var S=this._poseModule._malloc(3*this._float_size);I=S/4,(T=this._poseModule.HEAPF32.subarray(I,I+3)).set(v);var E=m(k,S,this._bufModelTriangles,this._geometryObjModel.faces.length/3);if(this._poseModule._free(k),this._poseModule._free(S),1==E){var N=bC(this._pose.project(new Float32Array([b,_,x]),zC.getCameraMat(this._config.fovY,this._currentWidth,this._currentHeight)),new Int32Array([1]),new Float32Array([this._subTrackerKeyps[g][3],this._subTrackerKeyps[g][7]]),new Int32Array([1]),0);this._subTrackerKeyps[g][3]=N[0],this._subTrackerKeyps[g][7]=N[1]}}}}}else this._trackingState=fC.Detection}(this._trackingState===fC.Detection||this._trackingState===fC.Detected&&a)&&(this._pose=new zC(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0])),this._pose.setTrackingState(fC.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=Nu(e),l=gu(u,"float32"),c=El(l,[1,this._currentHeight,this._currentWidth,3]),p=cf.cropAndResize(c,[s],[0],[this._detectorConfig.inHeight,this._detectorConfig.inWidth]),h=Oc(255),d=Qu(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*_,w=this._bufferHeatmaps/4;this._poseModule.HEAPF32.subarray(w,w+x).set(m),g(this._bufferHeatmaps,b,_,y,0,1,this._bufferKeypsDet,this._bufferFeatureScores);var v=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufferKeypsDet,2*y),k=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufferFeatureScores,y);u.dispose(),l.dispose(),h.dispose(),p.dispose(),d.dispose(),c.dispose(),f.dispose();var I=Math.min(this._currentWidth,this._currentHeight),T=I/this._detectorConfig.inWidth,S=I/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,T),{refinedFeatures:uC(v,this._simCropToImage),scores:k}},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!=fC.Detected){if(o=(s=$C(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==HC.FullBody?[7,8,9,10,13,14,15,16].forEach((function(e){u[e]=0})):a==HC.UpperBody?[7,8,9,10].forEach((function(e){u[e]=0})):a==HC.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==HC.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,zC.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,zC.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];XC(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 qC(t[0],t[u]),l[1]=n[3]>0&&n[4]>0?1:0,c[1]=new qC((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 qC((t[5]+t[6])/2,(t[5+u]+t[6+u])/2),l[3]=n[1]>0?1:0,c[3]=new qC(t[1],t[1+u]),l[4]=n[2]>0?1:0,c[4]=new qC(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 qC(t[0],t[u]),l[1]=n[p]>=0?1:0,c[1]=new qC(t[p],t[p+u]),l[2]=n[h]>=0?1:0,c[2]=new qC(t[h],t[h+u]),l[3]=n[1]>0?1:0,c[3]=new qC(t[1],t[1+u]),l[4]=n[2]>0?1:0,c[4]=new qC(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 qC(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 qC(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,w=(r[0]-1)/2,v=s.x-(y*_*x-b*_*w),k=s.y-(b*_*x+y*_*w);if(null!=a){var I=.8;_=(1-I)*_+I*a[7],v=(1-I)*v+I*a[2],k=(1-I)*k+I*a[5],o=(1-I)*o+I*a[6],y=Math.cos(o),b=Math.sin(o)}return[y*_,-b*_,v,b*_,y*_,k,o,_]}(a,void 0===p?o:p,r,[this._trackerConfig.inWidth,this._trackerConfig.inHeight],t==fC.Detected||this._fastMvt?null:this._simCropToImage):a==HC.Face?this._simCropToImage=function(e,t,n,r,a){var s=e.length/2,o=sC(e,t,s),i=new mC((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 mC(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 mC(e[8],e[8+s]),d=new mC(e[13],e[13+s]);21==s&&(h=new mC(e[10],e[10+s]),d=new mC(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 mC(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 mC(.5*(e[0]+e[1]),.5*(e[0+s]+e[1+s])),y=3,b=4):_=new mC(e[g],e[g+s]);var x=new mC(.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 mC((_.x+x.x)/2,(_.y+x.y)/2);var w=0;for(f=0;f<s;f++)m=new mC(e[f],e[f+s]).Dist(i),t[f]>0&&m>w&&(w=m);u=2*w}5==s&&(u=2*(o[1]-o[0])),22==s&&(c=.15)}var v=new yC(i.x-u/2,i.y-u/2,u,u),k=Math.cos(l),I=Math.sin(l),T=(v.w+c*v.w)/Math.max(n[0],n[1]),S=n[1]/2,E=n[0]/2,N=i.x-(k*T*S-I*T*E),A=i.y-(I*T*S+k*T*E);if(null!=r){var C=.8;N=C*N+(1-C)*r[2],A=C*A+(1-C)*r[5],T=.3*T+.7*r[7],Math.abs(l-r[6])<1&&(l=.3*l+.7*r[6]),k=Math.cos(l),I=Math.sin(l)}return[k*T,-I*T,N,I*T,k*T,A,l,T]}(void 0===p?y:p,r,[this._trackerConfig.inWidth,this._trackerConfig.inHeight],t==fC.Detected||this._fastMvt?null:this._simCropToImage,this._config.normMode):a==HC.Wrist?this._simCropToImage=function(e,t,n,r,a){var s=e.length/2,o=sC(e,t,s),i=lC("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=wC(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,w=f-(g*b*_-y*b*x),v=m-(y*b*_+g*b*x);if(null!=r){var k=.5;w=k*w+.5*r[2],v=k*v+.5*r[5],b=k*b+.5*r[7],Math.abs(h-r[6])<1&&(h=k*h+.5*r[6]),g=Math.cos(h),y=Math.sin(h)}return[g*b,-y*b,w,y*b,g*b,v,h,b]}(void 0===p?o:p,r,[this._trackerConfig.inWidth,this._trackerConfig.inHeight],t==fC.Detected||this._fastMvt?null:this._simCropToImage,this._config.normMode):a==HC.Hand?this._simCropToImage=function(e,t,n,r,a){var s=e.length/2,o=sC(e,t,s),i=Math.max(o[1]-o[0],o[3]-o[2]),u=cC("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==fC.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=cC(a,e))[0],o[1],s=o[2]),i=aC(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==fC.Detected||this._fastMvt?null:this._simCropToImage,a,c);var _=new ImageData(this._trackerConfig.inWidth,this._trackerConfig.inHeight);_=hC(e,_,this._simCropToImage);var x=LC(this._tfKeypointsTracker,this._trackerConfig,this._poseModule,[this._bufferHeatmaps],[this._bufferKeypsTrack],[this._bufferFeatureScores],[_],[this._flipMode]);x.masks[0]&&this._debug&&(console.log("masks",x.masks[0]),this._debugInitialized=!0,this._debugImage=function(e,t,n,r){for(var a=new Uint8ClampedArray(65536),s=0;s<16384;s++){for(var o=1*s,i=r[o],u=1;u<1;u++){var l=r[o+u];i=Math.max(i,l)}var c=4*s;a[c+0]=Math.round(255*(1-i)),a[c+1]=Math.round(255*(1-i)),a[c+2]=Math.round(255*(1-i)),a[c+3]=255}return new ImageData(a,128,128)}(0,0,0,x.masks[0]));var w=uC(x.coordinates[0],this._simCropToImage,this._flipMode,new Int32Array([this._trackerConfig.outHeight,this._trackerConfig.outWidth]));if(t!=fC.Detected){var v=iC(x.scores[0],this._config.validTrackedKeypThs);if(a==HC.Face&&!this._nonRigidInitialized){var k=this._pose.project(this._keypsVts,zC.getCameraMat(this._config.fovY,this._currentWidth,this._currentHeight)),I=w.length/2;for(f=0;f<I;f++)0==v[f]&&(v[f]=1,w[f]=k[2*f],w[f+I]=k[2*f+1])}w=bC(w,v,o,r,0)}return{imageFilteredKeyps:w,cropKeyps:x.coordinates[0],scores:x.scores[0],mask:x.masks[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=_C(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=[hC(e,new ImageData(this._subTrackerConfig.inWidth,this._subTrackerConfig.inHeight),a)];if(this._config.subTrackerSymmetric&&this._config.subTrackerSymmetricIds){var i=_C(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([hC(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=LC(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]=bC(e,n,r._subTrackerCropKeyps[t],r._subTrackerVis[t],0):r._subTrackerCropKeyps=r._subTrackerCropKeyps.concat([e]);var a=uC(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&&(XC(t)||t==HC.Wrist||t==HC.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==fC.Detection){var s=0,o=0,i=t==HC.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 zC(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==fC.Detected||e==fC.Tracking){s=0,o=e!=fC.Tracking||this._resetPose?0:1,this._resetPose=!1,i=t==HC.Hand||t==HC.Necklace||t==HC.Lamborghini?3:1,u=t==HC.Hand||t==HC.Necklace||t==HC.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 zC(_,x);var w=this._pose.project(this._keypsVts,zC.getCameraMat(this._config.fovY,this._currentWidth,this._currentHeight));this._reprojKeyps2D=new Float32Array(w.length);for(var v=0;v<w.length/2;v++)this._reprojKeyps2D[v]=w[2*v],this._reprojKeyps2D[v+this._reprojKeyps2D.length/2]=w[2*v+1];if(t==HC.Necklace){var k=this._pose.getRot();k[5]>.35&&(console.log(k[2],k[5],k[8]),k[2]=0,k[5]=0,k[8]=-1,this._pose.updateRotation(k))}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=XC(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==fC.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==HC.Face&&(l=25),t==HC.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 zC(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 w=this._poseModule._malloc(x*this._float_size),v=_(w);this._debug&&console.log(v);var k=new Float32Array(this._poseModule.HEAPF32.buffer,w,x);this._bsCoefs=new Float32Array(x);for(var I=0;I<x;I++)this._bsCoefs[I]=k[I];this._debug&&console.log(this._bsCoefs),this._poseModule._free(w)}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 s=t[r];if(void 0!==s)return s.exports;var a=t[r]={exports:{}};return e[r](a,a.exports,n),a.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";n.r(r),n.d(r,{Foot:()=>Su,Geometry:()=>Eu,Segmentation:()=>e.Segmentation,VideoManager:()=>p,shutdownTfjs:()=>Eo});var e={};n.r(e),n.d(e,{qK:()=>Su,ZX:()=>Eu,X7:()=>p,BX:()=>Eo});var t="/index.js";function s(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)}var a=function(){return a=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var s in t=arguments[n])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},a.apply(this,arguments)};function i(e,t,n,r){return new(n||(n=Promise))((function(s,a){function i(e){try{u(r.next(e))}catch(e){a(e)}}function o(e){try{u(r.throw(e))}catch(e){a(e)}}function u(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,o)}u((r=r.apply(e,t||[])).next())}))}function o(e,t){var n,r,s,a={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},i=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return i.next=o(0),i.throw=o(1),i.return=o(2),"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function o(o){return function(u){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;i&&(i=0,o[0]&&(a=0)),a;)try{if(n=1,r&&(s=2&o[0]?r.return:o[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,o[1])).done)return s;switch(r=0,s&&(o=[2&o[0],s.value]),o[0]){case 0:case 1:s=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!((s=(s=a.trys).length>0&&s[s.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!s||o[1]>s[0]&&o[1]<s[3])){a.label=o[1];break}if(6===o[0]&&a.label<s[1]){a.label=s[1],s=o;break}if(s&&a.label<s[2]){a.label=s[2],a.ops.push(o);break}s[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{n=s=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,u])}}}function u(e,t,n){if(n||2===arguments.length)for(var r,s=0,a=t.length;s<a;s++)!r&&s in t||(r||(r=Array.prototype.slice.call(t,0,s)),r[s]=t[s]);return e.concat(r||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError;var l,p=function(){function e(e,t,n){this.NB_BUFFERS=5,this._videoFrames=[],this._nbFramesDelay=0,this._videoElement=e,null!==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=u([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=u([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(){return this._nbFramesDelay>0&&this._videoFrames.length>0?this._nbFramesDelay<this._videoFrames.length?this._videoFrames[this._nbFramesDelay]:this._videoFrames[this._videoFrames.length-1]:this.getLastBuffer()},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}(),c=(l="undefined"!=typeof document?document.currentScript?.src:void 0,function(e={}){var t,n,r,s=e,a=new Promise(((e,r)=>{t=e,n=r})),i=Object.assign({},s),o="";"undefined"!=typeof document&&document.currentScript&&(o=document.currentScript.src),l&&(o=l),o=o.startsWith("blob:")?"":o.substr(0,o.replace(/[?#].*/,"").lastIndexOf("/")+1),r=e=>fetch(e,{credentials:"same-origin"}).then((e=>e.ok?e.arrayBuffer():Promise.reject(Error(e.status+" : "+e.url))));var u,p=console.error.bind(console);Object.assign(s,i),i=null,s.wasmBinary&&(u=s.wasmBinary);var c,h,d,f,m,y,g,_,b=!1;function w(){var e=c.buffer;s.HEAP8=h=new Int8Array(e),s.HEAP16=f=new Int16Array(e),s.HEAPU8=d=new Uint8Array(e),s.HEAPU16=new Uint16Array(e),s.HEAP32=m=new Int32Array(e),s.HEAPU32=y=new Uint32Array(e),s.HEAPF32=g=new Float32Array(e),s.HEAPF64=_=new Float64Array(e)}var v=[],T=[],S=[],k=0,N=null;function M(e){throw p(e="Aborted("+e+")"),b=!0,e=new WebAssembly.RuntimeError(e+". Build with -sASSERTIONS for more info."),n(e),e}var x,F=e=>e.startsWith("data:application/octet-stream;base64,");function I(e){if(e==x&&u)return new Uint8Array(u);throw"both async and sync fetching of the wasm failed"}function A(e,t,n){return function(e){return u?Promise.resolve().then((()=>I(e))):r(e).then((e=>new Uint8Array(e)),(()=>I(e)))}(e).then((e=>WebAssembly.instantiate(e,t))).then(n,(e=>{p(`failed to asynchronously prepare wasm: ${e}`),M(e)}))}var E,O="undefined"!=typeof TextDecoder?new TextDecoder:void 0,D=(e,t,n,r)=>{var a={string:e=>{var t=0;if(null!=e&&0!==e){for(var n=t=0;n<e.length;++n){var r=e.charCodeAt(n);127>=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}var s=t+1;if(n=t=B(s),r=d,0<s){s=n+s-1;for(var a=0;a<e.length;++a){var i=e.charCodeAt(a);if(55296<=i&&57343>=i&&(i=65536+((1023&i)<<10)|1023&e.charCodeAt(++a)),127>=i){if(n>=s)break;r[n++]=i}else{if(2047>=i){if(n+1>=s)break;r[n++]=192|i>>6}else{if(65535>=i){if(n+2>=s)break;r[n++]=224|i>>12}else{if(n+3>=s)break;r[n++]=240|i>>18,r[n++]=128|i>>12&63}r[n++]=128|i>>6&63}r[n++]=128|63&i}}r[n]=0}}return t},array:e=>{var t=B(e.length);return h.set(e,t),t}};e=s["_"+e];var i=[],o=0;if(r)for(var u=0;u<r.length;u++){var l=a[n[u]];l?(0===o&&(o=$()),i[u]=l(r[u])):i[u]=r[u]}return function(e){if(0!==o&&P(o),"string"===t)if(e){for(var n=d,r=e+NaN,s=e;n[s]&&!(s>=r);)++s;if(16<s-e&&n.buffer&&O)e=O.decode(n.subarray(e,s));else{for(r="";e<s;){var a=n[e++];if(128&a){var i=63&n[e++];if(192==(224&a))r+=String.fromCharCode((31&a)<<6|i);else{var u=63&n[e++];65536>(a=224==(240&a)?(15&a)<<12|i<<6|u:(7&a)<<18|i<<12|u<<6|63&n[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}e=r}}else e="";else e="boolean"===t?!!e:e;return e}(n=e(...i))},C={c:()=>{M("")},b:(e,t,n)=>d.copyWithin(e,t,t+n),a: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 s=Math;r=Math.max(e,r);e:{s=(s.min.call(s,2147483648,r+(65536-r%65536)%65536)-c.buffer.byteLength+65535)/65536;try{c.grow(s),w();var a=1;break e}catch(e){}a=void 0}if(a)return!0}return!1}},R=(E={a:C},k++,x||=F("libxzimgPoseEstimation.wasm")?"libxzimgPoseEstimation.wasm":s.locateFile?s.locateFile("libxzimgPoseEstimation.wasm",o):o+"libxzimgPoseEstimation.wasm",function(e,t){var n=x;return u||"function"!=typeof WebAssembly.instantiateStreaming||F(n)||"function"!=typeof fetch?A(n,e,t):fetch(n,{credentials:"same-origin"}).then((r=>WebAssembly.instantiateStreaming(r,e).then(t,(function(r){return p(`wasm streaming compile failed: ${r}`),p("falling back to ArrayBuffer instantiation"),A(n,e,t)}))))}(E,(function(e){R=e.instance.exports,c=R.d,w(),T.unshift(R.e),0==--k&&N&&(e=N,N=null,e())})).catch(n),{});s._malloc=e=>(s._malloc=R.g)(e),s._free=e=>(s._free=R.h)(e),s._xzimgInitializeCamera=(e,t,n)=>(s._xzimgInitializeCamera=R.i)(e,t,n),s._xzimgPoseEstimationRelease=()=>(s._xzimgPoseEstimationRelease=R.j)(),s._xzimgGetHeatmapsLocations=(e,t,n,r,a,i,o,u)=>(s._xzimgGetHeatmapsLocations=R.k)(e,t,n,r,a,i,o,u),s._xzimgEstimateRigidPose=(e,t,n,r,a,i,o,u,l,p,c,h)=>(s._xzimgEstimateRigidPose=R.l)(e,t,n,r,a,i,o,u,l,p,c,h),s._xzimgEstimateGetSimilarity=(e,t,n,r)=>(s._xzimgEstimateGetSimilarity=R.m)(e,t,n,r),s._xzimgMatchRecKeypsInit=e=>(s._xzimgMatchRecKeypsInit=R.n)(e),s._xzimgMatchRecKeyps=(e,t,n,r,a,i)=>(s._xzimgMatchRecKeyps=R.o)(e,t,n,r,a,i);var L,P=e=>(P=R.p)(e),B=e=>(B=R.q)(e),$=()=>($=R.r)();function z(){if(!(0<k)){for(;0<v.length;)v.shift()(s);if(!(0<k||L||(L=!0,s.calledRun=!0,b))){for(;0<T.length;)T.shift()(s);for(t(s);0<S.length;)S.shift()(s)}}}return s.ccall=D,s.cwrap=(e,t,n,r)=>{var a=!n||n.every((e=>"number"===e||"boolean"===e));return"string"!==t&&a&&!r?s["_"+e]:(...r)=>D(e,t,n,r)},s.setValue=function(e,t,n="i8"){switch(n.endsWith("*")&&(n="*"),n){case"i1":case"i8":h[e]=t;break;case"i16":f[e>>1]=t;break;case"i32":m[e>>2]=t;break;case"i64":M("to do setValue(i64) use WASM_BIGINT");case"float":g[e>>2]=t;break;case"double":_[e>>3]=t;break;case"*":y[e>>2]=t;break;default:M(`invalid type for setValue: ${n}`)}},s.getValue=function(e,t="i8"){switch(t.endsWith("*")&&(t="*"),t){case"i1":case"i8":return h[e];case"i16":return f[e>>1];case"i32":return m[e>>2];case"i64":M("to do getValue(i64) use WASM_BIGINT");case"float":return g[e>>2];case"double":return _[e>>3];case"*":return y[e>>2];default:M(`invalid type for getValue: ${t}`)}},N=function e(){L||z(),L||(N=e)},z(),a});class h{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 d{refCount(e){return f("refCount")}incRef(e){return f("incRef")}timerAvailable(){return!0}time(e){return f("time")}read(e){return f("read")}readSync(e){return f("readSync")}readToGPU(e,t){return f("readToGPU")}numDataIds(){return f("numDataIds")}disposeData(e,t){return f("disposeData")}write(e,t,n){return f("write")}move(e,t,n,r,s){return f("move")}createTensorFromGPUData(e,t,n){return f("createTensorFromGPUData")}memory(){return f("memory")}floatPrecision(){return f("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return f("dispose")}}function f(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 m(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function y(e){m(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function g(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 _(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 b(e){return e%1==0}function w(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function v(e,t){const n=t.length;return e=null==e?t.map(((e,t)=>t)):[].concat(e),m(e.every((e=>e>=-n&&e<n)),(()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),m(e.every((e=>b(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function T(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 S(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 k(e){return"string"==typeof e||e instanceof String}function N(e){return Array.isArray(e)?N(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":"number"==typeof e?"float32":k(e)?"string":"boolean"==typeof e?"bool":"float32"}function M(e){return!!(e&&e.constructor&&e.call&&e.apply)}function x(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 F(e,t,n,r=!1){const s=new Array;if(1===t.length){const a=t[0]*(r?2:1);for(let t=0;t<a;t++)s[t]=n[e+t]}else{const a=t[0],i=t.slice(1),o=i.reduce(((e,t)=>e*t))*(r?2:1);for(let t=0;t<a;t++)s[t]=F(e+t*o,i,n,r)}return s}function I(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 F(0,e,t,n)}function A(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 E(e){e.forEach((t=>{m(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function O(e){return e&&e.then&&"function"==typeof e.then}class D{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=C,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(R().getBool("IS_TEST")||R().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];R().getBool("IS_TEST")||R().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(O(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)}getString(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);"tfjsflags"in e&&e.tfjsflags.split(",").forEach((e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){const n=t.toLowerCase();return"true"===n||"false"===n?"true"===n:""+ +n===n?+n:t}(0,n)}))}}function C(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 R(){return P}let L,P=null;function B(){if(null==L){let e;if("undefined"!=typeof window)e=window;else if(void 0!==n.g)e=n.g;else if("undefined"!=typeof process)e=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}L=e}return L}function $(e,t){const n=function(){const e=B();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 z="Add",H="AddN",j="BatchMatMul",V="Cast",W="Concat",U="Conv2D",K="CropAndResize",G="DepthwiseConv2dNative",q="RealDiv",Q="ExpandDims",J="Identity",Y="Mean",X="Multiply",Z="PadV2",ee="Relu",te="Reshape",ne="ResizeBilinear",re="Relu6",se="Reverse",ae="Sigmoid",ie="StridedSlice",oe="Transpose",ue="Unpack",le="FromPixels",pe="_FusedMatMul",ce="FusedConv2D",he="FusedDepthwiseConv2D";function de(...e){R().getBool("IS_TEST")||R().getBool("PROD")||console.warn(...e)}const fe=$("kernelRegistry",(()=>new Map)),me=$("gradRegistry",(()=>new Map));function ye(e,t){const n=we(e,t);return fe.get(n)}function ge(e){return me.get(e)}function _e(e){const t=fe.entries(),n=[];for(;;){const{done:r,value:s}=t.next();if(r)break;const[a,i]=s,[o]=a.split("_");o===e&&n.push(i)}return n}function be(e){const{kernelName:t,backendName:n}=e,r=we(t,n);fe.has(r)&&de(`The kernel '${t}' for backend '${n}' is already registered`),fe.set(r,e)}function we(e,t){return`${t}_${e}`}function ve(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var Te="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==n.g?n.g:"undefined"!=typeof self?self:{};function Se(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function ke(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=!1;try{n=this instanceof e}catch{}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})})),n}function Ne(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Ae(e)),R().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 Me(){return R().platform.now()}function xe(e,t="utf-8"){return t=t||"utf-8",R().platform.encode(e,t)}function Fe(e,t="utf-8"){return t=t||"utf-8",R().platform.decode(e,t)}function Ie(e){return null!=R().platform.isTypedArray?R().platform.isTypedArray(e):ve(e)}function Ae(e,t=[],n=!1){if(null==t&&(t=[]),"boolean"==typeof e||"number"==typeof e||"string"==typeof e||O(e)||null==e||Ie(e)&&n)t.push(e);else if(Array.isArray(e)||Ie(e))for(let r=0;r<e.length;++r)Ae(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 s=0;s<=r;s++)Ae(e[s],t,n)}return t}class Ee{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new De)}profileKernel(e,t,n){let r;const s=()=>{r=n()};let a;const i=Me();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(s);else{s();for(const e of r)e.dataSync();a=Promise.resolve({kernelMs:Me()-i})}if(R().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<r.length;t++){const n=r[t];n.data().then((t=>{Oe(t,n.dtype,e)}))}return{kernelName:e,outputs:r,inputs:t,timeMs:a.then((e=>e.kernelMs)),extraInfo:a.then((e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():""))}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:s,extraInfo:a}=e;n.forEach((e=>{Promise.all([e.data(),r,a]).then((n=>{this.logger.logKernelProfile(t,e,n[0],n[1],s,n[2])}))}))}}function Oe(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 De{logKernelProfile(e,t,n,r,s,a){const i="number"==typeof r?w(`${r}ms`,9):r.error,o=w(e,25),u=t.rank,l=t.size,p=w(t.shape.toString(),14);let c="";for(const e in s){const n=s[e];if(null!=n){const r=n.shape||t.shape,s=r.length;c+=`${e}: ${s}D ${s>0?r:""} `}}console.log(`%c${o}\t%c${i}\t%c${u}D ${p}\t%c${l}\t%c${c}\t%c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function Ce(e,t,n,r){const s=x(t),a=function(e,t,n,r){const s=g(t),a=r[r.length-1],i=new Array(a).fill(0),o=t.length,u="complex64"===n?Be(e):e;if(o>1)for(let e=0;e<s/a;e++){const t=e*a;for(let e=0;e<a;e++)i[e]=Math.max(i[e],Re(u[t+e],0,n).length)}return i}(e,t,n,s),i=t.length,o=Pe(e,t,n,s,a),u=["Tensor"];return r&&(u.push(` dtype: ${n}`),u.push(` rank: ${i}`),u.push(` shape: [${t}]`),u.push(" values:")),u.push(o.map((e=>" "+e)).join("\n")),u.join("\n")}function Re(e,t,n){let r;return r=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:k(e)?`'${e}'`:"bool"===n?Le(e):parseFloat(e.toFixed(7)).toString(),w(r,t)}function Le(e){return 0===e?"false":"true"}function Pe(e,t,n,r,s,a=!0){const i="complex64"===n?2:1,o=t[0],u=t.length;if(0===u)return"complex64"===n?[Re(Be(e)[0],0,n)]:"bool"===n?[Le(e[0])]:[e[0].toString()];if(1===u){if(o>20){const t=3*i;let r=Array.from(e.slice(0,t)),a=Array.from(e.slice((o-3)*i,o*i));return"complex64"===n&&(r=Be(r),a=Be(a)),["["+r.map(((e,t)=>Re(e,s[t],n))).join(", ")+", ..., "+a.map(((e,t)=>Re(e,s[o-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?Be(e):Array.from(e)).map(((e,t)=>Re(e,s[t],n))).join(", ")+"]"]}const l=t.slice(1),p=r.slice(1),c=r[0]*i,h=[];if(o>20){for(let t=0;t<3;t++){const r=t*c,a=r+c;h.push(...Pe(e.slice(r,a),l,n,p,s,!1))}h.push("...");for(let t=o-3;t<o;t++){const r=t*c,a=r+c;h.push(...Pe(e.slice(r,a),l,n,p,s,t===o-1))}}else for(let t=0;t<o;t++){const r=t*c,a=r+c;h.push(...Pe(e.slice(r,a),l,n,p,s,t===o-1))}const d=2===u?",":"";h[0]="["+(o>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]+"]"+(a?"":f),h}function Be(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class $e{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=g(e),null!=n){const e=n.length;m(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||T(t,this.size),this.strides=x(e)}set(e,...t){0===t.length&&(t=[0]),m(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 ze().makeTensor(this.values,this.shape,this.dtype)}}let ze=null,He=null;class je{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=g(e),this.strides=x(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 He.buffer(this.shape,this.dtype,e)}bufferSync(){return He.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return I(this.shape,e,"complex64"===this.dtype)}arraySync(){return I(this.shape,this.dataSync(),"complex64"===this.dtype)}async data(){this.throwIfDisposed();const e=ze().read(this.dataId);if("string"===this.dtype){const t=await e;try{return t.map((e=>Fe(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(),ze().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=ze().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>Fe(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 ze().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),ze().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return He.print(this,e)}clone(){return this.throwIfDisposed(),He.clone(this)}toString(e=!1){return Ce(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),He.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),ze().makeVariable(this,e,t,n)}}function Ve(){return $("Tensor",(()=>je))}Object.defineProperty(je,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),Ve();class We extends je{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(!_(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);ze().disposeTensor(this),this.dataId=e.dataId,ze().incRef(this,null)}dispose(){ze().disposeVariable(this),this.isDisposedInternal=!0}}var Ue,Ke,Ge,qe,Qe;Object.defineProperty(We,Symbol.hasInstance,{value:e=>e instanceof je&&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"}(Ue||(Ue={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(Ke||(Ke={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(Ge||(Ge={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(qe||(qe={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(Qe||(Qe={}));const Je={float32:qe,int32:Ke,bool:Ge,complex64:Qe};function Ye(e){return null!=e&&"object"==typeof e&&"texture"in e&&e.texture instanceof WebGLTexture}function Xe(e){return"undefined"!=typeof GPUBuffer&&null!=e&&"object"==typeof e&&"buffer"in e&&e.buffer instanceof GPUBuffer}function Ze(e,t){if(e.dtype===t.dtype)return[e,t];const n=function(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Je[e][t]}(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function et(e){const t=[];return tt(e,t,new Set),t}function tt(e,t,n){if(null==e)return;if(e instanceof je)return void t.push(e);if(r=e,!Array.isArray(r)&&"object"!=typeof r)return;var r;const s=e;for(const e in s){const r=s[e];n.has(r)||(n.add(r),tt(r,t,n))}}function nt(e){return null!=e.kernelName}class rt{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 st{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new rt}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?(de(`${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 Ee(this.backendInstance),!0}setupRegisteredKernels(){_e(this.backendName).forEach((e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){_e(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 d||"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,de(`Initialization of backend ${e} failed`),de(n.stack||n.message)),!1)));return this.pendingBackendInit=r,{success:r,asyncInit:!0}}}catch(t){return de(`Initialization of backend ${e} failed`),de(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:s}=this.initializeBackend(n);if(s||r)return{name:n,asyncInit:s}}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,s=this.readSync(t),a=r.refCount(t);r.disposeData(t,!0),n.backend=e,e.move(t,s,n.shape,n.dtype,a),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 st.nextTensorId++}nextVariableId(){return st.nextVariableId++}clone(e){const t=it.runKernel(J,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e};return it.runKernel(V,t,{dtype:"float32"})}})),[],{}),t}runKernel(e,t,n){if(null==this.backendName&&this.backend,null==ye(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 s=0;n.forEach((e=>{s+="complex64"===e.dtype?3:1}));const a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=r-t-s-a;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const r=this.isTapeOn(),s=this.state.numBytes,a=this.state.numTensors;let i,o;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const u=nt(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(nt(e)){const{kernelName:t,inputs:s,attrs:a}=e;null==this.backendName&&this.backend;const u=ye(t,this.backendName);m(null!=u,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),i=()=>{const e=this.backend.numDataIds();o=u.kernelFunc({inputs:s,attrs:a,backend:this.backend});const i=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,i);const l=i.map((e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e)));if(r){const e=this.getTensorsForGradient(t,s,l);n=this.saveTensorsForBackwardMode(e)}return l}}else{const{forwardFunc:t}=e,s=e=>{r&&(n=e.map((e=>this.keep(this.clone(e)))))};i=()=>{const e=this.backend.numDataIds();o=this.tidy((()=>t(this.backend,s)));const n=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(u,e,n),n}}const{inputs:l,attrs:p}=e,c=nt(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,(()=>i())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(h),t=h.outputs):t=i()})),r&&this.addTapeNode(u,l,t,c,n,p),this.state.profiling&&this.state.activeProfile.kernels.push({name:u,bytesAdded:this.state.numBytes-s,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,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(o)?t:t[0]}saveTensorsForBackwardMode(e){const t=e.map((e=>this.keep(this.clone(e))));return t}getTensorsForGradient(e,t,n){const r=ge(e);if(null!=r){const e=r.inputsToSave||[],s=r.outputsToSave||[];let a;r.saveAllInputs?(m(Array.isArray(t),(()=>"saveAllInputs is true, expected inputs to be an array.")),a=Object.keys(t).map((e=>t[e]))):a=e.map((e=>t[e]));const i=n.filter(((e,t)=>s[t]));return a.concat(i)}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 s=e;"string"===n&&k(e[0])&&(s=e.map((e=>xe(e))));const a=r.write(s,t,n),i=new je(t,n,a,this.nextTensorId());if(this.trackTensor(i,r),"string"===n){const e=this.state.tensorInfo.get(a),t=function(e){if(null==e)return 0;let t=0;return e.forEach((e=>t+=e.length)),t}(s);this.state.numBytes+=t-e.bytes,e.bytes=t}return i}makeTensorFromDataId(e,t,n,r){const s={dataId:e,shape:t,dtype:n=n||"float32"};return this.makeTensorFromTensorInfo(s,r)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:r,dtype:s}=e,a=new je(r,s,n,this.nextTensorId());return this.trackTensor(a,t),a}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),null!=r&&r!==e.dtype&&(e=e.cast(r));const s=new We(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[s.name])throw new Error(`Variable with name ${s.name} was already registered`);return this.state.registeredVariables[s.name]=s,this.incRef(s,this.backend),s}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*S(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 We||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*S(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,s,a){const i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:s},o=ge(e);null!=o&&(r=o.gradFunc),null!=r&&(i.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],r=A(e.size,e.dtype);return this.makeTensor(r,e.shape,e.dtype)}return e})),r(e.length>1?e:e[0],s,a))),this.state.activeTape.push(i)}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=et(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(m(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 s=this.scopedRun((()=>this.startTape()),(()=>this.endTape()),(()=>this.tidy("forward",e)));m(s instanceof je,(()=>"The result y returned by f() must be a tensor."));const a=function(e,t,n){const r={},s={};for(let e=0;e<t.length;e++)r[t[e].id]=!0;for(let n=0;n<e.length;n++){const a=e[n],i=a.inputs;for(const e in i){const n=i[e];let o=!1;for(let e=0;e<t.length;e++)if(r[n.id]){a.outputs.forEach((e=>r[e.id]=!0)),o=!0,s[a.id]=!0;break}if(o)break}}const a={};a[n.id]=!0;const i={};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(a[n.outputs[e].id]){for(const e in r)a[r[e].id]=!0,i[n.id]=!0;break}}const o=[];for(let t=0;t<e.length;t++){const n=e[t];if(s[n.id]&&i[n.id]){const e={};for(const t in n.inputs){const s=n.inputs[t];r[s.id]&&(e[t]=s)}const t=Object.assign({},n);t.inputs=e,t.outputs=n.outputs,o.push(t)}}return o}(this.state.activeTape,t,s);if(!r&&0===a.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[s.id]=null==n?function(e){const t=function(e,t){const n=A(e,"float32");for(let e=0;e<n.length;e++)n[e]=1;return n}(g(e));return it.makeTensor(t,e,"float32")}(s.shape):n,function(e,t,n,r){for(let s=t.length-1;s>=0;s--){const a=t[s],i=[];if(a.outputs.forEach((t=>{const n=e[t.id];null!=n?i.push(n):i.push(null)})),null==a.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${a.kernelName}.`);const o=a.gradient(i);for(const t in a.inputs){if(!(t in o))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(o)}.`);const s=n((()=>o[t]()));if("float32"!==s.dtype)throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${s.dtype}'`);const i=a.inputs[t];if(!_(s.shape,i.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${t}' has shape '${s.shape}', which does not match the shape of the input '${i.shape}'`);if(null==e[i.id])e[i.id]=s;else{const t=e[i.id];e[i.id]=r(t,s),t.dispose()}}}}(e,a,(e=>this.tidy(e)),ot);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:s,grads:r}}))}customGrad(e){return m(M(e),(()=>"The f passed in customGrad(f) must be a function.")),(...t)=>{let n;m(t.every((e=>e instanceof je)),(()=>"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,s)=>(n=e(...t,s),m(n.value instanceof je,(()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor")),m(M(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 s=n.gradFunc(e,r),a=Array.isArray(s)?s:[s];m(a.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(...).")),m(a.every((e=>e instanceof je)),(()=>"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 i={};return a.forEach(((e,t)=>{i[t]=()=>e})),i},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=Me(),n=await this.backend.time(e);return n.wallMs=Me()-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 rt;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 at(){const e=B();if(null==e._tfengine){const t=new D(e);e._tfengine=new st(t)}var t;return t=e._tfengine.ENV,P=t,ze=()=>e._tfengine,e._tfengine}st.nextTensorId=0,st.nextVariableId=0;const it=at();function ot(e,t){const n={a:e,b:t};return it.runKernel(z,n)}function ut(e,t){let n=e;if(Ie(e))return"string"===t?[]:[e.length];if(Ye(e)){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if(Xe(e))return[e.buffer.size/(null==t?4:S(t))];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||Ie(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&R().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&lt(e,r,[]),r}function lt(e,t,n){if(n=n||[],!Array.isArray(e)&&!Ie(e))return void m(0===t.length,(()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`));m(t.length>0,(()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`)),m(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)lt(e[t],r,n.concat(t))}function pt(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 ct(e,t,n,r="numeric"){if(e instanceof Ve())return pt(r,e.dtype,t,n),e;let s=N(e);if("string"!==s&&["bool","int32","float32"].indexOf(r)>=0&&(s=r),pt(r,s,t,n),null==e||!Ie(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 a=ut(e,s);Ie(e)||Array.isArray(e)||(e=[e]);const i="string"!==s?Ne(e,s):Ae(e,[],!0);return it.makeTensor(i,a,s)}function ht(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,s)=>ct(e,`${t}[${s}]`,n,r)))}function dt(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+="__op";const s=(...e)=>{it.startScope(n);try{const t=r(...e);return O(t)&&console.error("Cannot return a Promise inside of tidy."),it.endScope(t),t}catch(e){throw it.endScope(null),e}};return Object.defineProperty(s,"name",{value:n,configurable:!0}),s}const ft=dt({cropAndResize_:function(e,t,n,r,s="bilinear",a=0){const i=ct(e,"image","cropAndResize"),o=ct(t,"boxes","cropAndResize","float32"),u=ct(n,"boxInd","cropAndResize","int32"),l=o.shape[0];m(4===i.rank,(()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`)),m(2===o.rank&&4===o.shape[1],(()=>`Error in cropAndResize: boxes must be have size [${l},4] but had shape ${o.shape}.`)),m(1===u.rank&&u.shape[0]===l,(()=>`Error in cropAndResize: boxInd must be have size [${l}] but had shape ${o.shape}.`)),m(2===r.length,(()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`)),m(r[0]>=1&&r[1]>=1,(()=>`cropSize must be atleast [1,1], but was ${r}`)),m("bilinear"===s||"nearest"===s,(()=>`method must be bilinear or nearest, but was ${s}`));const p={image:i,boxes:o,boxInd:u},c={method:s,extrapolationValue:a,cropSize:r};return it.runKernel(K,p,c)}}),mt=dt({cast_:function(e,t){const n=ct(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},s={dtype:t};return it.runKernel(V,r,s)}});function yt(e,t,n,r){if(null==r)r=N(e);else if("complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(Xe(e)||Ye(e)){if("float32"!==r&&"int32"!==r)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${r}.`);return it.backend.createTensorFromGPUData(e,t||n,r)}if(!Ie(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){E(t);const e=g(t),r=g(n);m(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],s=e!==n.length-1||r!==g(t.slice(e));m(n[e]===t[e]||!s,(()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `))}}return Ie(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==r?Ne(e,r):Ae(e,[],!0),it.makeTensor(e,t,r)}function gt(e,t){if((Ie(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&&Ie(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return yt(e,[],[],t)}let _t;const bt=dt({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,s=!1,a=!1,i=!1,o=!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)s=!0;else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)a=!0;else if(null!=e.getContext)i=!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}`);o=!0}if(null!=ye(le,it.backendName)){const n={pixels:e},r={numChannels:t};return it.runKernel(le,n,r)}const[u,l]=s?[e.videoWidth,e.videoHeight]:[e.width,e.height];let p,c;if(i)p=e.getContext("2d").getImageData(0,0,u,l).data;else if(r||n)p=e.data;else if(a||s||o){if(null==_t)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.");_t=new OffscreenCanvas(1,1).getContext("2d")}else _t=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});_t.canvas.width=u,_t.canvas.height=l,_t.drawImage(e,0,0,u,l),p=_t.getImageData(0,0,u,l).data}if(4===t)c=new Int32Array(p);else{const e=u*l;c=new Int32Array(e*t);for(let n=0;n<e;n++)for(let e=0;e<t;++e)c[n*t+e]=p[4*n+e]}return function(e,t,n){if(y(e),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");const r=ut(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 yt(e,t,r,n)}(c,[l,u,t],"int32")}}),wt=dt({complex_:function(e,t){const n=ct(e,"real","complex"),r=ct(t,"imag","complex");!function(e,t,n=""){m(_(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, must match in call to tf.complex().`);const s={real:n,imag:r};return it.runKernel("Complex",s)}});function vt(e,t="float32"){if(E(e),"complex64"===t){const t=vt(e,"float32"),n=vt(e,"float32");return wt(t,n)}const n=A(g(e),t);return it.makeTensor(n,e,t)}function Tt(e,t){y(e);const n=ut(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return yt(e,null,n,t)}const St=dt({sub_:function(e,t){let n=ct(e,"a","sub"),r=ct(t,"b","sub");[n,r]=Ze(n,r);const s={a:n,b:r};return it.runKernel("Sub",s)}}),kt=dt({reshape_:function(e,t){const n={x:ct(e,"x","reshape","string_or_numeric")},r={shape:t};return it.runKernel(te,n,r)}}),Nt=dt({floorDiv_:function(e,t){let n=ct(e,"a","floorDiv"),r=ct(t,"b","floorDiv");[n,r]=Ze(n,r);const s={a:n,b:r};return it.runKernel("FloorDiv",s)}}),Mt=dt({div_:function(e,t){let n=ct(e,"a","div"),r=ct(t,"b","div");if([n,r]=Ze(n,r),"int32"===n.dtype&&"int32"===r.dtype)return Nt(n,r);const s={a:n,b:r};return it.runKernel(q,s,{})}}),xt=R();function Ft(e,t,n){return yt(e,t,ut(e,n),n)}xt.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.")})),xt.registerFlag("IS_BROWSER",(()=>"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope)),xt.registerFlag("IS_NODE",(()=>"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node)),xt.registerFlag("IS_CHROME",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor))),xt.registerFlag("IS_SAFARI",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor))),xt.registerFlag("PROD",(()=>!1)),xt.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(()=>xt.getBool("DEBUG"))),xt.registerFlag("DEPRECATION_WARNINGS_ENABLED",(()=>!0)),xt.registerFlag("IS_TEST",(()=>!1)),xt.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",(()=>xt.getBool("DEBUG"))),xt.registerFlag("WRAP_TO_IMAGEBITMAP",(()=>!1)),xt.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",(()=>!1)),xt.registerFlag("USE_SETTIMEOUTCUSTOM",(()=>!1));const It={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};class At{static join(e){return new At(e).slice()}constructor(e){if(this.shards=[],this.previousShardIndex=0,null==e)return;if(e instanceof Array||(e=[e]),0===(e=e.map((e=>Ie(e)?e.buffer:e))).length)return;this.bufferUniformSize=e[0].byteLength;let t=0;for(let n=0;n<e.length;n++){const r=e[n];n!==e.length-1&&r.byteLength!==this.bufferUniformSize&&(this.bufferUniformSize=void 0);const s=t+r.byteLength;this.shards.push({buffer:r,start:t,end:s}),t=s}0===this.shards.length&&(this.byteLength=0),this.byteLength=this.shards[this.shards.length-1].end}slice(e=0,t=this.byteLength){if(0===this.shards.length)return new ArrayBuffer(0);if(e=isNaN(Number(e))?0:e,t=isNaN(Number(t))?0:t,e=Math.max(0,e),(t=Math.min(this.byteLength,t))<=e)return new ArrayBuffer(0);const n=this.findShardForByte(e);if(-1===n)throw new Error(`Could not find start shard for byte ${e}`);const r=new ArrayBuffer(t-e),s=new Uint8Array(r);let a=0;for(let r=n;r<this.shards.length;r++){const n=this.shards[r],i=e+a-n.start,o=a,u=Math.min(t,n.end)-n.start,l=new Uint8Array(n.buffer,i,u-i);if(s.set(l,o),a+=l.length,t<n.end)break}return r}findShardForByte(e){if(0===this.shards.length||e<0||e>=this.byteLength)return-1;if(null!=this.bufferUniformSize)return this.previousShardIndex=Math.floor(e/this.bufferUniformSize),this.previousShardIndex;function t(t){return e<t.start?-1:e>=t.end?1:0}if(0===t(this.shards[this.previousShardIndex]))return this.previousShardIndex;const n=function(e,t){let n=0,r=e.length;for(;n<=r;){const s=Math.floor((r-n)/2)+n,a=t(e[s]);if(0===a)return s;a<0?r=s:n=s+1}return-1}(this.shards,t);return-1===n?-1:(this.previousShardIndex=n,this.previousShardIndex)}}function Et(){return it}function Ot(e,t){return it.tidy(e,t)}function Dt(e){return it.keep(e)}function Ct(e){return it.setBackend(e)}function Rt(){return it.backendName}function Lt(e){it.removeBackend(e)}function Pt(e,t){const n=new At(e),r={};let s=0;for(const e of t){const t=Bt(e,((e,t)=>n.slice(s+e,s+t)));r[e.name]=zt(e,n.slice(s,s+t)),s+=t}return r}function Bt(e,t){const n=g(e.shape);let r;if("quantization"in e){const t=e.quantization;r=It[t.dtype]}else{if("string"===e.dtype){let e=0;for(let r=0;r<n;r++)e+=4+new Uint32Array(t(e,e+4))[0];return e}r=It[e.dtype]}return n*r}async function $t(e,t){const n=g(e.shape);let r;if("quantization"in e){const t=e.quantization;r=It[t.dtype]}else{if("string"===e.dtype){let e=0;for(let r=0;r<n;r++)e+=4+new Uint32Array(await t(e,e+4))[0];return e}r=It[e.dtype]}return n*r}function zt(e,t){const n=e.name,r=e.dtype,s=e.shape,a=g(s);let i,o=0;if("quantization"in e){const s=e.quantization;if("uint8"===s.dtype||"uint16"===s.dtype){if(!("min"in s)||!("scale"in s))throw new Error(`Weight ${e.name} with quantization ${s.dtype} doesn't have corresponding metadata min and scale.`)}else{if("float16"!==s.dtype)throw new Error(`Weight ${e.name} has unknown quantization dtype ${s.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);if("float32"!==r)throw new Error(`Weight ${e.name} is quantized with ${s.dtype} which only supports weights of type float32 not ${r}.`)}const u=It[s.dtype],l="uint8"===s.dtype?new Uint8Array(t):new Uint16Array(t);if("float32"===r)if("uint8"===s.dtype||"uint16"===s.dtype){i=new Float32Array(l.length);for(let e=0;e<l.length;e++){const t=l[e];i[e]=t*s.scale+s.min}}else{if("float16"!==s.dtype)throw new Error(`Unsupported quantization type ${s.dtype} for weight type float32.`);{const e=function(){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 s=new ArrayBuffer(4*r.length),a=new Uint32Array(s);for(let s=0;s<r.length;s++){const i=r[s],o=e[n[i>>10]+(1023&i)]+t[i>>10];a[s]=o}return new Float32Array(s)}}();i=e(l)}}else{if("int32"!==r)throw new Error(`Unsupported dtype in weight '${n}': ${r}`);if("uint8"!==s.dtype&&"uint16"!==s.dtype)throw new Error(`Unsupported quantization type ${s.dtype} for weight type int32.`);i=new Int32Array(l.length);for(let e=0;e<l.length;e++){const t=l[e];i[e]=Math.round(t*s.scale+s.min)}}o+=a*u}else if("string"===r){const n=g(e.shape);i=[];for(let e=0;e<n;e++){const e=new Uint32Array(t.slice(o,o+4))[0];o+=4;const n=new Uint8Array(t.slice(o,o+e));i.push(n),o+=e}}else{const e=It[r];if("float32"===r)i=new Float32Array(t);else if("int32"===r)i=new Int32Array(t);else{if("bool"!==r){if("complex64"===r){i=new Float32Array(t);const e=new Float32Array(i.length/2),n=new Float32Array(i.length/2);for(let t=0;t<e.length;t++)e[t]=i[2*t],n[t]=i[2*t+1];const r=Ft(e,s,"float32"),a=Ft(n,s,"float32"),o=wt(r,a);return r.dispose(),a.dispose(),o}throw new Error(`Unsupported dtype in weight '${n}': ${r}`)}i=new Uint8Array(t)}o+=a*e}return Ft(i,s,r)}async function Ht(e,t,n){let r=new Uint8Array(t);for(;r.byteLength<n;){const{done:t,value:s}=await e.read();if(t&&null==s){const e=n-r.byteLength;throw new Error(`Reader is done but ${e} bytes are still expected`)}const a=new Uint8Array(r.length+s.byteLength);a.set(r,0),a.set(new Uint8Array(s),r.length),r=a}return r.buffer}async function jt(e,t){const n={},r=e.getReader();let s=new ArrayBuffer(0);for(const e of t){const t=await $t(e,(async(e,t)=>(s=await Ht(r,s,t),s.slice(e,t))));s=await Ht(r,s,t);const a=s.slice(0,t);s=s.slice(t);const i=zt(e,a);if(n[e.name]=i,"webgpu"===Rt()){const e=it.backend;"uploadToGPU"in e&&g(i.shape)>=R().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")&&e.uploadToGPU(i.dataId)}}return n}function Vt(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 s=0;return n.forEach((e=>{r.set(new Uint8Array(e.buffer),s),s+=e.byteLength})),r.buffer}const Wt="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function Ut(e){return Wt?Buffer.byteLength(e,"utf8"):new Blob([e]).size}function Kt(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function Gt(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 qt(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 Qt(e,t){let n,r;return null!=e.weightsManifest&&([n,r]=await t(e.weightsManifest)),qt(e,n,r)}function Jt(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:Ut(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:Ut(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:new At(e.weightData).byteLength}}function Yt(e){const t=[];for(const n of e)t.push(...n.weights);return t}class Xt{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==Xt.instance&&(Xt.instance=new Xt),Xt.instance}static registerSaveRouter(e){Xt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Xt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Xt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Xt.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[];return("load"===t?Xt.getInstance().loadRouters:Xt.getInstance().saveRouters).forEach((t=>{const s=t(e,n);null!==s&&r.push(s)})),r}}const Zt="tensorflowjs",en="models_store",tn="model_info_store";function nn(){if(!R().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 rn(e){const t=e.result;t.createObjectStore(en,{keyPath:"modelPath"}),t.createObjectStore(tn,{keyPath:"modelPath"})}class sn{constructor(e){if(this.indexedDB=nn(),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(Zt,1);r.onupgradeneeded=()=>rn(r),r.onsuccess=()=>{const s=r.result;if(null==t){const t=s.transaction(en,"readonly"),r=t.objectStore(en).get(this.modelPath);r.onsuccess=()=>{if(null==r.result)return s.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(r.result.modelArtifacts)},r.onerror=e=>(s.close(),n(r.error)),t.oncomplete=()=>s.close()}else{t.weightData=At.join(t.weightData);const r=Jt(t),a=s.transaction(tn,"readwrite");let i,o,u=a.objectStore(tn);try{i=u.put({modelPath:this.modelPath,modelArtifactsInfo:r})}catch(e){return n(e)}i.onsuccess=()=>{o=s.transaction(en,"readwrite");const i=o.objectStore(en);let l;try{l=i.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:r})}catch(e){return n(e)}l.onsuccess=()=>e({modelArtifactsInfo:r}),l.onerror=e=>{u=a.objectStore(tn);const t=u.delete(this.modelPath);t.onsuccess=()=>(s.close(),n(l.error)),t.onerror=e=>(s.close(),n(l.error))}},i.onerror=e=>(s.close(),n(i.error)),a.oncomplete=()=>{null==o?s.close():o.oncomplete=()=>s.close()}}},r.onerror=e=>n(r.error)}))}}sn.URL_SCHEME="indexeddb://";const an=e=>{return R().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(sn.URL_SCHEME)?(t=e.slice(sn.URL_SCHEME.length),new sn(t)):null;var t};Xt.registerSaveRouter(an),Xt.registerLoadRouter(an);class on{constructor(){this.indexedDB=nn()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open(Zt,1);n.onupgradeneeded=()=>rn(n),n.onsuccess=()=>{const r=n.result,s=r.transaction(tn,"readonly"),a=s.objectStore(tn).getAll();a.onsuccess=()=>{const t={};for(const e of a.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},a.onerror=e=>(r.close(),t(a.error)),s.oncomplete=()=>r.close()},n.onerror=e=>t(n.error)}))}async removeModel(e){var t;return e=(t=e).startsWith(sn.URL_SCHEME)?t.slice(sn.URL_SCHEME.length):t,new Promise(((t,n)=>{const r=this.indexedDB.open(Zt,1);r.onupgradeneeded=()=>rn(r),r.onsuccess=()=>{const s=r.result,a=s.transaction(tn,"readwrite"),i=a.objectStore(tn),o=i.get(e);let u;o.onsuccess=()=>{if(null==o.result)return s.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const r=i.delete(e),a=()=>{u=s.transaction(en,"readwrite");const r=u.objectStore(en).delete(e);r.onsuccess=()=>t(o.result.modelArtifactsInfo),r.onerror=e=>n(o.error)};r.onsuccess=a,r.onerror=e=>(a(),s.close(),n(o.error))}},o.onerror=e=>(s.close(),n(o.error)),a.oncomplete=()=>{null==u?s.close():u.oncomplete=()=>s.close()}},r.onerror=e=>n(r.error)}))}}const un="/",ln="tensorflowjs_models",pn="info",cn="model_topology",hn="weight_specs",dn="weight_data",fn="model_metadata";function mn(e){return{info:[ln,e,pn].join(un),topology:[ln,e,cn].join(un),weightSpecs:[ln,e,hn].join(un),weightData:[ln,e,dn].join(un),modelMetadata:[ln,e,fn].join(un)}}function yn(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function gn(e){const t=e.split(un);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(un)}class _n{constructor(e){if(!R().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=mn(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=Jt(e),s=At.join(e.weightData);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(Wt)return Buffer.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)}(s));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 yn(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 s=this.LS.getItem(this.keys.modelMetadata);if(null!=s){const e=JSON.parse(s);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 a=this.LS.getItem(this.keys.weightData);if(null==a)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=function(e){if(Wt){const t=Buffer.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}(a),t}}_n.URL_SCHEME="localstorage://";const bn=e=>{return R().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(_n.URL_SCHEME)?(t=e.slice(_n.URL_SCHEME.length),new _n(t)):null;var t};Xt.registerSaveRouter(bn),Xt.registerLoadRouter(bn);class wn{constructor(){m(R().getBool("IS_BROWSER"),(()=>"Current environment is not a web browser")),m("undefined"==typeof window||void 0!==window.localStorage,(()=>"Current browser does not appear to support localStorage")),this.LS=window.localStorage}async listModels(){const e={},t=ln+un,n=un+pn;for(let r=0;r<this.LS.length;++r){const s=this.LS.key(r);s.startsWith(t)&&s.endsWith(n)&&(e[gn(s)]=JSON.parse(this.LS.getItem(s)))}return e}async removeModel(e){var t;const n=mn(e=(t=e).startsWith(_n.URL_SCHEME)?t.slice(_n.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 yn(n),r}}function vn(e){return new Promise((e=>setTimeout(e))).then(e)}class Tn{constructor(e){if(!R().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Tn.URL_SCHEME)&&(e=e.slice(Tn.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=At.join(e.weightData),n=window.URL.createObjectURL(new Blob([t],{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 t=Gt(e,[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}]),r=window.URL.createObjectURL(new Blob([JSON.stringify(t)],{type:"application/json"})),s=null==this.modelJsonAnchor?document.createElement("a"):this.modelJsonAnchor;if(s.download=this.modelJsonFileName,s.href=r,await vn((()=>s.dispatchEvent(new MouseEvent("click")))),null!=e.weightData){const e=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor;e.download=this.weightDataFileName,e.href=n,await vn((()=>e.dispatchEvent(new MouseEvent("click"))))}return{modelArtifactsInfo:Jt(e)}}}}Tn.URL_SCHEME="downloads://";class Sn{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),s=r.modelTopology;if(null==s)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:s});const a=Qt(r,(e=>this.loadWeights(e)));e(a)},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),s=n.map((e=>this.loadWeightsFile(e,r[e])));return Promise.all(s).then((e=>[t,e]))}loadWeightsFile(e,t){return new Promise(((n,r)=>{const s=new FileReader;s.onload=e=>{const t=e.target.result;n(t)},s.onerror=t=>r(`Failed to weights data from file of path '${e}'.`),s.readAsArrayBuffer(t)}))}checkManifestAndWeightFiles(e){const t=[],n=this.weightsFiles.map((e=>Kt(e.name))),r={};for(const s of e)s.paths.forEach((e=>{const s=Kt(e);if(-1!==t.indexOf(s))throw new Error(`Duplicate file basename found in weights manifest: '${s}'`);if(t.push(s),-1===n.indexOf(s))throw new Error(`Weight file with basename '${s}' is not provided.`);r[e]=this.weightsFiles[n.indexOf(s)]}));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 kn(e,t,n,r){!function(e){m(null!=e&&Array.isArray(e)&&e.length>0,(()=>"promises must be a none empty array"))}(e),function(e,t){m(e>=0&&e<=1,(()=>`Progress fraction must be in range [0, 1], but got startFraction ${e}`)),m(t>=0&&t<=1,(()=>`Progress fraction must be in range [0, 1], but got endFraction ${t}`)),m(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 s=0;return Promise.all(e.map((a=>(a.then((a=>{const i=n+ ++s/e.length*(r-n);return t(i),a})),a))))}async function Nn(e,t){null==t&&(t={});const n=null==t.fetchFunc?R().platform.fetch:t.fetchFunc,r=e.map((e=>n(e,t.requestInit,{isBinary:!0}))),s=(null==t.onProgress?await Promise.all(r):await kn(r,t.onProgress,0,.5)).map((e=>e.arrayBuffer()));return null==t.onProgress?await Promise.all(s):await kn(s,t.onProgress,.5,1)}function Mn(e){return async(t,n="",r)=>{const s=t.map((()=>!1)),a={},i=null!=r?r.map((()=>!1)):[],o=[];if(t.forEach(((e,t)=>{let n=0;e.weights.forEach((e=>{const u="quantization"in e?e.quantization.dtype:e.dtype,l=It[u]*g(e.shape),p=()=>{s[t]=!0,null==a[t]&&(a[t]=[]),a[t].push({manifestEntry:e,groupOffset:n,sizeBytes:l})};null!=r?r.forEach(((t,n)=>{t===e.name&&(p(),i[n]=!0)})):p(),o.push(e.name),n+=l}))})),!i.every((e=>e))){const e=r.filter(((e,t)=>!i[t]));throw new Error(`Could not find weights in manifest with names: ${e.join(", ")}. \nManifest JSON has weights with names: ${o.join(", ")}.`)}const u=s.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 p=await e(l),c={};let h=0;return u.forEach((e=>{const n=t[e].paths.length,r=new At(p.slice(h,h+n));a[e].forEach((e=>{const t=Pt(r.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(const e in t)c[e]=t[e]})),h+=n})),c}}Xt.registerSaveRouter((e=>R().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Tn.URL_SCHEME)?function(e="model"){return new Tn(e)}(e.slice(Tn.URL_SCHEME.length)):null));class xn{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?(m("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=R().platform.fetch,m(null!=e&&e.length>0,(()=>"URL path for http must not be null, undefined or empty.")),Array.isArray(e)&&m(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||{},this.loadOptions=t}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=Gt(e,[{paths:["./model.weights.bin"],weights:e.weightSpecs}]);if(t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData){const n=At.join(e.weightData);t.body.append("model.weights.bin",new Blob([n],{type:"application/octet-stream"}),"model.weights.bin")}const r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:Jt(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async loadModelJSON(){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 t}async load(){return this.loadOptions.streamWeights?this.loadStream():Qt(await this.loadModelJSON(),(e=>this.loadWeights(e)))}async loadStream(){const e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),n=Yt(e.weightsManifest);return Object.assign(Object.assign({},e),{weightSpecs:n,getWeightStream:()=>function(e,t){var n;const r=null==t.fetchFunc?R().platform.fetch:t.fetchFunc;let s,a=0;return null===(n=t.onProgress)||void 0===n||n.call(t,0),new ReadableStream({pull:async n=>{for(var i;a<e.length;){if(!s){const n=(await r(e[a],t.requestInit,{isBinary:!0})).body;s=n.getReader()}const{done:o,value:u}=await s.read();if(!o)return void n.enqueue(u);a++,s=void 0,null===(i=t.onProgress)||void 0===i||i.call(t,a/e.length)}n.close()}})}(t,this.loadOptions)})}async getWeightUrls(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),s=this.weightPathPrefix||n,a=[],i=[];for(const t of e)for(const e of t.paths)null!=this.weightUrlConverter?i.push(this.weightUrlConverter(e)):a.push(s+e+r);return this.weightUrlConverter&&a.push(...await Promise.all(i)),a}async loadWeights(e){const t=await this.getWeightUrls(e);return[Yt(e),await Nn(t,this.loadOptions)]}}function Fn(e){return null!=e.match(xn.URL_SCHEME_REGEX)}xn.URL_SCHEME_REGEX=/^https?:\/\//;const In=(e,t)=>{if("undefined"==typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every((e=>Fn(e))):Fn(e),n)return An(e,t)}return null};function An(e,t){return new xn(e,t)}Xt.registerSaveRouter(In),Xt.registerLoadRouter(In);class En{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class On{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class Dn{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function Cn(e,t,n,r){return 1===arguments.length?null!=e.modelTopology||null!=e.weightSpecs?new En(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 En({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 En({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r}))}const Rn="://";class Ln{constructor(){this.managers={}}static getInstance(){return null==Ln.instance&&(Ln.instance=new Ln),Ln.instance}static registerManager(e,t){m(null!=e,(()=>"scheme must not be undefined or null.")),e.endsWith(Rn)&&(e=e.slice(0,e.indexOf(Rn))),m(e.length>0,(()=>"scheme must not be an empty string."));const n=Ln.getInstance();m(null==n.managers[e],(()=>`A model store manager is already registered for scheme '${e}'.`)),n.managers[e]=t}static getManager(e){const t=Ln.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(Ln.getInstance().managers)}}function Pn(e){if(-1===e.indexOf(Rn))throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Ln.getSchemes().join(",")}`);return{scheme:e.split(Rn)[0],path:e.split(Rn)[1]}}async function Bn(e,t,n=!1){m(e!==t,(()=>`Old path and new path are the same: '${e}'`));const r=Xt.getLoadHandlers(e);m(r.length>0,(()=>`Copying failed because no load handler is found for source URL ${e}.`)),m(r.length<2,(()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${e}.`));const s=r[0],a=Xt.getSaveHandlers(t);m(a.length>0,(()=>`Copying failed because no save handler is found for destination URL ${t}.`)),m(a.length<2,(()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${t}.`));const i=a[0],o=Pn(e).scheme,u=Pn(e).path,l=o===Pn(e).scheme,p=await s.load();n&&l&&await Ln.getManager(o).removeModel(u);const c=await i.save(p);return n&&!l&&await Ln.getManager(o).removeModel(u),c.modelArtifactsInfo}var $n=Object.freeze({__proto__:null,CompositeArrayBuffer:At,browserFiles:function(e){return new Sn(e)},browserHTTPRequest:function(e,t){return An(e,t)},concatenateArrayBuffers:function(e){return At.join(e)},copyModel:async function(e,t){return Bn(e,t,!1)},decodeWeights:Pt,decodeWeightsStream:jt,encodeWeights:async function(e,t){const n=[],r=[],s=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);for(let a=0;a<s.length;++a){const i=s[a],o=Array.isArray(e)?e[a].tensor:e[i];if("float32"!==o.dtype&&"int32"!==o.dtype&&"bool"!==o.dtype&&"string"!==o.dtype&&"complex64"!==o.dtype)throw new Error(`Unsupported dtype in weight '${i}': ${o.dtype}`);const u={name:i,shape:o.shape,dtype:o.dtype};if("string"===o.dtype){const e=new Promise((async e=>{const t=await o.bytes(),n=t.reduce(((e,t)=>e+t.length),0)+4*t.length,r=new Uint8Array(n);let s=0;for(let e=0;e<t.length;e++){const n=t[e],a=new Uint8Array(new Uint32Array([n.length]).buffer);r.set(a,s),s+=4,r.set(n,s),s+=n.length}e(r)}));r.push(e)}else r.push(o.data());null!=t&&(u.group=t),n.push(u)}return{data:Vt(await Promise.all(r)),specs:n}},fromMemory:function(e,t,n,r){const s=arguments;return new Dn(Cn(...s))},fromMemorySync:Cn,getLoadHandlers:(e,t)=>Xt.getLoadHandlers(e,t),getModelArtifactsForJSON:Qt,getModelArtifactsForJSONSync:qt,getModelArtifactsInfoForJSON:Jt,getSaveHandlers:e=>Xt.getSaveHandlers(e),getWeightSpecs:Yt,http:An,isHTTPScheme:Fn,listModels:async function(){const e=Ln.getSchemes(),t={};for(const n of e){const e=await Ln.getManager(n).listModels();for(const r in e)t[n+Rn+r]=e[r]}return t},loadWeights:async function(e,t="",n,r){return Mn((e=>Nn(e,{requestInit:r})))(e,t,n)},moveModel:async function(e,t){return Bn(e,t,!0)},registerLoadRouter:e=>Xt.registerLoadRouter(e),registerSaveRouter:e=>Xt.registerSaveRouter(e),removeModel:async function(e){const t=Pn(e);return Ln.getManager(t.scheme).removeModel(t.path)},weightsLoaderFactory:Mn,withSaveHandler:function(e){return new On(e)},withSaveHandlerSync:function(e){return new On(e)}});const zn=dt({matMul_:function(e,t,n=!1,r=!1){let s=ct(e,"a","matMul"),a=ct(t,"b","matMul");[s,a]=Ze(s,a);const i={a:s,b:a},o={transposeA:n,transposeB:r};return it.runKernel(j,i,o)}});function Hn(e,t){const n=Math.max(e.length,t.length),r=new Array(n);for(let s=0;s<n;s++){let a=e[e.length-s-1];null==a&&(a=1);let i=t[t.length-s-1];if(null==i&&(i=1),1===a)r[n-s-1]=i;else if(1===i)r[n-s-1]=a;else{if(a!==i)throw Error(`Operands could not be broadcast together with shapes ${e} and ${t}.`);r[n-s-1]=a}}return r}function jn(e,t,n){let r=n.length;for(let e=0;e<n.length;e++)if(n[e]>1){r=e;break}for(let s=r+1;s<n.length;s++)if(t[s]>0||n[s]!==e[s])return!1;return!0}function Vn(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 Wn(e,t,n,r,s,a){if(s[t])return n>0?a[t]:a[t+1&1];{const t=e<0?r+e:e;return t<a[0]?a[0]:t>a[1]?a[1]:t}}const Un=dt({add_:function(e,t){let n=ct(e,"a","add"),r=ct(t,"b","add");[n,r]=Ze(n,r);const s={a:n,b:r};return it.runKernel(z,s)}}),Kn=dt({mul_:function(e,t){let n=ct(e,"a","mul"),r=ct(t,"b","mul");[n,r]=Ze(n,r);const s={a:n,b:r};return it.runKernel(X,s)}}),Gn=dt({addN_:function(e){m(Array.isArray(e),(()=>"The argument passed to tf.addN() must be a list of tensors")),m(e.length>=1,(()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`));const t=e.map(((e,t)=>ct(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(!_(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));const r=t;return it.runKernel(H,r)}});function qn(e,t,n,r,s,a,i=!1,o="channelsLast"){let[u,l,p,c]=[-1,-1,-1,-1];if("channelsLast"===o)[u,l,p,c]=e;else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);[u,c,l,p]=e}const[h,d,,f]=t,[m,y]=Qn(n),[g,_]=Qn(r),b=Jn(h,g),w=Jn(d,_),{padInfo:v,outHeight:T,outWidth:S}=function(e,t,n,r,s,a,i,o,u){let l,p,c;if("number"==typeof e){l={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const s=function(e,t,n,r,s){null==r&&(r=function(e,t,n,r=1){const s=Jn(t,r);return Math.floor((e[0]*(n-1)-n+s)/2)}(e,t,n));const a=e[1];return[Yn((e[0]-t+2*r)/n+1,s),Yn((a-t+2*r)/n+1,s)]}([t,n],a,r,e,o);p=s[0],c=s[1]}else if("same"===e){p=Math.ceil(t/r),c=Math.ceil(n/s);const e=Math.max(0,(p-1)*r+a-t),o=Math.max(0,(c-1)*s+i-n),u=Math.floor(e/2),h=e-u,d=Math.floor(o/2);l={top:u,bottom:h,left:d,right:o-d,type:"SAME"}}else if("valid"===e)l={top:0,bottom:0,left:0,right:0,type:"VALID"},p=Math.ceil((t-a+1)/r),c=Math.ceil((n-i+1)/s);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"},p=Yn((t-a+h+d)/r+1,o),c=Yn((n-i+f+m)/s+1,o)}}return{padInfo:l,outHeight:p,outWidth:c}}(s,l,p,m,y,b,w,a,o),k=i?f*c:f;let N;return"channelsFirst"===o?N=[u,k,T,S]:"channelsLast"===o&&(N=[u,T,S,k]),{batchSize:u,dataFormat:o,inHeight:l,inWidth:p,inChannels:c,outHeight:T,outWidth:S,outChannels:k,padInfo:v,strideHeight:m,strideWidth:y,filterHeight:h,filterWidth:d,effectiveFilterHeight:b,effectiveFilterWidth:w,dilationHeight:g,dilationWidth:_,inShape:e,outShape:N,filterShape:t}}function Qn(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function Jn(e,t){return t<=1?e:e+(e-1)*(t-1)}function Yn(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 Xn(e){const[t,n,r]=Qn(e);return 1===t&&1===n&&1===r}function Zn(e,t){return Xn(e)||Xn(t)}function er(e){return Qn(e).every((e=>e>0))}function tr(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)m(b(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=>{m(b(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`))}))}))}}}const nr=dt({clone_:function(e){const t={x:ct(e,"x","clone","string_or_numeric")};return it.runKernel(J,t)}}),rr=dt({concat_:function(e,t=0){m(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=ht(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 nr(n[0]);const r=n,s={axis:t};return it.runKernel(W,r,s)}}),sr=dt({sigmoid_:function(e){const t={x:ct(e,"x","sigmoid","float32")};return it.runKernel(ae,t)}}),ar=dt({slice_:function(e,t,n){const r=ct(e,"x","slice","string_or_numeric");if(0===r.rank)throw new Error("Slicing scalar is not possible");const s={x:r},a={begin:t,size:n};return it.runKernel("Slice",s,a)}});function ir(e,t="float32",n){return t=t||"float32",E(e),new $e(e,t,n)}const or=dt({conv2d_:function(e,t,n,r,s="NHWC",a=[1,1],i){const o=ct(e,"x","conv2d","float32"),u=ct(t,"filter","conv2d","float32");let l=o,p=!1;3===o.rank&&(p=!0,l=kt(o,[1,o.shape[0],o.shape[1],o.shape[2]])),m(4===l.rank,(()=>`Error in conv2d: input must be rank 4, but got rank ${l.rank}.`)),m(4===u.rank,(()=>`Error in conv2d: filter must be rank 4, but got rank ${u.rank}.`)),tr("conv2d",r,i);const c="NHWC"===s?l.shape[3]:l.shape[1];m(c===u.shape[2],(()=>`Error in conv2d: depth of input (${c}) must match input depth for filter ${u.shape[2]}.`)),m(Zn(n,a),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),m(er(a),(()=>"Error in conv2D: Dilated rates should be larger than 0.")),m(er(n),(()=>"Error in conv2D: Strides should be larger than 0."));const h={x:l,filter:u},d={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i},f=it.runKernel(U,h,d);return p?kt(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),ur=dt({conv2DBackpropInput_:function(e,t,n,r,s,a="NHWC",i){m(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let o=e,u=t,l=!1;3===t.rank&&(l=!0,u=kt(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),m(4===o.length,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`)),m(4===u.rank,(()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${u.rank}`)),m(4===n.rank,(()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`));const p="NHWC"===a?o[3]:o[1],c="NHWC"===a?u.shape[3]:u.shape[1];m(p===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${p}) must match input depth for filter ${n.shape[2]}.`)),m(c===n.shape[3],(()=>`Error in conv2dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[3]}.`)),tr("conv2dDerInput",s,i);const h={dy:u,filter:n},d={strides:r,pad:s,dataFormat:a,dimRoundingMode:i,inputShape:o},f=it.runKernel("Conv2DBackpropInput",h,d);return l?kt(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),lr=dt({depthwiseConv2d_:function(e,t,n,r,s="NHWC",a=[1,1],i){const o=ct(e,"x","depthwiseConv2d","float32"),u=ct(t,"filter","depthwiseConv2d","float32");let l=o,p=!1;3===o.rank&&(p=!0,l=kt(o,[1,o.shape[0],o.shape[1],o.shape[2]])),m(4===l.rank,(()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${l.rank}.`)),m(4===u.rank,(()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${u.rank}.`));const c="NHWC"===s?l.shape[3]:l.shape[1];m(c===u.shape[2],(()=>`Error in depthwiseConv2d: number of input channels (${c}) must match the inChannels dimension in filter ${u.shape[2]}.`)),tr("depthwiseConv2d",r,i);const h={x:l,filter:u},d={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i},f=it.runKernel(G,h,d);return p?kt(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),pr=dt({elu_:function(e){const t={x:ct(e,"x","elu","float32")};return it.runKernel("Elu",t)}});function cr(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function hr(e,t){return function(e,t,n){const r=e.length+t.length,s=[];let a=0,i=0;for(let o=0;o<r;o++)-1===n.indexOf(o)?s.push(e[a++]):s.push(t[i++]);return s}(e,t.map((e=>1)),t)}function dr(e,t){const n=[];for(let r=t-e;r<t;++r)n.push(r);return n}const fr=dt({max_:function(e,t=null,n=!1){const r={x:ct(e,"x","max")},s={reductionIndices:t,keepDims:n};return it.runKernel("Max",r,s)}}),mr=dt({min_:function(e,t=null,n=!1){const r={x:ct(e,"x","min")},s={axis:t,keepDims:n};return it.runKernel("Min",r,s)}}),yr=dt({sqrt_:function(e){const t={x:ct(e,"x","sqrt","float32")};return it.runKernel("Sqrt",t)}}),gr=dt({square_:function(e){const t=ct(e,"x","square");return it.runKernel("Square",{x:t},{})}}),_r=dt({sum_:function(e,t=null,n=!1){let r=ct(e,"x","sum");"bool"===r.dtype&&(r=mt(r,"int32"));const s={x:r},a={axis:t,keepDims:n};return it.runKernel("Sum",s,a)}}),br=dt({expandDims_:function(e,t=0){const n=ct(e,"x","expandDims","string_or_numeric");m(t<=n.rank,(()=>"Axis must be <= rank of the tensor"));const r={input:n},s={dim:t};return it.runKernel(Q,r,s)}}),wr=dt({leakyRelu_:function(e,t=.2){const n={x:ct(e,"x","leakyRelu")},r={alpha:t};return it.runKernel("LeakyRelu",n,r)}});function vr(e){return it.customGrad(e)}const Tr=dt({mean_:function(e,t=null,n=!1){const r={x:ct(e,"x","mean")},s={axis:t,keepDims:n};return it.runKernel(Y,r,s)}}),Sr=dt({moments_:function(e,t=null,n=!1){const r=v(t,(e=ct(e,"x","moments")).shape),s=Tr(e,r,n);let a=s.shape;n||(a=hr(s.shape,r));const i=gr(St(mt(e,"float32"),kt(s,a)));return{mean:s,variance:Tr(i,r,n)}}}),kr=dt({notEqual_:function(e,t){let n=ct(e,"a","notEqual","string_or_numeric"),r=ct(t,"b","notEqual","string_or_numeric");[n,r]=Ze(n,r),Hn(n.shape,r.shape);const s={a:n,b:r};return it.runKernel("NotEqual",s)}}),Nr=dt({pad_:function(e,t,n=0){const r=ct(e,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const s={paddings:t,constantValue:n},a={x:r};return it.runKernel(Z,a,s)}}),Mr=dt({prelu_:function(e,t){const n={x:ct(e,"x","prelu"),alpha:ct(t,"alpha","prelu")};return it.runKernel("Prelu",n)}});var xr=ke(Object.freeze({__proto__:null,default:{}}));const Fr=dt({relu_:function(e){const t={x:ct(e,"x","relu")};return it.runKernel(ee,t)}}),Ir=dt({relu6_:function(e){const t={x:ct(e,"x","relu6")};return it.runKernel(re,t)}}),Ar=dt({reverse_:function(e,t){const n={x:ct(e,"x","reverse")},r={dims:t};return it.runKernel(se,n,r)}}),Er=dt({stack_:function(e,t=0){const n=ht(e,"tensors","stack","string_or_numeric");m(n.length>=1,(()=>"Pass at least one tensor to tf.stack")),n.length>0&&m(t<=n[0].rank,(()=>"Axis must be <= rank of the tensor"));const r=n,s={axis:t};return it.runKernel("Pack",r,s)}}),Or=dt({step_:function(e,t=0){const n={x:ct(e,"x","step")},r={alpha:t};return it.runKernel("Step",n,r)}}),Dr=dt({stridedSlice_:function(e,t,n,r,s=0,a=0,i=0,o=0,u=0){const l={x:ct(e,"x","stridedSlice","string_or_numeric")},p={begin:t,end:n,strides:r,beginMask:s,endMask:a,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:u};return it.runKernel(ie,l,p)}}),Cr=dt({unstack_:function(e,t=0){const n=ct(e,"x","unstack","string_or_numeric");m(t>=-n.shape.length&&t<n.shape.length,(()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`));const r={value:n},s={axis:t};return it.runKernel(ue,r,s)}}),Rr=dt({conv2DBackpropFilter_:function(e,t,n,r,s,a="NHWC",i){let o=e;3===e.rank&&(o=kt(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u=t;3===u.rank&&(u=kt(t,[1,t.shape[0],t.shape[1],t.shape[2]])),m(4===o.rank,(()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`)),m(4===u.rank,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${u.shape}.`)),m(4===n.length,(()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`));const l="NHWC"===a?o.shape[3]:o.shape[1],p="NHWC"===a?u.shape[3]:u.shape[1];m(l===n[2],(()=>`Error in conv2dDerFilter: depth of input ${l}) must match input depth in filter (${n[2]}.`)),m(p===n[3],(()=>`Error in conv2dDerFilter: depth of dy (${p}) must match output depth for filter (${n[3]}).`)),tr("conv2dDerFilter",s,i);const c={x:o,dy:u},h={strides:r,pad:s,dataFormat:a,dimRoundingMode:i,filterShape:n};return it.runKernel("Conv2DBackpropFilter",c,h)}});function Lr(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return Kn(e,Or(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Pr(e,t){let n=t;const r=function(e,t){const n=[];for(let r=0;r<t.length;r++){const s=e[e.length-r-1],a=t.length-r-1,i=t[a];(null==s||1===s&&i>1)&&n.unshift(a)}return n}(e.shape,t.shape);return r.length>0&&(n=_r(n,r)),kt(n,e.shape)}function Br(e,t,n,r){if("linear"===t)return e;if("relu"===t)return Fr(e);if("elu"===t)return pr(e);if("relu6"===t)return Ir(e);if("prelu"===t)return Mr(e,n);if("leakyrelu"===t)return wr(e,r);if("sigmoid"===t)return sr(e);throw new Error(`Unknown fused activation ${t}.`)}const $r=(e,t)=>!(e>0)||"linear"===t,zr=dt({fusedConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:i,bias:o,activation:u="linear",preluActivationWeights:l,leakyreluAlpha:p}){if(u=u||"linear",!1===$r(it.state.gradientDepth,u)){m("NHWC"===s,(()=>`Error in fused conv2d: got dataFormat of ${s} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`));let c=or(e,t,n,r,s,a,i);return null!=o&&(c=Un(c,o)),Br(c,u,l,p)}const c=ct(e,"x","conv2d","float32"),h=ct(t,"filter","conv2d","float32");let d=c,f=!1;3===c.rank&&(f=!0,d=kt(c,[1,c.shape[0],c.shape[1],c.shape[2]])),m(4===d.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${d.rank}.`)),m(4===h.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${h.rank}.`)),tr("fused conv2d",r,i);const y="NHWC"===s?d.shape[3]:d.shape[1];m(h.shape[2]===y,(()=>`Error in conv2d: depth of input (${y}) must match input depth for filter ${h.shape[2]}.`)),m(Zn(n,a),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`));const g=qn(d.shape,h.shape,n,a,r,i);let _,b;if(null!=o&&(_=ct(o,"bias","fused conv2d"),[_]=Ze(_,c),"NHWC"===s?Hn(g.outShape,_.shape):(m(_.shape.length<=1,(()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${_.shape.length}.`)),m(0===_.shape.length||_.shape[0]===g.outChannels||1===_.shape[0],(()=>`Error in fused conv2d: bias shape (${_.shape}) is not compatible with the number of output channels (${g.outChannels})`)))),null!=l){const e=l.shape;if(m(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)m(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{Hn(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=ct(l,"prelu weights","fused conv2d")}const w=(e,t)=>{m("NHWC"===s,(()=>`Error in gradient of fused conv2D: got dataFormat of ${s} but only NHWC is currently supported.`));const[i,o,l,p]=t,c=Lr(e,l,u);m(Xn(a),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`));const h=[ur(o.shape,c,i,n,r),Rr(o,c,i.shape,n,r)];if(null!=p){const e=Pr(p,c);h.push(e)}return h},v={x:d,filter:h,bias:_,preluActivationWeights:b},T={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i,activation:u,leakyreluAlpha:p};if(null==o){const e=vr(((e,t,n)=>{let r=it.runKernel(ce,v,T);return n([t,e,r]),f&&(r=kt(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:w}}));return e(d,h)}{const e=vr(((e,t,n,r)=>{let s=it.runKernel(ce,v,T);return r([t,e,s,n]),f&&(s=kt(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:w}}));return e(d,h,_)}}}),Hr=dt({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,r,s,a=[1,1],i){let o=e;3===e.rank&&(o=kt(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u=t;3===u.rank&&(u=kt(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={x:o,dy:u},p={strides:r,pad:s,dimRoundingMode:i,dilations:a,filterShape:n};return it.runKernel("DepthwiseConv2dNativeBackpropFilter",l,p)}}),jr=dt({depthwiseConv2dNativeBackpropInput_:function(e,t,n,r,s,a=[1,1],i){let o=t,u=!1;3===t.rank&&(u=!0,o=kt(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={dy:o,filter:n},p={strides:r,pad:s,dimRoundingMode:i,dilations:a,inputShape:e},c=it.runKernel("DepthwiseConv2dNativeBackpropInput",l,p);return u?kt(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),Vr=dt({fusedDepthwiseConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:i,bias:o,activation:u="linear",preluActivationWeights:l,leakyreluAlpha:p}){if(!1===$r(it.state.gradientDepth,u)){let c=lr(e,t,n,r,s,a,i);return null!=o&&(c=Un(c,o)),Br(c,u,l,p)}const c=ct(e,"x","depthwiseConv2d","float32"),h=ct(t,"filter","depthwiseConv2d","float32");let d=c,f=!1;3===c.rank&&(f=!0,d=kt(c,[1,c.shape[0],c.shape[1],c.shape[2]])),m(4===d.rank,(()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${d.rank}.`)),m(4===h.rank,(()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`)),m(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==a&&(a=[1,1]),m(Zn(n,a),(()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),tr("fused depthwiseConv2d",r,i);const y=qn(d.shape,h.shape,n,a,r,i,!0);let g,_;null!=o&&(g=ct(o,"bias","fused conv2d"),[g]=Ze(g,c),Hn(y.outShape,g.shape)),null!=l&&(_=ct(l,"prelu weights","fused depthwiseConv2d"));const b=(e,t)=>{m(Xn(a),(()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`));const[s,o,l,p]=t,c=Lr(e,l,u),h=jr(o.shape,c,s,n,r,a,i),d=Hr(o,c,s.shape,n,r,a,i);return null!=p?[h,d,Pr(g,c)]:[h,d]},w={x:d,filter:h,bias:g,preluActivationWeights:_},v={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i,activation:u,leakyreluAlpha:p};if(null==o){const e=vr(((e,t,n)=>{let r=it.runKernel(he,w,v);return n([t,e,r]),f&&(r=kt(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:b}}));return e(d,h)}{const e=vr(((e,t,n,r)=>{let s=it.runKernel(he,w,v);return r([t,e,s,n]),f&&(s=kt(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:b}}));return e(d,h,g)}}}),Wr=dt({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:s,activation:a="linear",preluActivationWeights:i,leakyreluAlpha:o=.2}){if(!1===$r(it.state.gradientDepth,a)){let u=zn(e,t,n,r);return null!=s&&(u=Un(u,s)),Br(u,a,i,o)}let u=ct(e,"a","fused matMul"),l=ct(t,"b","fused matMul");[u,l]=Ze(u,l);const p=n?u.shape[u.rank-2]:u.shape[u.rank-1],c=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),y=l.shape.slice(0,-2),_=g(f),b=g(y);m(p===c,(()=>`Error in fused matMul: inner shapes (${p}) and (${c}) of Tensors with shapes ${u.shape} and ${l.shape} and transposeA=${n} and transposeB=${r} must match.`));const w=Hn(u.shape.slice(0,-2),l.shape.slice(0,-2)).concat([h,d]),v=kt(u,n?[_,p,h]:[_,h,p]),T=kt(l,r?[b,d,c]:[b,c,d]);let S,k;null!=s&&(S=ct(s,"bias","fused matMul"),[S]=Ze(S,u),Hn(w,S.shape)),null!=i&&(k=ct(i,"prelu weights","fused matMul"));const N=(e,t)=>{const[i,o,u,l]=t,p=Lr(kt(e,u.shape),u,a);let c,h;return n||r?!n&&r?(c=zn(p,o,!1,!1),h=zn(p,i,!0,!1)):n&&!r?(c=zn(o,p,!1,!0),h=zn(i,p,!1,!1)):(c=zn(o,p,!0,!0),h=zn(p,i,!0,!0)):(c=zn(p,o,!1,!0),h=zn(i,p,!0,!1)),null!=s?[c,h,Pr(l,p)]:[c,h]},M={a:v,b:T,bias:S,preluActivationWeights:k},x={transposeA:n,transposeB:r,activation:a,leakyreluAlpha:o};if(null==s){const e=vr(((e,t,n)=>{const r=it.runKernel(pe,M,x);return n([e,t,r]),{value:kt(r,w),gradFunc:N}}));return e(v,T)}{const e=vr(((e,t,n,r)=>{const s=it.runKernel(pe,M,x);return r([e,t,s,n]),{value:kt(s,w),gradFunc:N}}));return e(v,T,S)}}}),Ur=dt({resizeBilinear_:function(e,t,n=!1,r=!1){const s=ct(e,"images","resizeBilinear");m(3===s.rank||4===s.rank,(()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${s.rank}.`)),m(2===t.length,(()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`)),m(!1===r||!1===n,(()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false."));let a=s,i=!1;3===s.rank&&(i=!0,a=kt(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const o={images:a},u={alignCorners:n,halfPixelCenters:r,size:t},l=it.runKernel(ne,o,u);return i?kt(l,[l.shape[1],l.shape[2],l.shape[3]]):l}});function Kr(e,t){const n=e[0].slice();for(let r=1;r<e.length;r++)n[t]+=e[r][t];return n}function Gr(e){try{return e.map((e=>Fe(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function qr(e){return e.map((e=>xe(e)))}class Qr{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&&R().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 ve(e)}}if(R().get("IS_BROWSER")){R().setPlatform("browser",new Qr);try{Ln.registerManager(_n.URL_SCHEME,new wn)}catch(e){}try{Ln.registerManager(sn.URL_SCHEME,new on)}catch(e){}}let Jr;R().get("IS_NODE")&&!R().get("IS_BROWSER")&&R().setPlatform("node",new class{constructor(){this.util=n(345),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=R().global.fetch?R().global.fetch(e,t):(null==Jr&&(Jr=n(683)),Jr(e,t))}now(){const e=process.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)}}),at();const Yr={buffer:ir,cast:mt,clone:nr,print:function(e,t=!1){console.log(e.toString(t))}};var Xr,Zr;He=Yr,R().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"}(Xr||(Xr={})),function(e){var t;(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"}(Zr||(Zr={}));const es={};function ts(e){return es[e]}function ns(e,t,n,r,s){const a=t.inputParams[e];if(a&&void 0!==a.inputIndexStart){const e=a.inputIndexStart,i=0===a.inputIndexEnd?void 0:void 0===a.inputIndexEnd?e+1:a.inputIndexEnd,o=e<0?t.inputNames.length+e:e;if("tensor"===a.type)return rs(t.inputNames[o],n,r,s);if("tensors"===a.type){const a=t.inputs.slice(e,i),o=t.inputNames.slice(e,i).filter(((e,t)=>{var n;return"NoOp"!==(null===(n=a[t])||void 0===n?void 0:n.op)}));return o.map((e=>rs(e,n,r,s)))}const u=rs(t.inputNames[o],n,r,s),l=u.dataSync();return"number"===a.type?l[0]:I(u.shape,l)}const i=t.attrParams[e];return i&&i.value}function rs(e,t,n,r){const[s,a]=os(e,n);if(null!=r){const e=r.getHashTableHandleByName(s);if(null!=e)return e}const i=n.currentContextIds.find((e=>!!t[is(s,e)]));return void 0!==i?t[is(s,i)][a]:void 0}function ss(e,t,n){return t[is(e,n.currentContextId)]}function as(e,t){const[n,r,s]=os(e,t);return[is(n,t&&t.currentContextId),r,s]}function is(e,t){return t?`${e}-${t}`:e}function os(e,t){if(""===e)return["",0,void 0];const n=null!=t&&null!=t.parseNodeNameCache;if(n){const n=t.parseNodeNameCache.get(e);if(null!=n)return n}const r=e.split(":");let s;if(1===r.length)s=[e,0,void 0];else{const e=r[0],t=3===r.length?r[1]:void 0;s=[e,Number(r[r.length-1]),t]}return n&&t.parseNodeNameCache.set(e,s),s}function us(e,t,n){let r=ns("pad",e,t,n);if("explicit"===r){r=ns("explicitPaddings",e,t,n);const s=[[0,0],[0,0],[0,0],[0,0]];for(let e=0;e<4;e++)s[e][0]=r[2*e],s[e][1]=r[2*e+1];return s}return r}function ls(e){return e.kept?e:nr(e)}var ps=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}]}]}),cs=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:"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}]},{tfOpName:"IsFinite",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsInf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),hs=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"}]}]}),ds=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"}]}]}),fs=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:"RandomUniformInt",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number"},{tfName:"maxval",name:"maxval",type:"number"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,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"}]}]}),ms=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}]}]}),ys=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"}]}]}),gs=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"}]}]}),_s=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"}]}]}),bs=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"}]}]}),ws=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}]},{tfOpName:"BitwiseAnd",category:"logical",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}]}]}),vs=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"}]},{tfOpName:"MatrixBandPart",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"numLower",type:"tensor"},{start:1,name:"numUpper",type:"tensor"}]}]}),Ts=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"}]}]}),Ss=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"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{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"}]}]}),ks=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}]},{tfOpName:"TensorScatterUpdate",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"values",type:"tensor"}]}]}),Ns=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"}]}]}),Ms=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}]}]}),xs=Object.freeze({__proto__:null,json:[{tfOpName:"StaticRegexReplace",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"pattern",name:"pattern",type:"string"},{tfName:"rewrite",name:"rewrite",type:"string"},{tfName:"replace_global",name:"replaceGlobal",type:"bool"}]},{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"}]}]}),Fs=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:"EnsureShape",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 Is{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[].concat(...[ps,cs,hs,ds,fs,ms,ys,gs,_s,bs,ws,vs,Ts,Ss,ks,Ns,Ms,xs,Fs].map((e=>e.json)));this.opMappers=e.reduce(((e,t)=>(e[t.tfOpName]=t,e)),{})}transformGraph(e,t={}){const n=e.node,r=[],s=[],a=[],i=n.reduce(((e,t)=>(e[t.name]=this.mapNode(t),t.op.startsWith("Placeholder")?r.push(e[t.name]):"Const"===t.op?s.push(e[t.name]):null!=t.input&&0!==t.input.length||a.push(e[t.name]),e)),{});let o=[];const u=[];let l={},p={};null!=t&&(l=this.mapSignatureEntries(t.inputs),p=this.mapSignatureEntries(t.outputs));const c=Object.keys(i);c.forEach((e=>{const t=i[e];t.inputNames.forEach(((e,n)=>{const[r,,s]=as(e),a=i[r];if(null!=a.outputs){const e=a.outputs.indexOf(s);if(-1!==e){const s=`${r}:${e}`;t.inputNames[n]=s}}t.inputs.push(a),a.children.push(t)}))})),0===Object.keys(p).length?c.forEach((e=>{const t=i[e];0===t.children.length&&u.push(t)})):Object.keys(p).forEach((e=>{const[t]=as(e),n=i[t];null!=n&&(n.signatureKey=p[e],u.push(n))})),Object.keys(l).length>0?Object.keys(l).forEach((e=>{const[t]=as(e),n=i[t];n&&(n.signatureKey=l[e],o.push(n))})):o=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:i,inputs:o,outputs:u,weights:s,placeholders:r,signature:t,functions:h};return a.length>0&&(d.initNodes=a),d}mapSignatureEntries(e){return Object.keys(e||{}).reduce(((t,n)=>(t[e[n].name]=n,t)),{})}mapNode(e){const t=ts(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 s;switch(n.type){case"string":s=Es(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=Es(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":s=Hs(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=Hs(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":s=Ds(e.attr,n.tfName,n.defaultValue||0),void 0===s&&n.tfDeprecatedName&&(s=Ds(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":s=zs(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=zs(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":s=Os(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=Os(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":s=Vs(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=Vs(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":s=$s(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=$s(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":s=js(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=js(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":s=Ls(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=Ls(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":s=Ps(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=Ps(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":s=Rs(e.attr,n.tfName,n.defaultValue),void 0===s&&n.tfDeprecatedName&&(s=Rs(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:s,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 s=[],a=[];e.signature.inputArg.forEach((e=>{const[t]=as(e.name),n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Cs(e.type),type:"dtype"}},children:[]};n.signatureKey=e.name,s.push(n),r[t]=n})),Object.keys(r).forEach((e=>{const t=r[e];t.inputNames.forEach(((e,n)=>{const[s,,a]=as(e),i=r[s];if(null!=i.outputs){const e=i.outputs.indexOf(a);if(-1!==e){const r=`${s}:${e}`;t.inputNames[n]=r}}t.inputs.push(i),i.children.push(t)}))}));const i=e.ret;e.signature.outputArg.forEach((e=>{const[t,n]=as(i[e.name]),s=r[t];null!=s&&(s.defaultOutput=n,a.push(s))}));const o=this.mapArgsToSignature(e);return{nodes:r,inputs:s,outputs:a,weights:n,placeholders:[],signature:o}}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 As(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){const t=R().global;if(void 0!==t.atob)return t.atob(e);if("undefined"!=typeof Buffer)return new Buffer(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 Es(e,t,n,r=!1){const s=e[t];return null!=s?As(s.s,r):n}function Os(e,t,n){const r=e[t];return r?r.b:n}function Ds(e,t,n){const r=e[t]||{},s=null!=r.i?r.i:null!=r.f?r.f:n;return"number"==typeof s?s:parseInt(s,10)}function Cs(e){switch("string"==typeof e&&(e=Xr[e]),e){case Xr.DT_FLOAT:case Xr.DT_HALF:return"float32";case Xr.DT_INT32:case Xr.DT_INT64:case Xr.DT_INT8:case Xr.DT_UINT8:return"int32";case Xr.DT_BOOL:return"bool";case Xr.DT_DOUBLE:return"float32";case Xr.DT_STRING:return"string";case Xr.DT_COMPLEX64:case Xr.DT_COMPLEX128:return"complex64";default:return null}}function Rs(e,t,n){const r=e[t];return r&&r.func?r.func.name:n}function Ls(e,t,n){const r=e[t];return r&&r.type?Cs(r.type):n}function Ps(e,t,n){const r=e[t];return r&&r.list&&r.list.type?r.list.type.map((e=>Cs(e))):n}function Bs(e){if(!e.unknownRank)return null!=e.dim?e.dim.map((e=>"number"==typeof e.size?e.size:parseInt(e.size,10))):[]}function $s(e,t,n){const r=e[t];return r&&r.shape?Bs(r.shape):n}function zs(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 Hs(e,t,n,r=!1){const s=e[t];return s&&s.list&&s.list.s?s.list.s.map((e=>As(e,r))):n}function js(e,t,n){const r=e[t];return r&&r.list&&r.list.shape?r.list.shape.map((e=>Bs(e))):n}function Vs(e,t,n){const r=e[t];return r&&r.list&&r.list.b?r.list.b:n}class Ws{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 rs(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(null!=n.tensor)return rs(e,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return Ds(this.node.rawAttrs,e,t);if(null!=n.s)return Es(this.node.rawAttrs,e,t);if(null!=n.b)return Os(this.node.rawAttrs,e,t);if(null!=n.shape)return $s(this.node.rawAttrs,e,t);if(null!=n.type)return Ls(this.node.rawAttrs,e,t);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return zs(this.node.rawAttrs,e,t);if(null!=n.list.s)return Hs(this.node.rawAttrs,e,t);if(null!=n.list.shape)return js(this.node.rawAttrs,e,t);if(null!=n.list.b)return Vs(this.node.rawAttrs,e,t);if(null!=n.list.type)return Ps(this.node.rawAttrs,e,t)}return t}}const Us={conv2d:zr,depthwiseConv2d:Vr,matMul:Wr},Ks={resizeBilinear:Ur};var Gs=Object.freeze({__proto__:null,add:Un,addN:Gn,conv2d:or,depthwiseConv2d:lr,fused:Us,image:Ks,matMul:zn,mean:Tr,mul:Kn,pad:Nr,relu:Fr,relu6:Ir,scalar:gt,sigmoid:sr,stridedSlice:Dr,tensor1d:Tt});function qs(e,t,n=""){if("number"!=typeof e&&"number"!=typeof t){m(e.length===t.length,(()=>n+` Shapes ${e} and ${t} must match`));for(let r=0;r<e.length;r++){const s=e[r],a=t[r];m(s<0||a<0||s===a,(()=>n+` Shapes ${e} and ${t} must match`))}}}function Qs(e){return"number"!=typeof e&&!e.some((e=>e<0))}function Js(e,t,n){let r=Ys(e,n);const s=!Qs(r);if(s&&0===t.length)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${r}`);if(s&&t.forEach((e=>{r=Ys(e.shape,r)})),!Qs(r))throw new Error(`Non-fully-defined elementShape: ${r}`);return r}function Ys(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 s=e[r],a=t[r];if(s>=0&&a>=0&&s!==a)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[r]=s>=0?s:a}return n}class Xs{constructor(e,t,n,r,s,a,i){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=r,this.identicalElementShapes=s,this.dynamicSize=a,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=gt(0),Dt(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),qs(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,Dt(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 Ft([],[0].concat(this.elementShape));const n=this.readMany(e);return qs(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),Er(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 Ft([],[0].concat(this.elementShape));const t=[];for(let e=0;e<this.size();e++)t.push(e);const n=this.readMany(t);return qs(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),rr(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,Cr(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 s=0===n?0:t.size/n,a=[];Ot((()=>{t=kt(t,[1,n,s]);for(let n=0;n<e.length;++n){const i=[0,0===n?0:r[n-1],0],o=[1,e[n],s];a[n]=kt(ar(t,i,o),this.elementShape)}return a}));const i=[];for(let t=0;t<e.length;t++)i[t]=t;this.writeMany(i,a)}}class Zs{get id(){return this.idTensor.id}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}`);qs(t,e.shape,"TensorList shape mismatch: "),Dt(e)})),this.idTensor=gt(0),this.maxNumElements=r,Dt(this.idTensor)}copy(){return new Zs([...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.`);qs(e,this.elementShape,"TensorList shape mismatch: ");const r=Js(this.elementShape,this.tensors,e);return Ot((()=>{const e=this.tensors.map((e=>kt(e,r)));return Er(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=Js(this.elementShape,this.tensors,e),r=this.tensors.pop();return r.kept=!1,qs(r.shape,e,"TensorList shape mismatch: "),kt(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(qs(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Dt(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 Zs([],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.`);qs(this.tensors[e].shape,t,"TensorList shape mismatch: ");const r=Js(this.elementShape,this.tensors,t);return kt(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.`);qs(this.elementShape,t.shape,"TensorList shape mismatch: "),Dt(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}`);qs(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());const r=Js(this.elementShape,this.tensors,n);return 0===e.length?Ft([],[0].concat(r)):Ot((()=>{const t=e.map((e=>kt(this.tensors[e],r)));return Er(t,0)}))}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);qs(this.elementShape,t,"TensorList shape mismatch: ");const n=Js(this.elementShape,this.tensors,t);return 0===this.size()?Ft([],[0].concat(n)):Ot((()=>{const e=this.tensors.map((e=>kt(e,n)));return rr(e,0)}))}}function ea(e,t,n){const[r,s]=ns("fusedOps",e,t,n),a="biasadd"===r,i=!a,o="prelu"===s,u="fusedbatchnorm"===r,l=ns("numArgs",e,t,n);if(a){if(o&&2!==l)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&a&&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 p=ns("strides",e,t,n),c=us(e,t,n),h=ns("dataFormat",e,t,n).toUpperCase(),d=ns("dilations",e,t,n);let[f,m]=ns("args",e,t,n);return i&&(m=f,f=void 0),{stride:p,pad:c,dataFormat:h,dilations:d,biasArg:f,preluArg:m,activationFunc:s,leakyreluAlpha:ns("leakyreluAlpha",e,t,n)}}function ta(e,t,n){return{boxes:ns("boxes",e,t,n),scores:ns("scores",e,t,n),maxOutputSize:ns("maxOutputSize",e,t,n),iouThreshold:ns("iouThreshold",e,t,n),scoreThreshold:ns("scoreThreshold",e,t,n),softNmsSigma:ns("softNmsSigma",e,t,n)}}class na{get id(){return this.handle.id}constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=gt(0),this.tensorMap=new Map,Dt(this.handle)}clearAndClose(){this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return gt(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(),Ot((()=>{const e=Cr(t),r=n.length,s=e.length;m(r===s,(()=>`The number of elements doesn't match, keys has ${r} elements, the values has ${s} elements.`));for(let t=0;t<r;t++){const r=n[t],s=e[t];Dt(s),this.tensorMap.set(r,s)}return this.handle}))}async find(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return Ot((()=>{const e=[];for(let r=0;r<n.length;r++){const s=n[r],a=this.findWithDefault(s,t);e.push(a)}return Er(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 ra(e,t,n,r,s=Ot){const a=((e,t,n)=>{switch(e.category){case"arithmetic":return s((()=>((e,t,n,r=Gs)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[r.add(ns("a",e,t,n),ns("b",e,t,n))];case"AddN":return[r.addN(ns("tensors",e,t,n))];case"FloorMod":case"Mod":return[r.mod(ns("a",e,t,n),ns("b",e,t,n))];case"Mul":return[r.mul(ns("a",e,t,n),ns("b",e,t,n))];case"RealDiv":case"Div":return[r.div(ns("a",e,t,n),ns("b",e,t,n))];case"DivNoNan":return[r.divNoNan(ns("a",e,t,n),ns("b",e,t,n))];case"FloorDiv":return[r.floorDiv(ns("a",e,t,n),ns("b",e,t,n))];case"Sub":return[r.sub(ns("a",e,t,n),ns("b",e,t,n))];case"Minimum":return[r.minimum(ns("a",e,t,n),ns("b",e,t,n))];case"Maximum":return[r.maximum(ns("a",e,t,n),ns("b",e,t,n))];case"Pow":return[r.pow(ns("a",e,t,n),ns("b",e,t,n))];case"SquaredDifference":return[r.squaredDifference(ns("a",e,t,n),ns("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"basic_math":return s((()=>((e,t,n,r=Gs)=>{switch(e.op){case"Abs":case"ComplexAbs":return[r.abs(ns("x",e,t,n))];case"Acos":return[r.acos(ns("x",e,t,n))];case"Acosh":return[r.acosh(ns("x",e,t,n))];case"Asin":return[r.asin(ns("x",e,t,n))];case"Asinh":return[r.asinh(ns("x",e,t,n))];case"Atan":return[r.atan(ns("x",e,t,n))];case"Atan2":return[r.atan2(ns("x",e,t,n),ns("y",e,t,n))];case"Atanh":return[r.atanh(ns("x",e,t,n))];case"Ceil":return[r.ceil(ns("x",e,t,n))];case"Complex":return[r.complex(ns("real",e,t,n),ns("imag",e,t,n))];case"Cos":return[r.cos(ns("x",e,t,n))];case"Cosh":return[r.cosh(ns("x",e,t,n))];case"Elu":return[r.elu(ns("x",e,t,n))];case"Erf":return[r.erf(ns("x",e,t,n))];case"Exp":return[r.exp(ns("x",e,t,n))];case"Expm1":return[r.expm1(ns("x",e,t,n))];case"Floor":return[r.floor(ns("x",e,t,n))];case"Log":return[r.log(ns("x",e,t,n))];case"Log1p":return[r.log1p(ns("x",e,t,n))];case"Imag":return[r.imag(ns("x",e,t,n))];case"Neg":return[r.neg(ns("x",e,t,n))];case"Reciprocal":return[r.reciprocal(ns("x",e,t,n))];case"Real":return[r.real(ns("x",e,t,n))];case"Relu":return[r.relu(ns("x",e,t,n))];case"Round":return[r.round(ns("x",e,t,n))];case"Selu":return[r.selu(ns("x",e,t,n))];case"Sigmoid":return[r.sigmoid(ns("x",e,t,n))];case"Sin":return[r.sin(ns("x",e,t,n))];case"Sign":return[r.sign(ns("x",e,t,n))];case"Sinh":return[r.sinh(ns("x",e,t,n))];case"Softplus":return[r.softplus(ns("x",e,t,n))];case"Sqrt":return[r.sqrt(ns("x",e,t,n))];case"Square":return[r.square(ns("x",e,t,n))];case"Tanh":return[r.tanh(ns("x",e,t,n))];case"Tan":return[r.tan(ns("x",e,t,n))];case"ClipByValue":return[r.clipByValue(ns("x",e,t,n),ns("clipValueMin",e,t,n),ns("clipValueMax",e,t,n))];case"Relu6":return[r.relu6(ns("x",e,t,n))];case"Rsqrt":return[r.rsqrt(rs(e.inputNames[0],t,n))];case"LeakyRelu":return[r.leakyRelu(ns("x",e,t,n),ns("alpha",e,t,n))];case"Prelu":return[r.prelu(ns("x",e,t,n),ns("alpha",e,t,n))];case"IsNan":return[r.isNaN(rs(e.inputNames[0],t,n))];case"IsInf":return[r.isInf(rs(e.inputNames[0],t,n))];case"IsFinite":return[r.isFinite(rs(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=ns("thenBranch",e,t,n),s=ns("elseBranch",e,t,n),a=ns("cond",e,t,n),i=ns("args",e,t,n);return(await a.data())[0]?n.functionMap[r].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap):n.functionMap[s].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{const r=ns("body",e,t,n),s=ns("cond",e,t,n),a=ns("args",e,t,n),i=await n.functionMap[s].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap),o=a.map((e=>e.id));let u=await i[0].data();i.forEach((e=>{e.kept||-1!==o.indexOf(e.id)||e.dispose()}));let l=a;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!==o.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()}));const a=await n.functionMap[s].executeFunctionAsync(l,n.tensorArrayMap,n.tensorListMap);u=await a[0].data(),a.forEach((e=>{e.kept||-1!==o.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()}))}return l}case"LoopCond":return[ls(ns("pred",e,t,n))];case"Switch":{const r=ns("pred",e,t,n);let s=ns("data",e,t,n);return s.kept||(s=ls(s)),(await r.data())[0]?[void 0,s]:[s,void 0]}case"Merge":{const r=e.inputNames.find((e=>void 0!==rs(e,t,n)));return r?[ls(rs(r,t,n))]:void 0}case"Enter":{const r=ns("frameName",e,t,n),s=ns("tensor",e,t,n);return n.enterFrame(r),[ls(s)]}case"Exit":{const r=ns("tensor",e,t,n);return n.exitFrame(),[ls(r)]}case"NextIteration":{const r=ns("tensor",e,t,n);return n.nextIteration(),[ls(r)]}case"TensorArrayV3":{const r=ns("size",e,t,n),s=ns("dtype",e,t,n),a=ns("elementShape",e,t,n),i=ns("dynamicSize",e,t,n),o=ns("clearAfterRead",e,t,n),u=ns("identicalElementShapes",e,t,n),l=ns("name",e,t,n),p=new Xs(l,s,r,a,u,i,o);return n.addTensorArray(p),[p.idTensor,gt(1)]}case"TensorArrayWriteV3":{const r=ns("tensorArrayId",e,t,n),s=ns("index",e,t,n),a=ns("tensor",e,t,n),i=n.getTensorArray(r.id);return i.write(s,a),[i.idTensor]}case"TensorArrayReadV3":{const r=ns("tensorArrayId",e,t,n),s=ns("index",e,t,n);return[n.getTensorArray(r.id).read(s)]}case"TensorArrayGatherV3":{const r=ns("tensorArrayId",e,t,n),s=ns("indices",e,t,n),a=ns("dtype",e,t,n);return[n.getTensorArray(r.id).gather(s,a)]}case"TensorArrayScatterV3":{const r=ns("tensorArrayId",e,t,n),s=ns("indices",e,t,n),a=ns("tensor",e,t,n),i=n.getTensorArray(r.id);return i.scatter(s,a),[i.idTensor]}case"TensorArrayConcatV3":{const r=ns("tensorArrayId",e,t,n),s=n.getTensorArray(r.id),a=ns("dtype",e,t,n);return[s.concat(a)]}case"TensorArraySplitV3":{const r=ns("tensorArrayId",e,t,n),s=ns("tensor",e,t,n),a=ns("lengths",e,t,n),i=n.getTensorArray(r.id);return i.split(a,s),[i.idTensor]}case"TensorArraySizeV3":{const r=ns("tensorArrayId",e,t,n);return[gt(n.getTensorArray(r.id).size(),"int32")]}case"TensorArrayCloseV3":{const r=ns("tensorArrayId",e,t,n),s=n.getTensorArray(r.id);return s.clearAndClose(),[s.idTensor]}case"TensorListSetItem":{const r=ns("tensorListId",e,t,n),s=ns("index",e,t,n),a=ns("tensor",e,t,n),i=n.getTensorList(r.id);return i.setItem(s,a),[i.idTensor]}case"TensorListGetItem":{const r=ns("tensorListId",e,t,n),s=ns("index",e,t,n),a=ns("elementShape",e,t,n),i=ns("elementDType",e,t,n);return[n.getTensorList(r.id).getItem(s,a,i)]}case"TensorListScatterV2":case"TensorListScatter":{const r=ns("indices",e,t,n),s=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 s=Math.max(...t);if(null!=r&&-1!==r&&s>=r)throw new Error(`Max index must be < array size (${s} vs. ${r})`);const a=new Zs([],n,e.dtype,r),i=Cr(e,0);return t.forEach(((e,t)=>{a.setItem(e,i[t])})),a}(ns("tensor",e,t,n),r,ns("elementShape",e,t,n),ns("numElements",e,t,n));return n.addTensorList(s),[s.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const r=ns("elementShape",e,t,n),s=ns("elementDType",e,t,n);let a;a="TensorListReserve"===e.op?"numElements":"maxNumElements";const i=ns(a,e,t,n),o=function(e,t,n,r){return new Zs([],e,t,r)}(r,s,0,"TensorListReserve"===e.op?-1:i);return n.addTensorList(o),[o.idTensor]}case"TensorListGather":{const r=ns("tensorListId",e,t,n),s=ns("indices",e,t,n),a=ns("elementShape",e,t,n),i=ns("elementDType",e,t,n);return[n.getTensorList(r.id).gather(s,i,a)]}case"TensorListStack":{const r=ns("tensorListId",e,t,n),s=ns("elementShape",e,t,n),a=ns("elementDType",e,t,n),i=ns("numElements",e,t,n);return[n.getTensorList(r.id).stack(s,a,i)]}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}`);qs(e.shape.slice(1),t,"TensorList shape mismatch: ");const s=Cr(e);return new Zs(s,t,r)}(ns("tensor",e,t,n),ns("elementShape",e,t,n),ns("elementDType",e,t,n));return n.addTensorList(r),[r.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const r=ns("tensorListId",e,t,n),s=n.getTensorList(r.id),a=ns("dtype",e,t,n),i=ns("elementShape",e,t,n);return[s.concat(a,i)]}case"TensorListPushBack":{const r=ns("tensorListId",e,t,n),s=ns("tensor",e,t,n),a=n.getTensorList(r.id);return a.pushBack(s),[a.idTensor]}case"TensorListPopBack":{const r=ns("tensorListId",e,t,n),s=ns("elementShape",e,t,n),a=ns("elementDType",e,t,n);return[n.getTensorList(r.id).popBack(s,a)]}case"TensorListSplit":{const r=ns("tensor",e,t,n),s=ns("elementShape",e,t,n),a=function(e,t,n){let r=0;const s=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 a=Ys(e.shape.slice(1),n),i=0===r?0:e.size/r,o=Ot((()=>{const n=[];e=kt(e,[1,r,i]);for(let r=0;r<t.length;++r){const o=[0,0===r?0:s[r-1],0],u=[1,t[r],i];n[r]=kt(ar(e,o,u),a)}return e.dispose(),n})),u=new Zs([],n,e.dtype,t.length);for(let e=0;e<o.length;e++)u.setItem(e,o[e]);return u}(r,ns("lengths",e,t,n),s);return n.addTensorList(a),[a.idTensor]}case"TensorListLength":{const r=ns("tensorListId",e,t,n);return[gt(n.getTensorList(r.id).size(),"int32")]}case"TensorListResize":{const r=ns("tensorListId",e,t,n),s=ns("size",e,t,n),a=n.getTensorList(r.id).resize(s);return n.addTensorList(a),[a.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n);case"convolution":return s((()=>((e,t,n,r=Gs)=>{switch(e.op){case"Conv1D":{const s=ns("stride",e,t,n),a=ns("pad",e,t,n),i=ns("dataFormat",e,t,n).toUpperCase(),o=ns("dilation",e,t,n);return[r.conv1d(ns("x",e,t,n),ns("filter",e,t,n),s,a,i,o)]}case"Conv2D":{const s=ns("strides",e,t,n),a=us(e,t,n),i=ns("dataFormat",e,t,n).toUpperCase(),o=ns("dilations",e,t,n);return[r.conv2d(ns("x",e,t,n),ns("filter",e,t,n),[s[1],s[2]],a,i,[o[1],o[2]])]}case"_FusedConv2D":{const{stride:s,pad:a,dataFormat:i,dilations:o,biasArg:u,preluArg:l,activationFunc:p,leakyreluAlpha:c}=ea(e,t,n);return[r.fused.conv2d({x:ns("x",e,t,n),filter:ns("filter",e,t,n),strides:[s[1],s[2]],pad:a,dataFormat:i,dilations:[o[1],o[2]],bias:u,activation:p,preluActivationWeights:l,leakyreluAlpha:c})]}case"FusedDepthwiseConv2dNative":{const{stride:s,pad:a,dataFormat:i,dilations:o,biasArg:u,preluArg:l,activationFunc:p,leakyreluAlpha:c}=ea(e,t,n);return[r.fused.depthwiseConv2d({x:ns("x",e,t,n),filter:ns("filter",e,t,n),strides:[s[1],s[2]],pad:a,dataFormat:i,dilations:[o[1],o[2]],bias:u,activation:p,preluActivationWeights:l,leakyreluAlpha:c})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const s=ns("outputShape",e,t,n),a=ns("strides",e,t,n),i=us(e,t,n);return[r.conv2dTranspose(ns("x",e,t,n),ns("filter",e,t,n),s,[a[1],a[2]],i)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const s=ns("strides",e,t,n),a=us(e,t,n),i=ns("dilations",e,t,n),o=ns("dataFormat",e,t,n).toUpperCase();return[r.depthwiseConv2d(ns("input",e,t,n),ns("filter",e,t,n),[s[1],s[2]],a,o,[i[1],i[2]])]}case"Conv3D":{const s=ns("strides",e,t,n),a=ns("pad",e,t,n),i=ns("dataFormat",e,t,n).toUpperCase(),o=ns("dilations",e,t,n);return[r.conv3d(ns("x",e,t,n),ns("filter",e,t,n),[s[1],s[2],s[3]],a,i,[o[1],o[2],o[3]])]}case"AvgPool":{const s=ns("strides",e,t,n),a=ns("pad",e,t,n),i=ns("kernelSize",e,t,n);return[r.avgPool(ns("x",e,t,n),[i[1],i[2]],[s[1],s[2]],a)]}case"MaxPool":{const s=ns("strides",e,t,n),a=ns("pad",e,t,n),i=ns("kernelSize",e,t,n);return[r.maxPool(ns("x",e,t,n),[i[1],i[2]],[s[1],s[2]],a)]}case"MaxPoolWithArgmax":{const s=ns("strides",e,t,n),a=ns("pad",e,t,n),i=ns("kernelSize",e,t,n),o=ns("includeBatchInIndex",e,t,n),{result:u,indexes:l}=r.maxPoolWithArgmax(ns("x",e,t,n),[i[1],i[2]],[s[1],s[2]],a,o);return[u,l]}case"AvgPool3D":{const s=ns("strides",e,t,n),a=ns("pad",e,t,n),i=ns("kernelSize",e,t,n);return[r.avgPool3d(ns("x",e,t,n),[i[1],i[2],i[3]],[s[1],s[2],s[3]],a)]}case"MaxPool3D":{const s=ns("strides",e,t,n),a=ns("pad",e,t,n),i=ns("kernelSize",e,t,n);return[r.maxPool3d(ns("x",e,t,n),[i[1],i[2],i[3]],[s[1],s[2],s[3]],a)]}case"Dilation2D":{const s=ns("strides",e,t,n),a=ns("pad",e,t,n),i=ns("dilations",e,t,n),o=s[1],u=s[2],l=i[1],p=i[2];return[r.dilation2d(ns("x",e,t,n),ns("filter",e,t,n),[o,u],a,[l,p],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"creation":return s((()=>((e,t,n,r=Gs)=>{switch(e.op){case"Fill":{const s=ns("shape",e,t,n),a=ns("dtype",e,t,n),i=ns("value",e,t,n);return[r.fill(s,i,a)]}case"LinSpace":{const s=ns("start",e,t,n),a=ns("stop",e,t,n),i=ns("num",e,t,n);return[r.linspace(s,a,i)]}case"Multinomial":{const s=ns("logits",e,t,n),a=ns("numSamples",e,t,n),i=ns("seed",e,t,n);return[r.multinomial(s,a,i)]}case"OneHot":{const s=ns("indices",e,t,n),a=ns("depth",e,t,n),i=ns("onValue",e,t,n),o=ns("offValue",e,t,n),u=ns("dtype",e,t,n);return[r.oneHot(s,a,i,o,u)]}case"Ones":return[r.ones(ns("shape",e,t,n),ns("dtype",e,t,n))];case"OnesLike":return[r.onesLike(ns("x",e,t,n))];case"RandomStandardNormal":return[r.randomStandardNormal(ns("shape",e,t,n),ns("dtype",e,t,n),ns("seed",e,t,n))];case"RandomUniform":return[r.randomUniform(ns("shape",e,t,n),ns("minval",e,t,n),ns("maxval",e,t,n),ns("dtype",e,t,n))];case"RandomUniformInt":return[r.randomUniformInt(ns("shape",e,t,n),ns("minval",e,t,n),ns("maxval",e,t,n),ns("seed",e,t,n))];case"Range":{const s=ns("start",e,t,n),a=ns("stop",e,t,n),i=ns("step",e,t,n);return[r.range(s,a,i,ns("dtype",e,t,n))]}case"TruncatedNormal":{const s=ns("shape",e,t,n),a=ns("mean",e,t,n),i=ns("stdDev",e,t,n),o=ns("seed",e,t,n);return[r.truncatedNormal(s,a,i,ns("dtype",e,t,n),o)]}case"Zeros":return[r.zeros(ns("shape",e,t,n),ns("dtype",e,t,n))];case"ZerosLike":return[r.zerosLike(ns("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,s=Gs)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:r,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:u,softNmsSigma:l}=ta(e,t,n),p=await s.image.nonMaxSuppressionWithScoreAsync(r,a,i,o,u,l);return[p.selectedIndices,p.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:r,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:u}=ta(e,t,n),l=ns("padToMaxOutputSize",e,t,n),p=await s.image.nonMaxSuppressionPaddedAsync(r,a,i,o,u,l);return[p.selectedIndices,p.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:r,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:u}=ta(e,t,n);return[await s.image.nonMaxSuppressionAsync(r,a,i,o,u)]}case"Where":{const r=s.cast(ns("condition",e,t,n),"bool"),a=[await s.whereAsync(r)];return r.dispose(),a}case"ListDiff":return s.setdiff1dAsync(ns("x",e,t,n),ns("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n);case"evaluation":return s((()=>((e,t,n,r=Gs)=>{switch(e.op){case"LowerBound":{const s=ns("sortedSequence",e,t,n),a=ns("values",e,t,n);return[r.lowerBound(s,a)]}case"TopKV2":{const s=ns("x",e,t,n),a=ns("k",e,t,n),i=ns("sorted",e,t,n),o=r.topk(s,a,i);return[o.values,o.indices]}case"UpperBound":{const s=ns("sortedSequence",e,t,n),a=ns("values",e,t,n);return[r.upperBound(s,a)]}case"Unique":{const s=ns("x",e,t,n),a=r.unique(s);return[a.values,a.indices]}case"UniqueV2":{const s=ns("x",e,t,n),a=ns("axis",e,t,n),i=r.unique(s,a);return[i.values,i.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"image":return s((()=>((e,t,n,r=Gs)=>{switch(e.op){case"ResizeBilinear":{const s=ns("images",e,t,n),a=ns("size",e,t,n),i=ns("alignCorners",e,t,n),o=ns("halfPixelCenters",e,t,n);return[r.image.resizeBilinear(s,[a[0],a[1]],i,o)]}case"ResizeNearestNeighbor":{const s=ns("images",e,t,n),a=ns("size",e,t,n),i=ns("alignCorners",e,t,n),o=ns("halfPixelCenters",e,t,n);return[r.image.resizeNearestNeighbor(s,[a[0],a[1]],i,o)]}case"CropAndResize":{const s=ns("image",e,t,n),a=ns("boxes",e,t,n),i=ns("boxInd",e,t,n),o=ns("cropSize",e,t,n),u=ns("method",e,t,n),l=ns("extrapolationValue",e,t,n);return[r.image.cropAndResize(s,a,i,o,u,l)]}case"ImageProjectiveTransformV3":{const s=ns("images",e,t,n),a=ns("transforms",e,t,n),i=ns("outputShape",e,t,n),o=ns("fillValue",e,t,n),u=ns("interpolation",e,t,n),l=ns("fillMode",e,t,n);return[r.image.transform(s,a,u.toLowerCase(),l.toLowerCase(),o,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"graph":return s((()=>((e,t,n,r=Gs)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const s=ns("default",e,t,n);return[rs(e.name,t,n)||s];case"Placeholder":return[rs(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":case"Snapshot":return[ls(ns("x",e,t,n))];case"IdentityN":return ns("x",e,t,n).map((e=>ls(e)));case"Shape":return[r.tensor1d(ns("x",e,t,n).shape,"int32")];case"ShapeN":return ns("x",e,t,n).map((e=>r.tensor1d(e.shape)));case"Size":return[r.scalar(ns("x",e,t,n).size,"int32")];case"Rank":return[r.scalar(ns("x",e,t,n).rank,"int32")];case"NoOp":return[r.scalar(1)];case"Print":const a=ns("x",e,t,n),i=ns("data",e,t,n),o=ns("message",e,t,n),u=ns("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(o);for(let e=0;e<i.length;e++)console.log(Array.prototype.slice.call(i[e].dataSync()).slice(0,u));return[a];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"logical":return s((()=>((e,t,n,r=Gs)=>{switch(e.op){case"Equal":return[r.equal(ns("a",e,t,n),ns("b",e,t,n))];case"NotEqual":return[r.notEqual(ns("a",e,t,n),ns("b",e,t,n))];case"Greater":return[r.greater(ns("a",e,t,n),ns("b",e,t,n))];case"GreaterEqual":return[r.greaterEqual(ns("a",e,t,n),ns("b",e,t,n))];case"Less":return[r.less(ns("a",e,t,n),ns("b",e,t,n))];case"LessEqual":return[r.lessEqual(ns("a",e,t,n),ns("b",e,t,n))];case"LogicalAnd":return[r.logicalAnd(ns("a",e,t,n),ns("b",e,t,n))];case"LogicalNot":return[r.logicalNot(ns("a",e,t,n))];case"LogicalOr":return[r.logicalOr(ns("a",e,t,n),ns("b",e,t,n))];case"Select":case"SelectV2":return[r.where(ns("condition",e,t,n),ns("a",e,t,n),ns("b",e,t,n))];case"BitwiseAnd":return[r.bitwiseAnd(ns("a",e,t,n),ns("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"matrices":return s((()=>((e,t,n,r=Gs)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[r.matMul(ns("a",e,t,n),ns("b",e,t,n),ns("transposeA",e,t,n),ns("transposeB",e,t,n))];case"Einsum":return[r.einsum(ns("equation",e,t,n),...ns("tensors",e,t,n))];case"Transpose":return[r.transpose(ns("x",e,t,n),ns("perm",e,t,n))];case"_FusedMatMul":const[s,a]=ns("fusedOps",e,t,n),i="biasadd"===s,o="prelu"===a,u=ns("numArgs",e,t,n),l=ns("leakyreluAlpha",e,t,n);if(i){if(o&&2!==u)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&1!==u)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[p,c]=ns("args",e,t,n);return[r.fused.matMul({a:ns("a",e,t,n),b:ns("b",e,t,n),transposeA:ns("transposeA",e,t,n),transposeB:ns("transposeB",e,t,n),bias:p,activation:a,preluActivationWeights:c,leakyreluAlpha:l})];case"MatrixBandPart":return[r.linalg.bandPart(ns("a",e,t,n),ns("numLower",e,t,n),ns("numUpper",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"normalization":return s((()=>((e,t,n,r=Gs)=>{switch(e.op){case"EuclideanNorm":return[r.euclideanNorm(ns("x",e,t,n),ns("axis",e,t,n),ns("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[r.batchNorm(ns("x",e,t,n),ns("mean",e,t,n),ns("variance",e,t,n),ns("offset",e,t,n),ns("scale",e,t,n),ns("epsilon",e,t,n))];case"LRN":return[r.localResponseNormalization(ns("x",e,t,n),ns("radius",e,t,n),ns("bias",e,t,n),ns("alpha",e,t,n),ns("beta",e,t,n))];case"Softmax":return[r.softmax(ns("x",e,t,n))];case"LogSoftmax":return[r.logSoftmax(ns("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"ragged":return s((()=>((e,t,n,r=Gs)=>{switch(e.op){case"RaggedGather":{const{outputNestedSplits:s,outputDenseValues:a}=r.raggedGather(ns("paramsNestedSplits",e,t,n),ns("paramsDenseValues",e,t,n),ns("indices",e,t,n),ns("outputRaggedRank",e,t,n));return s.concat(a)}case"RaggedRange":{const{rtNestedSplits:s,rtDenseValues:a}=r.raggedRange(ns("starts",e,t,n),ns("limits",e,t,n),ns("splits",e,t,n));return[s,a]}case"RaggedTensorToTensor":return[r.raggedTensorToTensor(ns("shape",e,t,n),ns("values",e,t,n),ns("defaultValue",e,t,n),ns("rowPartitionTensors",e,t,n),ns("rowPartitionTypes",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"reduction":return s((()=>((e,t,n,r=Gs)=>{switch(e.op){case"Max":{const s=ns("axis",e,t,n),a=ns("keepDims",e,t,n);return[r.max(ns("x",e,t,n),s,a)]}case"Mean":{const s=ns("axis",e,t,n),a=ns("keepDims",e,t,n);return[r.mean(ns("x",e,t,n),s,a)]}case"Min":{const s=ns("axis",e,t,n),a=ns("keepDims",e,t,n);return[r.min(ns("x",e,t,n),s,a)]}case"Sum":{const s=ns("axis",e,t,n),a=ns("keepDims",e,t,n);return[r.sum(ns("x",e,t,n),s,a)]}case"All":{const s=ns("axis",e,t,n),a=ns("keepDims",e,t,n);return[r.all(ns("x",e,t,n),s,a)]}case"Any":{const s=ns("axis",e,t,n),a=ns("keepDims",e,t,n);return[r.any(ns("x",e,t,n),s,a)]}case"ArgMax":{const s=ns("axis",e,t,n);return[r.argMax(ns("x",e,t,n),s)]}case"ArgMin":{const s=ns("axis",e,t,n);return[r.argMin(ns("x",e,t,n),s)]}case"Prod":{const s=ns("axis",e,t,n),a=ns("keepDims",e,t,n);return[r.prod(ns("x",e,t,n),s,a)]}case"Cumprod":{const s=ns("axis",e,t,n),a=ns("exclusive",e,t,n),i=ns("reverse",e,t,n);return[r.cumprod(ns("x",e,t,n),s,a,i)]}case"Cumsum":{const s=ns("axis",e,t,n),a=ns("exclusive",e,t,n),i=ns("reverse",e,t,n);return[r.cumsum(ns("x",e,t,n),s,a,i)]}case"Bincount":const s=ns("x",e,t,n),a=ns("weights",e,t,n),i=ns("size",e,t,n);return[r.bincount(s,a,i)];case"DenseBincount":{const s=ns("x",e,t,n),a=ns("weights",e,t,n),i=ns("size",e,t,n),o=ns("binaryOutput",e,t,n);return[r.denseBincount(s,a,i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"slice_join":return s((()=>((e,t,n,r=Gs)=>{switch(e.op){case"ConcatV2":case"Concat":{const s=ns("n",e,t,n),a=ns("axis",e,t,n);let i=ns("tensors",e,t,n);return i=i.slice(0,s),[r.concat(i,a)]}case"Gather":{const s=ns("x",e,t,n),a=ns("indices",e,t,n);return[r.gather(s,r.cast(a,"int32"),0)]}case"GatherV2":{const s=ns("axis",e,t,n),a=ns("batchDims",e,t,n),i=ns("x",e,t,n),o=ns("indices",e,t,n);return[r.gather(i,r.cast(o,"int32"),s,a)]}case"Reverse":{const s=ns("dims",e,t,n),a=[];for(let e=0;e<s.length;e++)s[e]&&a.push(e);const i=ns("x",e,t,n);return[r.reverse(i,a)]}case"ReverseV2":{const s=ns("axis",e,t,n),a=ns("x",e,t,n);return[r.reverse(a,s)]}case"Slice":{const s=ns("begin",e,t,n),a=ns("size",e,t,n);return[r.slice(ns("x",e,t,n),s,a)]}case"StridedSlice":{const s=ns("begin",e,t,n),a=ns("end",e,t,n),i=ns("strides",e,t,n),o=ns("beginMask",e,t,n),u=ns("endMask",e,t,n),l=ns("ellipsisMask",e,t,n),p=ns("newAxisMask",e,t,n),c=ns("shrinkAxisMask",e,t,n),h=ns("x",e,t,n);return[r.stridedSlice(h,s,a,i,o,u,l,p,c)]}case"Pack":return Ot((()=>{const s=ns("axis",e,t,n),a=ns("tensors",e,t,n),i=a[0].shape,o=r.squeeze(a[0]).shape,u=a.map((e=>{const t=_(e.shape,i);if(!t&&!_(r.squeeze(e).shape,o))throw new Error("the input tensors shape does not match");return t?e:r.reshape(e,i)}));return[r.stack(u,s)]}));case"Unpack":{const s=ns("axis",e,t,n),a=ns("tensor",e,t,n);return r.unstack(a,s)}case"Tile":{const s=ns("reps",e,t,n);return[r.tile(ns("x",e,t,n),s)]}case"Split":case"SplitV":{const s=ns("axis",e,t,n),a=ns("numOrSizeSplits",e,t,n),i=ns("x",e,t,n);return r.split(i,a,s)}case"ScatterNd":{const s=ns("indices",e,t,n),a=ns("values",e,t,n),i=ns("shape",e,t,n);return[r.scatterND(s,a,i)]}case"GatherNd":{const s=ns("x",e,t,n),a=ns("indices",e,t,n);return[r.gatherND(s,a)]}case"SparseToDense":{const s=ns("sparseIndices",e,t,n),a=ns("outputShape",e,t,n),i=ns("sparseValues",e,t,n),o=ns("defaultValue",e,t,n);return[r.sparseToDense(s,i,a,i.dtype===o.dtype?o:r.cast(o,i.dtype))]}case"TensorScatterUpdate":{const s=ns("indices",e,t,n),a=ns("values",e,t,n),i=ns("tensor",e,t,n);return[r.tensorScatterUpdate(i,s,a)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"sparse":return s((()=>((e,t,n,r=Gs)=>{switch(e.op){case"SparseFillEmptyRows":{const{outputIndices:s,outputValues:a,emptyRowIndicator:i,reverseIndexMap:o}=r.sparse.sparseFillEmptyRows(ns("indices",e,t,n),ns("values",e,t,n),ns("denseShape",e,t,n),ns("defaultValue",e,t,n));return[s,a,i,o]}case"SparseReshape":{const{outputIndices:s,outputShape:a}=r.sparse.sparseReshape(ns("inputIndices",e,t,n),ns("inputShape",e,t,n),ns("newShape",e,t,n));return[s,a]}case"SparseSegmentMean":return[r.sparse.sparseSegmentMean(ns("data",e,t,n),ns("indices",e,t,n),ns("segmentIds",e,t,n))];case"SparseSegmentSum":return[r.sparse.sparseSegmentSum(ns("data",e,t,n),ns("indices",e,t,n),ns("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"spectral":return s((()=>((e,t,n,r=Gs)=>{switch(e.op){case"FFT":return[r.fft(ns("x",e,t,n))];case"IFFT":return[r.ifft(ns("x",e,t,n))];case"RFFT":return[r.rfft(ns("x",e,t,n))];case"IRFFT":return[r.irfft(ns("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"string":return s((()=>((e,t,n,r=Gs)=>{switch(e.op){case"StaticRegexReplace":return[r.string.staticRegexReplace(ns("input",e,t,n),ns("pattern",e,t,n),ns("rewrite",e,t,n),ns("replaceGlobal",e,t,n))];case"StringNGrams":{const{nGrams:s,nGramsSplits:a}=r.string.stringNGrams(ns("data",e,t,n),ns("dataSplits",e,t,n),ns("separator",e,t,n),ns("nGramWidths",e,t,n),ns("leftPad",e,t,n),ns("rightPad",e,t,n),ns("padWidth",e,t,n),ns("preserveShortSequences",e,t,n));return[s,a]}case"StringSplit":{const{indices:s,values:a,shape:i}=r.string.stringSplit(ns("input",e,t,n),ns("delimiter",e,t,n),ns("skipEmpty",e,t,n));return[s,a,i]}case"StringToHashBucketFast":return[r.string.stringToHashBucketFast(ns("input",e,t,n),ns("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"transformation":return s((()=>((e,t,n,r=Gs)=>{switch(e.op){case"Cast":return[r.cast(ns("x",e,t,n),ns("dtype",e,t,n))];case"ExpandDims":{const s=ns("axis",e,t,n);return[r.expandDims(ns("x",e,t,n),s)]}case"Squeeze":{const s=ns("axis",e,t,n);return[r.squeeze(ns("x",e,t,n),s)]}case"Reshape":return[r.reshape(ns("x",e,t,n),ns("shape",e,t,n))];case"EnsureShape":return[r.ensureShape(ns("x",e,t,n),ns("shape",e,t,n))];case"MirrorPad":return[r.mirrorPad(ns("x",e,t,n),ns("padding",e,t,n),ns("mode",e,t,n))];case"PadV2":case"Pad":return[r.pad(ns("x",e,t,n),ns("padding",e,t,n),ns("constantValue",e,t,n))];case"SpaceToBatchND":{const s=ns("blockShape",e,t,n),a=ns("paddings",e,t,n);return[r.spaceToBatchND(ns("x",e,t,n),s,a)]}case"BatchToSpaceND":{const s=ns("blockShape",e,t,n),a=ns("crops",e,t,n);return[r.batchToSpaceND(ns("x",e,t,n),s,a)]}case"DepthToSpace":{const s=ns("blockSize",e,t,n),a=ns("dataFormat",e,t,n).toUpperCase();return[r.depthToSpace(ns("x",e,t,n),s,a)]}case"BroadcastTo":return[r.broadcastTo(ns("x",e,t,n),ns("shape",e,t,n))];case"BroadcastArgs":return[r.broadcastArgs(ns("s0",e,t,n),ns("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 s=r.getHashTableHandleByName(e.name);if(null!=s)return[s];{const s=ns("keyDType",e,t,n),a=ns("valueDType",e,t,n),i=new na(s,a);return r.addHashTable(e.name,i),[i.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{const s=ns("tableHandle",e,t,n,r),a=ns("keys",e,t,n),i=ns("values",e,t,n),o=r.getHashTableById(s.id);return[await o.import(a,i)]}case"LookupTableFind":case"LookupTableFindV2":{const s=ns("tableHandle",e,t,n,r),a=ns("keys",e,t,n),i=ns("defaultValue",e,t,n),o=r.getHashTableById(s.id);return[await o.find(a,i)]}case"LookupTableSize":case"LookupTableSizeV2":{const s=ns("tableHandle",e,t,n,r);return[r.getHashTableById(s.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n,r);case"custom":const a=ts(e.op);if(a&&a.customExecutor)return a.customExecutor(new Ws(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 O(a)?a.then((e=>[].concat(e))):[].concat(a)}class sa{constructor(e={},t={},n={},r={},s){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=r,this.parseNodeNameCache=s,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 aa(e,t,n,r){const s=new Set,a=[];let i=null,o=null;const u=new Set,l=new Set(Object.keys(e).map((e=>os(e)[0])));r=r||[];const p=new Set(r.map((e=>os(e.name)[0]))),c=[...t];for(;c.length>0;){const e=c.pop();(pa(e)||ca(e)||ha(e))&&null==i&&(i=e,o=i.children.map((e=>e.name)).filter((e=>s.has(e)))),s.add(e.name),null==n[e.name]&&(l.has(e.name)||p.has(e.name)||(0!==e.inputs.length?e.inputs.forEach((e=>{u.has(e.name)||(u.add(e.name),c.push(e))})):a.push(e.name)))}return{inputs:e,outputs:t,usedNodes:s,missingInputs:a,dynamicNode:i,syncInputs:o}}class ia extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}}const oa=new Set(["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"]),ua=new Set(["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"]),la=new Set(["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"]);function pa(e){return oa.has(e.op)}function ca(e){return ua.has(e.op)}function ha(e){return la.has(e.op)}class da{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)),{})}constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this.parseNodeNameCache=new Map,this._weightMap={},this.SEPARATOR=",",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 da(e.functions[t],this)}))}getCompilationKey(e,t){const n=e.map((e=>e.name)).sort(),r=t.map((e=>e.name)).sort();return n.join(this.SEPARATOR)+"--"+r.join(this.SEPARATOR)}compile(e,t){const n=aa(e,t,this.weightMap,this._initNodes),{missingInputs:r,dynamicNode:s,syncInputs:a}=n;if(null!=s)throw new Error(`This execution contains the node '${s.name}', which has the dynamic op '${s.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${a}]`);if(r.length>0){const n=t.map((e=>e.name)),s=Object.keys(e);throw new Error(`Cannot compute the outputs [${n}] from the provided inputs [${s}]. Missing the following inputs: [${r}]`)}const i=function(e,t){const{usedNodes:n,inputs:r}=t,s=Object.keys(r).map((e=>os(e)[0])).map((t=>e.nodes[t])),a=e.initNodes||[],i=e=>n.has("string"==typeof e?e:e.name);function o(e){return[...new Map(e.map((e=>[e.name,e]))).values()]}const u=o([...s,...e.weights,...a]).filter(i),l=o([...u,...Object.values(e.nodes)]).filter(i),p=new Map(l.map((e=>[e.name,e]))),c={};for(const e of l){c[e.name]=c[e.name]||0;for(const t of e.children)i(t)||(c[t.name]=Number.POSITIVE_INFINITY),c[t.name]=(c[t.name]||0)+1}const h=Object.entries(c).filter((([,e])=>0===e)).map((([e])=>e)),d=[...h];for(;h.length>0;){const e=h.pop(),t=p.get(e);for(const e of t.children.filter(i))0==--c[e.name]&&(d.push(e.name),h.push(e.name))}const f=function(e,t){const n=new Map(e.map((e=>[e.name,e]))),r=t.map((e=>e.name)),s=new Set(r);for(;r.length>0;){const e=r.pop(),t=n.get(e);for(const e of t.children)n.has(e.name)&&!s.has(e.name)&&(s.add(e.name),r.push(e.name))}return e.filter((e=>s.has(e.name)))}(d.map((e=>p.get(e))),u);return function(e,t){const n=new Map(e.map(((e,t)=>[e.name,t]))),r=new Set(t.map((e=>e.name))),s=e=>r.has("string"==typeof e?e:e.name),a=new Set(e.map((e=>e.name))),i=e=>a.has("string"==typeof e?e:e.name);for(const t of e){for(const e of t.children.filter(i)){if(!n.has(e.name))throw new ia(`Child ${e.name} of node ${t.name} is unreachable.`);if(n.get(t.name)>n.get(e.name))throw new ia(`Node ${t.name} is scheduled to run after its child ${e.name}.`)}if(!s(t))for(const e of t.inputs){if(!n.has(e.name))throw new ia(`Input ${e.name} of node ${t.name} is unreachable.`);if(n.get(e.name)>n.get(t.name))throw new ia(`Node ${t.name} is scheduled to run before its input ${e.name}.`)}}}(f,u),f}(this.graph,n),o=function(e){const t=new Map(e.map(((e,t)=>[e.name,t]))),n=Number.MAX_SAFE_INTEGER,r=e.map(((e,t)=>pa(e)?n:t)),s=e=>{const n=r[t.get(e.name)];return null==n?-1:n},a=e.map(((e,t)=>e.children.map(s).reduce(((e,t)=>Math.max(e,t)),r[t]))),i=new Map;for(let t=0;t<e.length;++t){const r=a[t];if(r===n)continue;const s=e[t],o=e[r];i.has(o.name)||i.set(o.name,[]),i.get(o.name).push(s)}return i}(i);return{orderedNodes:i,nodeLiveUntilMap:o}}cloneAndKeepTensor(e){if(null==e)return null;const t=e.clone();return Dt(t),t}cloneTensorList(e){if(!e)return null;const t=e.map((e=>this.cloneAndKeepTensor(e)));return t}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[os(e)[0]])),s=t.map((e=>os(e)[0])),a=new Set(s);let i=s.map((e=>this.graph.nodes[e]));0===i.length&&(i=this._outputs);const o=this.getCompilationKey(r,i);let u=this.compiledMap.get(o);null==u&&(u=this.compile(e,i),this.compiledMap.set(o,u));try{this.keepIntermediateTensors=R().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const l={},p={};return Ot((()=>{const n=new sa(this.weightMap,l,p,this.functionExecutorMap,this.parseNodeNameCache),r=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(e).forEach((t=>{const[s,a]=os(t,n),i=[];i[a]=e[t],r[s]=i,this.keepIntermediateTensors&&(this.clonedTensorsMap[s]=this.cloneTensorList(i))}));const s=this.getFrozenTensorIds(r),{orderedNodes:i,nodeLiveUntilMap:o}=u;for(const e of i){if(r[e.name])continue;const t=ra(e,r,n,this._resourceManager);if(O(t))throw new Error(`The execution of the op '${e.op}' returned a promise. Please use model.executeAsync() instead.`);r[e.name]=t,this.keepIntermediateTensors&&(this.clonedTensorsMap[e.name]=this.cloneTensorList(t)),this.checkTensorForDisposalWithNodeLiveUntilInfo(e,r,n,s,a,o.get(e.name))}return null==this.parent&&n.dispose(s),t.map((e=>rs(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,s,a,i){if(!pa(t)&&!a.has(e)){for(const r of n[e])null!=r&&(i[r.id]=(i[r.id]||0)+t.children.length);for(const e of t.inputs){if(pa(e))continue;const t=ss(e.name,n,r);if(null!=t)for(const e of t){if(!e||e.kept||s.has(e.id))continue;const t=i[e.id];1===t?(e.dispose(),delete i[e.id]):null!=t&&i[e.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(e,t,n,r,s,a){function i(e){return pa(e)||s.has(e.name)}if(!pa(e)&&null!=a)for(const e of a){if(i(e))continue;const s=ss(e.name,t,n);for(const e of s)!e||e.kept||r.has(e.id)||e.dispose()}}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={},s={}){this.disposeIntermediateTensors(),n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepIntermediateTensors=R().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const a=new sa(this.weightMap,r,s,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));const i=await this.executeWithControlFlow(e,a,t,n),o=t.map((e=>rs(e,i,a))),u=o.map((e=>e.id)),l=Object.keys(e).map((t=>e[t].id)),p=new Set([...u,...l,...this.weightIds]);return Object.values(i).forEach((e=>{e.forEach((e=>{!e||e.isDisposed||p.has(e.id)||e.dispose()}))})),null==this.parent&&a.dispose(p),o}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 s=Object.keys(e),a=s.map((e=>this.graph.nodes[os(e)[0]])),i=n.map((e=>os(e)[0])),o=new Set(i);let u=i.map((e=>this.graph.nodes[e]));0===u.length&&(u=this._outputs);const{usedNodes:l,missingInputs:p,dynamicNode:c,syncInputs:h}=aa(e,u,this.weightMap,this._initNodes),d=[...a,...this.graph.weights,...this._initNodes||[]].map((e=>({node:e,contexts:t.currentContext}))),f=Object.assign({},this.weightMap);Object.keys(e).forEach((t=>{const[n,r]=os(t),s=[];s[r]=e[t],f[n]=s}));const m={},y=this.getFrozenTensorIds(f),g={};for(;d.length>0;){const e=this.processStack(a,d,t,f,g,y,o,m,l);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 _=u.filter((e=>!pa(e)&&!rs(e.name,f,t))).map((e=>e.name));if(_.length>0){let e="";throw null!=c&&(e=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${h}]`),new Error(`Cannot compute the outputs [${_}] from the provided inputs [${s}]. Consider providing the following inputs: [${p}]. ${e}`)}return f}processStack(e,t,n,r,s,a,i,o,u){const l=[];for(;t.length>0;){const e=t.pop();n.currentContext=e.contexts;let p="";if("Enter"===e.node.op&&ns("isConstant",e.node,r,n)&&([p]=as(e.node.name,n)),null==r[e.node.name]){const c=ra(e.node,r,n,this._resourceManager);p||([p]=as(e.node.name,n));const h=n.currentContext;O(c)?l.push(c.then((l=>(r[p]=l,this.keepIntermediateTensors&&(this.clonedTensorsMap[p]=this.cloneTensorList(l)),n.currentContext=h,this.checkTensorForDisposal(p,e.node,r,n,a,i,o),this.processChildNodes(e.node,t,n,r,s,u),l)))):(r[p]=c,this.keepIntermediateTensors&&(this.clonedTensorsMap[p]=this.cloneTensorList(c)),this.checkTensorForDisposal(p,e.node,r,n,a,i,o),this.processChildNodes(e.node,t,n,r,s,u))}else this.processChildNodes(e.node,t,n,r,s,u)}return l}processChildNodes(e,t,n,r,s,a){e.children.forEach((e=>{const[i]=as(e.name,n);!s[i]&&a.has(e.name)&&("Merge"===e.op?e.inputNames.some((e=>!!rs(e,r,n)))&&(s[i]=!0,t.push({contexts:n.currentContext,node:e})):e.inputNames.every((e=>!!rs(e,r,n)))&&(s[i]=!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]=os(t),s=this.graph.nodes[r];if(s.attrParams.shape&&s.attrParams.shape.value){const e=s.attrParams.shape.value;m(e.length===n.shape.length&&n.shape.every(((t,n)=>-1===e[n]||e[n]===t)),(()=>`The shape of dict['${s.name}'] provided in model.execute(dict) must be [${e}], but was [${n.shape}]`))}s.attrParams.dtype&&s.attrParams.dtype.value&&m(n.dtype===s.attrParams.dtype.value,(()=>`The dtype of dict['${s.name}'] provided in model.execute(dict) must be ${s.attrParams.dtype.value}, but was ${n.dtype}`))}))}mapInputs(e){var t,n;const r={};for(const s in e){const a=null===(n=null===(t=this._signature)||void 0===t?void 0:t.inputs)||void 0===n?void 0:n[s];null!=a?r[a.name]=e[s]:r[s]=e[s]}return r}checkInputs(e){const t=Object.keys(e).filter((e=>{const[t]=os(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]=os(e);if(!this.graph.nodes[t])throw new Error(`The output '${e}' is not found in the graph`)}))}}class fa{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 ma{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}constructor(e,t={},n=$n){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=n,null==t&&(this.loadOptions={}),this.resourceManager=new fa}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 O(e)?e.then((e=>null==e.getWeightStream?this.loadSync(e):this.loadStreaming(e))):this.loadSync(e)}loadSync(e){const t=this.io.decodeWeights(e.weightData,e.weightSpecs);return this.loadWithWeightMap(e,t)}async loadStreaming(e){if(null==e.getWeightStream)throw new Error("Model artifacts missing streamWeights function");const t=await jt(e.getWeightStream(),e.weightSpecs);return this.loadWithWeightMap(e,t)}loadWithWeightMap(e,t){this.artifacts=e;const n=this.artifacts.modelTopology;let r=this.artifacts.signature;if(null!=this.artifacts.userDefinedMetadata){const e=this.artifacts.userDefinedMetadata;null!=e.signature&&(r=e.signature),null!=e.structuredOutputKeys&&(this.structuredOutputKeys=e.structuredOutputKeys)}if(this.signature=r,this.version=`${n.versions.producer}.${n.versions.minConsumer}`,this.executor=new da(Is.Instance.transformGraph(n,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(t),this.executor.resourceManager=this.resourceManager,null!=e.modelInitializer&&null!=e.modelInitializer.node){const t=Is.Instance.transformGraph(e.modelInitializer);this.initializer=new da(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 je?[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 je||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 s,a,i;const o=null===(i=null===(a=null===(s=this.signature)||void 0===s?void 0:s.inputs)||void 0===a?void 0:a[n])||void 0===i?void 0:i.resourceId;return t[n]=null!=o?this.resourceIdToCapturedInput[o]: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 s=t[n[r]];this.resourceIdToCapturedInput[s.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&&et(this.resourceIdToCapturedInput).forEach((e=>e.dispose()))),this.resourceManager.dispose()}}async function ya(e,t={},n=$n){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 ma(e,t,n);return await r.load(),r}const ga=R();ga.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}})),ga.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",(async()=>{if(ga.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 _a,ba,wa,va={exports:{}},Ta=(_a||(_a=1,function(e,n){var r,s=(r=(r="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||t,function(e){function t(){return I.buffer!=D&&j(I.buffer),C}function n(){return I.buffer!=D&&j(I.buffer),R}function s(){return I.buffer!=D&&j(I.buffer),L}function a(){return I.buffer!=D&&j(I.buffer),P}function i(){return I.buffer!=D&&j(I.buffer),B}var o,u,l,p=void 0!==(e=e||{})?e:{};p.ready=new Promise((function(e,t){o=e,u=t})),"undefined"!=typeof process&&process.listeners&&(l={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var c,h,d,f=Object.assign({},p),m=(e,t)=>{throw t},y="object"==typeof window,g="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,b=p.ENVIRONMENT_IS_PTHREAD||!1,w="";function v(e){return p.locateFile?p.locateFile(e,w):w+e}if(_){var T=xr,S=xr;let e;w=g?S.dirname(w)+"/":"//",c=(e,t)=>(e=te(e)?new URL(e):S.normalize(e),T.readFileSync(e,t?void 0:"utf8")),d=e=>{var t=c(e,!0);return t.buffer||(t=new Uint8Array(t)),t},h=(e,t,n)=>{e=te(e)?new URL(e):S.normalize(e),T.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",(function(e){if(!(e instanceof se))throw e})),process.on("unhandledRejection",(function(e){throw e})),m=(e,t)=>{if(q())throw process.exitCode=e,t;var n;(n=t)instanceof se||F("exiting due to exception: "+n),process.exit(e)},p.inspect=function(){return"[Emscripten Module object]"};try{e=xr}catch(e){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),e}Te.Worker=e.Worker}else(y||g)&&(g?w=self.location.href:"undefined"!=typeof document&&document.currentScript&&(w=document.currentScript.src),void 0!==r&&r&&(w=r),w=0!==w.indexOf("blob:")?w.substr(0,w.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(c=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},g&&(d=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),h=(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)}));_&&"undefined"==typeof performance&&(Te.performance=xr.performance);var k=console.log.bind(console),N=console.warn.bind(console);_&&(k=e=>T.writeSync(1,e+"\n"),N=e=>T.writeSync(2,e+"\n"));var M,x=k,F=N;Object.assign(p,f),f=null,p.wasmBinary&&(M=p.wasmBinary);var I,A,E=!0;"object"!=typeof WebAssembly&&Z("no native wasm support detected");var O,D,C,R,L,P,B,$=!1,z="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function H(e,t,n){for(var r=(t>>>=0)+n,s=t;e[s]&&!(s>=r);)++s;if(s-t>16&&e.buffer&&z)return z.decode(e.buffer instanceof SharedArrayBuffer?e.slice(t,s):e.subarray(t,s));for(var a="";t<s;){var i=e[t++];if(128&i){var o=63&e[t++];if(192!=(224&i)){var u=63&e[t++];if((i=224==(240&i)?(15&i)<<12|o<<6|u:(7&i)<<18|o<<12|u<<6|63&e[t++])<65536)a+=String.fromCharCode(i);else{var l=i-65536;a+=String.fromCharCode(55296|l>>10,56320|1023&l)}}else a+=String.fromCharCode((31&i)<<6|o)}else a+=String.fromCharCode(i)}return a}function j(e){D=e,p.HEAP8=C=new Int8Array(e),p.HEAP16=new Int16Array(e),p.HEAP32=L=new Int32Array(e),p.HEAPU8=R=new Uint8Array(e),p.HEAPU16=new Uint16Array(e),p.HEAPU32=P=new Uint32Array(e),p.HEAPF32=new Float32Array(e),p.HEAPF64=B=new Float64Array(e)}b&&(D=p.buffer);var V,W=16777216;if(b)I=p.wasmMemory,D=p.buffer;else if(!((I=new WebAssembly.Memory({initial:W/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw F("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"),_&&F("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");I&&(D=I.buffer),W=D.byteLength,j(D);var U=[],K=[],G=[];function q(){return E}function Q(){b||pe(K)}var J,Y=0,X=null;function Z(e){F(e="Aborted("+e+")"),$=!0,O=1,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw u(t),t}function ee(e){return e.startsWith("data:application/octet-stream;base64,")}function te(e){return e.startsWith("file://")}function ne(e){try{if(e==J&&M)return new Uint8Array(M);if(d)return d(e);throw"both async and sync fetching of the wasm failed"}catch(e){Z(e)}}ee(J="tfjs-backend-wasm-threaded-simd.wasm")||(J=v(J));var re={};function se(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function ae(e){var t=le.pthreads[e];t||Z(undefined),le.returnWorkerToPool(t)}function ie(e){var t=le.getNewWorker();if(!t)return 6;le.runningWorkers.push(t),le.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=()=>{_&&t.ref(),t.postMessage(n,e.transferList),delete t.runPthread},t.loaded&&t.runPthread(),0}function oe(e){if(b)return be(1,1,e);O=e,q()||(le.terminateAllThreads(),$=!0),m(e,new se(e))}var ue=function(e,t){if(O=e,!t&&b)throw ce(e),"unwind";oe(e)},le={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init:function(){b?le.initWorker():le.initMainThread()},initMainThread:function(){for(var e=8;e--;)le.allocateUnusedWorker()},initWorker:function(){E=!1},setExitStatus:function(e){O=e},terminateAllThreads:function(){for(var e of Object.values(le.pthreads))le.returnWorkerToPool(e);for(var e of le.unusedWorkers)e.terminate();le.unusedWorkers=[]},returnWorkerToPool:function(e){var t=e.pthread_ptr;delete le.pthreads[t],le.unusedWorkers.push(e),le.runningWorkers.splice(le.runningWorkers.indexOf(e),1),e.pthread_ptr=0,_&&e.unref(),$e(t)},receiveObjectTransfer:function(e){},threadInitTLS:function(){le.tlsInitFunctions.forEach((e=>e()))},loadWasmModuleToWorker:function(e,t){e.onmessage=n=>{var r,s=n.data,a=s.cmd;if(e.pthread_ptr&&(le.currentProxiedOperationCallerThread=e.pthread_ptr),s.targetThread&&s.targetThread!=Oe()){var i=le.pthreads[s.targetThread];return i?i.postMessage(s,s.transferList):F('Internal error! Worker sent a message "'+a+'" to target pthread '+s.targetThread+", but that thread no longer exists!"),void(le.currentProxiedOperationCallerThread=void 0)}"processProxyingQueue"===a?ye(s.queue):"spawnThread"===a?ie(s):"cleanupThread"===a?ae(s.thread):"killThread"===a?function(e){var t=le.pthreads[e];delete le.pthreads[e],t.terminate(),$e(e),le.runningWorkers.splice(le.runningWorkers.indexOf(t),1),t.pthread_ptr=0}(s.thread):"cancelThread"===a?(r=s.thread,le.pthreads[r].postMessage({cmd:"cancel"})):"loaded"===a?(e.loaded=!0,_&&e.unref(),t&&t(e),e.runPthread&&e.runPthread()):"print"===a?x("Thread "+s.threadId+": "+s.text):"printErr"===a?F("Thread "+s.threadId+": "+s.text):"alert"===a?alert("Thread "+s.threadId+": "+s.text):"setimmediate"===s.target?e.postMessage(s):"callHandler"===a?p[s.handler](...s.args):a&&F("worker sent an unknown command "+a),le.currentProxiedOperationCallerThread=void 0},e.onerror=e=>{throw F("worker sent an error! "+e.filename+":"+e.lineno+": "+e.message),e},_&&(e.on("message",(function(t){e.onmessage({data:t})})),e.on("error",(function(t){e.onerror(t)})),e.on("detachedExit",(function(){})));var n=[];for(var s of[])p.hasOwnProperty(s)&&n.push(s);e.postMessage({cmd:"load",handlers:n,urlOrBlob:p.mainScriptUrlOrBlob||r,wasmMemory:I,wasmModule:A})},allocateUnusedWorker:function(){var e,t=v("tfjs-backend-wasm-threaded-simd.worker.js");e=new Worker(t),le.unusedWorkers.push(e)},getNewWorker:function(){return 0==le.unusedWorkers.length&&(le.allocateUnusedWorker(),le.loadWasmModuleToWorker(le.unusedWorkers[0])),le.unusedWorkers.pop()}};function pe(e){for(;e.length>0;)e.shift()(p)}function ce(e){if(b)return be(2,0,e);try{ue(e)}catch(e){!function(e){if(e instanceof se||"unwind"==e)return O;m(1,e)}(e)}}p.PThread=le,p.establishStackSpace=function(){var e=Oe(),t=s()[e+52>>>2],n=s()[e+56>>>2];He(t,t-n),Ve(t)};var he,de=[];function fe(e,t,n,r){return b?be(3,1,e,t,n,r):me(e,t,n,r)}function me(e,t,n,r){if("undefined"==typeof SharedArrayBuffer)return F("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var s=[];if(b&&0===s.length)return fe(e,t,n,r);var a={startRoutine:n,pthread_ptr:e,arg:r,transferList:s};return b?(a.cmd="spawnThread",postMessage(a,s),0):ie(a)}function ye(e){Atomics.store(s(),e>>2,1),Oe()&&Be(e),Atomics.compareExchange(s(),e>>2,1,0)}function ge(e){ge.shown||(ge.shown={}),ge.shown[e]||(ge.shown[e]=1,_&&(e="warning: "+e),F(e))}function _e(e){var t=je(),n=e();return Ve(t),n}function be(e,t){var n=arguments.length-2,r=arguments;return _e((()=>{for(var s=n,a=We(8*s),o=a>>3,u=0;u<n;u++){var l=r[2+u];i()[o+u>>>0]=l}return Ce(e,s,a,t)}))}p.invokeEntryPoint=function(e,t){var n,r,s=((r=de[n=e])||(n>=de.length&&(de.length=n+1),de[n]=r=V.get(n)),r)(t);q()?le.setExitStatus(s):ze(s)},p.executeNotifiedProxyingQueue=ye,he=_?()=>{var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:()=>performance.timeOrigin+performance.now();var we=[];function ve(e){try{return I.grow(e-D.byteLength+65535>>>16),j(I.buffer),1}catch(e){}}function Se(e){return b?be(4,1,e):52}function ke(e,t,n,r,s){return b?be(5,1,e,t,n,r,s):70}var Ne=[null,[],[]];function Me(e,t){var n=Ne[e];0===t||10===t?((1===e?x:F)(H(n,0)),n.length=0):n.push(t)}function xe(e,t,r,s){if(b)return be(6,1,e,t,r,s);for(var i=0,o=0;o<r;o++){var u=a()[t>>>2],l=a()[t+4>>>2];t+=8;for(var p=0;p<l;p++)Me(e,n()[u+p>>>0]);i+=l}return a()[s>>>2]=i,0}function Fe(e){return p["_"+e]}function Ie(e,r,s,a,i){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 s=(n>>>=0)+r-1,a=0;a<e.length;++a){var i=e.charCodeAt(a);if(i>=55296&&i<=57343&&(i=65536+((1023&i)<<10)|1023&e.charCodeAt(++a)),i<=127){if(n>=s)break;t[n++>>>0]=i}else if(i<=2047){if(n+1>=s)break;t[n++>>>0]=192|i>>6,t[n++>>>0]=128|63&i}else if(i<=65535){if(n+2>=s)break;t[n++>>>0]=224|i>>12,t[n++>>>0]=128|i>>6&63,t[n++>>>0]=128|63&i}else{if(n+3>=s)break;t[n++>>>0]=240|i>>18,t[n++>>>0]=128|i>>12&63,t[n++>>>0]=128|i>>6&63,t[n++>>>0]=128|63&i}}t[n>>>0]=0}(e,n(),t,r)}(e,t=We(r),r)}return t},array:e=>{var n=We(e.length);return function(e,n){t().set(e,n>>>0)}(e,n),n}};var u=Fe(e),l=[],p=0;if(a)for(var c=0;c<a.length;c++){var h=o[s[c]];h?(0===p&&(p=je()),l[c]=h(a[c])):l[c]=a[c]}var d=u.apply(null,l);return function(e){return 0!==p&&Ve(p),function(e){return"string"===r?(t=e,(t>>>=0)?H(n(),t,void 0):""):"boolean"===r?Boolean(e):e;var t}(e)}(d)}le.init();var Ae=[null,oe,ce,fe,Se,ke,xe],Ee={__emscripten_init_main_thread_js:function(e){De(e,!g,1,!y),le.threadInitTLS()},__emscripten_thread_cleanup:function(e){b?postMessage({cmd:"cleanupThread",thread:e}):ae(e)},__pthread_create_js:me,_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((()=>ye(r)));else if(b)postMessage({targetThread:e,cmd:"processProxyingQueue",queue:r});else{var s=le.pthreads[e];if(!s)return;s.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},_emscripten_set_offscreencanvas_size:function(e,t,n){return-1},abort:function(){Z("")},emscripten_check_blocking_allowed:function(){_||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 4294901760},emscripten_get_now:he,emscripten_memcpy_big:function(e,t,r){n().copyWithin(e>>>0,t>>>0,t+r>>>0)},emscripten_num_logical_cores:function(){return _?xr.cpus().length:navigator.hardwareConcurrency},emscripten_receive_on_main_thread_js:function(e,t,n){we.length=t;for(var r=n>>3,s=0;s<t;s++)we[s]=i()[r+s>>>0];return(e<0?re[-e-1]:Ae[e]).apply(null,we)},emscripten_resize_heap:function(e){var t=n().length;if((e>>>=0)<=t)return!1;var r=4294901760;if(e>r)return!1;let s=(e,t)=>e+(t-e%t)%t;for(var a=1;a<=4;a*=2){var i=t*(1+.2/a);if(i=Math.min(i,e+100663296),ve(Math.min(r,s(Math.max(e,i),65536))))return!0}return!1},emscripten_unwind_to_js_event_loop:function(){throw"unwind"},exit:ue,fd_close:Se,fd_seek:ke,fd_write:xe,memory:I||p.wasmMemory};!function(){var e={env:Ee,wasi_snapshot_preview1:Ee};function t(e,t){var n,r,s=e.exports;if(p.asm=s,n=p.asm._emscripten_tls_init,le.tlsInitFunctions.push(n),V=p.asm.__indirect_function_table,r=p.asm.__wasm_call_ctors,K.unshift(r),A=t,!b){var a=le.unusedWorkers.length;le.unusedWorkers.forEach((function(e){le.loadWasmModuleToWorker(e,(function(){--a||function(e){if(0==--Y&&X){var t=X;X=null,t()}}()}))}))}}function n(e){t(e.instance,e.module)}function r(t){return function(){if(!M&&(y||g)){if("function"==typeof fetch&&!te(J))return fetch(J,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+J+"'";return e.arrayBuffer()})).catch((function(){return ne(J)}));if(h)return new Promise((function(e,t){h(J,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return ne(J)}))}().then((function(t){return WebAssembly.instantiate(t,e)})).then((function(e){return e})).then(t,(function(e){F("failed to asynchronously prepare wasm: "+e),Z(e)}))}if(b||Y++,p.instantiateWasm)try{return p.instantiateWasm(e,t)}catch(e){F("Module.instantiateWasm callback failed with error: "+e),u(e)}(M||"function"!=typeof WebAssembly.instantiateStreaming||ee(J)||te(J)||_||"function"!=typeof fetch?r(n):fetch(J,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,e).then(n,(function(e){return F("wasm streaming compile failed: "+e),F("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(u)}(),p.___wasm_call_ctors=function(){return(p.___wasm_call_ctors=p.asm.__wasm_call_ctors).apply(null,arguments)},p._init=function(){return(p._init=p.asm.init).apply(null,arguments)},p._init_with_threads_count=function(){return(p._init_with_threads_count=p.asm.init_with_threads_count).apply(null,arguments)},p._get_threads_count=function(){return(p._get_threads_count=p.asm.get_threads_count).apply(null,arguments)},p._register_tensor=function(){return(p._register_tensor=p.asm.register_tensor).apply(null,arguments)},p._dispose_data=function(){return(p._dispose_data=p.asm.dispose_data).apply(null,arguments)},p._dispose=function(){return(p._dispose=p.asm.dispose).apply(null,arguments)},p._Add=function(){return(p._Add=p.asm.Add).apply(null,arguments)},p._AddN=function(){return(p._AddN=p.asm.AddN).apply(null,arguments)},p._Abs=function(){return(p._Abs=p.asm.Abs).apply(null,arguments)},p._DepthwiseConv2dNative=function(){return(p._DepthwiseConv2dNative=p.asm.DepthwiseConv2dNative).apply(null,arguments)},p._FusedConv2D=function(){return(p._FusedConv2D=p.asm.FusedConv2D).apply(null,arguments)},p._FusedDepthwiseConv2D=function(){return(p._FusedDepthwiseConv2D=p.asm.FusedDepthwiseConv2D).apply(null,arguments)},p._PadV2=function(){return(p._PadV2=p.asm.PadV2).apply(null,arguments)},p._Mean=function(){return(p._Mean=p.asm.Mean).apply(null,arguments)},p._Conv2D=function(){return(p._Conv2D=p.asm.Conv2D).apply(null,arguments)},p._Sigmoid=function(){return(p._Sigmoid=p.asm.Sigmoid).apply(null,arguments)},p._Multiply=function(){return(p._Multiply=p.asm.Multiply).apply(null,arguments)},p._ResizeBilinear=function(){return(p._ResizeBilinear=p.asm.ResizeBilinear).apply(null,arguments)},p._Transpose=function(){return(p._Transpose=p.asm.Transpose).apply(null,arguments)},p._CropAndResize=function(){return(p._CropAndResize=p.asm.CropAndResize).apply(null,arguments)},p._RealDiv=function(){return(p._RealDiv=p.asm.RealDiv).apply(null,arguments)},p._Reverse=function(){return(p._Reverse=p.asm.Reverse).apply(null,arguments)},p._Sub=function(){return(p._Sub=p.asm.Sub).apply(null,arguments)},p._StridedSlice=function(){return(p._StridedSlice=p.asm.StridedSlice).apply(null,arguments)},p._BatchMatMul=function(){return(p._BatchMatMul=p.asm.BatchMatMul).apply(null,arguments)},p._Relu=function(){return(p._Relu=p.asm.Relu).apply(null,arguments)},p._Relu6=function(){return(p._Relu6=p.asm.Relu6).apply(null,arguments)},p.__FusedMatMul=function(){return(p.__FusedMatMul=p.asm._FusedMatMul).apply(null,arguments)},p._malloc=function(){return(p._malloc=p.asm.malloc).apply(null,arguments)},p._free=function(){return(p._free=p.asm.free).apply(null,arguments)},p.__emscripten_tls_init=function(){return(p.__emscripten_tls_init=p.asm._emscripten_tls_init).apply(null,arguments)};var Oe=p._pthread_self=function(){return(Oe=p._pthread_self=p.asm.pthread_self).apply(null,arguments)};p.___errno_location=function(){return(p.___errno_location=p.asm.__errno_location).apply(null,arguments)};var De=p.__emscripten_thread_init=function(){return(De=p.__emscripten_thread_init=p.asm._emscripten_thread_init).apply(null,arguments)};p.__emscripten_thread_crashed=function(){return(p.__emscripten_thread_crashed=p.asm._emscripten_thread_crashed).apply(null,arguments)},p._emscripten_main_thread_process_queued_calls=function(){return(p._emscripten_main_thread_process_queued_calls=p.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},p._emscripten_main_browser_thread_id=function(){return(p._emscripten_main_browser_thread_id=p.asm.emscripten_main_browser_thread_id).apply(null,arguments)};var Ce=p._emscripten_run_in_main_runtime_thread_js=function(){return(Ce=p._emscripten_run_in_main_runtime_thread_js=p.asm.emscripten_run_in_main_runtime_thread_js).apply(null,arguments)};p._emscripten_dispatch_to_thread_=function(){return(p._emscripten_dispatch_to_thread_=p.asm.emscripten_dispatch_to_thread_).apply(null,arguments)};var Re,Le,Pe,Be=p.__emscripten_proxy_execute_task_queue=function(){return(Be=p.__emscripten_proxy_execute_task_queue=p.asm._emscripten_proxy_execute_task_queue).apply(null,arguments)},$e=p.__emscripten_thread_free_data=function(){return($e=p.__emscripten_thread_free_data=p.asm._emscripten_thread_free_data).apply(null,arguments)},ze=p.__emscripten_thread_exit=function(){return(ze=p.__emscripten_thread_exit=p.asm._emscripten_thread_exit).apply(null,arguments)},He=p._emscripten_stack_set_limits=function(){return(He=p._emscripten_stack_set_limits=p.asm.emscripten_stack_set_limits).apply(null,arguments)},je=p.stackSave=function(){return(je=p.stackSave=p.asm.stackSave).apply(null,arguments)},Ve=p.stackRestore=function(){return(Ve=p.stackRestore=p.asm.stackRestore).apply(null,arguments)},We=p.stackAlloc=function(){return(We=p.stackAlloc=p.asm.stackAlloc).apply(null,arguments)};function Ue(e){if(!(Y>0)){if(b)return o(p),Q(),void startWorker(p);pe(U),Y>0||Re||(Re=!0,p.calledRun=!0,$||(Q(),o(p),b||pe(G)))}}if(p.dynCall_iijjiiii=function(){return(p.dynCall_iijjiiii=p.asm.dynCall_iijjiiii).apply(null,arguments)},p.dynCall_jiji=function(){return(p.dynCall_jiji=p.asm.dynCall_jiji).apply(null,arguments)},p.keepRuntimeAlive=q,p.wasmMemory=I,p.cwrap=function(e,t,n,r){var s=(n=n||[]).every((e=>"number"===e||"boolean"===e));return"string"!==t&&s&&!r?Fe(e):function(){return Ie(e,t,n,arguments)}},p.ExitStatus=se,p.PThread=le,X=function e(){Re||Ue(),Re||(X=e)},Ue(),l&&(Le={uncaughtException:process.listeners("uncaughtException").filter((function(e){return!l.uncaughtException.indexOf(e)>-1})),unhandledRejection:process.listeners("unhandledRejection").filter((function(e){return!l.unhandledRejection.indexOf(e)>-1}))}),"undefined"!=typeof WasmBackendModule)Pe=WasmBackendModule;else{if(void 0===e)throw new Error("Could not find wasm module in post.js");Pe=e}if(Le){var Ke=Pe._dispose;Pe._dispose=function(){Ke(),Le.uncaughtException.forEach((function(e){process.removeListener("uncaughtException",e)})),Le.unhandledRejection.forEach((function(e){process.removeListener("unhandledRejection",e)}))}}return e.ready});e.exports=s}(va)),va.exports),Sa=Se(Ta),ka=s({__proto__:null,default:Sa},[Ta]),Na={},Ma=(ba||(ba=1,Na.wasmWorkerContents='"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}};'),Na),xa={exports:{}},Fa=(wa||(wa=1,function(e,n){var r,s=(r=(r="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||t,function(e){var t,n,s,a=void 0!==(e=e||{})?e:{};a.ready=new Promise((function(e,r){t=e,n=r})),"undefined"!=typeof process&&process.listeners&&(s={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var i,o,u,l=Object.assign({},a),p="object"==typeof window,c="function"==typeof importScripts,h="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,d="";if(h){var f=xr,m=xr;d=c?m.dirname(d)+"/":"//",i=(e,t)=>(e=P(e)?new URL(e):m.normalize(e),f.readFileSync(e,t?void 0:"utf8")),u=e=>{var t=i(e,!0);return t.buffer||(t=new Uint8Array(t)),t},o=(e,t,n)=>{e=P(e)?new URL(e):m.normalize(e),f.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),process.on("uncaughtException",(function(e){if(!(e instanceof $))throw e})),process.on("unhandledRejection",(function(e){throw e})),a.inspect=function(){return"[Emscripten Module object]"}}else(p||c)&&(c?d=self.location.href:"undefined"!=typeof document&&document.currentScript&&(d=document.currentScript.src),r&&(d=r),d=0!==d.indexOf("blob:")?d.substr(0,d.replace(/[?#].*/,"").lastIndexOf("/")+1):"",i=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},c&&(u=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),o=(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 y,g,_=console.log.bind(console),b=console.warn.bind(console);Object.assign(a,l),l=null,a.wasmBinary&&(y=a.wasmBinary),"object"!=typeof WebAssembly&&R("no native wasm support detected");var w,v,T,S,k=!1,N="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function M(e,t,n){for(var r=(t>>>=0)+n,s=t;e[s]&&!(s>=r);)++s;if(s-t>16&&e.buffer&&N)return N.decode(e.subarray(t,s));for(var a="";t<s;){var i=e[t++];if(128&i){var o=63&e[t++];if(192!=(224&i)){var u=63&e[t++];if((i=224==(240&i)?(15&i)<<12|o<<6|u:(7&i)<<18|o<<12|u<<6|63&e[t++])<65536)a+=String.fromCharCode(i);else{var l=i-65536;a+=String.fromCharCode(55296|l>>10,56320|1023&l)}}else a+=String.fromCharCode((31&i)<<6|o)}else a+=String.fromCharCode(i)}return a}function x(e){w=e,a.HEAP8=v=new Int8Array(e),a.HEAP16=new Int16Array(e),a.HEAP32=new Int32Array(e),a.HEAPU8=T=new Uint8Array(e),a.HEAPU16=new Uint16Array(e),a.HEAPU32=S=new Uint32Array(e),a.HEAPF32=new Float32Array(e),a.HEAPF64=new Float64Array(e)}var F,I,A=[],E=[],O=[],D=0,C=null;function R(e){b(e="Aborted("+e+")"),k=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw n(t),t}function L(e){return e.startsWith("data:application/octet-stream;base64,")}function P(e){return e.startsWith("file://")}function B(e){try{if(e==F&&y)return new Uint8Array(y);if(u)return u(e);throw"both async and sync fetching of the wasm failed"}catch(e){R(e)}}function $(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function z(e){for(;e.length>0;)e.shift()(a)}function H(e){try{return g.grow(e-w.byteLength+65535>>>16),x(g.buffer),1}catch(e){}}L(F="tfjs-backend-wasm.wasm")||(I=F,F=a.locateFile?a.locateFile(I,d):d+I);var j=[null,[],[]];function V(e,t){var n=j[e];0===t||10===t?((1===e?_:b)(M(n,0)),n.length=0):n.push(t)}function W(e){return a["_"+e]}function U(e,t,n,r,s){var a={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 s=(n>>>=0)+r-1,a=0;a<e.length;++a){var i=e.charCodeAt(a);if(i>=55296&&i<=57343&&(i=65536+((1023&i)<<10)|1023&e.charCodeAt(++a)),i<=127){if(n>=s)break;t[n++>>>0]=i}else if(i<=2047){if(n+1>=s)break;t[n++>>>0]=192|i>>6,t[n++>>>0]=128|63&i}else if(i<=65535){if(n+2>=s)break;t[n++>>>0]=224|i>>12,t[n++>>>0]=128|i>>6&63,t[n++>>>0]=128|63&i}else{if(n+3>=s)break;t[n++>>>0]=240|i>>18,t[n++>>>0]=128|i>>12&63,t[n++>>>0]=128|i>>6&63,t[n++>>>0]=128|63&i}}t[n>>>0]=0}(e,T,t,n)}(e,t=X(n),n)}return t},array:e=>{var t=X(e.length);return function(e,t){v.set(e,t>>>0)}(e,t),t}};var i=W(e),o=[],u=0;if(r)for(var l=0;l<r.length;l++){var p=a[n[l]];p?(0===u&&(u=J()),o[l]=p(r[l])):o[l]=r[l]}var c=i.apply(null,o);return function(e){return 0!==u&&Y(u),function(e){return"string"===t?(n=e,(n>>>=0)?M(T,n,void 0):""):"boolean"===t?Boolean(e):e;var n}(e)}(c)}var K={abort:function(){R("")},emscripten_get_heap_max:function(){return 4294901760},emscripten_memcpy_big:function(e,t,n){T.copyWithin(e>>>0,t>>>0,t+n>>>0)},emscripten_resize_heap:function(e){var t=T.length,n=4294901760;if((e>>>=0)>n)return!1;let r=(e,t)=>e+(t-e%t)%t;for(var s=1;s<=4;s*=2){var a=t*(1+.2/s);if(a=Math.min(a,e+100663296),H(Math.min(n,r(Math.max(e,a),65536))))return!0}return!1},fd_close:function(e){return 52},fd_seek:function(e,t,n,r,s){return 70},fd_write:function(e,t,n,r){for(var s=0,a=0;a<n;a++){var i=S[t>>>2],o=S[t+4>>>2];t+=8;for(var u=0;u<o;u++)V(e,T[i+u>>>0]);s+=o}return S[r>>>2]=s,0}};!function(){var e={env:K,wasi_snapshot_preview1:K};function t(e,t){var n,r=e.exports;a.asm=r,x((g=a.asm.memory).buffer),a.asm.__indirect_function_table,n=a.asm.__wasm_call_ctors,E.unshift(n),function(e){if(0==--D&&C){var t=C;C=null,t()}}()}function r(e){t(e.instance)}function s(t){return function(){if(!y&&(p||c)){if("function"==typeof fetch&&!P(F))return fetch(F,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+F+"'";return e.arrayBuffer()})).catch((function(){return B(F)}));if(o)return new Promise((function(e,t){o(F,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return B(F)}))}().then((function(t){return WebAssembly.instantiate(t,e)})).then((function(e){return e})).then(t,(function(e){b("failed to asynchronously prepare wasm: "+e),R(e)}))}if(D++,a.instantiateWasm)try{return a.instantiateWasm(e,t)}catch(e){b("Module.instantiateWasm callback failed with error: "+e),n(e)}(y||"function"!=typeof WebAssembly.instantiateStreaming||L(F)||P(F)||h||"function"!=typeof fetch?s(r):fetch(F,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,e).then(r,(function(e){return b("wasm streaming compile failed: "+e),b("falling back to ArrayBuffer instantiation"),s(r)}))}))).catch(n)}(),a.___wasm_call_ctors=function(){return(a.___wasm_call_ctors=a.asm.__wasm_call_ctors).apply(null,arguments)},a._init=function(){return(a._init=a.asm.init).apply(null,arguments)},a._init_with_threads_count=function(){return(a._init_with_threads_count=a.asm.init_with_threads_count).apply(null,arguments)},a._get_threads_count=function(){return(a._get_threads_count=a.asm.get_threads_count).apply(null,arguments)},a._register_tensor=function(){return(a._register_tensor=a.asm.register_tensor).apply(null,arguments)},a._dispose_data=function(){return(a._dispose_data=a.asm.dispose_data).apply(null,arguments)},a._dispose=function(){return(a._dispose=a.asm.dispose).apply(null,arguments)},a._Add=function(){return(a._Add=a.asm.Add).apply(null,arguments)},a._AddN=function(){return(a._AddN=a.asm.AddN).apply(null,arguments)},a._Abs=function(){return(a._Abs=a.asm.Abs).apply(null,arguments)},a._DepthwiseConv2dNative=function(){return(a._DepthwiseConv2dNative=a.asm.DepthwiseConv2dNative).apply(null,arguments)},a._FusedConv2D=function(){return(a._FusedConv2D=a.asm.FusedConv2D).apply(null,arguments)},a._FusedDepthwiseConv2D=function(){return(a._FusedDepthwiseConv2D=a.asm.FusedDepthwiseConv2D).apply(null,arguments)},a._PadV2=function(){return(a._PadV2=a.asm.PadV2).apply(null,arguments)},a._Mean=function(){return(a._Mean=a.asm.Mean).apply(null,arguments)},a._Conv2D=function(){return(a._Conv2D=a.asm.Conv2D).apply(null,arguments)},a._Sigmoid=function(){return(a._Sigmoid=a.asm.Sigmoid).apply(null,arguments)},a._Multiply=function(){return(a._Multiply=a.asm.Multiply).apply(null,arguments)},a._ResizeBilinear=function(){return(a._ResizeBilinear=a.asm.ResizeBilinear).apply(null,arguments)},a._Transpose=function(){return(a._Transpose=a.asm.Transpose).apply(null,arguments)},a._CropAndResize=function(){return(a._CropAndResize=a.asm.CropAndResize).apply(null,arguments)},a._RealDiv=function(){return(a._RealDiv=a.asm.RealDiv).apply(null,arguments)},a._Reverse=function(){return(a._Reverse=a.asm.Reverse).apply(null,arguments)},a._Sub=function(){return(a._Sub=a.asm.Sub).apply(null,arguments)},a._StridedSlice=function(){return(a._StridedSlice=a.asm.StridedSlice).apply(null,arguments)},a._BatchMatMul=function(){return(a._BatchMatMul=a.asm.BatchMatMul).apply(null,arguments)},a._Relu=function(){return(a._Relu=a.asm.Relu).apply(null,arguments)},a._Relu6=function(){return(a._Relu6=a.asm.Relu6).apply(null,arguments)},a.__FusedMatMul=function(){return(a.__FusedMatMul=a.asm._FusedMatMul).apply(null,arguments)},a._malloc=function(){return(a._malloc=a.asm.malloc).apply(null,arguments)},a._free=function(){return(a._free=a.asm.free).apply(null,arguments)},a.___errno_location=function(){return(a.___errno_location=a.asm.__errno_location).apply(null,arguments)};var G,q,Q,J=a.stackSave=function(){return(J=a.stackSave=a.asm.stackSave).apply(null,arguments)},Y=a.stackRestore=function(){return(Y=a.stackRestore=a.asm.stackRestore).apply(null,arguments)},X=a.stackAlloc=function(){return(X=a.stackAlloc=a.asm.stackAlloc).apply(null,arguments)};function Z(e){D>0||(z(A),D>0||G||(G=!0,a.calledRun=!0,k||(z(E),t(a),z(O))))}if(a.dynCall_iijjiiii=function(){return(a.dynCall_iijjiiii=a.asm.dynCall_iijjiiii).apply(null,arguments)},a.dynCall_jiji=function(){return(a.dynCall_jiji=a.asm.dynCall_jiji).apply(null,arguments)},a.cwrap=function(e,t,n,r){var s=(n=n||[]).every((e=>"number"===e||"boolean"===e));return"string"!==t&&s&&!r?W(e):function(){return U(e,t,n,arguments)}},C=function e(){G||Z(),G||(C=e)},Z(),s&&(q={uncaughtException:process.listeners("uncaughtException").filter((function(e){return!s.uncaughtException.indexOf(e)>-1})),unhandledRejection:process.listeners("unhandledRejection").filter((function(e){return!s.unhandledRejection.indexOf(e)>-1}))}),void 0!==e)Q=e;else{if("undefined"==typeof WasmBackendModuleThreadedSimd)throw new Error("Could not find wasm module in post.js");Q=WasmBackendModuleThreadedSimd}if(q){var ee=Q._dispose;Q._dispose=function(){ee(),q.uncaughtException.forEach((function(e){process.removeListener("uncaughtException",e)})),q.unhandledRejection.forEach((function(e){process.removeListener("unhandledRejection",e)}))}}return e.ready});e.exports=s}(xa)),xa.exports),Ia=Se(Fa);const Aa=Sa||ka,Ea=Ia||s({__proto__:null,default:Ia},[Fa]);class Oa extends d{constructor(e){super(),this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(za),this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new h(this,Et())}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=Me();return e(),{kernelMs:Me()-t}}move(e,t,n,r,s){const a=this.dataIdNextNumber++;if("string"===r){const i=t;return void this.dataIdMap.set(e,{id:a,stringBytes:i,shape:n,dtype:r,memoryOffset:null,refCount:s})}const i=g(n),o=i*S(r),u=this.wasm._malloc(o)>>>0;this.dataIdMap.set(e,{id:a,memoryOffset:u,shape:n,dtype:r,refCount:s}),this.wasm.tfjs.registerTensor(a,i,u),null!=t&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,o),u)}async read(e){return this.readSync(e)}readSync(e,t,n){const{memoryOffset:r,dtype:s,shape:a,stringBytes:i}=this.dataIdMap.get(e);if("string"===s)return null!=t&&0!==t||!(null==n||n>=i.length)?i.slice(t,n):i;t=t||0,n=n||g(a);const o=S(s);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*o,r+n*o).buffer,s)}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,r){let s;if(null==n)s=this.write(null!=r?r:null,e,t);else{const r=this.dataIdNextNumber++;s={id:r},this.dataIdMap.set(s,{id:r,memoryOffset:n,shape:e,dtype:t,refCount:1});const a=g(e);this.wasm.tfjs.registerTensor(r,a,n)}return{dataId:s,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:n}){const r=this.wasm.HEAPU8.buffer,{memoryOffset:s}=this.dataIdMap.get(n),a=g(e);switch(t){case"float32":return new Float32Array(r,s,a);case"int32":return new Int32Array(r,s,a);case"bool":return new Uint8Array(r,s,a);default:throw new Error(`Unknown dtype ${t}`)}}}function Da(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!=La&&null!=La[r]?La[r]:n+r}const Ca=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"];let Ra=null,La={},Pa=!1,Ba=!1;function $a(e,t=!1){if(Pa)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)Ra=e;else{La=e;const t=Ca.filter((e=>null==La[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.`)}Ba=t}let za=-1;var Ha,ja;function Va(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:n}=e,{a:s,b:a}=n,i=t.dataIdMap.get(s.dataId).id,o=t.dataIdMap.get(a.dataId).id,u=s.dtype,l=Hn(s.shape,a.shape),p=t.makeOutput(l,u);if(0===g(l))return p;const c=new Uint8Array(new Int32Array(s.shape).buffer),h=new Uint8Array(new Int32Array(a.shape).buffer),d=t.dataIdMap.get(p.dataId).id;return r(i,c,s.shape.length,o,h,a.shape.length,Ha[s.dtype],d),p}}}!function(e,t,n=1){it.registerBackend(e,t,n)}("wasm",(async()=>{const{wasm:e}=await async function(){const[e,t]=await Promise.all([R().getAsync("WASM_HAS_SIMD_SUPPORT"),R().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise(((n,r)=>{const s={locateFile:(n,r)=>{if(n.endsWith(".worker.js")){const e=Ma.wasmWorkerContents.replace(/\n/g,"\\n"),t=new Blob([e],{type:"application/javascript"});return URL.createObjectURL(t)}return n.endsWith(".wasm")?Da(e,t,null!=Ra?Ra:r):r+n}};var a;Ba&&(s.instantiateWasm=(a=Da(e,t,null!=Ra?Ra:""),(e,t)=>(function(e,t){return R().platform.fetch(e,{credentials:"same-origin"})}(a).then((n=>{n.ok||e.env.a(`failed to load wasm binary file at '${a}'`),n.arrayBuffer().then((n=>{WebAssembly.instantiate(n,e).then((e=>{t(e.instance,e.module)}))}))})),{})));let i,o=!1;if(s.onAbort=()=>{o||Pa||(Pa=!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){s.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+Aa.toString()],{type:"text/javascript"});const e=La["tfjs-backend-wasm-threaded-simd.wasm"];e instanceof ArrayBuffer&&(s.wasmBinary=e),i=Aa(s)}else{if(e){const e=La["tfjs-backend-wasm-simd.wasm"];e instanceof ArrayBuffer&&(s.wasmBinary=e)}else{const e=La["tfjs-backend-wasm.wasm"];e instanceof ArrayBuffer&&(s.wasmBinary=e)}i=Ea(s)}i.then((e=>{o=!0,Pa=!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,[])},e.wasmBinary&&(e.wasmBinary=null),n({wasm:e})})).catch(r)}))}();return new Oa(e)}),2),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"}(Ha||(Ha={})),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"}(ja||(ja={}));const Wa=Va(z);let Ua;const Ka={kernelName:H,backendName:"wasm",setupFunc:function(e){Ua=e.wasm.cwrap(H,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===g(r.shape))return r;const s=t.map((e=>n.dataIdMap.get(e.dataId).id)),a=new Uint8Array(new Int32Array(s).buffer),i=n.dataIdMap.get(r.dataId).id;return Ua(a,s.length,Ha[r.dtype],i),r}};function Ga(e){const{inputs:t,attrs:n}=e,{x:r}=t,{shape:s}=n,a=g(r.shape),i=function(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 s=e.slice();return s[r]=t/n,s}(s,a);return m(a===g(i),(()=>`new shape: ${i}, 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:i,dtype:r.dtype}}const qa={kernelName:te,backendName:"wasm",kernelFunc:Ga};let Qa;const Ja={kernelName:j,backendName:"wasm",setupFunc:function(e){Qa=e.wasm.cwrap(j,null,["number","array","number","number","array","number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:i,transposeB:o}=r;if("float32"!==s.dtype||"float32"!==a.dtype)throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");const u=s.shape.length,l=a.shape.length,p=i?s.shape[u-2]:s.shape[u-1],c=o?a.shape[l-1]:a.shape[l-2],h=i?s.shape[u-1]:s.shape[u-2],d=o?a.shape[l-2]:a.shape[l-1],f=s.shape.slice(0,-2),y=a.shape.slice(0,-2),_=g(f),b=g(y),w=Hn(s.shape.slice(0,-2),a.shape.slice(0,-2)).concat([h,d]);m(p===c,(()=>`Error in matMul: inner shapes (${p}) and (${c}) of Tensors with shapes ${s.shape} and ${a.shape} and transposeA=${i} and transposeB=${o} must match.`));const v=o?[b,d,c]:[b,c,d],T=Ga({inputs:{x:s},backend:n,attrs:{shape:i?[_,p,h]:[_,h,p]}}),S=Ga({inputs:{x:a},backend:n,attrs:{shape:v}}),k=n.dataIdMap.get(T.dataId).id,N=n.dataIdMap.get(S.dataId).id,M=i?T.shape[2]:T.shape[1],x=o?S.shape[1]:S.shape[2],F=Math.max(_,b),I=n.makeOutput([F,M,x],T.dtype),A=n.dataIdMap.get(I.dataId).id,E=new Uint8Array(new Int32Array(T.shape).buffer),O=new Uint8Array(new Int32Array(S.shape).buffer);return Qa(k,E,T.shape.length,N,O,S.shape.length,i,o,A),n.disposeData(T.dataId),n.disposeData(S.dataId),I.shape=w,I}};function Ya(e){const{inputs:{x:t},attrs:{dtype:n},backend:r}=e,s=r.makeOutput(t.shape,n),a=r.typedArrayFromHeap(t);return r.typedArrayFromHeap(s).set(a),s}const Xa={kernelName:V,backendName:"wasm",kernelFunc:Ya};function Za(e,t,n,r,s){const a=jn(r,t,n),i=g(n),o=x(r);if(a){const n=Vn(t,o);return"string"===s?e.slice(n,n+i):e.subarray(n,n+i)}const u=ir(r,s,"string"===s?Gr(e):e),l=ir(n,s);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"===s?qr(l.values):l.values}function ei(e){const{inputs:{x:t},backend:n}=e;if("string"===t.dtype)return Ft(n.readSync(t.dataId),t.shape,t.dtype);const r=n.makeOutput(t.shape,t.dtype),s=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(r).set(s),r}const ti={kernelName:J,backendName:"wasm",kernelFunc:ei},ni={kernelName:W,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n}=e,r=v(e.attrs.axis,t[0].shape)[0];!function(e,t){const n=e[0].length;e.forEach(((e,t)=>{m(e.length===n,(()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`))})),m(t>=0&&t<n,(()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`));const r=e[0];e.forEach(((e,s)=>{for(let a=0;a<n;a++)m(a===t||e[a]===r[a],(()=>`Error in concat${n}D: Shape of tensors[${s}] (${e}) does not match the shape of the rest (${r}) along the non-concatenated axis ${s}.`))}))}(t.map((e=>e.shape)),r);let s=Kr(t.map((e=>e.shape)),r);const a=t.filter((e=>g(e.shape)>0));if(1===a.length)return ei({inputs:{x:a[0]},backend:n});const i=n.makeOutput(s,t[0].dtype);if(0===g(s))return i;if("string"===a[0].dtype){const e=a.map((e=>{const t=g(e.shape.slice(r));return Ga({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),o=e.map((e=>({vals:n.readSync(e.dataId),shape:e.shape})));s=Kr(e.map((e=>e.shape)),1);const u=1===e[0].shape[0],l=function(e,t,n,r){const s=T(n,g(t));if(r&&"string"!==n){let t=0;e.forEach((e=>{const n=g(e.shape);s.set(e.vals,t),t+=n}))}else{let r=0;e.forEach((e=>{const a="string"===n?Gr(e.vals):e.vals;let i=0;for(let n=0;n<e.shape[0];++n){const o=n*t[1]+r;for(let t=0;t<e.shape[1];++t)s[o+t]=a[i++]}r+=e.shape[1]}))}return s}(o,s,t[0].dtype,u),p=Kr(a.map((e=>e.shape)),r);return i.shape=p,n.dataIdMap.get(i.dataId).stringBytes=qr(l),e.forEach((e=>n.disposeData(e.dataId))),i}const o=g(a[0].shape.slice(0,r));let u=0;const l=a.map((e=>{const t=g(e.shape.slice(r));return u+=t,t})),p=a.map((e=>n.typedArrayFromHeap(e))),c=n.typedArrayFromHeap(i);for(let e=0;e<o;e++){let t=e*u;for(let n=0;n<p.length;n++){const r=l[n],s=e*r,a=p[n].subarray(s,s+r);c.set(a,t),t+=r}}return i}};let ri;const si={kernelName:U,backendName:"wasm",setupFunc:function(e){ri=e.wasm.cwrap(U,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:s,filter:a}=t,i=r.dataIdMap.get(s.dataId).id,o=r.dataIdMap.get(a.dataId).id,{strides:u,dilations:l,pad:p,dimRoundingMode:c,dataFormat:h}=n,d=function(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}(h),f=qn(s.shape,a.shape,u,l,p,c,!1,d),m=f.filterHeight,y=f.filterWidth,g=f.padInfo.top,_=f.padInfo.right,b=f.padInfo.bottom,w=f.padInfo.left,v=f.dilationHeight,T=f.dilationWidth,S=f.strideHeight,k=f.strideWidth,N=f.inChannels,M=f.outChannels,x="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 F=r.makeOutput(f.outShape,"float32"),I=r.dataIdMap.get(F.dataId).id;return ri(i,s.shape[0],s.shape[1],s.shape[2],o,m,y,g,_,b,w,x,v,T,S,k,N,M,I),F}};var ai;let ii;!function(e){e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest"}(ai||(ai={}));const oi={kernelName:K,backendName:"wasm",setupFunc:function(e){ii=e.wasm.cwrap(K,null,["number","number","number","number","array","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{method:s,extrapolationValue:a,cropSize:i}=r,{image:o,boxes:u,boxInd:l}=n,p=u.shape[0],[c,h]=i,d=[p,c,h,o.shape[3]];let f,m=t.dataIdMap.get(o.dataId);"float32"!==o.dtype&&(f=Ya({backend:t,inputs:{x:o},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(f.dataId));const y=m.id,g=t.dataIdMap.get(u.dataId).id,_=t.dataIdMap.get(l.dataId).id,b=t.makeOutput(d,"float32"),w=t.dataIdMap.get(b.dataId).id,v=new Uint8Array(new Int32Array(o.shape).buffer);return ii(y,g,_,p,v,c,h,ai[s],a,w),null!=f&&t.disposeData(f.dataId),b}};let ui;const li={kernelName:G,backendName:"wasm",setupFunc:function(e){ui=e.wasm.cwrap(G,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:s,filter:a}=t,i=r.dataIdMap.get(s.dataId).id,o=r.dataIdMap.get(a.dataId).id,{strides:u,dilations:l,pad:p,dimRoundingMode:c}=n,h=null==l?[1,1]:l,d=qn(s.shape,a.shape,u,h,p,c,!0),f=d.filterHeight,m=d.filterWidth,y=d.padInfo.top,g=d.padInfo.right,_=d.padInfo.bottom,b=d.padInfo.left,w=d.dilationHeight,v=d.dilationWidth,T=d.strideHeight,S=d.strideWidth,k=d.inChannels,N=d.outChannels,M="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 x=r.makeOutput(d.outShape,"float32"),F=r.dataIdMap.get(x.dataId).id;return ui(i,s.shape[0],s.shape[1],s.shape[2],o,f,m,y,g,_,b,M,w,v,T,S,k,N,F),x}},pi={kernelName:Q,backendName:"wasm",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{input:s}=t,{dim:a}=n,i=s.shape.length,o=s.shape.slice();let u=a;return a<0&&(m(-(i+1)<=a,(()=>`Axis must be in the interval [${-(i+1)}, ${i}]`)),u=i+a+1),o.splice(u,0,1),Ga({inputs:{x:s},backend:r,attrs:{shape:o}})}};let ci;const hi={kernelName:ce,backendName:"wasm",setupFunc:function(e){ci=e.wasm.cwrap(ce,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:s,filter:a,bias:i,preluActivationWeights:o}=t,{strides:u,pad:l,dilations:p,dataFormat:c,dimRoundingMode:h,activation:d,leakyreluAlpha:f}=n,m=qn(s.shape,a.shape,u,p,l,h),y=ja[d];if(null==y)throw new Error(`${d} activation not yet supported for FusedConv2D in the wasm backend.`);const g=r.dataIdMap.get(s.dataId).id,_=r.dataIdMap.get(a.dataId).id,b=m.outChannels;let w=0;if(null!=i){const e=r.dataIdMap.get(i.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]!==b)throw new Error(`FusedConv2D bias shape (${e.shape}) does not match the number of output channels (${b})`);w=e.id}const v=m.filterHeight,T=m.filterWidth,S=m.padInfo.top,k=m.padInfo.right,N=m.padInfo.bottom,M=m.padInfo.left,x=m.dilationHeight,F=m.dilationWidth,I=m.strideHeight,A=m.strideWidth,E=m.inChannels,O="SAME"===m.padInfo.type?1:0,D=m.batchSize,C=m.inHeight,R=m.inWidth;if("NHWC"!==c)throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${c}'. Please use 'NHWC'.`);const L=r.makeOutput(m.outShape,"float32"),P=r.dataIdMap.get(L.dataId).id,B=null==o?0:r.dataIdMap.get(o.dataId).id;return ci(g,D,C,R,_,v,T,w,S,k,N,M,O,x,F,I,A,E,b,y,B,f||0,P),L}};let di;const fi={kernelName:he,backendName:"wasm",setupFunc:function(e){di=e.wasm.cwrap(he,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:s,filter:a,bias:i,preluActivationWeights:o}=t,{strides:u,pad:l,dilations:p,dataFormat:c,dimRoundingMode:h,activation:d,leakyreluAlpha:f}=n,m=qn(s.shape,a.shape,u,p,l,h,!0),y=ja[d];if(null==y)throw new Error(`${d} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);const g=r.dataIdMap.get(s.dataId).id,_=r.dataIdMap.get(a.dataId).id,b=m.outChannels;let w=0;if(null!=i){const e=r.dataIdMap.get(i.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]!==b)throw new Error(`FusedDepthwiseConv2D bias shape (${e.shape}) does not match the number of output channels (${b})`);w=e.id}const v=m.filterHeight,T=m.filterWidth,S=m.padInfo.top,k=m.padInfo.right,N=m.padInfo.bottom,M=m.padInfo.left,x=m.dilationHeight,F=m.dilationWidth,I=m.strideHeight,A=m.strideWidth,E=m.inChannels,O="SAME"===m.padInfo.type?1:0,D=m.batchSize,C=m.inHeight,R=m.inWidth;if("NHWC"!==c)throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${c}'. Please use 'NHWC'.`);const L=r.makeOutput(m.outShape,"float32"),P=r.dataIdMap.get(L.dataId).id,B=null==o?0:r.dataIdMap.get(o.dataId).id;return di(g,D,C,R,_,v,T,w,S,k,N,M,O,x,F,I,A,E,b,y,B,f||0,P),L}};let mi;function yi(e){const{inputs:t,backend:n,attrs:r}=e,[s,a]=function(e,t){const n=[],r=[];for(let s=0;s<e.length;++s)1!==e[s]&&n.push(e[s]),1!==e[t[s]]&&r.push(t[s]);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 i=!0;for(let e=0;e<a.length;e++)a[e]!==e&&(i=!1);const o=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:s,dtype:t.x.dtype};if(i){const e=ei({inputs:t,backend:n});return e.shape=o,e}const l=n.makeOutput(o,u.dtype),p=n.dataIdMap.get(u.dataId).id,c=n.dataIdMap.get(l.dataId).id,h=new Uint8Array(new Int32Array(a).buffer),d=new Uint8Array(new Int32Array(u.shape).buffer);return mi(p,d,u.shape.length,Ha[u.dtype],c,h,a.length),l}const gi={kernelName:oe,backendName:"wasm",kernelFunc:yi,setupFunc:function(e){mi=e.wasm.cwrap(oe,null,["number","array","number","number","number","array","number"])}};let _i;const bi={kernelName:Y,backendName:"wasm",setupFunc:function(e){_i=e.wasm.cwrap(Y,null,["number, number, number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{axis:s,keepDims:a}=r,{x:i}=n,o=t.dataIdMap.get(i.dataId).id;let u=o,l=i;const{transposed:p,axes:c,originalAxes:h,inputWasTransposed:d}=function(e,t,n){const r=e.shape,s=e.shape.length,a=v(t,r);let i=a;const o=function(e,t){if(cr(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}(i,s);let u=null,l=!1;if(null!=o){const t=new Array(s);for(let e=0;e<t.length;e++)t[e]=r[o[e]];i=dr(i.length,s),u=yi({inputs:{x:e},attrs:{perm:o},backend:n});const a=n.dataIdMap.get(e.dataId).id;n.dataIdMap.get(u.dataId).id!==a&&(l=!0)}return{transposed:u,originalAxes:a,axes:i,inputWasTransposed:l}}(i,s,t);let f=c;if(d){const e=t.dataIdMap.get(p.dataId).id;e!==o&&(l=p,u=e,f=dr(f.length,l.shape.length))}!function(e,t,n){m(cr(t,n),(()=>`mean supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`))}(0,f,l.shape.length);const[y,_]=function(e,t){const n=[],r=e.length;for(let s=0;s<r;s++)-1===t.indexOf(s)&&n.push(e[s]);return[n,t.map((t=>e[t]))]}(l.shape,f),b=g(_);let w=l;"float32"!==l.dtype&&(w=Ya({backend:t,inputs:{x:l},attrs:{dtype:"float32"}}),u=t.dataIdMap.get(w.dataId).id);const T=t.makeOutput(y,"float32");if(0!==g(l.shape)){const e=t.dataIdMap.get(T.dataId).id;_i(u,b,e)}if(d&&t.disposeData(p.dataId),a){const e=hr(T.shape,h);T.shape=e}return"float32"!==l.dtype&&t.disposeData(w.dataId),T}},wi=Va(X);let vi;const Ti={kernelName:Z,backendName:"wasm",kernelFunc:function(e){const{inputs:{x:t},backend:n,attrs:{paddings:r,constantValue:s}}=e,a=r.map(((e,n)=>e[0]+t.shape[n]+e[1]));if(0===g(t.shape))return function(e){const{attrs:{shape:t,value:n},backend:r}=e;let{attrs:{dtype:s}}=e;s=s||N(n);const a=r.makeOutput(t,s);return r.typedArrayFromHeap(a).fill(n),a}({backend:n,attrs:{shape:a,value:s,dtype:t.dtype}});const i=n.dataIdMap.get(t.dataId).id,o=n.makeOutput(a,t.dtype),u=n.dataIdMap.get(o.dataId).id,l=new Uint8Array(new Int32Array(t.shape).buffer),p=r.map((e=>e[0])),c=r.map((e=>e[1])),h=new Uint8Array(new Int32Array(p).buffer),d=new Uint8Array(new Int32Array(c).buffer);return vi(i,l,t.shape.length,Ha[t.dtype],h,d,s,u),o},setupFunc:function(e){vi=e.wasm.cwrap(Z,null,["number","array","number","number","array","array","number","number"])}},Si=Va(q);function ki(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:t,inputs:{x:r}}=e,s=t.dataIdMap.get(r.dataId).id,a=t.makeOutput(r.shape,r.dtype),i=t.dataIdMap.get(a.dataId).id;return 0===g(a.shape)||n(s,Ha[r.dtype],i),a}}}const Ni=ki(ee),Mi=ki(re);let xi;const Fi={kernelName:ne,backendName:"wasm",setupFunc:function(e){xi=e.wasm.cwrap(ne,null,["number","number","number","number","number","number","number","number","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{images:s}=n,{alignCorners:a,halfPixelCenters:i,size:o}=r,[u,l]=o,[p,c,h,d]=s.shape,f=[p,u,l,d];let m,y=t.dataIdMap.get(s.dataId);"float32"!==y.dtype&&(m=Ya({backend:t,inputs:{x:s},attrs:{dtype:"float32"}}),y=t.dataIdMap.get(m.dataId));const _=y.id,b=t.makeOutput(f,"float32");if(0===g(s.shape))return b;const w=t.dataIdMap.get(b.dataId).id;return xi(_,p,c,h,d,u,l,a?1:0,i?1:0,w),null!=m&&t.disposeData(m.dataId),b}};let Ii;const Ai={kernelName:se,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dims:a}=r,i=v(a,s.shape);if(0===s.shape.length)return ei({inputs:{x:s},backend:n});const o=n.makeOutput(s.shape,s.dtype),u=n.dataIdMap.get(s.dataId).id,l=n.dataIdMap.get(o.dataId).id,p=new Uint8Array(new Int32Array(i).buffer),c=new Uint8Array(new Int32Array(s.shape).buffer);Ii(u,p,i.length,c,s.shape.length,l);const h=Ga({inputs:{x:o},attrs:{shape:s.shape},backend:n});return n.disposeData(o.dataId),h},setupFunc:function(e){Ii=e.wasm.cwrap(se,null,["number","array","number","array","number","number"])}};let Ei;const Oi={kernelName:"Sigmoid",backendName:"wasm",setupFunc:function(e){Ei=e.wasm.cwrap(ae,null,["number","number"])},kernelFunc:function(e){const{backend:t,inputs:{x:n}}=e,r=t.dataIdMap.get(n.dataId).id,s=t.makeOutput(n.shape,n.dtype),a=t.dataIdMap.get(s.dataId).id;return 0===g(s.shape)||Ei(r,a),s}};function Di(e){const{inputs:{x:t},attrs:{begin:n,size:r},backend:s}=e,[a,i]=function(e,t,n){let r;const s=e.shape.length;let a;return r="number"==typeof t?[t,...new Array(s-1).fill(0)]:t.length<s?t.concat(new Array(s-t.length).fill(0)):t.slice(),r.forEach((e=>{m(-1!==e,(()=>"slice() does not support negative begin indexing."))})),a=null==n?new Array(s).fill(-1):"number"==typeof n?[n,...new Array(s-1).fill(-1)]:n.length<s?n.concat(new Array(s-n.length).fill(-1)):n,a=a.map(((t,n)=>t>=0?t:(m(-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,a]}(t,n,r),o=jn(t.shape,a,i),u=s.readSync(t.dataId),l=s.makeOutput(i,t.dtype),p=x(t.shape),c=s.dataIdMap.get(l.dataId);if(o){const e=Vn(a,p);return"string"===t.dtype?c.stringBytes=u.slice(e,e+g(i)):s.typedArrayFromHeap(l).set(u.subarray(e,e+g(i))),l}if("string"===t.dtype){const e=Za(u,a,i,t.shape,t.dtype);return c.stringBytes=e,l}const h=s.typedArrayFromHeap(l),d=t.shape.length;if(2===d)!function(e,t,n,r,s){let a=0;const i=r[0],o=r[1],u=i+s[0];for(let r=i;r<u;r++){const i=r*t+o;n.set(e.subarray(i,i+s[1]),a),a+=s[1]}}(u,p[0],h,a,i);else if(3===d)!function(e,t,n,r,s,a){let i=0;const o=s[0],u=s[1],l=s[2],p=o+a[0],c=u+a[1];for(let s=o;s<p;s++)for(let o=u;o<c;o++){const u=s*t+o*n+l;r.set(e.subarray(u,u+a[2]),i),i+=a[2]}}(u,p[0],p[1],h,a,i);else if(4===d)!function(e,t,n,r,s,a,i){let o=0;const u=a[0],l=a[1],p=a[2],c=u+i[0],h=l+i[1],d=p+i[2],f=a[3];for(let a=u;a<c;a++)for(let u=l;u<h;u++)for(let l=p;l<d;l++){const p=a*t+u*n+l*r+f;s.set(e.subarray(p,p+i[3]),o),o+=i[3]}}(u,p[0],p[1],p[2],h,a,i);else{const e=Za(u,a,i,t.shape,t.dtype);h.set(e)}return l}let Ci;const Ri={kernelName:ie,backendName:"wasm",setupFunc:function(e){Ci=e.wasm.cwrap(ie,null,["number","array","number","array","array","array","array","array","number","number"])},kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{x:s}=n,{begin:a,end:i,strides:o,beginMask:u,endMask:l,ellipsisMask:p,newAxisMask:c,shrinkAxisMask:h}=r,{finalShapeSparse:d,finalShape:f,isIdentity:y,sliceDim0:g,isSimpleSlice:_,begin:b,end:w,strides:v}=function(e,t,n,r,s,a,i,o,u){let l;if(null==r?(l=new Array(t.length),l.fill(1)):l=r,null!=i&&0!=(i&i-1))throw new Error("Multiple ellipses in slice is not allowed.");let p=!1;const c={dims:l.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:l.slice(),beginMask:s,endMask:a,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:u};for(let e=0;e<c.dims;e++)p&&0!=(1<<e&o)&&c.numAddAxisAfterEllipsis++,1<<e&i&&(p=!0);p||(c.ellipsisMask|=1<<c.dims,c.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 s=Math.min(t.dims-(e.dims-r)+1+e.numAddAxisAfterEllipsis,t.dims);for(;n<s;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++}}(c,h);let d=!0,f=!0,m=!0;const y=[],g=[];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){y.push(n?1:-1);continue}const s=[h.beginMask&1<<t,h.endMask&1<<t],a=[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 i=!!(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]=Wn(h.begin[t],0,h.strides[t],r,s,a),h.end[t]=Wn(h.end[t],1,h.strides[t],r,s,a);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]&&i,f=f&&(0===t&&1===h.strides[t]||i);let o,u=!1;if(h.beginValid&&h.endValid?(o=h.end[t]-h.begin[t],u=!0):n?(o=1,u=!0):i&&r>=0&&(o=h.strides[t]<0?-r:r,u=!0),u){let e;e=0===o||o<0!=h.strides[t]<0?0:Math.trunc(o/h.strides[t])+(o%h.strides[t]!=0?1:0),y.push(e)}else y.push(-1)}for(let e=0;e<h.finalShapeGatherIndices.length;++e){const t=h.finalShapeGatherIndices[e];t>=0?g.push(y[t]):-2===t&&g.push(1)}const _=g.filter(((e,t)=>-2!==h.finalShapeGatherIndices[t]));return{finalShapeSparse:_,finalShape:g,isIdentity:d,sliceDim0:f,isSimpleSlice:m,begin:h.begin,end:h.end,strides:h.strides}}(s.shape,a,i,o,u,l,p,c,h);let T;if(y)T=Ga({inputs:{x:s},backend:t,attrs:{shape:f}});else if(g||_){m(s.shape.length>=1,(()=>`Input must have rank at least 1, got: ${s.shape.length}`));const e=function(e,t,n){const r=[];for(let s=0;s<e.length;s++)r[s]=Math.ceil((t[s]-e[s])/n[s]);return r}(b,w,v),n=Di({inputs:{x:s},backend:t,attrs:{begin:b,size:e}});T=Ga({inputs:{x:n},backend:t,attrs:{shape:f}}),t.disposeData(n.dataId)}else{const e=t.makeOutput(d,"float32"),n=t.dataIdMap.get(s.dataId).id,r=new Uint8Array(new Int32Array(x(s.shape)).buffer),a=new Uint8Array(new Int32Array(b).buffer),i=new Uint8Array(new Int32Array(w).buffer),o=new Uint8Array(new Int32Array(v).buffer),u=new Uint8Array(new Int32Array(d).buffer),l=new Uint8Array(new Int32Array(x(d)).buffer),p=t.dataIdMap.get(e.dataId).id;Ci(n,r,s.shape.length,a,i,o,u,l,d.length,p),T=Ga({inputs:{x:e},backend:t,attrs:{shape:f}}),t.disposeData(e.dataId)}return T}},Li=Va("Sub"),Pi={kernelName:ue,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{value:s}=t;let{axis:a}=r;a<0&&(a+=s.shape.length);const i=s.shape[a],o=s.shape.length,u=new Array(o-1);let l=0;for(let e=0;e<o;e++)e!==a&&(u[l++]=s.shape[e]);const p=new Array(i),c=new Array(o).fill(0),h=s.shape.slice();h[a]=1;for(let e=0;e<p.length;e++)c[a]=e,p[e]=Di({inputs:{x:s},attrs:{begin:c,size:h},backend:n});return p.map((({dataId:e,dtype:t})=>({dataId:e,dtype:t,shape:u})))}};let Bi;const $i={kernelName:pe,backendName:"wasm",setupFunc:function(e){Bi=e.wasm.cwrap(pe,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:s,b:a,bias:i,preluActivationWeights:o}=t;if("float32"!==s.dtype||"float32"!==a.dtype)throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");const{transposeA:u,transposeB:l,activation:p,leakyreluAlpha:c}=r,h=n.dataIdMap.get(s.dataId).id,d=n.dataIdMap.get(a.dataId).id;let f=0;if(null!=i){const e=n.dataIdMap.get(i.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==o?0:n.dataIdMap.get(o.dataId).id,y=ja[p];if(null==y)throw new Error(`${p} activation not yet supported for FusedConv2D in the wasm backend.`);const g=u?s.shape[2]:s.shape[1],_=l?a.shape[1]:a.shape[2],b=Hn(s.shape.slice(0,-2),a.shape.slice(0,-2)),w=n.makeOutput([...b,g,_],s.dtype),v=n.dataIdMap.get(w.dataId).id,T=new Uint8Array(new Int32Array(s.shape).buffer),S=new Uint8Array(new Int32Array(a.shape).buffer);return Bi(h,T,s.shape.length,d,S,a.shape.length,u,l,y,f,m,c||0,v),w}};be(Wa),be(Ka),be(Ja),be(Xa),be(ni),be(si),be(oi),be(li),be(pi),be(hi),be(fi),be(ti),be(bi),be(wi),be(Ti),be(Si),be(Ni),be(Mi),be(qa),be(Fi),be(Ai),be(Oi),be(Ri),be(Li),be(gi),be(Pi),be($i);var zi={modelFilename:"",featuresFilename:"",objContainer:"",fovY:50,detectScoreThs:.2,trackScoreThs:.4,footToDetect:"RIGHT_FOOT",filteringLevel:2,filteringShift:.5,validTrackedKeypThs:.2,trackedNumKeypsThs:3,activeIds:new Int32Array};function Hi(e){return!!(void 0===e.outputNames||e.outputNames.length<1||e.outputNames.includes("heatmaps"))}var ji=Uint8Array,Vi=Uint16Array,Wi=Uint32Array,Ui=new ji([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]),Ki=new ji([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]),Gi=new ji([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),qi=function(e,t){for(var n=new Vi(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];var s=new Wi(n[30]);for(r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)s[a]=a-n[r]<<5|r;return[n,s]},Qi=qi(Ui,2),Ji=Qi[0],Yi=Qi[1];Ji[28]=258,Yi[258]=28;for(var Xi=qi(Ki,0)[0],Zi=new Vi(32768),eo=0;eo<32768;++eo){var to=(43690&eo)>>>1|(21845&eo)<<1;to=(61680&(to=(52428&to)>>>2|(13107&to)<<2))>>>4|(3855&to)<<4,Zi[eo]=((65280&to)>>>8|(255&to)<<8)>>>1}var no=function(e,t,n){for(var r=e.length,s=0,a=new Vi(t);s<r;++s)++a[e[s]-1];var i,o=new Vi(t);for(s=0;s<t;++s)o[s]=o[s-1]+a[s-1]<<1;if(n){i=new Vi(1<<t);var u=15-t;for(s=0;s<r;++s)if(e[s])for(var l=s<<4|e[s],p=t-e[s],c=o[e[s]-1]++<<p,h=c|(1<<p)-1;c<=h;++c)i[Zi[c]>>>u]=l}else for(i=new Vi(r),s=0;s<r;++s)e[s]&&(i[s]=Zi[o[e[s]-1]++]>>>15-e[s]);return i},ro=new ji(288);for(eo=0;eo<144;++eo)ro[eo]=8;for(eo=144;eo<256;++eo)ro[eo]=9;for(eo=256;eo<280;++eo)ro[eo]=7;for(eo=280;eo<288;++eo)ro[eo]=8;var so=new ji(32);for(eo=0;eo<32;++eo)so[eo]=5;var ao=no(ro,9,1),io=no(so,5,1),oo=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},uo=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(7&t)&n},lo=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},po=function(e,t,n){(null==t||t<0)&&(t=0),(null==n||n>e.length)&&(n=e.length);var r=new(e instanceof Vi?Vi:e instanceof Wi?Wi:ji)(n-t);return r.set(e.subarray(t,n)),r},co=new ji(0),ho=function(e,t){return e[t]|e[t+1]<<8},fo=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},mo=function(e,t){return fo(e,t)+4294967296*fo(e,t+4)};function yo(e,t){return function(e,t,n){var r=e.length;if(!r||n&&!n.l&&r<5)return t||new ji(0);var s=!t||n,a=!n||n.i;n||(n={}),t||(t=new ji(3*r));var i,o=function(e){var n=t.length;if(e>n){var r=new ji(Math.max(2*n,e));r.set(t),t=r}},u=n.f||0,l=n.p||0,p=n.b||0,c=n.l,h=n.d,d=n.m,f=n.n,m=8*r;do{if(!c){n.f=u=uo(e,l,1);var y=uo(e,l+1,3);if(l+=3,!y){var g=e[(F=((i=l)/8|0)+(7&i&&1)+4)-4]|e[F-3]<<8,_=F+g;if(_>r){if(a)throw"unexpected EOF";break}s&&o(p+g),t.set(e.subarray(F,_),p),n.b=p+=g,n.p=l=8*_;continue}if(1==y)c=ao,h=io,d=9,f=5;else{if(2!=y)throw"invalid block type";var b=uo(e,l,31)+257,w=uo(e,l+10,15)+4,v=b+uo(e,l+5,31)+1;l+=14;for(var T=new ji(v),S=new ji(19),k=0;k<w;++k)S[Gi[k]]=uo(e,l+3*k,7);l+=3*w;var N=oo(S),M=(1<<N)-1,x=no(S,N,1);for(k=0;k<v;){var F,I=x[uo(e,l,M)];if(l+=15&I,(F=I>>>4)<16)T[k++]=F;else{var A=0,E=0;for(16==F?(E=3+uo(e,l,3),l+=2,A=T[k-1]):17==F?(E=3+uo(e,l,7),l+=3):18==F&&(E=11+uo(e,l,127),l+=7);E--;)T[k++]=A}}var O=T.subarray(0,b),D=T.subarray(b);d=oo(O),f=oo(D),c=no(O,d,1),h=no(D,f,1)}if(l>m){if(a)throw"unexpected EOF";break}}s&&o(p+131072);for(var C=(1<<d)-1,R=(1<<f)-1,L=l;;L=l){var P=(A=c[lo(e,l)&C])>>>4;if((l+=15&A)>m){if(a)throw"unexpected EOF";break}if(!A)throw"invalid length/literal";if(P<256)t[p++]=P;else{if(256==P){L=l,c=null;break}var B=P-254;if(P>264){var $=Ui[k=P-257];B=uo(e,l,(1<<$)-1)+Ji[k],l+=$}var z=h[lo(e,l)&R],H=z>>>4;if(!z)throw"invalid distance";if(l+=15&z,D=Xi[H],H>3&&($=Ki[H],D+=lo(e,l)&(1<<$)-1,l+=$),l>m){if(a)throw"unexpected EOF";break}s&&o(p+131072);for(var j=p+B;p<j;p+=4)t[p]=t[p-D],t[p+1]=t[p+1-D],t[p+2]=t[p+2-D],t[p+3]=t[p+3-D];p=j}}n.l=c,n.p=L,n.b=p,c&&(u=1,n.m=d,n.d=h,n.n=f)}while(!u);return p==t.length?t:po(t,0,p)}(e,t)}var go="undefined"!=typeof TextDecoder&&new TextDecoder;try{go.decode(co,{stream:!0})}catch(e){}function _o(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(go)return go.decode(e);var s=function(e){for(var t="",n=0;;){var r=e[n++],s=(r>127)+(r>223)+(r>239);if(n+s>e.length)return[t,po(e,n-1)];s?3==s?(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&s?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),a=s[0];if(s[1].length)throw"invalid utf-8 data";return a}var bo=function(e,t){return t+30+ho(e,t+26)+ho(e,t+28)},wo=function(e,t,n){var r=ho(e,t+28),s=_o(e.subarray(t+46,t+46+r),!(2048&ho(e,t+8))),a=t+46+r,i=fo(e,t+20),o=n&&4294967295==i?vo(e,a):[i,fo(e,t+24),fo(e,t+42)],u=o[0],l=o[1],p=o[2];return[ho(e,t+10),u,l,s,a+ho(e,t+30)+ho(e,t+32),p]},vo=function(e,t){for(;1!=ho(e,t);t+=4+ho(e,t+2));return[mo(e,t+12),mo(e,t+4),mo(e,t+20)]};function To(e){for(var t={},n=e.length-22;101010256!=fo(e,n);--n)if(!n||e.length-n>65558)throw"invalid zip file";var r=ho(e,n+8);if(!r)return{};var s=fo(e,n+16),a=4294967295==s;if(a){if(n=fo(e,n-12),101075792!=fo(e,n))throw"invalid zip file";r=fo(e,n+32),s=fo(e,n+48)}for(var i=0;i<r;++i){var o=wo(e,s,a),u=o[0],l=o[1],p=o[2],c=o[3],h=o[4],d=o[5],f=bo(e,d);if(s=h,u){if(8!=u)throw"unknown compression type "+u;t[c]=yo(e.subarray(f,f+l),new ji(p))}else t[c]=po(e,f,f+l)}return t}function So(e){if(e)for(var t=0;t<e.length;t++)e[t]=~e[t];return e}var ko=function(){function e(e,t){this.jsonModel=e,this.weights=t}return e.prototype.load=function(){return i(this,void 0,void 0,(function(){var e,t,n,r;return o(this,(function(s){switch(s.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=s.sent(),n=t[0],r=t[1],e.weightSpecs=n,e.weightData=r,s.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 i(this,void 0,void 0,(function(){var e,t,n,r,s,a,i,u;return o(this,(function(o){for(e=[],t=[],n=0,r=this.jsonModel.weightsManifest;n<r.length;n++){for(s=r[n],a=0,i=s.paths;a<i.length;a++){if(u=i[a],!this.weights[u])throw new Error("Error loading weights: cannot find ".concat(u));e.push(this.weights[u])}t.push.apply(t,s.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+=(l=r[n]).length;for(var s=new ArrayBuffer(t),a=new Uint8Array(s),i=0,o=0,u=e;o<u.length;o++){var l=u[o];a.set(l,i),i+=l.length}return s}return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)},e}();function No(e,t){return i(this,void 0,void 0,(function(){var n,r,s,a,i;return o(this,(function(o){switch(o.label){case 0:return"string"!=typeof e?[3,2]:[4,Mo(e)];case 1:e=o.sent(),o.label=2;case 2:return[4,xo(e)];case 3:return[4,Fo(n=o.sent(),t)];case 4:return r=o.sent(),[4,Io(n,r)];case 5:return s=o.sent(),[4,Ao(n,s)];case 6:return a=o.sent(),[4,ya(new ko(s,a))];case 7:return i=o.sent(),[2,{config:r,graphModel:i}]}}))}))}function Mo(e){return i(this,void 0,void 0,(function(){var t;return o(this,(function(n){switch(n.label){case 0:return[4,fetch(e)];case 1:if(!(t=n.sent()).ok)throw new Error("HTTP error! status: ".concat(t.status));return[4,t.arrayBuffer()];case 2:return[2,n.sent()]}}))}))}function xo(e){return i(this,void 0,void 0,(function(){return o(this,(function(t){return[2,To(new Uint8Array(e))]}))}))}function Fo(e,t){return i(this,void 0,void 0,(function(){return o(this,(function(n){if(!e[t]&&(t=t.substring(0,t.lastIndexOf("."))+".json",!e[t]))throw new Error("Unable to retrieve model config: ".concat(t," is missing"));return t.includes(".bin")?[2,JSON.parse(_o(So(e[t])))]:[2,JSON.parse(_o(e[t]))]}))}))}function Io(e,t){return i(this,void 0,void 0,(function(){return o(this,(function(n){if(!t)throw new Error("Invalid model config");if(!e[t.filename])throw new Error("Error extracting model: ".concat(t.filename," is missing"));return[2,JSON.parse(_o(So(e[t.filename])))]}))}))}function Ao(e,t){return i(this,void 0,void 0,(function(){var n,r,s,a,i,u,l;return o(this,(function(o){if(!t)throw new Error("Unable to extract weights: model is undefined");if(!t.weightsManifest)return[2,{}];for(n={},r=0,s=t.weightsManifest;r<s.length;r++)for(a=s[r],i=0,u=a.paths;i<u.length;i++){if(l=u[i],!e[l])throw new Error("Error extracting weight: ".concat(l," is missing"));n[l]=So(e[l])}return[2,n]}))}))}function Eo(){Et().disposeVariables(),Et().reset();try{Lt("wasm")}catch(e){}try{Lt("cpu")}catch(e){}var e="undefined"!=typeof window?window:n.g;delete e._tfengine,e._tfGlobals&&(e._tfGlobals.clear(),delete e._tfGlobals)}function Oo(e,t){for(var n=1e4,r=1e4,s=-1e4,a=-1e4,i=0;i<t;i++){var o=e[i],u=e[t+i];o>s&&(s=o),u>a&&(a=u),o<n&&(n=o),u<r&&(r=u)}return[Math.floor(n),Math.floor(s+1),Math.floor(r),Math.floor(a+1)]}function Do(e,t,n){for(var r=1e4,s=1e4,a=-1e4,i=-1e4,o=0;o<n;o++)if(t[o]>0){var u=e[o],l=e[n+o];u>a&&(a=u),l>i&&(i=l),u<r&&(r=u),l<s&&(s=l)}return[Math.floor(r),Math.floor(a+1),Math.floor(s),Math.floor(i+1)]}function Co(e,t){void 0===t&&(t=.1);for(var n=e.length,r=0,s=0,a=new Int32Array(n),i=0;i<n;i++)e[i]>t?(s+=1,a[i]=1,r+=e[i]):a[i]=0;return s>0?r/=s:r=0,{globalScore:r,visibilty:a,totalVisible:s}}function Ro(e,t){void 0===t&&(t=.1);for(var n=e.length,r=new Int32Array(n),s=0;s<n;s++)e[s]>t?r[s]=1:r[s]=0;return r}function Lo(e,t,n,r){void 0===n&&(n=""),void 0===r&&(r=new Int32Array([-1,-1]));var s=Float32Array.from(e),a=e.length/2;if(""!=n)if("left_right"==n)for(var i=0;i<a;i++)s[i]=r[1]-1-s[i];else if("up_down"==n)for(i=0;i<a;i++)s[i+a]=r[0]-1-s[i+a];for(i=0;i<a;i++){var o=s[i],u=s[i+a];s[i]=t[0]*o+t[1]*u+t[2],s[i+a]=t[3]*o+t[4]*u+t[5]}return s}function Po(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];if(22==t)return[18,9];if(190==t)return[179,185];if(196==t)return[195,[11,128]];if(277==t)return[264,271];if(204==t)return[193,199];if(178==t)return[32,129];if(227==t)return[225,226]}return console.time("==> (E) Incorrect number of vertices"),[0,1]}function Bo(e,t,n){for(var r=0,s=0,a=e.length,i=0,o=e;i<o.length;i++){var u=o[i];r+=t[u],s+=t[u+n]}return new Wo(r/a,s/a)}function $o(e,t){var n,r,s=t.length/2,a=Po(e,s),i=a[0],o=a[1];n=Array.isArray(i)?Bo(i,t,s):new Wo(t[i],t[i+s]),r=Array.isArray(o)?Bo(o,t,s):new Wo(t[o],t[o+s]);var u=Wo.Center(n,r),l=-Math.atan2(n.y-r.y,r.x-n.x);return[u.x,u.y,l]}function zo(e){var t=new Float32Array(6);t[0]=1,t[4]=1;var n=e[0]*e[4]-e[1]*e[3];if(0!=n){n=1/n,t[0]=n*e[4],t[1]=-n*e[1],t[3]=-n*e[3],t[4]=n*e[0];var r=e[2],s=e[5];t[2]=-(t[0]*r+t[1]*s),t[5]=-(t[3]*r+t[4]*s)}return t}function Ho(e,t,n){for(var r=n[0],s=n[1],a=n[2],i=n[3],o=n[4],u=n[5],l=e.width,p=e.height,c=4*e.width,h=t.width,d=t.height,f=4*t.width,m=0;m<d;m++)for(var y=s*m+a,g=o*m+u,_=m*f,b=0;b<h;b++){var w=4*b,v=Math.floor(y),T=Math.floor(g),S=y-v,k=g-T,N=void 0,M=void 0;if(v>0&&v<l-1&&T>0&&T<p-1){for(var x=T*c+4*v,F=0;F<3;F++,x++){var I=e.data[x];N=I+S*(e.data[x+4]-I),M=e.data[x+c]+S*(e.data[x+c+4]-e.data[x+c]),t.data[_+w+F]=N+k*(M-N)}t.data[_+w+3]=255}else{for(F=0;F<3;F++)t.data[_+w+F]=0;t.data[_+w+3]=255}y+=r,g+=i}return t}function jo(e,t,n,r,s){for(var a=s[0],i=s[1],o=s[2],u=s[3],l=s[4],p=s[5],c=t[1],h=t[0],d=t[1],f=r[1],m=r[0],y=r[1],g=0;g<m;g++)for(var _=i*g+o,b=l*g+p,w=g*y,v=0;v<f;v++){var T=Math.floor(_),S=Math.floor(b),k=_-T,N=b-S,M=void 0,x=void 0;if(T>0&&T<c-1&&S>0&&S<h-1){var F=S*d+T,I=e[F];M=I+k*(e[F+1]-I),x=e[F+d]+k*(e[F+d+1]-e[F+d]),n[w+v]=M+N*(x-M)}else n[w+v]=0;_+=a,b+=u}return n}R().set("PROD",!0),P.set("DEPRECATION_WARNINGS_ENABLED",!1),P.global.Math=Math,P.global.Float32Array=Float32Array;var Vo,Wo=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.Center=function(t,n){return new e((t.x+n.x)/2,(t.y+n.y)/2)},e.prototype.add=function(t){return new e(this.x+t.x,this.y+t.y)},e.prototype.addInPlace=function(e){this.x+=e.x,this.y+=e.y},e}(),Uo=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}(),Ko=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 Wo(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 Go(e,t,n,r,s,a){void 0===a&&(a=!1);var i=e.length/2,o=Do(e,t,i),u=Math.max(o[1]-o[0],o[3]-o[2])/6;a&&(u=Math.max(o[1]-o[0],o[3]-o[2])/2);for(var l=0;l<i;l++)if(t[l]<=0&&r[l]>0)e[l]=n[l],e[l+i]=n[l+i];else if(t[l]>0&&r[l]<=0);else if(t[l]>0&&r[l]>0){var p=Math.sqrt((n[l]-e[l])*(n[l]-e[l])+(n[l+i]-e[l+i])*(n[l+i]-e[l+i])),c=(1-s)*Math.exp(-.5*p*p/u);e[l]=c*n[l]+(1-c)*e[l],e[l+i]=c*n[l+i]+(1-c)*e[l+i]}return e}function qo(e,t,n,r,s,a,i){void 0===i&&(i=0);for(var o=e.length/2,u=new Float32Array(2*n.length),l=0;l<n.length;l++){var p=n[l];u[l]=e[p],u[l+n.length]=e[p+o]}var c=n.length,h=new Wo(0,0);s.forEach((function(e){h.x+=u[e],h.y+=u[e+c]})),h.x/=s.length,h.y/=s.length;var d=r[0],f=r[1],m=new Wo(u[d],u[d+c]),y=new Wo(u[f],u[f+c]),g=-Math.atan2(y.y-m.y,m.x-y.x)+i,_=0;for(l=0;l<c;l++){var b=new Wo(u[l],u[l+c]).Dist(h);b>_&&(_=b)}_*=2;var w=new Ko(h.x-_/2,h.y-_/2,_,_),v=Math.cos(g),T=Math.sin(g);_=(w.w+a*w.w)/Math.max(t[0],t[1]);var S=t[1]/2,k=t[0]/2,N=h.x,M=h.y;return new Float32Array([v*_,-T*_,N-(v*_*S-T*_*k),T*_,v*_,M-(T*_*S+v*_*k)])}function Qo(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 Jo(e,t,n){for(var r=e.length/2,s=new Float32Array(2*r),a=0;a<r;a++)if(t[a]>0){var i=Qo(new Float32Array([e[a],e[a+r]]),n);s[a]=i[0],s[a+r]=i[1]}var o=Do(s,t,r);return Math.max(o[1]-o[0],o[3]-o[2])}!function(e){e.Detection="DETECTION",e.Detected="DETECTED",e.Tracking="TRACKING"}(Vo||(Vo={}));var Yo=function(){function e(e,t){this._trackingState=Vo.Detection,this._type=0,this._R=Float32Array.from(e),this._t=Float32Array.from(t),this._trackingState=Vo.Detection}return e.prototype.setTrackingState=function(e){this._trackingState=e},e.prototype.getTrackingState=function(){return this._trackingState},e.prototype.isDetected=function(){return this._trackingState==Vo.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,s,a=new Float32Array(4),i=e[1]*t[1]+e[2]*t[2]+e[3]*t[3]+e[0]*t[0],o=Math.abs(i);if(o>=.99999)r=1-n,s=n;else{var u=Math.acos(o),l=Math.sin(u);r=Math.sin((1-n)*u)/l,s=Math.sin(n*u)/l}return i<0&&(s=-s),a[1]=r*e[1]+s*t[1],a[2]=r*e[2]+s*t[2],a[3]=r*e[3]+s*t[3],a[0]=r*e[0]+s*t[0],a},e.getCameraMat=function(e,t,n){var r=n/2/Math.tan(e*Math.PI/180/2),s=r,a=(t-1)/2,i=(n-1)/2,o=new Float32Array(9);return o[0]=s,o[2]=a,o[4]=r,o[5]=i,o[8]=1,o},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),s=0;s<t.length/3;s++){var a=e.MatMultVec(this._R,new Float32Array([t[3*s],t[3*s+1],t[3*s+2]])),i=new Float32Array(3);i[0]=a[0]+this._t[0],i[1]=a[1]+this._t[1],i[2]=a[2]+this._t[2];var o=n[6]*i[0]+n[7]*i[1]+n[8]*i[2];r[2*s]=(n[0]*i[0]+n[1]*i[1]+n[2]*i[2])/o,r[2*s+1]=(n[3]*i[0]+n[4]*i[1]+n[5]*i[2])/o}return r},e.prototype.transform=function(t,n){for(var r=new Float32Array(t.length/3*2),s=0;s<t.length/3;s++){var a=e.MatMultVec(this._R,new Float32Array([t[3*s],t[3*s+1],t[3*s+2]]));r[3*s+0]=a[0]+this._t[0],r[3*s+1]=a[1]+this._t[1],r[3*s+2]=a[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]]),s=e.MatMultVec(r,t),a=e.MatMultVec(r,this._t);return n[0]=s[0]-a[0],n[1]=s[1]-a[1],n[2]=s[2]-a[2],n},e}();function Xo(e,t){e.length;var n=function(e,t){var n=e.length/2,r=tu(n,t),s=r[0],a=r[1],i=[e[s],e[s+n]],o=[e[a],e[a+n]],u=[(i[0]+o[0])/2,(i[1]+o[1])/2],l=-Math.atan2(i[1]-o[1],o[0]-i[0]),p=Math.sqrt((i[0]-o[0])*(i[0]-o[0])+(i[1]-o[1])*(i[1]-o[1]));return[u[0],u[1],l,p]}(e,t),r=n[0],s=n[1],a=n[2],i=n[3],o=[Math.cos(a),Math.sin(a)],u=[-o[1],o[0]],l=i/1,p=i/2;return[r+o[0]*l+u[0]*p,s+o[1]*l+u[1]*p,r+o[0]*l-u[0]*p,s+o[1]*l-u[1]*p,r-o[0]*l-u[0]*p,s-o[1]*l-u[1]*p,r-o[0]*l+u[0]*p,s-o[1]*l+u[1]*p]}function Zo(e,t,n){if(void 0===n&&(n=.1),6==e.length){for(var r=0,s=new Int32Array(3),a=0,i="RIGHT_FOOT"==t?3:0,o=i;o<i+3;o++)r+=e[o],e[o]>n&&(a+=1,s[o]=1);return{globalScore:r/=3,visibilty:s,totalVisible:a}}return Co(e,n)}function eu(e,t,n,r){var s=Float32Array.from(e),a=e.length/2;if(n)for(var i=0;i<a;i++)s[i+a]=r-1-s[i+a];for(i=0;i<a;i++){var o=s[i],u=s[i+a];s[i]=t[0]*o+t[1]*u+t[2],s[i+a]=t[3]*o+t[4]*u+t[5]}return s}function tu(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?15!=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 with size:",e),[0,1]):[115,167]:[210,78]:[9,11]:[9,6]:[0,9]}function nu(e,t){var n=e.length/2,r=tu(n,t),s=r[0],a=r[1],i=[e[s],e[s+n]],o=[e[a],e[a+n]],u=[(i[0]+o[0])/2,(i[1]+o[1])/2],l=-Math.atan2(i[1]-o[1],o[0]-i[0]);return[u[0],u[1],l]}function ru(e,t,n,r,s){for(var a=e.length/2,i=Do(e,t,a),o=Math.max(i[1]-i[0],i[3]-i[2])/5,u=0;u<a;u++)if(t[u]<=0&&r[u]>0)e[u]=n[u],e[u+a]=n[u+a];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+a]-e[u+a])*(n[u+a]-e[u+a])),p=1*(1-s)/(1+Math.exp(4*l-o/2));e[u]=p*n[u]+(1-p)*e[u],e[u+a]=p*n[u+a]+(1-p)*e[u+a]}return e}function su(e,t,n,r,s,a,i,o,u){var l,p;void 0===i&&(i=""),void 0===o&&(o=.5),void 0===u&&(u=0);var c=e.length/2,h=null,d=0,f=0,m=0,y=tu(c,a),g=y[0],_=y[1],b=[e[g],e[g+c]],w=[e[_],e[_+c]],v=Math.sqrt((b[0]-w[0])*(b[0]-w[0])+(b[1]-w[1])*(b[1]-w[1]));6==c?(f=(l=nu(e,a))[0],d=l[1],m=l[2],h=Oo("RIGHT_FOOT"==a?[e[3],e[4],e[5],e[3+c],e[4+c],e[5+c]]:[e[0],e[1],e[2],e[0+c],e[1+c],e[2+c]],3),m+=u):(f=(p=nu(e,a))[0],d=p[1],m=p[2],h=Do(e,t,c),m+=u,"oriented_bbox_size"==i&&(f=(h[1]+h[0])/2,d=(h[3]+h[2])/2,t&&(v=Jo(e,t,-m))));var T=Math.cos(m),S=Math.sin(m),k=(v+=o*v)/Math.max(r,n),N=(n-1)/2,M=(r-1)/2;return[T*k,-S*k,f-(T*k*N-S*k*M),S*k,T*k,d-(S*k*N+T*k*M),m,k]}function au(e,t){var n=t.length,r=e._malloc(4*n),s=r/4;return e.HEAPF32.subarray(s,s+n).set(t),r}function iu(e,t){var n=e._malloc(4*t.length);return e.HEAPF32.set(t,n/4),n}function ou(e,t,n){var r=new Float32Array(n),s=t/4;return r.set(e.HEAPF32.subarray(s,s+n)),r.slice()}function uu(e,t,n){var r=new Uint32Array(t.data.buffer),s=r.length,a=n/4;e.HEAPU32.subarray(a,a+s).set(r)}function lu(e,t,n,r){var s=e._malloc(28);return e.setValue(s,n,"i32"),e.setValue(s+4,r,"i32"),e.setValue(s+8,t,"i32"),e.setValue(s+12,0,"i32"),e.setValue(s+16,4,"i32"),e.setValue(s+20,0,"i32"),e.setValue(s+24,0,"i32"),s}function pu(e,t,n,r,s){var a=e.cwrap("xzimgMatchRecKeyps","number",["number","number","number","number","number"]),i=r.length/2;uu(e,t,n);for(var o=lu(e,n,t.width,t.height),u=iu(e,r),l=iu(e,r.slice()),p=e._malloc(4*i),c=0;c<i;c++)e.setValue(p+4*c,1,"float"),s.length>c&&0==s[c]&&e.setValue(p+4*c,-1,"float");var h=e._malloc(16);a(o,u,l,i,p,h);var d=ou(e,p,i),f=ou(e,l,r.length),m=ou(e,h,4);for(c=0;c<i;c++)0==d[c]&&(f[c]=r[c],f[c+i]=r[c+i]);return e._free(o),e._free(u),e._free(l),e._free(p),e._free(h),[f,m,d]}function cu(e,t,n,r){var s=iu(e,t),a=iu(e,n),i=e._malloc(16);e.cwrap("xzimgEstimateGetSimilarity","number",["number","number","number","number"])(s,a,t.length/2,i);var o=ou(e,i,4);return e._free(s),e._free(a),e._free(i),o}function hu(e,t,n){void 0===n&&(n=null);for(var r=new Float32Array(2),s=e.length/2,a=0,i=0;i<s;i++)(null==n||n[i]>0)&&(r[0]+=t[i]-e[i],r[1]+=t[i+s]-e[i+s],a+=1);return a>0&&(r[0]/=a,r[1]/=a),r}function du(e,t,n){var r,s,a,i,o;void 0===n&&(n=!0);var u=n?1:2;return r=function(e,t,n,r,s){void 0===s&&(s=1);var a=new Float32Array(r).fill(0),i=new Float32Array(2*r);if(1==s)for(var o=t*n,u=0;u<o;u++)for(var l=0;l<r;l++)(h=e[u*r+l])>a[l]&&(a[l]=h,i[l]=u%n,i[r+l]=Math.floor(u/n));else{var p=n*s;for(u=s;u<t;u+=s,p+=n*s)for(var c=s;c<n;c+=s)for(l=0;l<r;l++){var h;(h=e[(p+c)*r+l])>a[l]&&(a[l]=h,i[l]=c,i[r+l]=u)}}return[i,a]}(e,t[1],t[2],t[3],u),a=r[0],o=r[1],n?(s=function(e,t,n,r,s){for(var a=[-r*s-s,-r*s,-r*s+s,-s,0,s,r*s-s,r*s,r*s+s],i=new Float32Array(s),o=new Float32Array(2*s),u=0;u<s;u++){var l=t[u],p=t[s+u];o[u]=l,o[s+u]=p;var c=p*r*s+l*s+u,h=0;h=0;for(var d=0;d<9;d++)h+=e[c+a[d]];h/=9,i[u]=h;var f=Math.min(l+2,r-1),m=Math.max(l-2,0),y=Math.min(p+2,n-1),g=Math.max(p-2,0),_=0,b=0,w=p*r*s+m*s+u,v=p*r*s+f*s+u;for(d=0;d<9;d++)_+=e[w+a[d]],b+=e[v+a[d]];var T=2*(2*h-((_/=9)+(b/=9)));if(Math.abs(T)>1e-5){var S=2*(b-_)/T;o[u]+=S}var k=0,N=0,M=g*r*s+l*s+u,x=y*r*s+l*s+u;for(d=0;d<9;d++)k+=e[M+a[d]],N+=e[x+a[d]];T=2*(2*h-((k/=9)+(N/=9))),Math.abs(T)>1e-5&&(S=2*(N-k)/T,o[s+u]+=S)}return[o,i]}(e,a,t[1],t[2],t[3]),i=s[0],o=s[1]):i=a,[i,o]}function fu(e,t,n,r,s,a){var i=e.cwrap("xzimgGetHeatmapsLocations","number",["number","number","number","number","number","number","number","number"]),o=t[1]*t[2]*t[3],u=r/4;return e.HEAPF32.subarray(u,u+o).set(n),i(r,t[1],t[2],t[3],0,1,s,a),[new Float32Array(e.HEAPF32.buffer,s,2*t[3]),new Float32Array(e.HEAPF32.buffer,a,t[3])]}function mu(e){var t=kr(e,0),n=mt(t,"float32"),r=Kn(e,n),s=_r(r),a=_r(n),i=Mt(s,a),o=gr(e),u=Kn(o,n),l=_r(u),p=Mt(l,a),c=gr(i),h=St(p,c);return t.dispose(),n.dispose(),r.dispose(),s.dispose(),a.dispose(),o.dispose(),u.dispose(),l.dispose(),p.dispose(),c.dispose(),{mean:i,variance:h}}function yu(e,t,n,r,s,a,i,o){void 0===o&&(o=[""]);for(var u=[],l=[],p=[],c=[],h=[],d=[],f=0,m=null,y=0,g=i;y<g.length;y++){var _=g[y],b=bt(_);d.push(b);var w=mt(b,"float32");d.push(w);var v=kt(w,[1,t.inHeight,t.inWidth,3]);d.push(v);var T=null,S=t.inputNormMode?t.inputNormMode:"float_01";if("float_01"==S)T=Mt(v,gt(255));else if("float_11"==S){var k=St(v,gt(127.5));T=Mt(k,gt(127.5)),d.push(k)}else if("uint8"==S)T=mt(v,"int32");else if("imagenet"==S){var N=St(v,gt(255)),M=Tt([.485,.456,.406]),x=Tt([.229,.224,.225]);k=St(N,M),T=Mt(k,x),d.push(k),d.push(N),d.push(M),d.push(x)}else if("standardized"==S){N=St(v,gt(255));var F=Sr(N),I=(M=F.mean,F.variance);x=yr(I),k=St(N,M),T=Mt(k,x),d.push(N),d.push(k),d.push(M),d.push(I),d.push(x)}else if("standardized_01"==S){var A=mu(N=Mt(v,gt(255))),E=(M=A.mean,I=A.variance,x=yr(I),k=St(N,M),Mt(k,x)),O=mr(E),D=fr(E),C=St(E,O),R=St(D,O);T=Mt(C,R),d.push(k),d.push(M),d.push(I),d.push(x),d.push(N),d.push(E),d.push(O),d.push(D),d.push(C),d.push(R)}else console.error("Unknown image normalisation mode: ",S),T=Mt(v,gt(255));d.push(T),"left_right"!=o[f]&&"up_down"!=o[f]||(T=Ar(T,"left_right"==o[f]?2:1),d.push(T)),m?(m=rr([m,T]),d.push(m)):m=T,f+=1}if(null!=m){var L=[];if(t.numOutputs&&1!=t.numOutputs)for(var P=0,B=L=e.predict(m);P<B.length;P++){var $=B[P];d.push($)}else{var z=e.predict(m);d.push(z),L.push(z)}for(var H=0,j=0,V=L;j<V.length;j++){z=V[j];for(var W=[],U=[],K=0,G=Cr(z,0);K<G.length;K++){var q=G[K];d.push(q);var Q=br(q,0);d.push(Q),W.push(q.dataSync()),U.push(Q.shape)}if(t.outputNames&&"heatmaps"!=t.outputNames[H]){if(t.outputNames&&"masks"==t.outputNames[H])for(ie=0;ie<W.length;ie++)c.push(W[ie]);else if(t.outputNames&&"coordinates"==t.outputNames[H])for(ie=0;ie<W.length;ie++){for(var J=U[ie][1]/2,Y=new Float32Array(2*J),X=t.inHeight/2,Z=t.inWidth/2,ee=0;ee<J;ee++)Y[ee]=(W[ie][ee]+1)*Z,Y[ee+J]=(W[ie][ee+J]+1)*X;u.push(Y)}else if(t.outputNames&&"classes"==t.outputNames[H])for(ie=0;ie<W.length;ie++){var te=U[ie][1],ne=new Float32Array(te);for(ee=0;ee<te;ee++)ne[ee]=W[ie][ee];h.push(ne)}else if(t.outputNames&&"scores"==t.outputNames[H])if(t.outputTypes&&"logits"==t.outputTypes[H])for(ie=0;ie<W.length;ie++){var re=U[ie][1],se=new Float32Array(re);for(ee=0;ee<re;ee++)se[ee]=1/(1+Math.exp(-W[ie][ee]));l.push(se)}else for(ie=0;ie<W.length;ie++){for(re=U[ie][1],se=new Float32Array(re),ee=0;ee<re;ee++)se[ee]=W[ie][ee];l.push(se)}else if(t.outputNames&&"occlusions"==t.outputNames[H])if(t.outputTypes&&"logits"==t.outputTypes[H])for(ie=0;ie<W.length;ie++){re=U[ie][1];var ae=new Float32Array(re);for(ee=0;ee<re;ee++)ae[ee]=1/(1+Math.exp(-W[ie][ee]));p.push(ae)}else for(ie=0;ie<W.length;ie++){for(re=U[ie][1],ae=new Float32Array(re),ee=0;ee<re;ee++)ae[ee]=W[ie][ee];p.push(ae)}}else for(var ie=0;ie<W.length;ie++){var oe;oe=n?fu(n,U[ie],W[ie],r[ie],s[ie],a[ie]):du(W[ie],U[ie],!0),u.push(oe[0]),l.push(oe[1])}H+=1}}return d.forEach((function(e){return e.dispose()})),{coordinates:u,scores:l,occlusions:p,masks:c,classes:h}}var gu=new TextDecoder;function _u(e,t){return i(this,void 0,void 0,(function(){var t;return o(this,(function(n){switch(n.label){case 0:return"string"!=typeof e?[3,3]:""===e?[2,{vertices:new Float32Array,uvs:new Float32Array,faces:new Uint16Array}]:[4,fetch(e)];case 1:if(!(t=n.sent()).ok)throw new Error("HTTP error! status: ".concat(t.status));return[4,t.text()];case 2:return[2,bu(n.sent())];case 3:return[2,bu(gu.decode(e))]}}))}))}function bu(e,t){var n,r,s,a={vertices:new Float32Array,uvs:new Float32Array,faces:new Uint16Array},i=e.match(/^v\s+(-?\d+(?:\.\d+)?\s+){2}-?\d+(?:\.\d+)?$/gm);if(i){var o=i.map((function(e){var t=e.split(" ");return t.shift(),t.map((function(e){return+e}))})),u=(n=[]).concat.apply(n,o);a.vertices=new Float32Array(u)}var l=e.match(/^vt( -?\d+(\.\d+)?){2}$/gm);if(l){var p=l.map((function(e){var t=e.split(" ");return t.shift(),t.map((function(e){return+e}))})),c=(r=[]).concat.apply(r,p);a.uvs=new Float32Array(c)}var h=e.match(/^f( \d+\/\d*\/\d*){3}$/gm);if(h){var d=h.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]})),f=(s=[]).concat.apply(s,d);a.faces=new Uint16Array(f)}return a}var wu,vu=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=u([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()!==Vo.Tracking||r.getTrackingState()!==Vo.Tracking)return n;for(var s=Yo.getQuatFromRotMat(t.R()),a=Yo.getQuatFromRotMat(r.R()),i=Yo.slerp(s,a,.5),o=Yo.getRotMatFromQuat(i),u=t.t(),l=r.t(),p=new Float32Array(3),c=0;c<3;c++)p[c]=.5*u[c]+.5*l[c];var h=new Yo(o,p);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()!==Vo.Tracking||t.getTrackingState()!==Vo.Tracking)return this.getInterpolatedPoseAtDelay(this._nbFramesDelay);var n=this._poses[this._nbFramesDelay],r=e.t(),s=t.t();if(this._filterThreshold>0){var a=this.dst(r,n.t()),i=this.dst(s,n.t());if(a>this._filterThreshold||i>this._filterThreshold)return n}for(var o=Yo.getQuatFromRotMat(e.R()),u=Yo.getQuatFromRotMat(t.R()),l=Yo.slerp(o,u,this._interpolation),p=Yo.getRotMatFromQuat(l),c=new Float32Array(3),h=0;h<3;h++)c[h]=(1-this._interpolation)*r[h]+this._interpolation*s[h];var d=new Yo(p,c);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"}(wu||(wu={}));var Tu="config.bin",Su=function(){function e(){this._initialized=!1,this._currentWidth=0,this._currentHeight=0,this._trackingState=Vo.Detection,this._useWasmForHeatmaps=!1,this._float_size=4,this._bufferHeatmaps=null,this._bufferKeypsDet=null,this._bufRightScores=null,this._bufLeftScores=null,this._bufKeyps3D_R=null,this._bufKeyps3D_L=null,this._footToDetect=wu.Right,this._leftFootState=Vo.Detection,this._rightFootState=Vo.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._useRecursiveFilter=!0,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.getInputDims=function(){return[this._currentHeight,this._currentWidth]},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=wu.Right);var t=null;return(t=e==wu.Right?this._poseManager_R.getInterpolatedPose():this._poseManager_L.getInterpolatedPose())?t.getPosition():null},e.prototype.getRotation=function(e){void 0===e&&(e=wu.Right);var t=null;return(t=e==wu.Right?this._poseManager_R.getInterpolatedPose():this._poseManager_L.getInterpolatedPose())?t.getRotation():null},e.prototype.getPose=function(e){return void 0===e&&(e=wu.Right),e==wu.Right?this._pose_L:this._pose_R},e.prototype.getFeetCenterLocation=function(){return function(e,t,n,r){if(n!==Vo.Tracking&&r!==Vo.Tracking)return null;var s,a,i,o,u=e.length/2,l=tu(u,"LEFT_FOOT");n===Vo.Tracking&&(s=[e[l[1]],e[l[1]+u]],a=[e[l[0]],e[l[0]+u]],Math.sqrt((s[0]-a[0])*(s[0]-a[0])+(s[1]-a[1])*(s[1]-a[1]))),r===Vo.Tracking&&(i=[t[1],t[1+u]],o=[t[0],t[0+u]],Math.sqrt((i[0]-o[0])*(i[0]-o[0])+(i[1]-o[1])*(i[1]-o[1])));var p=[0,0];return s&&i?p=[(s[0]+i[0])/2,(s[1]+i[1])/2]:s?p=s:i&&(p=i),new Wo(p[0],p[1])}(this._leftFootRecShape,this._rightFootRecShape,this._leftFootState,this._rightFootState)},e.prototype.getMask=function(e,t){var n=new Float32Array(e*t),r=[this._footFeaturesConfig.outHeight,this._footFeaturesConfig.outWidth];if(this._rightFootState==Vo.Tracking&&this._leftFootState==Vo.Tracking){var s=Float32Array.from(this._simToImage_L),a=Float32Array.from(this._simToImage_R),i=e/this._currentWidth,o=t/this._currentHeight;s[0]=i*s[0],s[1]=i*s[1],s[3]=o*s[3],s[4]=o*s[4],s[2]=i*s[2],s[5]=o*s[5],(s=zo(s))[3]=-s[3],s[4]=-s[4],s[5]=-s[5]+(r[0]-1),a[0]=i*a[0],a[1]=i*a[1],a[3]=o*a[3],a[4]=o*a[4],a[2]=i*a[2],a[5]=o*a[5],a=zo(a),this._leftFootMask&&this._rightFootMask&&function(e,t,n,r,s,a,i){for(var o=a[0],u=a[1],l=a[2],p=a[3],c=a[4],h=a[5],d=i[0],f=i[1],m=i[2],y=i[3],g=i[4],_=i[5],b=n[1],w=n[0],v=n[1],T=s[1],S=s[0],k=s[1],N=0;N<S;N++)for(var M=u*N+l,x=c*N+h,F=f*N+m,I=g*N+_,A=N*k,E=0;E<T;E++){var O=Math.floor(M),D=Math.floor(x),C=M-O,R=x-D,L=void 0,P=0,B=0;O>0&&O<b-1&&D>0&&D<w-1&&(P=(L=(z=e[$=D*v+O])+C*(e[$+1]-z))+R*(e[$+v]+C*(e[$+v+1]-e[$+v])-L),B=Math.abs(w/2-x),B/=w/2,B=1/(1+Math.exp(30*B-20))),C=F-(O=Math.floor(F)),R=I-(D=Math.floor(I));var $,z,H=0,j=0;O>0&&O<b-1&&D>0&&D<w-1&&(H=(L=(z=t[$=D*v+O])+C*(t[$+1]-z))+R*(t[$+v]+C*(t[$+v+1]-t[$+v])-L),j=Math.abs(w/2-I),j/=w/2,j=1/(1+Math.exp(30*j-20)));var V=j+B;r[A+E]=V>0?Math.max(B*P,j*H):0,M+=o,x+=p,F+=d,I+=y}}(this._leftFootMask,this._rightFootMask,new Float32Array(r),n,new Float32Array([t,e]),s,a)}else if(this._rightFootState==Vo.Tracking){var u=Float32Array.from(this._simToImage_R);i=e/this._currentWidth,o=t/this._currentHeight,u[0]=i*u[0],u[1]=i*u[1],u[3]=o*u[3],u[4]=o*u[4],u[2]=i*u[2],u[5]=o*u[5],u=zo(u),this._rightFootMask&&jo(this._rightFootMask,new Float32Array(r),n,new Float32Array([t,e]),u)}else this._leftFootState==Vo.Tracking&&(u=Float32Array.from(this._simToImage_L),i=e/this._currentWidth,o=t/this._currentHeight,u[0]=i*u[0],u[1]=i*u[1],u[3]=o*u[3],u[4]=o*u[4],u[2]=i*u[2],u[5]=o*u[5],(u=zo(u))[3]=-u[3],u[4]=-u[4],u[5]=-u[5]+(r[0]-1),this._leftFootMask&&jo(this._leftFootMask,new Float32Array(r),n,new Float32Array([t,e]),u));return n},e.prototype.getInterpolatedPose=function(e){return void 0===e&&(e=wu.Right),e==wu.Right?this._poseManager_R.getInterpolatedPose():this._poseManager_L.getInterpolatedPose()},e.prototype.isInitialized=function(){return this._initialized},e.prototype.initialize=function(e,t,n){return i(this,void 0,void 0,(function(){var n,r,s,i,u,l,p,h,d,f,m,y,g,_,b,w,v,T,S,k=this;return o(this,(function(o){switch(o.label){case 0:if(null==e)throw"Invalid parameter";return this._config=t?a(a({},zi),t):zi,!0!==(null==t?void 0:t.useWasmBackend)?[3,2]:($a("./xzimg/"),[4,Ct("wasm")]);case 1:return o.sent(),[3,6];case 2:return!0!==(null===(w=null==t?void 0:t.wasmBackend)||void 0===w?void 0:w.enable)?[3,4]:($a({"tfjs-backend-wasm.wasm":null===(v=t.wasmBackend)||void 0===v?void 0:v.tfjsBackendWasmPath,"tfjs-backend-wasm-simd.wasm":null===(T=t.wasmBackend)||void 0===T?void 0:T.tfjsBackendWasmSimdPath,"tfjs-backend-wasm-threaded-simd.wasm":null===(S=t.wasmBackend)||void 0===S?void 0:S.tfjsBackendWasmThreadedPath}),[4,Ct("wasm")]);case 3:return o.sent(),[3,6];case 4:return[4,Ct("webgl")];case 5:o.sent(),o.label=6;case 6:return this.release(),this._videoManager=e,"BOTH"!==this._config.footToDetect&&"BOTH_FEET"!==this._config.footToDetect||(this._footToDetect=wu.Both),this._poseManager_R=new vu(this._videoManager.getNbFramesDelay()),this._poseManager_R.setInterpolation(this._config.filteringShift),this._poseManager_R.setFilteringLevel(this._config.filteringLevel),this._poseManager_L=new vu(this._videoManager.getNbFramesDelay()),this._poseManager_L.setInterpolation(this._config.filteringShift),this._poseManager_L.setFilteringLevel(this._config.filteringLevel),n=this._config.poseEstimationWasmFilename instanceof ArrayBuffer?{wasmBinary:this._config.poseEstimationWasmFilename}:{locateFile:function(e,t){return k._config.poseEstimationWasmFilename||t+e}},[4,c(n)];case 7:return(r=o.sent()).wasmBinary&&(r.wasmBinary=null),[4,No(this._config.modelFilename,Tu)];case 8:return s=o.sent(),[4,No(this._config.featuresFilename,Tu)];case 9:return i=o.sent(),[4,_u(this._config.objContainer)];case 10:if(u=o.sent(),this._poseModule=r,this._footObjModel=u,this._tfFootDetector=s.graphModel,this._footDetectorConfig=s.config,this._tfFootFeatures=i.graphModel,this._footFeaturesConfig=i.config,function(e){void 0===e.normExtRatio&&console.warn("Model config is missing extension ratio"),void 0===e.normAngleShift&&console.warn("Model config is missing angular shift")}(this._footFeaturesConfig),this._activeIds=this._config.activeIds,l=vt([1,this._footDetectorConfig.inHeight,this._footDetectorConfig.inWidth,3]),p=this._tfFootDetector.predict(l),this._footDetectorShape=p.shape,p.dataSync(),p.dispose(),l.dispose(),h=this._footDetectorConfig.outChannels,l=vt([1,this._footFeaturesConfig.inHeight,this._footFeaturesConfig.inWidth,3]),(p=this._tfFootFeatures.predict(l))instanceof Array?p.forEach((function(e){return e.dispose()})):p.dispose(),l.dispose(),l=vt([2,this._footFeaturesConfig.inHeight,this._footFeaturesConfig.inWidth,3]),(p=this._tfFootFeatures.predict(l))instanceof Array?p.forEach((function(e){return e.dispose()})):p.dispose(),l.dispose(),d=this._footFeaturesConfig.outChannels,this._footFeaturesConfig.outputNames&&this._footFeaturesConfig.numOutputs&&this._footFeaturesConfig.numOutputs>1)for(f=0,m=0,y=this._footFeaturesConfig.outputNames;m<y.length;m++)"heatmaps"==(g=y[m])?d=this._footFeaturesConfig.outputDims[3*f+2]:"coordinates"==g&&(d=this._footFeaturesConfig.outputDims[3*f+2]/2),f+=1;return b=function(e,t){var n=[];if(13==t)n=[[20],[40],[45],[47],[50,141],[67],[69],[95],[132,177],[157],[160],[164],[189]];else if(15==t)n=[[20],[40],[45,166],[47],[50,141],[67],[33,69],[171,192],[132,177],[157],[39,160],[164],[189],[26],[186]];else if(18==t)for(var r=[54,210,295,406,415,416,417,423,425,463,518,582,644,657,721,726,730,813],s=0;s<t;s++)n.push([r[s]]);else for(s=0;s<t;s++)n.push([s]);var a=new Float32Array(3*t),i=function(t){var r=n[t];Array.isArray(r)&&(r.forEach((function(n){a[3*t]+=e[3*n],a[3*t+1]+=e[3*n+1],a[3*t+2]+=e[3*n+2]})),a[3*t]/=r.length,a[3*t+1]/=r.length,a[3*t+2]/=r.length)};for(s=0;s<t;s++)i(s);var o=new Float32Array(3*t);for(s=0;s<t;s++)o[3*s]=-a[3*s],o[3*s+1]=a[3*s+1],o[3*s+2]=a[3*s+2];return[a,o]}(this._footObjModel.vertices,d),this._rightKeyps3D=b[0],this._leftKeyps3D=b[1],this._bufKeyps3D_R=this._poseModule._malloc(this._rightKeyps3D.length*this._float_size),this._poseModule.HEAPF32.set(this._rightKeyps3D,this._bufKeyps3D_R/4),this._bufKeyps3D_L=this._poseModule._malloc(this._leftKeyps3D.length*this._float_size),this._poseModule.HEAPF32.set(this._leftKeyps3D,this._bufKeyps3D_L/4),this._footDetectorConfig.outWidth>1&&this._footDetectorConfig.outHeight>1&&(_=h*this._footDetectorConfig.outWidth*this._footDetectorConfig.outHeight,this._bufferHeatmaps=this._poseModule._malloc(_*this._float_size)),this._footFeaturesConfig.outWidth>1&&this._footFeaturesConfig.outHeight>1&&(_=d*this._footFeaturesConfig.outWidth*this._footFeaturesConfig.outHeight,this._bufferHeatmaps_L=this._poseModule._malloc(_*this._float_size),this._bufferHeatmaps_R=this._poseModule._malloc(_*this._float_size)),this._bufferKeypsDet=this._poseModule._malloc(2*h*this._float_size),this._bufferKeypsTrack_L=this._poseModule._malloc(2*d*this._float_size),this._bufferKeypsTrack_R=this._poseModule._malloc(2*d*this._float_size),this._bufRightScores=this._poseModule._malloc(d*this._float_size),this._bufLeftScores=this._poseModule._malloc(d*this._float_size),this._pose_R=new Yo(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0])),this._pose_L=new Yo(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0])),this._trackHasHeatmaps=Hi(this._footFeaturesConfig),this._initialized=!0,[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._bufRightScores),this._poseModule._free(this._bufLeftScores),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=e;null==e&&(n=this._videoManager.getLastBuffer()),null!=n?(n.width===this._currentWidth&&n.height===this._currentHeight||(this._currentWidth=n.width,this._currentHeight=n.height,t=Yo.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()),this.trackFootSync(n)):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!=Vo.Detection&&this._leftFootState!=Vo.Detection){var n=Zo((c=this.trackFeetFeaturesSync(e,this._leftFootState,this._rightFootState,this._leftFootState==Vo.Detected?this._initShape:this._leftFootRecShape,this._rightFootState==Vo.Detected?this._initShape:this._rightFootRecShape,this._leftFootVis,this._rightFootVis,this._leftFootOcclusions,this._rightFootOcclusions)).scores_R,"RIGHT_FOOT",this._config.validTrackedKeypThs);this._rightFootRecShape=c.refinedFeatures_R,this._rightFootOcclusions=c.occlusions_R,this._rightFootVis=n.visibilty,this._rightFootMask=c.mask_R;var r=Zo(c.scores_L,"LEFT_FOOT",this._config.validTrackedKeypThs);this._leftFootRecShape=c.refinedFeatures_L,this._leftFootOcclusions=c.occlusions_L,this._leftFootVis=r.visibilty,this._leftFootMask=c.mask_L,!this._fastMovements_R&&c.classes_R.length>0&&c.classes_R[0]>c.classes_R[1]&&c.classes_R[0]>c.classes_R[2]&&(n.globalScore=0),!this._fastMovements_L&&c.classes_L.length>0&&c.classes_L[0]>c.classes_L[1]&&c.classes_L[0]>c.classes_L[2]&&(r.globalScore=0);var s=this._config.trackScoreThs;this._fastMovements_R&&(s=.1);var a=this._reproj_t;this._fastMovements_R&&(a=this._reproj_fast_t);var i=this._rightFootRecShape.length/2,o=tu(i,"RIGHT_FOOT"),u=new Ko(0,0,e.width,e.height),l=new Wo((this._rightFootRecShape[o[0]]+this._rightFootRecShape[o[1]])/2,(this._rightFootRecShape[o[0]+i]+this._rightFootRecShape[o[1]+i])/2);u.isPointInside(l)&&this._rightFootVis[o[0]]&&this._rightFootVis[o[1]]&&n.globalScore>=s&&n.totalVisible>=this._config.trackedNumKeypsThs?(t=this.computePoseSync(this._rightFootState,"RIGHT_FOOT"),this._rightFootState=Vo.Tracking,t>a&&(this._rightFootState=Vo.Detection)):this._rightFootState=Vo.Detection,s=this._config.trackScoreThs,this._fastMovements_L&&(s=.1),a=this._reproj_t,this._fastMovements_L&&(a=this._reproj_fast_t),o=tu(i,"LEFT_FOOT");var p=new Wo((this._leftFootRecShape[o[0]]+this._leftFootRecShape[o[1]])/2,(this._leftFootRecShape[o[0]+i]+this._leftFootRecShape[o[1]+i])/2);u.isPointInside(p)&&this._leftFootVis[o[0]]&&this._leftFootVis[o[1]]&&r.globalScore>=s&&r.totalVisible>=this._config.trackedNumKeypsThs?(t=this.computePoseSync(this._leftFootState,"LEFT_FOOT"),this._leftFootState=Vo.Tracking,t>a&&(this._leftFootState=Vo.Detection)):this._leftFootState=Vo.Detection,this._leftFootState==Vo.Tracking&&this._rightFootState==Vo.Tracking&&this.bothFeetSamePlace()&&(this._leftFootState=Vo.Detection,this._rightFootState=Vo.Detection)}else if(this._rightFootState!==Vo.Detection&&this._leftFootState===Vo.Detection){var c=this.trackFootFeaturesSync(e,this._rightFootState,this._rightFootState==Vo.Detected?this._initShape:this._rightFootRecShape,this._rightFootVis,this._rightFootOcclusions,"RIGHT_FOOT");this._rightFootRecShape=c.refinedFeatures,this._rightFootOcclusions=c.occlusions,this._rightFootMask=c.mask,n=Zo(c.scores,"RIGHT_FOOT",this._config.validTrackedKeypThs),this._rightFootVis=n.visibilty,s=this._config.trackScoreThs,a=this._reproj_t,this._fastMovements_R&&(a=this._reproj_fast_t),o=tu(this._rightFootRecShape.length/2,"RIGHT_FOOT"),n.globalScore>=s&&n.totalVisible>=this._config.trackedNumKeypsThs?(t=this.computePoseSync(this._rightFootState,"RIGHT_FOOT"),this._rightFootState=Vo.Tracking,t>a&&(this._rightFootState=Vo.Detection)):this._rightFootState=Vo.Detection;var h=this.detectFeetSync(e);this._initShape=h.refinedFeatures,r=Zo(h.scores,"LEFT_FOOT",this._config.detectScoreThs),n=Zo(h.scores,"RIGHT_FOOT",this._config.detectScoreThs);var d=!1;if(!this._fastMovements_R&&null!=this._cnnOutputDataInvMask){var f=du(this._cnnOutputDataInvMask,this._footDetectorShape,!1);f[0];var m=Zo(g=f[1],"LEFT_FOOT",this._config.detectScoreThs),y=Zo(g,"RIGHT_FOOT",this._config.detectScoreThs);n.globalScore>r.globalScore&&n.globalScore>y.globalScore+.1&&m.globalScore>y.globalScore&&(d=!0)}d&&n.globalScore>this._config.detectScoreThs?(this.invertFoot(),this._rightFootRecShape=h.refinedFeatures,this._rightFootState=Vo.Detected):r.globalScore>=this._config.detectScoreThs&&(this._leftFootRecShape=h.refinedFeatures,this._leftFootState=Vo.Detected)}else if(this._leftFootState!==Vo.Detection&&this._rightFootState===Vo.Detection){if(c=this.trackFootFeaturesSync(e,this._leftFootState,this._leftFootState==Vo.Detected?this._initShape:this._leftFootRecShape,this._leftFootVis,this._leftFootOcclusions,"LEFT_FOOT"),this._leftFootRecShape=c.refinedFeatures,this._leftFootOcclusions=c.occlusions,this._leftFootMask=c.mask,r=Zo(c.scores,"LEFT_FOOT",this._config.validTrackedKeypThs),this._leftFootVis=r.visibilty,s=this._config.trackScoreThs,this._fastMovements_L&&(s=.1),a=this._reproj_t,this._fastMovements_L&&(a=this._reproj_fast_t),o=tu(this._leftFootRecShape.length/2,"LEFT_FOOT"),this._leftFootVis[o[0]]&&this._leftFootVis[o[1]]&&r.globalScore>=s&&r.totalVisible>=this._config.trackedNumKeypsThs?(t=this.computePoseSync(this._leftFootState,"LEFT_FOOT"),this._leftFootState=Vo.Tracking,t>a&&(this._leftFootState=Vo.Detection)):this._leftFootState=Vo.Detection,h=this.detectFeetSync(e),this._initShape=h.refinedFeatures,n=Zo(h.scores,"RIGHT_FOOT",this._config.detectScoreThs),r=Zo(h.scores,"LEFT_FOOT",this._config.detectScoreThs),d=!1,!this._fastMovements_L&&null!=this._cnnOutputDataInvMask){var g,_=du(this._cnnOutputDataInvMask,this._footDetectorShape,!1);_[0],m=Zo(g=_[1],"LEFT_FOOT",this._config.detectScoreThs),y=Zo(g,"RIGHT_FOOT",this._config.detectScoreThs),r.globalScore>n.globalScore&&r.globalScore>m.globalScore+.1&&y.globalScore>m.globalScore&&(d=!0)}d&&r.globalScore>this._config.detectScoreThs?(this.invertFoot(),this._leftFootRecShape=h.refinedFeatures,this._leftFootState=Vo.Detected):n.globalScore>=this._config.detectScoreThs&&(this._rightFootRecShape=h.refinedFeatures,this._rightFootState=Vo.Detected)}else if((this._leftFootState===Vo.Detection||this._rightFootState===Vo.Detection)&&(c=this.detectFeetSync(e),this._initShape=c.refinedFeatures,r=Zo(c.scores,"LEFT_FOOT",this._config.detectScoreThs),n=Zo(c.scores,"RIGHT_FOOT",this._config.detectScoreThs),r.globalScore>=this._config.detectScoreThs&&(this._leftFootState=Vo.Detected),n.globalScore>=this._config.detectScoreThs&&(this._rightFootState=Vo.Detected),this._rightFootState!=Vo.Detection&&this._leftFootState!=Vo.Detection&&this.bothFeetSamePlaceInit()&&(this._rightFootState==Vo.Detected?this._rightFootState=Vo.Detection:this._leftFootState=Vo.Detection),this._leftFootState==Vo.Detected||this._rightFootState==Vo.Detected)){this._leftFootRecShape=c.refinedFeatures,this._rightFootRecShape=c.refinedFeatures,this._fastMovements_L=!0,this._fastMovements_R=!0;var b=this._poseModule.cwrap("xzimgMatchRecKeypsInit","number",["number"]);null==this._hptrImageBuffer&&(this._hptrImageBuffer=this._poseModule._malloc(e.width*e.height*4)),uu(this._poseModule,e,this._hptrImageBuffer);var w=lu(this._poseModule,this._hptrImageBuffer,e.width,e.height);b(w),this._poseModule._free(w)}this._leftFootState===Vo.Detection&&(this._pose_L=new Yo(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0]))),this._rightFootState==Vo.Detection&&(this._pose_R=new Yo(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,s,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),i=a.crop,o=a.deltaY,u=a.deltaX,l=bt(e),p=mt(l,"float32"),c=kt(p,[1,this._currentHeight,this._currentWidth,3]),h=ft(c,[i],[0],[this._footDetectorConfig.inHeight,this._footDetectorConfig.inWidth]),d=gt(255),f=Mt(h,d),m=null;if(this._footToDetect==wu.Both&&(this._leftFootState===Vo.Tracking||this._rightFootState===Vo.Tracking)){var y=function(e,t,n,r,s,a,i,o){for(var u=e.length/2,l=new Float32Array(2*u),p=0;p<u;p++)l[p]=(e[p]-s)/i,l[p+u]=(e[p+u]-r)/a;for(var c=Xo(l,o),h=c[0],d=c[1],f=c[2]-h,m=c[3]-d,y=c[6]-h,g=c[7]-d,_=f*f+m*m,b=y*y+g*g,w=new Float32Array(n*t),v=0;v<t;v++)for(var T=0;T<n;T++){var S=T-h,k=v-d,N=S*f+k*m,M=S*y+k*g;N>0&&M>0&&N<_&&M<b||(w[v*n+T]=1)}return w}(this._leftFootState===Vo.Tracking?this._leftFootRecShape:this._rightFootRecShape,this._footDetectorConfig.inHeight,this._footDetectorConfig.inWidth,o,u,(this._currentHeight-2*o)/this._footDetectorConfig.inWidth,(this._currentWidth-2*u)/this._footDetectorConfig.inHeight,this._leftFootState===Vo.Tracking?"LEFT_FOOT":"RIGHT_FOOT"),g=Tt(y,"float32");m=kt(g,[1,this._footDetectorConfig.inHeight,this._footDetectorConfig.inWidth,1]),g.dispose()}var _=this._tfFootDetector.predict(f);if(null!=m){var b=St(1,m),w=Kn(_,b);this._cnnOutputDataInvMask=w.dataSync(),b.dispose(),w.dispose();var v=Kn(_,m);_.dispose(),_=v,m.dispose()}var T,S,k=null!==(n=null==_?void 0:_.shape[3])&&void 0!==n?n:this._footDetectorConfig.outChannels,N=null!==(r=null==_?void 0:_.shape[1])&&void 0!==r?r:this._footDetectorConfig.outHeight,M=null!==(s=null==_?void 0:_.shape[2])&&void 0!==s?s:this._footDetectorConfig.outWidth;T=(t=du(_.dataSync(),[1,N,M,k],!1))[0],S=t[1];var x=this._bufferKeypsDet/4;this._poseModule.HEAPF32.subarray(x,x+2*k).set(T),l.dispose(),p.dispose(),d.dispose(),h.dispose(),f.dispose(),c.dispose(),_.dispose();var F=Math.min(this._currentWidth,this._currentHeight),I=F/this._footDetectorConfig.inWidth,A=F/this._footDetectorConfig.inHeight;return this._simToImage_Det=function(e,t,n,r){var s=new Float32Array(6);return s[0]=r,s[1]=0,s[2]=t,s[3]=0,s[4]=n,s[5]=e,s}(o,u,A,I),{refinedFeatures:eu(T,this._simToImage_Det,!1,_.shape[1]),scores:S}},e.prototype.trackFootFeaturesSync=function(e,t,n,r,s,a){var i,o,u,l,p="LEFT_FOOT"==a?this._simToImage_L:this._simToImage_R;if(this._useRecursiveFilter&&t!=Vo.Detected){var c=Int32Array.from(r);this._activeIds.length>0&&(c.forEach((function(e,t){c[t]=0})),this._activeIds.forEach((function(e){c[e]=1})),r.forEach((function(e,t){0==e&&(c[t]=0)})),s&&s.forEach((function(e,t){e>.5&&(r[t]=0)}))),o=(i=pu(this._poseModule,e,this._hptrImageBuffer,n,c))[0],u=i[1],l=i[2],Math.sqrt(u[2]*u[2]+u[3]*u[3])>10?"LEFT_FOOT"==a?this._fastMovements_L=!0:this._fastMovements_R=!0:"LEFT_FOOT"==a?this._fastMovements_L=!1:this._fastMovements_R=!1;var h=hu(n,o,l);"LEFT_FOOT"==a?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"==a&&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=o.length/2,f=0;f<d;f++)n[f]=n[f]+h[0],n[f+d]=n[f+d]+h[1]}else o=n;p=su(n,r,this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight,0,a,this._footFeaturesConfig.normSizeMode?this._footFeaturesConfig.normSizeMode:"",this._footFeaturesConfig.normExtRatio?this._footFeaturesConfig.normExtRatio:.5,this._footFeaturesConfig.normAngleShift?this._footFeaturesConfig.normAngleShift:0);var m=new ImageData(this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight);m=Ho(e,m,p);var y=yu(this._tfFootFeatures,this._footFeaturesConfig,this._poseModule,"LEFT_FOOT"==a?[this._bufferHeatmaps_L]:[this._bufferHeatmaps_R],"LEFT_FOOT"==a?[this._bufferKeypsTrack_L]:[this._bufferKeypsTrack_R],[this._bufRightScores],[m],"LEFT_FOOT"==a?["up_down"]:[""]),g=eu(y.coordinates[0],p,"LEFT_FOOT"==a,this._footFeaturesConfig.outHeight);if("LEFT_FOOT"==a?this._simToImage_L=p:this._simToImage_R=p,this._useRecursiveFilter&&t!=Vo.Detected){var _=Ro(y.scores[0],this._config.validTrackedKeypThs);g=ru(g,_,o,_,0)}return{refinedFeatures:g,scores:y.scores[0],occlusions:y.occlusions[0],mask:y.masks.length>0?y.masks[0]:new Float32Array([]),classes:y.classes.length>0?y.classes[0]:new Float32Array([])}},e.prototype.trackFeetFeaturesSync=function(e,t,n,r,s,a,i,o,u){var l,p,c;if(this._useRecursiveFilter&&t!=Vo.Detected&&n!=Vo.Detected){var h=r.length/2,d=new Int32Array(2*h);d.set(a),d.set(i,h);var f=null;o&&u&&((f=new Float32Array(2*h)).set(o),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>.5&&(d[t]=0)})));var y=pu(this._poseModule,e,this._hptrImageBuffer,function(e,t){for(var n=e.length/2,r=t.length/2,s=n+r,a=new Float32Array(e.length+t.length),i=0;i<n;i++)a[i]=e[i],a[i+s]=e[i+n];for(i=0;i<r;i++)a[i+n]=t[i],a[i+s+n]=t[i+r];return a}(r,s),m),g=y[0];y[1];var _=y[2];l=function(e,t,n){var r=new Float32Array(2*t),s=new Float32Array(2*n),a=e.length/2;t+n!=a&&console.log("ERROR (separateShapes): shapes not correct dims");for(var i=0;i<t;i++)r[i]=e[i],r[i+t]=e[i+a];for(i=0;i<n;i++)s[i]=e[i+t],s[i+n]=e[i+a+t];return[r,s]}(g,h,h),p=l[0],c=l[1];var b=_.slice(0,h),w=_.slice(h,2*h),v=cu(this._poseModule,r,p),T=cu(this._poseModule,s,c);Math.sqrt(v[2]*v[2]+v[3]*v[3])>10?this._fastMovements_L=!0:this._fastMovements_L=!1,Math.sqrt(T[2]*T[2]+T[3]*T[3])>10?this._fastMovements_R=!0:this._fastMovements_R=!1;var S=hu(r,p,b);this._pose_L.translate(S[0]*this._pose_L.t()[2]/this._fx,S[1]*this._pose_L.t()[2]/this._fy,0);var k=hu(s,c,w);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 N=c.length/2,M=0;M<N;M++)s[M]=s[M]+k[0],s[M+N]=s[M+N]+k[1],r[M]=r[M]+S[0],r[M+N]=r[M+N]+S[1]}else p=r,c=s;this._simToImage_L=su(r,a,this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight,0,"LEFT_FOOT",this._footFeaturesConfig.normSizeMode?this._footFeaturesConfig.normSizeMode:"",this._footFeaturesConfig.normExtRatio?this._footFeaturesConfig.normExtRatio:.5,this._footFeaturesConfig.normAngleShift?this._footFeaturesConfig.normAngleShift:0);var x=new ImageData(this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight);x=Ho(e,x,this._simToImage_L),this._simToImage_R=su(s,i,this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight,0,"RIGHT_FOOT",this._footFeaturesConfig.normSizeMode?this._footFeaturesConfig.normSizeMode:"",this._footFeaturesConfig.normExtRatio?this._footFeaturesConfig.normExtRatio:.5,this._footFeaturesConfig.normAngleShift?this._footFeaturesConfig.normAngleShift:0);var F=new ImageData(this._footFeaturesConfig.inWidth,this._footFeaturesConfig.inHeight);F=Ho(e,F,this._simToImage_R),this._debug&&n!=Vo.Detected&&(this._debugInitialized=!0,this._debugImage=F,function(e,t,n,r){for(var s=new Uint8ClampedArray(e*t*4),a=e*t,i=0;i<a;i++){var o=4*i,u=4*i;s[u+0]=1*r[o+0],s[u+1]=1*r[o+1],s[u+2]=1*r[o+2],s[u+3]=255}new ImageData(s,t,e)}(this._footFeaturesConfig.inHeight,this._footFeaturesConfig.inWidth,0,F));var I=yu(this._tfFootFeatures,this._footFeaturesConfig,this._poseModule,[this._bufferHeatmaps_L,this._bufferHeatmaps_R],[this._bufferKeypsTrack_L,this._bufferKeypsTrack_R],[this._bufRightScores,this._bufLeftScores],[x,F],["up_down",""]),A=eu(I.coordinates[0],this._simToImage_L,!0,this._footFeaturesConfig.outHeight),E=eu(I.coordinates[1],this._simToImage_R,!1,this._footFeaturesConfig.outHeight);return this._useRecursiveFilter&&t!=Vo.Detected&&(A=ru(A,Ro(I.scores[0],this._config.validTrackedKeypThs),p,a,0)),this._useRecursiveFilter&&n!=Vo.Detected&&(E=ru(E,Ro(I.scores[1],this._config.validTrackedKeypThs),c,i,0)),{refinedFeatures_L:A,refinedFeatures_R:E,scores_L:I.scores[0],scores_R:I.scores[1],occlusions_L:I.occlusions[0],occlusions_R:I.occlusions[1],mask_L:I.masks.length>0?I.masks[0]:new Float32Array([]),mask_R:I.masks.length>1?I.masks[1]:new Float32Array([]),classes_L:I.classes.length>0?I.classes[0]:new Float32Array([]),classes_R:I.classes.length>1?I.classes[1]:new Float32Array([])}},e.prototype.computePoseSync=function(e,t){var n=this,r=-1,s=this._poseModule.cwrap("xzimgEstimateRigidPose","number",["number","number","number","number","number","number","number","number","number","number","number","number"]);if(e==Vo.Detected||e==Vo.Tracking){var a=1;e==Vo.Detected&&(a=0);var i=3;"LEFT_FOOT"!=t||this._fastMovements_L||(i=1),"RIGHT_FOOT"!=t||this._fastMovements_R||(i=1);var o=new Float32Array(18);"LEFT_FOOT"==t?(o.set(this._pose_L.R()),o.set(this._pose_L.t(),9)):(o.set(this._pose_R.R()),o.set(this._pose_R.t(),9));var u=au(this._poseModule,o),l=("LEFT_FOOT"==t?this._simToImage_L:this._simToImage_R,Float32Array.from([1,0,0,0,1,0]));this._trackHasHeatmaps;var p=au(this._poseModule,l),c=null,h=null,d=new Float32Array(2*this._activeIds.length),f=new Float32Array(3*this._activeIds.length),m="LEFT_FOOT"==t?this._leftFootRecShape:this._rightFootRecShape,y="LEFT_FOOT"==t?this._leftKeyps3D:this._rightKeyps3D,g=m.length/2;this._activeIds.length>0?(this._activeIds.forEach((function(e,t){d[t]=m[e],d[t+n._activeIds.length]=m[e+g]})),c=au(this._poseModule,d),this._activeIds.forEach((function(e,t){f[3*t]=y[3*e],f[3*t+1]=y[3*e+1],f[3*t+2]=y[3*e+2]})),h=au(this._poseModule,f),g=this._activeIds.length):(c=au(this._poseModule,m),h=au(this._poseModule,"LEFT_FOOT"==t?this._leftKeyps3D:this._rightKeyps3D)),-1==(r=s("LEFT_FOOT"==t?this._bufferHeatmaps_L:this._bufferHeatmaps_R,this._footFeaturesConfig.outHeight,this._footFeaturesConfig.outWidth,g,0,p,c,h,a,1,i,u))&&(r=1e4),"LEFT_FOOT"==t?this._pose_L=new Yo(new Float32Array(this._poseModule.HEAPF32.buffer,u,9),new Float32Array(this._poseModule.HEAPF32.buffer,u+9*this._float_size,3)):this._pose_R=new Yo(new Float32Array(this._poseModule.HEAPF32.buffer,u,9),new Float32Array(this._poseModule.HEAPF32.buffer,u+9*this._float_size,3)),p&&this._poseModule._free(p),c&&this._poseModule._free(c),h&&this._activeIds.length>0&&this._poseModule._free(h)}return r},e.prototype.invertFoot=function(){var e,t,n,r,s,a,i;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],s=[this._rightFootState,this._leftFootState],this._leftFootState=s[0],this._rightFootState=s[1],a=[this._rightFootVis,this._leftFootVis],this._leftFootVis=a[0],this._rightFootVis=a[1],i=[this._bufferHeatmaps_L,this._bufferHeatmaps_R],this._bufferHeatmaps_R=i[0],this._bufferHeatmaps_L=i[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=Xo(this._leftFootRecShape,"LEFT_FOOT"),t=e[0],n=e[1],r=e[2],s=e[3],a=e[4],i=e[5],o=e[6],u=e[7],l=Xo(this._rightFootRecShape,"RIGHT_FOOT"),p=l[0],c=l[1],h=l[2],d=l[3],f=l[4],m=l[5],y=l[6],g=l[7],_=this.dst(t,n,o,u)/15;return this.dst(t,n,p,c)<_&&this.dst(r,s,h,d)<_&&this.dst(a,i,f,m)<_&&this.dst(o,u,y,g)<_},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}(),ku={modelFilename:"",featuresFilename:"",objContainer:"",fovY:50,detectScoreThs:.2,trackScoreThs:.4,geometryToDetect:"LAMBORGHINI",filteringLevel:2,filteringShift:.5,validDetectedKeypThs:.2,validTrackedKeypThs:.2,detectNumKeypsThs:3,trackedNumKeypsThs:3,normMode:"",TrackerAngleShift:0,reprojThs:25,activeIds:new Int32Array,computePose:!0,useWasmBackend:!0,subTrackerSymmetric:!1};function Nu(e){return i(this,void 0,void 0,(function(){var t,n,r,s;return o(this,(function(a){switch(a.label){case 0:return"string"!=typeof e?[3,3]:[4,fetch(e)];case 1:if(!(n=a.sent()).ok)throw new Error("HTTP ".concat(n.status,": ").concat(n.statusText));return[4,n.arrayBuffer()];case 2:return t=a.sent(),[3,4];case 3:t=e,a.label=4;case 4:return r=To(new Uint8Array(t)),(s=Object.keys(r)).length>1&&console.warn("XZIMG: Tried to load zip file that has these files inside: ".concat(s,". Only one file is expected.")),[2,r[s[0]]]}}))}))}var Mu,xu=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 Fu(e,t,n){for(var r=0,s=0,a=e.length,i=0,o=e;i<o.length;i++){var u=o[i];r+=t[u],s+=t[u+n]}return new Wo(r/a,s/a)}function Iu(e){return e==Mu.UpperBody||e==Mu.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"}(Mu||(Mu={}));var Au="config.json",Eu=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=Vo.Detection,this._denseVertices=new Float32Array(0),this._bsCoefs=new Float32Array(0),this._geometryType=Mu.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.getDebug=function(){return this._debug},e.prototype.getDebugImage=function(){return this._debugInitialized?this._debugImage:null},e.prototype.isDetected=function(){return this._trackingState===Vo.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.getOcclusions=function(){return this._occlusions},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.isMirrored=function(){return""!=this._flipMode},e.prototype.getMask=function(e,t){var n=new Float32Array(e*t),r=[this._trackerConfig.outHeight,this._trackerConfig.outWidth],s=Float32Array.from(this._simCropToImage),a=e/this._currentWidth,i=t/this._currentHeight;return s[0]=a*s[0],s[1]=a*s[1],s[3]=i*s[3],s[4]=i*s[4],s[2]=a*s[2],s[5]=i*s[5],s=zo(s),this.isMirrored()&&(s[3]=-s[3],s[4]=-s[4],s[5]=-s[5]+(r[0]-1)),this._objectMask&&jo(this._objectMask,new Float32Array(r),n,new Float32Array([t,e]),s),n},e.prototype.getInterpolatedPose=function(){return this._poseManager.getInterpolatedPose()},e.prototype.isInitialized=function(){return this._initialized},e.prototype.getReprojError=function(){return this._reprojError},e.prototype.initialize=function(e,t,n){return i(this,void 0,void 0,(function(){var n,r,s,i,u,l,p,h,d,f,m,y,g,_,b,w,v,T,S,k,N,M,x,F,I,A,E,O,D,C,R,L,P=this;return o(this,(function(o){switch(o.label){case 0:if(null==e)throw"Invalid parameter";return this._config=t?a(a({},ku),t):ku,!0!==(null==t?void 0:t.useWasmBackend)?[3,2]:($a("./xzimg/"),[4,Ct("wasm")]);case 1:return o.sent(),[3,6];case 2:return!0!==(null===(D=null==t?void 0:t.wasmBackend)||void 0===D?void 0:D.enable)?[3,4]:($a({"tfjs-backend-wasm.wasm":null===(C=t.wasmBackend)||void 0===C?void 0:C.tfjsBackendWasmPath,"tfjs-backend-wasm-simd.wasm":null===(R=t.wasmBackend)||void 0===R?void 0:R.tfjsBackendWasmSimdPath,"tfjs-backend-wasm-threaded-simd.wasm":null===(L=t.wasmBackend)||void 0===L?void 0:L.tfjsBackendWasmThreadedPath}),[4,Ct("wasm")]);case 3:return o.sent(),[3,6];case 4:return[4,Ct("webgl")];case 5:o.sent(),o.label=6;case 6:return this.release(),this._videoManager=e,this._poseManager=new vu(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 Mu.Lamborghini;if("HORSE"===e)return Mu.Horse;if("WATSON-CAN"===e)return Mu.WatsonCan;if("MARTELL-BOTTLE"===e)return Mu.MartellBottle;if("NECKLACE"===e)return Mu.Necklace;if("WRIST"===e)return Mu.Wrist;if("HAND"===e)return Mu.Hand;if("UPPER-BODY"===e)return Mu.UpperBody;if("FULL-BODY"===e)return Mu.FullBody;if("CAN-KIVISENSE"===e)return Mu.CanKivisense;if("TOY-TRUCK"===e)return Mu.ToyTruck;if("CHIVAS"===e)return Mu.Chivas;if("CHIVAS-LARGE"===e)return Mu.ChivasLarge;if("LION"===e)return Mu.Lion;if("BARTENDER"===e)return Mu.Bartender;if("WCBOTTLE"===e)return Mu.Wcbottle;if("EQA"===e)return Mu.EQA;if("FACE"===e)return Mu.Face}return Mu.Lamborghini}(this._config.geometryToDetect),n=this._config.poseEstimationWasmFilename instanceof ArrayBuffer?{wasmBinary:this._config.poseEstimationWasmFilename}:{locateFile:function(e,t){return P._config.poseEstimationWasmFilename||t+e}},[4,c(n)];case 7:return(r=o.sent()).wasmBinary&&(r.wasmBinary=null),[4,No(this._config.modelFilename,Au)];case 8:return s=o.sent(),[4,No(this._config.featuresFilename,Au)];case 9:return i=o.sent(),[4,_u(this._config.objContainer)];case 10:return u=o.sent(),this._config.pdmContainer?[4,Nu(this._config.pdmContainer)]:[3,12];case 11:l=o.sent(),o.label=12;case 12:return this._config.subTrackerFilename&&""!=this._config.subTrackerFilename?[4,No(this._config.subTrackerFilename,Au)]:[3,14];case 13:p=o.sent(),o.label=14;case 14:if(this._poseModule=r,this._geometryObjModel=u,this._tfKeypointsDetector=s.graphModel,this._detectorConfig=s.config,this._tfKeypointsTracker=i.graphModel,this._trackerConfig=i.config,h=vt([1,this._detectorConfig.inHeight,this._detectorConfig.inWidth,3]),d=this._tfKeypointsDetector.predict(h),this._detectorOutDims=d.shape,d.dispose(),this._detectorConfig.inHeight===this._trackerConfig.inHeight&&this._detectorConfig.inWidth===this._trackerConfig.inWidth||(h.dispose(),h=vt([1,this._trackerConfig.inHeight,this._trackerConfig.inWidth,3])),(d=this._tfKeypointsTracker.predict(h))instanceof Array?(this._debug&&d.forEach((function(e){return console.log(e.shape)})),d.forEach((function(e){return e.dispose()})),this._trackerOutDims=[1,this._trackerConfig.outHeight,this._trackerConfig.outWidth,this._trackerConfig.outChannels]):(this._trackerOutDims=d.shape,d.dispose()),h.dispose(),this._debug&&(console.log(this._detectorConfig),console.log(this._trackerConfig),console.log("(DEBUG) XZIMG BACKEND",Rt()),console.log("_trackerOutDims",this._trackerOutDims)),this._activeIds=this._config.activeIds,this._trackHasHeatmaps=Hi(this._trackerConfig),O=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,s=((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]))[3*4]+r[18])/2,a=(r[13]+r[19])/2,i=(r[14]+r[20])/2,o=0;o<r.length/3;o++)r[3*o]-=s,r[3*o+1]-=a,r[3*o+2]-=i;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)if(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 p=[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];p.forEach((function(e,t){p[t]=u[e]})),u=p}l=[]}else if(190==n)for(o=0;o<190;o++)u.push(o);else if(196==n)for(o=0;o<196;o++)u.push(o);else if(178==n)for(o=0;o<178;o++)u.push(o);else if(227==n)for(o=0;o<227;o++)u.push(o);else if(204==n)for(o=0;o<204;o++)u.push(o);var c=u.length,h=new Float32Array(3*c);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]}(this._geometryObjModel.vertices,this._geometryType,this._trackerConfig.outChannels),this._keypsVts=O[0],this._refKeypsVts=O[1],f=Math.max(this._detectorOutDims[1]*this._detectorOutDims[2]*this._detectorOutDims[3]),this._trackHasHeatmaps&&(f=Math.max(this._detectorOutDims[1]*this._detectorOutDims[2]*this._detectorOutDims[3],this._trackerOutDims[1]*this._trackerOutDims[2]*this._trackerOutDims[3])),m=Math.max(this._detectorOutDims[3],this._trackerOutDims[3]),this._bufferHeatmaps=this._poseModule._malloc(f*this._float_size),this._bufferKeypsDet=this._poseModule._malloc(2*this._detectorOutDims[3]*this._float_size),this._bufferKeypsTrack=this._poseModule._malloc(2*this._trackerOutDims[3]*this._float_size),this._bufferFeatureScores=this._poseModule._malloc(m*this._float_size),this._bufInOutPose=this._poseModule._malloc(21*this._float_size),l?(y=new Uint8Array(l),this._bufferPdmModel=this._poseModule._malloc(y.byteLength),this._poseModule.HEAPU8.set(y,this._bufferPdmModel),g={rigid_pose:0,num_iterations:1,filter_strength:5,reg_w:10,fovy_d:50,width:640,height:480,num_features:this._geometryType==Mu.Face?this._trackerOutDims[3]:-1,modelContent:this._bufferPdmModel,modelContentSize:y.byteLength,modelEncoding:this._geometryType==Mu.Face?2:1,bsMode:0},_=this._poseModule._malloc(48),this._poseModule.setValue(_+0,g.rigid_pose,"i32"),this._poseModule.setValue(_+4,g.num_iterations,"i32"),this._poseModule.setValue(_+8,g.filter_strength,"i32"),this._poseModule.setValue(_+12,g.reg_w,"float"),this._poseModule.setValue(_+16,g.fovy_d,"float"),this._poseModule.setValue(_+20,g.width,"i32"),this._poseModule.setValue(_+24,g.height,"i32"),this._poseModule.setValue(_+28,g.num_features,"i32"),this._poseModule.setValue(_+32,g.modelContent,"*"),this._poseModule.setValue(_+36,g.modelContentSize,"i32"),this._poseModule.setValue(_+40,g.modelEncoding,"i32"),this._poseModule.setValue(_+44,g.bsMode,"i32"),b=this._poseModule.cwrap("xzimgPoseEstimationInitialize","number",["number"]),w=b(_),this._debug&&console.log("PDM initialisation: ",w),this._poseModule._free(_),this._poseModule._free(this._bufferPdmModel),this._nonRigidInitialized=!0):null==this._bufKeyps3D&&(this._bufKeyps3D=this._poseModule._malloc(this._keypsVts.length*this._float_size),this._poseModule.HEAPF32.set(this._keypsVts,this._bufKeyps3D/4),(v=Array.from(this._keypsVts)).forEach((function(e,t){t%3==0&&(v[t]=-v[t])})),this._bufMirroredKeyps3D=this._poseModule._malloc(v.length*this._float_size),this._poseModule.HEAPF32.set(v,this._bufMirroredKeyps3D/4)),p&&(this._tfSubTracker=p.graphModel,this._subTrackerConfig=p.config,T=this._config.subTrackerSymmetric?2:1,S=vt([T,this._subTrackerConfig.inHeight,this._subTrackerConfig.inWidth,3]),k=this._tfSubTracker.predict(S),this._subTrackerOutDims=k.shape,k.dispose(),S.dispose(),N=Math.max(this._subTrackerOutDims[1]*this._subTrackerOutDims[2]*this._subTrackerOutDims[3]),this._bufSubTrackerHmaps=this._poseModule._malloc(N*this._float_size),this._bufSubTrackerHmapsSym=this._poseModule._malloc(N*this._float_size),this._config.subTrackerObjectType)){for(M=this._geometryObjModel.faces.length/3,this._bufModelTriangles=this._poseModule._malloc(9*M*this._float_size),x=new Float32Array(9*M),F=0;F<M;F++)I=this._geometryObjModel.faces[3*F],A=this._geometryObjModel.faces[3*F+1],E=this._geometryObjModel.faces[3*F+2],x[9*F]=this._geometryObjModel.vertices[3*I],x[9*F+1]=this._geometryObjModel.vertices[3*I+1],x[9*F+2]=this._geometryObjModel.vertices[3*I+2],x[9*F+3]=this._geometryObjModel.vertices[3*A],x[9*F+4]=this._geometryObjModel.vertices[3*A+1],x[9*F+5]=this._geometryObjModel.vertices[3*A+2],x[9*F+6]=this._geometryObjModel.vertices[3*E],x[9*F+7]=this._geometryObjModel.vertices[3*E+1],x[9*F+8]=this._geometryObjModel.vertices[3*E+2];this._poseModule.HEAPF32.set(x,this._bufModelTriangles/4)}return this._initialized=!0,[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=Vo.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=e;null==e&&(n=this._videoManager.getLastBuffer()),null!=n?(n.width===this._currentWidth&&n.height===this._currentHeight||(this._currentWidth=n.width,this._currentHeight=n.height,t=Yo.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()),this.trackGeometrySync(n)):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,s=Iu(this._geometryType)||this._geometryType==Mu.Wrist||this._geometryType==Mu.Hand||this._geometryType==Mu.Face;if(this._trackingState===Vo.Detection){var a=this._poseModule.cwrap("xzimgMatchRecKeypsInit","number",["number"]);null==this._hptrImageBuffer&&(this._hptrImageBuffer=this._poseModule._malloc(e.width*e.height*4)),uu(this._poseModule,e,this._hptrImageBuffer);var i=lu(this._poseModule,this._hptrImageBuffer,e.width,e.height);a(i),this._poseModule._free(i);var o=this.detectGeometrySync(e),u=o.refinedFeatures,l=o.scores;this._keyps2D=u;var p=Co(l,this._config.validDetectedKeypThs);this._visibility=p.visibilty,this._trackingState=Vo.Detection,p.totalVisible>=this._config.detectNumKeypsThs&&p.globalScore>=this._config.detectScoreThs&&(this._geometryType==Mu.Wrist&&(this._flipMode="","left"==(t=this._keyps2D,n=p.visibilty,(9==t.length/2?n[0]&&n[1]?Uo.CreateFromPoints(new Wo(t[0],t[9]),new Wo(t[1],t[10])):Uo.CreateFromPoints(new Wo(t[1],t[10]),new Wo(t[6],t[15])):Uo.CreateFromPoints(new Wo(t[30],t[211]),new Wo(t[163],t[344]))).x>0?"left":"right")&&(this._flipMode="up_down")),s?this._trackingState=Vo.Detected:(this._reprojError=this.computePoseSync(this._trackingState,this._geometryType),this._reprojError>0&&this._reprojError<this._config.reprojThs&&(this._trackingState=Vo.Detected)))}else{var c=this.trackGeometryFeaturesSync(e,this._trackingState,this._keyps2D,this._visibility,this._geometryType);this._keyps2D=c.imageFilteredKeyps,this._cropKeyps2D=c.cropKeyps,this._occlusions=c.occlusions,this._objectMask=c.mask;var h=Co(c.scores,this._config.validTrackedKeypThs);if(this._visibility=h.visibilty,1==this._visibility.length){var d=new Int32Array(this._keyps2D.length/2);d.forEach((function(e,t){d[t]=h.visibilty[0]})),this._visibility=d}var f=Po(this._geometryType,this._keyps2D.length/2);Array.isArray(f[0])&&(f[0]=f[0][0]),Array.isArray(f[1])&&(f[1]=f[1][0]);var m=1;if(this._geometryType!=Mu.FullBody&&this._geometryType!=Mu.UpperBody||(m=this._visibility[f[0]]&&this._visibility[f[1]]),this._debug&&(console.log("globalScore",h.globalScore),console.log("totalVisible",h.totalVisible)),m&&h.totalVisible>=this._config.trackedNumKeypsThs&&h.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=Vo.Detection:this._trackingState=Vo.Tracking):this._trackingState=Vo.Tracking,this._tfSubTracker&&this._trackingState==Vo.Tracking){this._debug&&console.log("tracking subgeomerty");var y=this.trackSubGeometrySync(e,this._keyps2D,this._visibility);if(this._subTrackerKeyps&&this._subTrackerKeyps.length>0?this._subTrackerKeyps.forEach((function(e,t){r._subTrackerKeyps[t]=Go(y.subTrackerKeyps[t],y.subTrackerVisibility[t],e,r._subTrackerVis[t],0)})):this._subTrackerKeyps=y.subTrackerKeyps,this._subTrackerScores=y.subTrackerKeypsScores,this._subTrackerVis=y.subTrackerVisibility,"ear"==this._config.subTrackerObjectType){var g=new Float32Array([0,0,0]);g=this._pose.transformInv(g);for(var _=this._poseModule.cwrap("xzimgGeometryGetModelIntersection","number",["number","number","number","number"]),b=0;b<this._subTrackerKeyps.length;b++){var w=0==b?2:3,v=this._keypsVts[3*w]-1.45;1==b&&(v=this._keypsVts[3*w]+1.45);var T=this._keypsVts[3*w+1]-.38,S=this._keypsVts[3*w+2]-1.6,k=Math.sqrt((v-g[0])*(v-g[0])+(T-g[1])*(T-g[1])+(S-g[2])*(S-g[2])),N=new Float32Array([(v-g[0])/k,(T-g[1])/k,(S-g[2])/k]);this._debug&&(console.log("dir",N),console.log("camCenter",g),console.log("numTriangles",this._geometryObjModel.faces.length/3));var M=this._poseModule._malloc(3*this._float_size),x=M/4,F=this._poseModule.HEAPF32.subarray(x,x+3);F.set(g);var I=this._poseModule._malloc(3*this._float_size);x=I/4,(F=this._poseModule.HEAPF32.subarray(x,x+3)).set(N);var A=_(M,I,this._bufModelTriangles,this._geometryObjModel.faces.length/3);if(this._poseModule._free(M),this._poseModule._free(I),1==A){var E=Go(this._pose.project(new Float32Array([v,T,S]),Yo.getCameraMat(this._config.fovY,this._currentWidth,this._currentHeight)),new Int32Array([1]),new Float32Array([this._subTrackerKeyps[b][3],this._subTrackerKeyps[b][7]]),new Int32Array([1]),0);this._subTrackerKeyps[b][3]=E[0],this._subTrackerKeyps[b][7]=E[1]}}}}}else this._trackingState=Vo.Detection}(this._trackingState===Vo.Detection||this._trackingState===Vo.Detected&&s)&&(this._pose=new Yo(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0])),this._pose.setTrackingState(Vo.Detection)),this._pose.setTrackingState(this._trackingState),this._poseManager.setPose(this._pose)},e.prototype.detectGeometrySync=function(e){var t,n,r,s=function(e,t,n,r){var s,a;void 0===n&&(n="center"),void 0===r&&(r=[-1,-1]);var i=0,o=0;return"custom"==n&&(r[1]=t-r[1],s=function(e,t,n){var r=0,s=0;return t>n?(r=Math.max(e[0]-n/2,0))+n>t&&(r=t-n):(s=Math.max(e[1]-t/2,0))+t>n&&(s=n-t),[r,s]}(r,e,t),i=s[0],o=s[1]),e>t?("top"==n?i=0:"bottom"==n?i=e-t:"center"==n&&(i=(e-t)/2),a=[(o=0)/t,i/e,1,(i+t)/e]):("top"==n?o=0:"bottom"==n?o=t-e:"center"==n&&(o=(t-e)/2),a=[o/t,(i=0)/e,(o+e)/t,1]),{crop:a,deltaY:o,deltaX:i}}(this._currentWidth,this._currentHeight),a=s.crop,i=s.deltaY,o=s.deltaX,u=bt(e),l=mt(u,"float32"),p=kt(l,[1,this._currentHeight,this._currentWidth,3]),c=ft(p,[a],[0],[this._detectorConfig.inHeight,this._detectorConfig.inWidth]),h=gt(255),d=Mt(c,h),f=this._tfKeypointsDetector.predict(d),m=f.dataSync(),y=this._poseModule.cwrap("xzimgGetHeatmapsLocations","number",["number","number","number","number","number","number","number","number"]),g=null!==(t=null==f?void 0:f.shape[3])&&void 0!==t?t:this._detectorConfig.outChannels,_=null!==(n=null==f?void 0:f.shape[1])&&void 0!==n?n:this._detectorConfig.outHeight,b=null!==(r=null==f?void 0:f.shape[2])&&void 0!==r?r:this._detectorConfig.outWidth,w=g*_*b,v=this._bufferHeatmaps/4;this._poseModule.HEAPF32.subarray(v,v+w).set(m),y(this._bufferHeatmaps,_,b,g,0,1,this._bufferKeypsDet,this._bufferFeatureScores);var T=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufferKeypsDet,2*g),S=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufferFeatureScores,g);u.dispose(),l.dispose(),h.dispose(),c.dispose(),d.dispose(),p.dispose(),f.dispose();var k=Math.min(this._currentWidth,this._currentHeight),N=k/this._detectorConfig.inWidth,M=k/this._detectorConfig.inHeight;return this._simCropToImage=function(e,t,n,r){var s=new Float32Array(6);return s[0]=r,s[1]=0,s[2]=t,s[3]=0,s[4]=n,s[5]=e,s}(i,o,M,N),{refinedFeatures:Lo(T,this._simCropToImage),scores:S}},e.prototype.trackGeometryFeaturesSync=function(e,t,n,r,s){var a,i,o,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 p,c,h=new Float32Array([0,0]);if(t!=Vo.Detected){if(i=(a=pu(this._poseModule,e,this._hptrImageBuffer,n,l))[0],o=a[1],u=a[2],Math.sqrt(o[2]*o[2]+o[3]*o[3])>10?this._fastMvt=!0:this._fastMvt=!1,s==Mu.FullBody?[7,8,9,10,13,14,15,16].forEach((function(e){u[e]=0})):s==Mu.UpperBody?[7,8,9,10].forEach((function(e){u[e]=0})):s==Mu.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,s,a,i){void 0===s&&(s=null);for(var o=new Float32Array(2),u=n.length/2,l=0,p=0;p<u;p++)(null==s||s[p]>0)&&(o[0]+=r[p]-n[p],o[1]+=r[p+u]-n[p+u],l+=1);l>0&&(o[0]/=l,o[1]/=l);var c=t/4,h=new Float32Array(18);return h.set(e.HEAPF32.subarray(c,c+18)),h[9]+=o[0]*h[11]/a,h[10]+=o[1]*h[11]/i,e.HEAPF32.set(h,t/4),o}(this._poseModule,this._bufInOutPose,n,i,u,this._fx,this._fy),s==Mu.Necklace)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;if("WATSON-CAN"==s||"CAN-KIVISENSE"==s||"TOY-TRUCK"==s||"CHIVAS"==s||"CHIVAS-LARGE"==s||"LION"==s||"BARTENDER"==s||"WCBOTTLE"==s||"EQA"==s||"MARTELL-BOTTLE"==s){var m=this._pose.project(this._refKeypsVts,Yo.getCameraMat(this._config.fovY,this._currentWidth,this._currentHeight));p=-Math.atan2(m[1]-m[3],m[2]-m[0]),"EQA"==s&&(p=0);var y=this._pose.project(this._keypsVts,Yo.getCameraMat(this._config.fovY,this._currentWidth,this._currentHeight));for(c=new Float32Array(y.length),f=0;f<c.length/2;f++)c[f]=y[2*f],c[f+c.length/2]=y[2*f+1]}var g=Float32Array.from(n),_=i.length/2;for(f=0;f<_;f++)g[f]+=h[0],g[f+_]+=h[1];Iu(s)?this._simCropToImage=function(e,t,n,r,s){var a,i,o,u=t.length/2,l=Array(5),p=new Array(5);if(7==u)l[0]=n[0]>0?1:0,p[0]=new xu(t[0],t[u]),l[1]=n[3]>0&&n[4]>0?1:0,p[1]=new xu((t[3]+t[4])/2,(t[3+u]+t[4+u])/2),l[2]=n[5]>0&&n[6]>0?1:0,p[2]=new xu((t[5]+t[6])/2,(t[5+u]+t[6+u])/2),l[3]=n[1]>0?1:0,p[3]=new xu(t[1],t[1+u]),l[4]=n[2]>0?1:0,p[4]=new xu(t[2],t[2+u]);else{var c=15==u?13:17,h=15==u?14:18;l[0]=n[0]>0?1:0,p[0]=new xu(t[0],t[u]),l[1]=n[c]>=0?1:0,p[1]=new xu(t[c],t[c+u]),l[2]=n[h]>=0?1:0,p[2]=new xu(t[h],t[h+u]),l[3]=n[1]>0?1:0,p[3]=new xu(t[1],t[1+u]),l[4]=n[2]>0?1:0,p[4]=new xu(t[2],t[2+u])}if("FULL-BODY"==e)if(l[1]>0&&l[2]>0)a=p[2],i=-Math.atan2(p[2].y-p[1].y,p[1].x-p[2].x),i+=Math.PI/2,o=2*p[2].Dist(p[1])*2.35;else if(l[0]>0&&l[1]>0)(a=p[1]).y+=2.24*(p[1].y-p[0].y),i=-Math.atan2(p[1].y-p[0].y,p[0].x-p[1].x),i+=Math.PI/2,o=2*p[0].Dist(p[1])*5.3;else if(l[0]>0&&l[2]>0)a=p[2],i=-Math.atan2(p[2].y-p[0].y,p[0].x-p[2].x),i+=Math.PI/2,o=2*p[0].Dist(p[2])*1.64;else{if(!(l[0]>0&&l[3]>0&&l[4]>0))return 0;var d=p[3].Dist(p[4]);(a=p[0]).y+=3*d,i=-Math.atan2(p[4].y-p[3].y,p[3].x-p[4].x),o=2*d*14}else if(console.log(l),l[1]>0&&l[2]>0)a=p[1],i=-Math.atan2(p[2].y-p[1].y,p[1].x-p[2].x),i+=Math.PI/2,o=2*p[2].Dist(p[1])*1.2;else if(l[0]>0&&l[1]>0)a=p[1],i=-Math.atan2(p[1].y-p[0].y,p[0].x-p[1].x),i+=Math.PI/2,o=2*p[0].Dist(p[1])*2.6;else if(l[0]>0&&l[2]>0)a=new xu(p[2].x+.75*(p[0].x-p[2].x),p[2].y+.75*(p[0].y-p[2].y)),i=-Math.atan2(p[2].y-p[0].y,p[0].x-p[2].x),i+=Math.PI/2,o=2*p[0].Dist(p[2])*.8;else{if(!(l[0]>0&&l[3]>0&&l[4]>0))return 0;d=p[3].Dist(p[4]),(a=p[0]).y+=5.5*d,i=-Math.atan2(p[4].y-p[3].y,p[3].x-p[4].x),o=2*d*11}for(var f=0,m=0;m<u;m++){var y=new xu(t[m],t[m+u]).Dist(a);n[m]>0&&y>f&&(f=y)}o=Math.max(o,2*f);var g=Math.cos(i),_=Math.sin(i),b=(o+.1*o)/Math.max(r[0],r[1]),w=(r[1]-1)/2,v=(r[0]-1)/2,T=a.x-(g*b*w-_*b*v),S=a.y-(_*b*w+g*b*v);if(null!=s){var k=.8;b=(1-k)*b+k*s[7],T=(1-k)*T+k*s[2],S=(1-k)*S+k*s[5],i=(1-k)*i+k*s[6],g=Math.cos(i),_=Math.sin(i)}return[g*b,-_*b,T,_*b,g*b,S,i,b]}(s,void 0===c?i:c,r,[this._trackerConfig.inWidth,this._trackerConfig.inHeight],t==Vo.Detected||this._fastMvt?null:this._simCropToImage):s==Mu.Face?this._simCropToImage=function(e,t,n,r,s){var a=e.length/2,i=Do(e,t,a),o=new Wo((i[0]+i[1])/2,(i[2]+i[3])/2),u=0,l=0,p=.3;if(19==a||21==a){var c=[15,16,17,18];21==a&&(c=[17,18,19,20]),0!=t[17]&&0!=t[20]||(c=[18,19]),0!=t[18]&&0!=t[19]||(c=[17,20]),o=new Wo(0,0),c.forEach((function(t){o.x+=e[t],o.y+=e[t+a]})),o.x/=c.length,o.y/=c.length;var h=new Wo(e[8],e[8+a]),d=new Wo(e[13],e[13+a]);21==a&&(h=new Wo(e[10],e[10+a]),d=new Wo(e[15],e[15+a])),l=1.57075-Math.atan2(d.y-h.y,h.x-d.x);for(var f=0;f<a;f++){var m=new Wo(e[f],e[f+a]).Dist(o);t[f]>0&&m>u&&(u=m)}u*=2,p=.3}else{var y=27,g=62,_=66;22==a&&(y=9,g=18,_=20),24==a&&(y=9,g=20,_=22);var b=void 0;5==a?(b=new Wo(.5*(e[0]+e[1]),.5*(e[0+a]+e[1+a])),g=3,_=4):b=new Wo(e[y],e[y+a]);var w=new Wo(.5*(e[g]+e[_]),.5*(e[g+a]+e[_+a]));if(l=1.57075-Math.atan2(w.y-b.y,b.x-w.x),u=Math.max(i[1]-i[0],i[3]-i[2]),s&&"face_center"==s){o=new Wo((b.x+w.x)/2,(b.y+w.y)/2);var v=0;for(f=0;f<a;f++)m=new Wo(e[f],e[f+a]).Dist(o),t[f]>0&&m>v&&(v=m);u=2*v}5==a&&(u=2*(i[1]-i[0])),22==a&&(p=.15)}var T=new Ko(o.x-u/2,o.y-u/2,u,u),S=Math.cos(l),k=Math.sin(l),N=(T.w+p*T.w)/Math.max(n[0],n[1]),M=n[1]/2,x=n[0]/2,F=o.x-(S*N*M-k*N*x),I=o.y-(k*N*M+S*N*x);if(null!=r){var A=.8;F=A*F+(1-A)*r[2],I=A*I+(1-A)*r[5],N=.3*N+.7*r[7],Math.abs(l-r[6])<1&&(l=.3*l+.7*r[6]),S=Math.cos(l),k=Math.sin(l)}return[S*N,-k*N,F,k*N,S*N,I,l,N]}(void 0===c?g:c,r,[this._trackerConfig.inWidth,this._trackerConfig.inHeight],t==Vo.Detected||this._fastMvt?null:this._simCropToImage,this._config.normMode):s==Mu.Wrist?this._simCropToImage=function(e,t,n,r,s,a,i){void 0===a&&(a=1),void 0===i&&(i=0);var o,u,l=e.length/2,p=Do(e,t,l),c=Po("WRIST",l),h=c[0],d=c[1];o=Array.isArray(h)?Fu(h,e,l):new Wo(e[h],e[h+l]),u=Array.isArray(d)?Fu(d,e,l):new Wo(e[d],e[d+l]);var f=-Math.atan2(u.y-o.y,o.x-u.x),m=(p[1]+p[0])/2,y=(p[3]+p[2])/2,g=1.5*o.Dist(u);9==l?(f=3.1415-Math.atan2(o.y-u.y,u.x-o.x),!t[0]&&t[1]&&t[6]&&(m=e[1],y=e[10],g=2*Math.sqrt(Math.pow(e[6]-m,2)+Math.pow(e[15]-m,2)))):g=Jo(e,t,-(f+=i));var _=Math.cos(f),b=Math.sin(f),w=(g+=a*g)/Math.max(n[0],n[1]),v=n[1]/2,T=n[0]/2,S=m-(_*w*v-b*w*T),k=y-(b*w*v+_*w*T);if(null!=r){var N=.5;S=N*S+.5*r[2],k=N*k+.5*r[5],w=N*w+.5*r[7],Math.abs(f-r[6])<1&&(f=N*f+.5*r[6]),_=Math.cos(f),b=Math.sin(f)}return[_*w,-b*w,S,b*w,_*w,k,f,w]}(void 0===c?i:c,r,[this._trackerConfig.inWidth,this._trackerConfig.inHeight],t==Vo.Detected||this._fastMvt?null:this._simCropToImage,this._config.normMode,this._trackerConfig.normExtRatio?this._trackerConfig.normExtRatio:1,this._config.TrackerAngleShift):s==Mu.Hand?this._simCropToImage=function(e,t,n,r,s){var a=e.length/2,i=Do(e,t,a),o=Math.max(i[1]-i[0],i[3]-i[2]),u=$o("HAND",e),l=u[0],p=u[1],c=u[2];c+=3.1415,9==a?t[3]&&t[6]&&(l=.5*(e[3]+e[6]),p=.5*(e[3+a]+e[6+a]),t[1]&&(o=2*Math.sqrt(Math.pow(e[1]-l,2)+Math.pow(e[1+a]-l,2)))):(o=Math.max(i[1]-i[0],i[3]-i[2]),l=(i[1]+i[0])/2,p=(i[3]+i[2])/2);var h=Math.cos(c),d=Math.sin(c),f=(o+=1.2*o)/Math.max(n[0],n[1]),m=n[1]/2,y=n[0]/2,g=l-(h*f*m-d*f*y),_=p-(d*f*m+h*f*y);if(null!=r){var b=.9;g=b*g+(1-b)*r[2],_=b*_+(1-b)*r[5],f=.3*f+.7*r[7],Math.abs(c-r[6])<1&&(c=.3*c+.7*r[6]),h=Math.cos(c),d=Math.sin(c)}return[h*f,-d*f,g,d*f,h*f,_,c,f]}(void 0===c?i:c,r,[this._trackerConfig.inWidth,this._trackerConfig.inHeight],t==Vo.Detected||this._fastMvt?null:this._simCropToImage,this._config.normMode):this._simCropToImage=function(e,t,n,r,s,a){var i,o,u=e.length/2;void 0===a&&((i=$o(s,e))[0],i[1],a=i[2]),o=Oo(e,u);var l=Math.cos(a),p=Math.sin(a),c=Math.sqrt((o[1]-o[0])*(o[1]-o[0])+(o[3]-o[2])*(o[3]-o[2])),h=.3;"NECKLACE"==s&&(h=.5),"MARTEL-BOTTLE"==s&&(h=.2),"EQA"==s&&(h=.2),"BARTENDER"==s&&(h=.2);var d=(c+=h*c)/Math.max(n,t),f=(t-1)/2,m=(n-1)/2,y=(o[0]+o[1])/2-(l*d*f-p*d*m),g=(o[2]+o[3])/2-(p*d*f+l*d*m);if(null!=r){if("NECKLACE"==s){var _=.9;y=_*y+(1-_)*r[2],g=_*g+(1-_)*r[5],d=.3*d+.7*r[7],Math.abs(a-r[6])<1&&(a=.3*a+.7*r[6])}else{var b=Math.sqrt((y-r[2])*(y-r[2])+(g-r[5])*(g-r[5])),w=1;b>20&&(w=.1),b>=10&&b<=20&&(w=1-.09*(b-5)),y=(1-w)*y+w*r[2],g=(1-w)*g+w*r[5],a=Math.abs(a-r[6])>1?(1-w)*a-w*r[6]:(1-w)*a+w*r[6],d=(1-w)*d+w*r[7]}l=Math.cos(a),p=Math.sin(a)}return[l*d,-p*d,y,p*d,l*d,g,a,d]}(void 0===c?i:c,this._trackerConfig.inWidth,this._trackerConfig.inHeight,t==Vo.Detected||this._fastMvt?null:this._simCropToImage,s,p);var b=new ImageData(this._trackerConfig.inWidth,this._trackerConfig.inHeight);b=Ho(e,b,this._simCropToImage),this._debug&&t!=Vo.Detected&&(this._debugInitialized=!0,this._debugImage=b);var w=yu(this._tfKeypointsTracker,this._trackerConfig,this._poseModule,[this._bufferHeatmaps],[this._bufferKeypsTrack],[this._bufferFeatureScores],[b],[this._flipMode]);w.masks[0]&&this._debug&&(console.log("masks",w.masks[0]),this._debugInitialized=!0,this._debugImage=function(e,t,n,r){for(var s=new Uint8ClampedArray(65536),a=0;a<16384;a++){for(var i=1*a,o=r[i],u=1;u<1;u++){var l=r[i+u];o=Math.max(o,l)}var p=4*a;s[p+0]=Math.round(255*(1-o)),s[p+1]=Math.round(255*(1-o)),s[p+2]=Math.round(255*(1-o)),s[p+3]=255}return new ImageData(s,128,128)}(0,0,0,w.masks[0]));var v=Lo(w.coordinates[0],this._simCropToImage,this._flipMode,new Int32Array([this._trackerConfig.outHeight,this._trackerConfig.outWidth]));if(t!=Vo.Detected){var T=new Int32Array(w.coordinates[0].length/2);if(T.forEach((function(e,t){T[t]=1})),"scores"in w&&w.scores.length>0&&(T=Ro(w.scores[0],this._config.validTrackedKeypThs)),s==Mu.Face&&!this._nonRigidInitialized){var S=this._pose.project(this._keypsVts,Yo.getCameraMat(this._config.fovY,this._currentWidth,this._currentHeight)),k=v.length/2;for(f=0;f<k;f++)0==T[f]&&(T[f]=1,v[f]=S[2*f],v[f+k]=S[2*f+1])}v=Go(v,T,i,r,0,s==Mu.Wrist)}var N;return N="scores"in w&&w.scores.length>0?w.scores[0]:w.classes[0],{imageFilteredKeyps:v,cropKeyps:w.coordinates[0],scores:N,occlusions:w.occlusions[0],mask:w.masks[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 s=qo(t,new Int32Array([this._subTrackerConfig.inWidth,this._subTrackerConfig.inHeight]),this._config.subTrackerIds,this._config.subTrackerAngleIds,this._config.subTrackerCenterIds,this._config.subTrackerExtRatio,this._config.subTrackerAngleShift),a=[s],i=[Ho(e,new ImageData(this._subTrackerConfig.inWidth,this._subTrackerConfig.inHeight),s)];if(this._config.subTrackerSymmetric&&this._config.subTrackerSymmetricIds){var o=qo(t,new Int32Array([this._subTrackerConfig.inWidth,this._subTrackerConfig.inHeight]),this._config.subTrackerSymmetricIds,this._config.subTrackerAngleIds,this._config.subTrackerCenterIds,this._config.subTrackerExtRatio,this._config.subTrackerAngleShift);a=a.concat([o]);var u=new ImageData(this._subTrackerConfig.inWidth,this._subTrackerConfig.inHeight);i=i.concat([Ho(e,u,o)])}var l=[""],p=[this._poseModule._malloc(2*this._subTrackerOutDims[3]*this._float_size)],c=[this._poseModule._malloc(this._subTrackerOutDims[3]*this._float_size)];this._config.subTrackerSymmetric&&(p=p.concat([this._poseModule._malloc(2*this._subTrackerOutDims[3]*this._float_size)]),c=c.concat([this._poseModule._malloc(this._subTrackerOutDims[3]*this._float_size)]),l=l.concat(["left_right"]));for(var h=yu(this._tfSubTracker,this._subTrackerConfig,null,[this._bufSubTrackerHmaps,this._bufSubTrackerHmapsSym],p,c,i,l),d=0;d<p.length;d++)this._poseModule._free(p[d]);for(d=0;d<c.length;d++)this._poseModule._free(c[d]);var f=[],m=[],y=[];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})),y=y.concat([n]),r._subTrackerCropKeyps&&r._subTrackerCropKeyps.length>t?r._subTrackerCropKeyps[t]=Go(e,n,r._subTrackerCropKeyps[t],r._subTrackerVis[t],0):r._subTrackerCropKeyps=r._subTrackerCropKeyps.concat([e]);var s=Lo(r._subTrackerCropKeyps[t],a[t],l[t],new Int32Array([r._subTrackerConfig.outHeight,r._subTrackerConfig.outWidth]));f=f.concat([s])})),{subTrackerKeyps:f,subTrackerKeypsScores:m,subTrackerVisibility:y}},e.prototype.computePoseSync=function(e,t){return this._nonRigidInitialized&&(Iu(t)||t==Mu.Wrist||t==Mu.Face)?this.computeNonRigidPoseSync(e,t):this.computeRigidPoseSync(e,t)},e.prototype.computeRigidPoseSync=function(e,t){var n=this,r=-1,s=this._poseModule.cwrap("xzimgEstimateRigidPose","number",["number","number","number","number","number","number","number","number","number","number","number","number"]);if(e==Vo.Detection){var a=0,i=0,o=t==Mu.Necklace?3:0,u=1,l=[1,0,0,0,1,0],p=(h=this._poseModule._malloc(6*this._float_size))/4,c=this._poseModule.HEAPF32.subarray(p,p+6);return this._trackHasHeatmaps?c.set(this._simCropToImage.slice(0,6)):c.set(l),r=s(this._bufferHeatmaps,this._detectorOutDims[1],this._detectorOutDims[2],this._detectorOutDims[3],a,h,this._bufferKeypsDet,this.isMirrored()?this._bufMirroredKeyps3D:this._bufKeyps3D,i,o,u,this._bufInOutPose),this._pose=new Yo(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==Vo.Detected||e==Vo.Tracking){a=0,i=e!=Vo.Tracking||this._resetPose?0:1,this._resetPose=!1,o=t==Mu.Hand||t==Mu.Necklace||t==Mu.Lamborghini?3:1,u=t==Mu.Hand||t==Mu.Necklace||t==Mu.Lamborghini?3:1,p=(h=this._poseModule._malloc(6*this._float_size))/4;var h,d=this._poseModule.HEAPF32.subarray(p,p+6);this._trackHasHeatmaps&&3==o?d.set(this._simCropToImage.slice(0,6)):(l=[1,0,0,0,1,0],d.set(l));var f=null,m=null,y=this._keyps2D.length/2;if(this._activeIds.length>0){var g=new Float32Array(2*this._activeIds.length),_=new Float32Array(3*this._activeIds.length);this._activeIds.forEach((function(e,t){g[t]=n._keyps2D[e],g[t+n._activeIds.length]=n._keyps2D[e+y]})),p=(f=this._poseModule._malloc(this._activeIds.length*this._float_size*2))/4,(d=this._poseModule.HEAPF32.subarray(p,p+2*this._activeIds.length)).set(g),this._activeIds.forEach((function(e,t){_[3*t]=n._keypsVts[3*e],n.isMirrored()&&(_[3*t]=-_[3*t]),_[3*t+1]=n._keypsVts[3*e+1],_[3*t+2]=n._keypsVts[3*e+2]})),p=(m=this._poseModule._malloc(this._activeIds.length*this._float_size*3))/4,(d=this._poseModule.HEAPF32.subarray(p,p+3*this._activeIds.length)).set(_),y=this._activeIds.length}else p=(f=this._poseModule._malloc(y*this._float_size*2))/4,(d=this._poseModule.HEAPF32.subarray(p,p+this._keyps2D.length)).set(this._keyps2D),2!=o&&3!=o||d.set(this._cropKeyps2D),p=(m=this._poseModule._malloc(this._keypsVts.length*this._float_size))/4,(d=this._poseModule.HEAPF32.subarray(p,p+this._keypsVts.length)).set(this._keypsVts);r=s(2==o||3==o?this._bufferHeatmaps:null,this._trackerOutDims[1],this._trackerOutDims[2],y,a,h,f,m,i,o,u,this._bufInOutPose);var b=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufInOutPose,9),w=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufInOutPose+9*this._float_size,3);this._pose=new Yo(b,w);var v=this._pose.project(this._keypsVts,Yo.getCameraMat(this._config.fovY,this._currentWidth,this._currentHeight));this._reprojKeyps2D=new Float32Array(v.length);for(var T=0;T<v.length/2;T++)this._reprojKeyps2D[T]=v[2*T],this._reprojKeyps2D[T+this._reprojKeyps2D.length/2]=v[2*T+1];if(t==Mu.Necklace){var S=this._pose.getRot();S[5]>.35&&(console.log(S[2],S[5],S[8]),S[2]=0,S[5]=0,S[8]=-1,this._pose.updateRotation(S))}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=Iu(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,s=e==Vo.Detected?1:0,a=this._trackerOutDims[3],i=(r=this._poseModule._malloc(this._keyps2D.length*this._float_size))/4;this._poseModule.HEAPF32.subarray(i,i+this._keyps2D.length).set(this._keyps2D);var o=this._poseModule._malloc(a*this._int_size),u=o/4;this._poseModule.HEAPF32.subarray(u,u+a).set(this._visibility),null==this._bufKeyps3D&&(this._bufKeyps3D=this._poseModule._malloc(a*this._float_size*3));var l=1e3;t==Mu.Face&&(l=25),t==Mu.Wrist&&(l=100);var p=performance.now(),c=n(s,r,a,o,5,l,this._config.reprojThs,.5,.75,.95,this._bufInOutPose,this._bufKeyps3D),h=performance.now();this.mean_t=.95*this.mean_t+.05*(h-p);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 Yo(d,f),this._keyps3D=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufKeyps3D,3*a),this._poseModule._free(r),this._poseModule._free(o);var m=this._poseModule.cwrap("xzimgEstimateGetNumVertices","number"),y=this._poseModule.cwrap("xzimgEstimateGetDenseVertices","number"),g=m();g>0&&(null==this._bufDenseVertices3D&&(this._bufDenseVertices3D=this._poseModule._malloc(g*this._float_size*3)),y(this._bufDenseVertices3D),this._denseVertices=new Float32Array(this._poseModule.HEAPF32.buffer,this._bufDenseVertices3D,3*g));var _=this._poseModule.cwrap("xzimgEstimateGetNumBlendShapes","number"),b=this._poseModule.cwrap("xzimgEstimateGetBlendShapes","number"),w=_();if(w>0){var v=this._poseModule._malloc(w*this._float_size),T=b(v);this._debug&&console.log(T);var S=new Float32Array(this._poseModule.HEAPF32.buffer,v,w);this._bsCoefs=new Float32Array(w);for(var k=0;k<w;k++)this._bsCoefs[k]=S[k];this._debug&&console.log(this._bsCoefs),this._poseModule._free(v)}return this._debug&&console.log(c),this._debug&&console.log(d),this._debug&&console.log(f),c},e}()})(),r})()));