UNPKG

shopar-plugin

Version:

Plugin for the Web that seamlessly integrates into your webpage to create embedded virtual try-on and 3D preview capabilities.

2 lines 421 kB
/*! For license information please see xzimg.js.LICENSE.txt */ !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