UNPKG

face-api.js

Version:

JavaScript API for face detection and face recognition in the browser with tensorflow.js

1 lines 664 kB
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t=t||self).faceapi=t.faceapi||{})}(this,function(c){"use strict";var r=function(t,e){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function t(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function y(i,a,s,u){return new(s=s||Promise)(function(t,e){function n(t){try{o(u.next(t))}catch(t){e(t)}}function r(t){try{o(u.throw(t))}catch(t){e(t)}}function o(e){e.done?t(e.value):new s(function(t){t(e.value)}).then(n,r)}o((u=u.apply(i,a||[])).next())})}function R(n,r){var o,i,a,t,s={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return t={next:e(0),throw:e(1),return:e(2)},"function"==typeof Symbol&&(t[Symbol.iterator]=function(){return this}),t;function e(e){return function(t){return function(e){if(o)throw new TypeError("Generator is already executing.");for(;s;)try{if(o=1,i&&(a=2&e[0]?i.return:e[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,e[1])).done)return a;switch(i=0,a&&(e=[2&e[0],a.value]),e[0]){case 0:case 1:a=e;break;case 4:return s.label++,{value:e[1],done:!1};case 5:s.label++,i=e[1],e=[0];continue;case 7:e=s.ops.pop(),s.trys.pop();continue;default:if(!(a=0<(a=s.trys).length&&a[a.length-1])&&(6===e[0]||2===e[0])){s=0;continue}if(3===e[0]&&(!a||e[1]>a[0]&&e[1]<a[3])){s.label=e[1];break}if(6===e[0]&&s.label<a[1]){s.label=a[1],a=e;break}if(a&&s.label<a[2]){s.label=a[2],s.ops.push(e);break}a[2]&&s.ops.pop(),s.trys.pop();continue}e=r.call(n,s)}catch(t){e=[6,t],i=0}finally{o=a=0}if(5&e[0])throw e[1];return{value:e[0]?e[1]:void 0,done:!0}}([e,t])}}}var o=(e.prototype.setPlatform=function(t,e){null!=this.platform&&console.warn("Platform "+this.platformName+" has already been set. Overwriting the platform with "+e+"."),this.platformName=t,this.platform=e},e.prototype.registerFlag=function(t,e,n){if(this.flagRegistry[t]={evaluationFn:e,setHook:n},null!=this.urlFlags[t]){var r=this.urlFlags[t];console.warn("Setting feature override from URL "+t+": "+r+"."),this.set(t,r)}},e.prototype.get=function(t){return t in this.flags||(this.flags[t]=this.evaluateFlag(t)),this.flags[t]},e.prototype.getNumber=function(t){return this.get(t)},e.prototype.getBool=function(t){return this.get(t)},e.prototype.getFlags=function(){return this.flags},Object.defineProperty(e.prototype,"features",{get:function(){return this.flags},enumerable:!0,configurable:!0}),e.prototype.set=function(t,e){if(null==this.flagRegistry[t])throw new Error("Cannot set flag "+t+" as it has not been registered.");this.flags[t]=e,null!=this.flagRegistry[t].setHook&&this.flagRegistry[t].setHook(e)},e.prototype.evaluateFlag=function(t){if(null==this.flagRegistry[t])throw new Error("Cannot evaluate flag '"+t+"': no evaluation function found.");return this.flagRegistry[t].evaluationFn()},e.prototype.setFlags=function(t){this.flags=Object.assign({},t)},e.prototype.reset=function(){this.flags={},this.urlFlags={},this.populateURLFlags()},e.prototype.populateURLFlags=function(){var o=this;if(void 0!==this.global&&void 0!==this.global.location&&void 0!==this.global.location.search){var t,r,e=(t=this.global.location.search,r={},t.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,function(t){for(var e=[],n=1;n<arguments.length;n++)e[n-1]=arguments[n];return function(t,e,n){t[decodeURIComponent(e)]=decodeURIComponent(n||"")}(r,e[0],e[1]),e.join("=")}),r);"tfjsflags"in e&&e.tfjsflags.split(",").forEach(function(t){var e=t.split(":"),n=e[0],r=e[1];o.urlFlags[n]=function(t,e){if("true"===(e=e.toLowerCase())||"false"===e)return"true"===e;if(""+ +e===e)return+e;throw new Error("Could not parse value flag value "+e+" for flag "+t+".")}(n,r)})}},e);function e(t){this.global=t,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}function _(){return i}var i=null,u=new Map,n=new Map;function g(t,e){var n=f(t,e);return u.get(n)}function l(t){return n.get(t)}function a(t){for(var e=u.entries(),n=[];;){var r=e.next(),o=r.done,i=r.value;if(o)break;var a=i[0],s=i[1];a.split("_")[0]===t&&n.push(s)}return n}function s(t){var e=t.kernelName,n=t.backendName,r=f(e,n);if(u.has(r))throw new Error("The kernel '"+e+"' for backend '"+n+"' is already registered");u.set(r,t)}function h(t){var e=t.kernelName;n.has(e)&&console.warn("Overriding the gradient for '"+e+"'"),n.set(e,t)}function f(t,e){return e+"_"+t}function p(t){for(var e=t.length,n=0,r=0;0<e;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n}function d(t,e,n){return Math.max(t,Math.min(e,n))}function E(t){return t%2==0?t:t+1}function v(t){for(var e=0,n=0;n<t.length;n++)e+=t[n];return e}function P(t,e){if(!t)throw new Error("string"==typeof e?e:e())}function x(t,e,n){void 0===n&&(n=""),P(A(t,e),function(){return n+" Shapes "+t+" and "+e+" must match"})}function m(t){P(null!=t,function(){return"The input to the tensor constructor must be a non-null value."})}function b(t,e,n){if(void 0===e&&(e=[]),void 0===n&&(n=!1),null==e&&(e=[]),Array.isArray(t)||z(t)&&!n)for(var r=0;r<t.length;++r)b(t[r],e,n);else e.push(t);return e}function L(t){if(0===t.length)return 1;for(var e=t[0],n=1;n<t.length;n++)e*=t[n];return e}function A(t,e){if(t===e)return!0;if(null==t||null==e)return!1;if(t.length!==e.length)return!1;for(var n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function B(t){return t%1==0}function w(t){if(null!=Math.tanh)return Math.tanh(t);if(t===1/0)return 1;if(t===-1/0)return-1;var e=Math.exp(2*t);return(e-1)/(e+1)}function C(t){var e=Math.ceil(Math.sqrt(t));return[e,Math.ceil(t/e)]}function I(t,e){return e<=t.length?t:t+" ".repeat(e-t.length)}function k(i,a,s){return void 0===a&&(a=function(t){return 0}),new Promise(function(e,n){var r=0,o=function(){if(i())e();else{var t=a(++r);null!=s&&s<=r?n():setTimeout(o,t)}};o()})}function S(t,e){for(var n=1,r=-1,o=0;o<t.length;++o)if(0<=t[o])n*=t[o];else if(-1===t[o]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+o);r=o}else if(t[o]<0)throw Error("Shapes can not be < 0. Found "+t[o]+" at dim "+o);if(-1===r){if(0<e&&e!==n)throw Error("Size("+e+") must match the product of shape "+t);return t}if(0===n)throw Error("Cannot infer the missing size in ["+t+"] when there are 0 elements");if(e%n!=0)throw Error("The implicit shape can't be a fractional number. Got "+e+" / "+n);var i=t.slice();return i[r]=e/n,i}function D(t,e){var n=e.length;return P((t=null==t?e.map(function(t,e){return e}):[].concat(t)).every(function(t){return-n<=t&&t<n}),function(){return"All values in axis param must be in range [-"+n+", "+n+") but got axis "+t}),P(t.every(function(t){return B(t)}),function(){return"All values in axis param must be integers but got axis "+t}),t.map(function(t){return t<0?n+t:t})}function T(t,e){for(var n=[],r=[],o=null!=e&&Array.isArray(e)&&0===e.length,i=null==e||o?null:D(e,t).sort(),a=0,s=0;s<t.length;++s){if(null!=i){if(i[a]===s&&1!==t[s])throw new Error("Can't squeeze axis "+s+" since its dim '"+t[s]+"' is not 1");(null==i[a]||i[a]>s)&&1===t[s]&&(n.push(t[s]),r.push(s)),i[a]<=s&&a++}1!==t[s]&&(n.push(t[s]),r.push(s))}return{newShape:n,keptDims:r}}function N(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else{if("bool"!==t)throw new Error("Unknown data type "+t);n=new Uint8Array(e)}return n}function F(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else if("bool"===t)n=new Uint8Array(e);else{if("string"!==t)throw new Error("Unknown data type "+t);n=new Array(e)}return n}function M(t,e){for(var n=0;n<t.length;n++){var r=t[n];if(isNaN(r)||!isFinite(r))throw Error("A tensor of type "+e+" being uploaded contains "+r+".")}}function O(t){return"bool"===t||"complex64"===t||"float32"===t||"int32"===t||"string"===t}function W(t,e){return!("complex64"===e||"float32"===e&&"complex64"!==t||"int32"===e&&"float32"!==t&&"complex64"!==t||"bool"===e&&"bool"===t)}function z(t){return t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array}function U(t){if("float32"===t||"int32"===t)return 4;if("complex64"===t)return 8;if("bool"===t)return 1;throw new Error("Unknown dtype "+t)}function V(t){if(null==t)return 0;var e=0;return t.forEach(function(t){return e+=t.length}),e}function G(t){return"string"==typeof t||t instanceof String}function H(t){return"boolean"==typeof t}function q(t){return"number"==typeof t}function j(t){return Array.isArray(t)?j(t[0]):t instanceof Float32Array?"float32":t instanceof Int32Array||t instanceof Uint8Array?"int32":q(t)?"float32":G(t)?"string":H(t)?"bool":"float32"}function K(t){return!!(t&&t.constructor&&t.call&&t.apply)}function X(t,e){for(var n=e;n<t;++n)if(t%n==0)return n;return t}function Y(t){var e=t.length;if(e<2)return[];var n=new Array(e-1);n[e-2]=t[e-1];for(var r=e-3;0<=r;--r)n[r]=n[r+1]*t[r+1];return n}function $(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=b(t)),n&&M(t,e),t instanceof Float32Array&&"float32"===e||t instanceof Int32Array&&"int32"===e||t instanceof Uint8Array&&"bool"===e)return t;if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"!==e)throw new Error("Unknown data type "+e);for(var r=new Uint8Array(t.length),o=0;o<r.length;++o)0!==Math.round(t[o])&&(r[o]=1);return r}function J(t,e){if(0===t.length)return e[0];var n=t.reduce(function(t,e){return t*e});if(0===n)return[];if(n!==e.length)throw new Error("["+t+"] does not match the input size.");return function t(e,n,r){var o=new Array;if(1===n.length)for(var i=n[0],a=0;a<i;a++)o[a]=r[e+a];else{i=n[0];var s=n.slice(1),u=s.reduce(function(t,e){return t*e});for(a=0;a<i;a++)o[a]=t(e+a*u,s,r)}return o}(0,t,e)}function Q(t,e){for(var n=Z(t,e),r=0;r<n.length;r++)n[r]=1;return n}function Z(t,e){if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e)return new Uint8Array(t);throw new Error("Unknown data type "+e)}function tt(){return _().platform.now()}function et(e){e.forEach(function(t){P(Number.isInteger(t)&&0<=t,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+e+"]."})})}function nt(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",_().platform.encode(t,e)}function rt(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",_().platform.decode(t,e)}function ot(t,e,n){if(0===e)return 0;if(1===e)return t[0];for(var r=t[t.length-1],o=0;o<t.length-1;++o)r+=n[o]*t[o];return r}function it(t,e,n){if(0===e)return[];if(1===e)return[t];for(var r=new Array(e),o=0;o<r.length-1;++o)r[o]=Math.floor(t/n[o]),t-=r[o]*n[o];return r[r.length-1]=t,r}var at=Object.freeze({shuffle:p,clamp:d,nearestLargerEven:E,sum:v,randUniform:function(t,e){var n=Math.random();return e*n+(1-n)*t},distSquared:function(t,e){for(var n=0,r=0;r<t.length;r++){var o=Number(t[r])-Number(e[r]);n+=o*o}return n},assert:P,assertShapesMatch:x,assertNonNull:m,flatten:b,sizeFromShape:L,isScalarShape:function(t){return 0===t.length},arraysEqual:A,isInt:B,tanh:w,sizeToSquarishShape:C,createShuffledIndices:function(t){for(var e=new Uint32Array(t),n=0;n<t;++n)e[n]=n;return p(e),e},rightPad:I,repeatedTry:k,inferFromImplicitShape:S,parseAxisParam:D,squeezeShape:T,getTypedArrayFromDType:N,getArrayFromDType:F,checkConversionForErrors:M,isValidDtype:O,hasEncodingLoss:W,isTypedArray:z,bytesPerElement:U,bytesFromStringArray:V,isString:G,isBoolean:H,isNumber:q,inferDtype:j,isFunction:K,nearestDivisor:X,computeStrides:Y,toTypedArray:$,toNestedArray:J,makeOnesTypedArray:Q,makeZerosTypedArray:Z,now:tt,assertNonNegativeIntegerDimensions:et,fetch:function(t,e){return _().platform.fetch(t,e)},encodeString:nt,decodeString:rt,locToIndex:ot,indexToLoc:it}),st=(ut.prototype.profileKernel=function(o,i,t){var e,a=this,s=this.backendTimer.time(function(){e=t()});return e.forEach(function(r){r.data().then(function(n){!function(t,e,n){if("float32"===e)for(var r=0;r<t.length;r++){var o=t[r];if(isNaN(o)||!isFinite(o))return console.warn("Found "+o+" in the result of '"+n+"'")}}(n,r.dtype,o),s.then(function(t){var e="";null!=t.getExtraProfileInfo&&(e=t.getExtraProfileInfo()),a.logger.logKernelProfile(o,r,n,t.kernelMs,i,e)})})}),e},ut);function ut(t,e){this.backendTimer=t,null==(this.logger=e)&&(this.logger=new ct)}var ct=(lt.prototype.logKernelProfile=function(t,e,n,r,o,i){var a="number"==typeof r?I(r+"ms",9):r.error,s=I(t,25),u=e.rank,c=e.size,l=I(e.shape.toString(),14),h="";for(var f in o){var p=o[f].shape||e.shape,d=p.length;h+=f+": "+d+"D "+(0<d?p:"")+" "}console.log("%c"+s+"\t%c"+a+"\t%c"+u+"D "+l+"\t%c"+c+"\t%c"+h+"\t%c"+i,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},lt);function lt(){}var ht=7;function ft(t,e,n){return I(Array.isArray(t)?parseFloat(t[0].toFixed(ht))+" + "+parseFloat(t[1].toFixed(ht))+"j":G(t)?"'"+t+"'":"bool"===n?pt(t):parseFloat(t.toFixed(ht)).toString(),e)}function pt(t){return 0===t?"false":"true"}function dt(t){for(var e=[],n=0;n<t.length;n+=2)e.push([t[n],t[n+1]]);return e}var vt=(xt.prototype.set=function(t){for(var e=this,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];0===n.length&&(n=[0]),P(n.length===this.rank,function(){return"The number of provided coordinates ("+n.length+") must match the rank ("+e.rank+")"});var o=this.locToIndex(n);this.values[o]=t},xt.prototype.get=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];0===t.length&&(t=[0]);for(var n=0,r=0,o=t;r<o.length;r++){var i=o[r];if(i<0||i>=this.shape[n]){var a="Requested out of range element at "+t+". Buffer shape="+this.shape;throw new Error(a)}n++}for(var s=t[t.length-1],u=0;u<t.length-1;++u)s+=this.strides[u]*t[u];return this.values[s]},xt.prototype.locToIndex=function(t){if(0===this.rank)return 0;if(1===this.rank)return t[0];for(var e=t[t.length-1],n=0;n<t.length-1;++n)e+=this.strides[n]*t[n];return e},xt.prototype.indexToLoc=function(t){if(0===this.rank)return[];if(1===this.rank)return[t];for(var e=new Array(this.shape.length),n=0;n<e.length-1;++n)e[n]=Math.floor(t/this.strides[n]),t-=e[n]*this.strides[n];return e[e.length-1]=t,e},Object.defineProperty(xt.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),xt.prototype.toTensor=function(){return mt().makeTensor(this.values,this.shape,this.dtype)},xt),mt=null,gt=null,yt=null;function xt(t,e,n){var r=this;if(this.dtype=e,this.shape=t.slice(),this.size=L(t),null!=n){var o=n.length;P(o===this.size,function(){return"Length of values '"+o+"' does not match the size inferred by the shape '"+r.size+"'."})}if("complex64"===e)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||F(e,this.size),this.strides=Y(t)}var bt=(wt.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},wt.prototype.asScalar=function(){return this.throwIfDisposed(),P(1===this.size,function(){return"The array must have only 1 element."}),this.reshape([])},wt.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size])},wt.prototype.as2D=function(t,e){return this.throwIfDisposed(),this.reshape([t,e])},wt.prototype.as3D=function(t,e,n){return this.throwIfDisposed(),this.reshape([t,e,n])},wt.prototype.as4D=function(t,e,n,r){return this.throwIfDisposed(),this.reshape([t,e,n,r])},wt.prototype.as5D=function(t,e,n,r,o){return this.throwIfDisposed(),this.reshape([t,e,n,r,o])},wt.prototype.asType=function(t){return this.throwIfDisposed(),gt.cast(this,t)},Object.defineProperty(wt.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),wt.prototype.buffer=function(){return y(this,void 0,void 0,function(){var e;return R(this,function(t){switch(t.label){case 0:return[4,this.data()];case 1:return e=t.sent(),[2,gt.buffer(this.shape,this.dtype,e)]}})})},wt.prototype.bufferSync=function(){return gt.buffer(this.shape,this.dtype,this.dataSync())},wt.prototype.array=function(){return y(this,void 0,void 0,function(){var e;return R(this,function(t){switch(t.label){case 0:return[4,this.data()];case 1:return e=t.sent(),[2,J(this.shape,e)]}})})},wt.prototype.arraySync=function(){return J(this.shape,this.dataSync())},wt.prototype.data=function(){return y(this,void 0,void 0,function(){var e,n;return R(this,function(t){switch(t.label){case 0:return this.throwIfDisposed(),e=mt().read(this.dataId),"string"!==this.dtype?[3,2]:[4,e];case 1:n=t.sent();try{return[2,n.map(function(t){return rt(t)})]}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}t.label=2;case 2:return[2,e]}})})},wt.prototype.dataSync=function(){this.throwIfDisposed();var t=mt().readSync(this.dataId);if("string"===this.dtype)try{return t.map(function(t){return rt(t)})}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return t},wt.prototype.bytes=function(){return y(this,void 0,void 0,function(){var e;return R(this,function(t){switch(t.label){case 0:return this.throwIfDisposed(),[4,mt().read(this.dataId)];case 1:return e=t.sent(),"string"===this.dtype?[2,e]:[2,new Uint8Array(e.buffer)]}})})},wt.prototype.dispose=function(){this.isDisposed||(mt().disposeTensor(this),this.isDisposedInternal=!0)},Object.defineProperty(wt.prototype,"isDisposed",{get:function(){return this.isDisposedInternal},enumerable:!0,configurable:!0}),wt.prototype.throwIfDisposed=function(){if(this.isDisposed)throw new Error("Tensor is disposed.")},wt.prototype.toFloat=function(){return this.asType("float32")},wt.prototype.toInt=function(){return this.asType("int32")},wt.prototype.toBool=function(){return this.asType("bool")},wt.prototype.print=function(t){return void 0===t&&(t=!1),gt.print(this,t)},wt.prototype.reshape=function(t){return this.throwIfDisposed(),gt.reshape(this,t)},wt.prototype.reshapeAs=function(t){return this.throwIfDisposed(),this.reshape(t.shape)},wt.prototype.expandDims=function(t){return void 0===t&&(t=0),gt.expandDims(this,t)},wt.prototype.cumsum=function(t,e,n){return void 0===t&&(t=0),void 0===e&&(e=!1),void 0===n&&(n=!1),gt.cumsum(this,t,e,n)},wt.prototype.squeeze=function(t){return this.throwIfDisposed(),gt.squeeze(this,t)},wt.prototype.clone=function(){return this.throwIfDisposed(),gt.clone(this)},wt.prototype.oneHot=function(t,e,n){return this.throwIfDisposed(),gt.oneHot(this,t,e,n)},wt.prototype.toString=function(t){return void 0===t&&(t=!1),function(t,e,n,r){var o=Y(e),i=function(t,e,n,r){var o=L(e),i=r[r.length-1],a=new Array(i).fill(0),s=e.length,u="complex64"===n?dt(t):t;if(1<s)for(var c=0;c<o/i;c++)for(var l=c*i,h=0;h<i;h++)a[h]=Math.max(a[h],ft(u[l+h],0,n).length);return a}(t,e,n,o),a=e.length,s=function t(e,n,r,o,i,a){void 0===a&&(a=!0);var s="complex64"===r?2:1,u=n[0],c=n.length;if(0===c)return"complex64"===r?[ft(dt(e)[0],0,r)]:"bool"===r?[pt(e[0])]:[e[0].toString()];if(1===c){if(20<u){var l=3*s,h=Array.from(e.slice(0,l)),f=Array.from(e.slice((u-3)*s,u*s));return"complex64"===r&&(h=dt(h),f=dt(f)),["["+h.map(function(t,e){return ft(t,i[e],r)}).join(", ")+", ..., "+f.map(function(t,e){return ft(t,i[u-3+e],r)}).join(", ")+"]"]}return["["+("complex64"===r?dt(e):Array.from(e)).map(function(t,e){return ft(t,i[e],r)}).join(", ")+"]"]}var p=n.slice(1),d=o.slice(1),v=o[0]*s,m=[];if(20<u){for(var g=0;g<3;g++){var y=(x=g*v)+v;m.push.apply(m,t(e.slice(x,y),p,r,d,i,!1))}for(m.push("..."),g=u-3;g<u;g++)y=(x=g*v)+v,m.push.apply(m,t(e.slice(x,y),p,r,d,i,g===u-1))}else for(g=0;g<u;g++){var x;y=(x=g*v)+v,m.push.apply(m,t(e.slice(x,y),p,r,d,i,g===u-1))}var b=2===c?",":"";for(m[0]="["+m[0]+b,g=1;g<m.length-1;g++)m[g]=" "+m[g]+b;var w=",\n";for(g=2;g<c;g++)w+="\n";return m[m.length-1]=" "+m[m.length-1]+"]"+(a?"":w),m}(t,e,n,o,i),u=["Tensor"];return r&&(u.push(" dtype: "+n),u.push(" rank: "+a),u.push(" shape: ["+e+"]"),u.push(" values:")),u.push(s.map(function(t){return" "+t}).join("\n")),u.join("\n")}(this.dataSync(),this.shape,this.dtype,t)},wt.prototype.tile=function(t){return this.throwIfDisposed(),gt.tile(this,t)},wt.prototype.gather=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),gt.gather(this,t,e)},wt.prototype.matMul=function(t,e,n){return void 0===e&&(e=!1),void 0===n&&(n=!1),this.throwIfDisposed(),gt.matMul(this,t,e,n)},wt.prototype.dot=function(t){return this.throwIfDisposed(),gt.dot(this,t)},wt.prototype.norm=function(t,e,n){return void 0===t&&(t="euclidean"),void 0===e&&(e=null),void 0===n&&(n=!1),this.throwIfDisposed(),gt.norm(this,t,e,n)},wt.prototype.slice=function(t,e){return this.throwIfDisposed(),gt.slice(this,t,e)},wt.prototype.reverse=function(t){return this.throwIfDisposed(),gt.reverse(this,t)},wt.prototype.concat=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),t instanceof wt&&(t=[t]),gt.concat([this].concat(t),e)},wt.prototype.split=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),gt.split(this,t,e)},wt.prototype.stack=function(t,e){return void 0===e&&(e=0),gt.stack([this,t],e)},wt.prototype.unstack=function(t){return void 0===t&&(t=0),gt.unstack(this,t)},wt.prototype.pad=function(t,e){return void 0===e&&(e=0),gt.pad(this,t,e)},wt.prototype.batchNormalization=function(t,e,n,r,o){return void 0===n&&(n=.001),yt("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon"),this.batchNorm(t,e,o,r,n)},wt.prototype.batchNorm=function(t,e,n,r,o){return void 0===o&&(o=.001),this.throwIfDisposed(),gt.batchNorm(this,t,e,n,r,o)},wt.prototype.all=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),gt.all(this,t,e)},wt.prototype.any=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),gt.any(this,t,e)},wt.prototype.logSumExp=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),gt.logSumExp(this,t,e)},wt.prototype.sum=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),gt.sum(this,t,e)},wt.prototype.prod=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),gt.prod(this,t,e)},wt.prototype.mean=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),gt.mean(this,t,e)},wt.prototype.min=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),gt.min(this,t,e)},wt.prototype.max=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),gt.max(this,t,e)},wt.prototype.argMin=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),gt.argMin(this,t)},wt.prototype.argMax=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),gt.argMax(this,t)},wt.prototype.cast=function(t){return this.throwIfDisposed(),gt.cast(this,t)},wt.prototype.add=function(t){return this.throwIfDisposed(),gt.add(this,t)},wt.prototype.addStrict=function(t){return this.throwIfDisposed(),gt.addStrict(this,t)},wt.prototype.atan2=function(t){return this.throwIfDisposed(),gt.atan2(this,t)},wt.prototype.sub=function(t){return this.throwIfDisposed(),gt.sub(this,t)},wt.prototype.subStrict=function(t){return this.throwIfDisposed(),gt.subStrict(this,t)},wt.prototype.pow=function(t){return this.throwIfDisposed(),gt.pow(this,t)},wt.prototype.powStrict=function(t){return this.throwIfDisposed(),gt.powStrict(this,t)},wt.prototype.mul=function(t){return this.throwIfDisposed(),gt.mul(this,t)},wt.prototype.mulStrict=function(t){return this.throwIfDisposed(),gt.mulStrict(this,t)},wt.prototype.div=function(t){return this.throwIfDisposed(),gt.div(this,t)},wt.prototype.divNoNan=function(t){return this.throwIfDisposed(),gt.divNoNan(this,t)},wt.prototype.floorDiv=function(t){return this.throwIfDisposed(),gt.floorDiv(this,t)},wt.prototype.divStrict=function(t){return this.throwIfDisposed(),gt.divStrict(this,t)},wt.prototype.minimum=function(t){return this.throwIfDisposed(),gt.minimum(this,t)},wt.prototype.minimumStrict=function(t){return this.throwIfDisposed(),gt.minimumStrict(this,t)},wt.prototype.maximum=function(t){return this.throwIfDisposed(),gt.maximum(this,t)},wt.prototype.maximumStrict=function(t){return this.throwIfDisposed(),gt.maximumStrict(this,t)},wt.prototype.mod=function(t){return this.throwIfDisposed(),gt.mod(this,t)},wt.prototype.modStrict=function(t){return this.throwIfDisposed(),gt.modStrict(this,t)},wt.prototype.squaredDifferenceStrict=function(t){return this.throwIfDisposed(),gt.squaredDifferenceStrict(this,t)},wt.prototype.transpose=function(t){return this.throwIfDisposed(),gt.transpose(this,t)},wt.prototype.notEqual=function(t){return this.throwIfDisposed(),gt.notEqual(this,t)},wt.prototype.notEqualStrict=function(t){return this.throwIfDisposed(),gt.notEqualStrict(this,t)},wt.prototype.less=function(t){return this.throwIfDisposed(),gt.less(this,t)},wt.prototype.lessStrict=function(t){return this.throwIfDisposed(),gt.lessStrict(this,t)},wt.prototype.equal=function(t){return this.throwIfDisposed(),gt.equal(this,t)},wt.prototype.equalStrict=function(t){return this.throwIfDisposed(),gt.equalStrict(this,t)},wt.prototype.lessEqual=function(t){return this.throwIfDisposed(),gt.lessEqual(this,t)},wt.prototype.lessEqualStrict=function(t){return this.throwIfDisposed(),gt.lessEqualStrict(this,t)},wt.prototype.greater=function(t){return this.throwIfDisposed(),gt.greater(this,t)},wt.prototype.greaterStrict=function(t){return this.throwIfDisposed(),gt.greaterStrict(this,t)},wt.prototype.greaterEqual=function(t){return this.throwIfDisposed(),gt.greaterEqual(this,t)},wt.prototype.greaterEqualStrict=function(t){return this.throwIfDisposed(),gt.greaterEqualStrict(this,t)},wt.prototype.logicalAnd=function(t){return this.throwIfDisposed(),gt.logicalAnd(this,t)},wt.prototype.logicalOr=function(t){return this.throwIfDisposed(),gt.logicalOr(this,t)},wt.prototype.logicalNot=function(){return this.throwIfDisposed(),gt.logicalNot(this)},wt.prototype.logicalXor=function(t){return this.throwIfDisposed(),gt.logicalXor(this,t)},wt.prototype.where=function(t,e){return this.throwIfDisposed(),gt.where(t,this,e)},wt.prototype.neg=function(){return this.throwIfDisposed(),gt.neg(this)},wt.prototype.ceil=function(){return this.throwIfDisposed(),gt.ceil(this)},wt.prototype.floor=function(){return this.throwIfDisposed(),gt.floor(this)},wt.prototype.sign=function(){return this.throwIfDisposed(),gt.sign(this)},wt.prototype.isNaN=function(){return this.throwIfDisposed(),gt.isNaN(this)},wt.prototype.isInf=function(){return this.throwIfDisposed(),gt.isInf(this)},wt.prototype.isFinite=function(){return this.throwIfDisposed(),gt.isFinite(this)},wt.prototype.exp=function(){return this.throwIfDisposed(),gt.exp(this)},wt.prototype.expm1=function(){return this.throwIfDisposed(),gt.expm1(this)},wt.prototype.log=function(){return this.throwIfDisposed(),gt.log(this)},wt.prototype.log1p=function(){return this.throwIfDisposed(),gt.log1p(this)},wt.prototype.sqrt=function(){return this.throwIfDisposed(),gt.sqrt(this)},wt.prototype.rsqrt=function(){return this.throwIfDisposed(),gt.rsqrt(this)},wt.prototype.square=function(){return this.throwIfDisposed(),gt.square(this)},wt.prototype.reciprocal=function(){return this.throwIfDisposed(),gt.reciprocal(this)},wt.prototype.abs=function(){return this.throwIfDisposed(),gt.abs(this)},wt.prototype.clipByValue=function(t,e){return this.throwIfDisposed(),gt.clipByValue(this,t,e)},wt.prototype.relu=function(){return this.throwIfDisposed(),gt.relu(this)},wt.prototype.relu6=function(){return this.throwIfDisposed(),gt.relu6(this)},wt.prototype.elu=function(){return this.throwIfDisposed(),gt.elu(this)},wt.prototype.selu=function(){return this.throwIfDisposed(),gt.selu(this)},wt.prototype.leakyRelu=function(t){return void 0===t&&(t=.2),this.throwIfDisposed(),gt.leakyRelu(this,t)},wt.prototype.prelu=function(t){return this.throwIfDisposed(),gt.prelu(this,t)},wt.prototype.sigmoid=function(){return this.throwIfDisposed(),gt.sigmoid(this)},wt.prototype.logSigmoid=function(){return this.throwIfDisposed(),gt.logSigmoid(this)},wt.prototype.softplus=function(){return this.throwIfDisposed(),gt.softplus(this)},wt.prototype.zerosLike=function(){return this.throwIfDisposed(),gt.zerosLike(this)},wt.prototype.onesLike=function(){return this.throwIfDisposed(),gt.onesLike(this)},wt.prototype.sin=function(){return this.throwIfDisposed(),gt.sin(this)},wt.prototype.cos=function(){return this.throwIfDisposed(),gt.cos(this)},wt.prototype.tan=function(){return this.throwIfDisposed(),gt.tan(this)},wt.prototype.asin=function(){return this.throwIfDisposed(),gt.asin(this)},wt.prototype.acos=function(){return this.throwIfDisposed(),gt.acos(this)},wt.prototype.atan=function(){return this.throwIfDisposed(),gt.atan(this)},wt.prototype.sinh=function(){return this.throwIfDisposed(),gt.sinh(this)},wt.prototype.cosh=function(){return this.throwIfDisposed(),gt.cosh(this)},wt.prototype.tanh=function(){return this.throwIfDisposed(),gt.tanh(this)},wt.prototype.asinh=function(){return this.throwIfDisposed(),gt.asinh(this)},wt.prototype.acosh=function(){return this.throwIfDisposed(),gt.acosh(this)},wt.prototype.atanh=function(){return this.throwIfDisposed(),gt.atanh(this)},wt.prototype.erf=function(){return this.throwIfDisposed(),gt.erf(this)},wt.prototype.round=function(){return this.throwIfDisposed(),gt.round(this)},wt.prototype.step=function(t){return void 0===t&&(t=0),this.throwIfDisposed(),gt.step(this,t)},wt.prototype.softmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),gt.softmax(this,t)},wt.prototype.logSoftmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),gt.logSoftmax(this,t)},wt.prototype.resizeBilinear=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),gt.image.resizeBilinear(this,t,e)},wt.prototype.resizeNearestNeighbor=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),gt.image.resizeNearestNeighbor(this,t,e)},wt.prototype.conv1d=function(t,e,n,r,o,i){return void 0===r&&(r="NWC"),void 0===o&&(o=1),this.throwIfDisposed(),gt.conv1d(this,t,e,n,r,o,i)},wt.prototype.conv2d=function(t,e,n,r,o,i){return void 0===r&&(r="NHWC"),void 0===o&&(o=[1,1]),this.throwIfDisposed(),gt.conv2d(this,t,e,n,r,o,i)},wt.prototype.conv2dTranspose=function(t,e,n,r,o){return this.throwIfDisposed(),gt.conv2dTranspose(this,t,e,n,r,o)},wt.prototype.depthwiseConv2D=function(t,e,n,r,o,i){return void 0===r&&(r="NHWC"),void 0===o&&(o=[1,1]),this.throwIfDisposed(),gt.depthwiseConv2d(this,t,e,n,r,o,i)},wt.prototype.separableConv2d=function(t,e,n,r,o,i){return void 0===o&&(o=[1,1]),void 0===i&&(i="NHWC"),this.throwIfDisposed(),gt.separableConv2d(this,t,e,n,r,o,i)},wt.prototype.avgPool=function(t,e,n,r){return this.throwIfDisposed(),gt.avgPool(this,t,e,n,r)},wt.prototype.maxPool=function(t,e,n,r){return this.throwIfDisposed(),gt.maxPool(this,t,e,n,r)},wt.prototype.localResponseNormalization=function(t,e,n,r){return void 0===t&&(t=5),void 0===e&&(e=1),void 0===n&&(n=1),void 0===r&&(r=.5),gt.localResponseNormalization(this,t,e,n,r)},wt.prototype.pool=function(t,e,n,r,o){return this.throwIfDisposed(),gt.pool(this,t,e,n,r,o)},wt.prototype.variable=function(t,e,n){return void 0===t&&(t=!0),this.throwIfDisposed(),mt().makeVariable(this,t,e,n)},wt.prototype.unsortedSegmentSum=function(t,e){return this.throwIfDisposed(),gt.unsortedSegmentSum(this,t,e)},wt.prototype.batchToSpaceND=function(t,e){return this.throwIfDisposed(),gt.batchToSpaceND(this,t,e)},wt.prototype.spaceToBatchND=function(t,e){return this.throwIfDisposed(),gt.spaceToBatchND(this,t,e)},wt.prototype.topk=function(t,e){return void 0===t&&(t=1),void 0===e&&(e=!0),this.throwIfDisposed(),gt.topk(this,t,e)},wt.prototype.stridedSlice=function(t,e,n,r,o,i,a,s){return void 0===r&&(r=0),void 0===o&&(o=0),void 0===i&&(i=0),void 0===a&&(a=0),void 0===s&&(s=0),this.throwIfDisposed(),gt.stridedSlice(this,t,e,n,r,o,i,a,s)},wt.prototype.depthToSpace=function(t,e){return this.throwIfDisposed(),gt.depthToSpace(this,t,e)},wt.prototype.fft=function(){return this.throwIfDisposed(),gt.spectral.fft(this)},wt.prototype.ifft=function(){return this.throwIfDisposed(),gt.spectral.ifft(this)},wt.prototype.rfft=function(){return this.throwIfDisposed(),gt.spectral.rfft(this)},wt.prototype.irfft=function(){return this.throwIfDisposed(),gt.spectral.irfft(this)},wt);function wt(t,e,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=L(t),this.strides=Y(t),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}Object.defineProperty(bt,Symbol.hasInstance,{value:function(t){return!!t&&null!=t.dataId&&null!=t.shape&&null!=t.dtype}});var Ct,Et,_t,It,Rt,kt,St,Dt,At,Tt,Nt,Ft=(t(Mt,kt=bt),Mt.prototype.assign=function(t){if(t.dtype!==this.dtype)throw new Error("dtype of the new value ("+t.dtype+") and previous value ("+this.dtype+") must match");if(!A(t.shape,this.shape))throw new Error("shape of the new value ("+t.shape+") and previous value ("+this.shape+") must match");mt().disposeTensor(this),this.dataId=t.dataId,mt().incRef(this,null)},Mt.prototype.dispose=function(){mt().disposeVariable(this),this.isDisposedInternal=!0},Mt);function Mt(t,e,n,r){var o=kt.call(this,t.shape,t.dtype,t.dataId,r)||this;return o.trainable=e,o.name=n,o}Object.defineProperty(Ft,Symbol.hasInstance,{value:function(t){return t instanceof bt&&null!=t.assign&&t.assign instanceof Function}}),(Nt=Ct=Ct||{}).R0="R0",Nt.R1="R1",Nt.R2="R2",Nt.R3="R3",Nt.R4="R4",Nt.R5="R5",Nt.R6="R6",(Tt=Et=Et||{}).float32="float32",Tt.int32="int32",Tt.bool="int32",Tt.complex64="complex64",(At=_t=_t||{}).float32="float32",At.int32="int32",At.bool="bool",At.complex64="complex64",(Dt=It=It||{}).float32="float32",Dt.int32="float32",Dt.bool="float32",Dt.complex64="complex64",(St=Rt=Rt||{}).float32="complex64",St.int32="complex64",St.bool="complex64",St.complex64="complex64";var Ot={float32:It,int32:Et,bool:_t,complex64:Rt};function Pt(t,e){if("string"!==t&&"string"!==e)return Ot[t][e];if("string"===t&&"string"===e)return"string";throw new Error("Can not upcast "+t+" with "+e)}function Bt(t){return Pt(t,"int32")}function Lt(t,e){if(t.dtype===e.dtype)return[t,e];var n=Pt(t.dtype,e.dtype);return[t.cast(n),e.cast(n)]}function Wt(t,e){P(t.dtype===e.dtype,function(){return"The dtypes of the first("+t.dtype+") and second("+e.dtype+") input must match"})}function zt(t){var e=[];return function t(e,n,r){if(null!=e)if(e instanceof bt)n.push(e);else if(o=e,Array.isArray(o)||"object"==typeof o){var o,i=e;for(var a in i){var s=i[a];r.has(s)||(r.add(s),t(s,n,r))}}}(t,e,new Set),e}var Ut,Vt=Object.freeze({makeTypesMatch:Lt,assertTypesMatch:Wt,isTensorInList:function(e,t){return t.some(function(t){return t.id===e.id})},getTensorsInContainer:zt}),Gt=(jt.prototype.dispose=function(){for(var t in this.registeredVariables)this.registeredVariables[t].dispose()},jt),Ht=(qt.prototype.ready=function(){return y(this,void 0,void 0,function(){var e,n,r;return R(this,function(t){switch(t.label){case 0:if(null!=this.pendingBackendInit)return[2,this.pendingBackendInit.then(function(){})];if(null!=this.backendInstance)return[2];e=this.getSortedBackends(),n=0,t.label=1;case 1:return n<e.length?(r=e[n],[4,this.initializeBackend(r).success]):[3,5];case 2:return t.sent()?[4,this.setBackend(r)]:[3,4];case 3:return t.sent(),[2];case 4:return n++,[3,1];case 5:throw new Error("Could not initialize any backends, all backend initializations failed.")}})})},Object.defineProperty(qt.prototype,"backend",{get:function(){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){var t=this.initializeBackendsAndReturnBest(),e=t.name;if(t.asyncInit)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},enumerable:!0,configurable:!0}),qt.prototype.backendNames=function(){return Object.keys(this.registryFactory)},qt.prototype.findBackend=function(t){if(!(t in this.registry)){if(!(t in this.registryFactory))return null;if(this.initializeBackend(t).asyncInit)return null}return this.registry[t]},qt.prototype.findBackendFactory=function(t){return t in this.registryFactory?this.registryFactory[t].factory:null},qt.prototype.registerBackend=function(t,e,n){return void 0===n&&(n=1),t in this.registryFactory?(console.warn(t+" backend was already registered. Reusing existing backend factory."),!1):(this.registryFactory[t]={factory:e,priority:n},!0)},qt.prototype.setBackend=function(o){return y(this,void 0,void 0,function(){var e,n,r;return R(this,function(t){switch(t.label){case 0:if(null==this.registryFactory[o])throw new Error("Backend name '"+o+"' not found in registry");return this.backendName=o,null!=this.registry[o]?[3,4]:(this.backendInstance=null,e=this.initializeBackend(o),n=e.success,e.asyncInit?[4,n]:[3,2]);case 1:return r=t.sent(),[3,3];case 2:r=n,t.label=3;case 3:if(!r)return[2,!1];t.label=4;case 4:return this.backendInstance=this.registry[o],this.setupRegisteredKernels(),this.profiler=new st(this.backendInstance),[2,!0]}})})},qt.prototype.setupRegisteredKernels=function(){var e=this;a(this.backendName).forEach(function(t){null!=t.setupFunc&&t.setupFunc(e.backendInstance)})},qt.prototype.disposeRegisteredKernels=function(e){var n=this;a(e).forEach(function(t){null!=t.disposeFunc&&t.disposeFunc(n.registry[e])})},qt.prototype.initializeBackend=function(e){var n=this,t=this.registryFactory[e];if(null==t)throw new Error("Cannot initialize backend "+e+", no registration found.");try{var r=t.factory();if(Promise.resolve(r)!==r)return this.registry[e]=r,{success:!0,asyncInit:!1};var o=++this.pendingBackendInitId,i=r.then(function(t){return!(o<n.pendingBackendInitId||(n.registry[e]=t,n.pendingBackendInit=null))}).catch(function(t){return!(o<n.pendingBackendInitId||(n.pendingBackendInit=null,console.warn("Initialization of backend "+e+" failed"),console.warn(t.stack||t.message),1))});return{success:this.pendingBackendInit=i,asyncInit:!0}}catch(n){return console.warn("Initialization of backend "+e+" failed"),console.warn(n.stack||n.message),{success:!1,asyncInit:!1}}},qt.prototype.removeBackend=function(t){if(!(t in this.registryFactory))throw new Error(t+" backend not found in registry");this.backendName===t&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,t in this.registry&&(this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t]),delete this.registryFactory[t],this.backendName===t&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)},qt.prototype.getSortedBackends=function(){var n=this;if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort(function(t,e){return n.registryFactory[e].priority-n.registryFactory[t].priority})},qt.prototype.initializeBackendsAndReturnBest=function(){for(var t=this.getSortedBackends(),e=0;e<t.length;e++){var n=t[e],r=this.initializeBackend(n),o=r.success,i=r.asyncInit;if(i||o)return{name:n,asyncInit:i}}throw new Error("Could not initialize any backends, all backend initializations failed.")},qt.prototype.moveData=function(t,e){var n=this.state.tensorInfo.get(e),r=n.backend,o=this.readSync(e);r.disposeData(e),(n.backend=t).move(e,o,n.shape,n.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++},qt.prototype.tidy=function(t,e){var n,r=this,o=null;if(null==e){if("function"!=typeof t)throw new Error("Please provide a function to tidy()");e=t}else{if("string"!=typeof t&&!(t instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof e)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");o=t}return this.scopedRun(function(){return r.startScope(o)},function(){return r.endScope(n)},function(){return(n=e())instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n})},qt.prototype.scopedRun=function(t,e,n){t();try{var r=n();return e(),r}catch(t){throw e(),t}},qt.prototype.nextTensorId=function(){return qt.nextTensorId++},qt.prototype.nextVariableId=function(){return qt.nextVariableId++},qt.prototype.clone=function(t){var e=this.makeTensorFromDataId(t.dataId,t.shape,t.dtype),n={x:t};return this.addTapeNode(this.state.activeScope.name,n,[e],function(t){return{x:function(){return t.toFloat()}}},[]),e},qt.prototype.runKernel=function(t,e,n,r,o){return this.runKernelFunc(null,e,null,t,n,r,o)},qt.prototype.shouldCheckForMemLeaks=function(){return this.ENV.getBool("IS_TEST")},qt.prototype.checkKernelForMemLeak=function(t,e,n){var r=this.backend.numDataIds(),o=0;n.forEach(function(t){o+="complex64"===t.dtype?3:1});var i=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=r-e-o-i;if(0<a)throw new Error("Backend '"+this.backendName+"' has an internal memory leak ("+a+" data ids) after running '"+t+"'")},qt.prototype.runKernelFunc=function(n,o,t,i,a,s,u){var e,c=this;void 0===s&&(s=[]),void 0===u&&(u=[]);var r=[],l=this.isTapeOn();function h(t){l&&(r=t.map(function(t){return c.keep(c.clone(t))}))}null==i&&(i=null!=this.state.activeScope?this.state.activeScope.name:"");var f,p=this.state.numBytes,d=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var v,m=g(i,this.backendName);return f=null!=m?function(){var t=c.backend.numDataIds();v=m.kernelFunc({inputs:o,attrs:a,backend:c.backend});var e=Array.isArray(v)?v:[v];c.shouldCheckForMemLeaks()&&c.checkKernelForMemLeak(i,t,e);var n=e.map(function(t){var e=t.dataId,n=t.shape,r=t.dtype;return c.makeTensorFromDataId(e,n,r)}),r=n.filter(function(t,e){return u[e]});return h((s||[]).slice().concat(r)),n}:function(){var t=c.backend.numDataIds();v=c.tidy(function(){return n(c.backend,h)});var e=Array.isArray(v)?v:[v];return c.shouldCheckForMemLeaks()&&c.checkKernelForMemLeak(i,t,e),e},this.scopedRun(function(){return c.state.kernelDepth++},function(){return c.state.kernelDepth--},function(){e=c.ENV.getBool("DEBUG")?c.profiler.profileKernel(i,o,function(){return f()}):f()}),l&&this.addTapeNode(i,o,e,t,r),this.state.profiling&&this.state.activeProfile.kernels.push({name:i,bytesAdded:this.state.numBytes-p,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-d,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(o).map(function(t){return o[t].shape}),outputShapes:e.map(function(t){return t.shape})}),Array.isArray(v)?e:e[0]},qt.prototype.makeTensor=function(t,e,n,r){if(null==t)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;var o=t;"string"===n&&G(t[0])&&(o=t.map(function(t){return nt(t)}));var i=r.write(o,e,n),a=new bt(e,n,i,this.nextTensorId());if(this.incRef(a,r),"string"===n){var s=this.state.tensorInfo.get(i),u=V(o);this.state.numBytes+=u-s.bytes,s.bytes=u}return a},qt.prototype.makeTensorFromDataId=function(t,e,n,r){var o=new bt(e,n=n||"float32",t,this.nextTensorId());return this.incRef(o,r),o},qt.prototype.makeVariable=function(t,e,n,r){void 0===e&&(e=!0),n=n||this.nextVariableId().toString(),null!=r&&r!==t.dtype&&(t=t.asType(r));var o=new Ft(t,e,n,this.nextTensorId());if(null!=this.state.registeredVariables[o.name])throw new Error("Variable with name "+o.name+" was already registered");return this.state.registeredVariables[o.name]=o,this.incRef(o,this.backend),o},qt.prototype.incRef=function(t,e){var n=this.state.tensorInfo.has(t.dataId)?this.state.tensorInfo.get(t.dataId).refCount:0;if(this.state.numTensors++,"string"===t.dtype&&this.state.numStringTensors++,0===n){this.state.numDataBuffers++;var r=0;"complex64"!==t.dtype&&"string"!==t.dtype&&(r=t.size*U(t.dtype)),this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:r,refCount:0}),this.state.numBytes+=r}this.state.tensorInfo.get(t.dataId).refCount++,t instanceof Ft||this.track(t)},qt.prototype.disposeTensor=function(t){if(this.state.tensorInfo.has(t.dataId)){this.state.numTensors--,"string"===t.dtype&&this.state.numStringTensors--;var e=this.state.tensorInfo.get(t.dataId);e.refCount<=1?("complex64"!==t.dtype&&(this.state.numBytes-=e.bytes),this.state.numDataBuffers--,e.backend.disposeData(t.dataId),this.state.tensorInfo.delete(t.dataId)):this.state.tensorInfo.get(t.dataId).refCount--}},qt.prototype.disposeVariables=function(){for(var t in this.state.registeredVariables){var e=this.state.registeredVariables[t];this.disposeVariable(e)}},qt.prototype.disposeVariable=function(t){this.disposeTensor(t),null!=this.state.registeredVariables[t.name]&&delete this.state.registeredVariables[t.name]},qt.prototype.memory=function(){var t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,0<this.state.numStringTensors&&(t.unreliable=!0,null==t.reasons&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t},qt.prototype.profile=function(r){return y(this,void 0,void 0,function(){var e,n;return R(this,function(t){return this.state.profiling=!0,e=this.state.numBytes,n=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=r(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map(function(t){return t.totalBytesSnapshot})),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-n,[2,this.state.activeProfile]})})},qt.prototype.isTapeOn=function(){return 0<this.state.gradientDepth&&0===this.state.kernelDepth},qt.prototype.addTapeNode=function(t,e,o,n,r){var i=this,a={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:o,saved:r},s=l(t);null!=s&&(n=s.gradFunc),null!=n&&(a.gradient=function(t){return t=t.map(function(t,e){if(null!=t)return t;var n=o[e],r=Z(n.size,n.dtype);return i.makeTensor(r,n.shape,n.dtype)}),n(1<t.length?t:t[0],r)}),this.state.activeTape.push(a)},qt.prototype.keep=function(t){return t.kept=!0,t},qt.prototype.startTape=function(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++},qt.prototype.endTape=function(){this.state.gradientDepth--},qt.prototype.startScope=function(t){var e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(e.name=t),this.state.scopeStack.push(e),this.state.activeScope=e},qt.prototype.endScope=function(t){for(var e=this,n=zt(t),r=new Set(n.map(function(t){return t.id})),o=0;o<this.state.activeScope.track.length;o++){var i=this.state.activeScope.track[o];i.kept||r.has(i.id)||i.dispose()}var a=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],n.forEach(function(t){t.kept||t.scopeId!==a.id||e.track(t)})},qt.prototype.gradients=function(t,o,i,e){var u=this;if(void 0===e&&(e=!1),P(0<o.length,function(){return"gradients() received an empty list of xs."}),null!=i&&"float32"!==i.dtype)throw new Error("dy must have 'float32' dtype, but has '"+i.dtype+"'");var a=this.scopedRun(function(){return u.startTape()},function(){return u.endTape()},function(){return u.tidy("forward",t)});P(a instanceof bt,function(){return"The result y returned by f() must be a tensor."});var s=function(t,e,n){for(var r={},o={},i=0;i<e.length;i++)r[e[i].id]=!0;for(i=0;i<t.length;i++){var a=(d=t[i]).inputs;for(var s in a){for(var u=a[s],c=!1,l=0;l<e.length;l++)if(r[u.id]){d.outputs.forEach(function(t){return r[t.id]=!0}),c=!0,o[d.id]=!0;break}if(c)break}}var h={};h[n.id]=!0;var f={};for(i=t.length-1;0<=i;i--)for(a=(d=t[i]).inputs,l=0;l<d.outputs.length;l++)if(h[d.outputs[l].id]){for(var s in a)h[a[s].id]=!0,f[d.id]=!0;break}var p=[];for(i=0;i<t.length;i++){var d;if(o[(d=t[i]).id]&&f[d.id]){var v={};for(var s in d.inputs){var m=d.inputs[s];r[m.id]&&(v[s]=m)}var g=Object.assign({},d);g.inputs=v,g.outputs=d.outputs,p.push(g)}}return p}(this.state.activeTape,o,a);if(!e&&0===s.length&&0<o.length)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",function(){var t,e,n={};n[a.id]=null==i?(e=Q(L(t=a.shape),"float32"),Kt.makeTensor(e,t,"float32")):i,function(a,s){for(var t=function(t){var o=s[t],n=[];if(o.outputs.forEach(function(t){var e=a[t.id];null!=e?n.push(e):n.push(null)}),null==o.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+o.kernelName+".");function e(t){if(!(t in i))throw new Error("Cannot backprop through input "+t+". Available gradients found: "+Object.keys(i)+".");var e=function(t){return u.tidy(t)}(function(){return i[t]()});if("float32"!==e.dtype)throw new Error("Error in gradient for op "+o.kernelName+". The gradient of input "+t+" must have 'float32' dtype, but has '"+e.dtype+"'");var n=o.inputs[t];if(!A(e.shape,n.shape))throw new Error("Error in gradient for op "+o.kernelName+". The gradient of input '"+t+"' has shape '"+e.shape+"', which does not match the shape of the input '"+n.shape+"'");if(null==a[n.id])a[n.id]=e;else{var r=a[n.id];a[n.id]=r.add(e),r.dispose()}}var i=o.gradient(n);for(var r in o.inputs)e(r)},e=s.length-1;0<=e;e--)t(e)}(n,s);var r=o.map(function(t){return n[t.id]});return 0===u.state.gradientDepth&&(u.state.activeTape.forEach(function(t){for(var e=0,n=t.saved;e<n.length;e++)n[e].dispose()}),u.state.activeTape=null),{