@nuralogix.ai/awc-tfjs-face-tracker
Version:
Anura Web Core TensorFlow.js Face Tracker Plugin
31 lines (27 loc) • 673 kB
JavaScript
/**
* @license
* Anura Web Core TensorFlow.js Face Tracker Plugin
* Copyright Nuralogix, 2022
* https://docs.deepaffex.ai/jsapiclient/
* Version: 1.0.0
* Published on 2022-05-18, 6:57:20 a.m. (EST)
*/
/**
* @license
* Copyright 2022 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
export const version = "1.0.0";
export const faceTrackerName = "TFjs_WebGL_FaceTracker";
export const workerCode = "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)}class t{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 n{refCount(e){return r(\"refCount\")}incRef(e){return r(\"incRef\")}timerAvailable(){return!0}time(e){return r(\"time\")}read(e){return r(\"read\")}readSync(e){return r(\"readSync\")}readToGPU(e,t){return r(\"readToGPU\")}numDataIds(){return r(\"numDataIds\")}disposeData(e,t){return r(\"disposeData\")}write(e,t,n){return r(\"write\")}move(e,t,n,a,s){return r(\"move\")}memory(){return r(\"memory\")}floatPrecision(){return r(\"floatPrecision\")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return r(\"dispose\")}}function r(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 a(e,t,n){return Math.max(e,Math.min(t,n))}function s(e){return e%2==0?e:e+1}function o(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function i(e,t){if(!e)throw new Error(\"string\"==typeof t?t:t())}function u(e,t,n=\"\"){i(d(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function l(e){i(null!=e,(()=>\"The input to the tensor constructor must be a non-null value.\"))}function c(e,t=[],n=!1){if(null==t&&(t=[]),Array.isArray(e)||w(e)&&!n)for(let r=0;r<e.length;++r)c(e[r],t,n);else t.push(e);return t}function p(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 d(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 h(e){return e%1==0}function f(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function m(e,t){return t<=e.length?e:e+\" \".repeat(t-e.length)}function g(e,t=(e=>0),n){return new Promise(((r,a)=>{let s=0;const o=()=>{if(e())return void r();s++;const i=t(s);null!=n&&s>=n?a():setTimeout(o,i)};o()}))}function x(e,t){const n=t.length;return i((e=null==e?t.map(((e,t)=>t)):[].concat(e)).every((e=>e>=-n&&e<n)),(()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),i(e.every((e=>h(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function y(e,t){const n=[],r=[],a=null!=t&&Array.isArray(t)&&0===t.length,s=null==t||a?null:x(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 b(e,t){let n=null;if(null==e||\"float32\"===e)n=new Float32Array(t);else if(\"int32\"===e)n=new Int32Array(t);else{if(\"bool\"!==e)throw new Error(`Unknown data type ${e}`);n=new Uint8Array(t)}return n}function v(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 w(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}function $(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 N(e){return\"string\"==typeof e||e instanceof String}function k(e){return Array.isArray(e)?k(e[0]):e instanceof Float32Array?\"float32\":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?\"int32\":\"number\"==typeof e?\"float32\":N(e)?\"string\":function(e){return\"boolean\"==typeof e}(e)?\"bool\":\"float32\"}function C(e){return!!(e&&e.constructor&&e.call&&e.apply)}function T(e,t){for(let n=t;n<e;++n)if(e%n==0)return n;return e}function I(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 S(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]=S(e+t*i,o,n,r)}return a}function E(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 S(0,e,t,n)}function R(e,t){const n=_(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}function _(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 A(e){e.forEach((t=>{i(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function O(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 D(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 F(e){return e&&e.then&&\"function\"==typeof e.then}class M{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=L,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(P().getBool(\"IS_TEST\")||P().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];P().getBool(\"IS_TEST\")||P().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(F(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(null==this.flagRegistry[e])throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(null==this.flagRegistry[e])throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(void 0===this.global||void 0===this.global.location||void 0===this.global.location.search)return;const e=this.getQueryParams(this.global.location.search);if(\"tfjsflags\"in e){e.tfjsflags.split(\",\").forEach((e=>{const[t,n]=e.split(\":\");this.urlFlags[t]=function(e,t){if(\"true\"===(t=t.toLowerCase())||\"false\"===t)return\"true\"===t;if(\"\"+ +t===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}(t,n)}))}}}function L(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 P(){return V}let B,V=null;function U(){if(null==B){let e;if(\"undefined\"!=typeof window)e=window;else if(\"undefined\"!=typeof global)e=global;else if(\"undefined\"!=typeof process)e=process;else{if(\"undefined\"==typeof self)throw new Error(\"Could not find a global object\");e=self}B=e}return B}function W(e,t){const n=function(){const e=U();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)}}function z(...e){P().getBool(\"IS_TEST\")||P().getBool(\"PROD\")||console.warn(...e)}const G=W(\"kernelRegistry\",(()=>new Map)),H=W(\"gradRegistry\",(()=>new Map));function j(e,t){const n=Y(e,t);return G.get(n)}function K(e){return H.get(e)}function q(e){const t=G.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 X(e){const{kernelName:t,backendName:n}=e,r=Y(t,n);G.has(r)&&z(`The kernel '${t}' for backend '${n}' is already registered`),G.set(r,e)}function Y(e,t){return`${t}_${e}`}\"undefined\"!=typeof globalThis?globalThis:\"undefined\"!=typeof window?window:\"undefined\"!=typeof global?global:\"undefined\"!=typeof self&&self;var Q=J,Z=null;try{Z=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 J(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function ee(e){return!0===(e&&e.__isLong__)}J.prototype.__isLong__,Object.defineProperty(J.prototype,\"__isLong__\",{value:!0}),J.isLong=ee;var te={},ne={};function re(e,t){var n,r,a;return t?(a=0<=(e>>>=0)&&e<256)&&(r=ne[e])?r:(n=se(e,(0|e)<0?-1:0,!0),a&&(ne[e]=n),n):(a=-128<=(e|=0)&&e<128)&&(r=te[e])?r:(n=se(e,e<0?-1:0,!1),a&&(te[e]=n),n)}function ae(e,t){if(isNaN(e))return t?fe:he;if(t){if(e<0)return fe;if(e>=ce)return be}else{if(e<=-pe)return ve;if(e+1>=pe)return ye}return e<0?ae(-e,t).neg():se(e%le|0,e/le|0,t)}function se(e,t,n){return new J(e,t,n)}J.fromInt=re,J.fromNumber=ae,J.fromBits=se;var oe=Math.pow;function ie(e,t,n){if(0===e.length)throw Error(\"empty string\");if(\"NaN\"===e||\"Infinity\"===e||\"+Infinity\"===e||\"-Infinity\"===e)return he;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 ie(e.substring(1),t,n).neg();for(var a=ae(oe(n,8)),s=he,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=ae(oe(n,i));s=s.mul(l).add(ae(u))}else s=(s=s.mul(a)).add(ae(u))}return s.unsigned=t,s}function ue(e,t){return\"number\"==typeof e?ae(e,t):\"string\"==typeof e?ie(e,t):se(e.low,e.high,\"boolean\"==typeof t?t:e.unsigned)}J.fromString=ie,J.fromValue=ue;var le=4294967296,ce=le*le,pe=ce/2,de=re(1<<24),he=re(0);J.ZERO=he;var fe=re(0,!0);J.UZERO=fe;var me=re(1);J.ONE=me;var ge=re(1,!0);J.UONE=ge;var xe=re(-1);J.NEG_ONE=xe;var ye=se(-1,2147483647,!1);J.MAX_VALUE=ye;var be=se(-1,-1,!0);J.MAX_UNSIGNED_VALUE=be;var ve=se(0,-2147483648,!1);J.MIN_VALUE=ve;var we=J.prototype;we.toInt=function(){return this.unsigned?this.low>>>0:this.low},we.toNumber=function(){return this.unsigned?(this.high>>>0)*le+(this.low>>>0):this.high*le+(this.low>>>0)},we.toString=function(e){if((e=e||10)<2||36<e)throw RangeError(\"radix\");if(this.isZero())return\"0\";if(this.isNegative()){if(this.eq(ve)){var t=ae(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=ae(oe(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}},we.getHighBits=function(){return this.high},we.getHighBitsUnsigned=function(){return this.high>>>0},we.getLowBits=function(){return this.low},we.getLowBitsUnsigned=function(){return this.low>>>0},we.getNumBitsAbs=function(){if(this.isNegative())return this.eq(ve)?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},we.isZero=function(){return 0===this.high&&0===this.low},we.eqz=we.isZero,we.isNegative=function(){return!this.unsigned&&this.high<0},we.isPositive=function(){return this.unsigned||this.high>=0},we.isOdd=function(){return 1==(1&this.low)},we.isEven=function(){return 0==(1&this.low)},we.equals=function(e){return ee(e)||(e=ue(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},we.eq=we.equals,we.notEquals=function(e){return!this.eq(e)},we.neq=we.notEquals,we.ne=we.notEquals,we.lessThan=function(e){return this.comp(e)<0},we.lt=we.lessThan,we.lessThanOrEqual=function(e){return this.comp(e)<=0},we.lte=we.lessThanOrEqual,we.le=we.lessThanOrEqual,we.greaterThan=function(e){return this.comp(e)>0},we.gt=we.greaterThan,we.greaterThanOrEqual=function(e){return this.comp(e)>=0},we.gte=we.greaterThanOrEqual,we.ge=we.greaterThanOrEqual,we.compare=function(e){if(ee(e)||(e=ue(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},we.comp=we.compare,we.negate=function(){return!this.unsigned&&this.eq(ve)?ve:this.not().add(me)},we.neg=we.negate,we.add=function(e){ee(e)||(e=ue(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,se((c&=65535)<<16|(p&=65535),(u&=65535)<<16|(l&=65535),this.unsigned)},we.subtract=function(e){return ee(e)||(e=ue(e)),this.add(e.neg())},we.sub=we.subtract,we.multiply=function(e){if(this.isZero())return he;if(ee(e)||(e=ue(e)),Z)return se(Z.mul(this.low,this.high,e.low,e.high),Z.get_high(),this.unsigned);if(e.isZero())return he;if(this.eq(ve))return e.isOdd()?ve:he;if(e.eq(ve))return this.isOdd()?ve:he;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(de)&&e.lt(de))return ae(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,d=0;return p+=(d+=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,se((p&=65535)<<16|(d&=65535),(l&=65535)<<16|(c&=65535),this.unsigned)},we.mul=we.multiply,we.divide=function(e){if(ee(e)||(e=ue(e)),e.isZero())throw Error(\"division by zero\");var t,n,r;if(Z)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?se((this.unsigned?Z.div_u:Z.div_s)(this.low,this.high,e.low,e.high),Z.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?fe:he;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return fe;if(e.gt(this.shru(1)))return ge;r=fe}else{if(this.eq(ve))return e.eq(me)||e.eq(xe)?ve:e.eq(ve)?me:(t=this.shr(1).div(e).shl(1)).eq(he)?e.isNegative()?me:xe:(n=this.sub(e.mul(t)),r=t.add(n.div(e)));if(e.eq(ve))return this.unsigned?fe:he;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=he}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:oe(2,a-48),o=ae(t),i=o.mul(e);i.isNegative()||i.gt(n);)i=(o=ae(t-=s,this.unsigned)).mul(e);o.isZero()&&(o=me),r=r.add(o),n=n.sub(i)}return r},we.div=we.divide,we.modulo=function(e){return ee(e)||(e=ue(e)),Z?se((this.unsigned?Z.rem_u:Z.rem_s)(this.low,this.high,e.low,e.high),Z.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},we.mod=we.modulo,we.rem=we.modulo,we.not=function(){return se(~this.low,~this.high,this.unsigned)},we.and=function(e){return ee(e)||(e=ue(e)),se(this.low&e.low,this.high&e.high,this.unsigned)},we.or=function(e){return ee(e)||(e=ue(e)),se(this.low|e.low,this.high|e.high,this.unsigned)},we.xor=function(e){return ee(e)||(e=ue(e)),se(this.low^e.low,this.high^e.high,this.unsigned)},we.shiftLeft=function(e){return ee(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?se(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):se(0,this.low<<e-32,this.unsigned)},we.shl=we.shiftLeft,we.shiftRight=function(e){return ee(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?se(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):se(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},we.shr=we.shiftRight,we.shiftRightUnsigned=function(e){if(ee(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?se(this.low>>>e|t<<32-e,t>>>e,this.unsigned):se(32===e?t:t>>>e-32,0,this.unsigned)},we.shru=we.shiftRightUnsigned,we.shr_u=we.shiftRightUnsigned,we.toSigned=function(){return this.unsigned?se(this.low,this.high,!1):this},we.toUnsigned=function(){return this.unsigned?this:se(this.low,this.high,!0)},we.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},we.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]},we.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]},J.fromBytes=function(e,t,n){return n?J.fromBytesLE(e,t):J.fromBytesBE(e,t)},J.fromBytesLE=function(e,t){return new J(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},J.fromBytesBE=function(e,t){return new J(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};const $e=Q||e({__proto__:null,default:Q},[Q]);function Ne(e){return $e.fromString(e,!0,16)}const ke=Ne(\"c3a5c85c97cb3127\"),Ce=Ne(\"b492b66fbe98f273\"),Te=Ne(\"9ae16a3b2f90404f\");function Ie(e){return e.xor(e.shru(47))}function Se(e,t,n){const r=e.slice(t,t+n);return $e.fromBytes(Array.from(r),!0,!0)}function Ee(e,t){return Se(e,t,8)}function Re(e,t){return Se(e,t,4)}function _e(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function Ae(e,t,n=Ne(\"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 Oe(e,t,n,r){return function(e,t,n,r,a,s){a=a.add(e),s=_e(s.add(a).add(r),21);const o=a;return a=(a=a.add(t)).add(n),s=s.add(_e(a,44)),[a.add(r),s.add(o)]}(Ee(e,t),Ee(e,t+8),Ee(e,t+16),Ee(e,t+24),n,r)}function De(e,t=e.length){const n=$e.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=Te.add(2*t),r=Ee(e,0).add(Te),a=Ee(e,t-8);return Ae(_e(a,37).mul(n).add(r),_e(r,25).add(a).mul(n),n)}if(t>=4){const n=Te.add(2*t);return Ae(Re(e,0).shl(3).add(t),Re(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),r=t+(e[t-1]<<2);return Ie(Te.mul(n).xor(ke.mul(r))).mul(Te)}return Te}(e,t):function(e,t=e.length){const n=Te.add(2*t),r=Ee(e,0).mul(Ce),a=Ee(e,8),s=Ee(e,t-8).mul(n),o=Ee(e,t-16).mul(Te);return Ae(_e(r.add(a),43).add(_e(s,30)).add(o),r.add(_e(a.add(Te),18)).add(s),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=Te.add(2*t),r=Ee(e,0).mul(Te),a=Ee(e,8),s=Ee(e,t-8).mul(n),o=Ee(e,t-16).mul(Te),i=_e(r.add(a),43).add(_e(s,30)).add(o),u=Ae(i,r.add(_e(a.add(Te),18)).add(s),n),l=Ee(e,16).mul(n),c=Ee(e,24),p=i.add(Ee(e,t-32)).mul(n),d=u.add(Ee(e,t-24)).mul(n);return Ae(_e(l.add(c),43).add(_e(p,30)).add(d),l.add(_e(c.add(r),18)).add(p),n)}(e,t);let r=n,a=n.mul(Ce).add(113),s=Ie(a.mul(Te).add(113)).mul(Te),o=[$e.UZERO,$e.UZERO],i=[$e.UZERO,$e.UZERO];r=r.mul(Te).add(Ee(e,0));let u=0;const l=64*(t-1>>6),c=l+(t-1&63)-63;do{r=_e(r.add(a).add(o[0]).add(Ee(e,u+8)),37).mul(Ce),a=_e(a.add(o[1]).add(Ee(e,u+48)),42).mul(Ce),r=r.xor(i[1]),a=a.add(o[0]).add(Ee(e,u+40)),s=_e(s.add(i[0]),33).mul(Ce),o=Oe(e,u,o[1].mul(Ce),r.add(i[0])),i=Oe(e,u+32,s.add(i[1]),a.add(Ee(e,u+16))),[s,r]=[r,s],u+=64}while(u!==l);const p=Ce.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=_e(r.add(a).add(o[0]).add(Ee(e,u+8)),37).mul(p),a=_e(a.add(o[1]).add(Ee(e,u+48)),42).mul(p),r=r.xor(i[1].mul(9)),a=a.add(o[0].mul(9).add(Ee(e,u+40))),s=_e(s.add(i[0]),33).mul(p),o=Oe(e,u,o[1].mul(p),r.add(i[0])),i=Oe(e,u+32,s.add(i[1]),a.add(Ee(e,u+16))),[s,r]=[r,s],Ae(Ae(o[0],i[0],p).add(Ie(a).mul(ke)).add(s),Ae(o[1],i[1],p).add(r),p)}function Fe(e,t){return\"string\"===t?Pe(e):Me([e],t)}function Me(e,t){if(\"string\"===t)throw new Error(\"Cannot convert a string[] to a TypedArray\");if(Array.isArray(e)&&(e=c(e)),P().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 Le(){return P().platform.now()}function Pe(e,t=\"utf-8\"){return t=t||\"utf-8\",P().platform.encode(e,t)}function Be(e,t=\"utf-8\"){return t=t||\"utf-8\",P().platform.decode(e,t)}class Ve{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new We)}profileKernel(e,t,n){let r;const a=()=>{r=n()};let s;const o=Le();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(a);else{a();for(const e of r)e.dataSync();s=Promise.resolve({kernelMs:Le()-o})}if(P().getBool(\"CHECK_COMPUTATION_FOR_ERRORS\"))for(let t=0;t<r.length;t++){const n=r[t];n.data().then((t=>{Ue(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 Ue(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 We{logKernelProfile(e,t,n,r,a,s){const o=\"number\"==typeof r?m(`${r}ms`,9):r.error,i=m(e,25),u=t.rank,l=t.size,c=m(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 ze(e,t,n,r){const a=I(t),s=function(e,t,n,r){const a=p(t),s=r[r.length-1],o=new Array(s).fill(0),i=t.length,u=\"complex64\"===n?Ke(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],Ge(u[t+e],0,n).length)}return o}(e,t,n,a),o=t.length,i=je(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 Ge(e,t,n){let r;return r=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:N(e)?`'${e}'`:\"bool\"===n?He(e):parseFloat(e.toFixed(7)).toString(),m(r,t)}function He(e){return 0===e?\"false\":\"true\"}function je(e,t,n,r,a,s=!0){const o=\"complex64\"===n?2:1,i=t[0],u=t.length;if(0===u){if(\"complex64\"===n){return[Ge(Ke(e)[0],0,n)]}return\"bool\"===n?[He(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=Ke(r),s=Ke(s)),[\"[\"+r.map(((e,t)=>Ge(e,a[t],n))).join(\", \")+\", ..., \"+s.map(((e,t)=>Ge(e,a[i-3+t],n))).join(\", \")+\"]\"]}return[\"[\"+(\"complex64\"===n?Ke(e):Array.from(e)).map(((e,t)=>Ge(e,a[t],n))).join(\", \")+\"]\"]}const l=t.slice(1),c=r.slice(1),p=r[0]*o,d=[];if(i>20){for(let t=0;t<3;t++){const r=t*p,s=r+p;d.push(...je(e.slice(r,s),l,n,c,a,!1))}d.push(\"...\");for(let t=i-3;t<i;t++){const r=t*p,s=r+p;d.push(...je(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;d.push(...je(e.slice(r,s),l,n,c,a,t===i-1))}const h=2===u?\",\":\"\";d[0]=\"[\"+d[0]+h;for(let e=1;e<d.length-1;e++)d[e]=\" \"+d[e]+h;let f=\",\\n\";for(let e=2;e<u;e++)f+=\"\\n\";return d[d.length-1]=\" \"+d[d.length-1]+\"]\"+(s?\"\":f),d}function Ke(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class qe{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=p(e),null!=n){const e=n.length;i(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||v(t,this.size),this.strides=I(e)}set(e,...t){0===t.length&&(t=[0]),i(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 Xe().makeTensor(this.values,this.shape,this.dtype)}}let Xe=null,Ye=null;class Qe{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||\"float32\",this.size=p(e),this.strides=I(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 Ye.buffer(this.shape,this.dtype,e)}bufferSync(){return Ye.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return E(this.shape,e,\"complex64\"===this.dtype)}arraySync(){return E(this.shape,this.dataSync(),\"complex64\"===this.dtype)}async data(){this.throwIfDisposed();const e=Xe().read(this.dataId);if(\"string\"===this.dtype){const t=await e;try{return t.map((e=>Be(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(),Xe().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=Xe().readSync(this.dataId);if(\"string\"===this.dtype)try{return e.map((e=>Be(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 Xe().read(this.dataId);return\"string\"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Xe().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error(\"Tensor is disposed.\")}print(e=!1){return Ye.print(this,e)}clone(){return this.throwIfDisposed(),Ye.clone(this)}toString(e=!1){return ze(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Ye.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Xe().makeVariable(this,e,t,n)}}Object.defineProperty(Qe,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),W(\"Tensor\",(()=>Qe));class Ze extends Qe{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(!d(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Xe().disposeTensor(this),this.dataId=e.dataId,Xe().incRef(this,null)}dispose(){Xe().disposeVariable(this),this.isDisposedInternal=!0}}var Je,et,tt,nt,rt;Object.defineProperty(Ze,Symbol.hasInstance,{value:e=>e instanceof Qe&&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\"}(Je||(Je={})),function(e){e.float32=\"float32\",e.int32=\"int32\",e.bool=\"int32\",e.complex64=\"complex64\"}(et||(et={})),function(e){e.float32=\"float32\",e.int32=\"int32\",e.bool=\"bool\",e.complex64=\"complex64\"}(tt||(tt={})),function(e){e.float32=\"float32\",e.int32=\"float32\",e.bool=\"float32\",e.complex64=\"complex64\"}(nt||(nt={})),function(e){e.float32=\"complex64\",e.int32=\"complex64\",e.bool=\"complex64\",e.complex64=\"complex64\"}(rt||(rt={}));const at={float32:nt,int32:et,bool:tt,complex64:rt};function st(e,t){if(\"string\"===e||\"string\"===t){if(\"string\"===e&&\"string\"===t)return\"string\";throw new Error(`Can not upcast ${e} with ${t}`)}return at[e][t]}function ot(e){return st(e,\"int32\")}function it(e,t){if(e.dtype===t.dtype)return[e,t];const n=st(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function ut(e){const t=[];return lt(e,t,new Set),t}function lt(e,t,n){if(null==e)return;if(e instanceof Qe)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),lt(r,t,n))}}function ct(e){return null!=e.kernelName}class pt{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 dt{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new pt}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?(z(`${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 Ve(this.backendInstance),!0}setupRegisteredKernels(){q(this.backendName).forEach((e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){q(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 r=t.factory();if(!r||r instanceof n||\"function\"!=typeof r.then)return this.registry[e]=r,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,n=r.then((n=>!(t<this.pendingBackendInitId)&&(this.registry[e]=n,this.pendingBackendInit=null,!0))).catch((n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,z(`Initialization of backend ${e} failed`),z(n.stack||n.message)),!1)));return this.pendingBackendInit=n,{success:n,asyncInit:!0}}}catch(t){return z(`Initialization of backend ${e} failed`),z(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 dt.nextTensorId++}nextVariableId(){return dt.nextVariableId++}clone(e){const t=ft.runKernel(\"Identity\",{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e},n={dtype:\"float32\"};return ft.runKernel(\"Cast\",t,n)}})),[],{}),t}runKernel(e,t,n){null==this.backendName&&this.backend;if(!(null!=j(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,u;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const l=ct(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:\"\";if(ct(e)){const{kernelName:t,inputs:a,attrs:s}=e;null==this.backendName&&this.backend;const l=j(t,this.backendName);i(null!=l,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),o=()=>{const e=this.backend.numDataIds();u=l.kernelFunc({inputs:a,attrs:s,backend:this.backend});const o=Array.isArray(u)?u:[u];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,o);const i=o.map((e=>{if(null!=e.rank)return e;const{dataId:t,shape:n,dtype:r}=e;return this.makeTensorFromDataId(t,n,r)}));if(r){const e=this.getTensorsForGradient(t,a,i);n=this.saveTensorsForBackwardMode(e)}return i}}else{const{forwardFunc:t}=e,a=e=>{r&&(n=e.map((e=>this.keep(this.clone(e)))))};o=()=>{const e=this.backend.numDataIds();u=this.tidy((()=>t(this.backend,a)));const n=Array.isArray(u)?u:[u];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,e,n),n}}const{inputs:c,attrs:p}=e,d=ct(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(l,c,(()=>o())),this.ENV.getBool(\"DEBUG\")&&this.profiler.logKernelProfile(h),t=h.outputs):t=o()})),r&&this.addTapeNode(l,c,t,d,n,p),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map((e=>null!=c[e]?c[e].shape:null)),outputShapes:t.map((e=>e.shape)),kernelTimeMs:h.timeMs,extraInfo:h.extraInfo}),Array.isArray(u)?t:t[0]}saveTensorsForBackwardMode(e){const t=e.map((e=>this.keep(this.clone(e))));return t}getTensorsForGradient(e,t,n){const r=K(e);if(null!=r){const e=r.inputsToSave||[],a=r.outputsToSave||[];let s;r.saveAllInputs?(i(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&&N(e[0])&&(a=e.map((e=>Pe(e))));const s=r.write(a,t,n),o=new Qe(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=new Qe(t,n=n||\"float32\",e,this.nextTensorId());return this.trackTensor(a,r),a}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),null!=r&&r!==e.dtype&&(e=e.cast(r));const a=new Ze(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*$(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 Ze||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*$(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=K(e);null!=i&&(r=i.gradFunc),null!=r&&(o.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],r=_(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=ut(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(i(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)));i(a instanceof Qe,(()=>\"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=R(p(e),\"float32\");return ft.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(!d(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)),mt);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 i(C(e),(()=>\"The f passed in customGrad(f) must be a function.\")),(...t)=>{let n;i(t.every((e=>e instanceof Qe)),(()=>\"The args passed in customGrad(f)(x1, x2,...) must all be tensors\"));const r={};t.forEach(((e,t)=>{r[t]=e}));return this.runKernelFunc({forwardFunc:(r,a)=>(n=e(...t,a),i(n.value instanceof Qe,(()=>\"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor\")),i(C(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];i(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(...).\")),i(s.every((e=>e instanceof Qe)),(()=>\"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=Le(),n=await this.backend.time(e);return n.wallMs=Le()-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 pt;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 ht(){const e=U();if(null==e._tfengine){const t=new M(e);e._tfengine=new dt(t)}var t;return t=e._tfengine.ENV,V=t,Xe=()=>e._tfengine,e._tfengine}dt.nextTensorId=0,dt.nextVariableId=0;const ft=ht();function mt(e,t){const n={a:e,b:t};return ft.runKernel(\"Add\",n)}function gt(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)