deepar 5.6.20 → 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:()=>GC,Geometry:()=>YC,Segmentation:()=>eT,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=function(){return 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(){return"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(){return"function"==typeof Symbol&&Symbol.observable||"@@observable"}();function T(e){return e}function S(e){return 0===e.length?T:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var E=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=N(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=0;t<arguments.length;t++)e[t]=arguments[t];return 0===e.length?this:S(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=N(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 N(e){if(e||(e=h.Promise||Promise),!e)throw new Error("no Promise impl found");return e}var A=function(e){return function(t){for(var n=0,r=e.length;n<r&&!t.closed;n++)t.next(e[n]);t.complete()}};function C(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}var R=C(),M=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function F(e){return!!e&&"function"!=typeof e.subscribe&&"function"==typeof e.then}var $=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(M(e))return A(e);if(F(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[R])return t=e,function(e){for(var n=t[R]();;){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.")},O=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),D=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 P(e){return e&&"function"==typeof e.schedule}var L=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 B(e,t,n,r,a){if(void 0===a&&(a=new L(e,n,r)),!a.closed)return t instanceof E?t.subscribe(a):$(t)(a)}var U=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 W(e,t){return new E((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 z(e,t){return t?W(e,t):new E(A(e))}var V={};function H(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=void 0,r=void 0;return P(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]),z(e,r).lift(new G(n))}var G=function(){function e(e){this.resultSelector=e}return e.prototype.call=function(e,t){return t.subscribe(new j(e,this.resultSelector))},e}(),j=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(V),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(B(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===V?--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}(U);function K(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 E((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(F(e))return function(e,t){return new E((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(M(e))return W(e,t);if(function(e){return e&&"function"==typeof e[R]}(e)||"string"==typeof e)return function(e,t){if(!e)throw new Error("Iterable cannot be null");return new E((function(n){var r,a=new _;return a.add((function(){r&&"function"==typeof r.return&&r.return()})),a.add(t.schedule((function(){r=e[R](),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 E?e:new E($(e))}function q(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e[e.length-1];return P(n)?(e.pop(),W(e,n)):z(e)}function X(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 Y(e,t))}}var Y=function(){function e(e,t){this.project=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new Q(e,this.project,this.thisArg))},e}(),Q=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),J=new E((function(e){return e.complete()}));function Z(e,t){return new E(t?function(n){return t.schedule(ee,0,{error:e,subscriber:n})}:function(t){return t.error(e)})}function ee(e){var t=e.error;e.subscriber.error(t)}function te(e){return function(t){return t.lift(new ne(e))}}var ne=function(){function e(e){this.callback=e}return e.prototype.call=function(e,t){return t.subscribe(new re(e,this.callback))},e}(),re=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),ae=function(){function e(){return Error.call(this),this.message="object unsubscribed",this.name="ObjectUnsubscribedError",this}return e.prototype=Object.create(Error.prototype),e}(),se=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}(_),oe=function(e){function t(t){var n=e.call(this,t)||this;return n.destination=t,n}return l(t,e),t}(v),ie=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 oe(this)},t.prototype.lift=function(e){var t=new ue(this,this);return t.operator=e,t},t.prototype.next=function(e){if(this.closed)throw new ae;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 ae;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 ae;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 ae;return e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){if(this.closed)throw new ae;return this.hasError?(e.error(this.thrownError),_.EMPTY):this.isStopped?(e.complete(),_.EMPTY):(this.observers.push(e),new se(this,e))},t.prototype.asObservable=function(){var e=new E;return e.source=this,e},t.create=function(e,t){return new ue(e,t)},t}(E),ue=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}(ie),le=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 ae;return this._value},t.prototype.next=function(t){e.prototype.next.call(this,this._value=t)},t}(ie);function ce(e){return void 0===e&&(e=-1),function(t){return t.lift(new pe(e,t))}}var pe=function(){function e(e,t){this.count=e,this.source=t}return e.prototype.call=function(e,t){return t.subscribe(new he(e,this.count,this.source))},e}(),he=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 de(e,t){return"function"==typeof t?function(n){return n.pipe(de((function(n,r){return K(e(n,r)).pipe(X((function(e,a){return t(n,e,r,a)})))})))}:function(t){return t.lift(new fe(e))}}var fe=function(){function e(e){this.project=e}return e.prototype.call=function(e,t){return t.subscribe(new me(e,this.project))},e}(),me=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 O(this),r=this.destination;r.add(n),this.innerSubscription=function(e,t){if(!t.closed){if(e instanceof E)return e.subscribe(t);var n;try{n=$(e)(t)}catch(e){t.error(e)}return n}}(e,n),this.innerSubscription!==n&&r.add(this.innerSubscription)},t.prototype._complete=function(){var t=this.innerSubscription;t&&!t.closed||e.prototype._complete.call(this),this.unsubscribe()},t.prototype._unsubscribe=function(){this.innerSubscription=void 0},t.prototype.notifyComplete=function(){this.innerSubscription=void 0,this.isStopped&&e.prototype._complete.call(this)},t.prototype.notifyNext=function(e){this.destination.next(e)},t}(D);function ge(){}function ye(e,t,n){return function(r){return r.lift(new be(e,t,n))}}var be=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 _e(e,this.nextOrObserver,this.error,this.complete))},e}(),_e=function(e){function t(t,n,r,a){var s=e.call(this,t)||this;return s._tapNext=ge,s._tapError=ge,s._tapComplete=ge,s._tapError=r||ge,s._tapComplete=a||ge,c(n)?(s._context=s,s._tapNext=n):n&&(s._context=n,s._tapNext=n.next||ge,s._tapError=n.error||ge,s._tapComplete=n.complete||ge),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 xe(e){return new E((function(t){var n,r;try{n=e()}catch(e){return void t.error(e)}return(n?K(n):r?function(e){return new E((function(t){return e.schedule((function(){return t.complete()}))}))}(r):J).subscribe(t)}))}var we=void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function ve(){throw new Error("setTimeout has not been defined")}function ke(){throw new Error("clearTimeout has not been defined")}var Ie=ve,Te=ke;function Se(e){if(Ie===setTimeout)return setTimeout(e,0);if((Ie===ve||!Ie)&&setTimeout)return Ie=setTimeout,setTimeout(e,0);try{return Ie(e,0)}catch(t){try{return Ie.call(null,e,0)}catch(t){return Ie.call(this,e,0)}}}"function"==typeof we.setTimeout&&(Ie=setTimeout),"function"==typeof we.clearTimeout&&(Te=clearTimeout);var Ee,Ne=[],Ae=!1,Ce=-1;function Re(){Ae&&Ee&&(Ae=!1,Ee.length?Ne=Ee.concat(Ne):Ce=-1,Ne.length&&Me())}function Me(){if(!Ae){var e=Se(Re);Ae=!0;for(var t=Ne.length;t;){for(Ee=Ne,Ne=[];++Ce<t;)Ee&&Ee[Ce].run();Ce=-1,t=Ne.length}Ee=null,Ae=!1,function(e){if(Te===clearTimeout)return clearTimeout(e);if((Te===ke||!Te)&&clearTimeout)return Te=clearTimeout,clearTimeout(e);try{Te(e)}catch(t){try{return Te.call(null,e)}catch(t){return Te.call(this,e)}}}(e)}}function Fe(e,t){this.fun=e,this.array=t}function $e(){}Fe.prototype.run=function(){this.fun.apply(null,this.array)};var Oe=$e,De=$e,Pe=$e,Le=$e,Be=$e,Ue=$e,We=$e,ze=we.performance||{},Ve=ze.now||ze.mozNow||ze.msNow||ze.oNow||ze.webkitNow||function(){return(new Date).getTime()},He=new Date,Ge={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];Ne.push(new Fe(e,t)),1!==Ne.length||Ae||Se(Me)},title:"browser",browser:!0,env:{},argv:[],version:"",versions:{},on:Oe,addListener:De,once:Pe,off:Le,removeListener:Be,removeAllListeners:Ue,emit:We,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*Ve.call(ze),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-He)/1e3}},je=Ge;class Ke{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 qe{refCount(e){return Xe("refCount")}incRef(e){return Xe("incRef")}timerAvailable(){return!0}time(e){return Xe("time")}read(e){return Xe("read")}readSync(e){return Xe("readSync")}readToGPU(e,t){return Xe("readToGPU")}numDataIds(){return Xe("numDataIds")}disposeData(e,t){return Xe("disposeData")}write(e,t,n){return Xe("write")}move(e,t,n,r,a){return Xe("move")}createTensorFromGPUData(e,t,n){return Xe("createTensorFromGPUData")}memory(){return Xe("memory")}floatPrecision(){return Xe("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return Xe("dispose")}}function Xe(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 Ye(e,t,n){return Math.max(e,Math.min(t,n))}function Qe(e){return e%2==0?e:e+1}function Je(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function Ze(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function et(e,t,n=""){Ze(rt(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function tt(e){Ze(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function nt(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 rt(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 at(e){return e%1==0}function st(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function ot(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function it(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 ut(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 lt(e,t){const n=t.length;return e=null==e?t.map(((e,t)=>t)):[].concat(e),Ze(e.every((e=>e>=-n&&e<n)),(()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),Ze(e.every((e=>at(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function ct(e,t){const n=[],r=[],a=null!=t&&Array.isArray(t)&&0===t.length,s=null==t||a?null:lt(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 pt(e,t){return ht(e,t)}function ht(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 dt(e,t){return!("complex64"===t||"float32"===t&&"complex64"!==e||"int32"===t&&"float32"!==e&&"complex64"!==e||"bool"===t&&"bool"===e)}function ft(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 mt(e){return"string"==typeof e||e instanceof String}function gt(e){return Array.isArray(e)?gt(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":"number"==typeof e?"float32":mt(e)?"string":"boolean"==typeof e?"bool":"float32"}function yt(e){return!!(e&&e.constructor&&e.call&&e.apply)}function bt(e,t){for(let n=t;n<e;++n)if(e%n==0)return n;return e}function _t(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 xt(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]=xt(e+t*i,o,n,r)}return a}function wt(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 xt(0,e,t,n)}function vt(e,t){const n=kt(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}function kt(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 It(e){e.forEach((t=>{Ze(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function Tt(e,t,n){if(0===t)return 0;if(1===t)return e[0];let r=e[e.length-1];for(let t=0;t<e.length-1;++t)r+=n[t]*e[t];return r}function St(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 Et(e){return e&&e.then&&"function"==typeof e.then}class Nt{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=At,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(Ct().getBool("IS_TEST")||Ct().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},null!=this.urlFlags[e]){const t=this.urlFlags[e];Ct().getBool("IS_TEST")||Ct().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${t}.`),this.set(e,t)}}async getAsync(e){return e in this.flags||(this.flags[e]=await this.evaluateFlag(e)),this.flags[e]}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(Et(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 At(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,((e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("=")))),t}function Ct(){return Mt}let Rt,Mt=null;function Ft(){if(null==Rt){let e;if("undefined"!=typeof window)e=window;else if(void 0!==we)e=we;else if(void 0!==je)e=je;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}Rt=e}return Rt}function $t(e,t){const n=function(){const e=Ft();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 Ot="Acos",Dt="Acosh",Pt="Add",Lt="AddN",Bt="All",Ut="Any",Wt="ArgMax",zt="ArgMin",Vt="Asin",Ht="Asinh",Gt="Atan",jt="Atanh",Kt="Atan2",qt="AvgPool",Xt="AvgPool3D",Yt="BatchMatMul",Qt="BatchToSpaceND",Jt="Bincount",Zt="BitwiseAnd",en="BroadcastArgs",tn="Cast",nn="Ceil",rn="ClipByValue",an="Concat",sn="Conv2D",on="Conv2DBackpropInput",un="Conv3D",ln="Conv3DBackpropFilterV2",cn="Conv3DBackpropInputV2",pn="Cosh",hn="Cumprod",dn="Cumsum",fn="CropAndResize",mn="DenseBincount",gn="DepthToSpace",yn="DepthwiseConv2dNative",bn="Diag",_n="Dilation2D",xn="Dilation2DBackpropInput",wn="Dilation2DBackpropFilter",vn="RealDiv",kn="Elu",In="EluGrad",Tn="Equal",Sn="Exp",En="ExpandDims",Nn="Expm1",An="Fill",Cn="FlipLeftRight",Rn="Floor",Mn="FloorDiv",Fn="FusedBatchNorm",$n="GatherV2",On="GatherNd",Dn="Greater",Pn="GreaterEqual",Ln="Identity",Bn="IsFinite",Un="IsInf",Wn="IsNan",zn="LeakyRelu",Vn="Less",Hn="LessEqual",Gn="LinSpace",jn="Log1p",Kn="LogicalAnd",qn="LogicalNot",Xn="LogicalOr",Yn="LRN",Qn="LRNGrad",Jn="Max",Zn="Maximum",er="MaxPool",tr="MaxPool3D",nr="MaxPoolWithArgmax",rr="Mean",ar="Min",sr="Minimum",or="MirrorPad",ir="Multinomial",ur="Multiply",lr="NotEqual",cr="NonMaxSuppressionV3",pr="NonMaxSuppressionV4",hr="NonMaxSuppressionV5",dr="OnesLike",fr="OneHot",mr="Pack",gr="PadV2",yr="Prelu",br="Prod",_r="Range",xr="Reciprocal",wr="Relu",vr="Reshape",kr="ResizeNearestNeighbor",Ir="ResizeNearestNeighborGrad",Tr="ResizeBilinear",Sr="ResizeBilinearGrad",Er="Relu6",Nr="Reverse",Ar="Round",Cr="Rsqrt",Rr="ScatterNd",Mr="TensorScatterUpdate",Fr="SearchSorted",$r="Select",Or="Selu",Dr="Slice",Pr="Sinh",Lr="Sign",Br="Sigmoid",Ur="Softplus",Wr="Sqrt",zr="Sum",Vr="SpaceToBatchND",Hr="SplitV",Gr="Softmax",jr="SparseFillEmptyRows",Kr="SparseReshape",qr="SparseSegmentMean",Xr="SparseSegmentSum",Yr="SparseToDense",Qr="SquaredDifference",Jr="StridedSlice",Zr="StringNGrams",ea="StringSplit",ta="StringToHashBucketFast",na="Sub",ra="Tanh",aa="Tile",sa="TopK",oa="Transform",ia="Transpose",ua="Unique",la="Unpack",ca="ZerosLike",pa="Step",ha="FromPixels",da="RotateWithOffset",fa="_FusedMatMul",ma="FusedConv2D",ga="FusedDepthwiseConv2D";function ya(...e){Ct().getBool("IS_TEST")||Ct().getBool("PROD")||console.warn(...e)}const ba=$t("kernelRegistry",(()=>new Map)),_a=$t("gradRegistry",(()=>new Map));function xa(e,t){const n=Ia(e,t);return ba.get(n)}function wa(e){return _a.get(e)}function va(e){const t=ba.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 ka(e){const{kernelName:t,backendName:n}=e,r=Ia(t,n);ba.has(r)&&ya(`The kernel '${t}' for backend '${n}' is already registered`),ba.set(r,e)}function Ia(e,t){return`${t}_${e}`}function Ta(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var Sa=Na,Ea=null;try{Ea=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 Na(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function Aa(e){return!0===(e&&e.__isLong__)}Na.prototype.__isLong__,Object.defineProperty(Na.prototype,"__isLong__",{value:!0}),Na.isLong=Aa;var Ca={},Ra={};function Ma(e,t){var n,r,a;return t?(a=0<=(e>>>=0)&&e<256)&&(r=Ra[e])?r:(n=$a(e,(0|e)<0?-1:0,!0),a&&(Ra[e]=n),n):(a=-128<=(e|=0)&&e<128)&&(r=Ca[e])?r:(n=$a(e,e<0?-1:0,!1),a&&(Ca[e]=n),n)}function Fa(e,t){if(isNaN(e))return t?Va:za;if(t){if(e<0)return Va;if(e>=Ba)return qa}else{if(e<=-Ua)return Xa;if(e+1>=Ua)return Ka}return e<0?Fa(-e,t).neg():$a(e%La|0,e/La|0,t)}function $a(e,t,n){return new Na(e,t,n)}Na.fromInt=Ma,Na.fromNumber=Fa,Na.fromBits=$a;var Oa=Math.pow;function Da(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return za;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 Da(e.substring(1),t,n).neg();for(var a=Fa(Oa(n,8)),s=za,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=Fa(Oa(n,i));s=s.mul(l).add(Fa(u))}else s=(s=s.mul(a)).add(Fa(u))}return s.unsigned=t,s}function Pa(e,t){return"number"==typeof e?Fa(e,t):"string"==typeof e?Da(e,t):$a(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}Na.fromString=Da,Na.fromValue=Pa;var La=4294967296,Ba=La*La,Ua=Ba/2,Wa=Ma(1<<24),za=Ma(0);Na.ZERO=za;var Va=Ma(0,!0);Na.UZERO=Va;var Ha=Ma(1);Na.ONE=Ha;var Ga=Ma(1,!0);Na.UONE=Ga;var ja=Ma(-1);Na.NEG_ONE=ja;var Ka=$a(-1,2147483647,!1);Na.MAX_VALUE=Ka;var qa=$a(-1,-1,!0);Na.MAX_UNSIGNED_VALUE=qa;var Xa=$a(0,-2147483648,!1);Na.MIN_VALUE=Xa;var Ya=Na.prototype;Ya.toInt=function(){return this.unsigned?this.low>>>0:this.low},Ya.toNumber=function(){return this.unsigned?(this.high>>>0)*La+(this.low>>>0):this.high*La+(this.low>>>0)},Ya.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(Xa)){var t=Fa(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=Fa(Oa(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}},Ya.getHighBits=function(){return this.high},Ya.getHighBitsUnsigned=function(){return this.high>>>0},Ya.getLowBits=function(){return this.low},Ya.getLowBitsUnsigned=function(){return this.low>>>0},Ya.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Xa)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<<t);t--);return 0!=this.high?t+33:t+1},Ya.isZero=function(){return 0===this.high&&0===this.low},Ya.eqz=Ya.isZero,Ya.isNegative=function(){return!this.unsigned&&this.high<0},Ya.isPositive=function(){return this.unsigned||this.high>=0},Ya.isOdd=function(){return 1==(1&this.low)},Ya.isEven=function(){return 0==(1&this.low)},Ya.equals=function(e){return Aa(e)||(e=Pa(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low},Ya.eq=Ya.equals,Ya.notEquals=function(e){return!this.eq(e)},Ya.neq=Ya.notEquals,Ya.ne=Ya.notEquals,Ya.lessThan=function(e){return this.comp(e)<0},Ya.lt=Ya.lessThan,Ya.lessThanOrEqual=function(e){return this.comp(e)<=0},Ya.lte=Ya.lessThanOrEqual,Ya.le=Ya.lessThanOrEqual,Ya.greaterThan=function(e){return this.comp(e)>0},Ya.gt=Ya.greaterThan,Ya.greaterThanOrEqual=function(e){return this.comp(e)>=0},Ya.gte=Ya.greaterThanOrEqual,Ya.ge=Ya.greaterThanOrEqual,Ya.compare=function(e){if(Aa(e)||(e=Pa(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},Ya.comp=Ya.compare,Ya.negate=function(){return!this.unsigned&&this.eq(Xa)?Xa:this.not().add(Ha)},Ya.neg=Ya.negate,Ya.add=function(e){Aa(e)||(e=Pa(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,$a((c&=65535)<<16|(p&=65535),(u&=65535)<<16|(l&=65535),this.unsigned)},Ya.subtract=function(e){return Aa(e)||(e=Pa(e)),this.add(e.neg())},Ya.sub=Ya.subtract,Ya.multiply=function(e){if(this.isZero())return za;if(Aa(e)||(e=Pa(e)),Ea)return $a(Ea.mul(this.low,this.high,e.low,e.high),Ea.get_high(),this.unsigned);if(e.isZero())return za;if(this.eq(Xa))return e.isOdd()?Xa:za;if(e.eq(Xa))return this.isOdd()?Xa:za;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(Wa)&&e.lt(Wa))return Fa(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,$a((p&=65535)<<16|(h&=65535),(l&=65535)<<16|(c&=65535),this.unsigned)},Ya.mul=Ya.multiply,Ya.divide=function(e){if(Aa(e)||(e=Pa(e)),e.isZero())throw Error("division by zero");var t,n,r;if(Ea)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?$a((this.unsigned?Ea.div_u:Ea.div_s)(this.low,this.high,e.low,e.high),Ea.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Va:za;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Va;if(e.gt(this.shru(1)))return Ga;r=Va}else{if(this.eq(Xa))return e.eq(Ha)||e.eq(ja)?Xa:e.eq(Xa)?Ha:(t=this.shr(1).div(e).shl(1)).eq(za)?e.isNegative()?Ha:ja:(n=this.sub(e.mul(t)),r=t.add(n.div(e)));if(e.eq(Xa))return this.unsigned?Va:za;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=za}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:Oa(2,a-48),o=Fa(t),i=o.mul(e);i.isNegative()||i.gt(n);)i=(o=Fa(t-=s,this.unsigned)).mul(e);o.isZero()&&(o=Ha),r=r.add(o),n=n.sub(i)}return r},Ya.div=Ya.divide,Ya.modulo=function(e){return Aa(e)||(e=Pa(e)),Ea?$a((this.unsigned?Ea.rem_u:Ea.rem_s)(this.low,this.high,e.low,e.high),Ea.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},Ya.mod=Ya.modulo,Ya.rem=Ya.modulo,Ya.not=function(){return $a(~this.low,~this.high,this.unsigned)},Ya.and=function(e){return Aa(e)||(e=Pa(e)),$a(this.low&e.low,this.high&e.high,this.unsigned)},Ya.or=function(e){return Aa(e)||(e=Pa(e)),$a(this.low|e.low,this.high|e.high,this.unsigned)},Ya.xor=function(e){return Aa(e)||(e=Pa(e)),$a(this.low^e.low,this.high^e.high,this.unsigned)},Ya.shiftLeft=function(e){return Aa(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?$a(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):$a(0,this.low<<e-32,this.unsigned)},Ya.shl=Ya.shiftLeft,Ya.shiftRight=function(e){return Aa(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?$a(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):$a(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},Ya.shr=Ya.shiftRight,Ya.shiftRightUnsigned=function(e){if(Aa(e)&&(e=e.toInt()),0==(e&=63))return this;var t=this.high;return e<32?$a(this.low>>>e|t<<32-e,t>>>e,this.unsigned):$a(32===e?t:t>>>e-32,0,this.unsigned)},Ya.shru=Ya.shiftRightUnsigned,Ya.shr_u=Ya.shiftRightUnsigned,Ya.toSigned=function(){return this.unsigned?$a(this.low,this.high,!1):this},Ya.toUnsigned=function(){return this.unsigned?this:$a(this.low,this.high,!0)},Ya.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},Ya.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]},Ya.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]},Na.fromBytes=function(e,t,n){return n?Na.fromBytesLE(e,t):Na.fromBytesBE(e,t)},Na.fromBytesLE=function(e,t){return new Na(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},Na.fromBytesBE=function(e,t){return new Na(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};const Qa=Sa||e({__proto__:null,default:Sa},[Sa]);function Ja(e){return Qa.fromString(e,!0,16)}const Za=Ja("c3a5c85c97cb3127"),es=Ja("b492b66fbe98f273"),ts=Ja("9ae16a3b2f90404f");function ns(e){return e.xor(e.shru(47))}function rs(e,t,n){const r=e.slice(t,t+n);return Qa.fromBytes(Array.from(r),!0,!0)}function as(e,t){return rs(e,t,8)}function ss(e,t){return rs(e,t,4)}function os(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function is(e,t,n=Ja("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 us(e,t,n,r){return function(e,t,n,r,a,s){a=a.add(e),s=os(s.add(a).add(r),21);const o=a;return a=(a=a.add(t)).add(n),s=s.add(os(a,44)),[a.add(r),s.add(o)]}(as(e,t),as(e,t+8),as(e,t+16),as(e,t+24),n,r)}function ls(e,t=e.length){const n=Qa.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=ts.add(2*t),r=as(e,0).add(ts),a=as(e,t-8);return is(os(a,37).mul(n).add(r),os(r,25).add(a).mul(n),n)}if(t>=4){const n=ts.add(2*t);return is(ss(e,0).shl(3).add(t),ss(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),r=t+(e[t-1]<<2);return ns(ts.mul(n).xor(Za.mul(r))).mul(ts)}return ts}(e,t):function(e,t=e.length){const n=ts.add(2*t),r=as(e,0).mul(es),a=as(e,8),s=as(e,t-8).mul(n),o=as(e,t-16).mul(ts);return is(os(r.add(a),43).add(os(s,30)).add(o),r.add(os(a.add(ts),18)).add(s),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=ts.add(2*t),r=as(e,0).mul(ts),a=as(e,8),s=as(e,t-8).mul(n),o=as(e,t-16).mul(ts),i=os(r.add(a),43).add(os(s,30)).add(o),u=is(i,r.add(os(a.add(ts),18)).add(s),n),l=as(e,16).mul(n),c=as(e,24),p=i.add(as(e,t-32)).mul(n),h=u.add(as(e,t-24)).mul(n);return is(os(l.add(c),43).add(os(p,30)).add(h),l.add(os(c.add(r),18)).add(p),n)}(e,t);let r=n,a=n.mul(es).add(113),s=ns(a.mul(ts).add(113)).mul(ts),o=[Qa.UZERO,Qa.UZERO],i=[Qa.UZERO,Qa.UZERO];r=r.mul(ts).add(as(e,0));let u=0;const l=64*(t-1>>6),c=l+(t-1&63)-63;do{r=os(r.add(a).add(o[0]).add(as(e,u+8)),37).mul(es),a=os(a.add(o[1]).add(as(e,u+48)),42).mul(es),r=r.xor(i[1]),a=a.add(o[0]).add(as(e,u+40)),s=os(s.add(i[0]),33).mul(es),o=us(e,u,o[1].mul(es),r.add(i[0])),i=us(e,u+32,s.add(i[1]),a.add(as(e,u+16))),[s,r]=[r,s],u+=64}while(u!==l);const p=es.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=os(r.add(a).add(o[0]).add(as(e,u+8)),37).mul(p),a=os(a.add(o[1]).add(as(e,u+48)),42).mul(p),r=r.xor(i[1].mul(9)),a=a.add(o[0].mul(9).add(as(e,u+40))),s=os(s.add(i[0]),33).mul(p),o=us(e,u,o[1].mul(p),r.add(i[0])),i=us(e,u+32,s.add(i[1]),a.add(as(e,u+16))),[s,r]=[r,s],is(is(o[0],i[0],p).add(ns(a).mul(Za)).add(s),is(o[1],i[1],p).add(r),p)}function cs(e,t){return"string"===t?ds(e):ps([e],t)}function ps(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=gs(e)),Ct().getBool("DEBUG")&&function(e,t){for(let n=0;n<e.length;n++){const r=e[n];if(isNaN(r)||!isFinite(r))throw Error(`A tensor of type ${t} being uploaded contains ${r}.`)}}(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){const t=new Uint8Array(e.length);for(let n=0;n<t.length;++n)0!==Math.round(e[n])&&(t[n]=1);return t}throw new Error(`Unknown data type ${t}`)}function hs(){return Ct().platform.now()}function ds(e,t="utf-8"){return t=t||"utf-8",Ct().platform.encode(e,t)}function fs(e,t="utf-8"){return t=t||"utf-8",Ct().platform.decode(e,t)}function ms(e){return null!=Ct().platform.isTypedArray?Ct().platform.isTypedArray(e):Ta(e)}function gs(e,t=[],n=!1){if(null==t&&(t=[]),"boolean"==typeof e||"number"==typeof e||"string"==typeof e||Et(e)||null==e||ms(e)&&n)t.push(e);else if(Array.isArray(e)||ms(e))for(let r=0;r<e.length;++r)gs(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++)gs(e[a],t,n)}return t}class ys{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new _s)}profileKernel(e,t,n){let r;const a=()=>{r=n()};let s;const o=hs();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(a);else{a();for(const e of r)e.dataSync();s=Promise.resolve({kernelMs:hs()-o})}if(Ct().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<r.length;t++){const n=r[t];n.data().then((t=>{bs(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 bs(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 _s{logKernelProfile(e,t,n,r,a,s){const o="number"==typeof r?ot(`${r}ms`,9):r.error,i=ot(e,25),u=t.rank,l=t.size,c=ot(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 xs(e,t,n,r){const a=_t(t),s=function(e,t,n,r){const a=nt(t),s=r[r.length-1],o=new Array(s).fill(0),i=t.length,u="complex64"===n?Is(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],ws(u[t+e],0,n).length)}return o}(e,t,n,a),o=t.length,i=ks(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 ws(e,t,n){let r;return r=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:mt(e)?`'${e}'`:"bool"===n?vs(e):parseFloat(e.toFixed(7)).toString(),ot(r,t)}function vs(e){return 0===e?"false":"true"}function ks(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?[ws(Is(e)[0],0,n)]:"bool"===n?[vs(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=Is(r),s=Is(s)),["["+r.map(((e,t)=>ws(e,a[t],n))).join(", ")+", ..., "+s.map(((e,t)=>ws(e,a[i-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?Is(e):Array.from(e)).map(((e,t)=>ws(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(...ks(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(...ks(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(...ks(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 Is(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class Ts{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=nt(e),null!=n){const e=n.length;Ze(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||ht(t,this.size),this.strides=_t(e)}set(e,...t){0===t.length&&(t=[0]),Ze(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 Ss().makeTensor(this.values,this.shape,this.dtype)}}let Ss=null,Es=null;class Ns{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=nt(e),this.strides=_t(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 Es.buffer(this.shape,this.dtype,e)}bufferSync(){return Es.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return wt(this.shape,e,"complex64"===this.dtype)}arraySync(){return wt(this.shape,this.dataSync(),"complex64"===this.dtype)}async data(){this.throwIfDisposed();const e=Ss().read(this.dataId);if("string"===this.dtype){const t=await e;try{return t.map((e=>fs(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(),Ss().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=Ss().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>fs(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 Ss().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),Ss().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Es.print(this,e)}clone(){return this.throwIfDisposed(),Es.clone(this)}toString(e=!1){return xs(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Es.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Ss().makeVariable(this,e,t,n)}}function As(){return $t("Tensor",(()=>Ns))}Object.defineProperty(Ns,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),As();class Cs extends Ns{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(!rt(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Ss().disposeTensor(this),this.dataId=e.dataId,Ss().incRef(this,null)}dispose(){Ss().disposeVariable(this),this.isDisposedInternal=!0}}var Rs,Ms,Fs,$s,Os;Object.defineProperty(Cs,Symbol.hasInstance,{value:e=>e instanceof Ns&&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"}(Rs||(Rs={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(Ms||(Ms={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(Fs||(Fs={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}($s||($s={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(Os||(Os={}));const Ds={float32:$s,int32:Ms,bool:Fs,complex64:Os};function Ps(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Ds[e][t]}function Ls(e){return null!=e&&"object"==typeof e&&"texture"in e&&e.texture instanceof WebGLTexture}function Bs(e){return"undefined"!=typeof GPUBuffer&&null!=e&&"object"==typeof e&&"buffer"in e&&e.buffer instanceof GPUBuffer}function Us(e,t){if(e.dtype===t.dtype)return[e,t];const n=Ps(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function Ws(e){const t=[];return zs(e,t,new Set),t}function zs(e,t,n){if(null==e)return;if(e instanceof Ns)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),zs(r,t,n))}}function Vs(e){return null!=e.kernelName}class Hs{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 Gs{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Hs}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?(ya(`${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 ys(this.backendInstance),!0}setupRegisteredKernels(){va(this.backendName).forEach((e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){va(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 qe||"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,ya(`Initialization of backend ${e} failed`),ya(n.stack||n.message)),!1)));return this.pendingBackendInit=r,{success:r,asyncInit:!0}}}catch(t){return ya(`Initialization of backend ${e} failed`),ya(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 Gs.nextTensorId++}nextVariableId(){return Gs.nextVariableId++}clone(e){const t=Ks.runKernel(Ln,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e};return Ks.runKernel(tn,t,{dtype:"float32"})}})),[],{}),t}runKernel(e,t,n){if(null==this.backendName&&this.backend,null==xa(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=Vs(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(Vs(e)){const{kernelName:t,inputs:a,attrs:s}=e;null==this.backendName&&this.backend;const u=xa(t,this.backendName);Ze(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=Vs(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){const t=e.map((e=>this.keep(this.clone(e))));return t}getTensorsForGradient(e,t,n){const r=wa(e);if(null!=r){const e=r.inputsToSave||[],a=r.outputsToSave||[];let s;r.saveAllInputs?(Ze(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&&mt(e[0])&&(a=e.map((e=>ds(e))));const s=r.write(a,t,n),o=new Ns(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 Ns(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 Cs(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*ft(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 Cs||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*ft(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=wa(e);null!=i&&(r=i.gradFunc),null!=r&&(o.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],r=kt(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=Ws(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(Ze(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)));Ze(a instanceof Ns,(()=>"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=vt(nt(e),"float32");return Ks.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(!rt(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)),qs);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 Ze(yt(e),(()=>"The f passed in customGrad(f) must be a function.")),(...t)=>{let n;Ze(t.every((e=>e instanceof Ns)),(()=>"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),Ze(n.value instanceof Ns,(()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor")),Ze(yt(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];Ze(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(...).")),Ze(s.every((e=>e instanceof Ns)),(()=>"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=hs(),n=await this.backend.time(e);return n.wallMs=hs()-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 Hs;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 js(){const e=Ft();if(null==e._tfengine){const t=new Nt(e);e._tfengine=new Gs(t)}var t;return t=e._tfengine.ENV,Mt=t,Ss=()=>e._tfengine,e._tfengine}Gs.nextTensorId=0,Gs.nextVariableId=0;const Ks=js();function qs(e,t){const n={a:e,b:t};return Ks.runKernel(Pt,n)}function Xs(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 Ys(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}const Qs=Ct();Qs.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.")})),Qs.registerFlag("IS_BROWSER",(()=>Ys())),Qs.registerFlag("IS_NODE",(()=>void 0!==je&&void 0!==je.versions&&void 0!==je.versions.node)),Qs.registerFlag("IS_CHROME",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor))),Qs.registerFlag("IS_SAFARI",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor))),Qs.registerFlag("PROD",(()=>!1)),Qs.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(()=>Qs.getBool("DEBUG"))),Qs.registerFlag("DEPRECATION_WARNINGS_ENABLED",(()=>!0)),Qs.registerFlag("IS_TEST",(()=>!1)),Qs.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",(()=>Qs.getBool("DEBUG"))),Qs.registerFlag("WRAP_TO_IMAGEBITMAP",(()=>!1)),Qs.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",(()=>!1)),Qs.registerFlag("USE_SETTIMEOUTCUSTOM",(()=>!1));var Js=[],Zs=[],eo="undefined"!=typeof Uint8Array?Uint8Array:Array,to=!1;function no(){to=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0,n=e.length;t<n;++t)Js[t]=e[t],Zs[e.charCodeAt(t)]=t;Zs["-".charCodeAt(0)]=62,Zs["_".charCodeAt(0)]=63}function ro(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(Js[(a=r)>>18&63]+Js[a>>12&63]+Js[a>>6&63]+Js[63&a]);return s.join("")}function ao(e){var t;to||no();for(var n=e.length,r=n%3,a="",s=[],o=16383,i=0,u=n-r;i<u;i+=o)s.push(ro(e,i,i+o>u?u:i+o));return 1===r?(t=e[n-1],a+=Js[t>>2],a+=Js[t<<4&63],a+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],a+=Js[t>>10],a+=Js[t>>4&63],a+=Js[t<<2&63],a+="="),s.push(a),s.join("")}function so(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 oo(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 io={}.toString,uo=Array.isArray||function(e){return"[object Array]"==io.call(e)};function lo(){return po.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function co(e,t){if(lo()<t)throw new RangeError("Invalid typed array length");return po.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=po.prototype:(null===e&&(e=new po(t)),e.length=t),e}function po(e,t,n){if(!(po.TYPED_ARRAY_SUPPORT||this instanceof po))return new po(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 mo(this,e)}return ho(this,e,t,n)}function ho(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),po.TYPED_ARRAY_SUPPORT?(e=t).__proto__=po.prototype:e=go(e,t),e}(e,t,n,r):"string"==typeof t?function(e,t,n){if("string"==typeof n&&""!==n||(n="utf8"),!po.isEncoding(n))throw new TypeError('"encoding" must be a valid string encoding');var r=0|_o(t,n),a=(e=co(e,r)).write(t,n);return a!==r&&(e=e.slice(0,a)),e}(e,t,n):function(e,t){if(bo(t)){var n=0|yo(t.length);return 0===(e=co(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?co(e,0):go(e,t);if("Buffer"===t.type&&uo(t.data))return go(e,t.data)}var r;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function fo(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 mo(e,t){if(fo(t),e=co(e,t<0?0:0|yo(t)),!po.TYPED_ARRAY_SUPPORT)for(var n=0;n<t;++n)e[n]=0;return e}function go(e,t){var n=t.length<0?0:0|yo(t.length);e=co(e,n);for(var r=0;r<n;r+=1)e[r]=255&t[r];return e}function yo(e){if(e>=lo())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+lo().toString(16)+" bytes");return 0|e}function bo(e){return!(null==e||!e._isBuffer)}function _o(e,t){if(bo(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 xo(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 Oo(this,t,n);case"utf8":case"utf-8":return Ro(this,t,n);case"ascii":return Fo(this,t,n);case"latin1":case"binary":return $o(this,t,n);case"base64":return Co(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Do(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function wo(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function vo(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=po.from(t,r)),bo(t))return 0===t.length?-1:ko(e,t,n,r,a);if("number"==typeof t)return t&=255,po.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):ko(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function ko(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 Io(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 To(e,t,n,r){return Ko(Go(t,e.length-n),e,n,r)}function So(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 Eo(e,t,n,r){return So(e,t,n,r)}function No(e,t,n,r){return Ko(jo(t),e,n,r)}function Ao(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 Co(e,t,n){return 0===t&&n===e.length?ao(e):ao(e.slice(t,n))}function Ro(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<=Mo)return String.fromCharCode.apply(String,e);for(var n="",r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=Mo));return n}(r)}po.TYPED_ARRAY_SUPPORT=void 0===we.TYPED_ARRAY_SUPPORT||we.TYPED_ARRAY_SUPPORT,lo(),po.poolSize=8192,po._augment=function(e){return e.__proto__=po.prototype,e},po.from=function(e,t,n){return ho(null,e,t,n)},po.TYPED_ARRAY_SUPPORT&&(po.prototype.__proto__=Uint8Array.prototype,po.__proto__=Uint8Array),po.alloc=function(e,t,n){return function(e,t,n,r){return fo(t),t<=0?co(e,t):void 0!==n?"string"==typeof r?co(e,t).fill(n,r):co(e,t).fill(n):co(e,t)}(null,e,t,n)},po.allocUnsafe=function(e){return mo(null,e)},po.allocUnsafeSlow=function(e){return mo(null,e)},po.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))},po.compare=function(e,t){if(!bo(e)||!bo(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},po.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}},po.concat=function(e,t){if(!uo(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return po.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=po.allocUnsafe(t),a=0;for(n=0;n<e.length;++n){var s=e[n];if(!bo(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(r,a),a+=s.length}return r},po.byteLength=_o,po.prototype._isBuffer=!0,po.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)wo(this,t,t+1);return this},po.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)wo(this,t,t+3),wo(this,t+1,t+2);return this},po.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)wo(this,t,t+7),wo(this,t+1,t+6),wo(this,t+2,t+5),wo(this,t+3,t+4);return this},po.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?Ro(this,0,e):xo.apply(this,arguments)},po.prototype.equals=function(e){if(!bo(e))throw new TypeError("Argument must be a Buffer");return this===e||0===po.compare(this,e)},po.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+">"},po.prototype.compare=function(e,t,n,r,a){if(!bo(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},po.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},po.prototype.indexOf=function(e,t,n){return vo(this,e,t,n,!0)},po.prototype.lastIndexOf=function(e,t,n){return vo(this,e,t,n,!1)},po.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 Io(this,e,t,n);case"utf8":case"utf-8":return To(this,e,t,n);case"ascii":return So(this,e,t,n);case"latin1":case"binary":return Eo(this,e,t,n);case"base64":return No(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ao(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},po.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Mo=4096;function Fo(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 $o(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 Oo(e,t,n){var r,a=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>a)&&(n=a);for(var s="",o=t;o<n;++o)s+=(r=e[o])<16?"0"+r.toString(16):r.toString(16);return s}function Do(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 Po(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 Lo(e,t,n,r,a,s){if(!bo(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 Bo(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 Uo(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 Wo(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 zo(e,t,n,r,a){return a||Wo(e,0,n,4),oo(e,t,n,r,23,4),n+4}function Vo(e,t,n,r,a){return a||Wo(e,0,n,8),oo(e,t,n,r,52,8),n+8}po.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),po.TYPED_ARRAY_SUPPORT)(n=this.subarray(e,t)).__proto__=po.prototype;else{var a=t-e;n=new po(a,void 0);for(var s=0;s<a;++s)n[s]=this[s+e]}return n},po.prototype.readUIntLE=function(e,t,n){e|=0,t|=0,n||Po(e,t,this.length);for(var r=this[e],a=1,s=0;++s<t&&(a*=256);)r+=this[e+s]*a;return r},po.prototype.readUIntBE=function(e,t,n){e|=0,t|=0,n||Po(e,t,this.length);for(var r=this[e+--t],a=1;t>0&&(a*=256);)r+=this[e+--t]*a;return r},po.prototype.readUInt8=function(e,t){return t||Po(e,1,this.length),this[e]},po.prototype.readUInt16LE=function(e,t){return t||Po(e,2,this.length),this[e]|this[e+1]<<8},po.prototype.readUInt16BE=function(e,t){return t||Po(e,2,this.length),this[e]<<8|this[e+1]},po.prototype.readUInt32LE=function(e,t){return t||Po(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},po.prototype.readUInt32BE=function(e,t){return t||Po(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},po.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||Po(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},po.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||Po(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},po.prototype.readInt8=function(e,t){return t||Po(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},po.prototype.readInt16LE=function(e,t){t||Po(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},po.prototype.readInt16BE=function(e,t){t||Po(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},po.prototype.readInt32LE=function(e,t){return t||Po(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},po.prototype.readInt32BE=function(e,t){return t||Po(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},po.prototype.readFloatLE=function(e,t){return t||Po(e,4,this.length),so(this,e,!0,23,4)},po.prototype.readFloatBE=function(e,t){return t||Po(e,4,this.length),so(this,e,!1,23,4)},po.prototype.readDoubleLE=function(e,t){return t||Po(e,8,this.length),so(this,e,!0,52,8)},po.prototype.readDoubleBE=function(e,t){return t||Po(e,8,this.length),so(this,e,!1,52,8)},po.prototype.writeUIntLE=function(e,t,n,r){e=+e,t|=0,n|=0,r||Lo(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},po.prototype.writeUIntBE=function(e,t,n,r){e=+e,t|=0,n|=0,r||Lo(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},po.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||Lo(this,e,t,1,255,0),po.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},po.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||Lo(this,e,t,2,65535,0),po.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Bo(this,e,t,!0),t+2},po.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||Lo(this,e,t,2,65535,0),po.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Bo(this,e,t,!1),t+2},po.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||Lo(this,e,t,4,4294967295,0),po.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):Uo(this,e,t,!0),t+4},po.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||Lo(this,e,t,4,4294967295,0),po.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Uo(this,e,t,!1),t+4},po.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);Lo(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},po.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var a=Math.pow(2,8*n-1);Lo(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},po.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||Lo(this,e,t,1,127,-128),po.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},po.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||Lo(this,e,t,2,32767,-32768),po.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Bo(this,e,t,!0),t+2},po.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||Lo(this,e,t,2,32767,-32768),po.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Bo(this,e,t,!1),t+2},po.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||Lo(this,e,t,4,2147483647,-2147483648),po.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):Uo(this,e,t,!0),t+4},po.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||Lo(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),po.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Uo(this,e,t,!1),t+4},po.prototype.writeFloatLE=function(e,t,n){return zo(this,e,t,!0,n)},po.prototype.writeFloatBE=function(e,t,n){return zo(this,e,t,!1,n)},po.prototype.writeDoubleLE=function(e,t,n){return Vo(this,e,t,!0,n)},po.prototype.writeDoubleBE=function(e,t,n){return Vo(this,e,t,!1,n)},po.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||!po.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},po.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&&!po.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=bo(e)?e:Go(new po(e,r).toString()),i=o.length;for(s=0;s<n-t;++s)this[s+t]=o[s%i]}return this};var Ho=/[^+\/0-9A-Za-z-_]/g;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;to||no();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 eo(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=Zs[e.charCodeAt(t)]<<18|Zs[e.charCodeAt(t+1)]<<12|Zs[e.charCodeAt(t+2)]<<6|Zs[e.charCodeAt(t+3)],o[u++]=a>>16&255,o[u++]=a>>8&255,o[u++]=255&a;return 2===s?(a=Zs[e.charCodeAt(t)]<<2|Zs[e.charCodeAt(t+1)]>>4,o[u++]=255&a):1===s&&(a=Zs[e.charCodeAt(t)]<<10|Zs[e.charCodeAt(t+1)]<<4|Zs[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(Ho,"")).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(ms(e))return"string"===t?[]:[e.length];if(Ls(e)){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if(Bs(e))return[e.buffer.size/(null==t?4:ft(t))];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||ms(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&Ct().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Yo(e,r,[]),r}function Yo(e,t,n){if(n=n||[],!Array.isArray(e)&&!ms(e))return void Ze(0===t.length,(()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`));Ze(t.length>0,(()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`)),Ze(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 As())return Qo(r,e.dtype,t,n),e;let a=gt(e);if("string"!==a&&["bool","int32","float32"].indexOf(r)>=0&&(a=r),Qo(r,a,t,n),null==e||!ms(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);ms(e)||Array.isArray(e)||(e=[e]);const o="string"!==a?ps(e,a):gs(e,[],!0);return Ks.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)=>{Ks.startScope(n);try{const t=r(...e);return Et(t)&&console.error("Cannot return a Promise inside of tidy."),Ks.endScope(t),t}catch(e){throw Ks.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");et(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 Ks.runKernel("Complex",a)}});function ri(e,t,n,r){if(null==r)r=gt(e);else if("complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(Bs(e)||Ls(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 Ks.backend.createTensorFromGPUData(e,t||n,r)}if(!ms(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){It(t);const e=nt(t),r=nt(n);Ze(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!==nt(t.slice(e));Ze(n[e]===t[e]||!a,(()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `))}}return ms(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==r?ps(e,r):gs(e,[],!0),Ks.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=>ms(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 Ks}function ui(e,t){return Ks.tidy(e,t)}function li(e){Ws(e).forEach((e=>e.dispose()))}function ci(e){return Ks.keep(e)}function pi(e){return Ks.setBackend(e)}function hi(){return Ks.backendName}function di(e,t,n=1){return Ks.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=nt(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=nt(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=nt(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(;0==(8388608&t);)n-=8388608,t<<=1;return t&=-8388609,n+=947912704,t|n},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let e=1024;e<2048;e++)t[e]=939524096+(e-1024<<13);return t}(),t=function(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}(),n=function(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}();return r=>{const a=new ArrayBuffer(4*r.length),s=new Uint32Array(a);for(let a=0;a<r.length;a++){const o=r[a],i=e[n[o>>10]+(1023&o)]+t[o>>10];s[a]=i}return new Float32Array(a)}}();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=nt(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=Ks.backend;"uploadToGPU"in e&&nt(o.shape)>=Ct().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="undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa;function vi(e){return wi?po.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(!Ct().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e="undefined"==typeof window?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function $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 Ct().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(!Ct().getBool("IS_BROWSER")||"undefined"==typeof window||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=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 po.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=po.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 Ct().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(){Ze(Ct().getBool("IS_BROWSER"),(()=>"Current environment is not a web browser")),Ze("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(!Ct().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){Ze(null!=e&&Array.isArray(e)&&e.length>0,(()=>"promises must be a none empty array"))}(e),function(e,t){Ze(e>=0&&e<=1,(()=>`Progress fraction must be in range [0, 1], but got startFraction ${e}`)),Ze(t>=0&&t<=1,(()=>`Progress fraction must be in range [0, 1], but got endFraction ${t}`)),Ze(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?Ct().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]*nt(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=>Ct().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?(Ze("function"==typeof t.fetchFunc,(()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)")),this.fetch=t.fetchFunc):this.fetch=Ct().platform.fetch,Ze(null!=e&&e.length>0,(()=>"URL path for http must not be null, undefined or empty.")),Array.isArray(e)&&Ze(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?Ct().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){Ze(null!=e,(()=>"scheme must not be undefined or null.")),e.endsWith(pu)&&(e=e.slice(0,e.indexOf(pu))),Ze(e.length>0,(()=>"scheme must not be an empty string."));const n=hu.getInstance();Ze(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){Ze(e!==t,(()=>`Old path and new path are the same: '${e}'`));const r=Ai.getLoadHandlers(e);Ze(r.length>0,(()=>`Copying failed because no load handler is found for source URL ${e}.`)),Ze(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);Ze(s.length>0,(()=>`Copying failed because no save handler is found for destination URL ${t}.`)),Ze(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){const a=arguments;return new lu(cu(...a))},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 Ks.runKernel(tn,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]=Us(a,s);const o={a,b:s},i={transposeA:n,transposeB:r};return Ks.runKernel(Yt,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 Ks.runKernel(fr,s,o)}}),_u=ti({imag_:function(e){const t={input:Jo(e,"input","imag")};return Ks.runKernel("Imag",t)}}),xu=ti({neg_:function(e){const t={x:Jo(e,"x","neg")};return Ks.runKernel("Neg",t)}}),wu=ti({real_:function(e){const t={input:Jo(e,"input","real")};return Ks.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()),Ze(r.rank===t.length,(()=>`Error in transpose: rank of input ${r.rank} must match length of perm ${t}.`)),t.forEach((e=>{Ze(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=Ks.runKernel(ia,{x:e},s),t=Ks.runKernel(ia,{x:t},s),n&&(t=xu(t)),ni(e,t)})):Ks.runKernel(ia,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(tt(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!=xa(ha,Ks.backendName)){const n={pixels:e},r={numChannels:t};return Ks.runKernel(ha,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===nt(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=[..._t(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:nt(t.shape)/i,sliceSize:o,strides:[..._t(n.slice(0,a)),1],outputSize:nt(n)}}function Fu(e,t,n){const r=e.shape.length;Ze(r===t.length,(()=>`Error in slice${r}D: Length of begin ${t} must match the rank of the array (${r}).`)),Ze(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)Ze(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]=Ye(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=Ye(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?Ye(0,o,u):Ye(-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=>{Ze(-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:(Ze(-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&&0!=(o&o-1))throw new Error("Multiple ellipses in slice is not allowed.");let c=!1;const p={dims:l.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:l.slice(),beginMask:a,endMask:s,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:u};for(let e=0;e<p.dims;e++)c&&0!=(1<<e&i)&&p.numAddAxisAfterEllipsis++,1<<e&o&&(c=!0);c||(p.ellipsisMask|=1<<p.dims,p.dims++);const h={dims:e.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};!function(e,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let n=0;t.beginValid=null!=e.begin,t.endValid=null!=e.end,t.begin=new Array(t.dims),t.end=new Array(t.dims),t.strides=new Array(t.dims),t.finalShapeGatherIndices=[],t.finalShapeGatherIndicesSparse=[],t.inputShapeGatherIndicesSparse=new Array(t.dims);for(let r=0;r<e.dims;r++)if(1<<r&e.ellipsisMask){const a=Math.min(t.dims-(e.dims-r)+1+e.numAddAxisAfterEllipsis,t.dims);for(;n<a;n++)t.begin[n]=0,t.end[n]=0,t.strides[n]=1,t.beginMask|=1<<n,t.endMask|=1<<n,t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(-1),t.inputShapeGatherIndicesSparse[n]=r}else if(1<<r&e.newAxisMask)t.finalShapeGatherIndices.push(-2),t.finalShapeGatherIndicesSparse.push(-1);else{if(n===t.begin.length)throw Error(`Index out of range using input dim ${n}; input has only ${t.dims} dims, ${t.begin.length}.`);null!=e.begin&&(t.begin[n]=e.begin[r]),null!=e.end&&(t.end[n]=e.end[r]),t.strides[n]=e.strides[r],e.beginMask&1<<r&&(t.beginMask|=1<<n),e.endMask&1<<r&&(t.endMask|=1<<n),e.shrinkAxisMask&1<<r?(t.finalShapeGatherIndices.push(-1),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<n):(t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(r)),t.inputShapeGatherIndicesSparse[n]=r,n++}}(p,h);let d=!0,f=!0,m=!0;const g=[],y=[];for(let t=0;t<e.length;++t){if(0===h.strides[t])throw Error(`strides[${t}] must be non-zero`);const n=!!(h.shrinkAxisMask&1<<t),r=e[t];if(-1===r){g.push(n?1:-1);continue}const a=[h.beginMask&1<<t,h.endMask&1<<t],s=[h.strides[t]>0?0:-1,h.strides[t]>0?r:r-1];if(n&&h.strides[t]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&1===h.strides[t];const o=!!(h.beginMask&1<<t&&h.endMask&1<<t);if(h.beginValid&&h.endValid){if(n){const e=h.begin[t]<0?r+h.begin[t]:h.begin[t];if(h.begin[t]=e,h.end[t]=h.begin[t]+1,e<0||e>=r)throw Error(`slice index ${h.begin[t]} of dimension ${t} out of bounds.`)}else h.begin[t]=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]=Us(n,r);const a={a:n,b:r};return Ks.runKernel(Pt,a)}}),Yu=ti({floorDiv_:function(e,t){let n=Jo(e,"a","floorDiv"),r=Jo(t,"b","floorDiv");[n,r]=Us(n,r);const a={a:n,b:r};return Ks.runKernel(Mn,a)}}),Qu=ti({div_:function(e,t){let n=Jo(e,"a","div"),r=Jo(t,"b","div");if([n,r]=Us(n,r),"int32"===n.dtype&&"int32"===r.dtype)return Yu(n,r);const a={a:n,b:r};return Ks.runKernel(vn,a,{})}}),Ju=ti({mul_:function(e,t){let n=Jo(e,"a","mul"),r=Jo(t,"b","mul");[n,r]=Us(n,r);const a={a:n,b:r};return Ks.runKernel(ur,a)}}),Zu=ti({abs_:function(e){const t=Jo(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return Ks.runKernel("ComplexAbs",e)}{const e={x:t};return Ks.runKernel("Abs",e)}}}),el=ti({acos_:function(e){const t={x:Jo(e,"x","acos")};return Ks.runKernel(Ot,t)}}),tl=ti({acosh_:function(e){const t={x:Jo(e,"x","acosh")};return Ks.runKernel(Dt,t)}}),nl=ti({addN_:function(e){Ze(Array.isArray(e),(()=>"The argument passed to tf.addN() must be a list of tensors")),Ze(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(!rt(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));const r=t;return Ks.runKernel(Lt,r)}}),rl=ti({all_:function(e,t=null,n=!1){const r={x:Jo(e,"x","all","bool")},a={axis:t,keepDims:n};return Ks.runKernel(Bt,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 Ks.runKernel(Ut,r,a)}}),sl=ti({argMax_:function(e,t=0){const n={x:Jo(e,"x","argMax")},r={axis:t};return Ks.runKernel(Wt,n,r)}}),ol=ti({argMin_:function(e,t=0){const n={x:Jo(e,"x","argMin")},r={axis:t};return Ks.runKernel(zt,n,r)}}),il=ti({asin_:function(e){const t={x:Jo(e,"x","asin")};return Ks.runKernel(Vt,t)}}),ul=ti({asinh_:function(e){const t={x:Jo(e,"x","asinh")};return Ks.runKernel(Ht,t)}}),ll=ti({atan_:function(e){const t={x:Jo(e,"x","atan")};return Ks.runKernel(Gt,t)}}),cl=ti({atan2_:function(e,t){let n=Jo(e,"a","atan2"),r=Jo(t,"b","atan2");[n,r]=Us(n,r);const a={a:n,b:r};return Ks.runKernel(Kt,a)}}),pl=ti({atanh_:function(e){const t={x:Jo(e,"x","atanh")};return Ks.runKernel(jt,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)Ze(at(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=>{Ze(at(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 Ks.runKernel(vr,n,r)}}),Nl=ti({avgPool_:function(e,t,n,r,a){const s=Jo(e,"x","avgPool","float32");Ze(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]])),Ze(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=Ks.runKernel(qt,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]])),Ze(5===i.rank,(()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`)),Ze("NDHWC"===s,(()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`)),Ze("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=Ks.runKernel(Xt,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 Ks.runKernel(Ln,t)}}),Rl=ti({concat_:function(e,t=0){Ze(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 Ks.runKernel(an,r,a)}}),Ml=ti({sigmoid_:function(e){const t={x:Jo(e,"x","sigmoid","float32")};return Ks.runKernel(Br,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 Ks.runKernel(Dr,a,s)}}),$l=ti({tanh_:function(e){const t={x:Jo(e,"x","tanh","float32")};return Ks.runKernel(ra,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));Ze(r.rank>=1+t.length,(()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`)),Ze(n.length===t.length,(()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`)),Ze(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 Ks.runKernel(Qt,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")),Ze(i.rank===u.rank,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),Ze(null==c||i.rank===c.rank,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),Ze(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=Ks.runKernel(Fn,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")),Ze(2===o.rank,(()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`)),Ze(2===i.rank||1===i.rank,(()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`)),Ze(2===u.rank||1===u.rank,(()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${u.rank}.`)),null!=l&&Ze(2===l.rank||1===l.rank,(()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${l.rank}.`)),null!=c&&Ze(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")),Ze(3===o.rank,(()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`)),Ze(3===i.rank||1===i.rank,(()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`)),Ze(3===u.rank||1===u.rank,(()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${u.rank}.`)),null!=l&&Ze(3===l.rank||1===l.rank,(()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${l.rank}.`)),null!=c&&Ze(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")),Ze(4===o.rank,(()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`)),Ze(4===i.rank||1===i.rank,(()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`)),Ze(4===u.rank||1===u.rank,(()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${u.rank}.`)),null!=l&&Ze(4===l.rank||1===l.rank,(()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${l.rank}.`)),null!=c&&Ze(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");Ze("int32"===r.dtype,(()=>`Error in bincount: input dtype must be int32, but got ${r.dtype}`)),Ze(n>=0,(()=>`size must be non-negative, but got ${n}.`)),Ze(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 Ks.runKernel(Jt,s,o)}}),zl=ti({bitwiseAnd_:function(e,t){const n=Jo(e,"x","bitwiseAnd"),r=Jo(t,"y","bitwiseAnd");if(!rt(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 Ks.runKernel(Zt,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 Ks.runKernel(en,a)}}),Hl=ti({broadcastTo_:function(e,t){let n=Jo(e,"broadcastTo","x");const r=n.shape;if(It(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 Ks.runKernel(aa,i,u)}});function Gl(e,t="float32",n){return t=t||"float32",It(e),new Ts(e,t,n)}const jl=ti({ceil_:function(e){const t={x:Jo(e,"x","ceil","float32")};return Ks.runKernel(nn,t)}});function Kl(e,t,n){It(e);const r={shape:e,value:t,dtype:n=n||gt(t)};return Ks.runKernel(An,{},r)}const ql=ti({clipByValue_:function(e,t,n){const r=Jo(e,"x","clipByValue");if(Ze(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 Ks.runKernel(rn,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]])),Ze(4===l.rank,(()=>`Error in conv2d: input must be rank 4, but got rank ${l.rank}.`)),Ze(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];Ze(p===u.shape[2],(()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${u.shape[2]}.`)),Ze(kl(n,s),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`)),Ze(Il(s),(()=>"Error in conv2D: Dilated rates should be larger than 0.")),Ze(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=Ks.runKernel(sn,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]])),Ze(3===l.rank,(()=>`Error in conv1d: input must be rank 3, but got rank ${l.rank}.`)),Ze(3===u.rank,(()=>`Error in conv1d: filter must be rank 3, but got rank ${u.rank}.`)),Sl("conv1d",r,o),Ze(l.shape[2]===u.shape[1],(()=>`Error in conv1d: depth of input (${l.shape[2]}) must match input depth for filter ${u.shape[1]}.`)),Ze(kl(n,s),(()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${s}'`)),Ze(Il(s),(()=>"Error in conv1D: Dilated rates should be larger than 0.")),Ze(Il(n),(()=>"Error in conv1D: Stride should be larger than 0.")),Ze("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){Ze(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]]),Ze(4===i.length,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`)),Ze(4===u.rank,(()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${u.rank}`)),Ze(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];Ze(c===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${n.shape[2]}.`)),Ze(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=Ks.runKernel(on,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]])),Ze(5===u.rank,(()=>`Error in conv3d: input must be rank 5, but got rank ${u.rank}.`)),Ze(5===i.rank,(()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`)),Ze(u.shape[4]===i.shape[3],(()=>`Error in conv3d: depth of input (${u.shape[4]}) must match input depth for filter ${i.shape[3]}.`)),Ze(kl(n,s),(()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`)),Ze("NDHWC"===a,(()=>`Error in conv3d: got dataFormat of ${a} but only NDHWC is currently supported.`)),Ze(Il(s),(()=>"Error in conv3D: Dilated rates should be larger than 0.")),Ze(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=Ks.runKernel(un,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){Ze(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];Ze(5===s.length,(()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`)),Ze(5===o.rank,(()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`)),Ze(5===n.rank,(()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`)),Ze(u===n.shape[3],(()=>`Error in conv3dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[3]}.`)),Ze(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=Ks.runKernel(cn,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 Ks.runKernel("Cos",t)}}),ic=ti({cosh_:function(e){const t={x:Jo(e,"x","cosh","float32")};return Ks.runKernel(pn,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 Ks.runKernel(hn,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 Ks.runKernel(dn,a,s)}}),cc=ti({denseBincount_:function(e,t,n,r=!1){const a=Jo(e,"x","denseBincount"),s=Jo(t,"weights","denseBincount");Ze("int32"===a.dtype,(()=>`Error in denseBincount: input dtype must be int32, but got ${a.dtype}`)),Ze(a.rank<=2,(()=>`Error in denseBincount: input must be at most rank 2, but got rank ${a.rank}.`)),Ze(n>=0,(()=>`size must be non-negative, but got ${n}.`)),Ze(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 Ks.runKernel(mn,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];Ze(t>1,(()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`)),Ze(a*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${a} and ${t} for depthToSpace with input shape\n ${r.shape}`)),Ze(s*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${s} and ${t} for depthToSpace with input shape\n ${r.shape}`)),Ze(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 Ks.runKernel(gn,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]])),Ze(4===l.rank,(()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${l.rank}.`)),Ze(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];Ze(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=Ks.runKernel(yn,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 Ks.runKernel(bn,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");Ze(3===o.rank||4===o.rank,(()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`)),Ze(3===i.rank,(()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`)),Ze("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),Ze(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=Ks.runKernel(_n,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]=Us(n,r),Tu(n.shape,r.shape);const a={a:n,b:r};return Ks.runKernel(Tn,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 Ks.runKernel($r,i)}}),yc=ti({zerosLike_:function(e){const t={x:Jo(e,"x","zerosLike")};return Ks.runKernel(ca,t)}}),bc=ti({divNoNan_:function(e,t){let n=Jo(e,"a","div"),r=Jo(t,"b","div");[n,r]=Us(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");Ze(!(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(Ze(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 Ks.runKernel("Einsum",n,r)}}),wc=ti({elu_:function(e){const t={x:Jo(e,"x","elu","float32")};return Ks.runKernel(kn,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");Ze("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 Ks.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){Ze(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 Ks.runKernel(Jn,r,a)}}),Fc=ti({min_:function(e,t=null,n=!1){const r={x:Jo(e,"x","min")},a={axis:t,keepDims:n};return Ks.runKernel(ar,r,a)}}),$c=ti({pow_:function(e,t){let n=Jo(e,"base","pow"),r=Jo(t,"exp","pow");[n,r]=Us(n,r);const a={a:n,b:r};return Ks.runKernel("Pow",a)}});function Oc(e,t){if((ms(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&&ms(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 Ks.runKernel(Wr,t)}}),Pc=ti({square_:function(e){const t=Jo(e,"x","square");return Ks.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 Ks.runKernel(zr,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=lt(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 Ks.runKernel(Sn,t)}}),Vc=ti({expandDims_:function(e,t=0){const n=Jo(e,"x","expandDims","string_or_numeric");Ze(t<=n.rank,(()=>"Axis must be <= rank of the tensor"));const r={input:n},a={dim:t};return Ks.runKernel(En,r,a)}}),Hc=ti({expm1_:function(e){const t={x:Jo(e,"x","expm1")};return Ks.runKernel(Nn,t)}}),Gc=ti({tile_:function(e,t){const n=Jo(e,"x","tile","string_or_numeric");Ze(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 Ks.runKernel(aa,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 Ks.runKernel(Rn,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 Ks.runKernel($n,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]=Us(n,r),Tu(n.shape,r.shape);const a={a:n,b:r};return Ks.runKernel(Dn,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]=Us(n,r),Tu(n.shape,r.shape);const a={a:n,b:r};return Ks.runKernel(Pn,a)}}),Qc=ti({isFinite_:function(e){const t={x:Jo(e,"x","isFinite")};return Ks.runKernel(Bn,t)}}),Jc=ti({isInf_:function(e){const t={x:Jo(e,"x","isInf")};return Ks.runKernel(Un,t)}}),Zc=ti({isNaN_:function(e){const t={x:Jo(e,"x","isNaN")};return Ks.runKernel(Wn,t)}}),ep=ti({leakyRelu_:function(e,t=.2){const n={x:Jo(e,"x","leakyRelu")},r={alpha:t};return Ks.runKernel(zn,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]=Us(n,r),Tu(n.shape,r.shape);const a={a:n,b:r};return Ks.runKernel(Vn,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]=Us(n,r),Tu(n.shape,r.shape);const a={a:n,b:r};return Ks.runKernel(Hn,a)}}),rp=ti({localResponseNormalization_:function(e,t=5,n=1,r=1,a=.5){const s=Jo(e,"x","localResponseNormalization");Ze(4===s.rank||3===s.rank,(()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank ${s.rank}.`)),Ze(at(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=Ks.runKernel(Yn,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 Ks.runKernel("Log",t)}}),sp=ti({log1p_:function(e){const t={x:Jo(e,"x","log1p")};return Ks.runKernel(jn,t)}});function op(e){return Ks.customGrad(e)}const ip=ti({softplus_:function(e){const t={x:Jo(e,"x","softplus")};return Ks.runKernel(Ur,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]=Us(n,r);const a={a:n,b:r};return Ks.runKernel(na,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=lt(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 Ks.runKernel(Kn,a)}}),dp=ti({logicalNot_:function(e){const t={x:Jo(e,"x","logicalNot","bool")};return Ks.runKernel(qn,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 Ks.runKernel(Xn,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(nt(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 Ks.runKernel(Fr,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]])),Ze(4===o.rank,(()=>`Error in maxPool: input must be rank 4 but got rank ${o.rank}.`)),Ze(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=Ks.runKernel(er,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]])),Ze(5===i.rank,(()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`)),Ze("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=Ks.runKernel(tr,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=Ks.runKernel(nr,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]=Us(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 Ks.runKernel(Zn,a)}}),vp=ti({mean_:function(e,t=null,n=!1){const r={x:Jo(e,"x","mean")},a={axis:t,keepDims:n};return Ks.runKernel(rr,r,a)}});function kp(e,t="float32"){if(It(e),"complex64"===t){const t=kp(e,"float32"),n=kp(e,"float32");return ni(t,n)}const n=kt(nt(e),t);return Ks.makeTensor(n,e,t)}function Ip(e,t="float32"){if(It(e),"complex64"===t){const t=Ip(e,"float32"),n=kp(e,"float32");return ni(t,n)}const n=vt(nt(e),t);return Ks.makeTensor(n,e,t)}const Tp=ti({minimum_:function(e,t){let n=Jo(e,"a","minimum"),r=Jo(t,"b","minimum");[n,r]=Us(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 Ks.runKernel(sr,a)}}),Sp=ti({mirrorPad_:function(e,t,n){Ze("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");Ze(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++)Ze(2===t[e].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),Ze(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 Ks.runKernel(or,o,s)}}),Ep=ti({mod_:function(e,t){let n=Jo(e,"a","mod"),r=Jo(t,"b","mod");[n,r]=Us(n,r);const a={a:n,b:r};return Ks.runKernel("Mod",a)}}),Np=ti({moments_:function(e,t=null,n=!1){const r=lt(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=Ks.runKernel(ir,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]=Us(n,r),Tu(n.shape,r.shape);const a={a:n,b:r};return Ks.runKernel(lr,a)}}),Mp=ti({onesLike_:function(e){const t={x:Jo(e,"x","onesLike")};return Ks.runKernel(dr,t)}}),Fp=ti({outerProduct_:function(e,t){const n=Jo(e,"v1","outerProduct"),r=Jo(t,"v2","outerProduct");Ze(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 Ks.runKernel(gr,s,a)}}),Op=ti({pad1d_:function(e,t,n=0){return Ze(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 Ze(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 Ze(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 Ze(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");Ze(r.rank>=1+t.length,(()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`)),Ze(n.length===t.length,(()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`)),Ze(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 Ks.runKernel(Vr,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]])),Ze(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))),r=n.map((e=>e-1)),a=r.map((e=>Math.floor(e/2))),s=r.map(((e,t)=>e-a[t]));return r.map(((e,t)=>[a[t],s[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])),u=t.map(((e,t)=>[r[t],i[t]])),l=t.map(((e,t)=>[0,o[t]]));return[u,l]}([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 Ks.runKernel(yr,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 Ks.runKernel(br,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=Ks.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=Ks.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 Ks.runKernel("RaggedTensorToTensor",l,c)}}),Kp=ti({rand_:function(e,t,n){It(e);const r=nt(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 Ks.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){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}function Yp(e){var t={exports:{}};return e(t,t.exports),t.exports}var Qp=Yp((function(e){!function(e,t,n){function r(e){var t,n=this,r=(t=4022871197,function(e){e=String(e);for(var n=0;n<e.length;n++){var r=.02519603282416938*(t+=e.charCodeAt(n));r-=t=r>>>0,t=(r*=t)>>>0,t+=4294967296*(r-=t)}return 2.3283064365386963e-10*(t>>>0)});n.next=function(){var e=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=e-(n.c=0|e)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(e),n.s0<0&&(n.s0+=1),n.s1-=r(e),n.s1<0&&(n.s1+=1),n.s2-=r(e),n.s2<0&&(n.s2+=1),r=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)})),Jp=Yp((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)})),Zp=Yp((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)})),eh=Yp((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)})),th=Yp((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)})),nh=Yp((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)})),rh=Xp(Object.freeze({__proto__:null,default:{}})),ah=Yp((function(e){!function(t,n,r){var a,s=256,o=r.pow(s,6),i=r.pow(2,52),u=2*i,l=255;function c(e,l,c){var g=[],y=f(d((l=1==l?{entropy:!0}:l||{}).entropy?[e,m(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)),m(e)}catch(e){var r=t.navigator,o=r&&r.plugins;return[+new Date,t,o,t.screen,m(n)]}}():e,3),g),b=new p(g),_=function(){for(var e=b.g(6),t=o,n=0;e<i;)e=(e+n)*s,t*=s,n=b.g(1);for(;e>=u;)e/=2,t/=2,n>>>=1;return(e+n)/t};return _.int32=function(){return 0|b.g(4)},_.quick=function(){return b.g(4)/4294967296},_.double=_,f(m(b.S),n),(l.pass||c||function(e,t,n,a){return a&&(a.S&&h(a,b),e.state=function(){return h(b,{})}),n?(r.random=e,t):e})(_,y,"global"in l?l.global:this==r,l.state)}function p(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=l&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=l&a+1],n=n*s+i[l&(i[a]=i[o=l&o+t])+(i[o]=t)];return r.i=a,r.j=o,n})(s)}function h(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function d(e,t){var n,r=[],a=typeof e;if(t&&"object"==a)for(n in e)try{r.push(d(e[n],t-1))}catch(e){}return r.length?r:"string"==a?e:e+"\0"}function f(e,t){for(var n,r=e+"",a=0;a<r.length;)t[l&a]=l&(n^=19*t[l&a])+r.charCodeAt(a++);return m(t)}function m(e){return String.fromCharCode.apply(0,e)}if(f(r.random(),n),e.exports){e.exports=c;try{a=rh}catch(e){}}else r.seedrandom=c}("undefined"!=typeof self?self:qp,[],Math)}));ah.alea=Qp,ah.xor128=Jp,ah.xorwow=Zp,ah.xorshift7=eh,ah.xor4096=th,ah.tychei=nh;var sh=ah;class oh{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=sh.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 ih{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const a=r||Math.random();this.randu=sh.alea(a.toString()),this.randn=new oh(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 uh{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=sh.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const lh=ti({randomGamma_:function(e,t,n=1,r="float32",a){if(It(e),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error(`Unsupported data type ${r}`);const s=new ih(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()}}),ch=ti({randomNormal_:function(e,t=0,n=1,r,a){if(It(e),null!=r&&"bool"===r)throw new Error(`Unsupported data type ${r}`);const s=new oh(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()}}),ph=ti({randomStandardNormal_:function(e,t,n){if(null!=t&&"bool"===t)throw new Error(`Unsupported data type ${t}`);return ch(e,0,1,t,n)}}),hh=ti({randomUniform_:function(e,t=0,n=1,r="float32",a){It(e);const s=Gl(e,r),o=new uh(t,n,null,a);for(let e=0;e<s.values.length;e++)s.values[e]=o.nextValue();return s.toTensor()}}),dh=ti({randomUniformInt_:function(e,t,n,r){return hh(e,t,n,"int32",r)}});function fh(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 Ks.runKernel(_r,{},a)}const mh=ti({reciprocal_:function(e){const t={x:Jo(e,"x","reciprocal")};return Ks.runKernel(xr,t)}}),gh=ti({relu_:function(e){const t={x:Jo(e,"x","relu")};return Ks.runKernel(wr,t)}}),yh=ti({relu6_:function(e){const t={x:Jo(e,"x","relu6")};return Ks.runKernel(Er,t)}}),bh=ti({reverse_:function(e,t){const n={x:Jo(e,"x","reverse")},r={dims:t};return Ks.runKernel(Nr,n,r)}}),_h=ti({reverse1d_:function(e){const t=Jo(e,"x","reverse");return Ze(1===t.rank,(()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`)),bh(t,0)}}),xh=ti({reverse2d_:function(e,t){const n=Jo(e,"x","reverse");return Ze(2===n.rank,(()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`)),bh(n,t)}}),wh=ti({reverse3d_:function(e,t){const n=Jo(e,"x","reverse");return Ze(3===n.rank,(()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`)),bh(n,t)}}),vh=ti({reverse4d_:function(e,t){const n=Jo(e,"x","reverse");return Ze(4===n.rank,(()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`)),bh(n,t)}}),kh=ti({round_:function(e){const t={x:Jo(e,"x","round")};return Ks.runKernel(Ar,t)}}),Ih=ti({rsqrt_:function(e){const t={x:Jo(e,"x","rsqrt","float32")};return Ks.runKernel(Cr,t)}}),Th=ti({selu_:function(e){const t={x:Jo(e,"x","selu")};return Ks.runKernel(Or,t)}}),Sh=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");Ze(4===c.rank,(()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`)),Ze(4===u.rank,(()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${u.rank}.`)),Ze(4===l.rank,(()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${u.rank}.`)),Ze(1===l.shape[0],(()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${l.shape[0]}.`)),Ze(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];Ze(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}}),Eh=ti({sign_:function(e){const t={x:Jo(e,"x","sign")};return Ks.runKernel(Lr,t)}}),Nh=ti({sin_:function(e){const t={x:Jo(e,"x","sin","float32")};return Ks.runKernel("Sin",t)}}),Ah=ti({sinh_:function(e){const t={x:Jo(e,"x","sinh")};return Ks.runKernel(Pr,t)}}),Ch=ti({slice1d_:function(e,t,n){const r=Jo(e,"x","slice1d");return Ze(1===r.rank,(()=>`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`)),Fl(r,[t],[n])}}),Rh=ti({slice2d_:function(e,t,n){const r=Jo(e,"x","slice2d");return Ze(2===r.rank,(()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`)),Fl(r,t,n)}}),Mh=ti({slice3d_:function(e,t,n){const r=Jo(e,"x","slice3d");return Ze(3===r.rank,(()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`)),Fl(r,t,n)}}),Fh=ti({slice4d_:function(e,t,n){const r=Jo(e,"x","slice4d");return Ze(4===r.rank,(()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`)),Fl(r,t,n)}}),$h=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 Ks.runKernel(Gr,r,a)}}),Oh=ti({fft_:function(e){Ze("complex64"===e.dtype,(()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`));const t={input:e};return Ks.runKernel("FFT",t)}}),Dh=ti({ifft_:function(e){Ze("complex64"===e.dtype,(()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`));const t={input:e};return Ks.runKernel("IFFT",t)}}),Ph=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=Dh(a)}else{const a=[n,2*(t-1)],s=El(wu(e),[n,t]),o=El(_u(e),[n,t]),i=bh(Fl(s,[0,1],[n,t-2]),1),u=Ju(bh(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=Dh(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}}),Lh=ti({split_:function(e,t,n=0){const r={x:Jo(e,"x","split")},a={numOrSizeSplits:t,axis:n};return Ks.runKernel(Hr,r,a)}}),Bh=ti({rfft_:function(e,t){Ze("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=Oh(o),u=Math.floor(n/2)+1,l=wu(i),c=_u(i),p=Lh(l,[u,n-u],l.shape.length-1),h=Lh(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)}}),Uh=ti({squaredDifference_:function(e,t){let n=Jo(e,"a","squaredDifference"),r=Jo(t,"b","squaredDifference");[n,r]=Us(n,r),Tu(n.shape,r.shape);const a={a:n,b:r};return Ks.runKernel(Qr,a,{})}}),Wh=ti({squeeze_:function(e,t){const n=Jo(e,"x","squeeze","string_or_numeric");return El(n,ct(n.shape,t).newShape)}}),zh=ti({stack_:function(e,t=0){const n=Zo(e,"tensors","stack","string_or_numeric");Ze(n.length>=1,(()=>"Pass at least one tensor to tf.stack")),n.length>0&&Ze(t<=n[0].rank,(()=>"Axis must be <= rank of the tensor"));const r=n,a={axis:t};return Ks.runKernel(mr,r,a)}}),Vh=ti({step_:function(e,t=0){const n={x:Jo(e,"x","step")},r={alpha:t};return Ks.runKernel(pa,n,r)}}),Hh=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 Ks.runKernel(Jr,l,c)}}),Gh=ti({tan_:function(e){const t={x:Jo(e,"x","tan","float32")};return Ks.runKernel("Tan",t)}});function jh(e,t){tt(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 Kh(e,t,n){if(tt(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 qh=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 Ks.runKernel(Mr,o,{})}}),Xh=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]=Ks.runKernel(sa,s,o);return{values:i,indices:u}}}),Yh=ti({truncatedNormal_:function(e,t=0,n=1,r,a){if(It(e),null!=r&&"bool"===r)throw new Error("Unsupported data type $ { dtype }");const s=new oh(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()}}),Qh=ti({unique_:function(e,t=0){const n=Jo(e,"x","unique","string_or_numeric");Ze(n.rank>0,(()=>"The input tensor must be at least 1D"));const r={x:n},a={axis:t},[s,o]=Ks.runKernel(ua,r,a);return{values:s,indices:o}}}),Jh=ti({unsortedSegmentSum_:function(e,t,n){const r=Jo(e,"x","unsortedSegmentSum"),a=Jo(t,"segmentIds","unsortedSegmentSum","int32");Ze(at(n),(()=>"numSegments must be of dtype int"));const s={x:r,segmentIds:a},o={numSegments:n};return Ks.runKernel("UnsortedSegmentSum",s,o)}}),Zh=ti({unstack_:function(e,t=0){const n=Jo(e,"x","unstack","string_or_numeric");Ze(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 Ks.runKernel(la,r,a)}});function ed(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 td=async function(e){const t=Jo(e,"condition","whereAsync","bool"),n=await t.data(),r=ed(t.shape,n);return e!==t&&t.dispose(),r},nd=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,Ze((u=s).dtype===l.dtype,(()=>`The dtypes of the first(${u.dtype}) and second(${l.dtype}) input must match`)),Ze(rt(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){Ze(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)}}),rd=ti({scatterND_:function(e,t,n){It(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 Ks.runKernel(Rr,s,o)}}),ad=ti({sparseToDense_:function(e,t,n,r=0){It(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 Ks.runKernel(Yr,i,u)}}),sd=ti({gatherND_:function(e,t){const n=Jo(t,"indices","gatherND","int32"),r={params:Jo(e,"x","gatherND","string_or_numeric"),indices:n};return Ks.runKernel(On,r)}}),od=ti({dropout_:function(e,t,n,r){const a=Jo(e,"x","dropout");if(Ze("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.`)),Ze(t>=0&&t<1,(()=>`rate must be a float in the range [0, 1), but got ${t}.`)),0===t)return e instanceof Ns?a.clone():a;const s=function(e,t){if(null==t)return e.shape.slice();if(rt(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(hh(s,0,1,"float32",r),o)),o);return Ju(a,i)}});function id(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function ud(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 jh(a,"float32")}const ld=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]])),Ze(4===i.rank,(()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`)),Ze(4===u.rank,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${u.shape}.`)),Ze(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];Ze(l===n[2],(()=>`Error in conv2dDerFilter: depth of input ${l}) must match input depth in filter (${n[2]}.`)),Ze(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 Ks.runKernel("Conv2DBackpropFilter",p,h)}});function cd(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return Ju(e,Vh(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function pd(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 hd(e,t,n,r){if("linear"===t)return e;if("relu"===t)return gh(e);if("elu"===t)return wc(e);if("relu6"===t)return yh(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 dd=(e,t)=>!(e>0)||"linear"===t,fd=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===dd(Ks.state.gradientDepth,u)){Ze("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)),hd(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]])),Ze(4===d.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${d.rank}.`)),Ze(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];Ze(h.shape[2]===m,(()=>`Error in conv2d: depth of input (${m}) must match input depth for filter ${h.shape[2]}.`)),Ze(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]=Us(y,p),"NHWC"===a?Tu(g.outShape,y.shape):(Ze(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}.`)),Ze(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(Ze(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)Ze(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)=>{Ze("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=cd(e,l,u);Ze(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),ld(i,p,o.shape,n,r)];if(null!=c){const e=pd(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=Ks.runKernel(ma,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=Ks.runKernel(ma,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)}}}),md=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 Ks.runKernel("DepthwiseConv2dNativeBackpropFilter",l,c)}}),gd=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=Ks.runKernel("DepthwiseConv2dNativeBackpropInput",l,c);return u?El(p,[p.shape[1],p.shape[2],p.shape[3]]):p}}),yd=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===dd(Ks.state.gradientDepth,u)){let p=hc(e,t,n,r,a,s,o);return null!=i&&(p=Xu(p,i)),hd(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]])),Ze(4===d.rank,(()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${d.rank}.`)),Ze(4===h.rank,(()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`)),Ze(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]),Ze(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]=Us(g,p),Tu(m.outShape,g.shape)),null!=l&&(y=Jo(l,"prelu weights","fused depthwiseConv2d"));const b=(e,t)=>{Ze(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=cd(e,l,u),h=gd(i.shape,p,a,n,r,s,o),d=md(i,p,a.shape,n,r,s,o);return null!=c?[h,d,pd(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=Ks.runKernel(ga,_,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=Ks.runKernel(ga,_,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)}}}),bd=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===dd(Ks.state.gradientDepth,s)){let u=yu(e,t,n,r);return null!=a&&(u=Xu(u,a)),hd(u,s,o,i)}let u=Jo(e,"a","fused matMul"),l=Jo(t,"b","fused matMul");[u,l]=Us(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=nt(f),y=nt(m);Ze(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]=Us(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=cd(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,pd(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=Ks.runKernel(fa,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=Ks.runKernel(fa,I,T);return r([e,t,a,n]),{value:El(a,b),gradFunc:k}}));return e(_,x,w)}}});var _d=Object.freeze({__proto__:null,conv2d:fd,depthwiseConv2d:yd,matMul:bd});const xd=ti({hammingWindow_:function(e){return ud(e,.54,.46)}}),wd=ti({hannWindow_:function(e){return ud(e,.5,.5)}}),vd=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?Kh([],[0,t]):El(Rl(o),[o.length,t])}}),kd=ti({stft_:function(e,t,n,r,a=wd){null==r&&(r=id(t));const s=vd(e,t,n),o=Ju(s,a(t));return Bh(o,r)}}),Id=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];Ze(4===o.rank,(()=>`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`)),Ze(2===i.rank&&4===i.shape[1],(()=>`Error in cropAndResize: boxes must be have size [${l},4] but had shape ${i.shape}.`)),Ze(1===u.rank&&u.shape[0]===l,(()=>`Error in cropAndResize: boxInd must be have size [${l}] but had shape ${i.shape}.`)),Ze(2===r.length,(()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`)),Ze(r[0]>=1&&r[1]>=1,(()=>`cropSize must be atleast [1,1], but was ${r}`)),Ze("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 Ks.runKernel(fn,c,p)}}),Td=ti({flipLeftRight_:function(e){const t=Jo(e,"image","flipLeftRight","float32");Ze(4===t.rank,(()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`));const n={image:t};return Ks.runKernel(Cn,n,{})}}),Sd=ti({grayscaleToRGB_:function(e){const t=Jo(e,"image","grayscaleToRGB"),n=t.rank-1,r=t.shape[n];Ze(t.rank>=2,(()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`)),Ze(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)}}),Ed=ti({rgbToGrayscale_:function(e){const t=Jo(e,"image","RGBToGrayscale"),n=t.rank-1,r=t.shape[n];Ze(t.rank>=2,(()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`)),Ze(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=jh([.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)}}),Nd=ti({rotateWithOffset_:function(e,t,n=0,r=.5){const a=Jo(e,"image","rotateWithOffset","float32");Ze(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 Ks.runKernel(da,s,o)}});function Ad(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),Ze(0<=r&&r<=1,(()=>`iouThreshold must be in [0, 1], but was '${r}'`)),Ze(2===e.rank,(()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`)),Ze(4===e.shape[1],(()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`)),Ze(1===t.rank,(()=>"scores must be a 1D tensor")),Ze(t.shape[0]===o,(()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`)),Ze(0<=s&&s<=1,(()=>`softNmsSigma must be in [0, 1], but was '${s}'`)),{maxOutputSize:n,iouThreshold:r,scoreThreshold:a,softNmsSigma:s}}const Cd=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=Ad(s,o,n,r,a),u={maxOutputSize:n=i.maxOutputSize,iouThreshold:r=i.iouThreshold,scoreThreshold:a=i.scoreThreshold};return Ks.runKernel(cr,{boxes:s,scores:o},u)}});function Rd(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||Md)}(e,t,n),a=r<0?-(r+1):r;e.splice(a,0,t)}function Md(e,t){return e>t?1:e<t?-1:0}function Fd(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(Dd);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=$d(e,s,p[n]);if(o>=r){i=!0;break}if(t.score=t.score*Od(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&&Rd(l,t,Dd))}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 $d(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 Od(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function Dd(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const Pd=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=Ad(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=Ks.runKernel(hr,l,c);return{selectedIndices:p[0],selectedScores:p[1]}}}),Ld=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=Ad(o,i,n,r,a,null),l={boxes:o,scores:i},c={maxOutputSize:u.maxOutputSize,iouThreshold:u.iouThreshold,scoreThreshold:u.scoreThreshold,padToMaxOutputSize:s},p=Ks.runKernel(pr,l,c);return{selectedIndices:p[0],validOutputs:p[1]}}}),Bd=ti({resizeBilinear_:function(e,t,n=!1,r=!1){const a=Jo(e,"images","resizeBilinear");Ze(3===a.rank||4===a.rank,(()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${a.rank}.`)),Ze(2===t.length,(()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`)),Ze(!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=Ks.runKernel(Tr,i,u);return o?El(l,[l.shape[1],l.shape[2],l.shape[3]]):l}}),Ud=ti({resizeNearestNeighbor_:function(e,t,n=!1,r=!1){const a=Jo(e,"images","resizeNearestNeighbor");Ze(3===a.rank||4===a.rank,(()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${a.rank}.`)),Ze(2===t.length,(()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`)),Ze("float32"===a.dtype||"int32"===a.dtype,(()=>"`images` must have `int32` or `float32` as dtype")),Ze(!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=Ks.runKernel(kr,i,u);return o?El(l,[l.shape[1],l.shape[2],l.shape[3]]):l}}),Wd=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(jh([r]),255);if(Ze(3===a.rank,(()=>`Error in threshold: image must be rank 3,but got rank ${a.rank}.`)),Ze(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]}.`)),Ze("int32"===a.dtype||"float32"===a.dtype,(()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${a.dtype}.`)),Ze("otsu"===t||"binary"===t,(()=>`Method must be binary or otsu, but was ${t}`)),3===a.shape[2]){[o,i,u]=Lh(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=jh([-1]),l=jh([0]),c=jh([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,fh(0,n.size)));a=Qu(h,Lc(n));const d=Kl(r.shape,n.size),f=Xu(fh(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(_,jh([p]),u)}return u}(Wl(gu(kh(l),"int32"),ai([]),256),s));const p=n?np(l,c):Xc(l,c);return gu(Ju(p,255),"int32")}}),zd=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");Ze(4===o.rank,(()=>`Error in transform: image must be rank 4,but got rank ${o.rank}.`)),Ze(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")),Ze(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 Ks.runKernel(oa,u,l)}}),Vd=ti({bandPart_:function(e,t,n){const r=Jo(e,"a","bandPart");Ze(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?(Ze(t%1==0,(()=>`bandPart(): numLower must be an integer, got ${t}.`)),Ze(t<=s,(()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`)),i=Jo(t<0?s:t,"numLower","bandPart")):(Ze("int32"===t.dtype,(()=>"bandPart(): numLower's dtype must be an int32.")),i=gc(tp(t,0),s,Tp(t,s))),"number"==typeof n?(Ze(n%1==0,(()=>`bandPart(): numUpper must be an integer, got ${n}.`)),Ze(n<=o,(()=>`bandPart(): numUpper (${n}) must not be greater than the number of columns (${o}).`)),u=Jo(n<0?o:n,"numUpper","bandPart")):(Ze("int32"===n.dtype,(()=>"bandPart(): numUpper's dtype must be an int32.")),u=gc(tp(n,0),o,Tp(n,o)));const l=El(fh(0,s,1,"int32"),[-1,1]),c=fh(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(zh(Zh(El(r,[-1,s,o])).map((e=>gc(h,e,d)))),a)}}),Hd=ti({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,Ze(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)Ze(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=Lh(e,e.shape[0],0).map((e=>Wh(e,[0])));Ze(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(Ks.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?zh(n,0):n}});function Gd(e,t=!1){return Ks.tidy((()=>{Ze(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=Kh([[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]=Ks.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),Kh([[-1]]),Kh([[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 jd=ti({qr_:function(e,t=!1){if(Ze(e.rank>=2,(()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`)),2===e.rank)return Gd(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),r=Zh(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]=Gd(e,t);a.push(n),s.push(r)})),[El(zh(a,0),e.shape),El(zh(s,0),e.shape)]}}});var Kd;!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"}(Kd||(Kd={}));const qd=ti({computeWeightedLoss_:function(e,t,n=Kd.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===Kd.NONE)return s;if(n===Kd.SUM)return Lc(s);if(n===Kd.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===Kd.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}`)}}),Xd=ti({absoluteDifference_:function(e,t,n,r=Kd.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")),et(a.shape,s.shape,"Error in absoluteDifference: ");const i=Zu(lp(a,s));return qd(i,o,r)}}),Yd=ti({cosineDistance_:function(e,t,n,r,a=Kd.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")),et(s.shape,o.shape,"Error in cosineDistance: ");const u=Oc(1),l=lp(u,Lc(Ju(s,o),n,!0));return qd(l,i,a)}}),Qd=ti({hingeLoss_:function(e,t,n,r=Kd.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")),et(a.shape,s.shape,"Error in hingeLoss: ");const i=Oc(1);a=lp(Ju(Oc(2),a),i);const u=gh(lp(i,Ju(a,s)));return qd(u,o,r)}}),Jd=ti({huberLoss_:function(e,t,n,r=1,a=Kd.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")),et(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 qd(h,i,a)}}),Zd=ti({logLoss_:function(e,t,n,r=1e-7,a=Kd.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")),et(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 qd(h,i,a)}}),ef=ti({meanSquaredError_:function(e,t,n,r=Kd.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")),et(a.shape,s.shape,"Error in meanSquaredError: ");const i=Uh(a,s);return qd(i,o,r)}}),tf=ti({sigmoidCrossEntropy_:function(e,t,n,r=0,a=Kd.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")),et(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");et(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const a=gh(r),s=Ju(r,n),o=sp(zc(xu(Zu(r))));return Xu(lp(a,s),o)}(s,o);return qd(u,i,a)}}),nf=ti({softmaxCrossEntropy_:function(e,t,n,r=0,a=Kd.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")),et(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 qd(u,i,a)}}),rf=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=Ks.runKernel(jr,u);return{outputIndices:l[0],outputValues:l[1],emptyRowIndicator:l[2],reverseIndexMap:l[3]}}}),af=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=Ks.runKernel(Kr,o);return{outputIndices:i[0],outputShape:i[1]}}}),sf=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 Ks.runKernel(qr,o)}}),of=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 Ks.runKernel(Xr,o)}}),uf=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=Ks.runKernel(Zr,p,c);return{nGrams:h[0],nGramsSplits:h[1]}}}),lf={fft:Oh,ifft:Dh,rfft:Bh,irfft:Ph},cf={hammingWindow:xd,hannWindow:wd,frame:vd,stft:kd},pf={flipLeftRight:Td,grayscaleToRGB:Sd,resizeNearestNeighbor:Ud,resizeBilinear:Bd,rgbToGrayscale:Ed,rotateWithOffset:Nd,cropAndResize:Id,nonMaxSuppression:Cd,nonMaxSuppressionAsync:async function(e,t,n,r=.5,a=Number.NEGATIVE_INFINITY){const s=Jo(e,"boxes","nonMaxSuppressionAsync"),o=Jo(t,"scores","nonMaxSuppressionAsync"),i=Ad(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 Fd(e,t,n,r,a,0)}(l,c,n,r,a);return s!==e&&s.dispose(),o!==t&&o.dispose(),jh(p,"int32")},nonMaxSuppressionWithScore:Pd,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=Ad(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 Fd(e,t,n,r,a,s,!0)}(c,p,n,r,a,s);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:jh(h,"int32"),selectedScores:jh(d)}},nonMaxSuppressionPadded:Ld,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=Ad(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 Fd(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:jh(f,"int32"),validOutputs:Oc(m,"int32")}},threshold:Wd,transform:zd},hf={bandPart:Vd,gramSchmidt:Hd,qr:jd},df={absoluteDifference:Xd,computeWeightedLoss:qd,cosineDistance:Yd,hingeLoss:Qd,huberLoss:Jd,logLoss:Zd,meanSquaredError:ef,sigmoidCrossEntropy:tf,softmaxCrossEntropy:nf},ff={sparseFillEmptyRows:rf,sparseReshape:af,sparseSegmentMean:sf,sparseSegmentSum:of},mf={stringNGrams:uf,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=Ks.runKernel(ea,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 Ks.runKernel(ta,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 Ks.runKernel("StaticRegexReplace",{x:a},s)}})},gf="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:e=>e();function yf(e,t){const n=e[0].length;e.forEach(((e,t)=>{Ze(e.length===n,(()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`))})),Ze(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++)Ze(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 bf(e,t){const n=e[0].slice();for(let r=1;r<e.length;r++)n[t]+=e[r][t];return n}var _f;function xf(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 wf(e){const t={FIRST_DIM_SIZE:_f.FIRST_DIM_SIZE,VALUE_ROWIDS:_f.VALUE_ROWIDS,ROW_LENGTHS:_f.ROW_LENGTHS,ROW_SPLITS:_f.ROW_SPLITS,ROW_LIMITS:_f.ROW_LIMITS,ROW_STARTS:_f.ROW_STARTS},n=[];for(const r of e){if(!(r in t))break;n.push(t[r])}return n}function vf(e){return 0===e.length?0:e[0]===_f.FIRST_DIM_SIZE?e.length-1:e.length}function kf(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 If(e){return e<=30?e:bt(e,Math.floor(Math.sqrt(e)))}function Tf(e,t,n){return[n*("number"==typeof e?e:e[0]),t*("number"==typeof e?e:e[1])]}function Sf(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 Ef(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 Nf(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 Af(e,t){const n=[0];for(let r=0;r<t;++r)n.push(e[r][0]);return n}function Cf(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 Rf(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"}(_f||(_f={}));const Mf=/->/g;function Ff(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 $f(e,t,n=0){let r=[];if("number"==typeof t)Ze(e.shape[n]%t==0,(()=>"Number of splits must evenly divide the axis.")),r=new Array(t).fill(e.shape[n]/t);else{Ze(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}Ze(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 Of(e){return`Received SparseTensor with denseShape[0] = 0 but\n indices.shape[0] = ${e}`}function Df(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function Pf(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function Lf(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function Bf(e,t){return`size ${e} must be non-negative, not ${t}`}function Uf(e,t){return`Input to reshape is a SparseTensor with ${nt(e)}\n dense values, but the requested shape requires a multiple of ${nt(t)}. inputShape=${e} outputShape= ${t}`}function Wf(e,t){return`Input to reshape is a tensor with ${nt(e)} dense values, but the requested shape has ${nt(t)}. inputShape=${e} outputShape=${t}`}function zf(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function Vf(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}function Hf(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 Gf=Object.freeze({__proto__:null,segOpComputeOptimalWindowSize:function(e,t){let n,r=!1;for(e<=30?(n=e,r=!0):n=bt(e,Math.floor(Math.sqrt(e)));!r;)n>t||n===e?r=!0:n=bt(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:Hf});function jf(e){try{return e.map((e=>fs(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function Kf(e){return e.map((e=>ds(e)))}var qf=Object.freeze({__proto__:null,slice_util:qu,segment_util:Gf,fromUint8ToStringArray:jf,fromStringArrayToUint8:Kf,upcastType:Ps,axesAreInnerMostDims:Ic,combineLocations:Tc,computeOutAndReduceShapes:Sc,expandShapeToKeepDim:Ec,assertAxesAreInnerMostDims:Nc,getAxesPermutation:Ac,getUndoAxesPermutation:Cc,getInnerMostAxes:Rc,getBroadcastDims:ku,getReductionAxes:Iu,assertAndGetBroadcastShape:Tu,assertParamsConsistent:yf,computeOutShape:bf,computeDilation2DInfo:hl,computePool2DInfo:dl,computePool3DInfo:fl,computeConv2DInfo:ml,computeConv3DInfo:gl,computeDefaultPad:yl,tupleValuesAreOne:vl,eitherStridesOrDilationsAreOne:kl,stridesOrDilationsArePositive:Il,convertConv2DDataFormat:Tl,checkPadOnDimRoundingMode:Sl,getFusedDyActivation:cd,getFusedBiasGradient:pd,applyActivation:hd,shouldFuse:dd,get RowPartitionType(){return _f},combineRaggedTensorToTensorShapes:xf,getRowPartitionTypesHelper:wf,getRaggedRank:vf,validateDefaultValueShape:kf,PARALLELIZE_THRESHOLD:30,computeOptimalWindowSize:If,getImageCenter:Tf,getReshaped:Sf,getPermuted:Ef,getReshapedPermuted:Nf,getSliceBeginCoords:Af,getSliceSize:Cf,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:ya,log:function(...e){Ct().getBool("IS_TEST")||Ct().getBool("PROD")||console.log(...e)},mergeRealAndImagArrays:Rf,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(Mf,"").length)/"->".length;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error('Equation must contain exactly one arrow ("->").');const[r,a]=e.split("->");Ze(-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]:Ze(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=Ff(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:$f,getSparseFillEmptyRowsIndicesDenseShapeMismatch:Of,getSparseFillEmptyRowsNegativeIndexErrorMessage:Df,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:Pf,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:Lf,getSparseReshapeNegativeOutputDimErrorMessage:Bf,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:function(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"},getSparseReshapeInputOutputMultipleErrorMessage:Uf,getSparseReshapeInputOutputMismatchErrorMessage:Wf,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:function(){return"segment ids must be >= 0"},getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:function(){return"segment ids are not increasing"},getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:zf,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:Vf});class Xf{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}setTimeoutCustom(e,t){"undefined"!=typeof window&&Ct().getBool("USE_SETTIMEOUTCUSTOM")?(this.functionRefs.push(e),setTimeout((()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")}),t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",(e=>{e.source===window&&e.data.name===this.messageName&&(e.stopPropagation(),(0,this.functionRefs[e.data.index])(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0))}),!0))):setTimeout(e,t)}isTypedArray(e){return Ta(e)}}if(Ct().get("IS_BROWSER")){Ct().setPlatform("browser",new Xf);try{hu.registerManager(qi.URL_SCHEME,new Yi)}catch(e){}try{hu.registerManager(Oi.URL_SCHEME,new Pi)}catch(e){}}let Yf;var Qf,Jf;Ct().get("IS_NODE")&&!Ct().get("IS_BROWSER")&&Ct().setPlatform("node",new class{constructor(){this.util=n(345),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=Ct().global.fetch?Ct().global.fetch(e,t):(null==Yf&&(Yf=n(683)),Yf(e,t))}now(){const e=je.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)}}),js(),Es={buffer:Gl,cast:gu,clone:Cl,print:zp},Ct().registerFlag("KEEP_INTERMEDIATE_TENSORS",(()=>!1),(e=>{e&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")})),function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_QINT16=15]="DT_QINT16",e[e.DT_QUINT16=16]="DT_QUINT16",e[e.DT_UINT16=17]="DT_UINT16",e[e.DT_COMPLEX128=18]="DT_COMPLEX128",e[e.DT_HALF=19]="DT_HALF",e[e.DT_RESOURCE=20]="DT_RESOURCE",e[e.DT_VARIANT=21]="DT_VARIANT",e[e.DT_UINT32=22]="DT_UINT32",e[e.DT_UINT64=23]="DT_UINT64",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",e[e.DT_QINT16_REF=115]="DT_QINT16_REF",e[e.DT_QUINT16_REF=116]="DT_QUINT16_REF",e[e.DT_UINT16_REF=117]="DT_UINT16_REF",e[e.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",e[e.DT_HALF_REF=119]="DT_HALF_REF",e[e.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",e[e.DT_VARIANT_REF=121]="DT_VARIANT_REF",e[e.DT_UINT32_REF=122]="DT_UINT32_REF",e[e.DT_UINT64_REF=123]="DT_UINT64_REF"}(Qf||(Qf={})),function(e){var t;(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"}(Jf||(Jf={}));const Zf={};function em(e){return Zf[e]}function tm(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 nm(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=>nm(e,n,r,a)))}const u=nm(t.inputNames[i],n,r,a),l=u.dataSync();return"number"===s.type?l[0]:wt(u.shape,l)}const o=t.attrParams[e];return o&&o.value}function nm(e,t,n,r){const[a,s]=om(e,n);if(null!=r){const e=r.getHashTableHandleByName(a);if(null!=e)return e}const o=n.currentContextIds.find((e=>!!t[sm(a,e)]));return void 0!==o?t[sm(a,o)][s]:void 0}function rm(e,t,n){return t[sm(e,n.currentContextId)]}function am(e,t){const[n,r,a]=om(e,t);return[sm(n,t&&t.currentContextId),r,a]}function sm(e,t){return t?`${e}-${t}`:e}function om(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 im(e,t,n){let r=tm("pad",e,t,n);if("explicit"===r){r=tm("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 um(e){return e.kept?e:Cl(e)}var lm=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}]}]}),cm=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}]}]}),pm=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"}]}]}),hm=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"}]}]}),dm=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"}]}]}),fm=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}]}]}),mm=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"}]}]}),gm=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"}]}]}),ym=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"}]}]}),bm=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"}]}]}),_m=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"}]}]}),xm=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"}]}]}),wm=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"}]}]}),vm=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"}]}]}),km=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"}]}]}),Im=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"}]}]}),Tm=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}]}]}),Sm=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"}]}]}),Em=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 Nm{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[].concat(...[lm,cm,pm,hm,dm,fm,mm,gm,ym,bm,_m,xm,wm,vm,km,Im,Tm,Sm,Em].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]=am(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]=am(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]=am(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=em(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=Cm(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Cm(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":a=Um(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Um(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":a=Mm(e.attr,n.tfName,n.defaultValue||0),void 0===a&&n.tfDeprecatedName&&(a=Mm(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":a=Bm(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Bm(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":a=Rm(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Rm(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":a=zm(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=zm(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":a=Lm(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Lm(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":a=Wm(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Wm(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"dtype[]":a=Dm(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=Dm(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":a=$m(e.attr,n.tfName,n.defaultValue),void 0===a&&n.tfDeprecatedName&&(a=$m(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]=am(e.name),n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Fm(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]=am(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]=am(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 Am(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){const t=Ct().global;return void 0!==t.atob?t.atob(e):new po(e,"base64").toString()}(e);return t?n:n.toLowerCase()}function Cm(e,t,n,r=!1){const a=e[t];return null!=a?Am(a.s,r):n}function Rm(e,t,n){const r=e[t];return r?r.b:n}function Mm(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 Fm(e){switch("string"==typeof e&&(e=Qf[e]),e){case Qf.DT_FLOAT:case Qf.DT_HALF:return"float32";case Qf.DT_INT32:case Qf.DT_INT64:case Qf.DT_INT8:case Qf.DT_UINT8:return"int32";case Qf.DT_BOOL:return"bool";case Qf.DT_DOUBLE:return"float32";case Qf.DT_STRING:return"string";case Qf.DT_COMPLEX64:case Qf.DT_COMPLEX128:return"complex64";default:return null}}function $m(e,t,n){const r=e[t];return r&&r.func?r.func.name:n}function Om(e,t,n){const r=e[t];return r&&r.type?Fm(r.type):n}function Dm(e,t,n){const r=e[t];return r&&r.list&&r.list.type?r.list.type.map((e=>Fm(e))):n}function Pm(e){if(!e.unknownRank)return null!=e.dim?e.dim.map((e=>"number"==typeof e.size?e.size:parseInt(e.size,10))):[]}function Lm(e,t,n){const r=e[t];return r&&r.shape?Pm(r.shape):n}function Bm(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 Um(e,t,n,r=!1){const a=e[t];return a&&a.list&&a.list.s?a.list.s.map((e=>Am(e,r))):n}function Wm(e,t,n){const r=e[t];return r&&r.list&&r.list.shape?r.list.shape.map((e=>Pm(e))):n}function zm(e,t,n){const r=e[t];return r&&r.list&&r.list.b?r.list.b:n}class Vm{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 nm(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(null!=n.tensor)return nm(e,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return Mm(this.node.rawAttrs,e,t);if(null!=n.s)return Cm(this.node.rawAttrs,e,t);if(null!=n.b)return Rm(this.node.rawAttrs,e,t);if(null!=n.shape)return Lm(this.node.rawAttrs,e,t);if(null!=n.type)return Om(this.node.rawAttrs,e,t);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return Bm(this.node.rawAttrs,e,t);if(null!=n.list.s)return Um(this.node.rawAttrs,e,t);if(null!=n.list.shape)return Wm(this.node.rawAttrs,e,t);if(null!=n.list.b)return zm(this.node.rawAttrs,e,t);if(null!=n.list.type)return Dm(this.node.rawAttrs,e,t)}return t}}var Hm=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 Ks.runKernel(Gn,{},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 Ns?e.dtype:"float32");if(void 0===t)return[r];let a=Jo(t,"y","meshgrid",t instanceof Ns?t.dtype:"float32");const s=nt(r.shape),o=nt(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:lh,randomNormal:ch,randomStandardNormal:ph,randomUniform:hh,randomUniformInt:dh,range:fh,real:wu,reciprocal:mh,relu:gh,relu6:yh,reshape:El,reverse:bh,reverse1d:_h,reverse2d:xh,reverse3d:wh,reverse4d:vh,round:kh,rsqrt:Ih,scalar:Oc,selu:Th,separableConv2d:Sh,setdiff1dAsync:async function(e,t){const n=Jo(e,"x","setdiff1d"),r=Jo(t,"y","setdiff1d");Ze(n.dtype===r.dtype,(()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`)),Ze(1===n.rank,(()=>`x should be 1D tensor, but got x (${n.shape}).`)),Ze(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 Ts([i],n.dtype),l=new Ts([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:Eh,sin:Nh,sinh:Ah,slice:Fl,slice1d:Ch,slice2d:Rh,slice3d:Mh,slice4d:Fh,softmax:$h,softplus:ip,spaceToBatchND:Bp,fft:Oh,ifft:Dh,irfft:Ph,rfft:Bh,split:Lh,sqrt:Dc,square:Pc,squaredDifference:Uh,squeeze:Wh,stack:zh,step:Vh,stridedSlice:Hh,sub:lp,sum:Lc,tan:Gh,tanh:$l,tensor:ai,tensor1d:jh,tensor2d:Kh,tensor3d:Su,tensor4d:function(e,t,n){if(tt(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(tt(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(tt(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:qh,tile:Gc,topk:Xh,truncatedNormal:Yh,unique:Qh,unsortedSegmentSum:Jh,unstack:Zh,upperBound:function(e,t){return yp(e,t,"right")},variable:function(e,t=!0,n,r){return Ks.makeVariable(e,t,n,r)},where:gc,whereAsync:td,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;Ze(o>0,(()=>"mask cannot be scalar")),et(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 td(p),d=Wh(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:nd,scatterND:rd,searchSorted:yp,sparseToDense:ad,gatherND:sd,dropout:od,enclosingPowerOfTwo:id,cosineWindow:ud,inTopKAsync:async function(e,t,n=1){const r=Jo(e,"predictions","inTopK"),a=Jo(t,"targets","inTopK");Ze(r.rank>1,(()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`)),Ze(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}`)),et(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];Ze(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=pt("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:pf,linalg:hf,losses:df,spectral:lf,fused:_d,signal:cf,sparse:ff,string:mf});function Gm(e,t,n=""){if("number"!=typeof e&&"number"!=typeof t){Ze(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];Ze(a<0||s<0||a===s,(()=>n+` Shapes ${e} and ${t} must match`))}}}function jm(e){return"number"!=typeof e&&!e.some((e=>e<0))}function Km(e,t,n){let r=qm(e,n);const a=!jm(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=qm(e.shape,r)})),!jm(r))throw new Error(`Non-fully-defined elementShape: ${r}`);return r}function qm(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 Xm{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),Gm(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 Gm(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),zh(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 Gm(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,Zh(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 Ym{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}`);Gm(t,e.shape,"TensorList shape mismatch: "),ci(e)})),this.idTensor=Oc(0),this.maxNumElements=r,ci(this.idTensor)}copy(){return new Ym([...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.`);Gm(e,this.elementShape,"TensorList shape mismatch: ");const r=Km(this.elementShape,this.tensors,e);return ui((()=>{const e=this.tensors.map((e=>El(e,r)));return zh(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=Km(this.elementShape,this.tensors,e),r=this.tensors.pop();return r.kept=!1,Gm(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(Gm(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 Ym([],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.`);Gm(this.tensors[e].shape,t,"TensorList shape mismatch: ");const r=Km(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.`);Gm(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}`);Gm(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());const r=Km(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 zh(t,0)}))}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Gm(this.elementShape,t,"TensorList shape mismatch: ");const n=Km(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 Qm(e,t,n){const[r,a]=tm("fusedOps",e,t,n),s="biasadd"===r,o=!s,i="prelu"===a,u="fusedbatchnorm"===r,l=tm("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=tm("strides",e,t,n),p=im(e,t,n),h=tm("dataFormat",e,t,n).toUpperCase(),d=tm("dilations",e,t,n);let[f,m]=tm("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:tm("leakyreluAlpha",e,t,n)}}function Jm(e,t,n){return{boxes:tm("boxes",e,t,n),scores:tm("scores",e,t,n),maxOutputSize:tm("maxOutputSize",e,t,n),iouThreshold:tm("iouThreshold",e,t,n),scoreThreshold:tm("scoreThreshold",e,t,n),softNmsSigma:tm("softNmsSigma",e,t,n)}}class Zm{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=Zh(t),r=n.length,a=e.length;Ze(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 zh(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 eg(e,t,n,r,a=ui){const s=((e,t,n)=>{switch(e.category){case"arithmetic":return a((()=>((e,t,n,r=Hm)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[r.add(tm("a",e,t,n),tm("b",e,t,n))];case"AddN":return[r.addN(tm("tensors",e,t,n))];case"FloorMod":case"Mod":return[r.mod(tm("a",e,t,n),tm("b",e,t,n))];case"Mul":return[r.mul(tm("a",e,t,n),tm("b",e,t,n))];case"RealDiv":case"Div":return[r.div(tm("a",e,t,n),tm("b",e,t,n))];case"DivNoNan":return[r.divNoNan(tm("a",e,t,n),tm("b",e,t,n))];case"FloorDiv":return[r.floorDiv(tm("a",e,t,n),tm("b",e,t,n))];case"Sub":return[r.sub(tm("a",e,t,n),tm("b",e,t,n))];case"Minimum":return[r.minimum(tm("a",e,t,n),tm("b",e,t,n))];case"Maximum":return[r.maximum(tm("a",e,t,n),tm("b",e,t,n))];case"Pow":return[r.pow(tm("a",e,t,n),tm("b",e,t,n))];case"SquaredDifference":return[r.squaredDifference(tm("a",e,t,n),tm("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=Hm)=>{switch(e.op){case"Abs":case"ComplexAbs":return[r.abs(tm("x",e,t,n))];case"Acos":return[r.acos(tm("x",e,t,n))];case"Acosh":return[r.acosh(tm("x",e,t,n))];case"Asin":return[r.asin(tm("x",e,t,n))];case"Asinh":return[r.asinh(tm("x",e,t,n))];case"Atan":return[r.atan(tm("x",e,t,n))];case"Atan2":return[r.atan2(tm("x",e,t,n),tm("y",e,t,n))];case"Atanh":return[r.atanh(tm("x",e,t,n))];case"Ceil":return[r.ceil(tm("x",e,t,n))];case"Complex":return[r.complex(tm("real",e,t,n),tm("imag",e,t,n))];case"Cos":return[r.cos(tm("x",e,t,n))];case"Cosh":return[r.cosh(tm("x",e,t,n))];case"Elu":return[r.elu(tm("x",e,t,n))];case"Erf":return[r.erf(tm("x",e,t,n))];case"Exp":return[r.exp(tm("x",e,t,n))];case"Expm1":return[r.expm1(tm("x",e,t,n))];case"Floor":return[r.floor(tm("x",e,t,n))];case"Log":return[r.log(tm("x",e,t,n))];case"Log1p":return[r.log1p(tm("x",e,t,n))];case"Imag":return[r.imag(tm("x",e,t,n))];case"Neg":return[r.neg(tm("x",e,t,n))];case"Reciprocal":return[r.reciprocal(tm("x",e,t,n))];case"Real":return[r.real(tm("x",e,t,n))];case"Relu":return[r.relu(tm("x",e,t,n))];case"Round":return[r.round(tm("x",e,t,n))];case"Selu":return[r.selu(tm("x",e,t,n))];case"Sigmoid":return[r.sigmoid(tm("x",e,t,n))];case"Sin":return[r.sin(tm("x",e,t,n))];case"Sign":return[r.sign(tm("x",e,t,n))];case"Sinh":return[r.sinh(tm("x",e,t,n))];case"Softplus":return[r.softplus(tm("x",e,t,n))];case"Sqrt":return[r.sqrt(tm("x",e,t,n))];case"Square":return[r.square(tm("x",e,t,n))];case"Tanh":return[r.tanh(tm("x",e,t,n))];case"Tan":return[r.tan(tm("x",e,t,n))];case"ClipByValue":return[r.clipByValue(tm("x",e,t,n),tm("clipValueMin",e,t,n),tm("clipValueMax",e,t,n))];case"Relu6":return[r.relu6(tm("x",e,t,n))];case"Rsqrt":return[r.rsqrt(nm(e.inputNames[0],t,n))];case"LeakyRelu":return[r.leakyRelu(tm("x",e,t,n),tm("alpha",e,t,n))];case"Prelu":return[r.prelu(tm("x",e,t,n),tm("alpha",e,t,n))];case"IsNan":return[r.isNaN(nm(e.inputNames[0],t,n))];case"IsInf":return[r.isInf(nm(e.inputNames[0],t,n))];case"IsFinite":return[r.isFinite(nm(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=tm("thenBranch",e,t,n),a=tm("elseBranch",e,t,n),s=tm("cond",e,t,n),o=tm("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=tm("body",e,t,n),a=tm("cond",e,t,n),s=tm("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[um(tm("pred",e,t,n))];case"Switch":{const r=tm("pred",e,t,n);let a=tm("data",e,t,n);return a.kept||(a=um(a)),(await r.data())[0]?[void 0,a]:[a,void 0]}case"Merge":{const r=e.inputNames.find((e=>void 0!==nm(e,t,n)));return r?[um(nm(r,t,n))]:void 0}case"Enter":{const r=tm("frameName",e,t,n),a=tm("tensor",e,t,n);return n.enterFrame(r),[um(a)]}case"Exit":{const r=tm("tensor",e,t,n);return n.exitFrame(),[um(r)]}case"NextIteration":{const r=tm("tensor",e,t,n);return n.nextIteration(),[um(r)]}case"TensorArrayV3":{const r=tm("size",e,t,n),a=tm("dtype",e,t,n),s=tm("elementShape",e,t,n),o=tm("dynamicSize",e,t,n),i=tm("clearAfterRead",e,t,n),u=tm("identicalElementShapes",e,t,n),l=tm("name",e,t,n),c=new Xm(l,a,r,s,u,o,i);return n.addTensorArray(c),[c.idTensor,Oc(1)]}case"TensorArrayWriteV3":{const r=tm("tensorArrayId",e,t,n),a=tm("index",e,t,n),s=tm("tensor",e,t,n),o=n.getTensorArray(r.id);return o.write(a,s),[o.idTensor]}case"TensorArrayReadV3":{const r=tm("tensorArrayId",e,t,n),a=tm("index",e,t,n);return[n.getTensorArray(r.id).read(a)]}case"TensorArrayGatherV3":{const r=tm("tensorArrayId",e,t,n),a=tm("indices",e,t,n),s=tm("dtype",e,t,n);return[n.getTensorArray(r.id).gather(a,s)]}case"TensorArrayScatterV3":{const r=tm("tensorArrayId",e,t,n),a=tm("indices",e,t,n),s=tm("tensor",e,t,n),o=n.getTensorArray(r.id);return o.scatter(a,s),[o.idTensor]}case"TensorArrayConcatV3":{const r=tm("tensorArrayId",e,t,n),a=n.getTensorArray(r.id),s=tm("dtype",e,t,n);return[a.concat(s)]}case"TensorArraySplitV3":{const r=tm("tensorArrayId",e,t,n),a=tm("tensor",e,t,n),s=tm("lengths",e,t,n),o=n.getTensorArray(r.id);return o.split(s,a),[o.idTensor]}case"TensorArraySizeV3":{const r=tm("tensorArrayId",e,t,n);return[Oc(n.getTensorArray(r.id).size(),"int32")]}case"TensorArrayCloseV3":{const r=tm("tensorArrayId",e,t,n),a=n.getTensorArray(r.id);return a.clearAndClose(),[a.idTensor]}case"TensorListSetItem":{const r=tm("tensorListId",e,t,n),a=tm("index",e,t,n),s=tm("tensor",e,t,n),o=n.getTensorList(r.id);return o.setItem(a,s),[o.idTensor]}case"TensorListGetItem":{const r=tm("tensorListId",e,t,n),a=tm("index",e,t,n),s=tm("elementShape",e,t,n),o=tm("elementDType",e,t,n);return[n.getTensorList(r.id).getItem(a,s,o)]}case"TensorListScatterV2":case"TensorListScatter":{const r=tm("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 Ym([],n,e.dtype,r),o=Zh(e,0);return t.forEach(((e,t)=>{s.setItem(e,o[t])})),s}(tm("tensor",e,t,n),r,tm("elementShape",e,t,n),tm("numElements",e,t,n));return n.addTensorList(a),[a.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const r=tm("elementShape",e,t,n),a=tm("elementDType",e,t,n);let s;s="TensorListReserve"===e.op?"numElements":"maxNumElements";const o=tm(s,e,t,n),i=function(e,t,n,r){return new Ym([],e,t,r)}(r,a,0,"TensorListReserve"===e.op?-1:o);return n.addTensorList(i),[i.idTensor]}case"TensorListGather":{const r=tm("tensorListId",e,t,n),a=tm("indices",e,t,n),s=tm("elementShape",e,t,n),o=tm("elementDType",e,t,n);return[n.getTensorList(r.id).gather(a,o,s)]}case"TensorListStack":{const r=tm("tensorListId",e,t,n),a=tm("elementShape",e,t,n),s=tm("elementDType",e,t,n),o=tm("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}`);Gm(e.shape.slice(1),t,"TensorList shape mismatch: ");const a=Zh(e);return new Ym(a,t,r)}(tm("tensor",e,t,n),tm("elementShape",e,t,n),tm("elementDType",e,t,n));return n.addTensorList(r),[r.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const r=tm("tensorListId",e,t,n),a=n.getTensorList(r.id),s=tm("dtype",e,t,n),o=tm("elementShape",e,t,n);return[a.concat(s,o)]}case"TensorListPushBack":{const r=tm("tensorListId",e,t,n),a=tm("tensor",e,t,n),s=n.getTensorList(r.id);return s.pushBack(a),[s.idTensor]}case"TensorListPopBack":{const r=tm("tensorListId",e,t,n),a=tm("elementShape",e,t,n),s=tm("elementDType",e,t,n);return[n.getTensorList(r.id).popBack(a,s)]}case"TensorListSplit":{const r=tm("tensor",e,t,n),a=tm("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=qm(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 Ym([],n,e.dtype,t.length);for(let e=0;e<i.length;e++)u.setItem(e,i[e]);return u}(r,tm("lengths",e,t,n),a);return n.addTensorList(s),[s.idTensor]}case"TensorListLength":{const r=tm("tensorListId",e,t,n);return[Oc(n.getTensorList(r.id).size(),"int32")]}case"TensorListResize":{const r=tm("tensorListId",e,t,n),a=tm("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=Hm)=>{switch(e.op){case"Conv1D":{const a=tm("stride",e,t,n),s=tm("pad",e,t,n),o=tm("dataFormat",e,t,n).toUpperCase(),i=tm("dilation",e,t,n);return[r.conv1d(tm("x",e,t,n),tm("filter",e,t,n),a,s,o,i)]}case"Conv2D":{const a=tm("strides",e,t,n),s=im(e,t,n),o=tm("dataFormat",e,t,n).toUpperCase(),i=tm("dilations",e,t,n);return[r.conv2d(tm("x",e,t,n),tm("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}=Qm(e,t,n);return[r.fused.conv2d({x:tm("x",e,t,n),filter:tm("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}=Qm(e,t,n);return[r.fused.depthwiseConv2d({x:tm("x",e,t,n),filter:tm("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=tm("outputShape",e,t,n),s=tm("strides",e,t,n),o=im(e,t,n);return[r.conv2dTranspose(tm("x",e,t,n),tm("filter",e,t,n),a,[s[1],s[2]],o)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const a=tm("strides",e,t,n),s=im(e,t,n),o=tm("dilations",e,t,n),i=tm("dataFormat",e,t,n).toUpperCase();return[r.depthwiseConv2d(tm("input",e,t,n),tm("filter",e,t,n),[a[1],a[2]],s,i,[o[1],o[2]])]}case"Conv3D":{const a=tm("strides",e,t,n),s=tm("pad",e,t,n),o=tm("dataFormat",e,t,n).toUpperCase(),i=tm("dilations",e,t,n);return[r.conv3d(tm("x",e,t,n),tm("filter",e,t,n),[a[1],a[2],a[3]],s,o,[i[1],i[2],i[3]])]}case"AvgPool":{const a=tm("strides",e,t,n),s=tm("pad",e,t,n),o=tm("kernelSize",e,t,n);return[r.avgPool(tm("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s)]}case"MaxPool":{const a=tm("strides",e,t,n),s=tm("pad",e,t,n),o=tm("kernelSize",e,t,n);return[r.maxPool(tm("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s)]}case"MaxPoolWithArgmax":{const a=tm("strides",e,t,n),s=tm("pad",e,t,n),o=tm("kernelSize",e,t,n),i=tm("includeBatchInIndex",e,t,n),{result:u,indexes:l}=r.maxPoolWithArgmax(tm("x",e,t,n),[o[1],o[2]],[a[1],a[2]],s,i);return[u,l]}case"AvgPool3D":{const a=tm("strides",e,t,n),s=tm("pad",e,t,n),o=tm("kernelSize",e,t,n);return[r.avgPool3d(tm("x",e,t,n),[o[1],o[2],o[3]],[a[1],a[2],a[3]],s)]}case"MaxPool3D":{const a=tm("strides",e,t,n),s=tm("pad",e,t,n),o=tm("kernelSize",e,t,n);return[r.maxPool3d(tm("x",e,t,n),[o[1],o[2],o[3]],[a[1],a[2],a[3]],s)]}case"Dilation2D":{const a=tm("strides",e,t,n),s=tm("pad",e,t,n),o=tm("dilations",e,t,n),i=a[1],u=a[2],l=o[1],c=o[2];return[r.dilation2d(tm("x",e,t,n),tm("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=Hm)=>{switch(e.op){case"Fill":{const a=tm("shape",e,t,n),s=tm("dtype",e,t,n),o=tm("value",e,t,n);return[r.fill(a,o,s)]}case"LinSpace":{const a=tm("start",e,t,n),s=tm("stop",e,t,n),o=tm("num",e,t,n);return[r.linspace(a,s,o)]}case"Multinomial":{const a=tm("logits",e,t,n),s=tm("numSamples",e,t,n),o=tm("seed",e,t,n);return[r.multinomial(a,s,o)]}case"OneHot":{const a=tm("indices",e,t,n),s=tm("depth",e,t,n),o=tm("onValue",e,t,n),i=tm("offValue",e,t,n),u=tm("dtype",e,t,n);return[r.oneHot(a,s,o,i,u)]}case"Ones":return[r.ones(tm("shape",e,t,n),tm("dtype",e,t,n))];case"OnesLike":return[r.onesLike(tm("x",e,t,n))];case"RandomStandardNormal":return[r.randomStandardNormal(tm("shape",e,t,n),tm("dtype",e,t,n),tm("seed",e,t,n))];case"RandomUniform":return[r.randomUniform(tm("shape",e,t,n),tm("minval",e,t,n),tm("maxval",e,t,n),tm("dtype",e,t,n))];case"RandomUniformInt":return[r.randomUniformInt(tm("shape",e,t,n),tm("minval",e,t,n),tm("maxval",e,t,n),tm("seed",e,t,n))];case"Range":{const a=tm("start",e,t,n),s=tm("stop",e,t,n),o=tm("step",e,t,n);return[r.range(a,s,o,tm("dtype",e,t,n))]}case"TruncatedNormal":{const a=tm("shape",e,t,n),s=tm("mean",e,t,n),o=tm("stdDev",e,t,n),i=tm("seed",e,t,n);return[r.truncatedNormal(a,s,o,tm("dtype",e,t,n),i)]}case"Zeros":return[r.zeros(tm("shape",e,t,n),tm("dtype",e,t,n))];case"ZerosLike":return[r.zerosLike(tm("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=Hm)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:r,scores:s,maxOutputSize:o,iouThreshold:i,scoreThreshold:u,softNmsSigma:l}=Jm(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}=Jm(e,t,n),l=tm("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}=Jm(e,t,n);return[await a.image.nonMaxSuppressionAsync(r,s,o,i,u)]}case"Where":{const r=a.cast(tm("condition",e,t,n),"bool"),s=[await a.whereAsync(r)];return r.dispose(),s}case"ListDiff":return a.setdiff1dAsync(tm("x",e,t,n),tm("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=Hm)=>{switch(e.op){case"LowerBound":{const a=tm("sortedSequence",e,t,n),s=tm("values",e,t,n);return[r.lowerBound(a,s)]}case"TopKV2":{const a=tm("x",e,t,n),s=tm("k",e,t,n),o=tm("sorted",e,t,n),i=r.topk(a,s,o);return[i.values,i.indices]}case"UpperBound":{const a=tm("sortedSequence",e,t,n),s=tm("values",e,t,n);return[r.upperBound(a,s)]}case"Unique":{const a=tm("x",e,t,n),s=r.unique(a);return[s.values,s.indices]}case"UniqueV2":{const a=tm("x",e,t,n),s=tm("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=Hm)=>{switch(e.op){case"ResizeBilinear":{const a=tm("images",e,t,n),s=tm("size",e,t,n),o=tm("alignCorners",e,t,n),i=tm("halfPixelCenters",e,t,n);return[r.image.resizeBilinear(a,[s[0],s[1]],o,i)]}case"ResizeNearestNeighbor":{const a=tm("images",e,t,n),s=tm("size",e,t,n),o=tm("alignCorners",e,t,n),i=tm("halfPixelCenters",e,t,n);return[r.image.resizeNearestNeighbor(a,[s[0],s[1]],o,i)]}case"CropAndResize":{const a=tm("image",e,t,n),s=tm("boxes",e,t,n),o=tm("boxInd",e,t,n),i=tm("cropSize",e,t,n),u=tm("method",e,t,n),l=tm("extrapolationValue",e,t,n);return[r.image.cropAndResize(a,s,o,i,u,l)]}case"ImageProjectiveTransformV3":{const a=tm("images",e,t,n),s=tm("transforms",e,t,n),o=tm("outputShape",e,t,n),i=tm("fillValue",e,t,n),u=tm("interpolation",e,t,n),l=tm("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=Hm)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const a=tm("default",e,t,n);return[nm(e.name,t,n)||a];case"Placeholder":return[nm(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":case"Snapshot":return[um(tm("x",e,t,n))];case"IdentityN":return tm("x",e,t,n).map((e=>um(e)));case"Shape":return[r.tensor1d(tm("x",e,t,n).shape,"int32")];case"ShapeN":return tm("x",e,t,n).map((e=>r.tensor1d(e.shape)));case"Size":return[r.scalar(tm("x",e,t,n).size,"int32")];case"Rank":return[r.scalar(tm("x",e,t,n).rank,"int32")];case"NoOp":return[r.scalar(1)];case"Print":const s=tm("x",e,t,n),o=tm("data",e,t,n),i=tm("message",e,t,n),u=tm("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=Hm)=>{switch(e.op){case"Equal":return[r.equal(tm("a",e,t,n),tm("b",e,t,n))];case"NotEqual":return[r.notEqual(tm("a",e,t,n),tm("b",e,t,n))];case"Greater":return[r.greater(tm("a",e,t,n),tm("b",e,t,n))];case"GreaterEqual":return[r.greaterEqual(tm("a",e,t,n),tm("b",e,t,n))];case"Less":return[r.less(tm("a",e,t,n),tm("b",e,t,n))];case"LessEqual":return[r.lessEqual(tm("a",e,t,n),tm("b",e,t,n))];case"LogicalAnd":return[r.logicalAnd(tm("a",e,t,n),tm("b",e,t,n))];case"LogicalNot":return[r.logicalNot(tm("a",e,t,n))];case"LogicalOr":return[r.logicalOr(tm("a",e,t,n),tm("b",e,t,n))];case"Select":case"SelectV2":return[r.where(tm("condition",e,t,n),tm("a",e,t,n),tm("b",e,t,n))];case"BitwiseAnd":return[r.bitwiseAnd(tm("a",e,t,n),tm("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=Hm)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[r.matMul(tm("a",e,t,n),tm("b",e,t,n),tm("transposeA",e,t,n),tm("transposeB",e,t,n))];case"Einsum":return[r.einsum(tm("equation",e,t,n),...tm("tensors",e,t,n))];case"Transpose":return[r.transpose(tm("x",e,t,n),tm("perm",e,t,n))];case"_FusedMatMul":const[a,s]=tm("fusedOps",e,t,n),o="biasadd"===a,i="prelu"===s,u=tm("numArgs",e,t,n),l=tm("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]=tm("args",e,t,n);return[r.fused.matMul({a:tm("a",e,t,n),b:tm("b",e,t,n),transposeA:tm("transposeA",e,t,n),transposeB:tm("transposeB",e,t,n),bias:c,activation:s,preluActivationWeights:p,leakyreluAlpha:l})];case"MatrixBandPart":return[r.linalg.bandPart(tm("a",e,t,n),tm("numLower",e,t,n),tm("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=Hm)=>{switch(e.op){case"EuclideanNorm":return[r.euclideanNorm(tm("x",e,t,n),tm("axis",e,t,n),tm("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[r.batchNorm(tm("x",e,t,n),tm("mean",e,t,n),tm("variance",e,t,n),tm("offset",e,t,n),tm("scale",e,t,n),tm("epsilon",e,t,n))];case"LRN":return[r.localResponseNormalization(tm("x",e,t,n),tm("radius",e,t,n),tm("bias",e,t,n),tm("alpha",e,t,n),tm("beta",e,t,n))];case"Softmax":return[r.softmax(tm("x",e,t,n))];case"LogSoftmax":return[r.logSoftmax(tm("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=Hm)=>{switch(e.op){case"RaggedGather":{const{outputNestedSplits:a,outputDenseValues:s}=r.raggedGather(tm("paramsNestedSplits",e,t,n),tm("paramsDenseValues",e,t,n),tm("indices",e,t,n),tm("outputRaggedRank",e,t,n));return a.concat(s)}case"RaggedRange":{const{rtNestedSplits:a,rtDenseValues:s}=r.raggedRange(tm("starts",e,t,n),tm("limits",e,t,n),tm("splits",e,t,n));return[a,s]}case"RaggedTensorToTensor":return[r.raggedTensorToTensor(tm("shape",e,t,n),tm("values",e,t,n),tm("defaultValue",e,t,n),tm("rowPartitionTensors",e,t,n),tm("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=Hm)=>{switch(e.op){case"Max":{const a=tm("axis",e,t,n),s=tm("keepDims",e,t,n);return[r.max(tm("x",e,t,n),a,s)]}case"Mean":{const a=tm("axis",e,t,n),s=tm("keepDims",e,t,n);return[r.mean(tm("x",e,t,n),a,s)]}case"Min":{const a=tm("axis",e,t,n),s=tm("keepDims",e,t,n);return[r.min(tm("x",e,t,n),a,s)]}case"Sum":{const a=tm("axis",e,t,n),s=tm("keepDims",e,t,n);return[r.sum(tm("x",e,t,n),a,s)]}case"All":{const a=tm("axis",e,t,n),s=tm("keepDims",e,t,n);return[r.all(tm("x",e,t,n),a,s)]}case"Any":{const a=tm("axis",e,t,n),s=tm("keepDims",e,t,n);return[r.any(tm("x",e,t,n),a,s)]}case"ArgMax":{const a=tm("axis",e,t,n);return[r.argMax(tm("x",e,t,n),a)]}case"ArgMin":{const a=tm("axis",e,t,n);return[r.argMin(tm("x",e,t,n),a)]}case"Prod":{const a=tm("axis",e,t,n),s=tm("keepDims",e,t,n);return[r.prod(tm("x",e,t,n),a,s)]}case"Cumprod":{const a=tm("axis",e,t,n),s=tm("exclusive",e,t,n),o=tm("reverse",e,t,n);return[r.cumprod(tm("x",e,t,n),a,s,o)]}case"Cumsum":{const a=tm("axis",e,t,n),s=tm("exclusive",e,t,n),o=tm("reverse",e,t,n);return[r.cumsum(tm("x",e,t,n),a,s,o)]}case"Bincount":const a=tm("x",e,t,n),s=tm("weights",e,t,n),o=tm("size",e,t,n);return[r.bincount(a,s,o)];case"DenseBincount":{const a=tm("x",e,t,n),s=tm("weights",e,t,n),o=tm("size",e,t,n),i=tm("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=Hm)=>{switch(e.op){case"ConcatV2":case"Concat":{const a=tm("n",e,t,n),s=tm("axis",e,t,n);let o=tm("tensors",e,t,n);return o=o.slice(0,a),[r.concat(o,s)]}case"Gather":{const a=tm("x",e,t,n),s=tm("indices",e,t,n);return[r.gather(a,r.cast(s,"int32"),0)]}case"GatherV2":{const a=tm("axis",e,t,n),s=tm("batchDims",e,t,n),o=tm("x",e,t,n),i=tm("indices",e,t,n);return[r.gather(o,r.cast(i,"int32"),a,s)]}case"Reverse":{const a=tm("dims",e,t,n),s=[];for(let e=0;e<a.length;e++)a[e]&&s.push(e);const o=tm("x",e,t,n);return[r.reverse(o,s)]}case"ReverseV2":{const a=tm("axis",e,t,n),s=tm("x",e,t,n);return[r.reverse(s,a)]}case"Slice":{const a=tm("begin",e,t,n),s=tm("size",e,t,n);return[r.slice(tm("x",e,t,n),a,s)]}case"StridedSlice":{const a=tm("begin",e,t,n),s=tm("end",e,t,n),o=tm("strides",e,t,n),i=tm("beginMask",e,t,n),u=tm("endMask",e,t,n),l=tm("ellipsisMask",e,t,n),c=tm("newAxisMask",e,t,n),p=tm("shrinkAxisMask",e,t,n),h=tm("x",e,t,n);return[r.stridedSlice(h,a,s,o,i,u,l,c,p)]}case"Pack":return ui((()=>{const a=tm("axis",e,t,n),s=tm("tensors",e,t,n),o=s[0].shape,i=r.squeeze(s[0]).shape,u=s.map((e=>{const t=rt(e.shape,o);if(!t&&!rt(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=tm("axis",e,t,n),s=tm("tensor",e,t,n);return r.unstack(s,a)}case"Tile":{const a=tm("reps",e,t,n);return[r.tile(tm("x",e,t,n),a)]}case"Split":case"SplitV":{const a=tm("axis",e,t,n),s=tm("numOrSizeSplits",e,t,n),o=tm("x",e,t,n);return r.split(o,s,a)}case"ScatterNd":{const a=tm("indices",e,t,n),s=tm("values",e,t,n),o=tm("shape",e,t,n);return[r.scatterND(a,s,o)]}case"GatherNd":{const a=tm("x",e,t,n),s=tm("indices",e,t,n);return[r.gatherND(a,s)]}case"SparseToDense":{const a=tm("sparseIndices",e,t,n),s=tm("outputShape",e,t,n),o=tm("sparseValues",e,t,n),i=tm("defaultValue",e,t,n);return[r.sparseToDense(a,o,s,o.dtype===i.dtype?i:r.cast(i,o.dtype))]}case"TensorScatterUpdate":{const a=tm("indices",e,t,n),s=tm("values",e,t,n),o=tm("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=Hm)=>{switch(e.op){case"SparseFillEmptyRows":{const{outputIndices:a,outputValues:s,emptyRowIndicator:o,reverseIndexMap:i}=r.sparse.sparseFillEmptyRows(tm("indices",e,t,n),tm("values",e,t,n),tm("denseShape",e,t,n),tm("defaultValue",e,t,n));return[a,s,o,i]}case"SparseReshape":{const{outputIndices:a,outputShape:s}=r.sparse.sparseReshape(tm("inputIndices",e,t,n),tm("inputShape",e,t,n),tm("newShape",e,t,n));return[a,s]}case"SparseSegmentMean":return[r.sparse.sparseSegmentMean(tm("data",e,t,n),tm("indices",e,t,n),tm("segmentIds",e,t,n))];case"SparseSegmentSum":return[r.sparse.sparseSegmentSum(tm("data",e,t,n),tm("indices",e,t,n),tm("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=Hm)=>{switch(e.op){case"FFT":return[r.fft(tm("x",e,t,n))];case"IFFT":return[r.ifft(tm("x",e,t,n))];case"RFFT":return[r.rfft(tm("x",e,t,n))];case"IRFFT":return[r.irfft(tm("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=Hm)=>{switch(e.op){case"StaticRegexReplace":return[r.string.staticRegexReplace(tm("input",e,t,n),tm("pattern",e,t,n),tm("rewrite",e,t,n),tm("replaceGlobal",e,t,n))];case"StringNGrams":{const{nGrams:a,nGramsSplits:s}=r.string.stringNGrams(tm("data",e,t,n),tm("dataSplits",e,t,n),tm("separator",e,t,n),tm("nGramWidths",e,t,n),tm("leftPad",e,t,n),tm("rightPad",e,t,n),tm("padWidth",e,t,n),tm("preserveShortSequences",e,t,n));return[a,s]}case"StringSplit":{const{indices:a,values:s,shape:o}=r.string.stringSplit(tm("input",e,t,n),tm("delimiter",e,t,n),tm("skipEmpty",e,t,n));return[a,s,o]}case"StringToHashBucketFast":return[r.string.stringToHashBucketFast(tm("input",e,t,n),tm("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=Hm)=>{switch(e.op){case"Cast":return[r.cast(tm("x",e,t,n),tm("dtype",e,t,n))];case"ExpandDims":{const a=tm("axis",e,t,n);return[r.expandDims(tm("x",e,t,n),a)]}case"Squeeze":{const a=tm("axis",e,t,n);return[r.squeeze(tm("x",e,t,n),a)]}case"Reshape":return[r.reshape(tm("x",e,t,n),tm("shape",e,t,n))];case"EnsureShape":return[r.ensureShape(tm("x",e,t,n),tm("shape",e,t,n))];case"MirrorPad":return[r.mirrorPad(tm("x",e,t,n),tm("padding",e,t,n),tm("mode",e,t,n))];case"PadV2":case"Pad":return[r.pad(tm("x",e,t,n),tm("padding",e,t,n),tm("constantValue",e,t,n))];case"SpaceToBatchND":{const a=tm("blockShape",e,t,n),s=tm("paddings",e,t,n);return[r.spaceToBatchND(tm("x",e,t,n),a,s)]}case"BatchToSpaceND":{const a=tm("blockShape",e,t,n),s=tm("crops",e,t,n);return[r.batchToSpaceND(tm("x",e,t,n),a,s)]}case"DepthToSpace":{const a=tm("blockSize",e,t,n),s=tm("dataFormat",e,t,n).toUpperCase();return[r.depthToSpace(tm("x",e,t,n),a,s)]}case"BroadcastTo":return[r.broadcastTo(tm("x",e,t,n),tm("shape",e,t,n))];case"BroadcastArgs":return[r.broadcastArgs(tm("s0",e,t,n),tm("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=tm("keyDType",e,t,n),s=tm("valueDType",e,t,n),o=new Zm(a,s);return r.addHashTable(e.name,o),[o.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{const a=tm("tableHandle",e,t,n,r),s=tm("keys",e,t,n),o=tm("values",e,t,n),i=r.getHashTableById(a.id);return[await i.import(s,o)]}case"LookupTableFind":case"LookupTableFindV2":{const a=tm("tableHandle",e,t,n,r),s=tm("keys",e,t,n),o=tm("defaultValue",e,t,n),i=r.getHashTableById(a.id);return[await i.find(s,o)]}case"LookupTableSize":case"LookupTableSizeV2":{const a=tm("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=em(e.op);if(s&&s.customExecutor)return s.customExecutor(new Vm(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 Et(s)?s.then((e=>[].concat(e))):[].concat(s)}class tg{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 ng(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=>om(e)[0])));r=r||[];const c=new Set(r.map((e=>om(e.name)[0]))),p=[...t];for(;p.length>0;){const e=p.pop();(ig(e)||ug(e)||lg(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 rg extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}}const ag=new Set(["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"]),sg=new Set(["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"]),og=new Set(["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"]);function ig(e){return ag.has(e.op)}function ug(e){return sg.has(e.op)}function lg(e){return og.has(e.op)}class cg{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 cg(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=ng(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=>om(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 rg(`Child ${e.name} of node ${t.name} is unreachable.`);if(n.get(t.name)>n.get(e.name))throw new rg(`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 rg(`Input ${e.name} of node ${t.name} is unreachable.`);if(n.get(e.name)>n.get(t.name))throw new rg(`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)=>ig(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){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[om(e)[0]])),a=t.map((e=>om(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=Ct().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const l={},c={};return ui((()=>{const n=new tg(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]=om(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=eg(e,r,n,this._resourceManager);if(Et(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=>nm(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(!ig(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(ig(e))continue;const t=rm(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 ig(e)||a.has(e.name)}if(!ig(e)&&null!=s)for(const e of s){if(o(e))continue;const a=rm(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=Ct().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const s=new tg(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=>nm(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[om(e)[0]])),o=n.map((e=>om(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}=ng(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]=om(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=>!ig(e)&&!nm(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&&tm("isConstant",e.node,r,n)&&([c]=am(e.node.name,n)),null==r[e.node.name]){const p=eg(e.node,r,n,this._resourceManager);c||([c]=am(e.node.name,n));const h=n.currentContext;Et(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]=am(e.name,n);!a[o]&&s.has(e.name)&&("Merge"===e.op?e.inputNames.some((e=>!!nm(e,r,n)))&&(a[o]=!0,t.push({contexts:n.currentContext,node:e})):e.inputNames.every((e=>!!nm(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]=om(t),a=this.graph.nodes[r];if(a.attrParams.shape&&a.attrParams.shape.value){const e=a.attrParams.shape.value;Ze(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&&Ze(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]=om(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]=om(e);if(!this.graph.nodes[t])throw new Error(`The output '${e}' is not found in the graph`)}))}}class pg{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 hg{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 pg}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 Et(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 cg(Nm.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=Nm.Instance.transformGraph(e.modelInitializer);this.initializer=new cg(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 Ns?[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 Ns||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 dg(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 hg(e,t,n);return await r.load(),r}function fg(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&Ze("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the CPU backend.`))}))}const mg=ed;class gg extends qe{nextDataId(){return gg.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new Ke(this,ii())}write(e,t,n){this.firstUse&&(this.firstUse=!1,Ct().get("IS_NODE")&&ya("\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&&mt(n[0])){const a=n.map((e=>ds(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?Rf(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=>fs(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=hs();return e(),{kernelMs:hs()-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){fg([e],"where");const t=this.readSync(e.dataId);return mg(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}function yg(e){return(t,n,r,a,s)=>{const o=Tu(t,n),i=o.length,u=_t(o),l=pt(s,nt(o)),c=t.length,p=n.length,h=_t(t),d=_t(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=St(t,i,u),s=n.slice(-c);f.forEach((e=>s[e]=0));const o=Tt(s,c,h),g=n.slice(-p);m.forEach((e=>g[e]=0));const y=Tt(g,p,d);l[t]=e(r[o],a[y])}return[l,o]}}function bg(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 _g(e,t,n="float32"){if("complex64"===n)return bg({inputs:{real:_g(e,t,"float32"),imag:_g(e,t,"float32")},backend:e});const r=kt(nt(t),n);return e.makeTensorInfo(t,n,r)}function xg(e){const{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}gg.nextDataId=0;const wg={kernelName:Ln,backendName:"cpu",kernelFunc:xg};function vg(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 kg(e,t,n,r){if("int32"===r)return[t,"int32",Int32Array.from(e)];if("bool"===r){const r=ps([0],n),[a,s]=yg(((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 Ig(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dtype:s}=r;if("complex64"===s){if("complex64"===a.dtype)return xg({inputs:{x:a},backend:n});const e=_g(n,a.shape,a.dtype),t=Ig({inputs:{x:a},backend:n,attrs:{dtype:"float32"}}),r=bg({inputs:{real:t,imag:e},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),r}if("complex64"===a.dtype){const e=vg({inputs:{input:a},backend:n}),t=Ig({inputs:{x:e},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(e),t}if(!dt(a.dtype,s)){const e=xg({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]=kg(o,a.shape,a.dtype,s);return n.makeTensorInfo(i,u,l)}const Tg={kernelName:tn,backendName:"cpu",kernelFunc:Ig};function Sg(e,t,n,r){return null==n?({inputs:n,backend:a})=>{const{a:s,b:o}=n,i=a;fg([s,o],e);const u=i.data.get(s.dataId).values,l=i.data.get(o.dataId).values,c="string"===s.dtype?jf(u):u,p="string"===s.dtype?jf(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=Ig({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=Ig({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=bg({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 Eg(e){return(t,n,r,a,s,o)=>{const i=Tu(t,n),u=nt(i),l=i.length,c=_t(i),p=pt("float32",u),h=pt("float32",u),d=ku(t,i),f=ku(n,i),m=Rf(r,a),g=Rf(s,o),y=t.length,b=_t(t),_=n.length,x=_t(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=St(t,l,c),r=n.slice(-y);d.forEach((e=>r[e]=0));const a=Tt(r,y,b),s=n.slice(-_);f.forEach((e=>s[e]=0));const o=Tt(s,_,x),i=e(m[2*a],m[2*a+1],g[2*o],g[2*o+1]);p[t]=i.real,h[t]=i.imag}return[p,h,i]}}const Ng=yg(((e,t)=>e+t)),Ag=Eg(((e,t,n,r)=>({real:e+n,imag:t+r}))),Cg=Sg(Pt,Ng,Ag),Rg={kernelName:Pt,backendName:"cpu",kernelFunc:Cg},Mg=yg(((e,t)=>e&t));function Fg(e){return(t,n,r)=>{const a=ht(n,t.length);for(let n=0;n<t.length;++n)a[n]=e(t[n],r);return a}}function $g(e,t,n){return Og(e,Fg(t),n)}function Og(e,t,n){return({inputs:r,attrs:a,backend:s})=>{const{x:o}=r;fg(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=jf(u)}else l=u;const c=n||o.dtype,p=t(l,c,a);return i.makeTensorInfo(o.shape,c,p)}}const Dg=Fg((e=>Math.ceil(e)));function Pg(e,t,n,r){const a=ht(n,nt(t));if(r&&"string"!==n){let t=0;e.forEach((e=>{const n=nt(e.shape);a.set(e.vals,t),t+=n}))}else{let r=0;e.forEach((e=>{const s="string"===n?jf(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 Lg=yg(((e,t)=>e===t?1:0)),Bg=Fg((e=>Math.exp(e))),Ug=Og(Sn,Bg,"float32"),Wg=Fg((e=>Math.expm1(e))),zg=Fg((e=>Math.floor(e))),Vg=yg(((e,t)=>Math.floor(e/t))),Hg=yg(((e,t)=>e>t?1:0)),Gg=yg(((e,t)=>e>=t?1:0)),jg=yg(((e,t)=>e<t?1:0)),Kg=yg(((e,t)=>e<=t?1:0)),qg=Fg((e=>Math.log(e)));function Xg(e,t,n,r){const a=pt(r,nt(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 Yg=yg(((e,t)=>Math.max(e,t))),Qg=yg(((e,t)=>Math.min(e,t))),Jg=yg(((e,t)=>e*t)),Zg=Eg(((e,t,n,r)=>({real:e*n-t*r,imag:e*r+t*n}))),ey=Sg(ur,Jg,Zg),ty={kernelName:ur,backendName:"cpu",kernelFunc:ey},ny=yg(((e,t)=>e!==t?1:0));function ry(e,t,n,r,a){const s=t.length,o=nt(t),i=_t(t),u=_t(a),l=pt(n,nt(a));for(let t=0;t<o;++t){const n=St(t,s,i),a=new Array(n.length);for(let e=0;e<a.length;e++)a[e]=n[r[e]];l[Tt(a,s,u)]=e[t]}return l}function ay(e){const{inputs:t,attrs:n,backend:r}=e,{x:a}=t,{perm:s}=n;fg(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=ry(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 sy(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 oy=_f;class iy{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=wf(l),this.raggedRank=vf(this.rowPartitionTypes)}getRowPartitionTypeByDimension(e){return this.rowPartitionTypes[0]===oy.FIRST_DIM_SIZE?this.rowPartitionTypes[e+1]:this.rowPartitionTypes[e]}getRowPartitionTensor(e){return this.rowPartitionTypes[0]===oy.FIRST_DIM_SIZE?this.rowPartitionValues[e+1]:this.rowPartitionValues[e]}getMaxWidth(e){const t=this.getRowPartitionTensor(e-1);switch(this.getRowPartitionTypeByDimension(e-1)){case oy.VALUE_ROWIDS:return iy.getMaxWidthValueRowID(t);case oy.ROW_SPLITS:return iy.getMaxWidthRowSplit(t);default:throw new Error(`Cannot handle partition type ${oy[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 ly(e,n)}calculateOutputSize(e){const t=this.valuesShape;kf(this.defaultValueShape,t);const n=this.tensorShapeFromTensor(this.shape,this.shapeShape),r=xf(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 Ze(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 oy.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(a,t,n,r);case oy.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: ${oy[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 oy.FIRST_DIM_SIZE:return e[0];case oy.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case oy.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${oy[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=ly(t,!1),a=ht(this.valuesDType,nt(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=nt(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);uy(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;)uy(s.slice(h*i),l,i),++h;r<0?(c=e+1,p=h):(c=e,p=h,h=p+1)}else++h}}}function uy(e,t,n){for(let r=0;r<n;r++)e[r]=t[r]}function ly(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 cy(e,t,n,r){if(e===t||e<t&&n<0||t<e&&n>1)return kt(0,r);const a=kt(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 py=Fg((e=>1/Math.sqrt(e))),hy=Fg((e=>1/(1+Math.exp(-e)))),dy=$g(Br,(e=>1/(1+Math.exp(-e)))),fy={kernelName:Br,backendName:"cpu",kernelFunc:dy};function my(e,t,n,r,a){const s=Vu(r,t,n),o=nt(n),i=_t(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?jf(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?Kf(l.values):l.values}function gy(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,size:o}=r;fg(a,"slice");const[i,u]=Gu(a,s,o);Fu(a,i,u);const l=my(n.data.get(a.dataId).values,i,u,a.shape,a.dtype);return n.makeTensorInfo(u,a.dtype,l)}const yy={kernelName:Dr,backendName:"cpu",kernelFunc:gy},by=Fg((e=>Math.sqrt(e))),_y=yg(((e,t)=>{const n=e-t;return n*n})),xy=Fg(((e,t)=>{const{pattern:n,replaceGlobal:r,rewrite:a}=t;return e.replace(new RegExp(n,r?"g":""),a)}));function wy(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 vy{constructor(e,t,n,r,a,s){this.separator=ds(e),this.nGramWidths=t,this.leftPad=ds(n),this.rightPad=ds(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=ht("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 ky(e,t,n,r,a,s,o,i){return new vy(n,r,a,s,o,i).compute(e,t)}function Iy(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 Ty(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;Iy(e[u],t,n,a);const l=a.length-r;i[u]=l,s+=l,o=Math.max(o,l)}const u=ht("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 Sy(e,t){const n=ht("int32",e.length);for(let r=0;r<e.length;++r)n[r]=ls(e[r]).modulo(t).getLowBitsUnsigned();return n}const Ey=yg(((e,t)=>e-t)),Ny=Eg(((e,t,n,r)=>({real:e-n,imag:t-r}))),Ay=Sg(na,Ey,Ny),Cy={kernelName:na,backendName:"cpu",kernelFunc:Ay},Ry=(e,t)=>{const n=t.value-e.value;return 0===n?e.index-t.index:n};function My(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);My(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(Je(e,n,t),Ry(e[r],a)>0&&Je(e,n,r);s<o;){for(Je(e,s,o),s++,o--;Ry(e[s],a)<0;)s+=1;for(;Ry(e[o],a)>0;)o-=1}0===Ry(e[n],a)?Je(e,n,o):(o+=1,Je(e,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}}function Fy(e,t,n,r){const a=lt(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 Ts(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 Ts(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 $y=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:Ng,bincountImpl:function(e,t,n,r,a){const s=nt(r),o=kt(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:Mg,castImpl:kg,ceilImpl:Dg,concatImpl:Pg,equalImpl:Lg,expImpl:Bg,expm1Impl:Wg,floorImpl:zg,floorDivImpl:Vg,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:Hg,greaterEqualImpl:Gg,lessImpl:jg,lessEqualImpl:Kg,linSpaceImpl:function(e,t,n){const r=(t-e)/(n-1),a=kt(n,"float32");a[0]=e;for(let e=1;e<a.length;e++)a[e]=a[e-1]+r;return a},logImpl:qg,maxImpl:Xg,maximumImpl:Yg,minimumImpl:Qg,multiplyImpl:Jg,negImpl:function(e,t,n){const r=cs(-1,n);return Jg([],t,r,e,n)},notEqualImpl:ny,prodImpl:function(e,t,n,r){const[a,s]=Sc(e,r),o=Ps(t,"int32"),i=kt(nt(a),o),u=nt(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=St(r,t.length,_t(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=ht("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=ht(n,nt(s)),i=e.length;return function(e,t,n,r,a,s){const o=sy(t,2)[1],i=sy(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=ht("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=ht(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 iy(e,t,n,r,a,s,o,i,u,l).compute()},rangeImpl:cy,rsqrtImpl:py,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 Ts?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:hy,sliceImpl:my,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(Of(i));return[ht(n,0),[0,p],ht(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(Df(t,n));if(n>=u)throw new Error(Pf(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=ht(n,t*p),h=ht(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=nt(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(Lf(c,e));c=e,u.push(1)}else{if(t<0)throw new Error(Bf(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(Uf(r,u));u[c]=e}if(nt(u)!==s)throw new Error(Wf(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=ht(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=ht(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(zf(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(Vf(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:by,squaredDifferenceImpl:_y,staticRegexReplaceImpl:xy,stridedSliceImpl:wy,stringNGramsImpl:ky,stringSplitImpl:Ty,stringToHashBucketFastImpl:Sy,subImpl:Ey,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=pt(n,o*r),l=pt("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&&(My(o,r),o=o.slice(0,r)),a&&o.sort(Ry);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:ry,uniqueImpl:Fy});function Oy(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{shape:s}=r,o=nt(a.shape),i=ut(s,o),u=nt(i);Ze(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 gg),1);const Dy={kernelName:vr,backendName:"cpu",kernelFunc:Oy},Py={kernelName:Tr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:o,size:i}=r;fg(a,"resizeBilinear");const u=_t(a.shape),[l,c]=i,[p,h,d,f]=a.shape,m=n.data.get(a.dataId).values,g=new Float32Array(nt([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)}},Ly=yg(((e,t)=>e/t)),By=Sg(vn,Ly),Uy={kernelName:vn,backendName:"cpu",kernelFunc:By},Wy={kernelName:gr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{paddings:s,constantValue:o}=r;fg(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=nt(a.shape),p=a.shape.length,h=_t(a.shape),d=nt(i),f=i.length,m=_t(i),g=pt(a.dtype,d);0!==o&&g.fill(o);for(let e=0;e<c;e++)g[Tt(St(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 zy(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;fg([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 Ts(h.outShape,a.dtype),w=_t(a.shape),v=_t(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 Vy={kernelName:sn,backendName:"cpu",kernelFunc:zy},Hy=$g(kn,(e=>e>=0?e:Math.exp(e)-1)),Gy=yg(((e,t)=>e<0?t*e:e)),jy=$g(wr,(e=>Math.max(0,e))),Ky={kernelName:wr,backendName:"cpu",kernelFunc:jy},qy=$g(Er,(e=>Math.min(Math.max(0,e),6))),Xy={kernelName:Er,backendName:"cpu",kernelFunc:qy};function Yy(e,t,n,r,a){if("linear"===n)return xg({inputs:{x:t},backend:e});if("relu"===n)return jy({inputs:{x:t},backend:e});if("elu"===n)return Hy({inputs:{x:t},backend:e});if("relu6"===n)return qy({inputs:{x:t},backend:e});if("prelu"===n)return function(e){const{inputs:t,backend:n}=e,{x:r,alpha:a}=t;fg([r,a],"prelu");const s=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values,[i,u]=Gy(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;fg([a],"leakyRelu");const o=nt(a.shape),i=n.data.get(a.dataId).values,u=pt("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 dy({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}const Qy={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=zy({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=Oy({inputs:{x:o},backend:n,attrs:{shape:[o.shape[0],1,1]}});m=Cg({inputs:{a:m,b:e},backend:n}),n.disposeIntermediateTensorInfo(e)}else m=Cg({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=Oy({inputs:{x:i},backend:n,attrs:{shape:[i.shape[0],1,1]}});m=Yy(n,m,d,e,f),n.disposeIntermediateTensorInfo(e)}else m=Yy(n,m,d,i,f);n.disposeIntermediateTensorInfo(e)}return m}};function Jy(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dilations:u,dimRoundingMode:l}=r;fg([a,s],"depthwiseConv2DNative");const c=_t(a.shape),p=_t(s.shape);let h=u;null==h&&(h=[1,1]),Ze(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 Ts(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 Zy={kernelName:yn,backendName:"cpu",kernelFunc:Jy},eb={kernelName:ga,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=Jy({inputs:{x:a,filter:s},backend:n,attrs:{strides:u,pad:l,dataFormat:c,dilations:p,dimRoundingMode:h}});if(o){const e=m;m=Cg({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(e)}if(d){const e=m;m=Yy(n,m,d,i,f),n.disposeIntermediateTensorInfo(e)}return m}},tb={kernelName:Vr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,paddings:o}=r;fg([a],"spaceToBatchND");const i=nt(s),u=[[0,0]];u.push(...o);for(let e=1+s.length;e<a.shape.length;++e)u.push([0,0]);const l=Wy.kernelFunc({inputs:{x:a},backend:n,attrs:{paddings:u,constantValue:0}}),c=Sf(l.shape,s,i,!1),p=Ef(c.length,s.length,!1),h=Nf(l.shape,s,i,!1),d=Oy({inputs:{x:l},backend:n,attrs:{shape:c}}),f=ay({inputs:{x:d},backend:n,attrs:{perm:p}}),m=Oy({inputs:{x:f},backend:n,attrs:{shape:h}});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),m}},nb={kernelName:Qt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,crops:o}=r;fg([a],"batchToSpaceND");const i=s.reduce(((e,t)=>e*t)),u=Sf(a.shape,s,i),l=Ef(u.length,s.length),c=Nf(a.shape,s,i),p=Af(o,s.length),h=Cf(c,o,s.length),d=Oy({inputs:{x:a},backend:n,attrs:{shape:u}}),f=ay({inputs:{x:d},backend:n,attrs:{perm:l}}),m=Oy({inputs:{x:f},backend:n,attrs:{shape:c}}),g=gy({inputs:{x:m},backend:n,attrs:{begin:p,size:h}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}},rb={kernelName:Jr,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;fg(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=Oy({inputs:{x:a},backend:n,attrs:{shape:f}});else if(g||y){Ze(a.shape.length>=1,(()=>`Input must have rank at least 1, got: ${a.shape.length}`));const e=$u(b,_,x),t=gy({inputs:{x:a},backend:n,attrs:{begin:b,size:e}});w=Oy({inputs:{x:t},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(t)}else{const e=wy(d,n.bufferSync(a),x,b);w=n.makeTensorInfo(f,e.dtype,e.values)}return w}};function ab(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r,s=lt(a,t[0].shape)[0];yf(t.map((e=>e.shape)),s);let o=bf(t.map((e=>e.shape)),s);if(0===nt(o))return n.makeTensorInfo(o,t[0].dtype,[]);const i=t.filter((e=>nt(e.shape)>0));if(1===i.length)return xg({inputs:{x:i[0]},backend:n});if("complex64"===i[0].dtype){const e=i.map((e=>vg({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=ab({inputs:e,backend:n,attrs:{axis:s}}),a=ab({inputs:t,backend:n,attrs:{axis:s}}),o=bg({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=nt(e.shape.slice(s));return Oy({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),l=u.map((e=>({vals:n.data.get(e.dataId).values,shape:e.shape})));o=bf(u.map((e=>e.shape)),1);const c=1===u[0].shape[0],p=Pg(l,o,t[0].dtype,c),h=bf(i.map((e=>e.shape)),s),d=n.makeTensorInfo(h,t[0].dtype,p);return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}const sb={kernelName:an,backendName:"cpu",kernelFunc:ab};function ob(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&&(Ze(-(o+1)<=s,(()=>`Axis must be in the interval [${-(o+1)}, ${o}]`)),u=o+s+1),i.splice(u,0,1),Oy({inputs:{x:a},backend:n,attrs:{shape:i}})}const ib={kernelName:mr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return ob({inputs:{input:t[0]},backend:n,attrs:{dim:a}});const s=t[0].shape,o=t[0].dtype;t.forEach((e=>{et(s,e.shape,"All tensors passed to stack must have matching shapes"),Ze(o===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const i=[],u=ab({inputs:t.map((e=>{const t=ob({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}},ub={kernelName:on,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;fg([a,s],"conv2dBackpropInput");const p=_t(s.shape),h=_t(a.shape);let d=Tl(l);const f=ml(o,s.shape,i,1,u,c,!1,d),m=new Ts(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)}},lb={kernelName:fn,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=_t(a.shape),v=_t(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)}},cb={kernelName:Nr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dims:s}=r;fg(a,"reverse");const o=a.shape.length,i=lt(s,a.shape);if(0===o)return xg({inputs:{x:a},backend:n});const u=new Ts(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)}},pb={kernelName:la,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=gy({inputs:{x:a},backend:n,attrs:{begin:c,size:p}});h[e]=Oy({inputs:{x:t},backend:n,attrs:{shape:u}}),n.disposeIntermediateTensorInfo(t)}return h}},hb={kernelName:Wt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;fg(a,"argMax");let o=lt(s,a.shape);const i=Ac(o,a.shape.length);let u=a;const l=[];null!=i&&(u=ay({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=kt(nt(c),"int32"),d=nt(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 db(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r;let i;fg(a,"sum"),i="bool"===a.dtype?Ig({inputs:{x:a},backend:n,attrs:{dtype:"int32"}}):xg({inputs:{x:a},backend:n});const u=i.shape.length,l=lt(s,i.shape),c=Ac(l,u);let p=l,h=i;null!=c&&(h=ay({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=_g(n,d,Ps(h.dtype,"int32"));const g=nt(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=Oy({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 fb={kernelName:rr,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r,i=lt(s,a.shape),u=nt(Sc(a.shape,i)[1]),l=[],c=n.makeTensorInfo([],"float32",new Float32Array([u]));l.push(c);const p=Ig({inputs:{x:a},backend:n,attrs:{dtype:"float32"}});l.push(p);const h=By({inputs:{a:p,b:c},backend:n});l.push(h);const d=db({inputs:{x:h},backend:n,attrs:{axis:s,keepDims:o}});return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),d}},mb={kernelName:Gr,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=lt([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=lt(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=ry(d,u,a.dtype,h,e),p=Rc(p.length,l),u=e}fg(a,"max"),Nc("max",p,l);const[f,m]=Sc(u,p),g=Xg(d,nt(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=Oy({inputs:{x:l},backend:n,attrs:{shape:c}}),h=Ay({inputs:{a,b:p},backend:n}),d=Ug({inputs:{x:h},backend:n}),f=db({inputs:{x:d},backend:n,attrs:{axis:u,keepDims:!1}}),m=Oy({inputs:{x:f},backend:n,attrs:{shape:c}}),g=By({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}},gb=$g(rn,((e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e})),yb={kernelName:rn,backendName:"cpu",kernelFunc:gb};function bb(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="max"===s?Number.NEGATIVE_INFINITY: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,m=t*r[0];for(let t=0;t<a.inChannels;++t)for(let y=0;y<a.outHeight;++y){const x=y*o-h,w=Math.max(0,x),v=Math.min(a.inHeight,c+x),k=n+y*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 y=f,b=0,x=0;for(let n=w;n<v;n+=u){const a=m+n*r[1];for(let n=c;n<h;n+=l){const o=e[a+n*r[2]+t];"max"===s&&o>y?y=o:"avg"===s&&(b+=o,x++)}if(isNaN(y))break}g[k+n*_+t]="avg"===s?b/x:y}}}return m}const _b={kernelName:qt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;fg(a,"avgPool");const{filterSize:s,strides:o,pad:i,dimRoundingMode:u}=r;Ze(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&&rt(l.inShape,l.outShape))c=xg({inputs:{x:a},backend:n});else{const e=n.data.get(a.dataId).values,t=_t(a.shape),r=bb(e,a.shape,a.dtype,t,l,"avg");c=n.makeTensorInfo(l.outShape,a.dtype,r.values)}return c}},xb={kernelName:Yt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a,b:s}=t,{transposeA:o,transposeB:i}=r;fg([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=nt(f),y=nt(m),b=Tu(a.shape.slice(0,-2),s.shape.slice(0,-2)).concat([h,d]);Ze(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=Oy({inputs:{x:a},backend:n,attrs:{shape:o?[g,c,h]:[g,h,c]}}),w=Oy({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=_t(x.shape),A=_t(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)}},wb={},vb={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function kb(e,t){if(!(e in wb)||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(Ct().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 wb[e]}),!1),Ct().getBool("SOFTWARE_WEBGL_ENABLED")&&(vb.failIfMajorPerformanceCaveat=!1),1===e?n.getContext("webgl",vb)||n.getContext("experimental-webgl",vb):n.getContext("webgl2",vb)}(e,t);if(null===n)return console.log("Could not get context for WebGL version",e),null;wb[e]=n}const n=wb[e];return null==n||n.isContextLost()?(delete wb[e],kb(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),wb[e])}var Ib,Tb,Sb;function Eb(e,t){return[t,e]}function Nb(e){const t=nt(e);return st(Math.ceil(t/4))}function Ab(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function Cb(e,t){const n=e;let r,a,s,o,i,u,l,c,p,h;return 2===Ct().getNumber("WEBGL_VERSION")?(r=n.R32F,a=n.R16F,s=n.RGBA16F,o=n.RGBA32F,i=n.RED,l=4,c=1,p=n.HALF_FLOAT,h=n.FLOAT,u=n.RGBA8):(r=e.RGBA,a=e.RGBA,s=e.RGBA,o=n.RGBA,i=e.RGBA,l=4,c=4,p=null!=t?t.HALF_FLOAT_OES:null,h=e.FLOAT,u=e.RGBA),{internalFormatFloat:r,internalFormatHalfFloat:a,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:o,textureFormatFloat:i,downloadTextureFormat:u,downloadUnpackNumChannels:l,defaultNumChannels:c,textureTypeHalfFloat:p,textureTypeFloat:h}}function Rb(e,t){const n=t();return Ct().getBool("DEBUG")&&function(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+function(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}(e,t))}(e),n}function Mb(e){return!!(Ct().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||5.96e-8<Math.abs(e)&&Math.abs(e)<65504)}function Fb(e,t){return Wb(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"}(Ib||(Ib={})),function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"}(Tb||(Tb={})),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"}(Sb||(Sb={}));const $b=/ERROR: [0-9]+:([0-9]+):/g;function Ob(e,t){const n=$b.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)=>ot((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 ${ot(l[0],i)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(c.join("\n"))}function Db(e,t){if(Rb(e,(()=>e.validateProgram(t))),!1===e.getProgramParameter(t,e.VALIDATE_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function Pb(e,t,n,r,a,s,o){const i=e.getAttribLocation(t,n);return-1!==i&&(Rb(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,r))),Rb(e,(()=>e.vertexAttribPointer(i,a,e.FLOAT,!1,s,o))),Rb(e,(()=>e.enableVertexAttribArray(i))),!0)}function Lb(e,t,n){Rb(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,n))),Rb(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)))}function Bb(e,t){Rb(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,t))),Rb(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)))}function Ub(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 Wb(e,t,n){const r=Rb(e,(()=>t()));if(null==r)throw new Error(n);return r}function zb(e,t=2){return nt(e.slice(0,e.length-t))}function Vb(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 Hb(e){let t=[1,1,1];return 0===e.length||1===e.length&&1===e[0]||(t=[zb(e),...Vb(e)]),t}function Gb(e){return e%2==0}function jb(e,t){if(rt(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(Gb(n)&&Gb(r)&&(1===e[0]||1===t[0]))return!0}return e[1]===t[1]&&Gb(e[0])&&Gb(t[0])}let Kb,qb;function Xb(e,t){return null!=e.getExtension(t)}function Yb(e){try{if(null!=kb(e))return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function Qb(e){const t=Cb(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 Jb=Ct();function Zb(){let e,t,n,r,a,s,o,i,u,l;return 2===Ct().getNumber("WEBGL_VERSION")?(e="#version 300 es",t="in",n="out",r="in",a="texture",s="outputColor",o="out vec4 outputColor;",i=Ct().getBool("WEBGL2_ISNAN_CUSTOM")?"\n bool isnan_custom(float val) {\n uint floatToUint = floatBitsToUint(val);\n return (floatToUint & 0x7fffffffu) > 0x7f800000u;\n }\n\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan_custom(val.x),\n isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n }\n\n #define isnan(value) isnan_custom(value)\n ":"",u="",l="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(e="",t="attribute",n="varying",r="varying",a="texture2D",s="gl_FragColor",o="",i="\n #define isnan(value) isnan_custom(value)\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n ",u="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",l="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:a,output:s,defineOutput:o,defineSpecialNaN:i,defineSpecialInf:u,defineRound:l}}function e_(e,t,n="index"){const r=_t(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 t_(e,t,n="index"){const r=_t(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 n_(e){const t=_t(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`}Jb.registerFlag("HAS_WEBGL",(()=>Jb.getNumber("WEBGL_VERSION")>0)),Jb.registerFlag("WEBGL_VERSION",(()=>Yb(2)?2:Yb(1)?1:0)),Jb.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",(()=>!1)),Jb.registerFlag("WEBGL_BUFFER_SUPPORTED",(()=>2===Jb.get("WEBGL_VERSION"))),Jb.registerFlag("WEBGL_CPU_FORWARD",(()=>!0)),Jb.registerFlag("WEBGL_FORCE_F16_TEXTURES",(()=>!1)),Jb.registerFlag("WEBGL_PACK",(()=>Jb.getBool("HAS_WEBGL"))),Jb.registerFlag("WEBGL_PACK_NORMALIZATION",(()=>Jb.getBool("WEBGL_PACK"))),Jb.registerFlag("WEBGL_PACK_CLIP",(()=>Jb.getBool("WEBGL_PACK"))),Jb.registerFlag("WEBGL_PACK_DEPTHWISECONV",(()=>Jb.getBool("WEBGL_PACK"))),Jb.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(()=>Jb.getBool("WEBGL_PACK"))),Jb.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(()=>Jb.getBool("WEBGL_PACK"))),Jb.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(()=>Jb.getBool("WEBGL_PACK"))),Jb.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(()=>Jb.getBool("WEBGL_PACK"))),Jb.registerFlag("WEBGL_PACK_REDUCE",(()=>Jb.getBool("WEBGL_PACK"))),Jb.registerFlag("WEBGL_LAZILY_UNPACK",(()=>Jb.getBool("WEBGL_PACK"))),Jb.registerFlag("WEBGL_CONV_IM2COL",(()=>Jb.getBool("WEBGL_PACK"))),Jb.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE",(()=>Jb.getBool("WEBGL_PACK"))),Jb.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(()=>function(e){if(null==Kb){const t=kb(e);Kb=t.getParameter(t.MAX_TEXTURE_SIZE)}return Kb}(Jb.getNumber("WEBGL_VERSION")))),Jb.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(()=>function(e){if(null==qb){const t=kb(e);qb=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,qb)}(Jb.getNumber("WEBGL_VERSION")))),Jb.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(()=>{const e=Jb.getNumber("WEBGL_VERSION");return 0===e?0:function(e){if(0===e)return 0;let t;const n=kb(e);return t=Xb(n,"EXT_disjoint_timer_query_webgl2")&&2===e?2:Xb(n,"EXT_disjoint_timer_query")?1:0,t}(e)})),Jb.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(()=>Jb.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!Xs())),Jb.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(()=>function(e){if(0===e)return!1;const t=kb(e);if(1===e){if(!Xb(t,"OES_texture_float"))return!1}else if(!Xb(t,"EXT_color_buffer_float"))return!1;return Qb(t)}(Jb.getNumber("WEBGL_VERSION")))),Jb.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(()=>!Jb.getBool("WEBGL_FORCE_F16_TEXTURES")&&Jb.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))),Jb.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(()=>function(e){if(0===e)return!1;const t=kb(e);if(1!==e){if(Xb(t,"EXT_color_buffer_float"))return Qb(t);const e="EXT_color_buffer_half_float";if(Xb(t,e)){const n=t.getExtension(e);return function(e,t){const n=Cb(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!!Xb(t,"OES_texture_float")&&!!Xb(t,"WEBGL_color_buffer_float")&&Qb(t)}(Jb.getNumber("WEBGL_VERSION")))),Jb.registerFlag("WEBGL_FENCE_API_ENABLED",(()=>{return 2===(e=Jb.getNumber("WEBGL_VERSION"))&&null!=kb(e).fenceSync;var e})),Jb.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(()=>Jb.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0)),Jb.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}.`)})),Jb.registerFlag("WEBGL_FLUSH_THRESHOLD",(()=>Xs()?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}.`)})),Jb.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",(()=>128)),Jb.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",(()=>!1)),Jb.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",(()=>1e5)),Jb.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",(()=>128)),Jb.registerFlag("WEBGL_EXP_CONV",(()=>!1)),Jb.registerFlag("SOFTWARE_WEBGL_ENABLED",(()=>Jb.getBool("IS_TEST"))),Jb.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",(()=>1/0)),Jb.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",(()=>!1)),Jb.registerFlag("WEBGL2_ISNAN_CUSTOM",(()=>!1)),Jb.registerFlag("ENGINE_COMPILE_ONLY",(()=>!1));const r_="\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:a_}=qf;function s_(e,t,n){const r=[];if(e.forEach((e=>{const t=nt(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}=m_(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?i_(e,r):o_(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=a_(e.shapeInfo.logicalShape,t.logicalShape),u=f_(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===nt(e.shapeInfo.logicalShape),m=1===nt(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&&rt(o,s))return`\n float ${a}() {\n return sampleTexture(${n}, resultUV);\n }\n `;const l=f_(u),c=a_(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=Zb(),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 ${u_}\n ${l_}\n ${c_}\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(rt(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 rt(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 ${t_(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n`;const r=e_(["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 ${t_(["r","c","d","d2"],e)}\n return ivec4(r, c, d, d2);\n }\n `;const r=e_(["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=e_(["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=e_(["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+=p_),[p,u,c,a,l,s,n.userCode].join("\n")}function o_(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=h_(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 ${d_(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=h_(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&&rt(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}=ct(n),u=o;if(u.length<n.length){const n=["row","col"];return`\n ${o_(g_(e,u),t)}\n float ${a}(int row, int col) {\n return ${a}(${y_(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 ${d_(e)}\n }\n `;const l=s[0],c=s[1],p=h_(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}=ct(n),l=i;if(l.length<n.length){const n=["row","col","depth"];return`\n ${o_(g_(e,l),t)}\n float ${a}(int row, int col, int depth) {\n return ${a}(${y_(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 ${d_(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=h_(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}=ct(n);if(u.length<n.length){const n=["row","col","depth","depth2"];return`\n ${o_(g_(e,u),t)}\n float ${a}(int row, int col, int depth, int depth2) {\n return ${a}(${y_(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 ${d_(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=h_(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}=ct(t);if(u.length<t.length){const t=["row","col","depth","depth2","depth3"];return`\n ${o_(g_(e,u))}\n float ${r}(int row, int col, int depth, int depth2, int depth3) {\n return ${r}(${y_(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 ${d_(e)}\n }\n `;const c=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,h=p[0],d=p[1];if(d===i&&null==c)return`\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 `;if(d===a&&null==c)return`\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 `;return`\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 + ${h_(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}=ct(t);if(a.length<t.length){const t=["row","col","depth","depth2","depth3","depth4"];return`\n ${o_(g_(e,a))}\n float ${r}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return ${r}(${y_(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 ${d_(e)}\n }\n `;const p=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,d=h[0],f=h[1];if(f===c&&null==p)return`\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 `;if(f===o&&null==p)return`\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 `;return`\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 + ${h_(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 i_(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 ${Zb().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=Zb();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=Zb();if(null!=s&&rt(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 ${i_(g_(e,n.slice(1)),t)}\n vec4 ${a}(int b, int row, int col) {\n return ${a}(${y_(s,r)});\n }\n `}const i=Zb();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=Zb();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 u_="\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",l_="\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",c_="\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",p_="\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 h_(e){return`offset${e}`}function d_(e){const t=e.name,n=nt(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 f_(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 m_(e,t,n){const{newShape:r,keptDims:a}=ct(t),s=t.length,o=e&&3===s&&1===t[0],i=o?t.slice(1):r,u=!e&&s>1&&!rt(t,n)&&r.length<s||o;return{useSqueezeShape:u,uniformShape:u?i:t,keptDims:a}}function g_(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function y_(e,t){return t.map((t=>e[t])).join(", ")}function b_(e,t,n){const r=[],a=[];let s,o,i,u=null,l=null;l=e.getUniformLocation(n,"NAN",!1),1===Ct().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 __(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(!rt(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(!rt(o,i))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${o} and ${i} must match`)}))}function x_(e){return Ct().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}class w_{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Ib.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=Zb();this.outputShape=e,this.enableShapeUniforms=x_(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?t_(["r","c","d"],e):e_(["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 v_{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Ib.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=Zb();this.outputShape=e,this.enableShapeUniforms=x_(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?t_(["r","c","d"],e):e_(["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 k_{constructor(e){this.variableNames=["A"],this.outTexUsage=Tb.DOWNLOAD;const t=Zb();this.outputShape=e,this.userCode=`\n ${r_}\n\n void main() {\n float x = getAAtOutCoords();\n ${t.output} = encode_float(x);\n }\n `}}class I_{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Tb.DOWNLOAD;const t=Zb();this.outputShape=e,this.userCode=`\n ${r_}\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 T_={R:0,G:1,B:2,A:3};class S_{constructor(e,t=!1,n="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const r=Zb();this.outputShape=e,this.enableShapeUniforms=x_(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[${T_[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":n_(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 E_{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=Zb();this.outputShape=e,this.enableShapeUniforms=x_(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":n_(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 N_(e,t,n,r,a,s){!function(e,t){const n=Ct().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0)throw new Error(`Requested texture size [${e}x${t}] is invalid.`);if(e>n||t>n)throw new Error(`Requested texture size [${e}x${t}] greater than WebGL maximum on this browser / GPU [${n}x${n}].`)}(t,n);const o=function(e){return Wb(e,(()=>e.createTexture()),"Unable to create WebGLTexture.")}(e),i=e.TEXTURE_2D;return Rb(e,(()=>e.bindTexture(i,o))),Rb(e,(()=>e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE))),Rb(e,(()=>e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE))),Rb(e,(()=>e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST))),Rb(e,(()=>e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST))),1===Ct().getNumber("WEBGL_VERSION")?Rb(e,(()=>e.texImage2D(i,0,r,t,n,0,a,s,null))):Rb(e,(()=>e.texStorage2D(i,1,r,t,n))),Rb(e,(()=>e.bindTexture(e.TEXTURE_2D,null))),{texture:o,texShape:[n,t]}}function A_(e){return e.internalFormatFloat}function C_(e){return e.internalFormatHalfFloat}function R_(e){return e.downloadTextureFormat}function M_(e){return e.internalFormatPackedFloat}function F_(e){return e.internalFormatPackedHalfFloat}class $_{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];const t=Ct().getNumber("WEBGL_VERSION");if(null!=e?(this.gl=e,function(e,t){wb[e]=t}(t,e)):this.gl=kb(t),e=this.gl,2===Ct().getNumber("WEBGL_VERSION")){const t=e;this.createVertexArray=()=>Rb(t,(()=>t.createVertexArray())),this.bindVertexArray=e=>Rb(t,(()=>t.bindVertexArray(e))),this.deleteVertexArray=e=>Rb(t,(()=>t.deleteVertexArray(e))),this.getVertexArray=()=>Rb(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=()=>Rb(e,(()=>t.createVertexArrayOES())),this.bindVertexArray=n=>Rb(e,(()=>t.bindVertexArrayOES(n))),this.deleteVertexArray=n=>Rb(e,(()=>t.deleteVertexArrayOES(n))),this.getVertexArray=()=>Rb(e,(()=>e.getParameter(t.VERTEX_ARRAY_BINDING_OES)))}let n="WEBGL_color_buffer_float";const r="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),1===Ct().getNumber("WEBGL_VERSION")){const e="OES_texture_float",t="OES_texture_half_float";if(this.textureFloatExtension=Fb(this.gl,e),Xb(this.gl,t))this.textureHalfFloatExtension=Fb(this.gl,t);else if(Ct().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Xb(this.gl,r))this.colorBufferHalfFloatExtension=Fb(this.gl,r);else if(Ct().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Xb(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!Xb(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=Wb(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return Rb(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),Rb(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=Wb(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return Rb(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n))),Rb(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 Wb(e,(()=>e.createFramebuffer()),"Unable to create WebGLFramebuffer.")}(this.gl),this.textureConfig=Cb(this.gl,this.textureHalfFloatExtension)}get debug(){return Ct().getBool("DEBUG")}dispose(){if(this.disposed)return;null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");const e=this.gl;Rb(e,(()=>e.finish())),Rb(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,null))),Rb(e,(()=>e.deleteFramebuffer(this.framebuffer))),Rb(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,null))),Rb(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null))),Rb(e,(()=>e.deleteBuffer(this.indexBuffer))),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=Eb(t,n);return N_(e,a,s,A_(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]=Eb(t,n);return N_(e,a,s,C_(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]=Eb(t,n);return N_(e,a,s,R_(r),e.RGBA,e.UNSIGNED_BYTE)}(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),function(e,t,n){Rb(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),n.data instanceof Uint8Array?2===Ct().getNumber("WEBGL_VERSION")?Rb(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data))):Rb(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data))):2===Ct().getNumber("WEBGL_VERSION")?Rb(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n))):Rb(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n))),Rb(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;Rb(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),a instanceof Uint8Array?(o=new Uint8Array(n*r*4),i=e.UNSIGNED_BYTE,u=e.RGBA):(o=new Float32Array(n*r*4),i=e.FLOAT,u=s.internalFormatPackedFloat),o.set(a),2===Ct().getNumber("WEBGL_VERSION")?Rb(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGBA,i,o))):Rb(e,(()=>e.texImage2D(e.TEXTURE_2D,0,u,n,r,0,e.RGBA,i,o))),Rb(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]=Ab(t,n);return N_(e,a,s,F_(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]=Ab(t,n);return N_(e,a,s,M_(r),e.RGBA,e.FLOAT)}(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Bb(this.gl,this.framebuffer),this.outputTexture=null),Rb(this.gl,(()=>this.gl.deleteTexture(e)))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>function(e,t,n,r){const[a,s]=Eb(t,n),o=new Uint8Array(t*n*4);return Rb(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]=Ab(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();Rb(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,a)));const s=16*t*n;return Rb(e,(()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ))),Rb(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0))),Rb(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null))),a}(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(Ct().getBool("WEBGL_FENCE_API_ENABLED")){const r=e,a=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{const e=r.clientWaitSync(a,0,0);return e===r.ALREADY_SIGNALED||e===r.CONDITION_SATISFIED},t=a}else Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>function(e,t,n){const r=new Float32Array(t*n*4);return Rb(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=Zb();return function(e,t){const n=Wb(e,(()=>e.createShader(e.VERTEX_SHADER)),"Unable to create vertex WebGLShader.");if(Rb(e,(()=>e.shaderSource(n,t))),Rb(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 Wb(e,(()=>e.createProgram()),"Unable to create WebGLProgram.")}(t);Rb(t,(()=>t.attachShader(n,this.vertexShader))),Rb(t,(()=>t.attachShader(n,e))),function(e,t){if(Rb(e,(()=>e.linkProgram(t))),!Ct().get("ENGINE_COMPILE_ONLY")&&!1===e.getProgramParameter(t,e.LINK_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}(t,n);const r=Object.assign(n,{vao:this.createVertexArray()});return this.debug&&Db(t,r),r}buildVao(e){this.setProgram(e),this.bindVertexArray(e.vao);const t=this.gl;Rb(t,(()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer))),function(e,t,n){Rb(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),Pb(e,t,"clipSpacePos",n,3,20,0)&&Pb(e,t,"uv",n,2,20,12)}(t,e,this.vertexBuffer)}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&(Rb(this.gl,(()=>this.gl.deleteProgram(e))),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,null!=this.program&&this.debug&&Db(this.gl,this.program),Rb(this.gl,(()=>this.gl.useProgram(e)))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?function(e,t,n){return Wb(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(),Rb(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){Rb(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),Rb(e,(()=>e.activeTexture(e.TEXTURE0+n))),Rb(e,(()=>e.bindTexture(e.TEXTURE_2D,t)))}(e,t,r))),Rb(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]=Ab(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&&Db(this.gl,this.program),Ub(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()}Rb(e,(()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),Rb(this.gl,(()=>this.gl.finish()))}getQueryTimerExtension(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=Fb(this.gl,2===Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(2===Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}const e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(2===Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2();return void e.endQuery(t.TIME_ELAPSED_EXT)}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await it((()=>this.disposed||this.isQueryAvailable(e,Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")))),this.getQueryTime(e,Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(0===t)return null;if(2===t){const t=this.gl;return t.getQueryParameter(e,t.QUERY_RESULT)/1e6}{const t=this.getQueryTimerExtensionWebGL1();return t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(0===t)return!0;if(2===t){const t=this.gl,n=this.getQueryTimerExtensionWebGL2(),r=t.getQueryParameter(e,t.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),r&&!this.disjoint}{const t=this.getQueryTimerExtensionWebGL1(),n=t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(t.GPU_DISJOINT_EXT)),n&&!this.disjoint}}pollFence(e){return new Promise((t=>{this.addItemToPoll((()=>e.isFencePassed()),(()=>t()))}))}pollItems(){const e=function(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}(this.itemsToPoll.map((e=>e.isDoneFn)));for(let t=0;t<=e;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;let n;"setTimeoutCustom"in Ct().platform&&(n=Ct().platform.setTimeoutCustom.bind(Ct().platform)),it((()=>(this.pollItems(),0===this.itemsToPoll.length)),(()=>0),null,n)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),Lb(this.gl,e,this.framebuffer),this.debug&&Ub(this.gl)}unbindTextureToFrameBuffer(){null!=this.outputTexture?(Lb(this.gl,this.outputTexture,this.framebuffer),this.debug&&Ub(this.gl)):Bb(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;Lb(r,e,this.framebuffer),this.debug&&Ub(r),this.outputTexture=e,Rb(r,(()=>r.viewport(0,0,t,n))),Rb(r,(()=>r.scissor(0,0,t,n)))}setOutputMatrixWriteRegionDriver(e,t,n,r){this.throwIfDisposed(),Rb(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:O_,bincountImpl:D_,bincountReduceImpl:P_,bitwiseAndImpl:L_,castImpl:B_,ceilImpl:U_,concatImpl:W_,equalImpl:z_,expImpl:V_,expm1Impl:H_,floorImpl:G_,gatherNdImpl:j_,gatherV2Impl:K_,greaterImpl:q_,greaterEqualImpl:X_,lessImpl:Y_,lessEqualImpl:Q_,linSpaceImpl:J_,logImpl:Z_,maxImpl:ex,maximumImpl:tx,minimumImpl:nx,multiplyImpl:rx,negImpl:ax,notEqualImpl:sx,prodImpl:ox,raggedGatherImpl:ix,raggedRangeImpl:ux,raggedTensorToTensorImpl:lx,rangeImpl:cx,rsqrtImpl:px,scatterImpl:hx,sigmoidImpl:dx,simpleAbsImpl:fx,sliceImpl:mx,sparseFillEmptyRowsImpl:gx,sparseReshapeImpl:yx,sparseSegmentReductionImpl:bx,sqrtImpl:_x,staticRegexReplaceImpl:xx,stridedSliceImpl:wx,stringNGramsImpl:vx,stringSplitImpl:kx,stringToHashBucketFastImpl:Ix,subImpl:Tx,tileImpl:Sx,topKImpl:Ex,transposeImpl:Nx,uniqueImpl:Ax}=$y;function Cx(e,t){return["x","y","z","w","u","v"].slice(0,t).map((t=>`${e}.${t}`))}function Rx(e,t){return 1===t?[e]:Cx(e,t)}class Mx{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=x_(this.outputShape.length),0===this.rank)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{const e=Rx("rc",this.rank),t=f_(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 Fx{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=x_(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"):e_(["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":n_(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 $x{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=Dx(t,n),a=Px(e,r,n);a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]);const s=Ox(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===Sb.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===Sb.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===Sb.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===Sb.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===Sb.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=Dx(n,r),s=Px(t,a,r);s in this.freeTextures||(this.freeTextures[s]=[]);const o=Ox(t,a,this.gpgpu.gl,this.gpgpu.textureConfig,r),i=Ct().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 Ox(e,t,n,r,a){const s=function(e,t){switch(e){case Sb.PACKED_2X2_FLOAT32:return M_(t);case Sb.PACKED_2X2_FLOAT16:return F_(t);case Sb.UNPACKED_FLOAT32:return A_(t);case Sb.UNPACKED_FLOAT16:return C_(t);case Sb.PACKED_4X1_UNSIGNED_BYTE:return R_(t);default:throw new Error(`Unknown physical texture type ${e}`)}}(t,r);let o;if(a){const[t,n]=Ab(e[0],e[1]);o=t*n}else{const[t,n]=Eb(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 Dx(e,t){if(e===Tb.UPLOAD)return Sb.PACKED_2X2_FLOAT32;if(e===Tb.RENDER||null==e)return function(e){return Ct().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Sb.PACKED_2X2_FLOAT32:Sb.UNPACKED_FLOAT32:e?Sb.PACKED_2X2_FLOAT16:Sb.UNPACKED_FLOAT16}(t);if(e===Tb.DOWNLOAD||e===Tb.PIXELS)return Sb.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function Px(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class Lx{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=x_(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 Bx="return abs(x);",Ux="return x;";class Wx{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=x_(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 zx{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=x_(this.outputShape.length);const t=e.length,n=Rx("rc",t),r=f_(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 Vx=ed,Hx={},Gx=Ct().getNumber("CPU_HANDOFF_SIZE_THRESHOLD");class jx extends qe{nextDataId(){return jx.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,!Ct().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(null!=e){if(e instanceof $_)t=e;else{const n=kb(Ct().getNumber("WEBGL_VERSION"),e);t=new $_(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{const e=kb(Ct().getNumber("WEBGL_VERSION"));t=new $_(e),this.binaryCache=((n=Ct().getNumber("WEBGL_VERSION"))in Hx||(Hx[n]={}),Hx[n]),this.gpgpuCreatedLocally=!0}var n;this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new $x(this.gpgpu),this.numMBBeforeWarning=null==Ct().global.screen?1024:Ct().global.screen.height*Ct().global.screen.width*window.devicePixelRatio*600/1024/1024,this.texData=new Ke(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=Hb(t),l=new S_(u,!1,s),c=this.runWebGLProgram(l,[o],n,[[r,a]]);return c.shape=t,i.texture=null,this.disposeIntermediateTensorInfo(o),c.dataId}write(e,t,n){if((Ct().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||Ct().getBool("DEBUG"))&&this.checkNumericalProblems(e),"complex64"===n&&null!=e)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const r={id:this.nextDataId()};return this.texData.set(r,{shape:t,dtype:n,values:e,usage:Tb.UPLOAD,refCount:1}),r}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){this.texData.get(e).refCount++}decRef(e){this.texData.has(e)&&this.texData.get(e).refCount--}move(e,t,n,r,a){if(Ct().getBool("DEBUG")&&this.checkNumericalProblems(t),"complex64"===r)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:r,values:t,usage:Tb.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 Wx(o,Ux):new Lx(o,Ux);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=hs()),c="complex64"===r?Rf(this.readSync(a.real.dataId),this.readSync(a.imag.dataId)):this.getValuesFromTexture(e),u&&(this.downloadWaitMs+=hs()-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 Wx(r,Ux):new Lx(r,Ux);const n=this.runWebGLProgram(t,[{dataId:e,shape:r,dtype:s}],s),a=this.read(n.dataId);return this.disposeIntermediateTensorInfo(n),a}if(null!=n)return this.convertAndCacheOnCPU(e);if(Ct().getBool("DEBUG")&&!Ct().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===Ct().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let u,l,c=null;if("complex64"!==s&&Ct().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);const t=this.texData.get(u.dataId);c=this.gpgpu.createBufferFromTexture(t.texture.texture,...Nb(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=Rf(e[0],e[1])}else if(null==c)l=this.getValuesFromTexture(e);else{const e=nt(r);l=this.gpgpu.downloadFloat32MatrixFromBuffer(c,e)}if(null!=u&&this.disposeIntermediateTensorInfo(u),null!=c){const e=this.gpgpu.gl;Rb(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 Wx(a,Ux):new Lx(a,Ux);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=>fs(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(!Mb(n)){if(Ct().getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))throw Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`);throw Error(`The value ${n} cannot be represented on this device.`)}}}getValuesFromTexture(e){const{shape:t,dtype:n,isPacked:r}=this.texData.get(e),a=nt(t);if(Ct().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const n=this.decode(e),r=this.texData.get(n.dataId),s=this.gpgpu.downloadMatrixFromPackedTexture(r.texture.texture,...Nb(t)).subarray(0,a);return this.disposeIntermediateTensorInfo(n),s}const s=Ct().getBool("WEBGL_PACK")&&!0===r,o=s?Hb(t):t,i=s?new I_(o):new k_(o),u=this.runWebGLProgram(i,[{shape:o,dtype:n,dataId:e}],"float32"),l=this.texData.get(u.dataId),c=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(l.texture.texture,l.texShape[0],l.texShape[1]).subarray(0,a);return this.disposeIntermediateTensorInfo(u),c}timerAvailable(){return Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(e){const t=this.activeTimers,n=[];let r=!1;null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e();const a=gs(this.activeTimers.map((e=>e.query))).filter((e=>null!=e)),s=gs(this.activeTimers.map((e=>e.name))).filter((e=>null!=e));this.activeTimers=t,r&&(this.programTimersStack=null);const o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const e=await Promise.all(a);o.kernelMs=function(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}(e),o.getExtraProfileInfo=()=>e.map(((e,t)=>({name:s[t],ms:e}))).map((e=>`${e.name}: ${e.ms}`)).join(", ")}else o.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,o})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:hs(),endMs:null}}endTimer(e){return Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=hs(),e)}async getQueryTime(e){if(Ct().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);const t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);const{complexTensorInfos:n}=this.texData.get(e);return null!=n&&(this.disposeData(n.real.dataId,t),this.disposeData(n.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){const{texture:t,dtype:n,texShape:r,usage:a,isPacked:s,slice:o}=this.texData.get(e),i=o&&o.origDataId||e,u=this.dataRefCount.get(i);u>1?this.dataRefCount.set(i,u-1):(this.dataRefCount.delete(i),null!=t&&(this.numBytesInGPU-=this.computeBytes(r,n),this.textureManager.releaseTexture(t,r,a,s)));const l=this.texData.get(e);l.texture=null,l.texShape=null,l.isPacked=!1,l.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=Gx){return Ct().getBool("WEBGL_CPU_FORWARD")&&e.every((e=>null==this.texData.get(e.dataId).texture&&nt(e.shape)<t))}getGPGPUContext(){return this.gpgpu}where(e){ya("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return Vx(e.shape,t)}packedUnaryOp(e,t,n){const r=new Wx(e.shape,t),a=this.compileAndRun(r,[e],n);return ii().makeTensorFromTensorInfo(a)}abs(e){if(this.shouldExecuteOnCPU([e])&&"complex64"!==e.dtype){const t=fx(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,t)}if(Ct().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Bx,e.dtype);const t=new Lx(e.shape,Bx),n=this.compileAndRun(t,[e]);return ii().makeTensorFromTensorInfo(n)}makeTensorInfo(e,t,n){let r;if("string"===t&&null!=n&&n.length>0&&mt(n[0])){const a=n.map((e=>ds(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 zx(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new Mx(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const n=[zb(e.shape),...Vb(e.shape)],r={dtype:e.dtype,shape:n,dataId:e.dataId},a=[zb(t),...Vb(t)],s=new Fx(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&&Ze(nt(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=Hb(a);let i;i=r?new v_(o):new w_(o);const u=[null!=t?t:Nb(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===Ib.DENSE){const t=null!=s?s:Nb(e.outputShape);i.texShape=t.map((e=>2*e))}if(null!=e.outTexUsage&&(i.usage=e.outTexUsage),0===nt(o.shape))return i.values=pt(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&&nt(t.shape)<=Ct().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:t.shape,texData:null,isUniform:!0,uniformValues:n.values};e.packedInputs&&(n.isPacked=!0,n.shape=t.shape)}if(this.uploadToGPU(t.dataId),!!n.isPacked!=!!e.packedInputs)t=n.isPacked?this.unpackTensor(t):this.packTensor(t),u.push(t),n=this.texData.get(t.dataId);else if(n.isPacked&&!jb(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}=m_(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=_t(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&&rt(t.shape,s),f=1===nt(t.shape),m=ku(t.shape,n.shape),g=!e.packedInputs&&h===n.shape.length&&rt(s,n.texData.texShape),y=e.packedInputs||i.length>2?"":`${s[0]>1}_${s[1]>1}`;r+=`${h}_${g}_${o?u:""}_${i.length}_${f}_${m}_${d}_${l}_${c}_${p}_${y}_${a}`}else{const e=t.isUniform?"uniform":t.texData.texShape;r+=`${t.shape}_${e}_${a}`}}));const a=e.userCode;let s=e.constructor.name;return s+="_"+r+"_"+a+`${Ct().getNumber("WEBGL_VERSION")}`,s}(e,l,c),h=this.getAndSaveBinary(p,(()=>function(e,t,n,r){const a=n.map(((e,n)=>{const r={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.isPacked,flatOffset:null};return null!=e.texData&&null!=e.texData.slice&&e.texData.slice.flatOffset>0&&(r.flatOffset=e.texData.slice.flatOffset),{name:t.variableNames[n],shapeInfo:r}})),s=a.map((e=>e.shapeInfo)),o={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},i=s_(a,o,t),u=function(e,t){const n=Wb(e,(()=>e.createShader(e.FRAGMENT_SHADER)),"Unable to create fragment WebGLShader.");if(Rb(e,(()=>e.shaderSource(n,t))),Rb(e,(()=>e.compileShader(n))),Ct().get("ENGINE_COMPILE_ONLY"))return n;if(!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw Ob(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}(e.gl,i),l=e.createProgram(u);return Ct().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:u,source:i,webGLProgram:l,inShapeInfos:s,outShapeInfo:o,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},b_(e,t,l)))}(this.gpgpu,e,l,c))),d=null!=this.activeTimers;let f;d&&(f=this.startTimer()),Ct().get("ENGINE_COMPILE_ONLY")||function(e,t,n,r,a){t.program.enableShapeUniforms||(__(t.inShapeInfos,n),__([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===Ct().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}=m_(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(nt(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=_t(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=Ct().getNumber("WEBGL_FLUSH_THRESHOLD");if(m>0){const e=hs();e-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=e)}if(!Ct().getBool("WEBGL_LAZILY_UNPACK")&&i.isPacked&&!1===a){const e=this.unpackTensor(o);return this.disposeIntermediateTensorInfo(o),e}return o}compileAndRun(e,t,n,r,a=!1){return n=n||t[0].dtype,this.runWebGLProgram(e,t,n,r,a)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(Ct().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach((e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]})),this.textureManager.dispose(),null!=this.canvas&&"undefined"!=typeof HTMLCanvasElement&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return null==this.floatPrecisionValue&&(this.floatPrecisionValue=ui((()=>{if(!Ct().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=Ct().getBool("DEBUG");Ct().set("DEBUG",!1);const t=this.abs(Oc(1e-8)).dataSync()[0];if(Ct().set("DEBUG",e),t>0)return 32}return 16}))),this.floatPrecisionValue}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}uploadToGPU(e){const t=this.texData.get(e),{shape:n,dtype:r,values:a,texture:s,usage:o,isPacked:i}=t;if(null!=s)return;const u=null!=this.activeTimers;let l;u&&(l=hs());let c=t.texShape;if(null==c&&(c=function(e,t=!1){let n=Ct().getNumber("WEBGL_MAX_TEXTURE_SIZE"),r=Ct().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");if(r===1/0&&Ct().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(r=n/2),t&&(n*=2,r*=2,e=e.map(((t,n)=>n>=e.length-2?Qe(e[n]):e[n])),1===e.length&&(e=[2,e[0]])),2!==e.length){const t=ct(e);e=t.newShape}let a=nt(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=zb(e);let n=2,r=2;e.length&&([n,r]=Vb(e)),a=t*(n/2)*(r/2),s=st(a).map((e=>2*e))}else s=st(a);return s}(n,i),t.texShape=c),null!=a){const e=Hb(n);let s,o=c[1],p=c[0];const h=a instanceof Uint8Array||a instanceof Uint8ClampedArray;!i&&h||([o,p]=Ab(c[0],c[1])),s=i?new E_(e,h):new S_(e,h);const d=h?[p,o]:c,f=this.makeTensorInfo(d,r),m=this.texData.get(f.dataId);m.usage=h?Tb.PIXELS:Tb.UPLOAD,m.texShape=d,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(f.dataId),o,p,a);const g=[[p,o]],y=!0,b=this.runWebGLProgram(s,[f],r,g,y),_=this.texData.get(b.dataId);t.texShape=_.texShape,t.isPacked=_.isPacked,t.usage=_.usage,Ct().get("ENGINE_COMPILE_ONLY")?this.disposeData(b.dataId):(t.texture=_.texture,t.values=null,this.texData.delete(b.dataId)),this.disposeIntermediateTensorInfo(f),u&&(this.uploadWaitMs+=hs()-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]*ft(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=>gf((()=>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 Ob(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}=b_(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)}}jx.nextDataId=0,Ys()&&di("webgl",(()=>new jx),2);class Kx{constructor(e){this.variableNames=["A"];const t=Zb(),[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 qx{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=Zb(),[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 Xx={kernelName:ha,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e;let{pixels:a}=t;const{numChannels:s}=r,o="undefined"!=typeof HTMLVideoElement&&a instanceof HTMLVideoElement,i="undefined"!=typeof HTMLImageElement&&a instanceof HTMLImageElement,[u,l]=o?[a.videoWidth,a.videoHeight]:[a.width,a.height],c=[l,u],p=[l,u,s];if(i||o){const e=Ct().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");null!=Yx&&e===Qx||(Qx=e,Yx=document.createElement("canvas").getContext("2d",{willReadFrequently:Qx})),Yx.canvas.width=u,Yx.canvas.height=l,Yx.drawImage(a,0,0,u,l),a=Yx.canvas}const h=n.makeTensorInfo(c,"int32");n.texData.get(h.dataId).usage=Tb.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(h.dataId),a);const d=Ct().getBool("WEBGL_PACK")?new qx(p):new Kx(p),f=n.runWebGLProgram(d,[h],"int32");return n.disposeData(h.dataId),f}};let Yx,Qx=Ct().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function Jx(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{shape:s}=r,o=n,i=nt(a.shape),u=ut(s,i),l=nt(u);Ze(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||jb(a.shape,u)||null!==c.texture&&jb(c.shape,u)?(o.incRef(a.dataId),{dataId:a.dataId,shape:u,dtype:a.dtype}):function(e,t,n){const r=[zb(e.shape),...Vb(e.shape)],a={dtype:e.dtype,shape:r,dataId:e.dataId},s=[zb(t),...Vb(t)],o=new Fx(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 Zx={kernelName:vr,backendName:"webgl",kernelFunc:Jx};function ew(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&&(Ze(-(o+1)<=a,(()=>`Axis must be in the interval [${-(o+1)}, ${o}]`)),u=o+a+1),i.splice(u,0,1),Jx({inputs:{x:s},backend:r,attrs:{shape:i}})}const tw={kernelName:En,backendName:"webgl",kernelFunc:ew};class nw{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 rw{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 aw={kernelName:Tr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:o,size:i}=r,[u,l]=i,c=Ct().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new rw(a.shape,u,l,s,o):new nw(a.shape,u,l,s,o);return n.runWebGLProgram(c,[a],"float32")}};function sw(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 ow={kernelName:Ln,backendName:"webgl",kernelFunc:sw};function iw(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=sw({inputs:{x:r},backend:n}),u=sw({inputs:{x:a},backend:n});return o.complexTensorInfos={real:i,imag:u},s}class uw{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=Tu(t,n),this.enableShapeUniforms=x_(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 lw{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=x_(a);let s="";if(r)if(0===a||1===nt(this.outputShape))s="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(s=`\n ${f_(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=Rx("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 `}}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=Ct().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&null!=t?new Wx(o.shape,t):new Lx(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 uw(e,u.shape,l.shape);return c.runWebGLProgram(o,[a,s],Ps(n.dtype,r.dtype))})),s=iw({inputs:{real:r,imag:a},backend:c});return c.disposeIntermediateTensorInfo(r),c.disposeIntermediateTensorInfo(a),s}const p=s||Ps(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?jf(e):e,r="string"===u.dtype?jf(t):t,[s,o]=a(u.shape,l.shape,n,r,p),i=c.makeTensorInfo(o,p);return c.texData.get(i.dataId).values=s,i}let h;return h=Ct().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&null!=t?new lw(t,u.shape,l.shape,n):new uw(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:sx,dtype:"bool"});function fw(e){const{inputs:t,backend:n}=e,{input:r}=t;return sw({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.real},backend:n})}const mw={kernelName:tn,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 sw({inputs:{x:s},backend:r});const t=kp(s.shape),n=e({inputs:{x:s},backend:r,attrs:{dtype:"float32"}}),a=iw({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(!dt(s.dtype,o)){const e=sw({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]=B_(e,s.shape,s.dtype,o);return r.makeTensorInfo(t,n,a)}if("int32"===o)return function(e,t){const n=new Lx(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",pt("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:vn,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=f_(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=f_(r),s=t.map((e=>e[0])).join(","),o=t.map(((t,n)=>t[0]+e[n])).join(","),i=Rx("rc",r),u=Rx("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===nt(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||gt(a),"string"===s){const e=ht(s,nt(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=Ct().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:gr,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=x_(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?Qe(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=x_(this.outputShape.length);const{dataFormat:n}=t,r=Zb(),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=x_(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=Ps(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=iw({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]=rx(r.shape,a.shape,e.values,t.values,s),u=n.makeTensorInfo(i,s);return n.texData.get(u.dataId).values=o,u}let o;return o=Ct().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new lw(Nw,r.shape,a.shape):new uw(Nw,r.shape,a.shape),n.runWebGLProgram(o,[r,a],s)}const Cw={kernelName:ur,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 * ${at(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=If(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=f_(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=f_(this.rank),a=Cx("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=Ct().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=lt(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=nt(h),m=Jx({inputs:{x:c},attrs:{shape:[nt(e.shape)/f,f]},backend:r}),g=Fw(m,Ps(e.dtype,"int32"),"sum",r),y=Jx({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=Nx(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=nt(m),b=nt(g),_=Tu(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([d,f]);Ze(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=Jx({inputs:{x:e},backend:a,attrs:{shape:x}}),k=Jx({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=Jx({inputs:{x:e},backend:a,attrs:{shape:[T,S,1]}}),I.push(o));const i=1===f?2:1;let u=t;s&&(u=Jx({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=Ps(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",cs(i,"float32"));c.push(e),I.push(e)}R=a.runWebGLProgram(l,c,u)}const M=Jx({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=Jx({inputs:{x:s},backend:r,attrs:{shape:e}}),m.push(s))}if(null!=a){const e=Uw(a.shape,d);null!=e&&(a=Jx({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&&rt(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]++,Ze(jb(l.shape,p.shape),(()=>`packed reshape ${l.shape} to ${p.shape} isn't free`));const d=Jx({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);Ze(y.isPacked,(()=>"batchMatMul result is expected to be packed")),l.shape=h,y.shape=n.outShape,f=sw({inputs:{x:g},backend:r}),f.shape=n.outShape,m.push(g)}else{const u=n.outHeight*n.outWidth,l=Jx({inputs:{x:e},backend:r,attrs:{shape:d?[n.batchSize,u,n.inChannels]:[n.batchSize,n.inChannels,u]}}),c=Jx({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=Jx({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=Jx({inputs:{x:s},backend:r,attrs:{shape:e}}),b.push(s))}if(null!=a){const e=Uw(a.shape,f);null!=e&&(a=Jx({inputs:{x:a},backend:r,attrs:{shape:e}}),b.push(a))}const _=Jx({inputs:{x:t},backend:r,attrs:{shape:[1,m,nt(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=Jx({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",cs(o,"float32"));A.push(e),b.push(e)}const C=r.runWebGLProgram(N,A,"float32"),R=Jx({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:sn,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&&Ct().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(Ct().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=Jx({inputs:{x:d},backend:n,attrs:{shape:h.outShape}});return n.disposeIntermediateTensorInfo(d),f}},Hw={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,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=Jx({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",cs(f,"float32"));e.push(t),b.push(t)}return e};if(1!==g.filterHeight||1!==g.filterWidth||1!==g.dilationHeight||1!==g.dilationWidth||1!==g.strideHeight||1!==g.strideWidth||"SAME"!==g.padInfo.type&&"VALID"!==g.padInfo.type)if(g.strideWidth<=2&&"channelsLast"===m&&Ct().getBool("WEBGL_EXP_CONV")){const e=d?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(Ct().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=Jx({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=x_(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=x_(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?Qe(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:ga,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]),Ze(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=Ct().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",cs(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:O_}),Yw={kernelName:Pt,backendName:"webgl",kernelFunc:Xw},Qw={kernelName:Vr,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,paddings:o}=r;Ze(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=Sf(c.shape,s,i,!1),h=Ef(p.length,s.length,!1),d=Nf(c.shape,s,i,!1),f=Jx({inputs:{x:c},backend:n,attrs:{shape:p}}),m=Lw({inputs:{x:f},backend:n,attrs:{perm:h}}),g=Jx({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:yn,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]),Ze(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=Ct().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=f_(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=f_(this.rank),n=Rx("coords",this.rank),r=Rx("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===nt(u))return n.makeTensorInfo(u,a.dtype,[]);if(n.shouldExecuteOnCPU([a])||"string"===a.dtype){const e=n.texData.get(a.dataId),t=mx(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=Ct().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,_t(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:Dr,backendName:"webgl",kernelFunc:nv},av={kernelName:Qt,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,crops:o}=r;Ze(a.shape.length<=4,(()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"));const i=s.reduce(((e,t)=>e*t)),u=Sf(a.shape,s,i),l=Ef(u.length,s.length),c=Nf(a.shape,s,i),p=Af(o,s.length),h=Cf(c,o,s.length),d=[],f=Jx({inputs:{x:a},backend:n,attrs:{shape:u}}),m=Lw({inputs:{x:f},backend:n,attrs:{perm:l}}),g=Jx({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:"if (isnan(x)) return x;\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:Er,backendName:"webgl",kernelFunc:sv};class iv{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const r=n.length,a=f_(n.length),s=f_(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:Jr,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=Jx({inputs:{x:a},backend:n,attrs:{shape:f}});else if(g||y){Ze(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=Jx({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=wx(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=Jx({inputs:{x:w},backend:n,attrs:{shape:f}});return n.disposeIntermediateTensorInfo(w),v}};class lv{constructor(e){this.outputShape=[],this.outputShape=bf(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=bf(e,t);const n=this.outputShape,r=n.length,a=f_(r),s=Rx("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 sw({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=iw({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=nt(e.shape.slice(t));return Jx({inputs:{x:e},backend:n,attrs:{shape:[-1,r]}})})),s=a.map((e=>({vals:n.readSync(e.dataId),shape:e.shape}))),o=bf(a.map((e=>e.shape)),1),i=1===a[0].shape[0],u=W_(s,o,r,i),l=bf(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=>nt(e.shape)>0)),o=Ct().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&s[0].shape.length>1;if(1===s.length){const t=o?new Lx(e[0].shape,Ux):new Wx(e[0].shape,Ux);return n.runWebGLProgram(t,e,r)}const i=Ct().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(s.length>i){const e=[];for(let r=0;r<s.length;r+=i){const a=s.slice(r,r+i);e.push(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=bf(e.map((e=>e.shape)),t),a=e.map((e=>Jx({inputs:{x:e},attrs:{shape:[-1,nt(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=Jx({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=lt(a,t[0].shape)[0];yf(t.map((e=>e.shape)),s);const o=bf(t.map((e=>e.shape)),s);if(0===nt(o))return n.makeTensorInfo(o,t[0].dtype,[]);const i=t.filter((e=>nt(e.shape)>0));return 1===i.length?sw({inputs:{x:i[0]},backend:n}):hv(i,s,n)}const fv={kernelName:an,backendName:"webgl",kernelFunc:dv},mv={kernelName:mr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return ew({inputs:{input:t[0]},backend:n,attrs:{dim:a}});const s=t[0].shape,o=t[0].dtype;t.forEach((e=>{et(s,e.shape,"All tensors passed to stack must have matching shapes"),Ze(o===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const i=[],u=dv({inputs:t.map((e=>{const t=ew({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=x_(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:on,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(Ct().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:"if (isnan(x)) return x;\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:wr,backendName:"webgl",kernelFunc:_v},wv=cw({opSnippet:"if (isnan(x)) return x;\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:dx}),vv={kernelName:Br,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:fn,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=f_(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=Rx("rc",n),a=`${r[n-1]} + 1 < ${this.outputShape[n-1]}`,s=`${r[n-2]} + 1 < ${this.outputShape[n-2]}`,o=f_(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:Nr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dims:s}=r,o=a.shape.length,i=lt(s,a.shape);if(0===o)return sw({inputs:{x:a},backend:n});const u=Ct().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:Tx}),Cv={kernelName:na,backendName:"webgl",kernelFunc:Av},Rv={kernelName:la,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=Jx({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,Ze(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=f_(i),l=Rx("coords",i);let c,p;if(1===s){p=i+1;const e=f_(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=Rx("sourceLocR",p-1).concat("inIdx.r"),g=Rx("sourceLocG",p-1).concat("inIdx.g"),y=Rx("sourceLocB",p-1).concat("inIdx.b"),b=Rx("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=If(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=If(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),!Ct().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){const n=[],s=e.texData.get(t.dataId);let o=t;null!==s&&s.isPacked&&(o=e.unpackTensor(t),n.push(o));const[i,u]=Sc(o.shape,a),l=nt(u),c=Jx({inputs:{x:o},backend:e,attrs:{shape:[-1,l]}});n.push(c);const p=$v(e,c,r);n.push(p);const h=Jx({inputs:{x:p},backend:e,attrs:{shape:i}});return n.forEach((t=>e.disposeIntermediateTensorInfo(t))),h}return Ov(e,t,r)}const Pv={kernelName:Wt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;let o=lt(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:rr,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=lt(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=Nx(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=nt(t),s=Jx({inputs:{x:e},attrs:{shape:[nt(e.shape)/a,a]},backend:r}),o=Fw(s,"float32","mean",r),i=Jx({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:"if (isnan(x)) return x;\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:V_,dtype:"float32"});const Uv={kernelName:Gr,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{dim:s}=r,o=lt([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=lt(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=Nx(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=ex(e,nt(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=nt(t),s=Jx({inputs:{x:e},attrs:{shape:[nt(e.shape)/a,a]},backend:r}),o=Fw(s,e.dtype,"max",r),i=Jx({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=Jx({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=Jx({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:rn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{clipValueMin:s,clipValueMax:o}=r;let i;i=Ct().getBool("WEBGL_PACK_CLIP")?new 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:qt,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&&Ze("complex64"!==e.dtype,(()=>"avgPool does not support complex64 tensors in the WebGL backend."))}))}(a);const{filterSize:s,strides:o,pad:i,dimRoundingMode:u}=r;Ze(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&&rt(l.inShape,l.outShape))return sw({inputs:{x:a},backend:n});const c=new Hv(l,"avg",!1);return n.runWebGLProgram(c,[a],"float32")}},jv={kernelName:Yt,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:fa,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})}};ka(Dy),ka(Py),ka(Tg),ka(Uy),ka(Wy),ka(Vy),ka(Qy),ka(eb),ka(Rg),ka(tb),ka(Zy),ka(nb),ka(ty),ka(Xy),ka(rb),ka(ib),ka(ub),ka(Ky),ka(fy),ka(wg),ka(lb),ka(cb),ka(sb),ka(Cy),ka(pb),ka(hb),ka(fb),ka(yy),ka(mb),ka(yb),ka(_b),ka(xb),ka(Xx),ka(Zx),ka(tw),ka(aw),ka(mw),ka(yw),ka(vw),ka(Vw),ka(Hw),ka(Kw),ka(Yw),ka(Qw),ka(Jw),ka(av),ka(Cw),ka(ov),ka(uv),ka(mv),ka(bv),ka(xv),ka(vv),ka(ow),ka(Iv),ka(Ev),ka(fv),ka(Cv),ka(Rv),ka(Pv),ka(Lv),ka(rv),ka(Uv),ka(Vv),ka(Gv),ka(jv),ka(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(X((function(e){return a.apply(void 0,e)})))}return Yv(e,null)}function Yv(e,t){return new E((function(n){var r=e.length;if(0!==r)for(var a=new Array(r),s=0,o=0,i=function(i){var u=K(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!==we&&we||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=X((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}(E),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)}(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);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.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(){return 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=function(){return 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,n=e.length;t<n;++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 zI(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return VI(e).length;default:if(r)return zI(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 HI(zI(t,e.length-n),e,n,r)}function kI(e,t,n,r){return HI(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 HI(VI(t),e,n,r)}function SI(e,t,n,r){return HI(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===we.TYPED_ARRAY_SUPPORT||we.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||GI(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&GI(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,a=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>a)&&(n=a);for(var s="",o=t;o<n;++o)s+=(r=e[o])<16?"0"+r.toString(16):r.toString(16);return s}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:zI(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,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 VI(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 HI(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 GI(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function jI(e,t){var n=new le(0),r=new le(0),a=new le(0),s=new le(0),o=H([n,r,a,s]).pipe(X((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(ce(2))}(e,n).pipe(de((function(e){return KI(e.response)})),de((function(e){return qI(e,t,r).pipe(X((function(t){return{jszip:e,config:t}})))})),de((function(e){var t=e.jszip,n=e.config;return XI(t,n,a).pipe(X((function(e){return{jszip:t,config:n,jsonModel:e}})))})),de((function(e){var t=e.jszip,n=e.config,r=e.jsonModel;return YI(t,r,s).pipe(X((function(e){return{config:n,jsonModel:r,weights:e}})))})),de((function(e){var t=e.config,n=e.jsonModel,r=e.weights;return K(dg(new Xk(n,r))).pipe(X((function(e){return{config:t,graphModel:e}})))})));return{model$:i,progress$:o}}return i=KI(e).pipe(de((function(e){return qI(e,t,r).pipe(X((function(t){return{jszip:e,config:t}})))})),de((function(e){var t=e.jszip,n=e.config;return XI(t,n,a).pipe(X((function(e){return{jszip:t,config:n,jsonModel:e}})))})),de((function(e){var t=e.jszip,n=e.config,r=e.jsonModel;return YI(t,r,s).pipe(X((function(e){return{config:n,jsonModel:r,weights:e}})))})),de((function(e){var t=e.config,n=e.jsonModel,r=e.weights;return K(dg(new Xk(n,r))).pipe(X((function(e){return{config:t,graphModel:e}})))}))),{model$:i,progress$:o}}function KI(e){return q(Kk(new Uint8Array(e)))}function qI(e,t,n){return e[t]||(t=t.substring(0,t.lastIndexOf("."))+".json",e[t])?xe((function(){return n.next(1),t.includes(".bin")?q(JSON.parse(Vk(qk(e[t])))):q(JSON.parse(Vk(e[t])))})):Z("Unable to retrieve model config: ".concat(t," is missing"))}function XI(e,t,n){return t?e[t.filename]?xe((function(){return n.next(1),q(JSON.parse(Vk(qk(e[t.filename]))))})):Z("Error extracting model: ".concat(t.filename," is missing")):Z("Invalid model config")}function YI(e,t,n){if(!t)return Z("Unable to extract weights: model is undefined");if(!t.weightsManifest)return n.next(1),q({});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:Z("Error extracting weight: ".concat(t," is missing"))};u[t]=xe((function(){var a=e[t];return i[l]=1,n.next(i.reduce((function(e,t){return e+t}),0)/r),q(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)}Mt.set("DEPRECATION_WARNINGS_ENABLED",!1),Mt.global.Math=Math,Mt.global.Float32Array=Float32Array,Ct().set("WEBGL_FORCE_F16_TEXTURES",!0);var QI,JI,ZI,eT=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=jI(this._config.filename,"config.json"),o=a.model$,i=a.progress$,u=i.pipe(X((function(e){return r&&r(e)}))).subscribe(),[4,o.pipe(X((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})),te((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=pf.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=$h(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}(),tT=(QI="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),QI&&(o=QI),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|0;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==(365&this.mode)},set:function(e){e?this.mode|=365:this.mode&=-366}},write:{get:function(){return 146==(146&this.mode)},set:function(e){e?this.mode|=146:this.mode&=-147}}}),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[a++>>0]=r.charCodeAt(s);h[a>>0]=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(0==(2097155&u.flags))throw new ue(8);if(16384==(61440&u.node.mode))throw new ue(31);if(!u.i.write)throw new ue(28);u.seekable&&1024&u.flags&&Ne(u,0,2);var f=void 0!==p;if(f){if(!u.seekable)throw new ue(70)}else p=u.position;var m=u.i.write(u,d,l,c,p,void 0);f||(u.position+=m);var y=m;if(0>y){var b=-1;break e}t+=y}b=t}return g[r>>2]=b,0}catch(e){if(void 0===Re||!(e instanceof ue))throw e;return e.C}},strftime_l:function(e,t,n,r){return function(e,t,n,r){function a(e,t,n){for(e="number"==typeof e?e.toString():e||"";e.length<t;)e=n[0]+e;return e}function s(e,t){return a(e,t,"0")}function o(e,t){function n(e){return 0>e?-1:0<e?1:0}var r;return 0===(r=n(e.getFullYear()-t.getFullYear()))&&0===(r=n(e.getMonth()-t.getMonth()))&&(r=n(e.getDate()-t.getDate())),r}function i(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function u(e){var t=e.G;for(e=new Date(new Date(e.H+1900,0,1).getTime());0<t;){var n=e.getMonth(),r=(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[e>>0]=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[e>>0];case"i16":return f[e>>1];case"i32":case"i64":return m[e>>2];case"float":return y[e>>2];case"double":return b[e>>3];case"*":return g[e>>2];default:$("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 nT;!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"}(JI||(JI={})),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"}(ZI||(ZI={}));const rT={kernelName:fa,backendName:"wasm",setupFunc:function(e){nT=e.wasm.cwrap(fa,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=ZI[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 nT(h,v,a.shape.length,d,k,s.shape.length,u,l,g,f,m,p||0,w),x}};function aT(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===nt(o.shape)||n(s,JI[a.dtype],i),o}}}const sT=aT("Abs"),oT=aT(Ot),iT=aT(Dt);function uT(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===nt(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,JI[s.dtype],f),p}}}const lT=uT(Pt);let cT;const pT={kernelName:Lt,backendName:"wasm",setupFunc:function(e){cT=e.wasm.cwrap(Lt,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===nt(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 cT(s,a.length,JI[r.dtype],o),r}};function hT(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 dT={kernelName:Ln,backendName:"wasm",kernelFunc:hT};let fT;function mT(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=hT({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 fT(c,d,u.shape.length,JI[u.dtype],p,h,s.length),l}const gT={kernelName:ia,backendName:"wasm",kernelFunc:mT,setupFunc:function(e){fT=e.wasm.cwrap(ia,null,["number","array","number","number","number","array","number"])}};function yT(e,t,n){const r=e.shape,a=e.shape.length,s=lt(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=mT({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 bT;const _T={kernelName:Bt,backendName:"wasm",setupFunc:function(e){bT=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}=yT(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=nt(f),g=t.makeOutput(d,o.dtype);if(0!==nt(u.shape)){const e=t.dataIdMap.get(g.dataId).id;bT(i,m,e)}if(h&&t.disposeData(l.dataId),s){const e=Ec(g.shape,p);g.shape=e}return g}};let xT;const wT={kernelName:Ut,backendName:"wasm",setupFunc:function(e){xT=e.wasm.cwrap(Ut,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}=yT(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=nt(f),g=t.makeOutput(d,o.dtype);if(0!==nt(u.shape)){const e=t.dataIdMap.get(g.dataId).id;xT(i,m,e)}if(h&&t.disposeData(l.dataId),s){const e=Ec(g.shape,p);g.shape=e}return g}};function vT(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}=yT(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=nt(f.shape),y=l.shape[p[0]];return t(u,JI[l.dtype],g,y,m),h&&n.disposeData(c.dataId),f}}}const kT=vT(Wt),IT=vT(zt),TT=aT(Vt),ST=aT(Ht),ET=aT(Gt),NT=uT(Kt),AT=aT(jt);let CT;const RT={kernelName:qt,backendName:"wasm",setupFunc:function(e){CT=e.wasm.cwrap(qt,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 CT(s,a.shape[0],a.shape[1],a.shape[2],p,h,d,f,m,g,y,b,_,w),x}};let MT;const FT={kernelName:Xt,backendName:"wasm",setupFunc:function(e){MT=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 MT(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 $T;const OT={kernelName:"AvgPool3DGrad",backendName:"wasm",setupFunc:function(e){$T=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 $T(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 DT;const PT={kernelName:"AvgPoolGrad",backendName:"wasm",setupFunc:function(e){DT=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 DT(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 LT(e){const{inputs:t,attrs:n}=e,{x:r}=t,{shape:a}=n,s=nt(r.shape),o=ut(a,s);return Ze(s===nt(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 BT={kernelName:vr,backendName:"wasm",kernelFunc:LT};let UT;const WT={kernelName:Yt,backendName:"wasm",setupFunc:function(e){UT=e.wasm.cwrap(Yt,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=nt(f),y=nt(m),b=Tu(a.shape.slice(0,-2),s.shape.slice(0,-2)).concat([h,d]);Ze(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=LT({inputs:{x:a},backend:n,attrs:{shape:o?[g,c,h]:[g,h,c]}}),w=LT({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 UT(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 zT(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=_t(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+nt(o)):a.typedArrayFromHeap(l).set(u.subarray(e,e+nt(o))),l}if("string"===t.dtype){const e=my(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=my(u,s,o,t.shape,t.dtype);h.set(e)}return l}const VT={kernelName:Dr,backendName:"wasm",kernelFunc:zT},HT={kernelName:Qt,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=Sf(a.shape,s,i),l=Ef(u.length,s.length),c=Nf(a.shape,s,i),p=Af(o,s.length),h=Cf(c,o,s.length),d=LT({inputs:{x:a},backend:n,attrs:{shape:u}}),f=mT({inputs:{x:d},backend:n,attrs:{perm:l}}),m=LT({inputs:{x:f},backend:n,attrs:{shape:c}}),g=zT({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 GT;const jT={kernelName:Jt,backendName:"wasm",setupFunc:function(e){GT=e.wasm.cwrap(Jt,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 GT(c(a),o,i,c(s),JI[s.dtype],c(l)),l}},KT=uT(Zt),qT={kernelName:en,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 XT(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 YT={kernelName:tn,backendName:"wasm",kernelFunc:XT},QT=aT(nn);let JT;const ZT={kernelName:rn,backendName:"wasm",setupFunc:function(e){JT=e.wasm.cwrap(rn,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 JT(i,s,o,l),u}};function eS(e){const{inputs:t,backend:n}=e,r=lt(e.attrs.axis,t[0].shape)[0];yf(t.map((e=>e.shape)),r);let a=bf(t.map((e=>e.shape)),r);const s=t.filter((e=>nt(e.shape)>0));if(1===s.length)return hT({inputs:{x:s[0]},backend:n});const o=n.makeOutput(a,t[0].dtype);if(0===nt(a))return o;if("string"===s[0].dtype){const e=s.map((e=>{const t=nt(e.shape.slice(r));return LT({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),i=e.map((e=>({vals:n.readSync(e.dataId),shape:e.shape})));a=bf(e.map((e=>e.shape)),1);const u=1===e[0].shape[0],l=Pg(i,a,t[0].dtype,u),c=bf(s.map((e=>e.shape)),r);return o.shape=c,n.dataIdMap.get(o.dataId).stringBytes=Kf(l),e.forEach((e=>n.disposeData(e.dataId))),o}const i=nt(s[0].shape.slice(0,r));let u=0;const l=s.map((e=>{const t=nt(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 tS={kernelName:an,backendName:"wasm",kernelFunc:eS};let nS;const rS={kernelName:sn,backendName:"wasm",setupFunc:function(e){nS=e.wasm.cwrap(sn,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 nS(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 aS;const sS={kernelName:on,backendName:"wasm",setupFunc:function(e){aS=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","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=_t(h.inShape),N=_t(a.shape),[A,C,R]=_t(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 aS(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 oS;const iS={kernelName:un,backendName:"wasm",setupFunc:function(e){oS=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,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 oS(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 uS;const lS={kernelName:ln,backendName:"wasm",setupFunc:function(e){uS=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,{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 uS(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 cS;const pS={kernelName:cn,backendName:"wasm",setupFunc:function(e){cS=e.wasm.cwrap(cn,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 cS(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}},hS=aT("Cos"),dS=aT(pn);var fS;let mS;!function(e){e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest"}(fS||(fS={}));const gS={kernelName:fn,backendName:"wasm",setupFunc:function(e){mS=e.wasm.cwrap(fn,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=XT({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 mS(g,y,b,c,w,p,h,fS[a],s,x),null!=f&&t.disposeData(f.dataId),_}};let yS;const bS={kernelName:hn,backendName:"wasm",setupFunc:function(e){yS=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;Ze("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=mT({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;yS(f,o?1:0,i?1:0,d,m,JI[a.dtype]);let g=h;return null!==l&&(g=mT({inputs:{x:h},attrs:{perm:Cc(l)},backend:n}),n.disposeData(c.dataId),n.disposeData(h.dataId)),g}};let _S;const xS={kernelName:dn,backendName:"wasm",setupFunc:function(e){_S=e.wasm.cwrap(dn,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;Ze("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=mT({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;_S(f,o?1:0,i?1:0,d,m,JI[a.dtype]);let g=h;return null!==l&&(g=mT({inputs:{x:h},attrs:{perm:Cc(l)},backend:n}),n.disposeData(c.dataId),n.disposeData(h.dataId)),g}};let wS;const vS={kernelName:mn,backendName:"wasm",setupFunc:function(e){wS=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 wS(p(a),new Uint8Array(new Int32Array(a.shape).buffer),a.shape.length,o,u,p(s),JI[s.dtype],i,p(c)),c}};let kS;const IS={kernelName:gn,backendName:"wasm",setupFunc:function(e){kS=e.wasm.cwrap(gn,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(_t(a.shape)).buffer),m=new Uint8Array(new Int32Array(p).buffer),g=new Uint8Array(new Int32Array(_t(p)).buffer),y=t.dataIdMap.get(h.dataId).id;return kS(d,s,"NHWC"===o?1:0,f,a.shape.length-1,m,g,p.length,y),h}};let TS;const SS={kernelName:yn,backendName:"wasm",setupFunc:function(e){TS=e.wasm.cwrap(yn,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 TS(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 ES;const NS={kernelName:bn,backendName:"wasm",setupFunc:function(e){ES=e.wasm.cwrap("Diag",null,["number","number","number","number"])},kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,a=nt(r.shape),s=n.makeOutput([...r.shape,...r.shape],r.dtype);return ES(n.dataIdMap.get(r.dataId).id,JI[r.dtype],a,n.dataIdMap.get(s.dataId).id),s}};let AS;const CS={kernelName:_n,backendName:"wasm",setupFunc:function(e){AS=e.wasm.cwrap(_n,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 AS(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(c.dataId).id,JI[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 RS;const MS={kernelName:wn,backendName:"wasm",setupFunc:function(e){RS=e.wasm.cwrap(wn,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 RS(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(o.dataId).id,n.dataIdMap.get(p.dataId).id,JI[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 FS;const $S={kernelName:xn,backendName:"wasm",setupFunc:function(e){FS=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(`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 FS(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(s.dataId).id,n.dataIdMap.get(o.dataId).id,n.dataIdMap.get(p.dataId).id,JI[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}},OS=aT(kn);let DS;const PS={kernelName:In,backendName:"wasm",setupFunc:function(e){DS=e.wasm.cwrap(In,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 DS(o(a),o(r),o(s)),s}},LS=uT(Tn,0,"bool"),BS=aT("Erf"),US=aT(Sn,"float32");function WS(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&&(Ze(-(o+1)<=s,(()=>`Axis must be in the interval [${-(o+1)}, ${o}]`)),u=o+s+1),i.splice(u,0,1),LT({inputs:{x:a},backend:r,attrs:{shape:i}})}const zS={kernelName:En,backendName:"wasm",kernelFunc:WS},VS=aT(Nn,"float32");function HS(e){const{attrs:{shape:t,value:n},backend:r}=e;let{attrs:{dtype:a}}=e;a=a||gt(n);const s=r.makeOutput(t,a);return r.typedArrayFromHeap(s).fill(n),s}const GS={kernelName:An,backendName:"wasm",kernelFunc:HS};let jS;const KS={kernelName:Cn,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 jS(s,i,u,l,c,o),a},setupFunc:function(e){jS=e.wasm.cwrap(Cn,null,["number","number","number","number","number","number"])}},qS=aT(Rn),XS=uT(Mn);let YS;const QS={kernelName:Fn,backendName:"wasm",setupFunc:function(e){YS=e.wasm.cwrap(Fn,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===nt(s.shape))return m;const g=t.dataIdMap.get(m.dataId).id;return YS(c,p,h,d,f,a,g),m}};let JS;const ZS={kernelName:ma,backendName:"wasm",setupFunc:function(e){JS=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),g=ZI[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 JS(y,F,$,O,b,w,v,x,k,I,T,S,M,E,N,A,C,R,_,g,L,f||0,P),D}};let eE;const tE={kernelName:ga,backendName:"wasm",setupFunc:function(e){eE=e.wasm.cwrap(ga,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=ZI[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 eE(y,F,$,O,b,w,v,x,k,I,T,S,M,E,N,A,C,R,_,g,L,f||0,P),D}};let nE;const rE={kernelName:On,backendName:"wasm",setupFunc:function(e){nE=e.wasm.cwrap(On,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 nE(h,JI[r.dtype],d,o,p,i,f,m),l}};let aE;const sE={kernelName:$n,backendName:"wasm",setupFunc:function(e){aE=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=lt(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];Ze(t<=c-1&&t>=0,(()=>`GatherV2: the index value ${t} is not in [0, ${c-1}]`))}const p=Hf(a,s,u,i),h=LT({inputs:{x:a},attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]},backend:t}),d=nt(s.shape),f=LT({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===nt(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(_t(h.shape)).buffer),v=new Uint8Array(new Int32Array(_t(m)).buffer);return aE(b,JI[a.dtype],w,y,_,p.batchSize,v,x),t.disposeData(h.dataId),t.disposeData(f.dataId),g.shape=p.outputShape,g}},oE=uT(Dn,0,"bool"),iE=uT(Pn,0,"bool"),uE=aT(Bn,"bool"),lE=aT(Un,"bool"),cE=aT(Wn,"bool");let pE;const hE={kernelName:zn,backendName:"wasm",setupFunc:function(e){pE=e.wasm.cwrap(zn,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!==nt(t.shape)){const e=r.dataIdMap.get(s.dataId).id;pE(a,JI[t.dtype],n,e)}return s}},dE=uT(Vn,0,"bool"),fE=uT(Hn,0,"bool");let mE;const gE={kernelName:Gn,backendName:"wasm",setupFunc:function(e){mE=e.wasm.cwrap(Gn,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 mE(n.dataIdMap.get(i.dataId).id,r,a,o),i}},yE=aT("Log"),bE=aT(jn),_E=uT(Kn,0,"bool"),xE=aT(qn),wE=uT(Xn,0,"bool"),vE=uT("LogicalXor",0,"bool");let kE;const IE={kernelName:Yn,backendName:"wasm",setupFunc:function(e){kE=e.wasm.cwrap(Yn,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 kE(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(l.dataId).id,a.shape[3],s,o,i,u),l}};let TE;const SE={kernelName:Qn,backendName:"wasm",setupFunc:function(e){TE=e.wasm.cwrap(Qn,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 TE(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 EE;const NE={kernelName:Jn,backendName:"wasm",setupFunc:function(e){EE=e.wasm.cwrap(Jn,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}=yT(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=nt(f),g=t.makeOutput(d,o.dtype);if(0!==nt(u.shape)){const e=t.dataIdMap.get(g.dataId).id;EE(i,JI[o.dtype],m,e)}if(h&&t.disposeData(l.dataId),s){const e=Ec(g.shape,p);g.shape=e}return g}},AE=uT(Zn);let CE;const RE={kernelName:er,backendName:"wasm",setupFunc:function(e){CE=e.wasm.cwrap(er,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;Ze("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 CE(s,a.shape[0],a.shape[1],a.shape[2],p,h,d,f,m,g,y,b,_,x,w,v,I),k}};let ME;const FE={kernelName:tr,backendName:"wasm",setupFunc:function(e){ME=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 ME(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 $E;const OE={kernelName:"MaxPool3DGrad",backendName:"wasm",setupFunc:function(e){$E=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 $E(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 DE;const PE={kernelName:"MaxPoolGrad",backendName:"wasm",setupFunc:function(e){DE=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 DE(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 LE;const BE={kernelName:nr,backendName:"wasm",setupFunc:function(e){LE=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;Ze(4===a.shape.length,(()=>`Error in maxPool: input must be rank 4 but got rank ${a.shape.length}.`));const l=[1,1];Ze(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 LE(n.dataIdMap.get(a.dataId).id,n.dataIdMap.get(p.dataId).id,n.dataIdMap.get(h.dataId).id,JI[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 UE;const WE={kernelName:rr,backendName:"wasm",setupFunc:function(e){UE=e.wasm.cwrap(rr,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}=yT(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=nt(g);let b=l;"float32"!==l.dtype&&(b=XT({backend:t,inputs:{x:l},attrs:{dtype:"float32"}}),u=t.dataIdMap.get(b.dataId).id);const _=t.makeOutput(m,"float32");if(0!==nt(l.shape)){const e=t.dataIdMap.get(_.dataId).id;UE(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 zE;const VE={kernelName:ar,backendName:"wasm",setupFunc:function(e){zE=e.wasm.cwrap(ar,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}=yT(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=nt(m),y=t.makeOutput(f,l.dtype);if(0!==nt(l.shape)){const e=t.dataIdMap.get(y.dataId).id;zE(u,JI[o.dtype],g,e)}if(d&&t.disposeData(c.dataId),s){const e=Ec(y.shape,h);y.shape=e}return y}},HE=uT(sr);var GE;let jE;!function(e){e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric"}(GE||(GE={}));const KE={kernelName:or,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 jE(o,l,t.shape.length,JI[t.dtype],h,d,GE[a],u),i},setupFunc:function(e){jE=e.wasm.cwrap(or,null,["number","array","number","number","array","array","number","number"])}};let qE;function XE(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=nt(n.shape)/i;return 0===nt(s.shape)||qE(a,o,i,u),s}const YE={kernelName:Gr,backendName:"wasm",setupFunc:function(e){qE=e.wasm.cwrap(Gr,null,["number","number","number","number"])},kernelFunc:XE};let QE;const JE={kernelName:ir,backendName:"wasm",setupFunc:function(e){QE=e.wasm.cwrap(ir,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:XE({inputs:{logits:a},backend:n,attrs:{dim:a.shape.length-1}}),[l,c]=u.shape,p=n.makeOutput([l,s],"int32");return QE(n.dataIdMap.get(u.dataId).id,l,c,s,o,n.dataIdMap.get(p.dataId).id),i||n.disposeData(u.dataId),p}},ZE=uT("Mod"),eN=uT(ur),tN=aT("Neg");function nN(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 rN;const aN={kernelName:cr,backendName:"wasm",setupFunc:function(e){rN=e.wasm.cwrap(cr,"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=rN(l,c,s,a,o),{pSelectedIndices:h,selectedSize:d,pSelectedScores:f,pValidOutputs:m}=nN(t,p);return t.wasm._free(f),t.wasm._free(m),t.makeOutput([d],"int32",h)}};let sN;const oN={kernelName:pr,backendName:"wasm",setupFunc:function(e){sN=e.wasm.cwrap(pr,"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=sN(c,p,s,a,o,i),{pSelectedIndices:d,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=nN(t,h);return t.wasm._free(m),[t.makeOutput([f],"int32",d),t.makeOutput([],"int32",g)]}};let iN;const uN={kernelName:hr,backendName:"wasm",setupFunc:function(e){iN=e.wasm.cwrap(hr,"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=iN(c,p,s,a,o,i),{pSelectedIndices:d,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=nN(t,h);return t.wasm._free(g),[t.makeOutput([f],"int32",d),t.makeOutput([f],"float32",m)]}},lN=uT(lr,0,"bool");let cN;const pN={kernelName:fr,backendName:"wasm",setupFunc:function(e){cN=e.wasm.cwrap(fr,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 cN(p,o,i,u,c),l}},hN={kernelName:dr,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}},dN={kernelName:mr,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return WS({inputs:{input:t[0]},backend:n,attrs:{dim:a}});const s=t[0].shape,o=t[0].dtype;t.forEach((e=>{et(s,e.shape,"All tensors passed to stack must have matching shapes"),Ze(o===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const i=[],u=eS({inputs:t.map((e=>{const t=WS({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 fN;const mN={kernelName:gr,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===nt(t.shape))return HS({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 fN(o,l,t.shape.length,JI[t.dtype],h,d,a,u),i},setupFunc:function(e){fN=e.wasm.cwrap(gr,null,["number","array","number","number","array","array","number","number"])}},gN=uT("Pow");let yN;const bN={kernelName:yr,backendName:"wasm",setupFunc:function(e){yN=e.wasm.cwrap(yr,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=XT({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 yN(i,o,p),"float32"!==u.dtype&&n.disposeData(l.dataId),c}};let _N;const xN={kernelName:br,backendName:"wasm",setupFunc:function(e){_N=e.wasm.cwrap(br,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}=yT(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=nt(g),b=t.makeOutput(m,l.dtype);if(0!==nt(l.shape)){const e=t.dataIdMap.get(b.dataId).id;_N(u,y,JI[b.dtype],e)}if(d&&t.disposeData(c.dataId),s){const e=Ec(b.shape,h);b.shape=e}return b}},wN={kernelName:_r,backendName:"wasm",kernelFunc:e=>{const{backend:t,attrs:n}=e,{start:r,stop:a,step:s,dtype:o}=n,i=cy(r,a,s,o),u=t.makeOutput([i.length],o);return t.typedArrayFromHeap(u).set(i),u}},vN=uT(vn),kN=aT(xr),IN=aT(wr),TN=aT(Er);let SN;const EN={kernelName:Tr,backendName:"wasm",setupFunc:function(e){SN=e.wasm.cwrap(Tr,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=XT({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===nt(a.shape))return b;const _=t.dataIdMap.get(b.dataId).id;return SN(y,c,p,h,d,u,l,s?1:0,o?1:0,_),null!=m&&t.disposeData(m.dataId),b}};let NN;const AN={kernelName:Sr,backendName:"wasm",setupFunc:function(e){NN=e.wasm.cwrap(Sr,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=XT({backend:n,inputs:{x:a},attrs:{dtype:"float32"}}),l=n.dataIdMap.get(u.dataId)),NN(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 CN;const RN={kernelName:kr,backendName:"wasm",setupFunc:function(e){CN=e.wasm.cwrap(kr,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===nt(a.shape))return m;let g,y=t.dataIdMap.get(a.dataId);"float32"!==y.dtype&&(g=XT({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 CN(b,c,p,h,d,u,l,s?1:0,o?1:0,_),null!=g&&t.disposeData(g.dataId),m}};let MN;const FN={kernelName:Ir,backendName:"wasm",setupFunc:function(e){MN=e.wasm.cwrap(Ir,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=XT({backend:n,inputs:{x:a},attrs:{dtype:"float32"}}),l=n.dataIdMap.get(u.dataId)),MN(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 $N;const ON={kernelName:Nr,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dims:s}=r,o=lt(s,a.shape);if(0===a.shape.length)return hT({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);$N(u,c,o.length,p,a.shape.length,l);const h=LT({inputs:{x:i},attrs:{shape:a.shape},backend:n});return n.disposeData(i.dataId),h},setupFunc:function(e){$N=e.wasm.cwrap(Nr,null,["number","array","number","array","number","number"])}};let DN;const PN={kernelName:da,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]=Tf(i,h,d),y="number"==typeof o?[o,o,o,0===o?0:255]:[...o,255],b=new Uint8Array(new Int32Array(y).buffer);return DN(l,p,h,d,f,s,m,g,b,y.length,c),u},setupFunc:function(e){DN=e.wasm.cwrap(da,null,["number","number","number","number","number","number","number","number","array","number","number"])}},LN=aT(Ar),BN=aT(Cr);let UN;const WN={kernelName:Rr,backendName:"wasm",setupFunc:function(e){UN=e.wasm.cwrap(Rr,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===nt(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 UN(d,f,JI[s.dtype],u,l,c,m,h,g),i}};let zN;const VN={kernelName:Fr,backendName:"wasm",setupFunc:function(e){zN=e.wasm.cwrap(Fr,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 zN(u(a),u(s),a.shape[0],a.shape[1],s.shape[1],JI[a.dtype],"left"===o,u(i)),i}};let HN;const GN={kernelName:$r,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:nt(a.shape.slice(1));return HN(o,i,u,d,c),l},setupFunc:function(e){HN=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}},jN=aT(Or);let KN;const qN={kernelName:"Sigmoid",backendName:"wasm",setupFunc:function(e){KN=e.wasm.cwrap(Br,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===nt(a.shape)||KN(r,s),a}},XN=aT(Lr),YN=aT("Sin"),QN=aT(Pr),JN=aT(Ur),ZN={kernelName:Vr,backendName:"wasm",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,paddings:o}=r,i=nt(s),u=[[0,0]];u.push(...o);for(let e=1+s.length;e<a.shape.length;++e)u.push([0,0]);const l=mN.kernelFunc({inputs:{x:a},backend:n,attrs:{paddings:u,constantValue:0}}),c=Sf(l.shape,s,i,!1),p=Ef(c.length,s.length,!1),h=Nf(l.shape,s,i,!1),d=LT({inputs:{x:l},backend:n,attrs:{shape:c}}),f=mT({inputs:{x:d},backend:n,attrs:{perm:p}}),m=LT({inputs:{x:f},backend:n,attrs:{shape:h}});return n.disposeData(l.dataId),n.disposeData(d.dataId),n.disposeData(f.dataId),m}};let eA;const tA={kernelName:jr,backendName:"wasm",setupFunc:function(e){eA=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=eA(p,h,JI[a.dtype],i,l,u,d,m,y,_,w,k),T=t.readSync(v.dataId);let S;switch(T[0]){case 1:S=Of(T[1]);break;case 2:S=Df(T[1],T[2]);break;case 3:S=Pf(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=zT({inputs:{x:f},attrs:{begin:0,size:[I,u]},backend:t}),N=zT({inputs:{x:g},attrs:{begin:0,size:I},backend:t}),t.disposeData(f.dataId),t.disposeData(g.dataId)),[E,N,b,x]}};let nA;const rA={kernelName:Kr,backendName:"wasm",setupFunc:function(e){nA=e.wasm.cwrap(Kr,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=nt(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;nA(o,i,u,l,h,f,g);const y=t.readSync(m.dataId);let b;switch(y[0]){case 0:b=Lf(y[1],y[2]);break;case 1:b=Bf(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=Uf(Array.from(t.readSync(a.dataId)),Array.from(t.readSync(d.dataId)));break;case 4:b=Wf(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 aA;function sA(e){aA=e.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function oA(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;aA(p,JI[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:_=zf(b[1],b[2]);break;case 3:_=Vf(b[1],b[2],b[3]);break;default:_=""}if(n.disposeData(g.dataId),_)throw n.disposeData(f.dataId),new Error(_);return f}const iA={kernelName:qr,backendName:"wasm",setupFunc:sA,kernelFunc:function(e){return oA(e,!0)}},uA={kernelName:Xr,backendName:"wasm",setupFunc:sA,kernelFunc:function(e){return oA(e,!1)}};let lA;const cA={kernelName:Yr,backendName:"wasm",setupFunc:function(e){lA=e.wasm.cwrap(Yr,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===nt(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 lA(f,m,s.shape.length,g,JI[o.dtype],l,c,p,y,d,b),u}},pA={kernelName:Hr,backendName:"wasm",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{x:a}=t,{numOrSizeSplits:s,axis:o}=n,i=lt(o,a.shape)[0],u=$f(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=zT({inputs:{x:a},attrs:{begin:l,size:t},backend:r});return l[i]+=e,n}))}},hA=aT(Wr),dA=aT("Square"),fA=uT(Qr);let mA;const gA={kernelName:pa,backendName:"wasm",setupFunc:function(e){mA=e.wasm.cwrap(pa,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 mA(o,a,JI[s.dtype],u),i}};let yA;const bA={kernelName:Jr,backendName:"wasm",setupFunc:function(e){yA=e.wasm.cwrap(Jr,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=LT({inputs:{x:a},backend:t,attrs:{shape:f}});else if(g||y){Ze(a.shape.length>=1,(()=>`Input must have rank at least 1, got: ${a.shape.length}`));const e=$u(b,_,x),n=zT({inputs:{x:a},backend:t,attrs:{begin:b,size:e}});w=LT({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(_t(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(_t(d)).buffer),c=t.dataIdMap.get(e.dataId).id;yA(n,r,a.shape.length,s,o,i,u,l,d.length,c),w=LT({inputs:{x:e},backend:t,attrs:{shape:f}}),t.disposeData(e.dataId)}return w}},_A={kernelName:Zr,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]=ky(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]}},xA={kernelName:ea,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]=Ty(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]}},wA={kernelName:ta,backendName:"wasm",kernelFunc:function(e){const{backend:t,inputs:n,attrs:r}=e,{input:a}=n,{numBuckets:s}=r,o=Sy(t.readSync(a.dataId),s),i=t.makeOutput(a.shape,"int32");return t.typedArrayFromHeap(i).set(o),i}},vA=uT(na);let kA;const IA={kernelName:zr,backendName:"wasm",setupFunc:function(e){kA=e.wasm.cwrap(zr,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}=yT(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=nt(g),b=t.makeOutput(m,l.dtype);if(0!==nt(l.shape)){const e=t.dataIdMap.get(b.dataId).id;kA(u,y,JI[b.dtype],e)}if(d&&t.disposeData(c.dataId),s){const e=Ec(b.shape,h);b.shape=e}return b}},TA=aT("Tan"),SA=aT(ra);let EA;const NA={kernelName:Mr,backendName:"wasm",setupFunc:function(e){EA=e.wasm.cwrap(Mr,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===nt(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 EA(d,f,JI[o.dtype],u,l,c,g,h,y,m),i}};let AA;const CA={kernelName:aa,backendName:"wasm",setupFunc:function(e){AA=e.wasm.cwrap(aa,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 AA(s,u,a.shape.length,l,i.length,JI[c.dtype],p),c}};let RA;const MA={kernelName:sa,backendName:"wasm",setupFunc:function(e){RA=e.wasm.cwrap(sa,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 RA(o,i,r.shape.length,JI[r.dtype],a,s,c,h),[l,p]}};let FA;const $A={kernelName:ua,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}=Fy(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)]}},OA={kernelName:la,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]=zT({inputs:{x:a},attrs:{begin:p,size:h},backend:n});return c.map((({dataId:e,dtype:t})=>({dataId:e,dtype:t,shape:u})))}},DA={kernelName:ca,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}},PA=[rT,sT,oT,iT,lT,pT,_T,wT,kT,IT,TT,ST,ET,NT,AT,RT,PT,FT,OT,WT,HT,jT,KT,qT,YT,QT,ZT,tS,rS,sS,iS,lS,pS,hS,dS,gS,bS,xS,vS,IS,SS,NS,CS,MS,$S,OS,PS,LS,BS,US,zS,VS,GS,KS,qS,XS,QS,ZS,tE,rE,sE,oE,iE,dT,uE,lE,cE,hE,dE,fE,gE,bE,yE,_E,xE,wE,vE,IE,SE,NE,AE,RE,FE,OE,PE,BE,WE,VE,HE,KE,JE,ZE,eN,tN,aN,oN,uN,lN,pN,hN,dN,mN,gN,bN,xN,wN,vN,kN,IN,TN,BT,EN,AN,RN,FN,ON,PN,LN,BN,WN,VN,GN,jN,qN,XN,YN,QN,VT,YE,JN,ZN,tA,rA,iA,uA,cA,pA,hA,dA,fA,gA,bA,_A,xA,wA,vA,IA,TA,SA,NA,CA,MA,{kernelName:oa,backendName:"wasm",setupFunc:function(e){FA=e.wasm.cwrap(oa,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(_t(a.shape)).buffer),b=new Uint8Array(new Int32Array(_t(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 FA(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),_}},gT,$A,OA,DA];for(const e of PA)ka(e);const LA=Ct();LA.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}})),LA.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",(async()=>{if(LA.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 BA=Yp((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 A.buffer!=F&&z(A.buffer),$}function r(){return A.buffer!=F&&z(A.buffer),O}function a(){return A.buffer!=F&&z(A.buffer),D}function s(){return A.buffer!=F&&z(A.buffer),P}function o(){return A.buffer!=F&&z(A.buffer),L}var i,u,l,c=void 0!==(t=t||{})?t:{};c.ready=new Promise((function(e,t){i=e,u=t})),void 0!==je&&je.listeners&&(l={uncaughtException:je.listeners("uncaughtException"),unhandledRejection:je.listeners("unhandledRejection")});var p,h,d,f=Object.assign({},c),m=(e,t)=>{throw t},g="object"==typeof window,y="function"==typeof importScripts,b="object"==typeof je&&"object"==typeof je.versions&&"string"==typeof je.versions.node,_=c.ENVIRONMENT_IS_PTHREAD||!1,x="";function w(e){return c.locateFile?c.locateFile(e,x):x+e}if(b){var v=rh,k=rh;let e;x=y?k.dirname(x)+"/":"/Users/kodbiro/Projects/GeometryTracking/xzimg-web-sdk/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out/",p=(e,t)=>(e=te(e)?new URL(e):k.normalize(e),v.readFileSync(e,t?void 0:"utf8")),d=e=>{var t=p(e,!0);return t.buffer||(t=new Uint8Array(t)),t},h=(e,t,n)=>{e=te(e)?new URL(e):k.normalize(e),v.readFile(e,(function(e,r){e?n(e):t(r.buffer)}))},je.argv.length>1&&je.argv[1].replace(/\\/g,"/"),je.argv.slice(2),je.on("uncaughtException",(function(e){if(!(e instanceof ae))throw e})),je.on("unhandledRejection",(function(e){throw e})),m=(e,t)=>{if(q())throw je.exitCode=e,t;var n;(n=t)instanceof ae||N("exiting due to exception: "+n),je.exit(e)},c.inspect=function(){return"[Emscripten Module object]"};try{e=rh}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(g||y)&&(y?x=self.location.href:"undefined"!=typeof document&&document.currentScript&&(x=document.currentScript.src),void 0!==e&&e&&(x=e),x=0!==x.indexOf("blob:")?x.substr(0,x.replace(/[?#].*/,"").lastIndexOf("/")+1):"",b||(p=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},y&&(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)}));b&&"undefined"==typeof performance&&(qp.performance=rh.performance);var I=console.log.bind(console),T=console.warn.bind(console);b&&(I=e=>v.writeSync(1,e+"\n"),T=e=>v.writeSync(2,e+"\n"));var S,E=c.print||I,N=c.printErr||T;Object.assign(c,f),f=null,c.arguments&&c.arguments,c.thisProgram&&c.thisProgram,c.quit&&(m=c.quit),c.wasmBinary&&(S=c.wasmBinary);var A,C,R=c.noExitRuntime||!0;"object"!=typeof WebAssembly&&Z("no native wasm support detected");var M,F,$,O,D,P,L,B=!1,U="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function W(e,t,n){for(var r=(t>>>=0)+n,a=t;e[a]&&!(a>=r);)++a;if(a-t>16&&e.buffer&&U)return U.decode(e.buffer instanceof SharedArrayBuffer?e.slice(t,a):e.subarray(t,a));for(var s="";t<a;){var o=e[t++];if(128&o){var i=63&e[t++];if(192!=(224&o)){var u=63&e[t++];if((o=224==(240&o)?(15&o)<<12|i<<6|u:(7&o)<<18|i<<12|u<<6|63&e[t++])<65536)s+=String.fromCharCode(o);else{var l=o-65536;s+=String.fromCharCode(55296|l>>10,56320|1023&l)}}else s+=String.fromCharCode((31&o)<<6|i)}else s+=String.fromCharCode(o)}return s}function z(e){F=e,c.HEAP8=$=new Int8Array(e),c.HEAP16=new Int16Array(e),c.HEAP32=D=new Int32Array(e),c.HEAPU8=O=new Uint8Array(e),c.HEAPU16=new Uint16Array(e),c.HEAPU32=P=new Uint32Array(e),c.HEAPF32=new Float32Array(e),c.HEAPF64=L=new Float64Array(e)}_&&(F=c.buffer);var V,H=c.INITIAL_MEMORY||16777216;if(_)A=c.wasmMemory,F=c.buffer;else if(c.wasmMemory)A=c.wasmMemory;else if(!((A=new WebAssembly.Memory({initial:H/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw N("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"),b&&N("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and/or recent version)"),Error("bad memory");A&&(F=A.buffer),H=F.byteLength,z(F);var G=[],j=[],K=[];function q(){return R}function X(){_||ce(j)}var Y,Q=0,J=null;function Z(e){c.onAbort&&c.onAbort(e),N(e="Aborted("+e+")"),B=!0,M=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==Y&&S)return new Uint8Array(S);if(d)return d(e);throw"both async and sync fetching of the wasm failed"}catch(e){Z(e)}}ee(Y="tfjs-backend-wasm-threaded-simd.wasm")||(Y=w(Y));var re={};function ae(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function se(e){var t=le.pthreads[e];t||Z(undefined),le.returnWorkerToPool(t)}function oe(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=()=>{b&&t.ref(),t.postMessage(n,e.transferList),delete t.runPthread},t.loaded&&t.runPthread(),0}function ie(e){if(_)return _e(1,1,e);M=e,q()||(le.terminateAllThreads(),c.onExit&&c.onExit(e),B=!0),m(e,new ae(e))}var ue=function(e,t){if(M=e,!t&&_)throw pe(e),"unwind";ie(e)},le={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],pthreads:{},init:function(){_?le.initWorker():le.initMainThread()},initMainThread:function(){for(var e=8;e--;)le.allocateUnusedWorker()},initWorker:function(){R=!1},setExitStatus:function(e){M=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,b&&e.unref(),Le(t)},receiveObjectTransfer:function(e){},threadInitTLS:function(){le.tlsInitFunctions.forEach((e=>e()))},loadWasmModuleToWorker:function(t,n){t.onmessage=e=>{var r,a=e.data,s=a.cmd;if(t.pthread_ptr&&(le.currentProxiedOperationCallerThread=t.pthread_ptr),a.targetThread&&a.targetThread!=Re()){var o=le.pthreads[a.targetThread];return o?o.postMessage(a,a.transferList):N('Internal error! Worker sent a message "'+s+'" to target pthread '+a.targetThread+", but that thread no longer exists!"),void(le.currentProxiedOperationCallerThread=void 0)}"processProxyingQueue"===s?ge(a.queue):"spawnThread"===s?oe(a):"cleanupThread"===s?se(a.thread):"killThread"===s?function(e){var t=le.pthreads[e];delete le.pthreads[e],t.terminate(),Le(e),le.runningWorkers.splice(le.runningWorkers.indexOf(t),1),t.pthread_ptr=0}(a.thread):"cancelThread"===s?(r=a.thread,le.pthreads[r].postMessage({cmd:"cancel"})):"loaded"===s?(t.loaded=!0,b&&t.unref(),n&&n(t),t.runPthread&&t.runPthread()):"print"===s?E("Thread "+a.threadId+": "+a.text):"printErr"===s?N("Thread "+a.threadId+": "+a.text):"alert"===s?alert("Thread "+a.threadId+": "+a.text):"setimmediate"===a.target?t.postMessage(a):"callHandler"===s?c[a.handler](...a.args):s&&N("worker sent an unknown command "+s),le.currentProxiedOperationCallerThread=void 0},t.onerror=e=>{throw N("worker sent an error! "+e.filename+":"+e.lineno+": "+e.message),e},b&&(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"])c.hasOwnProperty(a)&&r.push(a);t.postMessage({cmd:"load",handlers:r,urlOrBlob:c.mainScriptUrlOrBlob||e,wasmMemory:A,wasmModule:C})},allocateUnusedWorker:function(){var e,t=w("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 ce(e){for(;e.length>0;)e.shift()(c)}function pe(e){if(_)return _e(2,0,e);try{ue(e)}catch(e){!function(e){if(e instanceof ae||"unwind"==e)return M;m(1,e)}(e)}}c.PThread=le,c.establishStackSpace=function(){var e=Re(),t=a()[e+52>>>2],n=a()[e+56>>>2];Ue(t,t-n),ze(t)};var he,de=[];function fe(e,t,n,r){return _?_e(3,1,e,t,n,r):me(e,t,n,r)}function me(e,t,n,r){if("undefined"==typeof SharedArrayBuffer)return N("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];if(_&&0===a.length)return fe(e,t,n,r);var s={startRoutine:n,pthread_ptr:e,arg:r,transferList:a};return _?(s.cmd="spawnThread",postMessage(s,a),0):oe(s)}function ge(e){Atomics.store(a(),e>>2,1),Re()&&Pe(e),Atomics.compareExchange(a(),e>>2,1,0)}function ye(e){ye.shown||(ye.shown={}),ye.shown[e]||(ye.shown[e]=1,b&&(e="warning: "+e),N(e))}function be(e){var t=We(),n=e();return ze(t),n}function _e(e,t){var n=arguments.length-2,r=arguments;return be((()=>{for(var a=n,s=Ve(8*a),i=s>>3,u=0;u<n;u++){var l=r[2+u];o()[i+u>>>0]=l}return Fe(e,a,s,t)}))}c.invokeEntryPoint=function(e,t){var n,r,a=((r=de[n=e])||(n>=de.length&&(de.length=n+1),de[n]=r=V.get(n)),r)(t);q()?le.setExitStatus(a):Be(a)},c.executeNotifiedProxyingQueue=ge,he=b?()=>{var e=je.hrtime();return 1e3*e[0]+e[1]/1e6}:()=>performance.timeOrigin+performance.now();var xe=[];function we(e){try{return A.grow(e-F.byteLength+65535>>>16),z(A.buffer),1}catch(e){}}function ve(e){return _?_e(4,1,e):52}function ke(e,t,n,r,a){return _?_e(5,1,e,t,n,r,a):70}var Ie=[null,[],[]];function Te(e,t){var n=Ie[e];0===t||10===t?((1===e?E:N)(W(n,0)),n.length=0):n.push(t)}function Se(e,t,n,a){if(_)return _e(6,1,e,t,n,a);for(var o=0,i=0;i<n;i++){var u=s()[t>>>2],l=s()[t+4>>>2];t+=8;for(var c=0;c<l;c++)Te(e,r()[u+c>>>0]);o+=l}return s()[a>>>2]=o,0}function Ee(e){return c["_"+e]}function Ne(e,t,a,s,o){var i={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;n>>>=0;for(var a=n+r-1,s=0;s<e.length;++s){var o=e.charCodeAt(s);if(o>=55296&&o<=57343&&(o=65536+((1023&o)<<10)|1023&e.charCodeAt(++s)),o<=127){if(n>=a)break;t[n++>>>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,r(),t,n)}(e,t=Ve(n),n)}return t},array:e=>{var t=Ve(e.length);return function(e,t){n().set(e,t>>>0)}(e,t),t}};var u=Ee(e),l=[],c=0;if(s)for(var p=0;p<s.length;p++){var h=i[a[p]];h?(0===c&&(c=We()),l[p]=h(s[p])):l[p]=s[p]}var d=u.apply(null,l);return function(e){return 0!==c&&ze(c),function(e){return"string"===t?(n=e,(n>>>=0)?W(r(),n,void 0):""):"boolean"===t?Boolean(e):e;var n}(e)}(d)}le.init();var Ae=[null,ie,pe,fe,ve,ke,Se],Ce={__emscripten_init_main_thread_js:function(e){Me(e,!y,1,!g),le.threadInitTLS()},__emscripten_thread_cleanup:function(e){_?postMessage({cmd:"cleanupThread",thread:e}):se(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((()=>ge(r)));else if(_)postMessage({targetThread:e,cmd:"processProxyingQueue",queue:r});else{var a=le.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(){Z("")},emscripten_check_blocking_allowed:function(){b||y||ye("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,n){r().copyWithin(e>>>0,t>>>0,t+n>>>0)},emscripten_num_logical_cores:function(){return b?rh.cpus().length:navigator.hardwareConcurrency},emscripten_receive_on_main_thread_js:function(e,t,n){xe.length=t;for(var r=n>>3,a=0;a<t;a++)xe[a]=o()[r+a>>>0];return(e<0?re[-e-1]:Ae[e]).apply(null,xe)},emscripten_resize_heap:function(e){var t=r().length;if((e>>>=0)<=t)return!1;var n=4294901760;if(e>n)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),we(Math.min(n,a(Math.max(e,o),65536))))return!0}return!1},emscripten_unwind_to_js_event_loop:function(){throw"unwind"},exit:ue,fd_close:ve,fd_seek:ke,fd_write:Se,memory:A||c.wasmMemory};!function(){var e={env:Ce,wasi_snapshot_preview1:Ce};function t(e,t){var n,r,a=e.exports;if(c.asm=a,n=c.asm._emscripten_tls_init,le.tlsInitFunctions.push(n),V=c.asm.__indirect_function_table,r=c.asm.__wasm_call_ctors,j.unshift(r),C=t,!_){var s=le.unusedWorkers.length;le.unusedWorkers.forEach((function(e){le.loadWasmModuleToWorker(e,(function(){--s||function(e){if(Q--,c.monitorRunDependencies&&c.monitorRunDependencies(Q),0==Q&&J){var t=J;J=null,t()}}()}))}))}}function n(e){t(e.instance,e.module)}function r(t){return function(){if(!S&&(g||y)){if("function"==typeof fetch&&!te(Y))return fetch(Y,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+Y+"'";return e.arrayBuffer()})).catch((function(){return ne(Y)}));if(h)return new Promise((function(e,t){h(Y,(function(t){e(new Uint8Array(t))}),t)}))}return Promise.resolve().then((function(){return ne(Y)}))}().then((function(t){return WebAssembly.instantiate(t,e)})).then((function(e){return e})).then(t,(function(e){N("failed to asynchronously prepare wasm: "+e),Z(e)}))}if(_||(Q++,c.monitorRunDependencies&&c.monitorRunDependencies(Q)),c.instantiateWasm)try{return c.instantiateWasm(e,t)}catch(e){N("Module.instantiateWasm callback failed with error: "+e),u(e)}(S||"function"!=typeof WebAssembly.instantiateStreaming||ee(Y)||te(Y)||b||"function"!=typeof fetch?r(n):fetch(Y,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,e).then(n,(function(e){return N("wasm streaming compile failed: "+e),N("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(u)}(),c.___wasm_call_ctors=function(){return(c.___wasm_call_ctors=c.asm.__wasm_call_ctors).apply(null,arguments)},c._init=function(){return(c._init=c.asm.init).apply(null,arguments)},c._init_with_threads_count=function(){return(c._init_with_threads_count=c.asm.init_with_threads_count).apply(null,arguments)},c._get_threads_count=function(){return(c._get_threads_count=c.asm.get_threads_count).apply(null,arguments)},c._register_tensor=function(){return(c._register_tensor=c.asm.register_tensor).apply(null,arguments)},c._dispose_data=function(){return(c._dispose_data=c.asm.dispose_data).apply(null,arguments)},c._dispose=function(){return(c._dispose=c.asm.dispose).apply(null,arguments)},c._Abs=function(){return(c._Abs=c.asm.Abs).apply(null,arguments)},c._Acos=function(){return(c._Acos=c.asm.Acos).apply(null,arguments)},c._Acosh=function(){return(c._Acosh=c.asm.Acosh).apply(null,arguments)},c._Add=function(){return(c._Add=c.asm.Add).apply(null,arguments)},c._AddN=function(){return(c._AddN=c.asm.AddN).apply(null,arguments)},c._All=function(){return(c._All=c.asm.All).apply(null,arguments)},c._Any=function(){return(c._Any=c.asm.Any).apply(null,arguments)},c._ArgMax=function(){return(c._ArgMax=c.asm.ArgMax).apply(null,arguments)},c._ArgMin=function(){return(c._ArgMin=c.asm.ArgMin).apply(null,arguments)},c._Asin=function(){return(c._Asin=c.asm.Asin).apply(null,arguments)},c._Asinh=function(){return(c._Asinh=c.asm.Asinh).apply(null,arguments)},c._Atan=function(){return(c._Atan=c.asm.Atan).apply(null,arguments)},c._Atan2=function(){return(c._Atan2=c.asm.Atan2).apply(null,arguments)},c._Atanh=function(){return(c._Atanh=c.asm.Atanh).apply(null,arguments)},c._AvgPool=function(){return(c._AvgPool=c.asm.AvgPool).apply(null,arguments)},c._AvgPool3D=function(){return(c._AvgPool3D=c.asm.AvgPool3D).apply(null,arguments)},c._AvgPool3DGrad=function(){return(c._AvgPool3DGrad=c.asm.AvgPool3DGrad).apply(null,arguments)},c._AvgPoolGrad=function(){return(c._AvgPoolGrad=c.asm.AvgPoolGrad).apply(null,arguments)},c._BatchMatMul=function(){return(c._BatchMatMul=c.asm.BatchMatMul).apply(null,arguments)},c._Bincount=function(){return(c._Bincount=c.asm.Bincount).apply(null,arguments)},c._BitwiseAnd=function(){return(c._BitwiseAnd=c.asm.BitwiseAnd).apply(null,arguments)},c._Ceil=function(){return(c._Ceil=c.asm.Ceil).apply(null,arguments)},c._ClipByValue=function(){return(c._ClipByValue=c.asm.ClipByValue).apply(null,arguments)},c._Conv2D=function(){return(c._Conv2D=c.asm.Conv2D).apply(null,arguments)},c._Conv2DBackpropInput=function(){return(c._Conv2DBackpropInput=c.asm.Conv2DBackpropInput).apply(null,arguments)},c._Conv3D=function(){return(c._Conv3D=c.asm.Conv3D).apply(null,arguments)},c._Conv3DBackpropFilterV2=function(){return(c._Conv3DBackpropFilterV2=c.asm.Conv3DBackpropFilterV2).apply(null,arguments)},c._Conv3DBackpropInputV2=function(){return(c._Conv3DBackpropInputV2=c.asm.Conv3DBackpropInputV2).apply(null,arguments)},c._Cos=function(){return(c._Cos=c.asm.Cos).apply(null,arguments)},c._Cosh=function(){return(c._Cosh=c.asm.Cosh).apply(null,arguments)},c._CropAndResize=function(){return(c._CropAndResize=c.asm.CropAndResize).apply(null,arguments)},c._Cumprod=function(){return(c._Cumprod=c.asm.Cumprod).apply(null,arguments)},c._Cumsum=function(){return(c._Cumsum=c.asm.Cumsum).apply(null,arguments)},c._DenseBincount=function(){return(c._DenseBincount=c.asm.DenseBincount).apply(null,arguments)},c._DepthToSpace=function(){return(c._DepthToSpace=c.asm.DepthToSpace).apply(null,arguments)},c._DepthwiseConv2dNative=function(){return(c._DepthwiseConv2dNative=c.asm.DepthwiseConv2dNative).apply(null,arguments)},c._Diag=function(){return(c._Diag=c.asm.Diag).apply(null,arguments)},c._Dilation2D=function(){return(c._Dilation2D=c.asm.Dilation2D).apply(null,arguments)},c._Dilation2DBackpropFilter=function(){return(c._Dilation2DBackpropFilter=c.asm.Dilation2DBackpropFilter).apply(null,arguments)},c._Dilation2DBackpropInput=function(){return(c._Dilation2DBackpropInput=c.asm.Dilation2DBackpropInput).apply(null,arguments)},c._Elu=function(){return(c._Elu=c.asm.Elu).apply(null,arguments)},c._EluGrad=function(){return(c._EluGrad=c.asm.EluGrad).apply(null,arguments)},c._Equal=function(){return(c._Equal=c.asm.Equal).apply(null,arguments)},c._Erf=function(){return(c._Erf=c.asm.Erf).apply(null,arguments)},c._Exp=function(){return(c._Exp=c.asm.Exp).apply(null,arguments)},c._Expm1=function(){return(c._Expm1=c.asm.Expm1).apply(null,arguments)},c._FlipLeftRight=function(){return(c._FlipLeftRight=c.asm.FlipLeftRight).apply(null,arguments)},c._Floor=function(){return(c._Floor=c.asm.Floor).apply(null,arguments)},c._FloorDiv=function(){return(c._FloorDiv=c.asm.FloorDiv).apply(null,arguments)},c._FusedBatchNorm=function(){return(c._FusedBatchNorm=c.asm.FusedBatchNorm).apply(null,arguments)},c._FusedConv2D=function(){return(c._FusedConv2D=c.asm.FusedConv2D).apply(null,arguments)},c._FusedDepthwiseConv2D=function(){return(c._FusedDepthwiseConv2D=c.asm.FusedDepthwiseConv2D).apply(null,arguments)},c._Gather=function(){return(c._Gather=c.asm.Gather).apply(null,arguments)},c._GatherNd=function(){return(c._GatherNd=c.asm.GatherNd).apply(null,arguments)},c._Greater=function(){return(c._Greater=c.asm.Greater).apply(null,arguments)},c._GreaterEqual=function(){return(c._GreaterEqual=c.asm.GreaterEqual).apply(null,arguments)},c._IsFinite=function(){return(c._IsFinite=c.asm.IsFinite).apply(null,arguments)},c._IsInf=function(){return(c._IsInf=c.asm.IsInf).apply(null,arguments)},c._IsNan=function(){return(c._IsNan=c.asm.IsNan).apply(null,arguments)},c._LRN=function(){return(c._LRN=c.asm.LRN).apply(null,arguments)},c._LRNGrad=function(){return(c._LRNGrad=c.asm.LRNGrad).apply(null,arguments)},c._LeakyRelu=function(){return(c._LeakyRelu=c.asm.LeakyRelu).apply(null,arguments)},c._Less=function(){return(c._Less=c.asm.Less).apply(null,arguments)},c._LessEqual=function(){return(c._LessEqual=c.asm.LessEqual).apply(null,arguments)},c._LinSpace=function(){return(c._LinSpace=c.asm.LinSpace).apply(null,arguments)},c._Log=function(){return(c._Log=c.asm.Log).apply(null,arguments)},c._Log1p=function(){return(c._Log1p=c.asm.Log1p).apply(null,arguments)},c._LogicalAnd=function(){return(c._LogicalAnd=c.asm.LogicalAnd).apply(null,arguments)},c._LogicalNot=function(){return(c._LogicalNot=c.asm.LogicalNot).apply(null,arguments)},c._LogicalOr=function(){return(c._LogicalOr=c.asm.LogicalOr).apply(null,arguments)},c._LogicalXor=function(){return(c._LogicalXor=c.asm.LogicalXor).apply(null,arguments)},c._Max=function(){return(c._Max=c.asm.Max).apply(null,arguments)},c._MaxPool=function(){return(c._MaxPool=c.asm.MaxPool).apply(null,arguments)},c._MaxPool3D=function(){return(c._MaxPool3D=c.asm.MaxPool3D).apply(null,arguments)},c._MaxPool3DGrad=function(){return(c._MaxPool3DGrad=c.asm.MaxPool3DGrad).apply(null,arguments)},c._MaxPoolGrad=function(){return(c._MaxPoolGrad=c.asm.MaxPoolGrad).apply(null,arguments)},c._MaxPoolWithArgmax=function(){return(c._MaxPoolWithArgmax=c.asm.MaxPoolWithArgmax).apply(null,arguments)},c._Maximum=function(){return(c._Maximum=c.asm.Maximum).apply(null,arguments)},c._Mean=function(){return(c._Mean=c.asm.Mean).apply(null,arguments)},c._Min=function(){return(c._Min=c.asm.Min).apply(null,arguments)},c._Minimum=function(){return(c._Minimum=c.asm.Minimum).apply(null,arguments)},c._MirrorPad=function(){return(c._MirrorPad=c.asm.MirrorPad).apply(null,arguments)},c._Mod=function(){return(c._Mod=c.asm.Mod).apply(null,arguments)},c._Multinomial=function(){return(c._Multinomial=c.asm.Multinomial).apply(null,arguments)},c._Multiply=function(){return(c._Multiply=c.asm.Multiply).apply(null,arguments)},c._Neg=function(){return(c._Neg=c.asm.Neg).apply(null,arguments)},c._NonMaxSuppressionV3=function(){return(c._NonMaxSuppressionV3=c.asm.NonMaxSuppressionV3).apply(null,arguments)},c._NonMaxSuppressionV4=function(){return(c._NonMaxSuppressionV4=c.asm.NonMaxSuppressionV4).apply(null,arguments)},c._NonMaxSuppressionV5=function(){return(c._NonMaxSuppressionV5=c.asm.NonMaxSuppressionV5).apply(null,arguments)},c._NotEqual=function(){return(c._NotEqual=c.asm.NotEqual).apply(null,arguments)},c._OneHot=function(){return(c._OneHot=c.asm.OneHot).apply(null,arguments)},c._PadV2=function(){return(c._PadV2=c.asm.PadV2).apply(null,arguments)},c._Pow=function(){return(c._Pow=c.asm.Pow).apply(null,arguments)},c._Prelu=function(){return(c._Prelu=c.asm.Prelu).apply(null,arguments)},c._Prod=function(){return(c._Prod=c.asm.Prod).apply(null,arguments)},c._RealDiv=function(){return(c._RealDiv=c.asm.RealDiv).apply(null,arguments)},c._Reciprocal=function(){return(c._Reciprocal=c.asm.Reciprocal).apply(null,arguments)},c._Relu=function(){return(c._Relu=c.asm.Relu).apply(null,arguments)},c._Relu6=function(){return(c._Relu6=c.asm.Relu6).apply(null,arguments)},c._ResizeBilinear=function(){return(c._ResizeBilinear=c.asm.ResizeBilinear).apply(null,arguments)},c._ResizeBilinearGrad=function(){return(c._ResizeBilinearGrad=c.asm.ResizeBilinearGrad).apply(null,arguments)},c._ResizeNearestNeighbor=function(){return(c._ResizeNearestNeighbor=c.asm.ResizeNearestNeighbor).apply(null,arguments)},c._ResizeNearestNeighborGrad=function(){return(c._ResizeNearestNeighborGrad=c.asm.ResizeNearestNeighborGrad).apply(null,arguments)},c._Reverse=function(){return(c._Reverse=c.asm.Reverse).apply(null,arguments)},c._RotateWithOffset=function(){return(c._RotateWithOffset=c.asm.RotateWithOffset).apply(null,arguments)},c._Round=function(){return(c._Round=c.asm.Round).apply(null,arguments)},c._Rsqrt=function(){return(c._Rsqrt=c.asm.Rsqrt).apply(null,arguments)},c._ScatterNd=function(){return(c._ScatterNd=c.asm.ScatterNd).apply(null,arguments)},c._SearchSorted=function(){return(c._SearchSorted=c.asm.SearchSorted).apply(null,arguments)},c._SelectV2=function(){return(c._SelectV2=c.asm.SelectV2).apply(null,arguments)},c._Selu=function(){return(c._Selu=c.asm.Selu).apply(null,arguments)},c._Sigmoid=function(){return(c._Sigmoid=c.asm.Sigmoid).apply(null,arguments)},c._Sign=function(){return(c._Sign=c.asm.Sign).apply(null,arguments)},c._Sin=function(){return(c._Sin=c.asm.Sin).apply(null,arguments)},c._Sinh=function(){return(c._Sinh=c.asm.Sinh).apply(null,arguments)},c._Softmax=function(){return(c._Softmax=c.asm.Softmax).apply(null,arguments)},c._Softplus=function(){return(c._Softplus=c.asm.Softplus).apply(null,arguments)},c._SparseFillEmptyRows=function(){return(c._SparseFillEmptyRows=c.asm.SparseFillEmptyRows).apply(null,arguments)},c._SparseReshape=function(){return(c._SparseReshape=c.asm.SparseReshape).apply(null,arguments)},c._SparseSegmentReduction=function(){return(c._SparseSegmentReduction=c.asm.SparseSegmentReduction).apply(null,arguments)},c._SparseToDense=function(){return(c._SparseToDense=c.asm.SparseToDense).apply(null,arguments)},c._Sqrt=function(){return(c._Sqrt=c.asm.Sqrt).apply(null,arguments)},c._Square=function(){return(c._Square=c.asm.Square).apply(null,arguments)},c._SquaredDifference=function(){return(c._SquaredDifference=c.asm.SquaredDifference).apply(null,arguments)},c._Step=function(){return(c._Step=c.asm.Step).apply(null,arguments)},c._StridedSlice=function(){return(c._StridedSlice=c.asm.StridedSlice).apply(null,arguments)},c._Sub=function(){return(c._Sub=c.asm.Sub).apply(null,arguments)},c._Sum=function(){return(c._Sum=c.asm.Sum).apply(null,arguments)},c._Tan=function(){return(c._Tan=c.asm.Tan).apply(null,arguments)},c._Tanh=function(){return(c._Tanh=c.asm.Tanh).apply(null,arguments)},c._TensorScatterUpdate=function(){return(c._TensorScatterUpdate=c.asm.TensorScatterUpdate).apply(null,arguments)},c._Tile=function(){return(c._Tile=c.asm.Tile).apply(null,arguments)},c._TopK=function(){return(c._TopK=c.asm.TopK).apply(null,arguments)},c._Transform=function(){return(c._Transform=c.asm.Transform).apply(null,arguments)},c._Transpose=function(){return(c._Transpose=c.asm.Transpose).apply(null,arguments)},c.__FusedMatMul=function(){return(c.__FusedMatMul=c.asm._FusedMatMul).apply(null,arguments)},c._malloc=function(){return(c._malloc=c.asm.malloc).apply(null,arguments)},c._free=function(){return(c._free=c.asm.free).apply(null,arguments)},c.__emscripten_tls_init=function(){return(c.__emscripten_tls_init=c.asm._emscripten_tls_init).apply(null,arguments)};var Re=c._pthread_self=function(){return(Re=c._pthread_self=c.asm.pthread_self).apply(null,arguments)};c.___errno_location=function(){return(c.___errno_location=c.asm.__errno_location).apply(null,arguments)};var Me=c.__emscripten_thread_init=function(){return(Me=c.__emscripten_thread_init=c.asm._emscripten_thread_init).apply(null,arguments)};c.__emscripten_thread_crashed=function(){return(c.__emscripten_thread_crashed=c.asm._emscripten_thread_crashed).apply(null,arguments)},c._emscripten_main_thread_process_queued_calls=function(){return(c._emscripten_main_thread_process_queued_calls=c.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},c._emscripten_main_browser_thread_id=function(){return(c._emscripten_main_browser_thread_id=c.asm.emscripten_main_browser_thread_id).apply(null,arguments)};var Fe=c._emscripten_run_in_main_runtime_thread_js=function(){return(Fe=c._emscripten_run_in_main_runtime_thread_js=c.asm.emscripten_run_in_main_runtime_thread_js).apply(null,arguments)};c._emscripten_dispatch_to_thread_=function(){return(c._emscripten_dispatch_to_thread_=c.asm.emscripten_dispatch_to_thread_).apply(null,arguments)};var $e,Oe,De,Pe=c.__emscripten_proxy_execute_task_queue=function(){return(Pe=c.__emscripten_proxy_execute_task_queue=c.asm._emscripten_proxy_execute_task_queue).apply(null,arguments)},Le=c.__emscripten_thread_free_data=function(){return(Le=c.__emscripten_thread_free_data=c.asm._emscripten_thread_free_data).apply(null,arguments)},Be=c.__emscripten_thread_exit=function(){return(Be=c.__emscripten_thread_exit=c.asm._emscripten_thread_exit).apply(null,arguments)},Ue=c._emscripten_stack_set_limits=function(){return(Ue=c._emscripten_stack_set_limits=c.asm.emscripten_stack_set_limits).apply(null,arguments)},We=c.stackSave=function(){return(We=c.stackSave=c.asm.stackSave).apply(null,arguments)},ze=c.stackRestore=function(){return(ze=c.stackRestore=c.asm.stackRestore).apply(null,arguments)},Ve=c.stackAlloc=function(){return(Ve=c.stackAlloc=c.asm.stackAlloc).apply(null,arguments)};function He(e){if(!(Q>0)){if(_)return i(c),X(),void startWorker(c);!function(){if(c.preRun)for("function"==typeof c.preRun&&(c.preRun=[c.preRun]);c.preRun.length;)e=c.preRun.shift(),G.unshift(e);var e;ce(G)}(),Q>0||(c.setStatus?(c.setStatus("Running..."),setTimeout((function(){setTimeout((function(){c.setStatus("")}),1),t()}),1)):t())}function t(){$e||($e=!0,c.calledRun=!0,B||(X(),i(c),c.onRuntimeInitialized&&c.onRuntimeInitialized(),function(){if(!_){if(c.postRun)for("function"==typeof c.postRun&&(c.postRun=[c.postRun]);c.postRun.length;)e=c.postRun.shift(),K.unshift(e);var e;ce(K)}}()))}}if(c.dynCall_iijjiiii=function(){return(c.dynCall_iijjiiii=c.asm.dynCall_iijjiiii).apply(null,arguments)},c.dynCall_jiji=function(){return(c.dynCall_jiji=c.asm.dynCall_jiji).apply(null,arguments)},c.keepRuntimeAlive=q,c.wasmMemory=A,c.cwrap=function(e,t,n,r){var a=(n=n||[]).every((e=>"number"===e||"boolean"===e));return"string"!==t&&a&&!r?Ee(e):function(){return Ne(e,t,n,arguments)}},c.ExitStatus=ae,c.PThread=le,J=function e(){$e||He(),$e||(J=e)},c.preInit)for("function"==typeof c.preInit&&(c.preInit=[c.preInit]);c.preInit.length>0;)c.preInit.pop()();if(He(),l&&(Oe={uncaughtException:je.listeners("uncaughtException").filter((function(e){return!l.uncaughtException.indexOf(e)>-1})),unhandledRejection:je.listeners("unhandledRejection").filter((function(e){return!l.unhandledRejection.indexOf(e)>-1}))}),"undefined"!=typeof WasmBackendModule)De=WasmBackendModule;else{if(void 0===t)throw new Error("Could not find wasm module in post.js");De=t}if(Oe){var Ge=De._dispose;De._dispose=function(){Ge(),Oe.uncaughtException.forEach((function(e){je.removeListener("uncaughtException",e)})),Oe.unhandledRejection.forEach((function(e){je.removeListener("unhandledRejection",e)}))}}return t.ready}})();e.exports=n})),UA=e({__proto__:null,default:BA},[BA]),WA=Yp((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!==je&&je.listeners&&(a={uncaughtException:je.listeners("uncaughtException"),unhandledRejection:je.listeners("unhandledRejection")});var o,i,u,l=Object.assign({},s),c="object"==typeof window,p="function"==typeof importScripts,h="object"==typeof je&&"object"==typeof je.versions&&"string"==typeof je.versions.node,d="";if(h){var f=rh,m=rh;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)}))},je.argv.length>1&&je.argv[1].replace(/\\/g,"/"),je.argv.slice(2),je.on("uncaughtException",(function(e){if(!(e instanceof B))throw e})),je.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;n>>>=0;for(var a=n+r-1,s=0;s<e.length;++s){var o=e.charCodeAt(s);if(o>=55296&&o<=57343&&(o=65536+((1023&o)<<10)|1023&e.charCodeAt(++s)),o<=127){if(n>=a)break;t[n++>>>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}};var 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]}var p=o.apply(null,i);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)}(p)}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:je.listeners("uncaughtException").filter((function(e){return!a.uncaughtException.indexOf(e)>-1})),unhandledRejection:je.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){je.removeListener("uncaughtException",e)})),q.unhandledRejection.forEach((function(e){je.removeListener("unhandledRejection",e)}))}}return t.ready}})();e.exports=n}));const zA=BA||UA,VA=WA||e({__proto__:null,default:WA},[WA]);class HA extends qe{constructor(e){super(),this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(JA),ZA=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new Ke(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=hs();return e(),{kernelMs:hs()-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=nt(n),i=o*ft(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||nt(s);const i=ft(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=nt(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=nt(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 GA(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!=qA&&null!=qA[r]?qA[r]:n+r}const jA=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"];let KA=null,qA={},XA=!1,YA=!1;function QA(e,t=!1){if(XA)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)KA=e;else{qA=e;const t=jA.filter((e=>null==qA[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.`)}YA=t}let JA=-1,ZA=null;di("wasm",(async()=>{const{wasm:e}=await async function(){const[e,t]=await Promise.all([Ct().getAsync("WASM_HAS_SIMD_SUPPORT"),Ct().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise(((n,r)=>{const a={locateFile:(n,r)=>{if(n.endsWith(".worker.js")){const e='"use strict";var Module={};var ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads");var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",data=>onmessage({data:data}));var fs=require("fs");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,"utf8")+"//# sourceURL="+f)},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}var initializedJS=false;var pendingNotifiedProxyingQueues=[];function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+"\n");return}console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=(info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports};self.onunhandledrejection=e=>{throw e.reason??e};self.startWorker=instance=>{Module=instance;postMessage({"cmd":"loaded"})};self.onmessage=e=>{try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;for(const handler of e.data.handlers){Module[handler]=function(){postMessage({cmd:"callHandler",handler:handler,args:[...arguments]})}}Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob=="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module)}else if(e.data.cmd==="run"){Module["__emscripten_thread_init"](e.data.pthread_ptr,0,0,1);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInitTLS();if(!initializedJS){pendingNotifiedProxyingQueues.forEach(queue=>{Module["executeNotifiedProxyingQueue"](queue)});pendingNotifiedProxyingQueues=[];initializedJS=true}try{Module["invokeEntryPoint"](e.data.start_routine,e.data.arg)}catch(ex){if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["__emscripten_thread_exit"](ex.status)}}else{throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["__emscripten_thread_exit"](-1)}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processProxyingQueue"){if(initializedJS){Module["executeNotifiedProxyingQueue"](e.data.queue)}else{pendingNotifiedProxyingQueues.push(e.data.queue)}}else if(e.data.cmd){err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){if(Module["__emscripten_thread_crashed"]){Module["__emscripten_thread_crashed"]()}throw ex}};'.replace(/\n/g,"\\n"),t=new Blob([e],{type:"application/javascript"});return URL.createObjectURL(t)}return n.endsWith(".wasm")?GA(e,t,null!=KA?KA:r):r+n}};var s;YA&&(a.instantiateWasm=(s=GA(e,t,null!=KA?KA:""),(e,t)=>(function(e,t){return Ct().platform.fetch(e,{credentials:"same-origin"})}(s).then((n=>{n.ok||e.env.a(`failed to load wasm binary file at '${s}'`),n.arrayBuffer().then((n=>{WebAssembly.instantiate(n,e).then((e=>{t(e.instance,e.module)}))}))})),{})));let o,i=!1;a.onAbort=()=>{i||XA||(XA=!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 = "+zA.toString()],{type:"text/javascript"}),o=zA(a)):o=VA(a),o.then((e=>{i=!0,XA=!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 HA(e)}),2);var eC={modelFilename:"",featuresFilename:"",objContainer:"",fovY:50,detectScoreThs:.2,trackScoreThs:.4,footToDetect:"RIGHT_FOOT",filteringLevel:2,filteringShift:.5,validTrackedKeypThs:.2,trackedNumKeypsThs:3,activeIds:new Int32Array};function tC(e){return!!(void 0===e.outputNames||e.outputNames.length<1||e.outputNames.includes("heatmaps"))}function nC(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 rC(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 aC(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 sC(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 oC(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 iC(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 uC(e,t){var n=t.length/2,r=iC(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 lC(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 cC(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 pC(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 hC,dC=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}(),fC=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}(),mC=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 dC(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 gC(e,t,n,r,a){void 0===a&&(a=.5);for(var s=e.length/2,o=rC(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 yC(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 dC(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 dC(u[d],u[d+p]),g=new dC(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 dC(u[l],u[l+p]).Dist(h);_>b&&(b=_)}b*=2;var x=new mC(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 bC(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 _C(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=bC(new Float32Array([e[s],e[s+r]]),n);a[s]=o[0],a[s+r]=o[1]}var i=rC(a,t,r);return Math.max(i[1]-i[0],i[3]-i[2])}function xC(e,t){e.length;var n=function(e,t){var n=e.length/2,r=kC(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 wC(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 aC(e,n)}function vC(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 kC(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 IC(e,t){var n=e.length/2,r=kC(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 TC(e,t,n,r,a){void 0===a&&(a=.5);for(var s=e.length/2,o=rC(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 SC(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=kC(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=IC(e,s))[0],d=l[1],m=l[2],h=nC("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=IC(e,s))[0],d=c[1],m=c[2],h=rC(e,t,p),m+=u,"oriented_bbox_size"==o&&(f=(h[1]+h[0])/2,d=(h[3]+h[2])/2,t&&(w=_C(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 EC(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 NC(e,t){var n=e._malloc(4*t.length);return e.HEAPF32.set(t,n/4),n}function AC(e,t,n){var r=new Float32Array(n),a=t/4;return r.set(e.HEAPF32.subarray(a,a+n)),r.slice()}function CC(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 RC(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 MC(e,t,n,r,a){var s=e.cwrap("xzimgMatchRecKeyps","number",["number","number","number","number","number"]),o=r.length/2;CC(e,t,n);for(var i=RC(e,n,t.width,t.height),u=NC(e,r),l=NC(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=AC(e,c,o),f=AC(e,l,r.length),m=AC(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 FC(e,t,n,r){var a=NC(e,t),s=NC(e,n),o=e._malloc(16);e.cwrap("xzimgEstimateGetSimilarity","number",["number","number","number","number"])(a,s,t.length/2,o);var i=AC(e,o,4);return e._free(a),e._free(s),e._free(o),i}function $C(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 OC(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 DC(e,t,n,r,a,s){var o=e.cwrap("xzimgGetHeatmapsLocations","number",["number","number","number","number","number","number","number","number"]),i=t[1]*t[2]*t[3],u=r/4;return e.HEAPF32.subarray(u,u+i).set(n),o(r,t[1],t[2],t[3],0,1,a,s),[new Float32Array(e.HEAPF32.buffer,a,2*t[3]),new Float32Array(e.HEAPF32.buffer,s,t[3])]}function PC(e,t,n,r,a,s,o,i){void 0===i&&(i=[""]);for(var u=[],l=[],c=[],p=[],h=[],d=0,f=null,m=0,g=o;m<g.length;m++){var y=g[m],b=Nu(y);h.push(b);var _=gu(b,"float32");h.push(_);var x=El(_,[1,t.inHeight,t.inWidth,3]);h.push(x);var w=Oc(255),v=Qu(x,w);h.push(v),"left_right"!=i[d]&&"up_down"!=i[d]||(v=bh(v,"left_right"==i[d]?2:1),h.push(v)),f?(f=Rl([f,v]),h.push(f)):f=v,d+=1}if(null!=f){var k=[];if(t.numOutputs&&1!=t.numOutputs)for(var I=0,T=k=e.predict(f);I<T.length;I++){var S=T[I];h.push(S)}else{var E=e.predict(f);h.push(E),k.push(E)}for(var N=0,A=0,C=k;A<C.length;A++){E=C[A];for(var R=[],M=[],F=0,$=Zh(E,0);F<$.length;F++){var O=$[F];h.push(O);var D=Vc(O,0);h.push(D),R.push(O.dataSync()),M.push(D.shape)}if(t.outputNames&&"heatmaps"!=t.outputNames[N]){if(t.outputNames&&"masks"==t.outputNames[N])for(G=0;G<R.length;G++)p.push(R[G]);else if(t.outputNames&&"coordinates"==t.outputNames[N])for(G=0;G<R.length;G++){for(var P=M[G][1]/2,L=new Float32Array(2*P),B=t.inHeight/2,U=t.inWidth/2,W=0;W<P;W++)L[W]=(R[G][W]+1)*U,L[W+P]=(R[G][W+P]+1)*B;u.push(L)}else if(t.outputNames&&"scores"==t.outputNames[N])if(t.outputTypes&&"logits"==t.outputTypes[N])for(G=0;G<R.length;G++){var z=M[G][1],V=new Float32Array(z);for(W=0;W<z;W++)V[W]=1/(1+Math.exp(-R[G][W]));l.push(V)}else for(G=0;G<R.length;G++){for(z=M[G][1],V=new Float32Array(z),W=0;W<z;W++)V[W]=R[G][W];l.push(V)}else if(t.outputNames&&"occlusions"==t.outputNames[N])if(t.outputTypes&&"logits"==t.outputTypes[N])for(G=0;G<R.length;G++){z=M[G][1];var H=new Float32Array(z);for(W=0;W<z;W++)H[W]=1/(1+Math.exp(-R[G][W]));c.push(H)}else for(G=0;G<R.length;G++){for(z=M[G][1],H=new Float32Array(z),W=0;W<z;W++)H[W]=R[G][W];c.push(H)}}else for(var G=0;G<R.length;G++){var j;j=n?DC(n,M[G],R[G],r[G],a[G],s[G]):OC(R[G],M[G],!0),u.push(j[0]),l.push(j[1])}N+=1}}return h.forEach((function(e){return e.dispose()})),{coordinates:u,scores:l,occlusions:c,masks:p}}function LC(e,t){var n=new le(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(ce(2),X((function(e){return BC(e.response,t)}))),progress$:r};var a=xe((function(){return n.next(1),q(BC(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 BC(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"}(hC||(hC={}));var UC,WC=function(){function e(e,t){this._trackingState=hC.Detection,this._type=0,this._R=Float32Array.from(e),this._t=Float32Array.from(t),this._trackingState=hC.Detection}return e.prototype.setTrackingState=function(e){this._trackingState=e},e.prototype.getTrackingState=function(){return this._trackingState},e.prototype.isDetected=function(){return this._trackingState==hC.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}(),zC=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()!==hC.Tracking||r.getTrackingState()!==hC.Tracking)return n;for(var a=WC.getQuatFromRotMat(t.R()),s=WC.getQuatFromRotMat(r.R()),o=WC.slerp(a,s,.5),i=WC.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 WC(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()!==hC.Tracking||t.getTrackingState()!==hC.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=WC.getQuatFromRotMat(e.R()),u=WC.getQuatFromRotMat(t.R()),l=WC.slerp(i,u,this._interpolation),c=WC.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 WC(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"}(UC||(UC={}));var VC,HC="config.bin",GC=function(){function e(){this._initialized=!1,this._currentWidth=0,this._currentHeight=0,this._trackingState=hC.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=UC.Right,this._leftFootState=hC.Detection,this._rightFootState=hC.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=UC.Right);var t=null;return(t=e==UC.Right?this._poseManager_R.getInterpolatedPose():this._poseManager_L.getInterpolatedPose())?t.getPosition():null},e.prototype.getRotation=function(e){void 0===e&&(e=UC.Right);var t=null;return(t=e==UC.Right?this._poseManager_R.getInterpolatedPose():this._poseManager_L.getInterpolatedPose())?t.getRotation():null},e.prototype.getPose=function(e){return void 0===e&&(e=UC.Right),e==UC.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==hC.Tracking&&this._leftFootState==hC.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=lC(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=lC(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==hC.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=lC(u),this._rightFootMask&&pC(this._rightFootMask,new Float32Array(r),n,new Float32Array([t,e]),u)}else this._leftFootState==hC.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=lC(u))[3]=-u[3],u[4]=-u[4],u[5]=-u[5]+(r[0]-1),this._leftFootMask&&pC(this._leftFootMask,new Float32Array(r),n,new Float32Array([t,e]),u));return n},e.prototype.getInterpolatedPose=function(e){return void 0===e&&(e=UC.Right),e==UC.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({},eC),n):eC,(null===(o=null==n?void 0:n.wasmBackend)||void 0===o?void 0:o.enable)?(QA({"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=UC.Both),this._poseManager_R=new zC(this._videoManager.getNbFramesDelay()),this._poseManager_R.setInterpolation(this._config.filteringShift),this._poseManager_R.setFilteringLevel(this._config.filteringLevel),this._poseManager_L=new zC(this._videoManager.getNbFramesDelay()),this._poseManager_L.setInterpolation(this._config.filteringShift),this._poseManager_L.setFilteringLevel(this._config.filteringLevel),a=new le(0),c=K(tT({locateFile:function(e,t){return w._config.poseEstimationWasmFilename||t+e}})).pipe(ye((function(){return a.next(1)}))),p=jI(this._config.modelFilename,HC),h=p.model$,d=p.progress$,f=jI(this._config.featuresFilename,HC),m=f.model$,g=f.progress$,y=LC(this._config.objContainer,!1),b=y.model$,_=y.progress$,x=H([a,d,g,_]).pipe(X((function(e){return e.reduce((function(t,n){return t+n/e.length}),0)})),X((function(e){return r&&r(e)}))).subscribe(),[4,Xv({poseModule:c,model:h,features:m,footObjModel:b}).pipe(X((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 WC(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0])),w._pose_L=new WC(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0])),w._trackHasHeatmaps=tC(w._footFeaturesConfig),w._initialized=!0})),te((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=WC.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!=hC.Detection&&this._leftFootState!=hC.Detection){var n=this.trackFeetFeaturesSync(e,this._leftFootState,this._rightFootState,this._leftFootState==hC.Detected?this._initShape:this._leftFootRecShape,this._rightFootState==hC.Detected?this._initShape:this._rightFootRecShape,this._leftFootVis,this._rightFootVis,this._leftFootOcclusions,this._rightFootOcclusions),r=wC(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=wC(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=kC(i,"RIGHT_FOOT"),l=new mC(0,0,e.width,e.height),c=new dC((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=hC.Tracking,t>o&&(this._rightFootState=hC.Detection)):this._rightFootState=hC.Detection,s=this._config.trackScoreThs,this._fastMovements_L&&(s=.1),o=this._reproj_t,this._fastMovements_L&&(o=this._reproj_fast_t),u=kC(i,"LEFT_FOOT");var p=new dC((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=hC.Tracking,t>o&&(this._leftFootState=hC.Detection)):this._leftFootState=hC.Detection,this._leftFootState==hC.Tracking&&this._rightFootState==hC.Tracking&&this.bothFeetSamePlace()&&(this._leftFootState=hC.Detection,this._rightFootState=hC.Detection)}else if(this._rightFootState!==hC.Detection&&this._leftFootState===hC.Detection){var h=this.trackFootFeaturesSync(e,this._rightFootState,this._rightFootState==hC.Detected?this._initShape:this._rightFootRecShape,this._rightFootVis,this._rightFootOcclusions,"RIGHT_FOOT");this._rightFootRecShape=h.refinedFeatures,this._rightFootOcclusions=h.occlusions,this._rightFootMask=h.mask,r=wC(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=kC(this._rightFootRecShape.length/2,"RIGHT_FOOT"),r.globalScore>=s&&r.totalVisible>=this._config.trackedNumKeypsThs?(t=this.computePoseSync(this._rightFootState,"RIGHT_FOOT"),this._rightFootState=hC.Tracking,t>o&&(this._rightFootState=hC.Detection)):this._rightFootState=hC.Detection;var d=this.detectFeetSync(e);this._initShape=d.refinedFeatures,a=wC(d.scores,"LEFT_FOOT",this._config.detectScoreThs),r=wC(d.scores,"RIGHT_FOOT",this._config.detectScoreThs);var f=!1;if(!this._fastMovements_R&&null!=this._cnnOutputDataInvMask){var m=OC(this._cnnOutputDataInvMask,this._footDetectorShape,!1);m[0];var g=wC(_=m[1],"LEFT_FOOT",this._config.detectScoreThs),y=wC(_,"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=hC.Detected):a.globalScore>=this._config.detectScoreThs&&(this._leftFootRecShape=d.refinedFeatures,this._leftFootState=hC.Detected)}else if(this._leftFootState!==hC.Detection&&this._rightFootState===hC.Detection){var b=this.trackFootFeaturesSync(e,this._leftFootState,this._leftFootState==hC.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=wC(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=kC(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=hC.Tracking,t>o&&(this._leftFootState=hC.Detection)):this._leftFootState=hC.Detection,d=this.detectFeetSync(e),this._initShape=d.refinedFeatures,r=wC(d.scores,"RIGHT_FOOT",this._config.detectScoreThs),a=wC(d.scores,"LEFT_FOOT",this._config.detectScoreThs),f=!1,!this._fastMovements_L&&null!=this._cnnOutputDataInvMask){var _,x=OC(this._cnnOutputDataInvMask,this._footDetectorShape,!1);x[0],g=wC(_=x[1],"LEFT_FOOT",this._config.detectScoreThs),y=wC(_,"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=hC.Detected):r.globalScore>=this._config.detectScoreThs&&(this._rightFootRecShape=d.refinedFeatures,this._rightFootState=hC.Detected)}else if(this._leftFootState===hC.Detection||this._rightFootState===hC.Detection){var w=this.detectFeetSync(e);if(this._initShape=w.refinedFeatures,a=wC(w.scores,"LEFT_FOOT",this._config.detectScoreThs),r=wC(w.scores,"RIGHT_FOOT",this._config.detectScoreThs),a.globalScore>=this._config.detectScoreThs&&(this._leftFootState=hC.Detected),r.globalScore>=this._config.detectScoreThs&&(this._rightFootState=hC.Detected),this._rightFootState!=hC.Detection&&this._leftFootState!=hC.Detection&&this.bothFeetSamePlaceInit()&&(this._rightFootState==hC.Detected?this._rightFootState=hC.Detection:this._leftFootState=hC.Detection),this._leftFootState==hC.Detected||this._rightFootState==hC.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)),CC(this._poseModule,e,this._hptrImageBuffer);var k=RC(this._poseModule,this._hptrImageBuffer,e.width,e.height);v(k),this._poseModule._free(k)}}this._leftFootState===hC.Detection&&(this._pose_L=new WC(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0]))),this._rightFootState==hC.Detection&&(this._pose_R=new WC(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=pf.cropAndResize(p,[o],[0],[this._footDetectorConfig.inHeight,this._footDetectorConfig.inWidth]),d=Oc(255),f=Qu(h,d),m=null;if(this._footToDetect==UC.Both&&(this._leftFootState===hC.Tracking||this._rightFootState===hC.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=xC(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===hC.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===hC.Tracking?"LEFT_FOOT":"RIGHT_FOOT"),y=jh(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=OC(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:vC(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!=hC.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=MC(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=$C(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=SC(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=cC(e,m,c);var g=PC(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=vC(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!=hC.Detected){var b=sC(g.scores[0],this._config.validTrackedKeypThs);y=TC(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!=hC.Detected&&n!=hC.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=MC(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=FC(this._poseModule,r,c),v=FC(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=$C(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=$C(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=SC(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=cC(e,E,this._simToImage_L),this._simToImage_R=SC(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=cC(e,N,this._simToImage_R),this._debug&&n!=hC.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=PC(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=vC(A.coordinates[0],this._simToImage_L,!0,this._footFeaturesConfig.outHeight),R=vC(A.coordinates[1],this._simToImage_R,!1,this._footFeaturesConfig.outHeight);return this._useRecursiveFilter&&t!=hC.Detected&&(C=TC(C,sC(A.scores[0],this._config.validTrackedKeypThs),c,s,0)),this._useRecursiveFilter&&n!=hC.Detected&&(R=TC(R,sC(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==hC.Detected||e==hC.Tracking){var s=1;e==hC.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=EC(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=EC(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=EC(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=EC(this._poseModule,f),y=this._activeIds.length):(p=EC(this._poseModule,m),h=EC(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 WC(new Float32Array(this._poseModule.HEAPF32.buffer,u,9),new Float32Array(this._poseModule.HEAPF32.buffer,u+9*this._float_size,3)):this._pose_R=new WC(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=xC(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=xC(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}(),jC={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},KC=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 qC(e){return e==VC.UpperBody||e==VC.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"}(VC||(VC={}));var XC="config.json",YC=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=hC.Detection,this._denseVertices=new Float32Array(0),this._bsCoefs=new Float32Array(0),this._geometryType=VC.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===hC.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=lC(a),this.isMirrored()&&(a[3]=-a[3],a[4]=-a[4],a[5]=-a[5]+(r[0]-1)),this._objectMask&&pC(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({},jC),n):jC,(null===(o=null==n?void 0:n.wasmBackend)||void 0===o?void 0:o.enable)?(QA({"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 zC(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 VC.Lamborghini;if("HORSE"===e)return VC.Horse;if("WATSON-CAN"===e)return VC.WatsonCan;if("MARTELL-BOTTLE"===e)return VC.MartellBottle;if("NECKLACE"===e)return VC.Necklace;if("WRIST"===e)return VC.Wrist;if("HAND"===e)return VC.Hand;if("UPPER-BODY"===e)return VC.UpperBody;if("FULL-BODY"===e)return VC.FullBody;if("CAN-KIVISENSE"===e)return VC.CanKivisense;if("TOY-TRUCK"===e)return VC.ToyTruck;if("CHIVAS"===e)return VC.Chivas;if("CHIVAS-LARGE"===e)return VC.ChivasLarge;if("LION"===e)return VC.Lion;if("BARTENDER"===e)return VC.Bartender;if("WCBOTTLE"===e)return VC.Wcbottle;if("EQA"===e)return VC.EQA;if("FACE"===e)return VC.Face}return VC.Lamborghini}(this._config.geometryToDetect),a=new le(0),c=K(tT({locateFile:function(e,t){return N._config.poseEstimationWasmFilename||t+e}})).pipe(ye((function(){return a.next(1)}))),p=jI(this._config.modelFilename,XC),h=p.model$,d=p.progress$,f=jI(this._config.featuresFilename,XC),m=f.model$,g=f.progress$,b=new le(0),"string"==typeof this._config.objContainer&&""===this._config.objContainer?(y=q({vertices:new Float32Array,uvs:new Float32Array,faces:new Uint16Array}),b.next(1)):(_=LC(this._config.objContainer,!1),x=_.model$,w=_.progress$,y=x,b=w),k=new le(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(ce(2),de((function(e){return q(Kk(new Uint8Array(e.response)))})),de((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),q(e[t[0]])}))):q(Kk(new Uint8Array(A))).pipe(de((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),q(e[t[0]])})))):(k.next(1),I=q(null)),new le(0),this._config.subTrackerFilename&&""!=this._config.subTrackerFilename?(S=jI(this._config.subTrackerFilename,XC),T=S.model$,S.progress$):T=q(null),E=H([a,d,k,g,b]).pipe(X((function(e){return e.reduce((function(t,n){return t+n/e.length}),0)})),X((function(e){return r&&r(e)}))).subscribe(),[4,Xv({poseModule:c,detectorModel:h,pdmModel:I,trackerModel:m,geometryObjModel:y,subTracker:T}).pipe(X((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=tC(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]))[3*4]+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==VC.Face?N._trackerOutDims[3]:-1,modelContent:N._bufferPdmModel,modelContentSize:o.byteLength,modelEncoding:N._geometryType==VC.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})),te((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=hC.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=WC.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=qC(this._geometryType)||this._geometryType==VC.Wrist||this._geometryType==VC.Hand||this._geometryType==VC.Face;if(this._trackingState===hC.Detection){var s=this._poseModule.cwrap("xzimgMatchRecKeypsInit","number",["number"]);null==this._hptrImageBuffer&&(this._hptrImageBuffer=this._poseModule._malloc(e.width*e.height*4)),CC(this._poseModule,e,this._hptrImageBuffer);var o=RC(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=aC(l,this._config.validDetectedKeypThs);this._visibility=c.visibilty,this._trackingState=hC.Detection,c.totalVisible>=this._config.detectNumKeypsThs&&c.globalScore>=this._config.detectScoreThs&&(this._geometryType==VC.Wrist&&(this._flipMode="","left"==(t=this._keyps2D,n=c.visibilty,(9==t.length/2?n[0]&&n[1]?fC.CreateFromPoints(new dC(t[0],t[9]),new dC(t[1],t[10])):fC.CreateFromPoints(new dC(t[1],t[10]),new dC(t[6],t[15])):fC.CreateFromPoints(new dC(t[30],t[211]),new dC(t[163],t[344]))).x>0?"left":"right")&&(this._flipMode="up_down")),a?this._trackingState=hC.Detected:(this._reprojError=this.computePoseSync(this._trackingState,this._geometryType),this._reprojError>0&&this._reprojError<this._config.reprojThs&&(this._trackingState=hC.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=aC(p.scores,this._config.validTrackedKeypThs),this._visibility=c.visibilty;var h=iC(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=hC.Detection:this._trackingState=hC.Tracking):this._trackingState=hC.Tracking,this._tfSubTracker&&this._trackingState==hC.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]=gC(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=gC(this._pose.project(new Float32Array([b,_,x]),WC.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=hC.Detection}(this._trackingState===hC.Detection||this._trackingState===hC.Detected&&a)&&(this._pose=new WC(new Float32Array([1,0,0,0,-1,0,0,0,-1]),new Float32Array([0,0,0])),this._pose.setTrackingState(hC.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=pf.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:oC(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!=hC.Detected){if(o=(s=MC(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==VC.FullBody?[7,8,9,10,13,14,15,16].forEach((function(e){u[e]=0})):a==VC.UpperBody?[7,8,9,10].forEach((function(e){u[e]=0})):a==VC.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==VC.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,WC.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,WC.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];qC(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 KC(t[0],t[u]),l[1]=n[3]>0&&n[4]>0?1:0,c[1]=new KC((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 KC((t[5]+t[6])/2,(t[5+u]+t[6+u])/2),l[3]=n[1]>0?1:0,c[3]=new KC(t[1],t[1+u]),l[4]=n[2]>0?1:0,c[4]=new KC(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 KC(t[0],t[u]),l[1]=n[p]>=0?1:0,c[1]=new KC(t[p],t[p+u]),l[2]=n[h]>=0?1:0,c[2]=new KC(t[h],t[h+u]),l[3]=n[1]>0?1:0,c[3]=new KC(t[1],t[1+u]),l[4]=n[2]>0?1:0,c[4]=new KC(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 KC(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 KC(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==hC.Detected||this._fastMvt?null:this._simCropToImage):a==VC.Face?this._simCropToImage=function(e,t,n,r,a){var s=e.length/2,o=rC(e,t,s),i=new dC((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 dC(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 dC(e[8],e[8+s]),d=new dC(e[13],e[13+s]);21==s&&(h=new dC(e[10],e[10+s]),d=new dC(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 dC(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 dC(.5*(e[0]+e[1]),.5*(e[0+s]+e[1+s])),y=3,b=4):_=new dC(e[g],e[g+s]);var x=new dC(.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 dC((_.x+x.x)/2,(_.y+x.y)/2);var w=0;for(f=0;f<s;f++)m=new dC(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 mC(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==hC.Detected||this._fastMvt?null:this._simCropToImage,this._config.normMode):a==VC.Wrist?this._simCropToImage=function(e,t,n,r,a){var s=e.length/2,o=rC(e,t,s),i=iC("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=_C(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==hC.Detected||this._fastMvt?null:this._simCropToImage,this._config.normMode):a==VC.Hand?this._simCropToImage=function(e,t,n,r,a){var s=e.length/2,o=rC(e,t,s),i=Math.max(o[1]-o[0],o[3]-o[2]),u=uC("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==hC.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=uC(a,e))[0],o[1],s=o[2]),i=nC(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==hC.Detected||this._fastMvt?null:this._simCropToImage,a,c);var _=new ImageData(this._trackerConfig.inWidth,this._trackerConfig.inHeight);_=cC(e,_,this._simCropToImage);var x=PC(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=oC(x.coordinates[0],this._simCropToImage,this._flipMode,new Int32Array([this._trackerConfig.outHeight,this._trackerConfig.outWidth]));if(t!=hC.Detected){var v=sC(x.scores[0],this._config.validTrackedKeypThs);if(a==VC.Face&&!this._nonRigidInitialized){var k=this._pose.project(this._keypsVts,WC.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=gC(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=yC(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=[cC(e,new ImageData(this._subTrackerConfig.inWidth,this._subTrackerConfig.inHeight),a)];if(this._config.subTrackerSymmetric&&this._config.subTrackerSymmetricIds){var i=yC(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([cC(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=PC(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]=gC(e,n,r._subTrackerCropKeyps[t],r._subTrackerVis[t],0):r._subTrackerCropKeyps=r._subTrackerCropKeyps.concat([e]);var a=oC(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&&(qC(t)||t==VC.Wrist||t==VC.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==hC.Detection){var s=0,o=0,i=t==VC.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 WC(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==hC.Detected||e==hC.Tracking){s=0,o=e!=hC.Tracking||this._resetPose?0:1,this._resetPose=!1,i=t==VC.Hand||t==VC.Necklace||t==VC.Lamborghini?3:1,u=t==VC.Hand||t==VC.Necklace||t==VC.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 WC(_,x);var w=this._pose.project(this._keypsVts,WC.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==VC.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=qC(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==hC.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==VC.Face&&(l=25),t==VC.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 WC(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})()));