diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 0000000..7a05ac4 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,11 @@ +{ + "env": { "es6": true }, + "parserOptions": { + "ecmaVersion": 8, + "sourceType": "module" + }, + "rules": { + "semi": ["error", "always"], + "quotes": ["error"] + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b35f6b5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +node_modules +tests/js +.DS_Store \ No newline at end of file diff --git a/README.md b/README.md index e809c46..6fc955d 100644 --- a/README.md +++ b/README.md @@ -1 +1,3 @@ -# chrome-extension \ No newline at end of file +# chrome-extension + +Chrome extention for leveraging text predictions based on machine learning models trained via typelike.me \ No newline at end of file diff --git a/dist/css/dropdown.min.css b/dist/css/dropdown.min.css new file mode 100644 index 0000000..9741e71 --- /dev/null +++ b/dist/css/dropdown.min.css @@ -0,0 +1 @@ +.dropdown,.dropdown:before,.dropdown:after,.dropup,.dropup:before,.dropup:after,.dropdown *,.dropdown *:before,.dropdown *:after,.dropup *,.dropup *:before,.dropup *:after{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.dropup,.dropdown{position:relative}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;font-size:14px;text-align:left;list-style:none;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,0.175);box-shadow:0 6px 12px rgba(0,0,0,0.175)}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:400;line-height:1.42857143;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus{color:#262626;text-decoration:none;background-color:#f5f5f5}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#337ab7;outline:0}.dropdown.open>.dropdown-menu,.dropup.open>.dropdown-menu{display:block}.dropdown-menu-right{right:0;left:auto}.dropdown-menu-left{right:auto;left:0}.dropup .dropdown-menu{top:auto;bottom:100%;margin-bottom:2px}.autosuggest-loader{color:#333;font-size:6px;margin:24px auto;width:6px;height:6px;border-radius:50%;position:relative;text-indent:-9999em;-webkit-animation:load4 1.3s infinite linear;animation:load4 1.3s infinite linear;-webkit-transform:translateZ(0);-ms-transform:translateZ(0);transform:translateZ(0)}@-webkit-keyframes load4{0%,100%{box-shadow:0 -3em 0 .2em,2em -2em 0 0,3em 0 0 -1em,2em 2em 0 -1em,0 3em 0 -1em,-2em 2em 0 -1em,-3em 0 0 -1em,-2em -2em 0 0}12.5%{box-shadow:0 -3em 0 0,2em -2em 0 .2em,3em 0 0 0,2em 2em 0 -1em,0 3em 0 -1em,-2em 2em 0 -1em,-3em 0 0 -1em,-2em -2em 0 -1em}25%{box-shadow:0 -3em 0 -0.5em,2em -2em 0 0,3em 0 0 .2em,2em 2em 0 0,0 3em 0 -1em,-2em 2em 0 -1em,-3em 0 0 -1em,-2em -2em 0 -1em}37.5%{box-shadow:0 -3em 0 -1em,2em -2em 0 -1em,3em 0 0 0,2em 2em 0 .2em,0 3em 0 0,-2em 2em 0 -1em,-3em 0 0 -1em,-2em -2em 0 -1em}50%{box-shadow:0 -3em 0 -1em,2em -2em 0 -1em,3em 0 0 -1em,2em 2em 0 0,0 3em 0 .2em,-2em 2em 0 0,-3em 0 0 -1em,-2em -2em 0 -1em}62.5%{box-shadow:0 -3em 0 -1em,2em -2em 0 -1em,3em 0 0 -1em,2em 2em 0 -1em,0 3em 0 0,-2em 2em 0 .2em,-3em 0 0 0,-2em -2em 0 -1em}75%{box-shadow:0 -3em 0 -1em,2em -2em 0 -1em,3em 0 0 -1em,2em 2em 0 -1em,0 3em 0 -1em,-2em 2em 0 0,-3em 0 0 .2em,-2em -2em 0 0}87.5%{box-shadow:0 -3em 0 0,2em -2em 0 -1em,3em 0 0 -1em,2em 2em 0 -1em,0 3em 0 -1em,-2em 2em 0 0,-3em 0 0 0,-2em -2em 0 .2em}}@keyframes load4{0%,100%{box-shadow:0 -3em 0 .2em,2em -2em 0 0,3em 0 0 -1em,2em 2em 0 -1em,0 3em 0 -1em,-2em 2em 0 -1em,-3em 0 0 -1em,-2em -2em 0 0}12.5%{box-shadow:0 -3em 0 0,2em -2em 0 .2em,3em 0 0 0,2em 2em 0 -1em,0 3em 0 -1em,-2em 2em 0 -1em,-3em 0 0 -1em,-2em -2em 0 -1em}25%{box-shadow:0 -3em 0 -0.5em,2em -2em 0 0,3em 0 0 .2em,2em 2em 0 0,0 3em 0 -1em,-2em 2em 0 -1em,-3em 0 0 -1em,-2em -2em 0 -1em}37.5%{box-shadow:0 -3em 0 -1em,2em -2em 0 -1em,3em 0 0 0,2em 2em 0 .2em,0 3em 0 0,-2em 2em 0 -1em,-3em 0 0 -1em,-2em -2em 0 -1em}50%{box-shadow:0 -3em 0 -1em,2em -2em 0 -1em,3em 0 0 -1em,2em 2em 0 0,0 3em 0 .2em,-2em 2em 0 0,-3em 0 0 -1em,-2em -2em 0 -1em}62.5%{box-shadow:0 -3em 0 -1em,2em -2em 0 -1em,3em 0 0 -1em,2em 2em 0 -1em,0 3em 0 0,-2em 2em 0 .2em,-3em 0 0 0,-2em -2em 0 -1em}75%{box-shadow:0 -3em 0 -1em,2em -2em 0 -1em,3em 0 0 -1em,2em 2em 0 -1em,0 3em 0 -1em,-2em 2em 0 0,-3em 0 0 .2em,-2em -2em 0 0}87.5%{box-shadow:0 -3em 0 0,2em -2em 0 -1em,3em 0 0 -1em,2em 2em 0 -1em,0 3em 0 -1em,-2em 2em 0 0,-3em 0 0 0,-2em -2em 0 .2em}} \ No newline at end of file diff --git a/dist/js/background.js b/dist/js/background.js new file mode 100644 index 0000000..4802dbb --- /dev/null +++ b/dist/js/background.js @@ -0,0 +1,5 @@ +chrome.runtime.onInstalled.addListener(function() { + chrome.storage.local.set({active: 1}, function() { + console.log('Now Active'); + }); +}); \ No newline at end of file diff --git a/dist/js/content.js b/dist/js/content.js new file mode 100644 index 0000000..ad5f3b0 --- /dev/null +++ b/dist/js/content.js @@ -0,0 +1,1013 @@ +(function () { + 'use strict'; + + /** + * @license + * Copyright 2019 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. + * ============================================================================= + */ + var t=function(e,n){return (t=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]);})(e,n)};function e(e,n){function r(){this.constructor=e;}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r);}var n=function(){return (n=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])&&(6===a[0]||2===a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]0;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n;}function h(t,e,n){return Math.max(t,Math.min(e,n))}function p(t){return t%2==0?t:t+1}function f(t){for(var e=0,n=0;n=n?o():setTimeout(i,s);}};i();})}function I(t,e){for(var n=1,r=-1,o=0;o=0)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(e>0&&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 a=t.slice();return a[r]=e/n,a}function S(t,e){var n=e.length;return d((t=null==t?e.map(function(t,e){return e}):[].concat(t)).every(function(t){return t>=-n&&ti)&&1===t[i]&&(n.push(t[i]),r.push(i)),o[a]<=i&&a++;}1!==t[i]&&(n.push(t[i]),r.push(i));}return {newShape:n,keptDims:r}}function k(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 A(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 T(t,e,n){if("float32"===e)for(var r=0;r=0;--r)n[r]=n[r+1]*t[r+1];return n}function q(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=g(t)),n&&D(t,e),function(t,e){return t instanceof Float32Array&&"float32"===e||t instanceof Int32Array&&"int32"===e||t instanceof Uint8Array&&"bool"===e}(t,e))return t;if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e){for(var r=new Uint8Array(t.length),o=0;o=0,function(){return "Tensor must have a shape comprised of positive integers but got shape ["+t+"]."});});}function Y(t,e){return s.platform.fetch(t,e)}function Q(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",s.platform.encode(t,e)}function J(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",s.platform.decode(t,e)}var Z=Object.freeze({shuffle:c,clamp:h,nearestLargerEven:p,sum:f,randUniform:function(t,e){var n=Math.random();return e*n+(1-n)*t},distSquared:function(t,e){for(var n=0,r=0;r1)for(var l=0;lnt){var h=rt*s,p=Array.from(e.slice(0,h)),f=Array.from(e.slice(u-rt*s,u));return "complex64"===r&&(p=ut(p),f=ut(f)),["["+p.map(function(t,e){return it(t,a[e],r)}).join(", ")+", ..., "+f.map(function(t,e){return it(t,a[u-rt+e],r)}).join(", ")+"]"]}var d="complex64"===r?ut(e):Array.from(e);return ["["+d.map(function(t,e){return it(t,a[e],r)}).join(", ")+"]"]}var v=n.slice(1);var m=o.slice(1);var g=o[0]*s;var y=[];if(u>nt){for(var x=0;x=this.shape[n]){var i="Requested out of range element at "+t+". Buffer shape="+this.shape;throw new Error(i)}n++;}for(var s=t[t.length-1],u=0;u0&&(t.unreliable=!0,null==t.reasons&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t},t.prototype.profile=function(t){return r(this,void 0,void 0,function(){var e,n;return o(this,function(r){return this.state.profiling=!0,e=this.state.numBytes,n=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=t(),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]})})},t.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&0===this.state.kernelDepth},t.prototype.addTapeNode=function(t,e,n){var r={};t.forEach(function(t,e){r[e]=t;});var o={id:this.state.nextTapeNodeId++,name:this.state.activeScope.name,inputs:r,outputs:[e],gradient:function(t){var e=n(t),r={};return e.forEach(function(t,e){r[e]=function(){return t};}),r}};this.state.activeTape.push(o);},t.prototype.keep=function(t){return t.kept=!0,t},t.prototype.startTape=function(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++;},t.prototype.endTape=function(){this.state.gradientDepth--;},t.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;},t.prototype.endScope=function(t){for(var e=this,n=St(t),r=new Set(n.map(function(t){return t.id})),o=0;o0,function(){return "gradients() received an empty list of xs."}),null!=n&&"float32"!==n.dtype)throw new Error("dy must have 'float32' dtype, but has '"+n.dtype+"'");var a=this.scopedRun(function(){return o.startTape()},function(){return o.endTape()},function(){return o.tidy("forward",t)});d(a instanceof ft,function(){return "The result y returned by f() must be a tensor."});var i=function(t,e,n){for(var r={},o={},a=0;a=0;a--)for(i=(d=t[a]).inputs,c=0;c0)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,r,s={};s[a.id]=null==n?(t=a.shape,r=$(y(t),"float32"),ft.make(t,{values:r})):n,function(t,e,n){for(var r=function(r){var o=e[r],a=[];if(o.outputs.forEach(function(e){var n=t[e.id];if(null!=n)a.push(n);else{var r=ft.make(e.shape,{values:j(e.size,e.dtype)},e.dtype);a.push(r);}}),null==o.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+o.name+".");var i=o.gradient(1===o.outputs.length?a[0]:a),s=function(e){if(!(e in i))throw new Error("Cannot backprop through input "+e+". Available gradients found: "+Object.keys(i)+".");var r=n(function(){return i[e]()});if("float32"!==r.dtype)throw new Error("Error in gradient for op "+o.name+". The gradient of input "+e+" must have 'float32' dtype, but has '"+r.dtype+"'");var a=o.inputs[e];if(!x(r.shape,a.shape))throw new Error("Error in gradient for op "+o.name+". The gradient of input '"+e+"' has shape '"+r.shape+"', which does not match the shape of the input '"+a.shape+"'");if(null==t[a.id])t[a.id]=r;else{var s=t[a.id];t[a.id]=s.add(r),s.dispose();}};for(var u in o.inputs)s(u);},o=e.length-1;o>=0;o--)r(o);}(s,i,function(t){return o.tidy(t)});var u=e.map(function(t){return s[t.id]});return 0===o.state.gradientDepth&&(o.state.activeTape.forEach(function(t){for(var e in t.saved)t.saved[e].dispose();}),o.state.activeTape=null),{value:a,grads:u}})},t.prototype.customGrad=function(t){var e=this;return d(z(t),function(){return "The f passed in customGrad(f) must be a function."}),function(){for(var n,r=[],o=0;on||e>n){r="["+t+"x"+e+"]";throw new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU "+("["+n+"x"+n+"]")+".")}}function ne(t,e){return pe(t,e,function(){return t.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function re(t,e,n,r,o,a,i,s){var u=t.getAttribLocation(n,r);return -1!==u&&(Lt(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,o)}),Lt(t,e,function(){return t.vertexAttribPointer(u,a,t.FLOAT,!1,i,s)}),Lt(t,e,function(){return t.enableVertexAttribArray(u)}),!0)}function oe(t,e,n,r){fe(t,r),Lt(t,e,function(){return t.activeTexture(t.TEXTURE0+r)}),Lt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)});}function ae(t,e,n,r){return pe(t,e,function(){return t.getUniformLocation(n,r)},'uniform "'+r+'" not present in program.')}function ie(t,e,n){return t.getUniformLocation(e,n)}function se(t,e,n,r,o,a){Lt(t,e,function(){return oe(t,e,r,a)}),Lt(t,e,function(){return t.uniform1i(o,a)});}function ue(t,e,n,r){Lt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,r)}),Lt(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)});}function le(t,e,n){Lt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)}),Lt(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0)});}function ce(t){var e=t.checkFramebufferStatus(t.FRAMEBUFFER);if(e!==t.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+he(t,e))}function he(t,e){switch(e){case t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return "FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return "FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return "FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case t.FRAMEBUFFER_UNSUPPORTED:return "FRAMEBUFFER_UNSUPPORTED";default:return "unknown error "+e}}function pe(t,e,n,r){var o=Lt(t,e,function(){return n()});if(null==o)throw new Error(r);return o}function fe(t,e){var n=t.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=e+t.TEXTURE0;if(rn)throw new Error("textureUnit must be in "+("[gl.TEXTURE0, gl.TEXTURE"+n+"]")+".")}function de(t,e){return void 0===e&&(e=2),y(t.slice(0,t.length-e))}function ve(t){if(0===t.length)throw Error("Cannot get rows and columns of an empty shape array.");return [t.length>1?t[t.length-2]:1,t[t.length-1]]}function me(t){var e=[1,1,1];return 0===t.length||1===t.length&&1===t[0]||(e=[de(t)].concat(ve(t))),e}function ge(t,e){var n;void 0===e&&(e=!1);var r=s.getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e&&(r*=2,1===(t=t.map(function(e,n){return n>=t.length-2?p(t[n]):t[n]})).length&&(t=[2,t[0]])),2!==t.length){var o=N(t);t=o.newShape;}var a=y(t);if(t.length<=1&&a<=r)return [1,a];if(2===t.length&&t[0]<=r&&t[1]<=r)return t;if(3===t.length&&t[0]*t[1]<=r&&t[2]<=r)return [t[0]*t[1],t[2]];if(3===t.length&&t[0]<=r&&t[1]*t[2]<=r)return [t[0],t[1]*t[2]];if(4===t.length&&t[0]*t[1]*t[2]<=r&&t[3]<=r)return [t[0]*t[1]*t[2],t[3]];if(4===t.length&&t[0]<=r&&t[1]*t[2]*t[3]<=r)return [t[0],t[1]*t[2]*t[3]];if(e){var i=de(t),u=2,l=2;return t.length&&(u=(n=ve(t))[0],l=n[1]),C(a=i*(u/2)*(l/2)).map(function(t){return 2*t})}return C(a)}function ye(t){return t%2==0}function xe(t,e){if(x(t=t.slice(-2),e=e.slice(-2)))return !0;if(!t.length||!e.length)return !0;if(0===t[0]||0===t[1]||0===e[0]||0===e[1])return !0;if(t.length!==e.length){var n=t.slice(-1)[0],r=e.slice(-1)[0];if(n===r)return !0;if(ye(n)&&ye(r)&&(1===t[0]||1===e[0]))return !0}return t[1]===e[1]&&ye(t[0])&&ye(e[0])}function be(t){if(null==$t){var e=Bt(t);$t=e.getParameter(e.MAX_TEXTURE_SIZE);}return $t}function we(t){if(null==jt){var e=Bt(t);jt=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS);}return Math.min(16,jt)}function Ce(t){if(0===t)return 0;var e=Bt(t);return Ee(e,"EXT_disjoint_timer_query_webgl2")&&2===t?2:Ee(e,"EXT_disjoint_timer_query")?1:0}function Ee(t,e){return null!=t.getExtension(e)}function Re(t){try{if(null!=Bt(t))return !0}catch(t){return !1}return !1}function Ie(t){if(0===t)return !1;var e=Bt(t);if(1===t){if(!Ee(e,"OES_texture_float"))return !1}else if(!Ee(e,"EXT_color_buffer_float"))return !1;return Ne(e,t)}function Se(t){if(0===t)return !1;var e=Bt(t);if(1===t){if(!Ee(e,"OES_texture_float"))return !1;if(!Ee(e,"WEBGL_color_buffer_float"))return !1}else if(!Ee(e,"EXT_color_buffer_float"))return !1;return Ne(e,t)}function Ne(t,e){var n=t.createFramebuffer(),r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r);var o=2===e?t.RGBA32F:t.RGBA;t.texImage2D(t.TEXTURE_2D,0,o,1,1,0,t.RGBA,t.FLOAT,null),t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var a=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(r),t.deleteFramebuffer(n),a}function ke(t){return 2===t&&null!=Bt(t).fenceSync}var Ae=Object.freeze({callAndCheck:Lt,canBeRepresented:zt,getWebGLErrorMessage:Vt,getExtensionOrThrow:Gt,createVertexShader:qt,createFragmentShader:Ht,createProgram:Xt,linkProgram:Yt,validateProgram:Qt,createStaticVertexBuffer:Jt,createStaticIndexBuffer:Zt,getNumChannels:function(){return 2===s.getNumber("WEBGL_VERSION")?1:4},createTexture:te,validateTextureSize:ee,createFramebuffer:ne,bindVertexBufferToProgramAttribute:re,bindTextureUnit:oe,unbindTextureUnit:function(t,e,n){fe(t,n),Lt(t,e,function(){return t.activeTexture(t.TEXTURE0+n)}),Lt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)});},getProgramUniformLocationOrThrow:ae,getProgramUniformLocation:ie,bindTextureToProgramUniformSampler:se,bindCanvasToFramebuffer:function(t,e){Lt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)}),Lt(t,e,function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)}),Lt(t,e,function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)});},bindColorTextureToFramebuffer:ue,unbindColorTextureFromFramebuffer:le,validateFramebuffer:ce,getFramebufferErrorMessage:he,getBatchDim:de,getRowsCols:ve,getShapeAs3D:me,getTextureShapeFromLogicalShape:ge,isReshapeFree:xe,get MAX_TEXTURE_SIZE(){return $t},get MAX_TEXTURES_IN_SHADER(){return jt},getWebGLMaxTextureSize:be,getMaxTexturesInShader:we,getWebGLDisjointQueryTimerVersion:Ce,isWebGLVersionEnabled:Re,isRenderToFloatTextureEnabled:Ie,isDownloadFloatTextureEnabled:Se,isWebGLFenceEnabled:ke});function Oe(t){s.getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().");}function Fe(){return Dt.memory()}function Pe(t,e){return Dt.tidy(t,e)}function Le(t){St(t).forEach(function(t){return t.dispose()});}function We(t){return Dt.keep(t)}function Ke(){return Dt.backend}function Ye(){for(var t=[],e=0;e0,function(){return "Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"});d(e.length===n[0],function(){return "Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements"});var o=n.slice(1);for(var a=0;a=0&&(o=r),Je(r,o,e,n),null==t||!M(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t){var a=null==t?"null":t.constructor.name;throw new Error("Argument '"+e+"' passed to '"+n+"' must be a Tensor or TensorLike, but got '"+a+"'")}var i=Qe(t,o);M(t)||Array.isArray(t)||(t=[t]);var u="string"!==o?q(t,o,s.getBool("DEBUG")):g(t,[],!0);return ft.make(i,{values:u},o)}function tn(t,e,n,r){if(void 0===r&&(r="numeric"),!Array.isArray(t))throw new Error("Argument "+e+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");return t.map(function(t,r){return Ze(t,e+"["+r+"]",n)},r)}function en(t,e){for(var n=0;n=0&&e0}),s.registerFlag("WEBGL_VERSION",function(){return Re(2)?2:Re(1)?1:0}),s.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return 2===s.get("WEBGL_VERSION")}),s.registerFlag("WEBGL_CPU_FORWARD",function(){return !0}),s.registerFlag("WEBGL_PACK",function(){return s.getBool("HAS_WEBGL")}),s.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return s.getBool("WEBGL_PACK")}),s.registerFlag("WEBGL_PACK_CLIP",function(){return s.getBool("WEBGL_PACK")}),s.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return !1}),s.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return s.getBool("WEBGL_PACK")}),s.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return s.getBool("WEBGL_PACK")}),s.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return s.getBool("WEBGL_PACK")}),s.registerFlag("WEBGL_PACK_REDUCE",function(){return s.getBool("WEBGL_PACK")}),s.registerFlag("WEBGL_LAZILY_UNPACK",function(){return s.getBool("WEBGL_PACK")}),s.registerFlag("WEBGL_CONV_IM2COL",function(){return s.getBool("WEBGL_PACK")}),s.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return be(s.getNumber("WEBGL_VERSION"))}),s.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return we(s.getNumber("WEBGL_VERSION"))}),s.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var t=s.getNumber("WEBGL_VERSION");return 0===t?0:Ce(t)}),s.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return s.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(t=navigator.userAgent||navigator.vendor||window.opera,!(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))));var t;}),s.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return Ie(s.getNumber("WEBGL_VERSION"))}),s.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return Se(s.getNumber("WEBGL_VERSION"))}),s.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return ke(s.getNumber("WEBGL_VERSION"))}),s.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){return s.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0}),pt=Oe;var fn=pn({complex_:function(t,e){var n=Ze(t,"real","complex"),r=Ze(e,"imag","complex");return v(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),Dt.runKernel(function(t){return t.complex(n,r)},{$real:n,$imag:r})}}),dn=pn({real_:function(t){var e=Ze(t,"input","real");return Dt.runKernel(function(t){return t.real(e)},{$input:e})}}),vn=pn({imag_:function(t){var e=Ze(t,"input","imag");return Dt.runKernel(function(t){return t.imag(e)},{$input:e})}});function mn(t,e,n){return gn(t,e,Qe(t,n),n)}function gn(t,e,n,r){if(null==r&&(r=U(t)),"complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!M(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=e){X(e);var o=y(e),a=y(n);d(o===a,function(){return "Based on the provided shape, ["+e+"], the tensor should have "+o+" values but has "+a});for(var i=0;i1)return Sn([0],r);var o=j(Math.abs(Math.ceil((e-t)/n)),r);e=1,function(){return "Pass at least one tensor to concat"});var n=tn(t,"tensors","concat");e=S(e,n[0].shape)[0];var r=hn(n.map(function(t){return t.shape}),e);if(0===y(r))return mn([],r);if(1===(n=n.filter(function(t){return t.size>0})).length)return n[0];var o=n.map(function(t){return t.shape});cn(o,e);var a=n;return Dt.runKernel(function(t){return t.concat(n,e)},a,function(t){var n=o.map(function(t){return t[e]});return Pn(t,n,e).map(function(t){return function(){return t}})})}}),On=pn({concat1d_:function(t){return _n(t,0)}}),Mn=pn({concat2d_:function(t,e){return _n(t,e)}}),Fn=pn({concat3d_:function(t,e){return _n(t,e)}}),Bn=pn({concat4d_:function(t,e){return _n(t,e)}}),Pn=pn({split_:function(t,e,n){void 0===n&&(n=0);var r,o=Ze(t,"x","split");return n=S(n,o.shape)[0],"number"==typeof e?(d(o.shape[n]%e==0,function(){return "Number of splits must evenly divide the axis."}),r=new Array(e).fill(o.shape[n]/e)):(d(o.shape[n]===e.reduce(function(t,e){return t+e}),function(){return "The sum of sizes must match the size of the axis dimension."}),r=e),Dt.runKernel(function(t){return t.split(o,r,n)},{$x:o},function(t){return {$x:function(){return _n(t,n)}}})}});function Ln(t,e){return t(e={exports:{}},e.exports),e.exports}var Wn=Ln(function(t){!function(t,e,n){function r(t){var e,n=this,r=(e=4022871197,function(t){t=t.toString();for(var n=0;n>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e);}return 2.3283064365386963e-10*(e>>>0)});n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(t),n.s0<0&&(n.s0+=1),n.s1-=r(t),n.s1<0&&(n.s1+=1),n.s2-=r(t),n.s2<0&&(n.s2+=1),r=null;}function o(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}function a(t,e){var n=new r(t),a=e&&e.state,i=n.next;return i.int32=function(){return 4294967296*n.next()|0},i.double=function(){return i()+1.1102230246251565e-16*(2097152*i()|0)},i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.alea=a;}(0,t,!1);}),Un=Ln(function(t){!function(t,e,n){function r(t){var e=this,n="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8},t===(0|t)?e.x=t:n+=t;for(var r=0;r>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.xor128=a;}(0,t,!1);}),zn=Ln(function(t){!function(t,e,n){function r(t){var e=this,n="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:n+=t;for(var r=0;r>>4),e.next();}function o(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e}function a(t,e){var n=new r(t),a=e&&e.state,i=function(){return (n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.xorwow=a;}(0,t,!1);}),Vn=Ln(function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.x,o=e.i;return t=r[o],n=(t^=t>>>7)^t<<24,n^=(t=r[o+1&7])^t>>>10,n^=(t=r[o+3&7])^t>>>3,n^=(t=r[o+4&7])^t<<7,t=r[o+7&7],n^=(t^=t<<13)^t<<9,r[o]=n,e.i=o+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n0;--n)t.next();}(e,t);}function o(t,e){return e.x=t.x.slice(),e.i=t.i,e}function a(t,e){null==t&&(t=+new Date);var n=new r(t),a=e&&e.state,i=function(){return (n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);}while(0===t);return t},i.int32=n.next,i.quick=i,a&&(a.x&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.xorshift7=a;}(0,t,!1);}),Gn=Ln(function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.w,o=e.X,a=e.i;return e.w=r=r+1640531527|0,n=o[a+34&127],t=o[a=a+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=o[a]=n^t,e.i=a,n+(r^r>>>16)|0},function(t,e){var n,r,o,a,i,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),o=0,a=-32;a>>15,r^=r<<4,r^=r>>>13,a>=0&&(i=i+1640531527|0,o=0==(n=s[127&a]^=r+i)?o+1:0);for(o>=128&&(s[127&(e&&e.length||0)]=-1),o=127,a=512;a>0;--a)r=s[o+34&127],n=s[o=o+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[o]=r^n;t.w=i,t.X=s,t.i=o;}(e,t);}function o(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function a(t,e){null==t&&(t=+new Date);var n=new r(t),a=e&&e.state,i=function(){return (n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);}while(0===t);return t},i.int32=n.next,i.quick=i,a&&(a.X&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.xor4096=a;}(0,t,!1);}),qn=Ln(function(t){!function(t,e,n){function r(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,o=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^o,o=o-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>16^o,e.a=o-t|0},e.a=0,e.b=0,e.c=-1640531527,e.d=1367130551,t===Math.floor(t)?(e.a=t/4294967296|0,e.b=0|t):n+=t;for(var r=0;r>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a}):this.tychei=a;}(0,t,!1);}),Hn=Ln(function(t){!function(e,n){var r,o=this,a=256,i=6,s="random",u=n.pow(a,i),l=n.pow(2,52),c=2*l,h=a-1;function p(t,h,p){var g=[],y=v(function t(e,n){var r,o=[],a=typeof e;if(n&&"object"==a)for(r in e)try{o.push(t(e[r],n-1));}catch(t){}return o.length?o:"string"==a?e:e+"\0"}((h=1==h?{entropy:!0}:h||{}).entropy?[t,m(e)]:null==t?function(){try{var t;return r&&(t=r.randomBytes)?t=t(a):(t=new Uint8Array(a),(o.crypto||o.msCrypto).getRandomValues(t)),m(t)}catch(t){var n=o.navigator,i=n&&n.plugins;return [+new Date,o,i,o.screen,m(e)]}}():t,3),g),x=new f(g),b=function(){for(var t=x.g(i),e=u,n=0;t=c;)t/=2,e/=2,n>>>=1;return (t+n)/e};return b.int32=function(){return 0|x.g(4)},b.quick=function(){return x.g(4)/4294967296},b.double=b,v(m(x.S),e),(h.pass||p||function(t,e,r,o){return o&&(o.S&&d(o,x),t.state=function(){return d(x,{})}),r?(n[s]=t,e):t})(b,y,"global"in h?h.global:this==n,h.state)}function f(t){var e,n=t.length,r=this,o=0,i=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);o=1||0===i);var s=Math.sqrt(-2*Math.log(i)/i);e=this.mean+this.stdDev*o*s,n=this.mean+this.stdDev*a*s,this.truncated&&!this.isValidTruncated(e)||(r=!0);}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(e)},t.prototype.convertValue=function(t){return null==this.dtype||"float32"===this.dtype?t:Math.round(t)},t.prototype.isValidTruncated=function(t){return t<=this.upper&&t>=this.lower},t}(),Kn=function(){function t(t,e,n,r){void 0===t&&(t=0),void 0===e&&(e=1);var o=this;if(this.canReturnFloat=function(){return null==o.dtype||"float32"===o.dtype},this.min=t,this.range=e-t,this.dtype=n,null==r&&(r=Math.random()),"number"==typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error("The difference between "+t+" - "+e+" <= 1 and dtype is not float");this.random=$n(r);}return t.prototype.convertValue=function(t){return this.canReturnFloat()?t:Math.round(t)},t.prototype.nextValue=function(){return this.convertValue(this.min+this.range*this.random())},t}();function Xn(t,e,n){return void 0===e&&(e="float32"),e=e||"float32",X(t),new lt(t,e,n)}function Yn(t,e){void 0===e&&(e=!1),console.log(t.toString(e));}var Qn=pn({batchToSpaceND_:function(t,e,n){var r=Ze(t,"x","batchToSpaceND"),o=e.reduce(function(t,e){return t*e});return d(r.rank>=1+e.length,function(){return "input rank is "+r.rank+" but should be > than blockShape.length "+e.length}),d(n.length===e.length,function(){return "crops.length is "+n.length+" but should be equal to blockShape.length "+e.length}),d(r.shape[0]%o==0,function(){return "input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+e.join(" * ")+" === "+o}),Dt.runKernel(function(t){return t.batchToSpaceND(r,e,n)},{$x:r},function(t){return {$x:function(){return t.spaceToBatchND(e,n)}}})}}),Jn=pn({cast_:function(t,e){var n=Ze(t,"x","cast");if(!_(e))throw new Error("Failed to cast to unknown dtype "+e);if("string"===e&&"string"!==n.dtype||"string"!==e&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");return Dt.runKernel(function(t){return t.cast(n,e)},{$x:n},function(t){return {$x:function(){return t.clone()}}})}}),Zn=pn({clone_:function(t){var e=Ze(t,"x","clone",null);return Dt.runKernel(function(t){return ft.make(e.shape,{dataId:e.dataId},e.dtype)},{$x:e},function(t){return {$x:function(){return t.toFloat()}}})}}),tr=pn({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var o=Ze(t,"x","cumsum"),a=sn([e|=0],o.rank),i=o;null!=a&&(i=o.transpose(a));var s=ln(1,o.rank)[0],u=Dt.runKernel(function(t){return t.cumsum(i,s,n,r)},{permutedX:i},function(t){return {permutedX:function(){return t.cumsum(e,n,!r)}}});return null!=a&&(u=u.transpose(a)),u}}),er=pn({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=Ze(t,"x","depthToSpace"),o="NHWC"===n?r.shape[1]:r.shape[2],a="NHWC"===n?r.shape[2]:r.shape[3],i="NHWC"===n?r.shape[3]:r.shape[1];return d(o*e>=0,function(){return "Negative dimension size caused by overflow when multiplying\n "+o+" and "+e+" for depthToSpace with input shape\n "+r.shape}),d(a*e>=0,function(){return "Negative dimension size caused by overflow when multiplying\n "+a+" and "+e+" for depthToSpace with input shape\n "+r.shape}),d(i%(e*e)==0,function(){return "Dimension size must be evenly divisible by "+e*e+" but is "+i+" for depthToSpace with input shape "+r.shape}),Dt.runKernel(function(t){return t.depthToSpace(r,e,n)},{$x:r})}}),nr=pn({expandDims_:function(t,e){void 0===e&&(e=0);var n=Ze(t,"x","expandDims",null);d(e<=n.rank,function(){return "Axis must be <= rank of the tensor"});var r=n.shape.slice();return e<0&&(d(-(n.rank+1)<=e,function(){return "Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]"}),e=n.rank+e+1),r.splice(e,0,1),dr(n,r)}}),rr=pn({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var o=Xn([t,e],r),a=t<=e?t:e,i=0;i2)throw new Error("Rank of probabilities must be 1 or 2, but is "+i);n=n||Math.random();var s=1===i?o.as2D(1,-1):o,u=Dt.runKernel(function(t){return t.multinomial(s,r,e,n)},{logits2D:s});return 1===i?u.as1D():u}}),ar=pn({oneHot_:function(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r=0),e<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+e);var o=Ze(t,"indices","oneHot","int32"),a=o.shape.concat([e]);return o=o.flatten(),Dt.runKernel(function(t){return t.oneHot(o,e,n,r)},{$indices:o},function(t){return {$indices:function(){return Sn(o.shape,"float32")}}}).reshape(a)}}),ir=pn({pad_:function(t,e,n){void 0===n&&(n=0);var r=Ze(t,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var o=e.map(function(t){return t[0]});return Dt.runKernel(function(t){return t.pad(r,e,n)},{$x:r},function(t){return {$x:function(){return t.slice(o,r.shape)}}})}}),sr=pn({pad1d_:function(t,e,n){return void 0===n&&(n=0),d(2===e.length,function(){return "Invalid number of paddings. Must be length of 2."}),ir(t,[e],n)}}),ur=pn({pad2d_:function(t,e,n){return void 0===n&&(n=0),d(2===e.length&&2===e[0].length&&2===e[1].length,function(){return "Invalid number of paddings. Must be length of 2 each."}),ir(t,e,n)}}),lr=pn({pad3d_:function(t,e,n){return void 0===n&&(n=0),d(3===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length,function(){return "Invalid number of paddings. Must be length of 2 each."}),ir(t,e,n)}}),cr=pn({pad4d_:function(t,e,n){return void 0===n&&(n=0),d(4===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length&&2===e[3].length,function(){return "Invalid number of paddings. Must be length of 2 each."}),ir(t,e,n)}}),hr=pn({rand_:function(t,e,n){var r=y(t),o=null;if(null==n||"float32"===n)o=new Float32Array(r);else if("int32"===n)o=new Int32Array(r);else{if("bool"!==n)throw new Error("Unknown data type "+n);o=new Uint8Array(r);}for(var a=0;a=1+e.length,function(){return "input rank "+r.rank+" should be > than [blockShape] "+e.length}),d(n.length===e.length,function(){return "paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length}),d(r.shape.reduce(function(t,r,o){return o>0&&o<=e.length?t&&(r+n[o-1][0]+n[o-1][1])%e[o-1]==0:t},!0),function(){return "input spatial dimensions "+r.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+e.toString()}),Dt.runKernel(function(t){return t.spaceToBatchND(r,e,n)},{$x:r},function(t){return {$x:function(){return t.batchToSpaceND(e,n)}}})}}),mr=pn({squeeze_:function(t,e){var n=Ze(t,"x","squeeze");return dr(n,N(n.shape,e).newShape)}}),gr=pn({stack_:function(t,e){void 0===e&&(e=0);var n=tn(t,"tensors","stack");if(d(n.length>=1,function(){return "Pass at least one tensor to tf.stack"}),1===n.length)return n[0].expandDims(e);var r=n[0].rank,o=n[0].shape,a=n[0].dtype;d(e<=r,function(){return "Axis must be <= rank of the tensor"}),n.forEach(function(t){v(o,t.shape,"All tensors passed to stack must have matching shapes");}),n.forEach(function(t){d(a===t.dtype,function(){return "All tensors passed to stack must have matching dtypes"});});var i=n.map(function(t){return t.expandDims(e)});return _n(i,e)}}),yr=pn({tile_:function(t,e){var n=Ze(t,"x","tile",null);return d(n.rank===e.length,function(){return "Error in transpose: rank of input "+n.rank+" must match length of reps "+e+"."}),Dt.runKernel(function(t,r){var o=t.tile(n,e);return r([n]),o},{$x:n},function(t,n){var r=n[0];return {$x:function(){var n=Dn(r);if(1===r.rank)for(var o=0;o=-n.shape.length&&e=2*e+1||o%2==1?i.push(o):a.push(o);r.push.apply(r,a),r.push(0),r.push.apply(r,i);}return r}function Rr(t,e,n,r){void 0===r&&(r=!0);var o=[];r?o.push(t[0]/n):o.push(t[0]*n);for(var a=1;at.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+e.shape[e.rank-1]+" vs. "+t.rank);if(0===t.size)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+t.shape+".");for(var n=e.shape,r=n[n.length-1],o=1,a=0;a1?e.shape[e.rank-1]:1,o=e.rank>1?e.rank-1:1,a="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+", indices.shape: "+e.shape+", shape: "+t+", sliceDim: "+r+", and batchDim: "+o+".";if(n.rank1?e.shape[e.rank-1]:1,o=n.length,a=1,i=r;i0?a>=c[e]:a<=c[e]);a+=o)n+=1;return n}),[l,f,h]}function Or(t,e,n,r,o){var a=e[o],i=n[o]||1;(t&1<0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=r[o];return a<0&&(a+=s),a=h(0,a,s-1)}function Mr(t,e,n,r,o){var a=e[o],i=n[o]||1;(t&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=r[o];return a<0&&(a+=s),a=i>0?h(0,a,s):h(-1,a,s-1)}function Fr(t,e,n){for(var r=n.length,o=0;o1){r=o;break}for(o=r+1;o0||n[o]!==t[o])return !1;return !0}function Br(t,e){for(var n=t.length>0?t[t.length-1]:1,r=0;r0,function(){return "variableGrads() expects at least one of the input variables to be trainable, but none of the "+a+" variables is trainable."});var i=Dt.gradients(t,e,null,!0),s=i.value,u=i.grads;d(u.some(function(t){return null!=t}),function(){return "Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."}),d(0===s.rank,function(){return "The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"});var l={};return e.forEach(function(t,e){null!=u[e]&&(l[t.name]=u[e]);}),null!=o&&o.forEach(function(t){return l[t.name]=null}),{value:s,grads:l}}function Vr(t){return Dt.customGrad(t)}var qr=pn({softmax_:function(t,e){void 0===e&&(e=-1);var n=Ze(t,"logits","softmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and dim was "+e);return Vr(function(t,n){var r=t.logSumExp([e],!0),o=t.toFloat().sub(r).exp();return n([o]),{value:o,gradFunc:function(t,n){var r=n[0],o=t.mul(r);return o.sub(o.sum([e],!0).mul(r))}}})(n)}}),Hr=pn({logSoftmax_:function(t,e){void 0===e&&(e=-1);var n=Ze(t,"logits","logSoftmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and axis was "+e);return Vr(function(t,n){var r=t.max(e,!0),o=t.sub(r),a=o.toFloat().sub(o.exp().sum(e,!0).log());return n([a]),{value:a,gradFunc:function(t,n){var r=n[0].exp();return t.sub(t.sum(e,!0).mul(r))}}})(n)}}),$r=function(){function t(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap;}return t.prototype.get=function(t){return this.data.has(t)||this.dataMover.moveData(this.backend,t),this.data.get(t)},t.prototype.set=function(t,e){this.data.set(t,e);},t.prototype.has=function(t){return this.data.has(t)},t.prototype.delete=function(t){return this.data.delete(t)},t}();function Kr(t,e){for(var n=t.length,r=[],o=0;o1&&1===i&&r.unshift(a);}return r}function Xr(t,e){for(var n=[],r=0;r1)&&n.unshift(a);}return n}function Yr(t,e){for(var n=[],r=Math.max(t.length,e.length),o=0;oo}).sort(function(t,e){return e.score-t.score}),i=[],s=0;s=0;--p){if(go(t,c,i[p])>=r){h=!0;break}}if(!h&&(i.push(c),i.length>=n))break}return xn(i,"int32")}function go(t,e,n){var r=t.subarray(4*e,4*e+4),o=t.subarray(4*n,4*n+4),a=Math.min(r[0],r[2]),i=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(o[0],o[2]),c=Math.min(o[1],o[3]),h=Math.max(o[0],o[2]),p=Math.max(o[1],o[3]),f=(s-a)*(u-i),d=(h-l)*(p-c);if(f<=0||d<=0)return 0;var v=Math.max(a,l),m=Math.max(i,c),g=Math.min(s,h),y=Math.min(u,p),x=Math.max(g-v,0)*Math.max(y-m,0);return x/(f+d-x)}function yo(t,e,n){var r=new Array(t.rank).fill(0),o=t.shape.slice();return e.map(function(e){o[n]=e;var a=t.slice(r,o);return r[n]+=e,a})}function xo(t,e){for(var n=new Array(t.rank),r=0;r":"<",u=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+r+";\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < "+r+"; i++) {\n int inIdx = "+u+";\n float candidate = getA(batch, inIdx);\n if (candidate "+s+" bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n ";}}();function Io(t,e){return ["x","y","z","w","u","v"].slice(0,e).map(function(e){return t+"."+e})}function So(t,e){return 1===e?[t]:Io(t,e)}function No(){var t,e,n,r,o,a,i,u,l,c;return 2===s.getNumber("WEBGL_VERSION")?(t="#version 300 es",e="in",n="out",r="in",o="texture",a="outputColor",i="out vec4 outputColor;",u="\n bool isnan_custom(float val) {\n return (val > 0. || val < 0. || val == 0.) ? false : true;\n }\n ",l="\n const float INFINITY = uintBitsToFloat(uint(0x7f800000));\n ",c="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(t="",e="attribute",n="varying",r="varying",o="texture2D",a="gl_FragColor",i="",u="\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n ",l="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",c="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:t,attribute:e,varyingVs:n,varyingFs:r,texture2D:o,output:a,defineOutput:i,defineSpecialNaN:u,defineSpecialInf:l,defineRound:c}}function ko(t,e,n){void 0===n&&(n="index");var r=G(e);return r.map(function(e,o){return "int "+t[o]+" = "+n+" / "+e+"; "+(o===r.length-1?"int "+t[o+1]+" = "+n+" - "+t[o]+" * "+e:"index -= "+t[o]+" * "+e)+";"}).join("")}function Ao(t){var e=G(t).map(function(t){return t.toString()});return "\n int getFlatIndex(ivec3 coords) {\n return coords.x * "+e[0]+" + coords.y * "+e[1]+" + coords.z;\n }\n"}var To="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isnan(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n";function Do(t,e,n,r){var o=[];t.forEach(function(t){var e=y(t.shapeInfo.logicalShape);t.shapeInfo.isUniform?o.push("uniform float "+t.name+(e>1?"["+e+"]":"")+";"):(o.push("uniform sampler2D "+t.name+";"),o.push("uniform int offset"+t.name+";"));});var a,i,s=o.join("\n"),u=t.map(function(t){return function(t,e,n){void 0===n&&(n=!1);var r="";r+=n?Oo(t):_o(t);var o=t.shapeInfo.logicalShape,a=e.logicalShape;o.length<=a.length&&(r+=n?function(t,e){var n,r=t.name,o=r.charAt(0).toUpperCase()+r.slice(1),a="get"+o+"AtOutCoords",i=t.shapeInfo.logicalShape.length,s=e.logicalShape.length,u=Kr(t.shapeInfo.logicalShape,e.logicalShape),l=Uo(s),c=s-i,h=["x","y","z","w","u","v"];n=0===i?"":s<2&&u.length>=1?"coords = 0;":u.map(function(t){return "coords."+h[t+c]+" = 0;"}).join("\n");var p="";p=s<2&&i>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return "coords."+h[e+c]}).join(", ");var f="return outputValue;",d=1===y(t.shapeInfo.logicalShape),v=1===y(e.logicalShape);if(1!==i||d||v){if(d&&!v)f=1===s?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(u.length){var m=i-2,g=i-1;u.indexOf(m)>-1&&u.indexOf(g)>-1?f="return vec4(outputValue.x);":u.indexOf(m)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":u.indexOf(g)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);");}}else f="\n return vec4(outputValue.xy, outputValue.xy);\n ";return "\n vec4 "+a+"() {\n "+l+" coords = getOutputCoords();\n "+n+"\n vec4 outputValue = get"+o+"("+p+");\n "+f+"\n }\n "}(t,e):function(t,e){var n=t.name,r=n.charAt(0).toUpperCase()+n.slice(1),o="get"+r+"AtOutCoords",a=e.texShape,i=t.shapeInfo.texShape,s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length;if(!t.shapeInfo.isUniform&&s===u&&null==t.shapeInfo.flatOffset&&x(i,a))return "\n float "+o+"() {\n return sampleTexture("+n+", resultUV);\n }\n ";var l,c=Uo(u),h=Kr(t.shapeInfo.logicalShape,e.logicalShape),p=u-s,f=["x","y","z","w","u","v"];l=0===s?"":u<2&&h.length>=1?"coords = 0;":h.map(function(t){return "coords."+f[t+p]+" = 0;"}).join("\n");var d="";d=u<2&&s>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return "coords."+f[e+p]}).join(", ");return "\n float "+o+"() {\n "+c+" coords = getOutputCoords();\n "+l+"\n return get"+r+"("+d+");\n }\n "}(t,e));return r}(t,e,r)}).join("\n"),l=e.texShape,c=No(),h=function(t){return "\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return "+t.texture2D+"(textureSampler, uv).r;\n }\n "}(c),p=function(t){return t.version+"\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n "+t.varyingFs+" vec2 resultUV;\n "+t.defineOutput+"\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n #define isnan(value) isnan_custom(value)\n "+t.defineSpecialNaN+"\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n\n "+t.defineSpecialInf+"\n "+t.defineRound+"\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n "+Mo+"\n "+Fo+"\n "+Bo+"\n "}(c);return e.isPacked?(a=function(t,e){switch(t.length){case 0:return "\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(1===n[0])return "\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+n[1]+".0);\n }\n ";if(1===n[1])return "\n int getOutputCoords() {\n return 2 * int(resultUV.y * "+n[0]+".0);\n }\n ";return "\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n return 2 * (resTexRC.x * "+n[1]+" + resTexRC.y);\n }\n "}(0,e);case 2:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(x(t,e))return "\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2("+n[0]+", "+n[1]+"));\n }\n ";var r=Math.ceil(t[1]/2);return "\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n int r = 2 * (index / "+r+");\n int c = imod(index, "+r+") * 2;\n\n return ivec2(r, c);\n }\n "}(t,e);case 3:return n=t,r=e,o=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=Math.ceil(n[2]/2),i=a*Math.ceil(n[1]/2),"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+o[0]+", "+o[1]+"));\n int index = resTexRC.x * "+o[1]+" + resTexRC.y;\n\n int b = index / "+i+";\n index -= b * "+i+";\n\n int r = 2 * (index / "+a+");\n int c = imod(index, "+a+") * 2;\n\n return ivec3(b, r, c);\n }\n ";default:return function(t,e){for(var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],r=Math.ceil(t[t.length-1]/2),o=r*Math.ceil(t[t.length-2]/2),a=o,i="",s="b, r, c",u=2;u2,function(){return "Packed arg"+(n.charAt(0).toUpperCase()+n.slice(1))+" supports only inputs with rank above 2."});var o=t[t.length-1],a=Math.ceil(o/e);this.outputShape=t.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");var i,s,u=this.outputShape,l=u.length,c=Uo(l),h=So("coords",l);if(1===a){var p=Uo(s=l+1);i="\n "+p+" sourceLocR = "+p+"("+h.join()+", 0);\n ++"+h[l-1]+";\n "+p+" sourceLocG = "+p+"("+h.join()+", 0);\n ++"+h[l-2]+";\n "+p+" sourceLocA = "+p+"("+h.join()+", 0);\n --"+h[l-1]+";\n "+p+" sourceLocB = "+p+"("+h.join()+", 0);\n --"+h[l-2]+";";}else s=l,i="\n "+c+" sourceLocR = coords;\n ++"+h[l-1]+";\n "+c+" sourceLocG = coords;\n ++"+h[l-2]+";\n "+c+" sourceLocA = coords;\n --"+h[l-1]+";\n "+c+" sourceLocB = coords;\n --"+h[l-2]+";";var f=["x","y","z","w","u","v"].slice(0,s),v="."+f[s-1],m=f.map(function(t){return "int "+t}),g=So("sourceLocR",s-1).concat("inIdx.r"),y=So("sourceLocG",s-1).concat("inIdx.g"),x=So("sourceLocB",s-1).concat("inIdx.b"),b=So("sourceLocA",s-1).concat("inIdx.a"),w="max"===n?"greaterThan":"lessThan",C=r?"":"\n inIdx = round(vec4(getBestIndicesAChannel("+g.join()+"),\n getBestIndicesAChannel("+y.join()+"),\n getBestIndicesAChannel("+x.join()+"),\n getBestIndicesAChannel("+b.join()+")));",E="vec4(\n getAChannel("+g.join()+"),\n hasNextCol ? getAChannel("+y.join()+") : 0.,\n hasNextRow ? getAChannel("+x.join()+") : 0.,\n hasNextRow && hasNextCol ? getAChannel("+b.join()+") : 0.)",R=r?"":"\n float getBestIndicesAChannel("+m.join()+") {\n return getChannel(getBestIndicesA("+f.join()+"),\n vec2("+f.slice(-2).join()+"));\n }";this.userCode="\n float getAChannel("+m.join()+") {\n return getChannel(getA("+f.join()+"),\n vec2("+f.slice(-2).join()+"));\n }\n "+R+"\n void main() {\n "+c+" coords = getOutputCoords();\n bool hasNextCol = "+h[l-1]+" < "+(u[l-1]-1)+";\n bool hasNextRow = "+h[l-2]+" < "+(u[l-2]-1)+";\n "+i+"\n ivec4 srcIdx = ivec4(sourceLocR"+v+", sourceLocG"+v+",\n sourceLocB"+v+", sourceLocA"+v+") * "+e+";\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = "+E+";\n\n for (int i = 0; i < "+e+"; i++) {\n inIdx = srcIdx;\n "+C+"\n vec4 candidate = "+E+";\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4("+w+"(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n ";}}(),qo=function(){return function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a=t.dilationHeight,i=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,l=s-1-t.padInfo.top,c=u-1-t.padInfo.left,h=1/(e*n);this.userCode="\n const ivec2 pads = ivec2("+l+", "+c+");\n const float avgMultiplier = float("+h+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+s+";\n wR += "+a+") {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+u+";\n wC+= "+i+") {\n float dyC = float(dyCCorner + wC) / "+o+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n ";}}(),Ho=function(){return function(t,e,n,r,o,a){this.outputShape=[],this.variableNames=["x","mean","variance"],Yr(t,e),Yr(t,n);var i="0.0";null!=r&&(Yr(t,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="1.0";null!=o&&(Yr(t,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = "+i+";\n float scale = "+s+";\n float inv = scale * inversesqrt(variance + float("+a+"));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n ";}}(),$o=function(){return function(t,e,n,r,o,a){this.usesPackedTextures=!0,this.variableNames=["x","mean","variance"],Yr(t,e),Yr(t,n);var i="vec4(0.0)";null!=r&&(Yr(t,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=o&&(Yr(t,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n vec4 offset = "+i+";\n vec4 scale = "+s+";\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4("+a+"));\n\n setOutput((x - mean) * inv + offset);\n }\n ";}}(),jo="return areal * breal - aimag * bimag;",Ko="return areal * bimag + aimag * breal;",Xo=function(){return function(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Yr(e,n),this.userCode="\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n "+t+"\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n ";}}(),Yo="return a + b;",Qo="return a - b;",Jo="return a * b;",Zo=function(){return function(t,e,n){this.variableNames=["A","B"],this.outputShape=Yr(e,n),this.userCode="\n float binaryOperation(float a, float b) {\n "+t+"\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n ";}}(),ta=function(){return function(t,e,n,r){void 0===r&&(r=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.usesPackedTextures=!0,this.outputShape=Yr(e,n);var o=this.outputShape.length,a="";if(r)if(0===o||1===y(this.outputShape))a="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(a="\n "+Uo(o)+" coords = getOutputCoords();\n ",1===o)a+="\n result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ";else{var i=So("coords",o);a+="\n bool nextRowOutOfBounds =\n ("+i[o-2]+" + 1) >= "+this.outputShape[o-2]+";\n bool nextColOutOfBounds =\n ("+i[o-1]+" + 1) >= "+this.outputShape[o-1]+";\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n ";}this.userCode="\n vec4 binaryOperation(vec4 a, vec4 b) {\n "+t+"\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n "+a+"\n\n setOutput(result);\n }\n ";}}(),ea=function(){function t(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\n uniform float min;\n uniform float max;\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, min, max));\n }\n ";}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,o){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(o,"min"),n.maxLoc=r.getUniformLocationNoThrow(o,"max")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e);}},t}(),na=function(){function t(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t,this.userCode="\n uniform float min;\n uniform float max;\n\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(min), vec4(max)));\n }\n ";}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,o){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(o,"min"),n.maxLoc=r.getUniformLocationNoThrow(o,"max")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e);}},t}(),ra=function(){return function(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode="\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\n }\n ";}}(),oa=function(){return function(t){this.outputShape=[],this.outputShape=hn(t,1),this.variableNames=t.map(function(t,e){return "T"+e});var e=new Array(t.length-1);e[0]=t[0][1];for(var n=1;n= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+o+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n ";}}(),sa=function(){return function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a=e-1-t.padInfo.top,i=n-1-t.padInfo.left;this.userCode="\n const ivec2 pads = ivec2("+a+", "+i+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+o+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n ";}}(),ua=function(){return function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,o=t.padInfo.front,a=t.padInfo.top,i=t.padInfo.left;this.userCode="\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yF = 0; yF < "+t.outDepth+"; yF++) {\n int xF = wF + yF * "+e+" - "+o+";\n\n if (xF < 0 || xF >= "+t.inDepth+") {\n continue;\n }\n\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+n+" - "+a+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+r+" - "+i+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n ";}}(),la=function(){return function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=e-1-t.padInfo.front,u=n-1-t.padInfo.top,l=r-1-t.padInfo.left;this.userCode="\n const ivec3 pads = ivec3("+s+", "+u+", "+l+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < "+e+"; wF++) {\n float dyF = float(dyFCorner + wF) / "+o+".0;\n\n if (dyF < 0.0 || dyF >= "+t.outDepth+".0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = "+e+" - 1 - wF;\n\n for (int wR = 0; wR < "+n+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+a+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+n+" - 1 - wR;\n\n for (int wC = 0; wC < "+r+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+r+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n ";}}(),ca=function(){return function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,o=t.padInfo.left,a=t.outChannels/t.inChannels;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * "+a+" + dm;\n\n float dotProd = 0.0;\n\n // TODO: Vec4 over the batch size\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+r+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+o+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n ";}}(),ha=function(){return function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a=e-1-t.padInfo.top,i=n-1-t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode="\n const ivec2 pads = ivec2("+a+", "+i+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+o+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n // TODO: Vec4 over the channelMul\n for (int dm = 0; dm < "+s+"; dm++) {\n int d2 = d1 * "+s+" + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n ";}}(),pa=function(){return function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.top,n=t.padInfo.left,r=t.strideHeight,o=t.strideWidth,a=t.dilationHeight,i=t.dilationWidth,s=t.filterHeight,u=t.filterWidth,l=4*Math.floor(t.inChannels/4),c=t.inChannels%4;this.userCode="\n const ivec2 strides = ivec2("+r+", "+o+");\n const ivec2 pads = ivec2("+e+", "+n+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+s+"; wR++) {\n int xR = xRCorner + wR * "+a+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+u+"; wC++) {\n int xC = xCCorner + wC * "+i+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+l+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===c)+") {\n dotProd +=\n getX(batch, xR, xC, "+l+") *\n getW(wR, wC, "+l+", d2);\n } else if ("+(2===c)+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+l+"),\n getX(batch, xR, xC, "+l+" + 1)\n );\n vec2 wValues = vec2(\n getW(wR, wC, "+l+", d2),\n getW(wR, wC, "+l+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===c)+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+l+"),\n getX(batch, xR, xC, "+l+" + 1),\n getX(batch, xR, xC, "+l+" + 2)\n );\n vec3 wValues = vec3(\n getW(wR, wC, "+l+", d2),\n getW(wR, wC, "+l+" + 1, d2),\n getW(wR, wC, "+l+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n setOutput(dotProd);\n }\n ";}}(),fa=function(){return function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,n=t.padInfo.top,r=t.padInfo.left,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.filterDepth,h=t.filterHeight,p=t.filterWidth,f=4*Math.floor(t.inChannels/4),d=t.inChannels%4;this.userCode="\n const ivec3 strides = ivec3("+o+", "+a+", "+i+");\n const ivec3 pads = ivec3("+e+", "+n+", "+r+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < "+c+"; wF++) {\n int xF = xFCorner + wF * "+s+";\n\n if (xF < 0 || xF >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+h+"; wR++) {\n int xR = xRCorner + wR * "+u+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+"; wC++) {\n int xC = xCCorner + wC * "+l+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+f+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===d)+") {\n dotProd +=\n getX(batch, xF, xR, xC, "+f+") *\n getW(wF, wR, wC, "+f+", d2);\n } else if ("+(2===d)+") {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, "+f+"),\n getX(batch, xF, xR, xC, "+f+" + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, "+f+", d2),\n getW(wF, wR, wC, "+f+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===d)+") {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, "+f+"),\n getX(batch, xF, xR, xC, "+f+" + 1),\n getX(batch, xF, xR, xC, "+f+" + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, "+f+", d2),\n getW(wF, wR, wC, "+f+" + 1, d2),\n getW(wF, wR, wC, "+f+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n ";}}(),da=function(){return function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.inHeight,n=t.inWidth,r=t.padInfo.top,o=t.padInfo.left,a=t.strideHeight,i=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,l=t.filterHeight,c=t.filterWidth,h=t.outChannels/t.inChannels;this.userCode="\n const ivec2 strides = ivec2("+a+", "+i+");\n const ivec2 pads = ivec2("+r+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / "+h+";\n int q = d2 - d1 * "+h+";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TODO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+l+"; wR++) {\n int xR = xRCorner + wR * "+s+";\n\n if (xR < 0 || xR >= "+e+") {\n continue;\n }\n\n for (int wC = 0; wC < "+c+"; wC++) {\n int xC = xCCorner + wC * "+u+";\n\n if (xC < 0 || xC >= "+n+") {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n setOutput(dotProd);\n }\n ";}}(),va=function(){return function(t){this.variableNames=["x","W"],this.usesPackedTextures=!0,this.outputShape=t.outShape;for(var e=t.inHeight,n=t.inWidth,r=t.padInfo.top,o=t.padInfo.left,a=t.strideHeight,i=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,l=t.filterHeight,c=t.filterWidth,h=c,f="int xR; int xC; int xCOffset;",d=0;d= 0 && xR < "+e+" && xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+v+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+d+"C"+v+" = vec4(0.);\n }\n\n xCOffset = xC + 1 - 2;\n if(xR >= 0 && xR < "+e+" && xCOffset >= 0 && xCOffset < "+n+") {\n vec4 previous = getX(batch, xR, xCOffset, d1);\n xR"+d+"C"+v+" = vec4(previous.zw, xTexelR"+d+"C"+v+".xy);\n } else {\n xR"+d+"C"+v+" = vec4(0, 0, xTexelR"+d+"C"+v+".xy);\n }\n ":"\n if(xR >= 0 && xR < "+e+" && xC >= 0 && xC < "+n+") {\n xTexelR"+d+"C"+v+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+d+"C"+v+" = vec4(0.);\n }\n\n xR"+d+"C"+v+" = xTexelR"+d+"C"+v+";\n ",v+1= 0 && xR < "+e+" &&\n xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n }\n ",u>1&&(f+="\n xCOffset -= 2;\n if(xR >= 0 && xR < "+e+" &&\n xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+v+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+d+"C"+v+" = vec4(0.);\n }\n "),f+="\n xR"+d+"C"+(v+1)+" = vec4(\n xTexelR"+d+"C"+v+".zw, xTexelR"+d+"C"+(v+2)+".xy);\n "):f+="\n xCOffset = xC + "+g+";\n\n if(xR >= 0 && xR < "+e+" &&\n xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n }\n\n xR"+d+"C"+(v+1)+" = xTexelR"+d+"C"+(v+2)+";\n ";}}else v= 0 && xR < "+e+") {\n ",o%2==1?(f+="\n xCOffset = xC + 1 - "+i+";\n if(xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+v+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+d+"C"+v+" = vec4(0.);\n }\n\n if(xC + 1 >= 0 && xC + 1 < "+n+") {\n xTexelR"+d+"C"+(v+2)+" = getX(batch, xR, xC + 1, d1);\n } else {\n xTexelR"+d+"C"+(v+2)+" = vec4(0.);\n }\n\n xR"+d+"C"+v+" = vec4(\n xTexelR"+d+"C"+v+".zw, xTexelR"+d+"C"+(v+2)+".zw);\n ",v+1= 0 && xCOffset < "+n+") {\n final = getX(batch, xR, xCOffset, d1);\n }\n xR"+d+"C"+(v+1)+" = vec4(xTexelR"+d+"C"+(v+2)+".xy, final.xy);\n ")):(f+="\n if(xC >= 0 && xC < "+n+") {\n xTexelR"+d+"C"+v+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+d+"C"+v+" = vec4(0.);\n }\n\n xCOffset = xC + "+i+";\n if(xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+d+"C"+(v+2)+" = vec4(0.);\n }\n\n xR"+d+"C"+v+" = vec4(\n xTexelR"+d+"C"+v+".xy, xTexelR"+d+"C"+(v+2)+".xy);\n ",v+11?[""+(i-1)/(c-1),"(y2-y1) * height_ratio","y1*"+d+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+d],g=m[0],y=m[1],x=m[2],b=h>1?[""+(s-1)/(h-1),"(x2-x1) * width_ratio","x1*"+v+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+v],w=b[0],C=b[1],E=b[2];this.userCode="\n const float height_ratio = float("+g+");\n const float width_ratio = float("+w+");\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= "+a+") {\n return;\n }\n\n float height_scale = "+y+";\n float width_scale = "+C+";\n\n float in_y = "+x+";\n if( in_y < 0.0 || in_y > "+d+" ) {\n setOutput(float("+o+"));\n return;\n }\n float in_x = "+E+";\n if( in_x < 0.0 || in_x > "+v+" ) {\n setOutput(float("+o+"));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if("+p+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n ";}}(),ga=function(){return function(t,e,n){this.variableNames=["x"],this.outputShape=t;var r=t.length,o=t[t.length-1],a=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+o+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+Uo(r)+" coords = getOutputCoords();\n int end = "+ya(r,"coords")+";\n float val = 0.0;\n for (int i = "+o+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+a+" end) {\n continue;\n }\n if (idx == end && "+e+") {\n continue;\n }\n "+ya(r,"coords")+" = idx;\n val += getX("+function(t,e){if(1===t)return ""+e;if(2===t)return e+".x, "+e+".y";if(3===t)return e+".x, "+e+".y, "+e+".z";if(4===t)return e+".x, "+e+".y, "+e+".z, "+e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}(r,"coords")+");\n }\n setOutput(val);\n }\n ";}}();function ya(t,e){if(1===t)return ""+e;if(2===t)return e+".y";if(3===t)return e+".z";if(4===t)return e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}var xa=function(){return function(t,e){this.variableNames=["A"];var n=No();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+ko(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = 4 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n "+n.output+" = result;\n }\n ";}}(),ba=function(){return function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0;var n=No();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+ko(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = 4 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n "+n.output+" = result;\n }\n ";}}(),wa=function(){function t(t,e,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=n,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = "+this.getHeightCoordString()+";\n int w = "+this.getWidthCoordString()+";\n int d = "+this.getDepthCoordString()+";\n\n int in_h = h / "+e+";\n int offset_h = imod(h, "+e+");\n int in_w = w / "+e+";\n int offset_w = imod(w, "+e+");\n int offset_d = (offset_h * "+e+" + offset_w) *\n "+this.getOutputDepthSize()+";\n int in_d = d + offset_d;\n\n float result = "+this.getInputSamplingString()+";\n setOutput(result);\n }\n ";}return t.prototype.getHeightCoordString=function(){return "NHWC"===this.dataFormat?"coords[1]":"coords[2]"},t.prototype.getWidthCoordString=function(){return "NHWC"===this.dataFormat?"coords[2]":"coords[3]"},t.prototype.getDepthCoordString=function(){return "NHWC"===this.dataFormat?"coords[3]":"coords[1]"},t.prototype.getOutputDepthSize=function(){return "NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},t.prototype.getInputSamplingString=function(){return "NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},t}(),Ca=function(){return function(t){this.variableNames=["A"];var e=No();this.outputShape=t,this.userCode="\n "+To+"\n\n void main() {\n float x = getAAtOutCoords();\n "+e.output+" = encode_float(x);\n }\n ";}}(),Ea=function(){return function(t){this.variableNames=["A"],this.usesPackedTextures=!0;var e=No();this.outputShape=t,this.userCode="\n "+To+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n "+e.output+" = encode_float(x);\n }\n ";}}(),Ra=function(){return function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=No(),o=e[0],a=e[1];this.outputShape=t;var i="result";n&&(i="floor(result * 255. + 0.5)"),this.userCode="\n "+Ao(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n \n int r = flatIndex / "+a+";\n int c = imod(flatIndex, "+a+");\n vec2 uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+o+".0);\n vec4 values = "+r.texture2D+"(A, uv);\n\n float result;\n\n if(offset == 0) {\n result = values[0];\n } else if(offset == 1) {\n result = values[1];\n } else if(offset == 2) {\n result = values[2];\n } else {\n result = values[3];\n }\n\n "+r.output+" = vec4("+i+", 0., 0., 0.);\n }\n ";}}(),Ia=function(){return function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=No(),o=e[0],a=e[1];this.outputShape=t;var i="",s="result";n&&(s="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var l=0;l<=1;l++){var c=2*u+l;i+="\n localCoords = coords;\n if(localCoords[2] + "+l+" < "+t[2]+") {\n localCoords[2] += "+l+";\n if(localCoords[1] + "+u+" < "+t[1]+") {\n localCoords[1] += "+u+";\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n \n flatIndex = idiv(flatIndex, 4, 1.);\n\n r = flatIndex / "+a+";\n c = imod(flatIndex, "+a+");\n uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+o+".0);\n values = "+r.texture2D+"(A, uv);\n\n if(offset == 0) {\n result["+c+"] = values[0];\n } else if(offset == 1) {\n result["+c+"] = values[1];\n } else if(offset == 2) {\n result["+c+"] = values[2];\n } else {\n result["+c+"] = values[3];\n }\n }\n }\n ";}this.userCode="\n "+Ao(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n \n "+i+"\n\n "+r.output+" = "+s+";\n }\n ";}}(),Sa="return real * expR - imag * expI;",Na="return real * expI + imag * expR;",ka=function(){return function(t,e,n){this.variableNames=["real","imag"];var r=e[1];this.outputShape=e;var o=n?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,a=n?r+".0":"1.0";this.userCode="\n const float exponentMultiplier = "+o+";\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n "+t+"\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float("+r+");\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < "+r+"; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / "+a+";\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n ";}}(),Aa=function(){function t(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode="\n uniform float value;\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n ";}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.valueLoc&&(e.valueLoc=n.getUniformLocationNoThrow(r,"value")),n.gl.uniform1f(e.valueLoc,t);}},t}(),Ta=function(){return function(t){this.variableNames=["A"];var e=No(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n\n vec4 values = "+e.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n ";}}(),Da=function(){return function(t){this.variableNames=["A"];var e=No(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n vec4 values = "+e.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n "+e.output+" = result;\n }\n ";}}(),_a=function(){return function(t,e,n){this.variableNames=["A","indices"];var r=t.slice();r[n]=e,this.outputShape=r,this.rank=r.length;var o=Uo(this.rank),a=function(t,e){var n=t.length;if(n>4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return "int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],a=0;a1?"strides[j]":"strides";this.userCode="\n "+r+" strides = "+r+"("+this.strides+");\n void main() {\n "+o+" coords = getOutputCoords();\n int flattenIndex = 0;\n for (int j = 0; j < "+this.sliceDim+"; j++) {\n int index = round(getIndices(coords[0], j));\n flattenIndex += index * "+a+";\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n ";}}();function Ba(t,e){return [e,t]}function Pa(t){var e=y(t);return C(Math.ceil(e/4))}function La(t,e){return [Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(t/2))]}function Wa(t,e){var n=No();return qt(t,e,n.version+"\n precision highp float;\n "+n.attribute+" vec3 clipSpacePos;\n "+n.attribute+" vec2 uv;\n "+n.varyingVs+" vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function Ua(t,e){return Jt(t,e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function za(t,e){return Zt(t,e,new Uint16Array([0,1,2,2,1,3]))}function Va(t,e){var n,r,o,a,i,u,l,c,h=t;return 2===s.getNumber("WEBGL_VERSION")?(n=h.R32F,r=h.R16F,o=h.RGBA16F,a=h.RGBA32F,i=h.RED,u=4,l=1,c=h.HALF_FLOAT):(n=t.RGBA,r=t.RGBA,o=t.RGBA,a=h.RGBA,i=t.RGBA,u=4,l=4,c=null!=e?e.HALF_FLOAT_OES:null),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:o,internalFormatPackedFloat:a,textureFormatFloat:i,downloadTextureFormat:t.RGBA,downloadUnpackNumChannels:u,defaultNumChannels:l,textureTypeHalfFloat:c}}function Ga(t,e,n,r,o,a,i){ee(n,r);var s=te(t,e),u=t.TEXTURE_2D;return Lt(t,e,function(){return t.bindTexture(u,s)}),Lt(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)}),Lt(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)}),Lt(t,e,function(){return t.texParameteri(u,t.TEXTURE_MIN_FILTER,t.NEAREST)}),Lt(t,e,function(){return t.texParameteri(u,t.TEXTURE_MAG_FILTER,t.NEAREST)}),Lt(t,e,function(){return t.texImage2D(u,0,o,n,r,0,a,i,null)}),Lt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)}),s}function qa(t,e,n,r,o){var a=Ba(n,r);return Ga(t,e,a[0],a[1],o.internalFormatFloat,o.textureFormatFloat,t.FLOAT)}function Ha(t,e,n,r,o){var a=Ba(n,r);return Ga(t,e,a[0],a[1],o.internalFormatHalfFloat,o.textureFormatFloat,o.textureTypeHalfFloat)}function $a(t,e,n,r,o){var a=Ba(n,r);return Ga(t,e,a[0],a[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function ja(t,e,n,r,o){var a=La(n,r);return Ga(t,e,a[0],a[1],o.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function Ka(t,e,n,r,o){var a=La(n,r);return Ga(t,e,a[0],a[1],o.internalFormatPackedHalfFloat,t.RGBA,o.textureTypeHalfFloat)}function Xa(t,e,n,r){return Lt(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,r)}),re(t,e,n,"clipSpacePos",r,3,20,0)&&re(t,e,n,"uv",r,2,20,12)}function Ya(t,e,n,r,o,a,i){var s,u,l;Lt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)}),a instanceof Uint8Array?(s=new Uint8Array(r*o*4),u=t.UNSIGNED_BYTE,l=t.RGBA):(s=new Float32Array(r*o*4),u=t.FLOAT,l=i.internalFormatPackedFloat),s.set(a),Lt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,l,r,o,0,t.RGBA,u,s)}),Lt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)});}function Qa(t,e,n,r){Lt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)}),r.data instanceof Uint8Array?Lt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,r.width,r.height,0,t.RGBA,t.UNSIGNED_BYTE,r.data)}):Lt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)}),Lt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)});}function Ja(t,e,n,r,o){var a=t.createBuffer();Lt(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,a)});var i=16*n*r;return Lt(t,e,function(){return t.bufferData(t.PIXEL_PACK_BUFFER,i,t.STREAM_READ)}),Lt(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,0)}),Lt(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,null)}),a}function Za(t,e,n){var r=t,o=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,e),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,o),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),o}function ti(t,e,n,r,o){var a=Ba(n,r),i=a[0],s=a[1],u=new Uint8Array(n*r*4);return Lt(t,e,function(){return t.readPixels(0,0,i,s,o.downloadTextureFormat,t.UNSIGNED_BYTE,u)}),new Float32Array(u.buffer)}function ei(t,e,n,r,o,a,i,s){var u=t,l=new Float32Array(function(t,e){var n=La(t,e);return n[0]*n[1]*4}(a,i));return u.bindBuffer(u.PIXEL_PACK_BUFFER,e),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,l),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),l}function ni(t,e,n,r){var o=new Float32Array(n*r*4);return Lt(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,o)}),o}!function(t){t[t.RENDER=0]="RENDER",t[t.UPLOAD=1]="UPLOAD",t[t.PIXELS=2]="PIXELS",t[t.DOWNLOAD=3]="DOWNLOAD";}(Oa||(Oa={})),function(t){t[t.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",t[t.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",t[t.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",t[t.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",t[t.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16";}(Ma||(Ma={}));var ri=Object.freeze({createVertexShader:Wa,createVertexBuffer:Ua,createIndexBuffer:za,getTextureConfig:Va,createFloat32MatrixTexture:qa,createFloat16MatrixTexture:Ha,createUnsignedBytesMatrixTexture:$a,createPackedMatrixTexture:ja,createFloat16PackedMatrixTexture:Ka,bindVertexProgramAttributeStreams:Xa,uploadDenseMatrixToTexture:Ya,uploadPixelDataToTexture:Qa,createBufferFromOutputTexture:Ja,downloadFloat32MatrixFromBuffer:Za,downloadByteEncodedFloatMatrixFromOutputTexture:ti,downloadPackedMatrixFromBuffer:ei,downloadMatrixFromPackedOutputTexture:ni}),oi=function(){function t(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=s.getNumber("WEBGL_VERSION");null!=t?(this.gl=t,Ft(e,t)):this.gl=Bt(e),1===s.getNumber("WEBGL_VERSION")?(this.textureFloatExtension=Gt(this.gl,this.debug,"OES_texture_float"),this.colorBufferFloatExtension=this.gl.getExtension("WEBGL_color_buffer_float"),s.getBool("WEBGL_RENDER_FLOAT32_ENABLED")||(this.textureHalfFloatExtension=Gt(this.gl,this.debug,"OES_texture_half_float"),this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float"))):this.colorBufferFloatExtension=Gt(this.gl,this.debug,"EXT_color_buffer_float"),this.vertexBuffer=Ua(this.gl,this.debug),this.indexBuffer=za(this.gl,this.debug),this.framebuffer=ne(this.gl,this.debug),this.textureConfig=Va(this.gl,this.textureHalfFloatExtension);}return Object.defineProperty(t.prototype,"debug",{get:function(){return s.getBool("DEBUG")},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){var t=this;if(!this.disposed){null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");var e=this.gl;Lt(e,this.debug,function(){return e.finish()}),Lt(e,this.debug,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),Lt(e,this.debug,function(){return e.deleteFramebuffer(t.framebuffer)}),Lt(e,this.debug,function(){return e.bindBuffer(e.ARRAY_BUFFER,null)}),Lt(e,this.debug,function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)}),Lt(e,this.debug,function(){return e.deleteBuffer(t.indexBuffer)}),this.disposed=!0;}},t.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),qa(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),Ha(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),$a(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),Qa(this.gl,this.debug,t,e);},t.prototype.uploadDenseMatrixToTexture=function(t,e,n,r){this.throwIfDisposed(),Ya(this.gl,this.debug,t,e,n,r,this.textureConfig);},t.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),Ka(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),ja(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(le(this.gl,this.debug,this.framebuffer),this.outputTexture=null),Lt(this.gl,this.debug,function(){return e.gl.deleteTexture(t)});},t.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,function(){return ti(r.gl,r.debug,e,n,r.textureConfig)})},t.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,r,o,a){return ei(this.gl,t,0,0,0,o,a,this.textureConfig)},t.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return Za(this.gl,t,e)},t.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var r=Ja(this.gl,this.debug,e,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r},t.prototype.createAndWaitForFence=function(){var t=this.createFence(this.gl);return this.pollFence(t)},t.prototype.createFence=function(t){var e,n,r=this;if(s.getBool("WEBGL_FENCE_API_ENABLED")){var o=t,a=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),n=function(){var t=o.clientWaitSync(a,0,0);return t===o.ALREADY_SIGNALED||t===o.CONDITION_SATISFIED},e=a;}else s.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(e,s.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):n=function(){return !0};return {query:e,isFencePassed:n}},t.prototype.downloadMatrixFromPackedTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,function(){return ni(r.gl,r.debug,e,n)})},t.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=Ht(e,this.debug,t),r=Wa(e,this.debug),o=Xt(e,this.debug);return Lt(e,this.debug,function(){return e.attachShader(o,r)}),Lt(e,this.debug,function(){return e.attachShader(o,n)}),Yt(e,this.debug,o),this.debug&&Qt(e,this.debug,o),this.vertexAttrsAreBound||(this.setProgram(o),this.vertexAttrsAreBound=Xa(e,this.debug,this.program,this.vertexBuffer)),o},t.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&Lt(this.gl,this.debug,function(){return e.gl.deleteProgram(t)});},t.prototype.setProgram=function(t){var e=this;this.throwIfDisposed(),this.program=t,null!=this.program&&this.debug&&Qt(this.gl,this.debug,this.program),Lt(this.gl,this.debug,function(){return e.gl.useProgram(t)});},t.prototype.getUniformLocation=function(t,e,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?ae(this.gl,this.debug,t,e):ie(this.gl,t,e)},t.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),Lt(this.gl,this.debug,function(){return n.gl.getAttribLocation(t,e)})},t.prototype.getUniformLocationNoThrow=function(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)},t.prototype.setInputMatrixTexture=function(t,e,n){this.throwIfDisposed(),this.throwIfNoProgram(),se(this.gl,this.debug,this.program,t,e,n);},t.prototype.setOutputMatrixTexture=function(t,e,n){this.setOutputMatrixTextureDriver(t,n,e);},t.prototype.setOutputPackedMatrixTexture=function(t,e,n){this.throwIfDisposed();var r=La(e,n),o=r[0],a=r[1];this.setOutputMatrixTextureDriver(t,o,a);},t.prototype.setOutputMatrixWriteRegion=function(t,e,n,r){this.setOutputMatrixWriteRegionDriver(n,t,r,e);},t.prototype.setOutputPackedMatrixWriteRegion=function(t,e,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},t.prototype.debugValidate=function(){null!=this.program&&Qt(this.gl,this.debug,this.program),ce(this.gl);},t.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),Lt(t,this.debug,function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)});},t.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),Lt(this.gl,this.debug,function(){return t.gl.finish()});},t.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=Gt(this.gl,this.debug,2===s.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},t.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},t.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},t.prototype.beginQuery=function(){if(2===s.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.gl,e=this.getQueryTimerExtensionWebGL2(),n=t.createQuery();return t.beginQuery(e.TIME_ELAPSED_EXT,n),n}var r=this.getQueryTimerExtensionWebGL1(),o=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,o),o},t.prototype.endQuery=function(){if(2!==s.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.getQueryTimerExtensionWebGL1();t.endQueryEXT(t.TIME_ELAPSED_EXT);}else{var e=this.gl,n=this.getQueryTimerExtensionWebGL2();e.endQuery(n.TIME_ELAPSED_EXT);}},t.prototype.waitForQueryAndGetTime=function(t){return r(this,void 0,void 0,function(){var e=this;return o(this,function(n){switch(n.label){case 0:return [4,R(function(){return e.disposed||e.isQueryAvailable(t,s.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return n.sent(),[2,this.getQueryTime(t,s.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},t.prototype.getQueryTime=function(t,e){if(0===e)return null;if(2===e){var n=this.gl;return n.getQueryParameter(t,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(t,r.QUERY_RESULT_EXT)/1e6},t.prototype.isQueryAvailable=function(t,e){if(0===e)return !0;if(2===e){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),o=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),o&&!this.disjoint}o=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),o&&!this.disjoint},t.prototype.pollFence=function(t){var e=this;return new Promise(function(n){e.addItemToPoll(function(){return t.isFencePassed()},function(){return n()});})},t.prototype.pollItems=function(){for(var t=function(t){for(var e=0;e1||R(function(){return n.pollItems(),0===n.itemsToPoll.length});},t.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),ue(this.gl,this.debug,t,this.framebuffer),this.debug&&ce(this.gl);},t.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(ue(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&ce(this.gl)):le(this.gl,this.debug,this.framebuffer);},t.prototype.downloadMatrixDriver=function(t,e){this.bindTextureToFrameBuffer(t);var n=e();return this.unbindTextureToFrameBuffer(),n},t.prototype.setOutputMatrixTextureDriver=function(t,e,n){this.throwIfDisposed();var r=this.gl;ue(r,this.debug,t,this.framebuffer),this.debug&&ce(r),this.outputTexture=t,Lt(r,this.debug,function(){return r.viewport(0,0,e,n)}),Lt(r,this.debug,function(){return r.scissor(0,0,e,n)});},t.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var o=this;this.throwIfDisposed(),Lt(this.gl,this.debug,function(){return o.gl.scissor(t,e,n,r)});},t.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},t.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},t}();function ai(t,e){if(t.length!==e.length)throw Error("Binary was compiled with "+t.length+" inputs, but was executed with "+e.length+" inputs");t.forEach(function(t,n){var r=t.logicalShape,o=e[n],a=o.shape;if(!x(r,a))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+a+" must match");if(!t.isUniform||!o.isUniform){var i=t.texShape,s=o.isUniform?null:o.texData.texShape;if(!x(i,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+i+" and "+s+" must match")}});}var ii=function(){return function(t,e,n){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;for(var r=n.filterWidth,o=n.inChannels,a=n.strideWidth,i=n.strideHeight,s=n.padInfo,u=n.outWidth,l=n.dilationWidth,c=n.dilationHeight,h=s.left,p=s.top,f=o*r,d=No(),v="",m=0;m<=1;m++)for(var g=0;g<=1;g++)v+="\n blockIndex = rc.y + "+g+";\n pos = rc.x + "+m+";\n \n if(blockIndex < "+t[1]+" && pos < "+t[0]+") {\n offsetY = int(blockIndex / ("+u+")) * "+i+" - "+p+";\n d0 = offsetY + "+c+" * (pos / "+f+");\n \n if(d0 < "+e[0]+" && d0 >= 0) {\n offsetX = int(mod(float(blockIndex), "+u+".) * "+a+". - "+h+".);\n d1 = offsetX + "+l+" * (int(mod(float(pos), "+f+".) / "+o+".));\n \n if(d1 < "+e[1]+" && d1 >= 0) {\n innerDims = vec2(d1, int(mod(float(pos), "+o+".)));\n result["+(2*m+g)+"] = getChannel(getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n \n }\n ";this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1;\n vec2 innerDims;\n\n "+v+"\n\n "+d.output+" = result;\n }\n ";}}(),si=function(){return function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[];var a,i=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.5===o?"inversesqrt("+u+")":1===o?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -"+i+"; j <= "+i+"; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= "+s+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+a+";\n setOutput(val);\n }\n ";}}(),ui=function(){return function(t,e,n,r,o){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=n,this.alpha=r,this.beta=o,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < "+this.depth+"; ++d) {\n int depthBegin = int(max(0.0, float(d - "+e+")));\n int depthEnd = int(min(float("+this.depth+"),\n float(d + "+e+" + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = "+this.depth+";\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float("+r+") * norm + float("+n+");\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float("+r+")\n * float("+o+")\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * "+o+");\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\n }\n ";}}(),li=function(){return function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[],this.usesPackedTextures=!0;var a,i=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.5===o?"inversesqrt("+u+")":1===o?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < "+this.outputShape[3]+";\n bool hasNextRow = c < "+this.outputShape[2]+";\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - "+i+";\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - "+i+"; j <= "+i+"; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2("+s+"));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * "+a+";\n setOutput(result);\n }\n ";}}(),ci=function(){return function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,o=t.effectiveFilterHeight,a=t.effectiveFilterWidth,i=o-1-t.padInfo.top,s=a-1-t.padInfo.left,u=o*a-1;this.userCode="\n const ivec2 pads = ivec2("+i+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+o+";\n wR += "+r+") {\n float dyR = float(dyRCorner + wR) / "+e+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+a+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+n+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = "+u+" - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * "+a+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n ";}}(),hi=function(){return function(t,e,n,r,o,a){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===a&&(a=null),this.variableNames=["matrixA","matrixB"],this.usesPackedTextures=!0,this.outputShape=e;var i=n?t[1]:t[2],s=Math.ceil(i/2),u=n?"i * 2, rc.y":"rc.y, i * 2",l=r?"rc.z, i * 2":"i * 2, rc.z",c=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],h=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],p="",f="";a&&(p="vec4 activation(vec4 x) {\n "+a+"\n }",f="result = activation(result);");var d=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),this.userCode="\n "+p+"\n\n const float sharedDimension = "+s+".0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+s+"; i++) {\n vec4 a = getMatrixA(rc.x, "+u+");\n vec4 b = getMatrixB(rc.x, "+l+");\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += ("+c[0]+" * "+h[0]+");\n result += ("+c[1]+" * "+h[1]+");\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n "+d+"\n\n "+f+"\n\n setOutput(result);\n }\n ";}}(),pi=function(){function t(t,e,n){this.variableNames=["probs"],this.outputShape=[t,n],this.userCode="\n uniform float seed;\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < "+(e-1)+"; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float("+(e-1)+"));\n }\n ";}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.seedLoc&&(e.seedLoc=n.getUniformLocation(r,"seed")),n.gl.uniform1f(e.seedLoc,t);}},t}(),fi=function(){return function(t,e,n,r){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float("+r+"), float("+n+"),\n float(index == coords.y)));\n }\n ";}}(),di=function(){return function(t){this.variableNames=["A"],this.outputShape=t;var e=t.length;if(0===e)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{var n=So("rc",e),r=Uo(e),o=function(t,e,n){if(1===t)return "rc > "+e[0];for(var r="",o=t-2;o= "+e[o],o= "+e+";\n bool rEdge = rp1 >= "+n+";\n "}(e,t[t.length-1],t[t.length-2],n),i=function(t,e){var n=t.length,r=function(t,e){for(var n=[],r=0;r<=1;r++)for(var o=0;o<=1;o++){for(var a=(0===r?"r":"rp1")+", "+(0===o?"c":"cp1"),i=2;i= "+t[0]+" ? 0. : getA(rc + 1),\n 0, 0":"getA("+r[0]+"),\n cEdge ? 0. : getA("+r[1]+"),\n rEdge ? 0. : getA("+r[2]+"),\n rEdge || cEdge ? 0. : getA("+r[3]+")"}(t,n);this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n\n if("+o+") {\n setOutput(vec4(0));\n } else {\n "+a+"\n\n setOutput(vec4("+i+"));\n }\n }\n ";}}}();var vi=function(){return function(t,e,n){this.variableNames=["x"],this.outputShape=e.map(function(e,n){return e[0]+t[n]+e[1]});var r=t.length,o=Uo(r),a=e.map(function(t){return t[0]}).join(","),i=e.map(function(e,n){return e[0]+t[n]}).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n "+o+" start = "+o+"("+a+");\n "+o+" end = "+o+"("+i+");\n\n void main() {\n "+o+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+n+"));\n } else {\n "+o+" coords = outC - start;\n setOutput(getX("+s+"));\n }\n }\n ":"\n int start = "+a+";\n int end = "+i+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n ";}}(),mi=function(){return function(t,e,n){this.variableNames=["x"],this.usesPackedTextures=!0,this.outputShape=e.map(function(e,n){return e[0]+t[n]+e[1]});for(var r=t.length,o=Uo(r),a=e.map(function(t){return t[0]}).join(","),i=e.map(function(e,n){return e[0]+t[n]}).join(","),s=So("rc",r),u=So("source",r),l=s[r-1]+" < "+this.outputShape[r-1],c=1===r?"source":"vec2("+u.slice(-2).join()+")",h=[o+" rc = outputLoc;",s[r-1]+" += 1;\n if("+l+") {\n ",1===r?"":"}\n rc = outputLoc;\n "+s[r-2]+" += 1;\n if("+s[r-2]+" < "+this.outputShape[r-2]+") {",1===r?"":" "+s[r-1]+" += 1;\n if("+l+") {"],p=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",f="",d=0,v=1===r?2:4;d= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+l+";\n wC += "+s+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = wR * "+l+" + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var d=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(d="avgValue / count");var v=4*Math.floor(r/4),m=r%4,g="\n if ("+p+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+o+", "+a+");\n const ivec2 pads = ivec2("+c+", "+h+");\n const float initializationValue = "+f+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= "+t.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4("+f+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+u+";\n wR += "+i+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+v+"; wC += 4) {\n int xC = xCCorner + wC * "+s+";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n getValue(batch, xR, xC + 3 * "+s+", d)\n );\n\n "+g+"\n }\n\n int xC = xCCorner + "+v+";\n if ("+(1===m)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+g+"\n } else if ("+(2===m)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n initializationValue,\n initializationValue\n );\n\n "+g+"\n } else if ("+(3===m)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n initializationValue\n );\n\n "+g+"\n }\n }\n setOutput("+d+");\n }\n ";}}}(),yi=function(){return function(t,e){this.variableNames=["x"];var n=t.windowSize,r=t.batchSize,o=t.inSize,a=Math.ceil(o/n);this.outputShape=[r,a];var i="0.0",s="";"prod"===e?i="1.0":"min"===e?(i="1.0 / 1e-20",s="min"):"max"===e&&(i="-1.0 / 1e-20",s="max");var u=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===e?u="sumValue":"prod"===e?u="prodValue":"all"===e?u="allValue":"any"===e&&(u="anyValue");var l=4*Math.floor(n/4),c=n%4,h="\n if ("+("sum"===e)+") {\n sumValue += dot(values, ones);\n } else if ("+("prod"===e)+") {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = "+s+"(values, minMaxValue);\n }\n ",p="vec4";"all"===e?(i="1.0",h="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",p="bvec4"):"any"===e&&(i="0.0",h="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",p="bvec4");var f="";o%n>0&&(f="\n if (inIdx < 0 || inIdx >= "+o+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+i+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+f+"\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+n+";\n\n vec4 minMaxValue = vec4("+i+");\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < "+l+"; i += 4) {\n int inIdx = inOffset + i;\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n "+h+"\n }\n\n int inIdx = inOffset + "+l+";\n if ("+(1===c)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+h+"\n } else if ("+(2===c)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+h+"\n } else if ("+(3===c)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+h+"\n }\n setOutput("+u+");\n }\n ";}}(),xi=function(){return function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;for(var n="",r=0;r<4;r++){var o="thisRC = rc;";r%2==1&&(o+="thisRC.z += 1;"),r>1&&(o+="thisRC.y += 1;"),n+="\n "+o+"\n "+(r>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+"\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result["+r+"] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n "+(r>0?"}":"")+"\n ";}this.userCode="\n \n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n "+ko(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n \n "+Ao(t)+"\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = "+t[1]+";\n int cols = "+t[2]+";\n\n "+n+"\n\n setOutput(result);\n }\n ";}}();var bi=function(){return function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],a=r[2],i=t.shape,s=i[1],u=i[2],l=[n&&s>1?o-1:o,n&&u>1?a-1:a],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],h=l[0]/c[0],p=l[1]/c[1],f=1/h,d=1/p,v=2*Math.ceil(f)+2,m=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+h+");\n const float widthScale = float("+p+");\n\n const float invHeightScale = float("+f+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+v+");\n const int winWidth = int("+m+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(o-1)+".0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), "+(a-1)+".0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n ";}}(),wi=function(){return function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+a+".0, "+i+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n ";}}(),Ci=function(){return function(t,e,n,r){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+",\n "+u[1]/l[1]+");\n const vec3 inputShapeRC = vec3("+a+".0, "+i+".0,\n "+i+".0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n \n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < "+(s-1)+"; \n bool hasNextRow = coords.z < "+(n-1)+";\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n ";}}(),Ei=function(){return function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],a=r[2],i=t.shape,s=i[1],u=i[2],l=[n&&s>1?o-1:o,n&&u>1?a-1:a],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],h=l[0]/c[0],p=l[1]/c[1],f=1/h,d=1/p,v=2*Math.ceil(f)+2,m=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+h+");\n const float widthScale = float("+p+");\n\n const float invHeightScale = float("+f+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+v+");\n const int winWidth = int("+m+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float sourceFracRow =\n float("+l[0]+") *\n (float(dyR) / float("+c[0]+"));\n\n float sourceFracCol =\n float("+l[1]+") *\n (float(dyC) / float("+c[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+o+") - 1),\n "+n+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+a+") - 1),\n "+n+" ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n ";}}(),Ri=function(){return function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],l=[r&&e>1?e-1:e,r&&n>1?n-1:n],c=r?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+a+".0, "+i+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+c+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n ";}}(),Ii=function(){return function(t,e){this.variableNames=["x"];var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");if(this.outputShape=t,1!==n){var r=t.map(function(n,r){return function(n){return -1!==e.indexOf(n)&&1!==t[n]?t[n]+" - coords["+n+"] - 1":"coords["+n+"]"}(r)}).join(","),o=Uo(n);this.userCode="\n void main() {\n "+o+" coords = getOutputCoords();\n setOutput(getX("+r+"));\n }\n ";}else this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+t[0]+" - coord - 1));\n }\n ";}}(),Si=function(){return function(t,e){this.variableNames=["x"],this.usesPackedTextures=!0;var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");this.outputShape=t;var r=So("rc",n),o=r[n-1]+" + 1 < "+this.outputShape[n-1],a=r[n-2]+" + 1 < "+this.outputShape[n-2],i=Uo(n);function s(n){var r=t.map(function(r,o){return function(n,r){return -1!==e.indexOf(n)&&1!==t[n]?t[n]+" - "+r[n]+" - 1":""+r[n]}(o,n)});return "getChannel(getX("+r.join(",")+"), vec2("+r.slice(-2).join(",")+"))"}this.userCode=1===n?"\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX("+t[0]+" - rc - 1),\n "+t[0]+" - rc - 1);\n if("+o+"){\n result.g = getChannel(getX("+t[0]+" - (rc + 1) - 1),\n "+t[0]+" - (rc + 1) - 1);\n }\n setOutput(result);\n }\n ":"\n void main() {\n "+i+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = "+function(t){return s(t)}(r.slice())+";\n if("+o+"){\n result.g = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",s(t)}(r.slice())+";\n }\n if("+a+") {\n result.b = "+function(t){return t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n if("+o+") {\n result.a = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n }\n }\n setOutput(result);\n }\n ";}}(),Ni=function(){return function(t,e,n,r,o,a,i){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;var s=Uo(o.length),u=Uo(a.length),l="";1===n?l="i":2===n&&(l="i, j");var c="getIndices("+l+")",h="";1===r?h="i":2===r&&(h="i, coords[1]");var p="getUpdates("+h+")",f=e>1?"strides[j]":"strides";this.userCode="\n "+s+" strides = "+s+"("+o+");\n\n void main() {\n "+u+" coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < "+t+"; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < "+e+"; j++) {\n int index = round("+c+");\n flattenedIndex += index * "+f+";\n }\n if (flattenedIndex == coords[0]) {\n sum += "+p+";\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n ";}}(),ki=function(){return function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,r=t.batchSize,o=t.inSize,a=t.numSegments,i=a*Math.ceil(o/n);this.outputShape=[r,i];var s=4*Math.floor(n/4),u=n%4,l="\n sumValue += dot(values, segFilter);\n ",c="";o%n>0&&(c="\n if (inIdx < 0 || inIdx >= "+o+") {\n return initializationValue;\n }\n ");var h="";o%n>0&&(h="\n if (inIdx < 0 || inIdx >= "+o+") {\n return -1.0;\n }\n "),this.userCode="\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n "+c+"\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n "+h+"\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n "+a+")) * float("+n+"));\n int currentSeg = int(mod(float(outIdx), float("+a+")));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < "+s+"; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n "+l+"\n }\n\n int inIdx = inOffset + "+s+";\n if ("+(1===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n "+l+"\n } else if ("+(2===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n "+l+"\n } else if ("+(3===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n "+l+"\n }\n setOutput(sumValue);\n }\n ";}}(),Ai=function(){return function(t,e,n){var r,o;if(this.variableNames=["c","a","b"],this.outputShape=e,n>4)throw Error("Where for rank "+n+" is not yet supported");if(1===n)o="resRC",r="resRC";else{for(var a=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],s=[],u=0;u= 1.0) {\n setOutput(getA("+o+"));\n } else {\n setOutput(getB("+o+"));\n }\n }\n ";}}(),Ti=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=Uo(this.rank),r="uniform int start["+this.rank+"];",o=function(t){if(1===t)return "sourceLoc";if(t<=6)return Di.slice(0,t).map(function(t){return "sourceLoc."+t}).join(",");throw Error("Slicing for rank "+t+" is not yet supported")}(this.rank);e="\n "+n+" sourceLoc;\n "+n+" coords = getOutputCoords();\n "+t.map(function(t,e){return "sourceLoc."+Di[e]+" = start["+e+"] + coords."+Di[e]+";"}).join("\n")+"\n ",this.userCode="\n "+r+"\n void main() {\n "+e+"\n setOutput(getSource("+o+"));\n }\n ";}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t);}},t}(),Di=["x","y","z","w","u","v"];var _i=function(){function t(t){this.variableNames=["source"],this.usesPackedTextures=!0,this.outputShape=t,this.rank=t.length;var e=Uo(this.rank),n=So("coords",this.rank),r=So("sourceLoc",this.rank),o=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",a="getChannel(getSource("+r.join()+"), "+o+")",i="\n result.x = "+a+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.y = "+a+";\n --"+r[this.rank-1]+";\n }\n ",s=1===this.rank?"":"\n --"+n[this.rank-1]+";\n if (++"+n[this.rank-2]+" < "+t[this.rank-2]+") {\n ++"+r[this.rank-2]+";\n result.z = "+a+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.w = "+a+";\n }\n }\n ",u=this.rank<=4?"sourceLoc = coords +\n "+e+"("+t.map(function(t,e){return "start["+e+"]"}).join()+");":t.map(function(t,e){return r[e]+" = "+n[e]+" + start["+e+"];"}).join("\n");this.userCode="\n uniform int start["+this.rank+"];\n void main() {\n "+e+" coords = getOutputCoords();\n "+e+" sourceLoc;\n "+u+" \n vec4 result = vec4(0.);\n "+i+"\n "+s+"\n setOutput(result);\n }\n ";}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t);}},t}(),Oi=function(){return function(t,e,n,r){this.variableNames=["x"];var o=n.filter(function(t,e){return -1===r.indexOf(e)});this.outputShape=o;var a=n.length,i=Uo(n.length),s=Uo(o.length),u="";if(1===a)u="coords * strides + begin";else{var l=0;u=n.map(function(t,e){return -1===r.indexOf(e)?(l++,1===o.length?"coords * strides["+e+"] + begin["+e+"]":"coords["+(l-1)+"] * strides["+e+"] + begin["+e+"]"):"begin["+e+"]"}).join(",");}this.userCode="\n "+i+" begin = "+i+"("+t+");\n "+i+" strides = "+i+"("+e+");\n\n void main() {\n "+s+" coords = getOutputCoords();\n setOutput(getX("+u+"));\n }\n ";}}(),Mi=function(){function t(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={};}return t.prototype.acquireTexture=function(t,e,n){var r,o=Fi(e,n),a=Bi(t,o,n);if(a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]),this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var i=this.freeTextures[a].shift();return this.usedTextures[a].push(i),i}return this.numUsedTextures++,this.log(),o===Ma.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):o===Ma.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):o===Ma.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):o===Ma.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):o===Ma.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[a].push(r),r},t.prototype.releaseTexture=function(t,e,n,r){if(null!=this.freeTextures){var o=Bi(e,Fi(n,r),r);o in this.freeTextures||(this.freeTextures[o]=[]),this.freeTextures[o].push(t),this.numFreeTextures++,this.numUsedTextures--;var a=this.usedTextures[o],i=a.indexOf(t);if(i<0)throw new Error("Cannot release a texture that was never provided by this texture manager");a.splice(i,1),this.log();}},t.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")");}},t.prototype.getNumUsedTextures=function(){return this.numUsedTextures},t.prototype.getNumFreeTextures=function(){return this.numFreeTextures},t.prototype.dispose=function(){var t=this;if(null!=this.freeTextures){for(var e in this.freeTextures)this.freeTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e);});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e);});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0;}},t}();function Fi(t,e){if(t===Oa.UPLOAD)return Ma.PACKED_2X2_FLOAT32;if(t===Oa.RENDER||null==t)return e?s.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?Ma.PACKED_2X2_FLOAT32:Ma.PACKED_2X2_FLOAT16:s.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?Ma.UNPACKED_FLOAT32:Ma.UNPACKED_FLOAT16;if(t===Oa.DOWNLOAD||t===Oa.PIXELS)return Ma.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+t)}function Bi(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var Pi=function(){return function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r5)throw Error("Tile for rank "+e+" is not yet supported");if(1===e)return "imod(resRC, "+t[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[],o=0;o6)throw Error("Transpose for rank "+e+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(e),o=0;o6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var o=Uo(this.rank),a=Io("rc",this.rank),i=new Array(this.rank);for(r=0;r= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n";var ji="return exp(x);",Ki=Gi+"\n return sin(x);\n",Xi=Gi+"\n return cos(x);\n",Yi=Gi+"\n return atan(x);\n",Qi=Gi+"\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));",Ji=Gi+"\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;",Zi="return x;",ts="\n vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",es=function(){return function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t,this.userCode="\n vec4 unaryOperation(vec4 x) {\n "+e+"\n }\n\n void main() {\n vec4 x = getAAtOutCoords();\n vec4 y = unaryOperation(x);\n\n setOutput(y);\n }\n ";}}(),ns=function(){return function(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;var e=t.length,n=So("rc",e),r=Uo(e),o=function(t,e){if(1===t)return "rc";for(var n="",r=0;r0?this.gpgpu.beginQuery():{startMs:K(),endMs:null}},t.prototype.endTimer=function(t){return s.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),t):(t.endMs=K(),t)},t.prototype.getQueryTime=function(t){return r(this,void 0,void 0,function(){var e;return o(this,function(n){return s.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?[2,this.gpgpu.waitForQueryAndGetTime(t)]:[2,(e=t).endMs-e.startMs]})})},t.prototype.disposeData=function(t){if(!this.pendingDisposal.has(t))if(this.pendingRead.has(t))this.pendingDisposal.add(t);else if(this.texData.has(t)){this.releaseGPUData(t);var e=this.texData.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.texData.delete(t);}},t.prototype.releaseGPUData=function(t){var e=this.texData.get(t),n=e.texture,r=e.dtype,o=e.texShape,a=e.usage,i=e.isPacked,s=e.slice,u=s&&s.origDataId||t,l=this.dataRefCount.get(u);l>1?this.dataRefCount.set(u,l-1):(this.dataRefCount.delete(u),null!=n&&(this.numBytesInGPU-=this.computeBytes(o,r),this.textureManager.releaseTexture(n,o,a,i)));var c=this.texData.get(t);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null;},t.prototype.getTexture=function(t){return this.uploadToGPU(t),this.texData.get(t).texture},t.prototype.getCPUBackend=function(){return s.getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=Dt.findBackend("cpu")),this.cpuBackend):null},t.prototype.shouldExecuteOnCPU=function(t,e){var n=this;return void 0===e&&(e=128),null!=this.getCPUBackend()&&t.every(function(t){return null==n.texData.get(t.dataId).texture&&t.sizes.getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var n=Math.floor(t.length/2),r=this.concat(t.slice(0,n),e),o=this.concat(t.slice(n),e);return this.concat([r,o],e)}if(s.getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&t[0].rank>1){var a=new aa(t.map(function(t){return t.shape}),e);return this.compileAndRun(a,t)}var i=hn(t.map(function(t){return t.shape}),e),u=t.map(function(t){return t.as2D(-1,y(t.shape.slice(e)))}),l=new oa(u.map(function(t){return t.shape}));return this.compileAndRun(l,u).reshape(i)},t.prototype.neg=function(t){var e=new Vi(t.shape,"return -x;");return this.compileAndRun(e,[t])},t.prototype.batchMatMul=function(t,e,n,r){var o=n?t.shape[2]:t.shape[1],a=r?e.shape[1]:e.shape[2],i=n?t.shape[1]:t.shape[2],s=t.shape[0];if((1===o||1===a)&&i>1e3){n&&(t=t.transpose([0,2,1])),r&&(e=e.transpose([0,2,1]));var u=1===a?t:t.as3D(s,i,1),l=1===a?2:1,c=1===a?e.as3D(s,1,i):e;return this.multiply(u,c).sum(l,!0)}var h=Ct(t.dtype,e.dtype),p=new hi(t.shape,[s,o,a],n,r),f=this.makePackedTensor(p.outputShape,h);return this.compileAndRun(p,[t,e],f)},t.prototype.fusedBatchMatMul=function(t,e,n,r,o,a){var i=n?t.shape[2]:t.shape[1],s=r?e.shape[1]:e.shape[2],u=t.shape[0],l=Ct(t.dtype,e.dtype),c=new hi(t.shape,[u,i,s],n,r,!!o,a?function(t,e){if(void 0===e&&(e=!1),"linear"===t)return e?Zi:qi;if("relu"===t)return e?ts:Hi;throw new Error("Activation "+t+" has not been implemented for the WebGL backend.")}(a,!0):null),h=this.makePackedTensor(c.outputShape,l),p=[t,e];return o&&p.push(o),this.compileAndRun(c,p,h)},t.prototype.multiply=function(t,e){if("complex64"===t.dtype){var n=this.texData.get(t.dataId),r=this.texData.get(e.dataId),o=new Xo(jo,t.shape,e.shape),a=new Xo(Ko,t.shape,e.shape),i=[this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag),this.makeComplexComponentTensorHandle(e,r.complexTensors.real),this.makeComplexComponentTensorHandle(e,r.complexTensors.imag)],u=this.compileAndRun(o,i),l=this.compileAndRun(a,i),c=this.complex(u,l);return u.dispose(),l.dispose(),c}if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.multiply(t,e);if(s.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Jo,t.dtype);var h=new Zo(Jo,t.shape,e.shape),p=this.makeOutputArray(h.outputShape,t.dtype);return this.compileAndRun(h,[t,e],p)},t.prototype.batchNormalization=function(t,e,n,r,o,a){var i=[t,e,n],u=null;null!=a&&(u=a.shape,i.push(a));var l=null;if(null!=o&&(l=o.shape,i.push(o)),s.getBool("WEBGL_PACK_NORMALIZATION")){var c=new $o(t.shape,e.shape,n.shape,u,l,r);return this.compileAndRun(c,i)}var h=new Ho(t.shape,e.shape,n.shape,u,l,r);return this.compileAndRun(h,i)},t.prototype.localResponseNormalization4D=function(t,e,n,r,o){var a=s.getBool("WEBGL_PACK_NORMALIZATION")?new li(t.shape,e,n,r,o):new si(t.shape,e,n,r,o);return this.compileAndRun(a,[t])},t.prototype.LRNGrad=function(t,e,n,r,o,a,i){var s=new ui(e.shape,r,o,a,i);return this.compileAndRun(s,[e,n,t])},t.prototype.tile=function(t,e){if("string"===t.dtype){var n=this.readSync(t.dataId).map(function(t){return J(t)});return xo(Xn(t.shape,t.dtype,n),e)}var r=new Pi(t.shape,e);return this.compileAndRun(r,[t])},t.prototype.pad=function(t,e,n){var r=s.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new mi(t.shape,e,n):new vi(t.shape,e,n);return this.compileAndRun(r,[t])},t.prototype.transpose=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.transpose(t,e);var n=s.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Wi(t.shape,e):new Li(t.shape,e);return this.compileAndRun(n,[t])},t.prototype.gather=function(t,e,n){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.gather(t,e,n);var r=new _a(t.shape,e.size,n);return this.compileAndRun(r,[t,e])},t.prototype.batchToSpaceND=function(t,e,n){d(t.rank<=4,function(){return "batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"});var r=e.reduce(function(t,e){return t*e}),o=Cr(t.shape,e,r),a=Er(o.length,e.length),i=Rr(t.shape,e,r),s=Ir(n,e.length),u=Sr(i,n,e.length);return t.reshape(o).transpose(a).reshape(i).slice(s,u)},t.prototype.spaceToBatchND=function(t,e,n){d(t.rank<=4,function(){return "spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"});var r=e.reduce(function(t,e){return t*e}),o=[[0,0]];o.push.apply(o,n);for(var a=1+e.length;ae||n===t?r=!0:n=V(t,n+1);return n}(i,o),u=new ki({windowSize:s,inSize:i,batchSize:a,numSegments:o},e),l=u.outputShape,c=l[0],h=l[1],p=this.makeOutputArray([c,h],r);return this.compileAndRun(u,[t,n],p),p.shape[1]===o?p:(n=An(0,o).tile([i/s]),this.segOpCompute(p,e,n,r,o))},t.prototype.argMinMaxReduce=function(t,e,n){var r=[e];if(an("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,t.rank),!s.getBool("WEBGL_PACK_REDUCE")||t.rank<=2){var o=rn(t.shape,r),a=o[0],i=y(o[1]),u=t.as2D(-1,i);return this.argReduce(u,n).reshape(a)}return this.argReducePacked(t,n)},t.prototype.argMin=function(t,e){return this.argMinMaxReduce(t,e,"min")},t.prototype.argMax=function(t,e){return this.argMinMaxReduce(t,e,"max")},t.prototype.cumsum=function(t,e,n,r){if(e!==t.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(t.rank-1)+" but got axis="+e);var o=new ga(t.shape,n,r);return this.compileAndRun(o,[t])},t.prototype.equal=function(t,e){if(s.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(equal(a, b));\n","bool");var n=new Zo("return float(a == b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.notEqual=function(t,e){if(s.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(notEqual(a, b));\n","bool");var n=new Zo("return float(a != b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.less=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.less(t,e);if(s.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThan(a, b));\n","bool");var n=new Zo("return float(a < b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.lessEqual=function(t,e){if(s.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThanEqual(a, b));\n","bool");var n=new Zo("return float(a <= b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.greater=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.greater(t,e);if(s.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThan(a, b));\n","bool");var n=new Zo("return float(a > b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.greaterEqual=function(t,e){if(s.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThanEqual(a, b));\n","bool");var n=new Zo("return float(a >= b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.logicalNot=function(t){var e=new Vi(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},t.prototype.logicalAnd=function(t,e){if(s.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n","bool");var n=new Zo("return float(a >= 1.0 && b >= 1.0);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.logicalOr=function(t,e){if(s.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n","bool");var n=new Zo("return float(a >= 1.0 || b >= 1.0);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.select=function(t,e,n){var r=new Ai(t.rank,e.shape,e.rank),o=this.makeOutputArray(r.outputShape,Ct(e.dtype,n.dtype));return this.compileAndRun(r,[t,e,n],o)},t.prototype.where=function(t){Ye("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return wo(t.shape,e)},t.prototype.topk=function(t,e,n){return bo(t.dataSync(),t.shape,t.dtype,e)},t.prototype.min=function(t,e){an("min",e,t.rank);var n=rn(t.shape,e),r=n[0],o=y(n[1]),a=t.as2D(-1,o);return this.reduce(a,"min",a.dtype).reshape(r)},t.prototype.minimum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.minimum(t,e);var n=s.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ta("\n vec4 result = vec4(min(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Zo("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return min(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.mod=function(t,e){var n=s.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ta("\n vec4 result = mod(a, b);\n vec4 isNaN = vec4(equal(b, vec4(0.0)));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Zo("if (b == 0.0) return NAN;\n return mod(a, b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.max=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.max(t,e);an("max",e,t.rank);var n=rn(t.shape,e),r=n[0],o=y(n[1]),a=t.as2D(-1,o);return this.reduce(a,"max",a.dtype).reshape(r)},t.prototype.maximum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.maximum(t,e);var n=s.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ta("\n vec4 result = vec4(max(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Zo("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return max(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.all=function(t,e){an("all",e,t.rank);var n=rn(t.shape,e),r=n[0],o=y(n[1]),a=t.as2D(-1,o);return this.reduce(a,"all",a.dtype).reshape(r)},t.prototype.any=function(t,e){an("any",e,t.rank);var n=rn(t.shape,e),r=n[0],o=y(n[1]),a=t.as2D(-1,o);return this.reduce(a,"any",a.dtype).reshape(r)},t.prototype.squaredDifference=function(t,e){var n=s.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ta("return (a - b) * (a - b);",t.shape,e.shape):new Zo("return (a - b) * (a - b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.realDivide=function(t,e){if(s.getBool("WEBGL_PACK_BINARY_OPERATIONS")){return this.packedBinaryOp(t,e,"\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(b.x == 0.0) {\n result.x = NAN;\n } else if(a.x == b.x) {\n result.x = 1.;\n }\n if(b.y == 0.0) {\n result.y = NAN;\n } else if(a.y == b.y) {\n result.y = 1.;\n }\n if(b.z == 0.0) {\n result.z = NAN;\n } else if(a.z == b.z) {\n result.z = 1.;\n }\n if(b.w == 0.0) {\n result.w = NAN;\n } else if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n","float32",!0)}var n=new Zo("\nif (b == 0.0) {\n return NAN;\n}\nif (a == b) {\n return 1.0;\n};\nreturn a / b;",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t,e],r)},t.prototype.floorDiv=function(t,e){if(s.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n ivec4 ia = round(a);\n ivec4 ib = round(b);\n bvec4 cond = notEqual(ib, ivec4(0));\n ivec4 result = ivec4(0);\n vec4 s = sign(a) * sign(b);\n\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n if (cond[0]) {\n result[0] = idiv(ia[0], ib[0], s[0]);\n }\n if (cond[1]) {\n result[1] = idiv(ia[1], ib[1], s[1]);\n }\n if (cond[2]) {\n result[2] = idiv(ia[2], ib[2], s[2]);\n }\n if (cond[3]) {\n result[3] = idiv(ia[3], ib[3], s[3]);\n }\n return vec4(result);\n","int32");var n=new Zo("\n float s = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n if (ib != 0) {\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n return float(idiv(ia, ib, s));\n } else {\n return NAN;\n }\n",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"int32");return this.compileAndRun(n,[t,e],r)},t.prototype.add=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,Yo);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.add(t,e);var n=Ct(t.dtype,e.dtype);if(s.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Yo,n);var r=new Zo(Yo,t.shape,e.shape),o=this.makeOutputArray(r.outputShape,n);return this.compileAndRun(r,[t,e],o)},t.prototype.packedBinaryOp=function(t,e,n,r,o){void 0===o&&(o=!1);var a=new ta(n,t.shape,e.shape,o),i=this.makePackedTensor(a.outputShape,r);return this.compileAndRun(a,[t,e],i)},t.prototype.complexSeparableBinaryOp=function(t,e,n){var r=this,o=this.texData.get(t.dataId),a=this.texData.get(e.dataId),i=[[o.complexTensors.real,a.complexTensors.real],[o.complexTensors.imag,a.complexTensors.imag]].map(function(o){var a=o[0],i=o[1],s=r.makeComplexComponentTensorHandle(t,a),u=r.makeComplexComponentTensorHandle(e,i),l=new Zo(n,t.shape,e.shape),c=r.makeOutputArray(l.outputShape,Ct(a.dtype,i.dtype));return r.compileAndRun(l,[s,u],c)}),s=i[0],u=i[1],l=this.complex(s,u);return s.dispose(),u.dispose(),l},t.prototype.makeComplexComponentTensorHandle=function(t,e){return {dataId:e.dataId,dtype:e.dtype,shape:t.shape}},t.prototype.addN=function(t){if(1===t.length)return t[0];if(t.length>s.get("WEBGL_MAX_TEXTURES_IN_SHADER")){var e=Math.floor(t.length/2),n=this.addN(t.slice(0,e)),r=this.addN(t.slice(e));return this.addN([n,r])}var o=t.map(function(t){return t.dtype}).reduce(function(t,e){return Ct(t,e)}),a=t.map(function(t){return t.shape}),i=s.getBool("WEBGL_PACK"),u=i?new Eo(t[0].shape,a):new Co(t[0].shape,a),l=i?this.makePackedTensor(u.outputShape,o):this.makeOutputArray(u.outputShape,o);return this.compileAndRun(u,t,l)},t.prototype.subtract=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,Qo);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.subtract(t,e);var n=Ct(t.dtype,e.dtype);if(s.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Qo,t.dtype);var r=new Zo(Qo,t.shape,e.shape),o=this.makeOutputArray(r.outputShape,n);return this.compileAndRun(r,[t,e],o)},t.prototype.pow=function(t,e){var n=s.getBool("WEBGL_PACK_BINARY_OPERATIONS"),r=n?new ta("\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\n\n vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Zo("\nif(a < 0.0 && floor(b) < b){\n return NAN;\n}\nif (b == 0.0) {\n return 1.0;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",t.shape,e.shape),o=Ct(t.dtype,e.dtype),a=n?this.makePackedTensor(r.outputShape,o):this.makeOutputArray(r.outputShape,o);return this.compileAndRun(r,[t,e],a)},t.prototype.ceil=function(t){var e=new Vi(t.shape,"return ceil(x);");return this.compileAndRun(e,[t])},t.prototype.floor=function(t){var e=new Vi(t.shape,"return floor(x);");return this.compileAndRun(e,[t])},t.prototype.sign=function(t){var e=new Vi(t.shape,"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n");return this.compileAndRun(e,[t])},t.prototype.isNaN=function(t){var e=new Vi(t.shape,"return float(isnan(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n)},t.prototype.isInf=function(t){var e=new Vi(t.shape,"return float(isinf(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n)},t.prototype.isFinite=function(t){var e=new Vi(t.shape,"return float(!isnan(x) && !isinf(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n)},t.prototype.round=function(t){var e=new Vi(t.shape,"\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n");return this.compileAndRun(e,[t])},t.prototype.exp=function(t){var e;return e=s.getBool("WEBGL_PACK")?new es(t.shape,ji):new Vi(t.shape,ji),this.compileAndRun(e,[t])},t.prototype.expm1=function(t){var e=new Vi(t.shape,"return exp(x) - 1.0;");return this.compileAndRun(e,[t])},t.prototype.log=function(t){var e;return e=s.getBool("WEBGL_PACK")?new es(t.shape,"\n vec4 result = log(x);\n vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n result.r = isNaN.r == 1.0 ? NAN : result.r;\n result.g = isNaN.g == 1.0 ? NAN : result.g;\n result.b = isNaN.b == 1.0 ? NAN : result.b;\n result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n return result;\n"):new Vi(t.shape,"if (x < 0.0) return NAN;\n return log(x);"),this.compileAndRun(e,[t])},t.prototype.log1p=function(t){var e=new Vi(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},t.prototype.sqrt=function(t){var e=new Vi(t.shape,"return sqrt(x);");return this.compileAndRun(e,[t])},t.prototype.rsqrt=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.rsqrt(t);var e=new Vi(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},t.prototype.square=function(t){var e=new Vi(t.shape,"return x * x;");return this.compileAndRun(e,[t])},t.prototype.reciprocal=function(t){var e=new Vi(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},t.prototype.relu=function(t){var e;return e=s.getBool("WEBGL_PACK")?new es(t.shape,ts):new Vi(t.shape,Hi),this.compileAndRun(e,[t])},t.prototype.prelu=function(t,e){var n=s.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ta("\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",t.shape,e.shape):new Zo("return (a < 0.) ? b * a : a;",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.elu=function(t){var e=new Vi(t.shape,"return (x >= 0.0) ? x : (exp(x) - 1.0);");return this.compileAndRun(e,[t])},t.prototype.eluDer=function(t,e){var n=s.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ta("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",t.shape,e.shape):new Zo("return (b >= 1.0) ? a : a * (b + 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.selu=function(t){var e=new Vi(t.shape,$i);return this.compileAndRun(e,[t])},t.prototype.int=function(t){var e=new Vi(t.shape,"return float(int(x));"),n=this.makeOutputArray(e.outputShape,"int32");return this.compileAndRun(e,[t],n)},t.prototype.clip=function(t,e,n){var r,o=(r=s.getBool("WEBGL_PACK_CLIP")?new na(t.shape):new ea(t.shape)).getCustomSetupFunc(e,n);return this.compileAndRun(r,[t],null,o)},t.prototype.abs=function(t){var e=new Vi(t.shape,"return abs(x);");return this.compileAndRun(e,[t])},t.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new ra(t.shape),r=[this.makeComplexComponentTensorHandle(t,e.complexTensors.real),this.makeComplexComponentTensorHandle(t,e.complexTensors.imag)];return this.compileAndRun(n,r)},t.prototype.sigmoid=function(t){var e=new Vi(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},t.prototype.softplus=function(t){var e=new Vi(t.shape,"\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n");return this.compileAndRun(e,[t])},t.prototype.sin=function(t){var e=new Vi(t.shape,Ki);return this.compileAndRun(e,[t])},t.prototype.cos=function(t){var e=new Vi(t.shape,Xi);return this.compileAndRun(e,[t])},t.prototype.tan=function(t){var e=new Vi(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},t.prototype.asin=function(t){var e=new Vi(t.shape,"return asin(x);");return this.compileAndRun(e,[t])},t.prototype.acos=function(t){var e=new Vi(t.shape,"return acos(x);");return this.compileAndRun(e,[t])},t.prototype.atan=function(t){var e=new Vi(t.shape,Yi);return this.compileAndRun(e,[t])},t.prototype.atan2=function(t,e){var n=s.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ta("\n vec4 result = atan(a, b);\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Zo("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return atan(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.sinh=function(t){var e=new Vi(t.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},t.prototype.cosh=function(t){var e=new Vi(t.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},t.prototype.tanh=function(t){var e=new Vi(t.shape,"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(e,[t])},t.prototype.asinh=function(t){var e=new Vi(t.shape,"return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(e,[t])},t.prototype.acosh=function(t){var e=new Vi(t.shape,Qi);return this.compileAndRun(e,[t])},t.prototype.atanh=function(t){var e=new Vi(t.shape,Ji);return this.compileAndRun(e,[t])},t.prototype.erf=function(t){var e=new Vi(t.shape,'\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = 0.3275911;\n float a1 = 0.254829592;\n float a2 = -0.284496736;\n float a3 = 1.421413741;\n float a4 = -1.453152027;\n float a5 = 1.061405429;\n\n float t = 1.0 / (1.0 + p * x);\n return 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);\n');return this.compileAndRun(e,[t])},t.prototype.step=function(t,e){var n=new Vi(t.shape,function(t){return void 0===t&&(t=0),Gi+"\n return x > 0.0 ? 1.0 : float("+t+");\n "}(e));return this.compileAndRun(n,[t])},t.prototype.conv2dByMatMul=function(t,e,n){var r=t.shape,o=this.texData.get(t.dataId),a=n.inChannels,i=r[0]*r[1]*r[2],u=n.outChannels,l=(1===i||1===u)&&a>1e3,c=r[2]%2!=0&&!!o.isPacked;if(l||!s.getBool("WEBGL_LAZILY_UNPACK")||!s.getBool("WEBGL_PACK_BINARY_OPERATIONS")||!c){var h=this.reshape(t,[1,r[0]*r[1]*r[2],n.inChannels]),p=this.reshape(e,[1,n.inChannels,n.outChannels]);return this.reshape(this.batchMatMul(h,p,!1,!1),n.outShape)}var f=ft.make([1,r[0]*r[1]*(r[2]+1),n.inChannels],{dataId:t.dataId},t.dtype,this),v=o.shape;o.shape=o.shape.slice(),o.shape[o.shape.length-2]++,d(xe(o.shape,f.shape),function(){return "packed reshape "+o.shape+" to "+f.shape+" isn't free"});var m=this.reshape(e,[1,n.inChannels,n.outChannels]),g=this.batchMatMul(f,m,!1,!1),y=this.texData.get(g.dataId);return d(y.isPacked,function(){return "batchMatMul result is expected to be packed"}),o.shape=v,y.shape=n.outShape,ft.make(n.outShape,{dataId:g.dataId},g.dtype,this)},t.prototype.conv2dWithIm2Row=function(t,e,n){var r=n.filterWidth,o=n.filterHeight,a=n.inChannels,i=n.outWidth,s=n.outHeight,u=r*o*a,l=s*i,c=[u,l],h=t.squeeze([0]),p=e.reshape([1,u,-1]),f=new ii(c,h.shape,n),d=this.compileAndRun(f,[h]).reshape([1,c[0],c[1]]),v=new hi(d.shape,[1,l,n.outChannels],!0,!1);return this.compileAndRun(v,[d,p]).reshape([1,s,i,n.outChannels])},t.prototype.conv2d=function(t,e,n){if(1===n.filterHeight&&1===n.filterWidth&&1===n.dilationHeight&&1===n.dilationWidth&&1===n.strideHeight&&1===n.strideWidth&&("SAME"===n.padInfo.type||"VALID"===n.padInfo.type))return this.conv2dByMatMul(t,e,n);if(s.getBool("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,e,n);var r=new pa(n);return this.compileAndRun(r,[t,e])},t.prototype.conv2dDerInput=function(t,e,n){var r=new sa(n);return this.compileAndRun(r,[t,e])},t.prototype.conv2dDerFilter=function(t,e,n){var r=new ia(n);return this.compileAndRun(r,[t,e])},t.prototype.depthwiseConv2D=function(t,e,n){var r;return s.getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new va(n),this.compileAndRun(r,[t,e],this.makePackedTensor(n.outShape,t.dtype))):(r=new da(n),this.compileAndRun(r,[t,e]))},t.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new ha(n);return this.compileAndRun(r,[t,e])},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new ca(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3d=function(t,e,n){var r=new fa(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3dDerInput=function(t,e,n){var r=new la(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3dDerFilter=function(t,e,n){var r=new ua(n);return this.compileAndRun(r,[t,e])},t.prototype.maxPool=function(t,e){var n=new gi(e,"max",!1),r=this.makeOutputArray(n.outputShape,t.dtype);return this.compileAndRun(n,[t],r)},t.prototype.avgPool=function(t,e){var n=new gi(e,"avg",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t],r)},t.prototype.maxPoolBackprop=function(t,e,n,r){var o=new gi(r,"max",!0),a=this.compileAndRun(o,[e]),i=new ci(r),s=this.makeOutputArray(i.outputShape,e.dtype),u=this.compileAndRun(i,[t,a],s);return a.dispose(),u},t.prototype.avgPoolBackprop=function(t,e,n){var r=new qo(n),o=this.makeOutputArray(r.outputShape,e.dtype);return this.compileAndRun(r,[t],o)},t.prototype.cast=function(t,e){return so(t,e,this)},t.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),o=0,a=0;a1,function(){return "blockSize should be > 1 for depthToSpace, but was: "+e});var r=t.shape[0],o="NHWC"===n?t.shape[1]:t.shape[2],a="NHWC"===n?t.shape[2]:t.shape[3],i="NHWC"===n?t.shape[3]:t.shape[1],s=o*e,u=a*e,l=i/(e*e),c=new wa("NHWC"===n?[r,s,u,l]:[r,l,s,u],e,n);return this.compileAndRun(c,[t])},t.prototype.split=function(t,e,n){return yo(t,e,n)},t.prototype.scatterND=function(t,e,n){var r=Dr(0,t,n),o=r.sliceRank,a=r.numUpdates,i=r.sliceSize,s=r.strides,u=r.outputSize,l=[u/i,i],c=t.reshape([a,o]),h=e.reshape([a,i]);if(0===u)return uo(mn([]),n);var p=yn(0),f=new Ni(a,o,c.rank,h.rank,s,l);return this.compileAndRun(f,[h,c,p]).reshape(n)},t.prototype.sparseToDense=function(t,e,n,r){var o=Dr(0,t,n),a=o.sliceRank,i=o.numUpdates,s=o.strides,u=o.outputSize,l=new Ni(i,a,t.rank,e.rank,s,[u,1],!1);return this.compileAndRun(l,[e,t,r]).reshape(n)},t.prototype.fft=function(t){return this.fftImpl(t,!1)},t.prototype.ifft=function(t){return this.fftImpl(t,!0)},t.prototype.fftImpl=function(t,e){var n=this.texData.get(t.dataId),r=new ka(Sa,t.shape,e),o=new ka(Na,t.shape,e),a=[this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag)],i=this.compileAndRun(r,a),s=this.compileAndRun(o,a),u=this.complex(i,s).as2D(t.shape[0],t.shape[1]);return i.dispose(),s.dispose(),u},t.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],o=Nr(t,e),a=o[0],i=o[1],s=o[2],u=o[3],l=e.reshape([i,r]),c=t.reshape([t.size/s,s]),h=new Fa(r,u,[i,s]);return this.compileAndRun(h,[c,l]).reshape(a)},t.prototype.fill=function(t,e,n){if("string"===(n=n||U(e))){var r=A(n,y(t));return r.fill(e),ft.make(t,{values:r},n)}var o=new Aa(t,e),a=o.getCustomSetupFunc(e),i=this.makeOutputArray(t,n);return this.compileAndRun(o,[],i,a)},t.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported under string dtype");return this.fill(t.shape,1,t.dtype)},t.prototype.zerosLike=function(t){return this.fill(t.shape,"string"===t.dtype?"":0,t.dtype)},t.prototype.linspace=function(t,e,n){return lo(t,e,n)},t.prototype.makeOutputArray=function(t,e){return ft.make(t,{},e,this)},t.prototype.makePackedTensor=function(t,e){var n=ft.make(t,{},e,this);return this.texData.get(n.dataId).isPacked=!0,n},t.prototype.unpackTensor=function(t){var e=new ns(t.shape);return this.compileAndRun(e,[t],ft.make(e.outputShape,{},t.dtype,this))},t.prototype.packTensor=function(t){var e=new di(t.shape);return this.compileAndRun(e,[t],this.makePackedTensor(t.shape,t.dtype),null,!0)},t.prototype.packedReshape=function(t,e){var n=t.reshape([de(t.shape)].concat(ve(t.shape))),r=[de(e)].concat(ve(e)),o=new xi(r,n.shape);return this.compileAndRun(o,[n]).reshape(e)},t.prototype.decode=function(t){var e,n=this.texData.get(t),r=n.isPacked,o=n.shape,a=n.dtype,i=me(o),s=Pa(o),u=this.makeTensorHandle(o,"float32");return this.texData.get(u.dataId).isPacked=!0,this.texData.get(u.dataId).dtype=a,this.texData.get(u.dataId).texShape=s.map(function(t){return 2*t}),e=r?new ba(i,s):new xa(i,s),this.compileAndRun(e,[{shape:i,dtype:a,dataId:t}],u,null,!0),u},t.prototype.compileAndRun=function(t,e,n,r,o){var a=this;if(void 0===o&&(o=!1),null==n&&(n=t.usesPackedTextures?this.makePackedTensor(t.outputShape,e[0].dtype):this.makeOutputArray(t.outputShape,e[0].dtype)),0===n.size)return this.texData.get(n.dataId).values=k(n.dtype,0),n;var i=e.map(function(e){if("complex64"===e.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var n=a.texData.get(e.dataId);if(null==n.texture){if(!t.usesPackedTextures&&y(e.shape)<=s.getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return {shape:e.shape,texData:null,isUniform:!0,uniformValues:n.values};t.usesPackedTextures&&(n.isPacked=!0,n.shape=e.shape);}else if(!!n.isPacked!=!!t.usesPackedTextures)e=n.isPacked?a.unpackTensor(e):a.packTensor(e),n=a.texData.get(e.dataId);else if(n.isPacked&&!xe(n.shape,e.shape)){var r=e,o=e.shape;e.shape=n.shape,e=a.packedReshape(e,o),n=a.texData.get(e.dataId),r.shape=o;}return a.uploadToGPU(e.dataId),{shape:e.shape,texData:n,isUniform:!1}});this.uploadToGPU(n.dataId);var u,l={shape:n.shape,texData:this.texData.get(n.dataId),isUniform:!1},c=function(t,e,n){var r="";e.concat(n).forEach(function(t){var e=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0,n=t.isUniform?"uniform":t.texData.texShape;r+=t.shape+"_"+n+"_"+e;});var o=t.userCode,a=t.constructor.name;return a+="_"+r+"_"+o}(t,i,l),h=this.getAndSaveBinary(c,function(){return function(t,e,n,r){var o=e.userCode,a=n.map(function(t,n){var r={logicalShape:t.shape,texShape:t.isUniform?null:t.texData.texShape,isUniform:t.isUniform,isPacked:!t.isUniform&&t.texData.isPacked,flatOffset:null};return null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0&&(r.flatOffset=t.texData.slice.flatOffset),{name:e.variableNames[n],shapeInfo:r}}),i=a.map(function(t){return t.shapeInfo}),u={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},l=Do(a,u,o,e.usesPackedTextures),c=t.createProgram(l),h=null,p=t.getUniformLocation(c,"NAN",!1);1===s.getNumber("WEBGL_VERSION")&&(h=t.getUniformLocation(c,"INFINITY",!1));for(var f={},d=0;d0?32:16})),this.floatPrecisionValue},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},t.prototype.uploadToGPU=function(t){var e,n=this.texData.get(t),r=n.shape,o=n.dtype,a=n.values,i=n.texture,s=n.usage,u=n.isPacked;if(null==i){var l,c=null!=this.activeTimers;c&&(l=K());var h=n.texShape;if(null==h&&(h=ge(r,u),n.texShape=h),null!=a){var p=me(r),f=void 0,d=h[1],v=h[0],m=a instanceof Uint8Array;u?(d=(e=La(h[0],h[1]))[0],v=e[1],f=new Ia(p,[v,d],m)):f=new Ra(p,[v,d],m);var g=this.makeTensorHandle([v,d],o);this.texData.get(g.dataId).usage=m?Oa.PIXELS:Oa.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(g.dataId),d,v,a);var x=this.makeTensorHandle(f.outputShape,g.dtype);x.size=y(f.outputShape),this.texData.get(x.dataId).isPacked=u,this.compileAndRun(f,[g],x);var b=this.texData.get(x.dataId);n.texture=b.texture,n.texShape=b.texShape,n.isPacked=b.isPacked,n.usage=b.usage,this.disposeData(g.dataId),this.texData.delete(x.dataId),n.values=null,c&&(this.uploadWaitMs+=K()-l);}else{var w=this.acquireTexture(h,s,o,u);n.texture=w;}}},t.prototype.convertAndCacheOnCPU=function(t,e){var n=this.texData.get(t),r=n.dtype;return this.releaseGPUData(t),null!=e&&(n.values=function(t,e){if("float32"===e||"complex64"===e)return t;if("int32"===e||"bool"===e){for(var n="int32"===e?new Int32Array(t.length):new Uint8Array(t.length),r=0;r1024*this.numMBBeforeWarning*1024){var o=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+o+" MB, most likely due to a memory leak");}return this.textureManager.acquireTexture(t,e,r)},t.prototype.computeBytes=function(t,e){return t[0]*t[1]*F(e)},t}();_t()&&Dt.registerBackend("webgl",function(){return new as},2);var is=pn({abs_:function(t){var e=Ze(t,"x","abs");return "complex64"===e.dtype?Dt.runKernel(function(t){return t.complexAbs(e)},{$x:e}):Dt.runKernel(function(t,n){var r=t.abs(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.mul(n.toFloat().step(-1))}}})}}),ss=pn({acos_:function(t){var e=Ze(t,"x","acos");return Dt.runKernel(function(t,n){var r=t.acos(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.divStrict(yn(1).sub(n.toFloat().square()).sqrt()).neg()}}})}}),us=pn({acosh_:function(t){var e=Ze(t,"x","acosh");return Dt.runKernel(function(t,n){var r=t.acosh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.divStrict(n.toFloat().square().sub(1).sqrt())}}})}}),ls=pn({asin_:function(t){var e=Ze(t,"x","asin");return Dt.runKernel(function(t,n){var r=t.asin(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.divStrict(yn(1).sub(n.toFloat().square()).sqrt())}}})}}),cs=pn({asinh_:function(t){var e=Ze(t,"x","asinh");return Dt.runKernel(function(t,n){var r=t.asinh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.divStrict(yn(1).add(n.toFloat().square()).sqrt())}}})}}),hs=pn({atan_:function(t){var e=Ze(t,"x","atan");return Dt.runKernel(function(t,n){var r=t.atan(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.div(n.toFloat().square().add(1))}}})}}),ps=pn({atanh_:function(t){var e=Ze(t,"x","atanh");return Dt.runKernel(function(t,n){var r=t.atanh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.div(yn(1).sub(n.toFloat().square()))}}})}}),fs=pn({ceil_:function(t){var e=Ze(t,"x","ceil");return Dt.runKernel(function(t){return t.ceil(e)},{$x:e},function(t){return {$x:function(){return Dn(t)}}})}}),ds=pn({clipByValue_:function(t,e,n){var r=Ze(t,"x","clipByValue");return d(e<=n,function(){return "Error in clip: min ("+e+") must be less than or equal to max ("+n+")."}),Dt.runKernel(function(t,o){var a=t.clip(r,e,n);return o([r]),a},{$x:r},function(t,r){var o=r[0];return {$x:function(){return t.where(o.greaterEqual(e).logicalAnd(o.lessEqual(n)),Dn(t))}}})}}),vs=pn({cos_:function(t){var e=Ze(t,"x","cos");return Dt.runKernel(function(t,n){var r=t.cos(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return n.toFloat().sin().neg().mul(t)}}})}}),ms=pn({cosh_:function(t){var e=Ze(t,"x","cosh");return Dt.runKernel(function(t,n){var r=t.cosh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return n.toFloat().sinh().mulStrict(t)}}})}}),gs=pn({erf_:function(t){var e=Ze(t,"x","erf");return d("int32"===e.dtype||"float32"===e.dtype,function(){return "Input dtype must be `int32` or `float32`."}),"int32"===e.dtype&&(e=e.toFloat()),Dt.runKernel(function(t,n){var r=t.erf(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.mul(n.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}})}}),ys=pn({exp_:function(t){var e=Ze(t,"x","exp");return Dt.runKernel(function(t,n){var r=t.exp(e);return n([r]),r},{$x:e},function(t,e){return {$x:function(){return t.mulStrict(e[0])}}})}}),xs=pn({expm1_:function(t){var e=Ze(t,"x","expm1");return Dt.runKernel(function(t,n){var r=t.expm1(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.mul(n.exp())}}})}}),bs=pn({floor_:function(t){var e=Ze(t,"x","floor");return Dt.runKernel(function(t){return t.floor(e)},{$x:e},function(t){return {$x:function(){return Dn(t)}}})}}),ws=pn({log_:function(t){var e=Ze(t,"x","log");return Dt.runKernel(function(t,n){var r=t.log(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.div(n.toFloat())}}})}}),Cs=pn({log1p_:function(t){var e=Ze(t,"x","log1p");return Dt.runKernel(function(t,n){var r=t.log1p(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.div(n.add(1))}}})}}),Es=pn({logSigmoid_:function(t){var e=Ze(t,"x","logSigmoid");return Dt.runKernel(function(t,n){var r=t.softplus(e.neg()).neg();return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.mul(n.neg().sigmoid())}}})}}),Rs=pn({neg_:function(t){var e=Ze(t,"x","neg");return Dt.runKernel(function(t){return t.neg(e)},{$x:e},function(t){return {$x:function(){return t.neg()}}})}}),Is=pn({reciprocal_:function(t){var e=Ze(t,"x","reciprocal");return Dt.runKernel(function(t,n){var r=t.reciprocal(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.div(n.square().neg())}}})}}),Ss=pn({round_:function(t){var e=Ze(t,"x","round");return Dt.runKernel(function(t){return t.round(e)},{$x:e},function(t){return {$x:function(){return Dn(t)}}})}}),Ns=pn({rsqrt_:function(t){var e=Ze(t,"x","rsqrt");return Dt.runKernel(function(t,n){var r=t.rsqrt(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.div(n.pow(1.5).mul(2)).neg()}}})}}),ks=pn({sigmoid_:function(t){var e=Ze(t,"x","sigmoid");return Dt.runKernel(function(t,n){var r=t.sigmoid(e);return n([r]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.mul(n.mul(yn(1).sub(n)))}}})}}),As=pn({sign_:function(t){var e=Ze(t,"x","sign");return Dt.runKernel(function(t){return t.sign(e)},{$x:e},function(t){return {$x:function(){return Dn(t)}}})}}),Ts=pn({isNaN_:function(t){var e=Ze(t,"x","isNaN");return Dt.runKernel(function(t){return t.isNaN(e)},{$x:e},function(t){return {$x:function(){return Dn(t)}}})}}),Ds=pn({isInf_:function(t){var e=Ze(t,"x","isInf");return Dt.runKernel(function(t){return t.isInf(e)},{$x:e},function(t){return {$x:function(){return Dn(t)}}})}}),_s=pn({isFinite_:function(t){var e=Ze(t,"x","isFinite");return Dt.runKernel(function(t){return t.isFinite(e)},{$x:e},function(t){return {$x:function(){return Dn(t)}}})}}),Os=pn({sin_:function(t){var e=Ze(t,"x","sin");return Dt.runKernel(function(t,n){var r=t.sin(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return n.toFloat().cos().mul(t)}}})}}),Ms=pn({sinh_:function(t){var e=Ze(t,"x","sinh");return Dt.runKernel(function(t,n){var r=t.sinh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return n.toFloat().cosh().mulStrict(t)}}})}}),Fs=pn({softplus_:function(t){var e=Ze(t,"x","softplus");return Dt.runKernel(function(t,n){var r=t.softplus(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.mul(n.sigmoid())}}})}}),Bs=pn({sqrt_:function(t){var e=Ze(t,"x","sqrt");return Dt.runKernel(function(t,n){var r=t.sqrt(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.div(n.toFloat().sqrt().mul(2))}}})}}),Ps=pn({square_:function(t){var e=Ze(t,"x","square");return Dt.runKernel(function(t,n){return n([e]),t.square(e)},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.mul(n.toFloat().mul(2))}}})}}),Ls=pn({step_:function(t,e){void 0===e&&(e=0);var n=Ze(t,"x","step");return Dt.runKernel(function(t){return t.step(n,e)},{$x:n},function(t){return {$x:function(){return Dn(t)}}})}}),Ws=pn({tan_:function(t){var e=Ze(t,"x","tan");return Dt.runKernel(function(t,n){var r=t.tan(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.div(n.cos().square())}}})}}),Us=pn({tanh_:function(t){var e=Ze(t,"x","tanh");return Dt.runKernel(function(t,n){var r=t.tanh(e);return n([r]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return yn(1).sub(n.square()).mulStrict(t)}}})}});function zs(t,e,n,r,o,a){var i,s,u=Ze(t,"x","batchNorm"),l=Ze(e,"mean","batchNorm"),c=Ze(n,"variance","batchNorm");return null!=o&&(i=Ze(o,"scale","batchNorm")),null!=r&&(s=Ze(r,"offset","batchNorm")),d(2===u.rank,function(){return "Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),d(2===l.rank||1===l.rank,function(){return "Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+l.rank+"."}),d(2===c.rank||1===c.rank,function(){return "Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+c.rank+"."}),null!=i&&d(2===i.rank||1===i.rank,function(){return "Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+i.rank+"."}),null!=s&&d(2===s.rank||1===s.rank,function(){return "Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."}),qs(u,l,c,s,i,a)}function Vs(t,e,n,r,o,a){var i,s,u=Ze(t,"x","batchNorm"),l=Ze(e,"mean","batchNorm"),c=Ze(n,"variance","batchNorm");return null!=o&&(i=Ze(o,"scale","batchNorm")),null!=r&&(s=Ze(r,"offset","batchNorm")),d(3===u.rank,function(){return "Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),d(3===l.rank||1===l.rank,function(){return "Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+l.rank+"."}),d(3===c.rank||1===c.rank,function(){return "Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+c.rank+"."}),null!=i&&d(3===i.rank||1===i.rank,function(){return "Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+i.rank+"."}),null!=s&&d(3===s.rank||1===s.rank,function(){return "Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."}),qs(u,l,c,s,i,a)}function Gs(t,e,n,r,o,a){var i,s,u=Ze(t,"x","batchNorm"),l=Ze(e,"mean","batchNorm"),c=Ze(n,"variance","batchNorm");return null!=o&&(i=Ze(o,"scale","batchNorm")),null!=r&&(s=Ze(r,"offset","batchNorm")),d(4===u.rank,function(){return "Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."}),d(4===l.rank||1===l.rank,function(){return "Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+l.rank+"."}),d(4===c.rank||1===c.rank,function(){return "Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+c.rank+"."}),null!=i&&d(4===i.rank||1===i.rank,function(){return "Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+i.rank+"."}),null!=s&&d(4===s.rank||1===s.rank,function(){return "Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."}),qs(u,l,c,s,i,a)}function qs(t,e,n,r,o,a){null==a&&(a=.001);var i,s,u,l=Ze(t,"x","batchNorm"),c=Ze(e,"mean","batchNorm"),h=Ze(n,"variance","batchNorm");null!=o&&(i=Ze(o,"scale","batchNorm")),null!=r&&(s=Ze(r,"offset","batchNorm")),d(c.rank===h.rank,function(){return "Batch normalization gradient requires mean and variance to have equal ranks."}),d(null==s||c.rank===s.rank,function(){return "Batch normalization gradient requires mean and offset to have equal ranks."}),d(null==i||c.rank===i.rank,function(){return "Batch normalization gradient requires mean and scale to have equal ranks."}),u=0===l.rank||1===l.rank?l.as4D(1,1,1,l.size):2===l.rank?l.as4D(1,1,l.shape[0],l.shape[1]):3===l.rank?l.as4D(1,l.shape[0],l.shape[1],l.shape[2]):l;return Dt.runKernel(function(t,e){var n=t.batchNormalization(u,Hs(c),Hs(h),a,Hs(i),Hs(s));return e([l,c,h,i]),n},{$x:l,$mean:c,$variance:h,$scale:i,$offset:s},function(t,e){var n=e,r=n[0],o=n[1],i=n[2],s=n[3],l=null==s?yn(1):s,c=Xr(o.shape,u.shape),h=[];if(1===o.rank){for(var p=0;p=2&&i.rank>=2&&a.rank===i.rank,function(){return "Error in matMul: inputs must have the same rank of at least 2, got ranks "+a.rank+" and "+i.rank+"."}),d(x(h,p),function(){return "Error in matMul: outer dimensions ("+h+") and ("+p+") of Tensors with shapes "+a.shape+" and "+i.shape+" must match."}),d(s===u,function(){return "Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+a.shape+" and "+i.shape+" and transposeA="+n+" and transposeB="+r+" must match."});var m=a.shape.slice(0,-2).concat([l,c]),g=n?a.as3D(f,s,l):a.as3D(f,l,s),b=r?i.as3D(v,c,u):i.as3D(v,u,c);return Dt.runKernel(function(t,e){var o=t.batchMatMul(g,b,n,r);return e([g,b]),o},{$a:g,$b:b},function(t,e){var o=e,a=o[0],i=o[1];return n||r?!n&&r?{$a:function(){return t.matMul(i,!1,!1)},$b:function(){return t.matMul(a,!0,!1)}}:n&&!r?{$a:function(){return i.matMul(t,!1,!0)},$b:function(){return a.matMul(t,!1,!1)}}:{$a:function(){return i.matMul(t,!0,!0)},$b:function(){return t.matMul(a,!0,!0)}}:{$a:function(){return t.matMul(i,!1,!0)},$b:function(){return a.matMul(t,!0,!1)}}}).reshape(m)}}),pu=pn({dot_:function(t,e){var n=Ze(t,"t1","dot"),r=Ze(e,"t2","dot");d(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),function(){return "Error in dot: inputs must all be rank 1 or 2, but got ranks "+n.rank+" and "+r.rank+"."});var o=1===n.rank?n.size:n.shape[1],a=1===r.rank?r.size:r.shape[0];return d(o===a,function(){return "Error in dot: inner dimensions of inputs must match, but got "+o+" and "+a+"."}),1===n.rank&&1===r.rank?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():1===n.rank&&2===r.rank?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():2===n.rank&&1===r.rank?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]))}}),fu=pn({outerProduct_:function(t,e){var n=Ze(t,"v1","outerProduct"),r=Ze(e,"v2","outerProduct");return d(1===n.rank&&1===r.rank,function(){return "Error in outerProduct: inputs must be rank 1, but got ranks "+n.rank+" and "+r.rank+"."}),n.as2D(-1,1).matMul(r.as2D(1,-1))}});var du=pn({reverse_:function(t,e){var n=Ze(t,"x","reverse");if(0===n.rank)return n.clone();var r=S(e,n.shape);return Dt.runKernel(function(t){return t.reverse(n,r)},{$x:n},function(t){return {$x:function(){return t.reverse(r)}}}).reshapeAs(n)}}),vu=pn({reverse1d_:function(t){var e=Ze(t,"x","reverse");return d(1===e.rank,function(){return "Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."}),du(e,0)}}),mu=pn({reverse2d_:function(t,e){var n=Ze(t,"x","reverse");return d(2===n.rank,function(){return "Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."}),du(n,e)}}),gu=pn({reverse3d_:function(t,e){var n=Ze(t,"x","reverse");return d(3===n.rank,function(){return "Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."}),du(n,e)}}),yu=pn({reverse4d_:function(t,e){var n=Ze(t,"x","reverse");return d(4===n.rank,function(){return "Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."}),du(n,e)}});function xu(t,e,n,r,o,a){var i=Ze(t,"x","maxPool"),s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),null==r&&(r=[1,1]),d(4===s.rank,function(){return "Error in maxPool: input must be rank 4 but got rank "+s.rank+"."}),d(io(n,r),function(){return "Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"}),null!=a&&d(b(o),function(){return "Error in maxPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."});var l=Qr(s.shape,e,n,r,o,a),c=Dt.runKernel(function(t,e){var n=t.maxPool(s,l);return e([s,n]),n},{x:s},function(t,a){var i=a[0],s=a[1];return {x:function(){return function(t,e,n,r,o,a,i,s){var u=Ze(t,"dy","maxPoolBackprop"),l=Ze(e,"input","maxPoolBackprop"),c=Ze(n,"output","maxPoolBackprop");d(l.rank===u.rank,function(){return "Rank of input ("+l.rank+") does not match rank of dy ("+u.rank+")"}),null==a&&(a=[1,1]),d(io(o,a),function(){return "Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'"}),d(4===u.rank,function(){return "Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."}),d(4===l.rank,function(){return "Error in maxPoolBackprop: input must be rank 4 but got rank "+l.rank+"."}),null!=s&&d(b(i),function(){return "Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+i+"."});var h=Qr(l.shape,r,o,a,i,s);return Dt.runKernel(function(t){return t.maxPoolBackprop(u,l,c,h)},{$dy:u,$input:l})}(t,i,s,e,n,r,o)}}});return u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}function bu(t,e,n,r,o,a){var i=Ze(t,"x","avgPool","float32");null==r&&(r=[1,1]),d(io(n,r),function(){return "Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"});var s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),d(4===s.rank,function(){return "Error in avgPool: x must be rank 4 but got rank "+s.rank+"."}),null!=a&&d(b(o),function(){return "Error in avgPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."});var l=Qr(s.shape,e,n,r,o,a),c=Dt.runKernel(function(t){return t.avgPool(s,l)},{x:s},function(t){return {x:function(){return function(t,e,n,r,o,a){var i=Ze(t,"dy","avgPoolBackprop"),s=Ze(e,"input","avgPoolBackprop");d(s.rank===i.rank,function(){return "Rank of input ("+s.rank+") does not match rank of dy ("+i.rank+")"}),null==o&&(o=[1,1]),d(io(r,o),function(){return "Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"});var u=s,l=i,c=!1;3===s.rank&&(c=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),l=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),d(4===l.rank,function(){return "Error in avgPoolBackprop: dy must be rank 4 but got rank "+l.rank+"."}),d(4===u.rank,function(){return "Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+"."});var h=Qr(u.shape,n,r,o,a),p=Dt.runKernel(function(t){return t.avgPoolBackprop(l,u,h)},{dy4D:l,input4D:u});return c?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}(t,s,e,n,r,o)}}});return c=c.cast(i.dtype),u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}var wu=pn({maxPool_:function(t,e,n,r,o){return xu(t,e,n,1,r,o)}}),Cu=pn({avgPool_:function(t,e,n,r,o){return bu(t,e,n,1,r,o)}}),Eu=pn({pool_:function(t,e,n,r,o,a){null==o&&(o=[1,1]),null==a&&(a=1),0===r&&(r="valid");var i=Ze(t,"x","maxPool"),s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),d(io(a,o),function(){return "Error in pool: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+o+"'"});var l,c=Qr(s.shape,e,a,o,r),h=[c.dilationHeight,c.dilationWidth];l="same"===r?function(t,e){var n=t.map(function(t,n){return t+(t-1)*(e[n]-1)}).map(function(t){return t-1}),r=n.map(function(t){return Math.floor(t/2)}),o=n.map(function(t,e){return t-r[e]});return n.map(function(t,e){return [r[e],o[e]]})}([c.filterHeight,c.filterWidth],h):[[0,0],[0,0]];var p=1===h[0]&&1===h[1],f=function(t,e,n){var r=n.map(function(t){return t[0]}),o=n.map(function(t){return t[1]}),a=t.concat(r,o),i=e.map(function(t,e){return (t-a[e]%t)%t}),s=o.map(function(t,e){return t+i[e]}),u=e.map(function(t,e){return [r[e],s[e]]}),l=e.map(function(t,e){return [0,i[e]]});return [u,l]}([c.inHeight,c.inWidth],h,l),v=f[0],m=f[1],g=p?r:"valid",y=p?s:vr(s,h,v),x=("avg"===n?function(){return bu(y,e,a,1,g)}:function(){return xu(y,e,a,1,g)})(),b=p?x:Qn(x,h,m);return u?b.as3D(b.shape[1],b.shape[2],b.shape[3]):b}});var Ru=pn({slice_:function(t,e,n){var r,o,a=Ze(t,"x","slice");if(0===a.rank)throw new Error("Slicing scalar is not possible");r="number"==typeof e?[e].concat(new Array(a.rank-1).fill(0)):e.length=0?t:(d(-1===t,function(){return "Bad value in size"}),a.shape[e]-r[e])}),function(t,e,n){d(t.rank===e.length,function(){return "Error in slice"+t.rank+"D: Length of begin "+e+" must match the rank of the array ("+t.rank+")."}),d(t.rank===n.length,function(){return "Error in slice"+t.rank+"D: Length of size "+n+" must match the rank of the array ("+t.rank+")."});for(var r=function(r){d(e[r]+n[r]<=t.shape[r],function(){return "Error in slice"+t.rank+"D: begin["+r+"] + size["+r+"] ("+(e[r]+n[r])+") would overflow input.shape["+r+"] ("+t.shape[r]+")"});},o=0;o0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=Xr(o.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(o.shape)}}})}}),tl=pn({addN_:function(t){d(Array.isArray(t),function(){return "The argument passed to tf.addN() must be a list of tensors"}),d(t.length>=1,function(){return "Must pass at least one tensor to tf.addN(), but got "+t.length});var e=t.map(function(t,e){return Ze(t,"tensors"+e,"addN")}),n=e[0];e.forEach(function(t){if(t.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),e.forEach(function(t){if(!x(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var r=e;return Dt.runKernel(function(t){return t.addN(e)},r,function(t){var n={};return e.forEach(function(e,r){n[r]=function(){return t.clone()};}),n})}}),el=pn({addStrict_:function(t,e){var n=Ze(t,"a","addStrict"),r=Ze(e,"b","addStrict");return v(n.shape,r.shape,"Error in addStrict: "),n.add(r)}}),nl=pn({atan2_:function(t,e){var n,r=Ze(t,"a","atan2"),o=Ze(e,"b","atan2");n=Rt(r,o),r=n[0],o=n[1];var a=Yr(r.shape,o.shape);return Dt.runKernel(function(t,e){var n=t.atan2(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return {$a:function(){var e=Zu(n.square(),r.square()),o=t.mul(r.div(e)),i=Xr(n.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(n.shape)},$b:function(){var e=Zu(n.square(),r.square()),o=Rs(t.mul(n.div(e))),i=Xr(r.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(r.shape)}}})}}),rl=pn({div_:function(t,e){var n,r=Ze(t,"a","div"),o=Ze(e,"b","div");if(n=Rt(r,o),r=n[0],o=n[1],"int32"===r.dtype&&"int32"===o.dtype)return al(r,o);var a=Yr(r.shape,o.shape);return Dt.runKernel(function(t,e){var n=t.realDivide(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return {$a:function(){var e=t.div(r.toFloat()),o=Xr(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),o=Xr(r.shape,a);o.length>0&&(e=e.sum(o).reshape(r.shape));var i=r.square();return e.div(i.toFloat()).neg()}}})}}),ol=pn({divStrict_:function(t,e){var n=Ze(t,"a","div"),r=Ze(e,"b","div");return v(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),al=pn({floorDiv_:function(t,e){var n,r=Ze(t,"a","floorDiv"),o=Ze(e,"b","floorDiv");n=Rt(r,o),r=n[0],o=n[1];var a=Yr(r.shape,o.shape);return Dt.runKernel(function(t,e){var n=t.floorDiv(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return {$a:function(){var e=t.div(r.toFloat()),o=Xr(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),o=Xr(r.shape,a);o.length>0&&(e=e.sum(o).reshape(r.shape));var i=r.square();return e.div(i.toFloat()).neg()}}})}}),il=pn({maximum_:function(t,e){var n,r=Ze(t,"a","maximum"),o=Ze(e,"b","maximum");return n=Rt(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),Yr(r.shape,o.shape),Dt.runKernel(function(t,e){var n=t.maximum(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return {$a:function(){return t.mul(n.greaterEqual(r).toFloat())},$b:function(){return t.mul(n.less(r).toFloat())}}})}}),sl=pn({maximumStrict_:function(t,e){var n=Ze(t,"a","maximumStrict"),r=Ze(e,"b","maximumStrict");return v(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),ul=pn({minimum_:function(t,e){var n,r=Ze(t,"a","minimum"),o=Ze(e,"b","minimum");return n=Rt(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),Yr(r.shape,o.shape),Dt.runKernel(function(t,e){var n=t.minimum(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return {$a:function(){return t.mul(n.lessEqual(r).toFloat())},$b:function(){return t.mul(n.greater(r).toFloat())}}})}}),ll=pn({minimumStrict_:function(t,e){var n=Ze(t,"a","minimumStrict"),r=Ze(e,"b","minimumStrict");return v(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),cl=pn({mod_:function(t,e){var n,r=Ze(t,"a","mod"),o=Ze(e,"b","mod");n=Rt(r,o),r=n[0],o=n[1];var a=Yr(r.shape,o.shape);return Dt.runKernel(function(t,e){var n=t.mod(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return {$a:function(){var e=Xr(n.shape,a);return e.length>0?t.sum(e).reshape(n.shape):t},$b:function(){var e=t.mul(n.div(r).floor().neg()),o=Xr(r.shape,a);return o.length>0?e.sum(o).reshape(r.shape):e}}})}}),hl=pn({modStrict_:function(t,e){var n=Ze(t,"a","modStrict"),r=Ze(e,"b","modStrict");return v(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),pl=pn({mul_:function(t,e){var n,r=Ze(t,"a","mul"),o=Ze(e,"b","mul");n=Rt(r,o),r=n[0],o=n[1];var a=Yr(r.shape,o.shape);return Dt.runKernel(function(t,e){var n=t.multiply(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return {$a:function(){var e=t.mul(r.toFloat()),o=Xr(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),o=Xr(r.shape,a);return o.length>0?e.sum(o).reshape(r.shape):e}}})}}),fl=pn({mulStrict_:function(t,e){var n=Ze(t,"a","mul"),r=Ze(e,"b","mul");return v(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),dl=pn({pow_:function(t,e){var n=Ze(t,"base","pow"),r=Ze(e,"exp","pow"),o=Yr(n.shape,r.shape);return t=n.cast(Ct(n.dtype,r.dtype)),e=r.cast(Ct(n.dtype,r.dtype)),Dt.runKernel(function(t,e){var o=t.pow(n,r);return e([n,r,o]),o},{$base:n,$exp:r},function(t,e){var n=e[0],r=e[1],a=e[2];return {$base:function(){var e=r.toFloat(),a=t.mul(e.mul(n.pow(e.sub(yn(1))))),i=Xr(n.shape,o);return i.length>0&&(a=a.sum(i)),a.reshape(n.shape)},$exp:function(){var e=n.greater(0),i=n.log().where(e,Dn(n)),s=t.mul(a.mul(i)),u=Xr(r.shape,o);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape)}}})}}),vl=pn({powStrict_:function(t,e){return v(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),ml=pn({squaredDifference_:function(t,e){var n,r=Ze(t,"a","squaredDifference"),o=Ze(e,"b","squaredDifference");return n=Rt(r,o),r=n[0],o=n[1],Yr(r.shape,o.shape),Dt.runKernel(function(t,e){var n=t.squaredDifference(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1],o=yn(2);return {$a:function(){return t.mul(n.sub(r).mul(o))},$b:function(){return t.mul(r.sub(n).mul(o))}}})}}),gl=pn({squaredDifferenceStrict_:function(t,e){var n=Ze(t,"a","squaredDifferenceStrict"),r=Ze(e,"b","squaredDifferenceStrict");return v(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),yl=pn({sub_:function(t,e){var n,r=Ze(t,"a","sub"),o=Ze(e,"b","sub");n=Rt(r,o),r=n[0],o=n[1];var a=Yr(r.shape,o.shape);return Dt.runKernel(function(t){return t.subtract(r,o)},{$a:r,$b:o},function(t){return {$a:function(){var e=t,n=Xr(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=Xr(o.shape,a);return n.length>0&&(e=e.sum(n)),e.neg().reshape(o.shape)}}})}}),xl=pn({subStrict_:function(t,e){var n=Ze(t,"a","subStrict"),r=Ze(e,"b","subStrict");return v(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}});var bl=pn({logicalAnd_:function(t,e){var n=Ze(t,"a","logicalAnd","bool"),r=Ze(e,"b","logicalAnd","bool");return Yr(n.shape,r.shape),Dt.runKernel(function(t){return t.logicalAnd(n,r)},{$a:n,$b:r})}}),wl=pn({logicalNot_:function(t){var e=Ze(t,"x","logicalNot","bool");return Dt.runKernel(function(t){return t.logicalNot(e)},{$x:e})}}),Cl=pn({logicalOr_:function(t,e){var n=Ze(t,"a","logicalOr","bool"),r=Ze(e,"b","logicalOr","bool");return Yr(n.shape,r.shape),Dt.runKernel(function(t){return t.logicalOr(n,r)},{$a:n,$b:r})}}),El=pn({logicalXor_:function(t,e){var n=Ze(t,"a","logicalXor","bool"),r=Ze(e,"b","logicalXor","bool");return Yr(n.shape,r.shape),Cl(t,e).logicalAnd(bl(t,e).logicalNot())}}),Rl=pn({where_:function(t,e,n){var r=Ze(e,"a","where"),o=Ze(n,"b","where"),a=Ze(t,"condition","where","bool");return v(r.shape,o.shape,"Error in where: "),1===a.rank?d(a.shape[0]===r.shape[0],function(){return "The first dimension of `a` must match the size of `condition`."}):v(a.shape,o.shape,"Error in where: "),Dt.runKernel(function(t,e){var n=t.select(a,r,o);return e([a]),n},{$condition:a,$a:r,$b:o},function(t,e){var n=e[0];return {$condition:function(){return Dn(n).toFloat()},$a:function(){return t.mul(n.cast(t.dtype))},$b:function(){return t.mul(n.logicalNot().cast(t.dtype))}}})}}),Il=function(t){return r(this,void 0,void 0,function(){var e,n,r;return o(this,function(o){switch(o.label){case 0:return [4,(e=Ze(t,"condition","whereAsync","bool")).data()];case 1:return n=o.sent(),r=wo(e.shape,n),t!==e&&e.dispose(),[2,r]}})})};var Sl=pn({elu_:function(t){var e=Ze(t,"x","elu");return Dt.runKernel(function(t,n){var r=t.elu(e);return n([r]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return Dt.runKernel(function(e){return e.eluDer(t,n)},{dy:t,y:n})}}})}}),Nl=pn({leakyRelu_:function(t,e){void 0===e&&(e=.2);var n=Ze(t,"x","leakyRelu");return il(yn(e).mul(n),n)}}),kl=pn({prelu_:function(t,e){var n=Ze(t,"x","prelu"),r=Ze(e,"alpha","prelu");return Dt.runKernel(function(t,e){var o=t.prelu(n,r);return e([n,r]),o},{$x:n,$alpha:r},function(t,e){var n=e[0],r=e[1],o=n.greater(0);return {$x:function(){return Rl(o,t,t.mul(r))},$alpha:function(){var e=Rl(o,Dn(t),t.mul(n)),a=Xr(r.shape,t.shape);return a.length>0&&(e=e.sum(a)),e.reshape(r.shape)}}})}}),Al=pn({relu_:function(t){var e=Ze(t,"x","relu");return "bool"===e.dtype?e.toInt():Dt.runKernel(function(t,n){var r=t.relu(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){return t.mulStrict(n.step().toFloat())}}})}}),Tl=pn({selu_:function(t){var e=Ze(t,"x","selu");return Dt.runKernel(function(t,n){var r=t.selu(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return {$x:function(){var e=n.greater(yn(0)),r=yn(Ui),o=yn(zi),a=t.mul(o),i=t.mul(r).mul(n.toFloat().exp());return Rl(e,a,i)}}})}});var Dl=pn({transpose_:function(t,e){var n=Ze(t,"x","transpose");return null==e&&(e=n.shape.map(function(t,e){return e}).reverse()),d(n.rank===e.length,function(){return "Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."}),e.forEach(function(t){d(t>=0&&to)throw new Error("'k' passed to topk() must be <= the last dimension ("+o+") but got "+e);var a=Dt.runKernel(function(t){return t.topk(r,e,n)},{$x:r});return {values:a[0],indices:a[1]}}});var Gl=pn({scatterND_:function(t,e,n){var r=Ze(t,"indices","scatterND","int32"),o=Ze(e,"updates","scatterND");return Tr(o,r,n),Dt.runKernel(function(t){return t.scatterND(r,o,n)},{$indices:r,$updates:o})}});var ql=pn({fft_:function(t){d("complex64"===t.dtype,function(){return "The dtype for tf.spectral.fft() must be complex64 but got "+t.dtype+"."});var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Dt.runKernel(function(t){return t.fft(r)},{input:t}).reshape(t.shape)}}),Hl=pn({ifft_:function(t){d("complex64"===t.dtype,function(){return "The dtype for tf.spectral.ifft() must be complex64 but got "+t.dtype+"."});var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Dt.runKernel(function(t){return t.ifft(r)},{input:t}).reshape(t.shape)}}),$l=pn({rfft_:function(t,e){d("float32"===t.dtype,function(){return "The dtype for rfft() must be real value but got "+t.dtype});var n,r=t.shape[t.shape.length-1],o=t.size/r;if(null!=e&&er){var s=t.shape.map(function(t){return t});s[t.shape.length-1]=e-r,n=t.concat(Sn(s),t.shape.length-1),r=e;}else n=t;var u=n.zerosLike(),l=fn(n,u).as2D(o,r),c=ql(l),h=Math.floor(r/2)+1,p=dn(c),f=vn(c),v=p.split([h,r-h],p.shape.length-1),m=f.split([h,r-h],f.shape.length-1),g=n.shape.slice();return g[n.shape.length-1]=h,fn(v[0],m[0]).reshape(g)}}),jl=pn({irfft_:function(t){var e=t.shape[t.shape.length-1],n=t.size/e;if(e<=2){var r=t.as2D(n,e),o=Hl(r);return dn(o)}var a=[n,2*(e-1)],i=dn(t).as2D(n,e),s=vn(t).as2D(n,e),u=i.slice([0,1],[n,e-2]).reverse(1),l=s.slice([0,1],[n,e-2]).reverse(1).mul(yn(-1)),c=i.concat(u,1),h=s.concat(l,1);return r=fn(c,h).as2D(a[0],a[1]),o=Hl(r),dn(o)}}),Kl=Object.freeze({fft:ql,ifft:Hl,rfft:$l,irfft:jl});var Xl=pn({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var o=Ze(t,"sparseIndices","sparseToDense","int32"),a=Ze(e,"sparseValues","sparseToDense"),i=Ze(r,"defaultValue","sparseToDense",a.dtype);return function(t,e,n,r){if("int32"!==t.dtype)throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+t.dtype+".");if(t.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+t.shape+".");var o=t.rank>0?t.shape[0]:1,a=t.rank>1?t.shape[1]:1;if(n.length!==a)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+a+".");var i=e.size;if(0!==e.rank&&(1!==e.rank||i!==o))throw new Error("sparseValues has incorrect shape "+e.shape+", should be [] or ["+o+"]");if(e.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(o,a,n,i),Dt.runKernel(function(t){return t.sparseToDense(o,a,n,i)},{$sparseIndices:o,$sparseValues:a,$defaultValue:i})}});var Yl=pn({gatherND_:function(t,e){var n=Ze(e,"indices","gatherND","int32"),r=Ze(t,"x","gatherND");return Dt.runKernel(function(t){return t.gatherND(r,n)},{$x:r,$indices:n})}});var Ql=pn({dropout_:function(t,e,n,r){if(null!=n&&!x(t.shape,n))throw new Error("Non-default noise shape is not implemented yet: "+JSON.stringify(n));var o=fr(t.shape,0,1,"float32",r).greater(e);return o=o.div(yl(1,e)),t.mul(o)}});function Jl(t,e,n){for(var r=1-t%2,o=new Float32Array(t),a=0;a1?s.div(yn(i)):s}if(n===Zl.SUM_BY_NONZERO_WEIGHTS){if(null==o)return a.sum().div(yn(r.size));var u=o.mul(In(r.shape)).notEqual(yn(0)).sum().toFloat();return a.sum().div(u)}throw Error("Unknown reduction: "+n)}}),ic=pn({cosineDistance_:function(t,e,n,r,o){void 0===o&&(o=Zl.SUM_BY_NONZERO_WEIGHTS);var a=Ze(t,"labels","cosineDistance"),i=Ze(e,"predictions","cosineDistance"),s=null;null!=r&&(s=Ze(r,"weights","cosineDistance")),v(a.shape,i.shape,"Error in cosineDistance: ");var u=yn(1).sub(a.mul(i).sum(n,!0));return ac(u,s,o)}}),sc=pn({hingeLoss_:function(t,e,n,r){void 0===r&&(r=Zl.SUM_BY_NONZERO_WEIGHTS);var o=Ze(t,"labels","hingeLoss"),a=Ze(e,"predictions","hingeLoss"),i=null;null!=n&&(i=Ze(n,"weights","hingeLoss")),v(o.shape,a.shape,"Error in hingeLoss: ");var s=yn(1);o=yn(2).mul(o).sub(s);var u=s.sub(o.mul(a)).relu();return ac(u,i,r)}}),uc=pn({huberLoss_:function(t,e,n,r,o){void 0===r&&(r=1),void 0===o&&(o=Zl.SUM_BY_NONZERO_WEIGHTS);var a=Ze(t,"labels","huberLoss"),i=Ze(e,"predictions","huberLoss"),s=null;null!=n&&(s=Ze(n,"weights","huberLoss")),v(a.shape,i.shape,"Error in huberLoss: ");var u=yn(r),l=i.sub(a).abs(),c=ul(l,u),h=l.sub(c),p=yn(.5).mul(c.square()).add(u.mul(h));return ac(p,s,o)}}),lc=pn({logLoss_:function(t,e,n,r,o){void 0===r&&(r=1e-7),void 0===o&&(o=Zl.SUM_BY_NONZERO_WEIGHTS);var a=Ze(t,"labels","logLoss"),i=Ze(e,"predictions","logLoss"),s=null;null!=n&&(s=Ze(n,"weights","logLoss")),v(a.shape,i.shape,"Error in logLoss: ");var u=yn(1),l=yn(r),c=a.mul(i.add(l).log()).neg().sub(u.sub(a).mul(u.sub(i).add(l).log()));return ac(c,s,o)}}),cc=pn({meanSquaredError_:function(t,e,n,r){void 0===r&&(r=Zl.SUM_BY_NONZERO_WEIGHTS);var o=Ze(t,"labels","meanSquaredError"),a=Ze(e,"predictions","meanSquaredError"),i=null;null!=n&&(i=Ze(n,"weights","meanSquaredError")),v(o.shape,a.shape,"Error in meanSquaredError: ");var s=o.squaredDifference(a);return ac(s,i,r)}}),hc=pn({sigmoidCrossEntropy_:function(t,e,n,r,o){void 0===r&&(r=0),void 0===o&&(o=Zl.SUM_BY_NONZERO_WEIGHTS);var a=Ze(t,"multiClassLabels","sigmoidCrossEntropy"),i=Ze(e,"logits","sigmoidCrossEntropy"),s=null;if(null!=n&&(s=Ze(n,"weights","sigmoidCrossEntropy")),v(a.shape,i.shape,"Error in sigmoidCrossEntropy: "),r>0){var u=yn(r),l=yn(1),c=yn(.5);a=a.mul(l.sub(u)).add(c.mul(u));}var h=function(t,e){var n=Ze(t,"labels","sigmoidCrossEntropyWithLogits"),r=Ze(e,"logits","sigmoidCrossEntropyWithLogits");v(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var o=r.relu(),a=r.mul(n),i=r.abs().neg().exp().log1p();return o.sub(a).add(i)}(a,i);return ac(h,s,o)}}),pc=pn({softmaxCrossEntropy_:function(t,e,n,r,o){void 0===r&&(r=0),void 0===o&&(o=Zl.SUM_BY_NONZERO_WEIGHTS);var a=Ze(t,"onehotLabels","softmaxCrossEntropy"),i=Ze(e,"logits","softmaxCrossEntropy"),s=null;if(null!=n&&(s=Ze(n,"weights","softmaxCrossEntropy")),v(a.shape,i.shape,"Error in softmaxCrossEntropy: "),r>0){var u=yn(r),l=yn(1),c=yn(a.shape[1]);a=a.mul(l.sub(u)).add(u.div(c));}var h=function(t,e,n){if(void 0===n&&(n=-1),-1===n&&(n=e.rank-1),n!==e.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+e.rank+" and dim was "+n);return Vr(function(t,e,r){var o=e.logSumExp([n],!0),a=e.toFloat().sub(o);return r([t,a]),{value:a.mul(t).neg().sum([n]),gradFunc:function(t,e){var r=e[0],o=e[1],a=on(t.shape,[n]);return [t.reshape(a).mul(r.toFloat().sub(o.exp())),t.reshape(a).mul(o.exp().sub(r.toFloat()))]}}})(t,e)}(a,i);return ac(h,s,o)}}),fc=Object.freeze({get Reduction(){return Zl},absoluteDifference:oc,computeWeightedLoss:ac,cosineDistance:ic,hingeLoss:sc,huberLoss:uc,logLoss:lc,meanSquaredError:cc,sigmoidCrossEntropy:hc,softmaxCrossEntropy:pc});function dc(t,e){return void 0===e&&(e=!1),Dt.tidy(function(){if(2!==t.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+t.shape.length+"D Tensor.");for(var n=t.shape[0],r=t.shape[1],o=rr(n),a=t.clone(),i=bn([[1]],[1,1]),s=i.clone(),u=n>=r?r:n,l=function(t){var e,u=a,l=s,c=o;e=Dt.tidy(function(){var e=a.slice([t,t],[n-t,1]),u=e.norm(),l=a.slice([t,t],[1,1]),c=l.sign().neg(),h=l.sub(c.mul(u)),p=e.div(h);s=1===p.shape[0]?i.clone():i.concat(p.slice([1,0],[p.shape[0]-1,p.shape[1]]),0);var f=c.matMul(h).div(u).neg(),d=a.slice([t,0],[n-t,r]),v=f.mul(s);a=0===t?d.sub(v.matMul(s.transpose().matMul(d))):a.slice([0,0],[t,r]).concat(d.sub(v.matMul(s.transpose().matMul(d))),0);var m=o.slice([0,t],[n,o.shape[1]-t]);return o=0===t?m.sub(m.matMul(s).matMul(v.transpose())):o.slice([0,0],[n,t]).concat(m.sub(m.matMul(s).matMul(v.transpose())),1),[s,a,o]}),s=e[0],a=e[1],o=e[2],Le([u,l,c]);},c=0;cr&&(o=o.slice([0,0],[n,r]),a=a.slice([0,0],[r,r])),[o,a]})}var vc=pn({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,d(null!=t&&t.length>0,function(){return "Gram-Schmidt process: input must not be null, undefined, or empty"});for(var n=t[0].shape[0],r=function(e){d(t[e].shape[0]===n,function(){return "Gram-Schmidt: Non-unique lengths found in the input vectors: ("+t[e].shape[0]+" vs. "+n+")"});},o=1;o0)for(var n=0;n= 2, but got rank "+t.rank);if(2===t.rank)return dc(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce(function(t,e){return t*e}),r=br(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0),o=[],a=[];return r.forEach(function(t){var n=dc(t,e),r=n[0],i=n[1];o.push(r),a.push(i);}),[gr(o,0).reshape(t.shape),gr(a,0).reshape(t.shape)]}}),gc=Object.freeze({gramSchmidt:vc,qr:mc});function yc(t,e,n,r,o){null==r&&(r=.5),null==o&&(o=Number.NEGATIVE_INFINITY);var a=t.shape[0];return n=Math.min(n,a),d(0<=r&&r<=1,function(){return "iouThreshold must be in [0, 1], but was '"+r+"'"}),d(2===t.rank,function(){return "boxes must be a 2D tensor, but was of rank '"+t.rank+"'"}),d(4===t.shape[1],function(){return "boxes must have 4 columns, but 2nd dimension was "+t.shape[1]}),d(1===e.rank,function(){return "scores must be a 1D tensor"}),d(e.shape[0]===a,function(){return "scores has incompatible shape with boxes. Expected "+a+", but was "+e.shape[0]}),{maxOutputSize:n,iouThreshold:r,scoreThreshold:o}}var xc=pn({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=Ze(t,"images","resizeBilinear");d(3===r.rank||4===r.rank,function(){return "Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."}),d(2===e.length,function(){return "Error in resizeBilinear: new shape must 2D, but got shape "+e+"."});var o=r,a=!1;3===r.rank&&(a=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var i=e[0],s=e[1],u=Dt.runKernel(function(t,e){return e([o]),t.resizeBilinear(o,i,s,n)},{batchImages:o},function(t,e){return {batchImages:function(){return Dt.runKernel(function(r){return r.resizeBilinearBackprop(t,e[0],n)},{})}}});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),bc=pn({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=Ze(t,"images","resizeNearestNeighbor");d(3===r.rank||4===r.rank,function(){return "Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."}),d(2===e.length,function(){return "Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."}),d("float32"===r.dtype||"int32"===r.dtype,function(){return "`images` must have `int32` or `float32` as dtype"});var o=r,a=!1;3===r.rank&&(a=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var i=e[0],s=e[1],u=Dt.runKernel(function(t,e){return e([o]),t.resizeNearestNeighbor(o,i,s,n)},{batchImages:o},function(t,e){return {batchImages:function(){return Dt.runKernel(function(r){return r.resizeNearestNeighborBackprop(t,e[0],n)},{})}}});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),wc=pn({nonMaxSuppression_:function(t,e,n,r,o){void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY);var a=Ze(t,"boxes","nonMaxSuppression"),i=Ze(e,"scores","nonMaxSuppression"),s=yc(a,i,n,r,o);return n=s.maxOutputSize,r=s.iouThreshold,o=s.scoreThreshold,Dt.runKernel(function(t){return t.nonMaxSuppression(a,i,n,r,o)},{$boxes:a})}}),Cc=function(t,e,n,a,i){return void 0===a&&(a=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY),r(this,void 0,void 0,function(){var r,s,u,l,c,h;return o(this,function(o){switch(o.label){case 0:return r=Ze(t,"boxes","nonMaxSuppressionAsync"),s=Ze(e,"scores","nonMaxSuppressionAsync"),u=yc(r,s,n,a,i),n=u.maxOutputSize,a=u.iouThreshold,i=u.scoreThreshold,[4,r.data()];case 1:return l=o.sent(),[4,s.data()];case 2:return c=o.sent(),h=mo(l,c,n,a,i),r!==t&&r.dispose(),s!==e&&s.dispose(),[2,h]}})})},Ec=pn({cropAndResize_:function(t,e,n,r,o,a){var i=Ze(t,"image","cropAndResize","float32"),s=Ze(e,"boxes","cropAndResize","float32"),u=Ze(n,"boxInd","cropAndResize","int32");o=o||"bilinear",a=a||0;var l=s.shape[0];return d(4===i.rank,function(){return "Error in cropAndResize: image must be rank 4,but got rank "+i.rank+"."}),d(2===s.rank&&4===s.shape[1],function(){return "Error in cropAndResize: boxes must be have size ["+l+",4] but had shape "+s.shape+"."}),d(1===u.rank&&u.shape[0]===l,function(){return "Error in cropAndResize: boxInd must be have size ["+l+"] but had shape "+s.shape+"."}),d(2===r.length,function(){return "Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."}),d(r[0]>=1&&r[1]>=1,function(){return "cropSize must be atleast [1,1], but was "+r}),d("bilinear"===o||"nearest"===o,function(){return "method must be bilinear or nearest, but was "+o}),Dt.runKernel(function(t,e){return t.cropAndResize(i,s,u,r,o,a)},{$image:i,$boxes:s})}}),Rc=Object.freeze({resizeBilinear:xc,resizeNearestNeighbor:bc,nonMaxSuppression:wc,nonMaxSuppressionAsync:Cc,cropAndResize:Ec});var Ic=pn({matMul_:function(t,e,n,r,o,a){var i;void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===a&&(a="linear");var s=Ze(t,"a","fused matMul"),u=Ze(e,"b","fused matMul");i=Rt(s,u),s=i[0],u=i[1];var l=n?s.shape[s.rank-2]:s.shape[s.rank-1],c=r?u.shape[u.rank-1]:u.shape[u.rank-2],h=n?s.shape[s.rank-1]:s.shape[s.rank-2],p=r?u.shape[u.rank-2]:u.shape[u.rank-1],f=s.shape.slice(0,-2),v=u.shape.slice(0,-2),m=y(f),g=y(v);d(s.rank>=2&&u.rank>=2&&s.rank===u.rank,function(){return "Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+s.rank+" and "+u.rank+"."}),d(x(f,v),function(){return "Error in fused matMul: outer dimensions ("+f+") and ("+v+") of Tensors with shapes "+s.shape+" and "+u.shape+" must match."}),d(l===c,function(){return "Error in fused matMul: inner shapes ("+l+") and ("+c+") of Tensors with shapes "+s.shape+" and "+u.shape+" and transposeA="+n+" and transposeB="+r+" must match."});var b,w=s.shape.slice(0,-2).concat([h,p]),C=n?s.as3D(m,l,h):s.as3D(m,h,l),E=r?u.as3D(g,p,c):u.as3D(g,c,p);null!=o&&Yr(w,(b=Rt(b=Ze(o,"bias","fused matMul"),s)[0]).shape);var R={$a:C,$b:E};return null!=o&&(R.$bias=b),Dt.runKernel(function(t,e){var o=t.fusedBatchMatMul(C,E,n,r,b,a);return e([C,E,o]),o},R,function(t,e){var i,s=e[0],u=e[1],l=e[2];if(null==a||"linear"===a)i=t;else{if("relu"!==a)throw new Error("Gradient for activation "+a+" has not been implemented yet.");i=t.mul(l.step());}var c={};return null!=o&&(c={$bias:function(){var t=i,e=Xr(b.shape,i.shape);return e.length>0&&(t=t.sum(e)),t.reshape(b.shape)}}),n||r?!n&&r?Object.assign({$a:function(){return i.matMul(u,!1,!1)},$b:function(){return i.matMul(s,!0,!1)}},c):n&&!r?Object.assign({$a:function(){return u.matMul(i,!1,!0)},$b:function(){return s.matMul(i,!1,!1)}},c):Object.assign({$a:function(){return u.matMul(i,!0,!0)},$b:function(){return i.matMul(s,!0,!0)}},c):Object.assign({$a:function(){return i.matMul(u,!1,!0)},$b:function(){return s.matMul(i,!0,!1)}},c)}).reshape(w)}}),Sc=Object.freeze({matMul:Ic}),Nc=Object.freeze({image:Rc,linalg:gc,losses:fc,spectral:Kl,fused:Sc,signal:rc,op:pn,batchNormalization2d:js,batchNormalization3d:Ks,batchNormalization4d:Xs,batchNormalization:Ys,batchNorm:Qs,batchNorm2d:Js,batchNorm3d:Zs,batchNorm4d:tu,complex:fn,real:dn,imag:vn,concat:_n,concat1d:On,concat2d:Mn,concat3d:Fn,concat4d:Bn,split:Pn,conv1d:ou,conv2d:au,conv3d:iu,conv2dDerFilter:su,depthwiseConv2d:uu,separableConv2d:lu,conv2dTranspose:cu,matMul:hu,dot:pu,outerProduct:fu,reverse:du,reverse1d:vu,reverse2d:mu,reverse3d:gu,reverse4d:yu,maxPool:wu,avgPool:Cu,pool:Eu,slice:Ru,slice1d:Iu,slice2d:Su,slice3d:Nu,slice4d:ku,abs:is,acos:ss,acosh:us,asin:ls,asinh:cs,atan:hs,atanh:ps,ceil:fs,clipByValue:ds,cos:vs,cosh:ms,erf:gs,exp:ys,expm1:xs,floor:bs,log:ws,log1p:Cs,logSigmoid:Es,neg:Rs,reciprocal:Is,round:Ss,rsqrt:Ns,sigmoid:ks,sign:As,isNaN:Ts,isInf:Ds,isFinite:_s,sin:Os,sinh:Ms,softplus:Fs,sqrt:Bs,square:Ps,step:Ls,tan:Ws,tanh:Us,all:Tu,any:Du,argMax:_u,argMin:Ou,logSumExp:Mu,max:Fu,mean:Bu,min:Pu,moments:Lu,sum:Wu,prod:Uu,equal:zu,equalStrict:Vu,greater:Gu,greaterEqual:qu,greaterEqualStrict:Hu,greaterStrict:$u,less:ju,lessEqual:Ku,lessEqualStrict:Xu,lessStrict:Yu,notEqual:Qu,notEqualStrict:Ju,add:Zu,addN:tl,addStrict:el,atan2:nl,div:rl,divStrict:ol,floorDiv:al,maximum:il,maximumStrict:sl,minimum:ul,minimumStrict:ll,mod:cl,modStrict:hl,mul:pl,mulStrict:fl,pow:dl,powStrict:vl,squaredDifference:ml,squaredDifferenceStrict:gl,sub:yl,subStrict:xl,elu:Sl,leakyRelu:Nl,prelu:kl,relu:Al,selu:Tl,logicalAnd:bl,logicalNot:wl,logicalOr:Cl,logicalXor:El,where:Rl,whereAsync:Il,buffer:Xn,print:Yn,batchToSpaceND:Qn,cast:Jn,clone:Zn,cumsum:tr,depthToSpace:er,expandDims:nr,eye:rr,multinomial:or,oneHot:ar,pad:ir,pad1d:sr,pad2d:ur,pad3d:lr,pad4d:cr,rand:hr,randomNormal:pr,randomUniform:fr,reshape:dr,spaceToBatchND:vr,squeeze:mr,stack:gr,tile:yr,truncatedNormal:xr,unstack:br,setdiff1dAsync:wr,fill:Nn,linspace:kn,ones:In,range:An,scalar:yn,tensor:mn,tensor1d:xn,tensor2d:bn,tensor3d:wn,tensor4d:Cn,tensor5d:En,tensor6d:Rn,zeros:Sn,onesLike:Tn,zerosLike:Dn,transpose:Dl,softmax:qr,logSoftmax:Hr,localResponseNormalization:_l,norm:Ol,gather:Bl,unsortedSegmentSum:Pl,basicLSTMCell:Ll,multiRNNCell:Wl,movingAverage:Ul,stridedSlice:zl,topk:Vl,scatterND:Gl,fft:ql,ifft:Hl,rfft:$l,irfft:jl,sparseToDense:Xl,gatherND:Yl,dropout:Ql,hannWindow:tc,hammingWindow:ec,frame:nc});var kc=function(){function t(){if(this.blockSize=48,this.firstUse=!0,s.get("IS_BROWSER")){var t="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(300,150):"undefined"!=typeof document?document.createElement("canvas"):null;null!==t&&(this.fromPixels2DContext=t.getContext("2d"));}this.data=new $r(this,Dt);}return t.prototype.register=function(t,e,n){if(this.firstUse&&(this.firstUse=!1,s.get("IS_NODE")&&Ye("\n============================\nHi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================\n")),this.data.has(t))throw new Error("Data buffer is already registered");this.data.set(t,{dtype:n});},t.prototype.write=function(t,e){if(null==e)throw new Error("MathBackendCPU.write(): values can not be null");this.data.get(t).values=e;},t.prototype.fromPixels=function(t,e){if(null==t)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n,r,o=t.data instanceof Uint8Array,a="undefined"!=typeof ImageData&&t instanceof ImageData,i="undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement,u="undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement;if(s.get("IS_NODE")&&null==t.getContext)throw new Error("When running in node, pixels must be an HTMLCanvasElement like the one returned by the `canvas` npm package");if(null!=t.getContext)n=t.getContext("2d").getImageData(0,0,t.width,t.height).data;else if(a||o)n=t.data;else{if(!u&&!i)throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData or {data: Uint32Array, width: number, height: number}, but was "+t.constructor.name);if(null==this.fromPixels2DContext)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");this.fromPixels2DContext.canvas.width=t.width,this.fromPixels2DContext.canvas.height=t.height,this.fromPixels2DContext.drawImage(t,0,0,t.width,t.height),n=this.fromPixels2DContext.getImageData(0,0,t.width,t.height).data;}if(4===e)r=new Int32Array(n);else{var l=t.width*t.height;r=new Int32Array(l*e);for(var c=0;cp&&(p=v,f=d);}u[c]=f;}return i},t.prototype.cumsum=function(t,e,n,r){if(this.assertNotComplex(t,"cumsum"),e!==t.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(t.rank-1)+" but got axis="+e);for(var o=Ct(t.dtype,"int32"),a=Sn(t.shape,o),i=this.readSync(a.dataId),s=this.readSync(t.dataId),u=t.shape[t.rank-1],l=r?function(t,e){return t+u-e-1}:function(t,e){return t+e},c=0;ce?1:0})},t.prototype.greaterEqual=function(t,e){return this.assertNotComplex([t,e],"greaterEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t>=e?1:0})},t.prototype.logicalNot=function(t){this.assertNotComplex(t,"logicalNot");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r1||1===e.rank?1:e.shape[1],c=0;c=0&&e>=0?n:(n+e)%e})},t.prototype.max=function(t,e){this.assertNotComplex(t,"max"),an("max",e,t.rank);for(var n=rn(t.shape,e),r=n[0],o=n[1],a=Sn(r,t.dtype),i=y(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;lh&&(h=f);}s[l]=h;}return a},t.prototype.maximum=function(t,e){return this.assertNotComplex([t,e],"maximum"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.max(t,e)})},t.prototype.all=function(t,e){this.assertNotComplex(t,"all"),an("all",e,t.rank);for(var n=rn(t.shape,e),r=n[0],o=n[1],a=Sn(r,t.dtype),i=y(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l0?n[r]=1:n[r]=0;return ft.make(t.shape,{values:n})},t.prototype.isNaN=function(t){this.assertNotComplex(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r.5?n[r]=Math.ceil(e[r]):n[r]=o%2==0?o:o+1;}return ft.make(t.shape,{values:n})},t.prototype.exp=function(t){this.assertNotComplex(t,"exp");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r=0?o:Math.exp(o)-1;}return ft.make(t.shape,{values:e})},t.prototype.eluDer=function(t,e){this.assertNotComplex([t,e],"eluDer");for(var n=new Float32Array(e.size),r=this.readSync(e.dataId),o=this.readSync(t.dataId),a=0;a=1?o[a]:o[a]*(i+1);}return ft.make(e.shape,{values:n})},t.prototype.selu=function(t){this.assertNotComplex(t,"selu");for(var e=Ui,n=zi,r=new Float32Array(t.size),o=this.readSync(t.dataId),a=0;a=0?n*i:e*(Math.exp(i)-1);}return ft.make(t.shape,{values:r})},t.prototype.clip=function(t,e,n){this.assertNotComplex(t,"clip");for(var r=new Float32Array(t.size),o=this.readSync(t.dataId),a=0;an?n:i-e,i=r[o]0?1:e;}return ft.make(t.shape,{values:n})},t.prototype.conv2d=function(t,e,n){this.assertNotComplex([t,e],"conv2d");for(var r=n.filterHeight,o=n.filterWidth,a=n.dilationHeight,i=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l=Xn(n.outShape,t.dtype),c=this.readSync(t.dataId),h=this.readSync(e.dataId),p=l.values,f=0;f=n.inHeight))for(var w=x*e.strides[0],C=d+b*t.strides[1],E=0;E=n.inWidth))for(var k=w+S*e.strides[1],A=C+N*n.inChannels,T=k,D=0;D=n.inDepth))for(var R=C*e.strides[0],I=g+E*t.strides[1],S=0;S=n.inHeight))for(var D=R+A*e.strides[1],_=I+T*t.strides[2],O=0;O=n.inWidth))for(var L=D+B*e.strides[2],W=_+P*n.inChannels,U=L,z=0;z=n.inHeight))for(var C=b*e.strides[0],E=v+w*t.strides[1],R=0;R=n.inWidth))for(var A=C+N*e.strides[1],T=E+k*n.inChannels,D=I,_=A,O=0;OD?D=P:"avg"===n&&(_+=P,O++);}if(isNaN(D))break}d[S+N*g+w]="avg"===n?_/O:D;}return f.toTensor()},t.prototype.maxPool=function(t,e){return this.pool(t,e,"max")},t.prototype.maxPoolPositions=function(t,e){for(var n=Xn(e.outShape,"int32"),r=e.strideHeight,o=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=e.padInfo.top,c=e.padInfo.left,h=this.bufferSync(t),p=0;pC&&(C=k,E=I*u+N);}n.set(E,p,d,y,f);}}return n.toTensor()},t.prototype.maxPoolBackprop=function(t,e,n,r){this.assertNotComplex([e,n],"maxPoolBackprop");for(var o=this.maxPoolPositions(e,r),a=r.strideHeight,i=r.strideWidth,s=r.dilationHeight,u=r.dilationWidth,l=r.effectiveFilterHeight,c=r.effectiveFilterWidth,h=c-1-r.padInfo.left,p=l-1-r.padInfo.top,f=Xn(e.shape,"float32"),d=this.bufferSync(o),v=this.bufferSync(t),m=0;m=r.outHeight||Math.floor(R)!==R))for(var I=0;I=r.outWidth||Math.floor(S)!==S)){var N=l*c-1-d.get(m,R,S,g)===E*c+I?1:0;if(0!==N)C+=v.get(m,R,S,g)*N;}}}f.set(C,m,y,x,g);}return f.toTensor()},t.prototype.avgPoolBackprop=function(t,e,n){this.assertNotComplex([t,e],"avgPoolBackprop");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,l=n.effectiveFilterHeight,c=n.effectiveFilterWidth,h=c-1-n.padInfo.left,p=l-1-n.padInfo.top,f=Xn(e.shape,"float32"),d=1/(a*i),v=this.bufferSync(t),m=0;m=n.outHeight||Math.floor(R)!==R))for(var I=0;I=n.outWidth||Math.floor(S)!==S))C+=v.get(m,R,S,g);}}f.set(C*d,m,y,x,g);}return f.toTensor()},t.prototype.cast=function(t,e){return so(t,e,this)},t.prototype.reshape=function(t,e){return uo(t,e)},t.prototype.avgPool=function(t,e){return this.assertNotComplex(t,"avgPool"),this.pool(t,e,"avg").toFloat()},t.prototype.resizeBilinear=function(t,e,n,r){this.assertNotComplex(t,"resizeBilinear");for(var o=t.shape,a=o[0],i=o[1],s=o[2],u=o[3],l=this.readSync(t.dataId),c=new Float32Array(y([a,e,n,u])),h=[r&&e>1?i-1:i,r&&n>1?s-1:s],p=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=0,d=h[0]/p[0],v=h[1]/p[1],m=0;m1?a-1:a,n&&c>1?i-1:i],f=[n&&l>1?l-1:l,n&&c>1?c-1:c],d=p[0]/f[0],v=p[1]/f[1],m=this.readSync(t.dataId),g=0,y=0;y1?i-1:i,r&&n>1?s-1:s],p=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=h[0]/p[0],d=h[1]/p[1],v=0,m=0;m1?a-1:a,n&&c>1?i-1:i],d=[n&&l>1?l-1:l,n&&c>1?c-1:c],v=f[0]/d[0],m=f[1]/d[1],g=1/v,y=1/m,x=2*Math.ceil(g)+2,b=2*Math.ceil(y)+2,w=0;w=l)){var F=C+M*t.strides[1],B=M*v;if(E===Math.min(a-1,n?Math.round(B):Math.floor(B)))for(var P=0;P=c)){var W=F+L*t.strides[2],U=L*m;N===Math.min(i-1,n?Math.round(U):Math.floor(U))&&(_+=p[W+D]);}}}}h[k+D]=_;}return Cn(h,e.shape,e.dtype)},t.prototype.batchNormalization=function(t,e,n,r,o,a){this.assertNotComplex([t,e,n,o,a],"batchNorm");for(var i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=this.readSync(n.dataId),l=o?this.readSync(o.dataId):new Float32Array([1]),c=a?this.readSync(a.dataId):new Float32Array([0]),h=new Float32Array(i.length),p=c.length,f=l.length,d=u.length,v=s.length,m=0,g=0,y=0,x=0,b=0;b=p&&(m=0),g>=v&&(g=0),y>=f&&(y=0),x>=d&&(x=0);return Cn(h,t.shape)},t.prototype.localResponseNormalization4D=function(t,e,n,r,o){this.assertNotComplex(t,"localResponseNormalization4D");var a=t.shape[3],i=a-1,s=this.readSync(t.dataId),u=t.size,l=new Float32Array(u);function c(t){for(var n=t%a,r=t-n+Math.max(0,n-e),o=t-n+Math.min(n+e,i),u=0;r<=o;r++){var l=s[r];u+=l*l;}return u}for(var h=0;h=0&&a[i]1,function(){return "blockSize should be > 1 for depthToSpace, but was: "+e});for(var r=t.shape[0],o=t.shape[1],a=t.shape[2],i=t.shape[3],s=o*e,u=a*e,l=i/(e*e),c=this.readSync(t.dataId),h=new Float32Array(r*s*u*l),p=0,f=0;f=s))for(var N=p>1?(R-C)*(u-1)/(p-1):0,k=f>1?(I-E)*(l-1)/(f-1):0,A=0;A1?C*(u-1)+A*N:.5*(C+R)*(u-1);if(T<0||T>u-1)for(var D=0;D1?E*(l-1)+D*k:.5*(E+I)*(l-1))<0||H>l-1)for(_=0;_1?E*(l-1)+D*k:.5*(E+I)*(l-1))<0||H>l-1)for(_=0;_=t.size/s)throw new Error("Invalid indices: "+f+" does not index into "+t.shape);for(var g=0;g=r/o)throw new Error("Invalid indices: "+v+" does not index into "+n);for(var x=0;x0,function(){return "scheme must not be an empty string."});var r=t.getInstance();d(null==r.managers[e],function(){return "A model store manager is already registered for scheme '"+e+"'."}),r.managers[e]=n;},t.getManager=function(t){var e=this.getInstance().managers[t];if(null==e)throw new Error("Cannot find model manager for scheme '"+t+"'");return e},t.getSchemes=function(){return Object.keys(this.getInstance().managers)},t}();function Hc(t){if(-1===t.indexOf(Gc))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+qc.getSchemes().join(","));return {scheme:t.split(Gc)[0],path:t.split(Gc)[1]}}function $c(t,e,n){return void 0===n&&(n=!1),r(this,void 0,void 0,function(){var r,a,i,s,u,l,c,h,p;return o(this,function(o){switch(o.label){case 0:return d(t!==e,function(){return "Old path and new path are the same: '"+t+"'"}),d((r=Vc.getLoadHandlers(t)).length>0,function(){return "Copying failed because no load handler is found for source URL "+t+"."}),d(r.length<2,function(){return "Copying failed because more than one ("+r.length+") load handlers for source URL "+t+"."}),a=r[0],d((i=Vc.getSaveHandlers(e)).length>0,function(){return "Copying failed because no save handler is found for destination URL "+e+"."}),d(i.length<2,function(){return "Copying failed because more than one ("+r.length+") save handlers for destination URL "+e+"."}),s=i[0],u=Hc(t).scheme,l=Hc(t).path,c=u===Hc(t).scheme,[4,a.load()];case 1:return h=o.sent(),n&&c?[4,qc.getManager(u).removeModel(l)]:[3,3];case 2:o.sent(),o.label=3;case 3:return [4,s.save(h)];case 4:return p=o.sent(),!n||c?[3,6]:[4,qc.getManager(u).removeModel(l)];case 5:o.sent(),o.label=6;case 6:return [2,p.modelArtifactsInfo]}})})}var jc="models_store",Kc="model_info_store";function Xc(){if(!s.getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var t=window,e=t.indexedDB||t.mozIndexedDB||t.webkitIndexedDB||t.msIndexedDB||t.shimIndexedDB;if(null==e)throw new Error("The current browser does not appear to support IndexedDB.");return e}function Yc(t){var e=t.result;e.createObjectStore(jc,{keyPath:"modelPath"}),e.createObjectStore(Kc,{keyPath:"modelPath"});}var Qc=function(){function t(t){if(this.indexedDB=Xc(),null==t||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t;}return t.prototype.save=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return [2,this.databaseAction(this.modelPath,t)]})})},t.prototype.load=function(){return r(this,void 0,void 0,function(){return o(this,function(t){return [2,this.databaseAction(this.modelPath)]})})},t.prototype.databaseAction=function(t,e){var n=this;return new Promise(function(t,r){var o=n.indexedDB.open("tensorflowjs",1);o.onupgradeneeded=function(){return Yc(o)},o.onsuccess=function(){var a=o.result;if(null==e){var i=a.transaction(jc,"readonly"),s=i.objectStore(jc).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return a.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));t(s.result.modelArtifacts);},s.onerror=function(t){return a.close(),r(s.error)},i.oncomplete=function(){return a.close()};}else{var u,l=zc(e),c=a.transaction(Kc,"readwrite"),h=c.objectStore(Kc),p=h.put({modelPath:n.modelPath,modelArtifactsInfo:l});p.onsuccess=function(){var o=(u=a.transaction(jc,"readwrite")).objectStore(jc).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:l});o.onsuccess=function(){return t({modelArtifactsInfo:l})},o.onerror=function(t){var e=(h=c.objectStore(Kc)).delete(n.modelPath);e.onsuccess=function(){return a.close(),r(o.error)},e.onerror=function(t){return a.close(),r(o.error)};};},p.onerror=function(t){return a.close(),r(p.error)},c.oncomplete=function(){null==u?a.close():u.oncomplete=function(){return a.close()};};}},o.onerror=function(t){return r(o.error)};})},t.URL_SCHEME="indexeddb://",t}(),Jc=function(t){return s.getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(Qc.URL_SCHEME)?(e=t.slice(Qc.URL_SCHEME.length),new Qc(e)):null;var e;};Vc.registerSaveRouter(Jc),Vc.registerLoadRouter(Jc);var Zc=function(){function t(){this.indexedDB=Xc();}return t.prototype.listModels=function(){return r(this,void 0,void 0,function(){var t=this;return o(this,function(e){return [2,new Promise(function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return Yc(r)},r.onsuccess=function(){var t=r.result,o=t.transaction(Kc,"readonly"),a=o.objectStore(Kc).getAll();a.onsuccess=function(){for(var t={},n=0,r=a.result;n0,function(){return "promises must be a none empty array"});}(t),function(t,e){d(t>=0&&t<=1,function(){return "Progress fraction must be in range [0, 1], but got startFraction "+t}),d(e>=0&&e<=1,function(){return "Progress fraction must be in range [0, 1], but got endFraction "+e}),d(e>=t,function(){return "startFraction must be no more than endFraction, but got startFraction "+t+" and endFraction "+e});}(n=null==n?0:n,r=null==r?1:r);var o=0;return Promise.all(t.map(function(a){return a.then(function(a){var i=n+ ++o/t.length*(r-n);return e(i),a}),a}))}function xh(t,e){return r(this,void 0,void 0,function(){var n,r,a,i,s,u,l,c,h;return o(this,function(o){switch(o.label){case 0:return null==e&&(e={}),n=null==e.fetchFunc?Y:e.fetchFunc,r=t.map(function(t){return n(t,e.requestInit)}),a=0,i=.5,null!=e.onProgress?[3,2]:[4,Promise.all(r)];case 1:return s=o.sent(),[3,4];case 2:return [4,yh(r,e.onProgress,a,i)];case 3:s=o.sent(),o.label=4;case 4:return u=s.map(function(t){return t.arrayBuffer()}),l=.5,c=1,null!=e.onProgress?[3,6]:[4,Promise.all(u)];case 5:return h=o.sent(),[3,8];case 6:return [4,yh(u,e.onProgress,l,c)];case 7:h=o.sent(),o.label=8;case 8:return [2,h]}})})}function bh(t){var e=this;return function(n,a,i){return void 0===a&&(a=""),r(e,void 0,void 0,function(){var e,r,s,u,l,c,h,p,f,d;return o(this,function(o){switch(o.label){case 0:if(e=n.map(function(){return !1}),r={},s=null!=i?i.map(function(){return !1}):[],u=[],n.forEach(function(t,n){var o=0;t.weights.forEach(function(t){var a="quantization"in t?t.quantization.dtype:t.dtype,l=Oc[a]*y(t.shape),c=function(){e[n]=!0,null==r[n]&&(r[n]=[]),r[n].push({manifestEntry:t,groupOffset:o,sizeBytes:l});};null!=i?i.forEach(function(e,n){e===t.name&&(c(),s[n]=!0);}):c(),u.push(t.name),o+=l;});}),!s.every(function(t){return t}))throw l=i.filter(function(t,e){return !s[e]}),new Error("Could not find weights in manifest with names: "+l.join(", ")+". \nManifest JSON has weights with names: "+u.join(", ")+".");return c=e.reduce(function(t,e,n){return e&&t.push(n),t},[]),h=[],c.forEach(function(t){n[t].paths.forEach(function(t){var e=a+(a.endsWith("/")?"":"/")+t;h.push(e);});}),[4,t(h)];case 1:return p=o.sent(),f={},d=0,c.forEach(function(t){for(var e=n[t].paths.length,o=0,a=0;a0,function(){return "URL path for http must not be null, undefined or empty."}),Array.isArray(t)&&d(2===t.length,function(){return "URL paths for http must have a length of 2, (actual length is "+t.length+")."}),this.path=t,null!=e.requestInit&&null!=e.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{};}return t.prototype.save=function(t){return r(this,void 0,void 0,function(){var e,n,r,a;return o(this,function(o){switch(o.label){case 0:if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return (e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=t.weightData&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if((a=o.sent()).ok)return [2,{modelArtifactsInfo:zc(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}})})},t.prototype.load=function(){return r(this,void 0,void 0,function(){var t,e,n,r,a,i,s,u;return o(this,function(o){switch(o.label){case 0:return [4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=o.sent()).ok)throw new Error("Request to "+this.path+" failed with status code "+t.status+". Please verify this URL points to the model JSON of the model to load.");o.label=2;case 2:return o.trys.push([2,4,,5]),[4,t.json()];case 3:return e=o.sent(),[3,5];case 4:throw o.sent(),n="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?n+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":n+=" Please make sure the server is serving valid JSON for this request.",new Error(n);case 5:if(r=e.modelTopology,a=e.weightsManifest,null==r&&null==a)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==a?[3,7]:[4,this.loadWeights(a)];case 6:u=o.sent(),i=u[0],s=u[1],o.label=7;case 7:return [2,{modelTopology:r,weightSpecs:i,weightData:s}]}})})},t.prototype.loadWeights=function(t){return r(this,void 0,void 0,function(){var e,n,r,a,i,s,u,l,c,h,p;return o(this,function(o){switch(o.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(t){var e=t.lastIndexOf("/"),n=t.lastIndexOf("?"),r=t.substring(0,e),o=n>e?t.substring(n):"";return [r+"/",o]}(e),r=n[0],a=n[1],i=this.weightPathPrefix||r,s=[],u=0,l=t;u0&&(t=n({weightSpecs:this.weightSpecs},t)),null!=this.weightData&&this.weightData.byteLength>0&&(t=n({weightData:this.weightData},t)),null!=this.trainingConfig&&(t=n({trainingConfig:this.trainingConfig},t)),[2,t]})})},t}(),Sh=function(){function t(t){this.saveHandler=t;}return t.prototype.save=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){return [2,this.saveHandler(t)]})})},t}();var Nh=Object.freeze({browserFiles:function(t){return new gh(t)},browserHTTPRequest:function(t,e){return Rh(t,e)},concatenateArrayBuffers:Wc,decodeWeights:Fc,encodeWeights:function(t,e){return r(this,void 0,void 0,function(){var n,a,i,s,u,l=this;return o(this,function(c){switch(c.label){case 0:for(n=[],a=[],i=Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t),s=function(s){var u=i[s],c=Array.isArray(t)?t[s].tensor:t[u];if("float32"!==c.dtype&&"int32"!==c.dtype&&"bool"!==c.dtype&&"string"!==c.dtype)throw new Error("Unsupported dtype in weight '"+u+"': "+c.dtype);var h={name:u,shape:c.shape,dtype:c.dtype};if("string"===c.dtype){var p=new Promise(function(t){return r(l,void 0,void 0,function(){var e,n,r,a,i,s,u;return o(this,function(o){switch(o.label){case 0:return [4,c.bytes()];case 1:for(e=o.sent(),n=e.reduce(function(t,e){return t+e.length},0)+Mc*e.length,r=new Uint8Array(n),a=0,i=0;i0&&Number.isInteger(n),function(){return "If provided, numClasses must be a positive integer, but got "+n}),d(1===r.rank,function(){return "Expected the rank of labels to be 1, but got "+r.rank}),d(1===o.rank,function(){return "Expected the rank of predictions to be 1, but got "+o.rank}),d(r.shape[0]===o.shape[0],function(){return "Mismatch in the number of examples: "+r.shape[0]+" vs. "+o.shape[0]+". Labels and predictions should have the same number of elements."}),d(n>0&&Number.isInteger(n),function(){return "numClasses is required to be a positive integer, but got "+n});var a=ar(r.asType("int32"),n),i=ar(o.asType("int32"),n);return a.transpose().matMul(i).asType("int32")}}),Ah=Object.freeze({confusionMatrix:kh});var Th=pn({fromPixels_:function(t,e){if(void 0===e&&(e=3),e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");return Dt.fromPixels(t,e)}}),Dh=Object.freeze({toPixels:function(t,e){return r(this,void 0,void 0,function(){var n,r,a,i,s,u,l,c,h,p,f,d,v,m,g,y,x,b,w,C,E,R,I;return o(this,function(o){switch(o.label){case 0:if(n=Ze(t,"img","toPixels"),t instanceof ft||(n=n.toInt()),2!==n.rank&&3!==n.rank)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+n.rank+".");if(r=n.shape.slice(0,2),a=r[0],i=r[1],(s=2===n.rank?1:n.shape[2])>4||2===s)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+s);return [4,n.data()];case 1:return u=o.sent(),l=n.min(),c=n.max(),[4,Promise.all([l.data(),c.data()])];case 2:if(h=o.sent(),p=h[0],f=h[1],d=p[0],v=f[0],l.dispose(),c.dispose(),"float32"===n.dtype){if(d<0||v>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+d+" - "+v+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(d<0||v>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+d+" - "+v+"].")}for(m="float32"===n.dtype?255:1,g=new Uint8ClampedArray(i*a*4),y=0;y0,function(){return "Class being registered has an empty-string as its className, which is disallowed."}),Oh.register(t);}var Fh=Object.freeze({Serializable:_h,SerializationMap:Oh,registerClass:Mh}),Bh=.001,Ph=.1;function Lh(){return 32===Dt.backend.floatPrecision()?Bh:Ph}function Wh(t,e,n){var r=!0;if((M(t)||M(e))&&(r=!1),M(t)&&M(e)&&(r=!0),r){var o=t.constructor.name,a=e.constructor.name;if(o!==a)throw new Error("Arrays are of different type. Actual: "+o+". Expected: "+a)}if(Array.isArray(t)&&Array.isArray(e)){var i=Qe(t),s=Qe(e);if(!x(i,s))throw new Error("Arrays have different shapes. Actual: ["+i+"]. Expected: ["+s+"]")}var u=M(t)?t:g(t),l=M(e)?e:g(e);if(u.length!==l.length)throw new Error("Arrays have different lengths actual: "+u.length+" vs expected: "+l.length+".\nActual: "+u+".\nExpected: "+l+".");for(var c=0;cn)}var zh=Object.freeze({TEST_EPSILON_FLOAT16:Ph,expectArraysClose:function(t,e,n){return null==n&&(n=Lh()),Wh(t,e,function(t,e){return Uh(t,e,n)})},testEpsilon:Lh,expectPromiseToFail:function(t,e){t().then(function(){return e.fail()},function(){return e()});},expectArraysEqual:function(t,e){var n="string"==typeof e||"number"==typeof e||"boolean"==typeof e?[e]:e;return P(t)||P(t[0])||P(e)||P(e[0])?Wh(t,n,function(t,e){return t==e}):Wh(t,e,function(t,e){return Uh(t,e,0)})},expectNumbersClose:function(t,e,n){if(null==n&&(n=Lh()),!Uh(t,e,n))throw new Error("Numbers differ: actual === "+t+", expected === "+e)},expectValuesInRange:function(t,e,n){for(var r=0;rn)throw new Error("Value out of range:"+t[r]+" low: "+e+", high: "+n)},expectArrayBuffersEqual:function(t,e){expect(new Float32Array(t)).toEqual(new Float32Array(e));}}),Gh=Object.freeze({gpgpu_util:ri,webgl_util:Ae,MathBackendWebGL:as,setWebGLContext:Ft,GPGPUContext:oi}),qh=function(t){function n(){return null!==t&&t.apply(this,arguments)||this}return e(n,t),n.prototype.minimize=function(t,e,n){void 0===e&&(e=!1);var r=this.computeGradients(t,n),o=r.value,a=r.grads;if(null!=n){var i=n.map(function(t){return {name:t.name,tensor:a[t.name]}});this.applyGradients(i);}else this.applyGradients(a);return Le(a),e?o:(o.dispose(),null)},Object.defineProperty(n.prototype,"iterations",{get:function(){return null==this.iterations_&&(this.iterations_=0),this.iterations_},enumerable:!0,configurable:!0}),n.prototype.incrementIterations=function(){this.iterations_=this.iterations+1;},n.prototype.computeGradients=function(t,e){return zr(t,e)},n.prototype.dispose=function(){null!=this.iterations_&&Le(this.iterations_);},n.prototype.saveIterations=function(){return r(this,void 0,void 0,function(){return o(this,function(t){return null==this.iterations_&&(this.iterations_=0),[2,{name:"iter",tensor:yn(this.iterations_,"int32")}]})})},n.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return o(this,function(t){throw new Error("getWeights() is not implemented for this optimizer yet.")})})},n.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return o(this,function(t){throw new Error("setWeights() is not implemented for this optimizer class "+this.getClassName())})})},n.prototype.extractIterations=function(t){return r(this,void 0,void 0,function(){var e;return o(this,function(n){switch(n.label){case 0:return e=this,[4,t[0].tensor.data()];case 1:return e.iterations_=n.sent()[0],[2,t.slice(1)]}})})},n}(_h);Object.defineProperty(qh,Symbol.hasInstance,{value:function(t){return null!=t.minimize&&null!=t.computeGradients&&null!=t.applyGradients}});var Hh=function(t){function n(e,n,r){void 0===r&&(r=null);var o=t.call(this)||this;return o.learningRate=e,o.rho=n,o.epsilon=r,o.accumulatedGrads=[],o.accumulatedUpdates=[],null==r&&(o.epsilon=Dt.backend.epsilon()),o}return e(n,t),n.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var o=Dt.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accum_grad",variable:Pe(function(){return Dn(o).variable(!1)})}),null==e.accumulatedUpdates[r]&&(e.accumulatedUpdates[r]={originalName:n+"/accum_var",variable:Pe(function(){return Dn(o).variable(!1)})});var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=e.accumulatedGrads[r].variable,s=e.accumulatedUpdates[r].variable;Pe(function(){var t=i.mul(e.rho).add(a.square().mul(1-e.rho)),n=s.add(e.epsilon).sqrt().div(i.add(e.epsilon).sqrt()).mul(a),r=s.mul(e.rho).add(n.square().mul(1-e.rho));i.assign(t),s.assign(r);var u=n.mul(-e.learningRate).add(o);o.assign(u);});}}),this.incrementIterations();},n.prototype.dispose=function(){null!=this.accumulatedUpdates&&(Le(this.accumulatedGrads.map(function(t){return t.variable})),Le(this.accumulatedUpdates.map(function(t){return t.variable})));},n.prototype.getWeights=function(){return r(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return t=this.accumulatedGrads.concat(this.accumulatedUpdates),[4,this.saveIterations()];case 1:return [2,[e.sent()].concat(t.map(function(t){return {name:t.originalName,tensor:t.variable}}))]}})})},n.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){var e;return o(this,function(n){switch(n.label){case 0:return [4,this.extractIterations(t)];case 1:return t=n.sent(),e=t.length/2,this.accumulatedGrads=t.slice(0,e).map(function(t){return {originalName:t.name,variable:t.tensor.variable(!1)}}),this.accumulatedUpdates=t.slice(e,2*e).map(function(t){return {originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},n.prototype.getConfig=function(){return {learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},n.fromConfig=function(t,e){return new t(e.learningRate,e.rho,e.epsilon)},n.className="AdadeltaOptimizer",n}(qh);Mh(Hh);var $h=function(t){function n(e,n){void 0===n&&(n=.1);var r=t.call(this)||this;return r.learningRate=e,r.initialAccumulatorValue=n,r.accumulatedGrads=[],r}return e(n,t),n.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var o=Dt.registeredVariables[n];if(null==e.accumulatedGrads[r]){e.accumulatedGrads[r]={originalName:n+"/accumulator",variable:Pe(function(){return Nn(o.shape,e.initialAccumulatorValue).variable(!1)})};}var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=e.accumulatedGrads[r].variable;Pe(function(){var t=i.add(a.square());i.assign(t);var n=a.div(t.add(Dt.backend.epsilon()).sqrt()).mul(-e.learningRate).add(o);o.assign(n);});}}),this.incrementIterations();},n.prototype.dispose=function(){null!=this.accumulatedGrads&&Le(this.accumulatedGrads.map(function(t){return t.variable}));},n.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return o(this,function(t){switch(t.label){case 0:return [4,this.saveIterations()];case 1:return [2,[t.sent()].concat(this.accumulatedGrads.map(function(t){return {name:t.originalName,tensor:t.variable}}))]}})})},n.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return [4,this.extractIterations(t)];case 1:return t=e.sent(),this.accumulatedGrads=t.map(function(t){return {originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},n.prototype.getConfig=function(){return {learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},n.fromConfig=function(t,e){return new t(e.learningRate,e.initialAccumulatorValue)},n.className="Adagrad",n}(qh);Mh($h);var jh=function(t){function n(e,n,r,o){void 0===o&&(o=null);var a=t.call(this)||this;return a.learningRate=e,a.beta1=n,a.beta2=r,a.epsilon=o,a.accumulatedFirstMoment=[],a.accumulatedSecondMoment=[],Pe(function(){a.accBeta1=yn(n).variable(),a.accBeta2=yn(r).variable();}),null==o&&(a.epsilon=Dt.backend.epsilon()),a}return e(n,t),n.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t);Pe(function(){var r=yl(1,e.accBeta1),o=yl(1,e.accBeta2);n.forEach(function(n,a){var i=Dt.registeredVariables[n];null==e.accumulatedFirstMoment[a]&&(e.accumulatedFirstMoment[a]={originalName:n+"/m",variable:Pe(function(){return Dn(i).variable(!1)})}),null==e.accumulatedSecondMoment[a]&&(e.accumulatedSecondMoment[a]={originalName:n+"/v",variable:Pe(function(){return Dn(i).variable(!1)})});var s=Array.isArray(t)?t[a].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[a].variable,l=e.accumulatedSecondMoment[a].variable,c=u.mul(e.beta1).add(s.mul(1-e.beta1)),h=l.mul(e.beta2).add(s.square().mul(1-e.beta2)),p=c.div(r),f=h.div(o);u.assign(c),l.assign(h);var d=p.div(f.sqrt().add(e.epsilon)).mul(-e.learningRate).add(i);i.assign(d);}}),e.accBeta1.assign(e.accBeta1.mul(e.beta1)),e.accBeta2.assign(e.accBeta2.mul(e.beta2));}),this.incrementIterations();},n.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&Le(this.accumulatedFirstMoment.map(function(t){return t.variable})),null!=this.accumulatedSecondMoment&&Le(this.accumulatedSecondMoment.map(function(t){return t.variable}));},n.prototype.getWeights=function(){return r(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return t=this.accumulatedFirstMoment.concat(this.accumulatedSecondMoment),[4,this.saveIterations()];case 1:return [2,[e.sent()].concat(t.map(function(t){return {name:t.originalName,tensor:t.variable}}))]}})})},n.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){var e,n=this;return o(this,function(r){switch(r.label){case 0:return [4,this.extractIterations(t)];case 1:return t=r.sent(),Pe(function(){n.accBeta1.assign(dl(n.beta1,n.iterations_+1)),n.accBeta2.assign(dl(n.beta2,n.iterations_+1));}),e=t.length/2,this.accumulatedFirstMoment=t.slice(0,e).map(function(t){return {originalName:t.name,variable:t.tensor.variable(!1)}}),this.accumulatedSecondMoment=t.slice(e,2*e).map(function(t){return {originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},n.prototype.getConfig=function(){return {learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},n.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon)},n.className="Adam",n}(qh);Mh(jh);var Kh=function(t){function n(e,n,r,o,a){void 0===o&&(o=null),void 0===a&&(a=0);var i=t.call(this)||this;return i.learningRate=e,i.beta1=n,i.beta2=r,i.epsilon=o,i.decay=a,i.accumulatedFirstMoment=[],i.accumulatedWeightedInfNorm=[],Pe(function(){i.iteration=yn(0).variable(),i.accBeta1=yn(n).variable();}),null==o&&(i.epsilon=Dt.backend.epsilon()),i}return e(n,t),n.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t);Pe(function(){var r=yl(1,e.accBeta1),o=rl(-e.learningRate,e.iteration.mul(e.decay).add(1));n.forEach(function(n,a){var i=Dt.registeredVariables[n];null==e.accumulatedFirstMoment[a]&&(e.accumulatedFirstMoment[a]={originalName:n+"/m",variable:Dn(i).variable(!1)}),null==e.accumulatedWeightedInfNorm[a]&&(e.accumulatedWeightedInfNorm[a]={originalName:n+"/v",variable:Dn(i).variable(!1)});var s=Array.isArray(t)?t[a].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[a].variable,l=e.accumulatedWeightedInfNorm[a].variable,c=u.mul(e.beta1).add(s.mul(1-e.beta1)),h=l.mul(e.beta2),p=s.abs(),f=h.maximum(p);u.assign(c),l.assign(f);var d=o.div(r).mul(c.div(f.add(e.epsilon))).add(i);i.assign(d);}}),e.iteration.assign(e.iteration.add(1)),e.accBeta1.assign(e.accBeta1.mul(e.beta1));}),this.incrementIterations();},n.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&Le(this.accumulatedFirstMoment.map(function(t){return t.variable})),null!=this.accumulatedWeightedInfNorm&&Le(this.accumulatedWeightedInfNorm.map(function(t){return t.variable}));},n.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return o(this,function(t){throw new Error("getWeights() is not implemented for Adamax yet.")})})},n.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return o(this,function(t){throw new Error("setWeights() is not implemented for Adamax yet.")})})},n.prototype.getConfig=function(){return {learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},n.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon,e.decay)},n.className="Adamax",n}(qh);Mh(Kh);var Xh=function(t){function n(e){var n=t.call(this)||this;return n.learningRate=e,n.setLearningRate(e),n}return e(n,t),n.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var o=Array.isArray(t)?t[r].tensor:t[n];if(null!=o){var a=Dt.registeredVariables[n];Pe(function(){var t=e.c.mul(o).add(a);a.assign(t);});}}),this.incrementIterations();},n.prototype.setLearningRate=function(t){this.learningRate=t,null!=this.c&&this.c.dispose(),this.c=We(yn(-t));},n.prototype.dispose=function(){this.c.dispose();},n.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return o(this,function(t){switch(t.label){case 0:return [4,this.saveIterations()];case 1:return [2,[t.sent()]]}})})},n.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return [4,this.extractIterations(t)];case 1:if(0!==(t=e.sent()).length)throw new Error("SGD optimizer does not have settable weights.");return [2]}})})},n.prototype.getConfig=function(){return {learningRate:this.learningRate}},n.fromConfig=function(t,e){return new t(e.learningRate)},n.className="SGD",n}(qh);Mh(Xh);var Yh=function(t){function n(e,n,r){void 0===r&&(r=!1);var o=t.call(this,e)||this;return o.learningRate=e,o.momentum=n,o.useNesterov=r,o.accumulations=[],o.m=yn(o.momentum),o}return e(n,t),n.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var o=Dt.registeredVariables[n];if(null==e.accumulations[r]){e.accumulations[r]={originalName:n+"/momentum",variable:Pe(function(){return Dn(o).variable(!1)})};}var a=e.accumulations[r].variable,i=Array.isArray(t)?t[r].tensor:t[n];null!=i&&Pe(function(){var t,n=e.m.mul(a).add(i);t=e.useNesterov?e.c.mul(i.add(n.mul(e.m))).add(o):e.c.mul(n).add(o),a.assign(n),o.assign(t);});}),this.incrementIterations();},n.prototype.dispose=function(){this.m.dispose(),null!=this.accumulations&&Le(this.accumulations.map(function(t){return t.variable}));},n.prototype.setMomentum=function(t){this.momentum=t;},n.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return o(this,function(t){switch(t.label){case 0:return [4,this.saveIterations()];case 1:return [2,[t.sent()].concat(this.accumulations.map(function(t){return {name:t.originalName,tensor:t.variable}}))]}})})},n.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return [4,this.extractIterations(t)];case 1:return t=e.sent(),this.accumulations=t.map(function(t){return {originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},n.prototype.getConfig=function(){return {learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},n.fromConfig=function(t,e){return new t(e.learningRate,e.momentum,e.useNesterov)},n.className="MomentumOptimizer",n}(Xh);Mh(Yh);var Qh=function(t){function n(e,n,r,o,a){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===o&&(o=null),void 0===a&&(a=!1);var i=t.call(this)||this;return i.learningRate=e,i.decay=n,i.momentum=r,i.epsilon=o,i.accumulatedMeanSquares=[],i.accumulatedMoments=[],i.accumulatedMeanGrads=[],i.centered=a,null==o&&(i.epsilon=Dt.backend.epsilon()),i}return e(n,t),n.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var o=Dt.registeredVariables[n];null==e.accumulatedMeanSquares[r]&&(e.accumulatedMeanSquares[r]={originalName:n+"/rms",variable:Pe(function(){return Dn(o).variable(!1)})}),null==e.accumulatedMoments[r]&&(e.accumulatedMoments[r]={originalName:n+"/momentum",variable:Pe(function(){return Dn(o).variable(!1)})}),null==e.accumulatedMeanGrads[r]&&e.centered&&(e.accumulatedMeanGrads[r]={originalName:n+"/mg",variable:Pe(function(){return Dn(o).variable(!1)})});var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=e.accumulatedMeanSquares[r].variable,s=e.accumulatedMoments[r].variable;Pe(function(){var t=i.mul(e.decay).add(a.square().mul(1-e.decay));if(e.centered){var n=e.accumulatedMeanGrads[r].variable,u=n.mul(e.decay).add(a.mul(1-e.decay)),l=s.mul(e.momentum).add(a.mul(e.learningRate).div(t.sub(u.square().add(e.epsilon)).sqrt()));i.assign(t),n.assign(u),s.assign(l);var c=o.sub(l);o.assign(c);}else{var h=i.mul(e.decay).add(a.square().mul(1-e.decay));l=s.mul(e.momentum).add(a.mul(e.learningRate).div(h.add(e.epsilon).sqrt()));i.assign(h),s.assign(l);c=o.sub(l);o.assign(c);}});}}),this.incrementIterations();},n.prototype.dispose=function(){null!=this.accumulatedMeanSquares&&Le(this.accumulatedMeanSquares.map(function(t){return t.variable})),null!=this.accumulatedMeanGrads&&this.centered&&Le(this.accumulatedMeanGrads.map(function(t){return t.variable})),null!=this.accumulatedMoments&&Le(this.accumulatedMoments.map(function(t){return t.variable}));},n.prototype.getWeights=function(){return r(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return t=this.accumulatedMeanSquares.concat(this.accumulatedMoments),this.centered&&t.push.apply(t,this.accumulatedMeanGrads),[4,this.saveIterations()];case 1:return [2,[e.sent()].concat(t.map(function(t){return {name:t.originalName,tensor:t.variable}}))]}})})},n.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){var e;return o(this,function(n){switch(n.label){case 0:return [4,this.extractIterations(t)];case 1:return t=n.sent(),e=this.centered?t.length/3:t.length/2,this.accumulatedMeanSquares=t.slice(0,e).map(function(t){return {originalName:t.name,variable:t.tensor.variable(!1)}}),this.accumulatedMoments=t.slice(e,2*e).map(function(t){return {originalName:t.name,variable:t.tensor.variable(!1)}}),this.centered&&(this.accumulatedMeanGrads=t.slice(2*e,3*e).map(function(t){return {originalName:t.name,variable:t.tensor.variable(!1)}})),[2]}})})},n.prototype.getConfig=function(){return {learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},n.fromConfig=function(t,e){return new t(e.learningRate,e.decay,e.momentum,e.epsilon,e.centered)},n.className="RMSProp",n}(qh);Mh(Qh);var Jh=function(){function t(){}return t.sgd=function(t){return new Xh(t)},t.momentum=function(t,e,n){return void 0===n&&(n=!1),new Yh(t,e,n)},t.rmsprop=function(t,e,n,r,o){return void 0===e&&(e=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===o&&(o=!1),new Qh(t,e,n,r,o)},t.adam=function(t,e,n,r){return void 0===t&&(t=.001),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),new jh(t,e,n,r)},t.adadelta=function(t,e,n){return void 0===t&&(t=.001),void 0===e&&(e=.95),void 0===n&&(n=null),new Hh(t,e,n)},t.adamax=function(t,e,n,r,o){return void 0===t&&(t=.002),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),void 0===o&&(o=0),new Kh(t,e,n,r,o)},t.adagrad=function(t,e){return void 0===e&&(e=.1),new $h(t,e)},t}(),Zh={sgd:Jh.sgd,momentum:Jh.momentum,adadelta:Jh.adadelta,adagrad:Jh.adagrad,rmsprop:Jh.rmsprop,adamax:Jh.adamax,adam:Jh.adam},tp="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:function(t){return t()};function ep(){return new Promise(function(t){return tp(function(){return t()})})}ht=Nc; + + /** + * @license + * Copyright 2019 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. + * ============================================================================= + */ + var extendStatics=function(e,t){return (extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t;}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);})(e,t)};function __extends(e,t){function n(){this.constructor=e;}extendStatics(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n);}var _epsilon,__assign=function(){return (__assign=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])&&(6===a[0]||2===a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]t?1:0}function reverseNumberCompare(e,t){return -1*numberCompare(e,t)}function unique(e){if(null==e)return e;for(var t=[],n=0,r=e;n=0),assert(r>=n),Array.isArray(e)&&e.length>=n&&e.length<=r&&e.every(function(e){return typeof e===t})}function assertPositiveInteger(e,t){Array.isArray(e)?(Z.assert(e.length>0,function(){return t+" is unexpectedly an empty array."}),e.forEach(function(e,n){return assertPositiveInteger(e,"element "+(n+1)+" of "+t)})):Z.assert(Number.isInteger(e)&&e>0,function(){return "Expected "+t+" to be a positive integer, but got "+formatAsFriendlyString(e)+"."});}function formatAsFriendlyString(e){return null===e?"null":Array.isArray(e)?"["+e.map(function(e){return formatAsFriendlyString(e)}).join(",")+"]":"string"==typeof e?'"'+e+'"':""+e}function debounce(e,t){var n,r=Z.now();return function(){for(var i=[],a=0;a0){var n=e+"_"+t;return nameMap.set(n,1),n}return e}var tensorNameRegex=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function isValidTensorName(e){return !!e.match(tensorNameRegex)}function isInteger(e){return e===parseInt(e.toString(),10)}function arrayProd(e,t,n){null==t&&(t=0),null==n&&(n=e.length);for(var r=1,i=t;i= 2 but got x shape = "+e.shape+" and y shape = "+t.shape);if(t.rank>=3&&(s=e.shape.slice(-1)[0])!==(c=t.shape.slice(-2)[0]))throw new NotImplementedError("If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = "+e.shape+" and y shape = "+t.shape);if(2===e.rank&&2===t.rank){var i=!1,a=!1;return Sc.matMul(e,t,i,a,r?reshapeBias(e.rank,r,imageDataFormat()):null,n)}var o=e.shape.slice(),s=o.pop();e=e.reshape([-1,s]);var l=t.shape.slice(),u=l.pop(),c=l.pop(),p=l.concat([u]),h=Array.from({length:t.rank},function(e,n){return 0===n?t.rank-2:n<=t.rank-2?n-1:n});t=t.transpose(h).reshape([c,-1]);var d=o.concat(p);i=!1,a=!1;return Sc.matMul(e,t,i,a,r?reshapeBias(e.rank,r,imageDataFormat()):null,n).reshape(d)}function gather$1(e,t,n){return Pe(function(){return t=Array.isArray(t)?xn(t,"int32"):t.toInt(),Bl(e,t,n)})}function square(e){return fl(e,e)}function reshapeBias(e,t,n){var r=t.shape;if(1!==t.rank&&t.rank!==e)throw new ValueError("Unexpected bias dimensions: "+t.rank+"; expected it to be 1 or "+e);if(5===e){if("channelsFirst"===n)return 1===r.length?t.reshape([1,r[0],1,1,1]):t.reshape([1,r[3],r[0],r[1],r[2]]);if("channelsLast"===n)return 1===r.length?t.reshape([1,1,1,1,r[0]]):t.reshape([1].concat(r))}else if(4===e){if("channelsFirst"===n)return 1===r.length?t.reshape([1,r[0],1,1]):t.reshape([1,r[2],r[0],r[1]]);if("channelsLast"===n)return 1===r.length?t.reshape([1,1,1,r[0]]):t.reshape([1].concat(r))}else if(3===e){if("channelsFirst"===n)return 1===r.length?t.reshape([1,r[0],1]):t.reshape([1,r[1],r[0]]);if("channelsLast"===n)return 1===r.length?t.reshape([1,1,r[0]]):t.reshape([1].concat(r))}else if(e<3)return t;throw new ValueError("Unsupported input rank by biasAdd: "+t.rank)}function biasAdd(e,t,n){return Pe(function(){return null==n&&(n=imageDataFormat()),checkDataFormat(n),e.add(reshapeBias(e.rank,t,n))})}function elu$1(e,t){if(void 0===t&&(t=1),1!==t)throw new NotImplementedError("Support for alpha values other than 1 ("+t+") is not implemented yet.");return Sl(e)}function softsign(e){return Pe(function(){return rl(e,is(e).add(1))})}function dropout$1(e,t,n,r){return Pe(function(){return Ql(e,t,n,r)})}function hardSigmoid(e){return Pe(function(){var t=Zu(.5,pl(.2,e));return ds(t,0,1)})}function inTrainPhase(e,t,n){return void 0===n&&(n=!1),n?e():t()}var VALID_FAN_MODE_VALUES=["fanIn","fanOut","fanAvg"],VALID_DISTRIBUTION_VALUES=["normal","uniform","truncatedNormal"];function checkFanMode(e){checkStringTypeUnionValue(VALID_FAN_MODE_VALUES,"FanMode",e);}function checkDistribution(e){checkStringTypeUnionValue(VALID_DISTRIBUTION_VALUES,"Distribution",e);}var Initializer=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),t.prototype.fromConfigUsesCustomObjects=function(){return !1},t.prototype.getConfig=function(){return {}},t}(Fh.Serializable),Zeros=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),t.prototype.apply=function(e,t){return Sn(e,t)},t.className="Zeros",t}(Initializer);Fh.registerClass(Zeros);var Ones=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),t.prototype.apply=function(e,t){return In(e,t)},t.className="Ones",t}(Initializer);Fh.registerClass(Ones);var Constant=function(e){function t(t){var n=e.call(this)||this;if("object"!=typeof t)throw new ValueError("Expected argument of type ConstantConfig but got "+t);if(void 0===t.value)throw new ValueError("config must have value set but got "+t);return n.value=t.value,n}return __extends(t,e),t.prototype.apply=function(e,t){var n=this;return Pe(function(){return pl(yn(n.value),In(e,t))})},t.prototype.getConfig=function(){return {value:this.value}},t.className="Constant",t}(Initializer);Fh.registerClass(Constant);var RandomUniform=function(e){function t(t){var n=e.call(this)||this;return n.DEFAULT_MINVAL=-.05,n.DEFAULT_MAXVAL=.05,n.minval=t.minval||n.DEFAULT_MINVAL,n.maxval=t.maxval||n.DEFAULT_MAXVAL,n.seed=t.seed,n}return __extends(t,e),t.prototype.apply=function(e,t){return fr(e,this.minval,this.maxval,t)},t.prototype.getConfig=function(){return {minval:this.minval,maxval:this.maxval,seed:this.seed}},t.className="RandomUniform",t}(Initializer);Fh.registerClass(RandomUniform);var RandomNormal=function(e){function t(t){var n=e.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=t.mean||n.DEFAULT_MEAN,n.stddev=t.stddev||n.DEFAULT_STDDEV,n.seed=t.seed,n}return __extends(t,e),t.prototype.apply=function(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new NotImplementedError("randomNormal does not support dType "+t+".");return randomNormal$1(e,this.mean,this.stddev,t,this.seed)},t.prototype.getConfig=function(){return {mean:this.mean,stddev:this.stddev,seed:this.seed}},t.className="RandomNormal",t}(Initializer);Fh.registerClass(RandomNormal);var TruncatedNormal=function(e){function t(t){var n=e.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=t.mean||n.DEFAULT_MEAN,n.stddev=t.stddev||n.DEFAULT_STDDEV,n.seed=t.seed,n}return __extends(t,e),t.prototype.apply=function(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new NotImplementedError("truncatedNormal does not support dType "+t+".");return xr(e,this.mean,this.stddev,t,this.seed)},t.prototype.getConfig=function(){return {mean:this.mean,stddev:this.stddev,seed:this.seed}},t.className="TruncatedNormal",t}(Initializer);Fh.registerClass(TruncatedNormal);var Identity=function(e){function t(t){var n=e.call(this)||this;return n.gain=null!=t.gain?t.gain:1,n}return __extends(t,e),t.prototype.apply=function(e,t){var n=this;return Pe(function(){if(2!==e.length||e[0]!==e[1])throw new ValueError("Identity matrix initializer can only be used for 2D square matrices.");return pl(n.gain,rr(e[0]))})},t.prototype.getConfig=function(){return {gain:this.gain}},t.className="Identity",t}(Initializer);function computeFans(e,t){var n,r;if(void 0===t&&(t="channelsLast"),checkDataFormat(t),2===e.length)n=e[0],r=e[1];else if(-1!==[3,4,5].indexOf(e.length)){if("channelsFirst"===t){var i=arrayProd(e,2);n=e[1]*i,r=e[0]*i;}else if("channelsLast"===t){i=arrayProd(e,0,e.length-2);n=e[e.length-2]*i,r=e[e.length-1]*i;}}else{var a=arrayProd(e);n=Math.sqrt(a),r=Math.sqrt(a);}return [n,r]}Fh.registerClass(Identity);var VarianceScaling=function(e){function t(t){var n=e.call(this)||this;if(t.scale<0)throw new ValueError("scale must be a positive float. Got: "+t.scale);return n.scale=null==t.scale?1:t.scale,n.mode=null==t.mode?"fanIn":t.mode,checkFanMode(n.mode),n.distribution=null==t.distribution?"normal":t.distribution,checkDistribution(n.distribution),n.seed=t.seed,n}return __extends(t,e),t.prototype.apply=function(e,t){var n=computeFans(e),r=n[0],i=n[1],a=this.scale;if("fanIn"===this.mode?a/=Math.max(1,r):"fanOut"===this.mode?a/=Math.max(1,i):a/=Math.max(1,(r+i)/2),"normal"===this.distribution){var o=Math.sqrt(a);if("float32"!==(t=t||"float32")&&"int32"!==t)throw new NotImplementedError(this.getClassName()+" does not support dType "+t+".");return xr(e,0,o,t,this.seed)}var s=Math.sqrt(3*a);return fr(e,-s,s,t)},t.prototype.getConfig=function(){return {scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},t.className="VarianceScaling",t}(Initializer);Fh.registerClass(VarianceScaling);var GlorotUniform=function(e){function t(t){return e.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:null==t?null:t.seed})||this}return __extends(t,e),t.prototype.getClassName=function(){return VarianceScaling.className},t.className="GlorotUniform",t}(VarianceScaling);Fh.registerClass(GlorotUniform);var GlorotNormal=function(e){function t(t){return e.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:null==t?null:t.seed})||this}return __extends(t,e),t.prototype.getClassName=function(){return VarianceScaling.className},t.className="GlorotNormal",t}(VarianceScaling);Fh.registerClass(GlorotNormal);var HeNormal=function(e){function t(t){return e.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:null==t?null:t.seed})||this}return __extends(t,e),t.prototype.getClassName=function(){return VarianceScaling.className},t.className="HeNormal",t}(VarianceScaling);Fh.registerClass(HeNormal);var HeUniform=function(e){function t(t){return e.call(this,{scale:2,mode:"fanIn",distribution:"uniform",seed:null==t?null:t.seed})||this}return __extends(t,e),t.prototype.getClassName=function(){return VarianceScaling.className},t.className="HeUniform",t}(VarianceScaling);Fh.registerClass(HeUniform);var LeCunNormal=function(e){function t(t){return e.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:null==t?null:t.seed})||this}return __extends(t,e),t.prototype.getClassName=function(){return VarianceScaling.className},t.className="LeCunNormal",t}(VarianceScaling);Fh.registerClass(LeCunNormal);var LeCunUniform=function(e){function t(t){return e.call(this,{scale:1,mode:"fanIn",distribution:"uniform",seed:null==t?null:t.seed})||this}return __extends(t,e),t.prototype.getClassName=function(){return VarianceScaling.className},t.className="LeCunNormal",t}(VarianceScaling);Fh.registerClass(LeCunUniform);var Orthogonal=function(e){function t(t){var n=e.call(this)||this;if(n.DEFAULT_GAIN=1,n.gain=null==t.gain?n.DEFAULT_GAIN:t.gain,n.seed=t.seed,null!=n.seed)throw new NotImplementedError("Random seed is not implemented for Orthogonal Initializer yet.");return n}return __extends(t,e),t.prototype.apply=function(e,t){var n=this;return Pe(function(){if(2!==e.length)throw new NotImplementedError("The Orthogonal Initializer does not support non-2D shapes yet.");e[0]*e[1]>2e3&&console.warn("Orthogonal initializer is being called on a matrix with more than 2000 ("+e[0]*e[1]+") elements: Slowness may result.");var t=randomNormal$1(e[0]>e[1]?[e[1],e[0]]:e,0,1,"float32"),r=gc.gramSchmidt(t);return e[0]>e[1]&&(r=r.transpose()),pl(n.gain,r)})},t.prototype.getConfig=function(){return {gain:this.gain,seed:this.seed}},t.className="Orthogonal",t}(Initializer);Fh.registerClass(Orthogonal);var INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function deserializeInitializer(e,t){return void 0===t&&(t={}),deserializeKerasObject(e,Fh.SerializationMap.getMap().classNameMap,t,"initializer")}function serializeInitializer(e){return serializeKerasObject(e)}function getInitializer(e){if("string"==typeof e){var t=e in INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP?INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[e]:e;if("GlorotNormal"===t)return new GlorotNormal;if("GlorotUniform"===t)return new GlorotUniform;if("HeNormal"===t)return new HeNormal;if("HeUniform"===t)return new HeUniform;if("LeCunNormal"===t)return new LeCunNormal;if("LeCunUniform"===t)return new LeCunUniform;var n={};return n.className=t,n.config={},deserializeInitializer(n)}return e instanceof Initializer?e:deserializeInitializer(e)}function zeros$1(){return new Zeros}function ones$1(){return new Ones}function constant(e){return new Constant(e)}function randomUniform$1(e){return new RandomUniform(e)}function randomNormal$2(e){return new RandomNormal(e)}function truncatedNormal$1(e){return new TruncatedNormal(e)}function identity(e){return new Identity(e)}function varianceScaling(e){return new VarianceScaling(e)}function glorotUniform(e){return new GlorotUniform(e)}function glorotNormal(e){return new GlorotNormal(e)}function heNormal(e){return new HeNormal(e)}function heUniform(e){return new HeUniform(e)}function leCunNormal(e){return new LeCunNormal(e)}function leCunUniform(e){return new LeCunUniform(e)}function orthogonal(e){return new Orthogonal(e)}var exports_initializers=Object.freeze({zeros:zeros$1,ones:ones$1,constant:constant,randomUniform:randomUniform$1,randomNormal:randomNormal$2,truncatedNormal:truncatedNormal$1,identity:identity,varianceScaling:varianceScaling,glorotUniform:glorotUniform,glorotNormal:glorotNormal,heNormal:heNormal,heUniform:heUniform,leCunNormal:leCunNormal,leCunUniform:leCunUniform,orthogonal:orthogonal}),_nextUniqueTensorId=0;function getNextUniqueTensorId(){return _nextUniqueTensorId++}var _uidPrefixes={};function getUid(e){return void 0===e&&(e=""),e in _uidPrefixes||(_uidPrefixes[e]=0),_uidPrefixes[e]+=1,e+_uidPrefixes[e].toString()}function isArrayOfShapes(e){return Array.isArray(e)&&Array.isArray(e[0])}function normalizeShapeList(e){return 0===e.length?[]:Array.isArray(e[0])?e:[e]}function getExactlyOneTensor(e){var t;if(Array.isArray(e)){if(1!==e.length)throw new ValueError("Expected Tensor length to be 1; got "+e.length);t=e[0];}else t=e;return t}function getExactlyOneShape(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(1===e.length)return (e=e)[0];throw new ValueError("Expected exactly 1 Shape; got "+e.length)}return e}function countParamsInWeights(e){for(var t=0,n=0,r=e;n1)throw new AttributeError("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use `getInputAt(nodeIndex)` instead.');if(0===this.inboundNodes.length)throw new AttributeError("Layer "+this.name+" is not connected, no input to return.");return singletonOrArray(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){if(0===this.inboundNodes.length)throw new AttributeError("Layer "+this.name+" has no inbound nodes.");if(this.inboundNodes.length>1)throw new AttributeError("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return singletonOrArray(this.getNodeAtIndex(0,"output").outputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"losses",{get:function(){return this._losses},enumerable:!0,configurable:!0}),t.prototype.calculateLosses=function(){return this.losses.map(function(e){return e()})},Object.defineProperty(t.prototype,"updates",{get:function(){return this._updates},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"built",{get:function(){return this._built},set:function(e){this._built=e;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainable",{get:function(){return this.trainable_},set:function(e){this._trainableWeights.forEach(function(t){return t.trainable=e}),this.trainable_=e;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.trainable_?this._trainableWeights.filter(function(e){return e.trainable}):[]},set:function(e){this._trainableWeights=e;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this._trainableWeights.filter(function(e){return !e.trainable}).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)},set:function(e){this._nonTrainableWeights=e;},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stateful",{get:function(){return this._stateful},enumerable:!0,configurable:!0}),t.prototype.resetStates=function(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")},t.prototype.assertInputCompatibility=function(e){if(e=toList(e),null!=this.inputSpec&&0!==this.inputSpec.length){var t=toList(this.inputSpec);if(e.length!==t.length)throw new ValueError("Layer "+this.name+" expects "+t.length+" inputs, but it received "+e.length+" input tensors. Input received: "+e);for(var n=0;n=0?o[l]:o[o.length+l];if(null!=u&&-1===[u,null].indexOf(c))throw new ValueError("Input "+n+" is incompatible with layer "+this.name+": expected axis "+l+" of input shape to have value "+u+" but got shape "+o+".")}}if(null!=i.shape)for(var p=0;p0&&Array.isArray(f[0])?f.map(function(r,i){return new SymbolicTensor(m,r,n,toList(e),t,n.name,i)}):new SymbolicTensor(m,f,n,toList(e),t,n.name),n.addInboundNode(e,g,null,null,d,f,t),n._refCount++,null!=n.activityRegularizer)throw new NotImplementedError("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return g})},t.prototype.warnOnIncompatibleInputShape=function(e){if(null!=this.batchInputShape)if(e.length!==this.batchInputShape.length)console.warn("The rank of the input tensor provided (shape: "+JSON.stringify(e)+") does not match that of the batchInputShape ("+JSON.stringify(this.batchInputShape)+") of the layer "+this.name);else{var t=!1;this.batchInputShape.forEach(function(n,r){null!=n&&null!=e[r]&&e[r]!==n&&(t=!0);}),t&&console.warn("The shape of the input tensor ("+JSON.stringify(e)+") does not match the expectation of layer "+this.name+": "+JSON.stringify(this.batchInputShape));}},Object.defineProperty(t.prototype,"outputShape",{get:function(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new AttributeError("The layer "+this.name+" has never been called and thus has no defined output shape.");for(var e=[],t=0,n=this.inboundNodes;t0)&&(t=e.sourceLayer,n=e.nodeIndex),0===t.inboundNodes.length)return [e];var r=t.inboundNodes[n];if(0===r.inboundLayers.length)return r.inputTensors;for(var i=[],a=0;a0?[4,Promise.all(t)]:[3,2];case 1:for(s=u.sent(),l=0;l=0&&Number.isInteger(t),function(){return "Verbosity level is expected to be an integer >= 0, but got "+t}),e.checkForDuplicate(n),null==e.constructors[t]&&(e.constructors[t]=[]),e.constructors[t].push(n);},e.checkForDuplicate=function(t){for(var n in e.constructors){e.constructors[+n].forEach(function(e){if(e===t)throw new ValueError("Duplicate callback constructor.")});}},e.clear=function(){e.constructors={};},e.createCallbacks=function(t){var n=[];for(var r in e.constructors){var i=+r;t>=i&&n.push.apply(n,e.constructors[i]);}return n.map(function(e){return new e})},e.constructors={},e}();function configureCallbacks(e,t,n,r,i,a,o,s,l){var u=new History,c=[new BaseLogger].concat(CallbackConstructorRegistry.createCallbacks(t));null!=e&&c.push.apply(c,e),c.push(u);var p=new CallbackList(c);return p.setParams({epochs:n,initialEpoch:r,samples:i,steps:a,batchSize:o,verbose:t,doValidation:s,metrics:l}),{callbackList:p,history:u}}function deserialize(e,t,n){return void 0===t&&(t={}),void 0===n&&(n=!1),deserializeKerasObject(e,Fh.SerializationMap.getMap().classNameMap,t,"layer",n)}function l2Normalize(e,t){return Pe(function(){"float32"!==e.dtype&&(e=e.asType("float32"));var n=Wu(square(e),t,!0),r=Nn(n.shape,epsilon()),i=Bs(il(n,r));return rl(e,i)})}function meanSquaredError(e,t){return Pe(function(){return Bu(square(yl(t,e)),-1)})}function meanAbsoluteError(e,t){return Pe(function(){return Bu(is(yl(t,e)),-1)})}function meanAbsolutePercentageError(e,t){return Pe(function(){var n=yl(e,t),r=ds(is(e),epsilon(),Number.MAX_VALUE),i=is(rl(n,r));return pl(100,Bu(i,-1))})}function meanSquaredLogarithmicError(e,t){return Pe(function(){var n=ds(t,epsilon(),Number.MAX_VALUE),r=ws(Zu(1,n)),i=ds(e,epsilon(),Number.MAX_VALUE),a=ws(Zu(1,i));return Bu(square(yl(r,a)),-1)})}function squaredHinge(e,t){return Pe(function(){var n=il(0,yl(1,pl(e,t)));return Bu(square(n),-1)})}function hinge(e,t){return Pe(function(){var n=il(0,yl(1,pl(e,t)));return Bu(n,-1)})}function categoricalHinge(e,t){return Pe(function(){var n=Wu(pl(e,t),-1),r=Fu(pl(yl(1,e),t),-1);return il(0,Zu(1,yl(r,n)))})}function logcosh(e,t){return Pe(function(){var n=Math.log(2),r=yl(t,e),i=yl(Zu(r,Fs(pl(-2,r))),n);return Bu(i,-1)})}function categoricalCrossentropy(e,t,n){return void 0===n&&(n=!1),Pe(function(){if(n)t=qr(t);else{var r=Wu(t,t.shape.length-1,!0);t=rl(t,r);}return t=ds(t,epsilon(),1-epsilon()),Rs(Wu(pl(e.toFloat(),ws(t)),t.shape.length-1))})}function sparseCategoricalCrossentropy(e,t){return Pe(function(){var n=bs(flatten(e)).toInt(),r=(t=ds(t,epsilon(),1-epsilon())).shape;return categoricalCrossentropy(ar(n,r[r.length-1]).reshape(r),t,!1)})}function sigmoidCrossEntropyWithLogits(e,t){if(!Z.arraysEqual(e.shape,t.shape))throw new ValueError("logits and labels must have the same shape, but got shapes "+JSON.stringify(e.shape)+" and "+JSON.stringify(t.shape));return Pe(function(){var n=t.relu(),r=t.abs().neg();return n.sub(t.mul(e)).add(r.exp().log1p())})}function binaryCrossentropy(e,t){return Pe(function(){var n;return n=ds(t,epsilon(),1-epsilon()),n=ws(rl(n,yl(1,n))),Bu(sigmoidCrossEntropyWithLogits(e,n),-1)})}function kullbackLeiblerDivergence(e,t){return Pe(function(){var n=ds(e,epsilon(),1),r=ds(t,epsilon(),1);return Wu(pl(e,ws(rl(n,r))),-1)})}function poisson(e,t){return Pe(function(){var n=ws(Zu(epsilon(),t));return Bu(yl(t,pl(e,n)),-1)})}function cosineProximity(e,t){return Pe(function(){var n=l2Normalize(e,-1),r=l2Normalize(t,-1),i=pl(n,r);return Rs(Wu(i,-1))})}var lossesMap={meanSquaredError:meanSquaredError,meanAbsoluteError:meanAbsoluteError,meanAbsolutePercentageError:meanAbsolutePercentageError,meanSquaredLogarithmicError:meanSquaredLogarithmicError,squaredHinge:squaredHinge,hinge:hinge,categoricalHinge:categoricalHinge,logcosh:logcosh,categoricalCrossentropy:categoricalCrossentropy,sparseCategoricalCrossentropy:sparseCategoricalCrossentropy,binaryCrossentropy:binaryCrossentropy,kullbackLeiblerDivergence:kullbackLeiblerDivergence,poisson:poisson,cosineProximity:cosineProximity};function get(e){if("string"==typeof e){if(e in lossesMap)return lossesMap[e];var t="Unknown loss "+e;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t="Unknown loss "+e+'. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy'),new ValueError(t)}return e}function binaryAccuracy(e,t){return Pe(function(){var n=pl(.5,Tn(t)),r=cast$1(Gu(t,n),e.dtype);return Bu(zu(e,r),-1)})}function categoricalAccuracy(e,t){return Pe(function(){return cast$1(zu(_u(e,-1),_u(t,-1)),"float32")})}function truePositives(e,t){return Pe(function(){return bl(e.equal(1),t.equal(1)).sum().cast("float32")})}function falseNegatives(e,t){return Pe(function(){return bl(e.equal(1),t.equal(0)).sum().cast("float32")})}function falsePositives(e,t){return Pe(function(){return bl(e.equal(0),t.equal(1)).sum().cast("float32")})}function precision(e,t){return Pe(function(){var n=truePositives(e,t),r=falsePositives(e,t),i=n.add(r);return Rl(Gu(i,0),n.div(i),0).cast("float32")})}function recall(e,t){return Pe(function(){var n=truePositives(e,t),r=falseNegatives(e,t),i=n.add(r);return Rl(Gu(i,0),n.div(i),0).cast("float32")})}function binaryCrossentropy$1(e,t){return binaryCrossentropy(e,t)}function sparseCategoricalAccuracy(e,t){return e.rank===t.rank&&(e=e.squeeze([e.rank-1])),(t=t.argMax(-1)).dtype!==e.dtype&&(t=t.asType(e.dtype)),zu(e,t).asType("float32")}var mse$1=meanSquaredError,MSE$1=meanSquaredError,mae$1=meanAbsoluteError,MAE$1=meanAbsoluteError,mape$1=meanAbsolutePercentageError,MAPE$1=meanAbsolutePercentageError,categoricalCrossentropy$1=categoricalCrossentropy,cosine$1=cosineProximity,sparseCategoricalCrossentropy$1=sparseCategoricalCrossentropy,metricsMap={binaryAccuracy:binaryAccuracy,categoricalAccuracy:categoricalAccuracy,precision:precision,categoricalCrossentropy:categoricalCrossentropy$1,sparseCategoricalCrossentropy:sparseCategoricalCrossentropy$1,mse:mse$1,MSE:MSE$1,mae:mae$1,MAE:MAE$1,mape:mape$1,MAPE:MAPE$1,cosine:cosine$1};function get$1(e){if("string"==typeof e&&e in metricsMap)return metricsMap[e];if("string"!=typeof e&&null!=e)return e;throw new ValueError("Unknown metric "+e)}function getLossOrMetricName(e){if(assert(null!==e,"Unknown LossOrMetricFn "+e),"string"==typeof e)return e;for(var t=void 0,n=0,r=Object.keys(lossesMap);n1||1===s.length&&s[0].inboundLayers.length>1){t=!1;break}r.push.apply(r,s);}if(t)for(var l=0,u=e.layers;l0&&(r=r.slice(0,r.length-1)+" "),r=(r+=e[i]).slice(0,t[i]),r+=" ".repeat(t[i]-r.length);n(r);}function printLayerSummary(e,t,n){var r;try{r=JSON.stringify(e.outputShape);}catch(e){r="multiple";}printRow([e.name+" ("+e.getClassName()+")",r,e.countParams().toString()],t,n);}function printLayerSummaryWithConnections(e,t,n,r){var i;try{i=JSON.stringify(e.outputShape);}catch(e){i="multiple";}for(var a=[],o=0,s=e.inboundNodes;o0&&-1===n.indexOf(l)))for(var u=0;ur.maxNumTensors&&(r.maxNumTensors=b),b0,function(){return "Expected at least one fetch, got none"});var n=[],r={};if(1===e.length){var i=getTopologicalSortAndRecipientCountsForOneFetch(e[0],t);n=i.sorted,r=i.recipientMap;}else for(var a=new Set,o=0,s=e;o0;){var c=l[l.length-1];if(n.has(c.name))l.pop();else{var p=u[u.length-1]===l.length-1;if(0===c.inputs.length||p)l.pop(),r.push(c),n.add(c.name),p&&u.pop();else{u.push(l.length-1);for(var h=0,d=c.inputs;h1 nodes"),assert(0===u,"input layer has >1 tensors"),r.inputLayers.push(s),r.inputLayersNodeIndices.push(l),r.inputLayersTensorIndices.push(u);}r.inputNames=[],r.outputNames=[],r.feedInputShapes=[],r.feedInputNames=[],r.feedOutputNames=[];for(var h=0;h=0;)i.splice(i.indexOf(l),1);w.push(l);}},S=[],A=[],_=0,C=r.outputs;_r?1:0});for(var W=0,j=U;W0)throw new ValueError("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return [];for(var e=[],t=0,n=this.layers;t0)throw new ValueError(p.length+" of "+r+" weights are not set: "+p)}batchSetValue(u);},t.prototype.updatedConfig=function(){var e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion="tfjs-layers "+version,t.backend="TensorFlow.js",t},t.prototype.toJSON=function(e,t){void 0===t&&(t=!0);var n=convertTsToPythonic(this.updatedConfig());return t?JSON.stringify(n):n},t.prototype.call=function(e,t){var n=this;return Pe(function(){e=toList(e);for(var r=new FeedDict,i=0;i1)for(var s=0,l=o;s0){for(var d=[],f=0;f0&&e.apply(singletonOrArray(r),n);}function l(e){var n=e.name,a=deserialize(e,null!=t.customObjects?t.customObjects:{});a.setFastWeightInitDuringBuild(r),i[n]=a,e.inboundNodes.forEach(function(e){if(!(e instanceof Array))throw new ValueError("Corrupted configuration, expected array for nodeData: "+e);o(a,e);});}for(var u=t.name,c=t.layers,p=0,h=c;p0&&"object"==typeof e[Object.keys(e)[0]]){var i=[];return t.forEach(function(t){t in e?i.push(e[t]):i.push(null);}),i}throw new Error("The model has multiple ("+r+") outputs, so "+n+" must be either an array with "+r+" elements or an object with "+t+" keys. Provided "+n+" not understood: "+JSON.stringify(e))}function standardizeClassWeights(e,t){return standardizeSampleOrClassWeights(e,t,"classWeight")}function standardizeWeights(e,t,n,r){return __awaiter(this,void 0,void 0,function(){var i,a,o,s,l;return __generator(this,function(u){switch(u.label){case 0:if(null!=t||null!=r)throw new Error("Support sampleWeight is not implemented yet");return null==n?[3,2]:(i=Pe(function(){if(1===e.shape.length)return e.clone();if(2===e.shape.length){if(e.shape[1]>1){return e.argMax(1)}if(1===e.shape[1])return e.reshape([e.shape[0]]);throw new Error("Encountered unexpected last-dimension size ("+e.shape[1]+") during handling of class weights. The size is expected to be >= 1.")}throw new Error("Unexpected rank of target (y) tensor ("+e.rank+") during handling of class weights. The rank is expected to be 1 or 2.")}),s=(o=Array).from,[4,i.data()]);case 1:return a=s.apply(o,[u.sent()]),Le(i),l=[],a.forEach(function(e){if(null==n[e])throw new Error("classWeight must contain all classes in the training data. The class "+e+" exists in the data but not in classWeight");l.push(n[e]);}),[2,xn(l,"float32")];case 2:return [2,null]}})})}function computeWeightedLoss(e,t){return pl(e,t)}var DEFAULT_VALIDATION_BATCH_SIZE=32;function standardizeDataIteratorOutput(e,t){var n,r,i=t;n=i.xs,r=i.ys,Z.assert(null!=n&&null!=r,function(){return "A Dataset iterator for fitDataset() is expected to generate objects of the form `{xs: xVal, ys: yVal}`, where the two values may be `tf.Tensor`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates "+t});var a=flattenTensorOrArrayOrMap("input",e.inputNames,n),o=flattenTensorOrArrayOrMap("output",e.outputNames,r),s=a[0].shape[0];Z.assert(a.length===e.inputs.length,function(){return "LayersModel has "+e.inputs.length+" inputs, but the dataset provides "+a.length+" inputs. (Expected input keys: "+JSON.stringify(e.inputNames)+")"}),Z.assert(o.length===e.outputs.length,function(){return "LayersModel has "+e.outputs.length+" outputs, but the dataset provides "+o.length+" outputs. (Expected output keys: "+JSON.stringify(e.outputNames)+")"});var l=function(t){Z.assert(a[t].shape[0]===s,function(){return "Batch size mismatch: input "+e.inputNames[t]+" has "+a[t].shape[0]+"; expected "+s+" based on input "+e.inputNames[0]+"."});};for(var u in a)l(u);var c=function(t){Z.assert(o[t].shape[0]===s,function(){return "Batch size mismatch: output "+e.outputNames[t]+" has "+o[t].shape[0]+"; expected "+s+" based on input "+e.inputNames[0]+"."});};for(var p in o)c(p);return {xs:a,ys:o}}function flattenTensorOrArrayOrMap(e,t,n){if(n instanceof ft)return [n];if(Array.isArray(n))return Z.assert(n.length===t.length,function(){return "Received an array of "+n.length+" Tensors, but expected "+t.length+" to match the "+e+" keys "+t+"."}),n;for(var r=[],i=0,a=t;i0&&Number.isInteger(n.epochs),function(){return "For fitDataset(), config.epochs is expected to be a positive integer, but got "+n.epochs}),Z.assert(!r||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),function(){return "For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got "+n.batchesPerEpoch}),Z.assert(null==n.validationSplit,function(){return "`validationSplit` is not supported by `fitDataset()`. Use validationData instead."}),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0,P.label=1;case 1:return P.trys.push([1,,26,27]),i=null!=n.validationData,a=void 0,o=void 0,i&&(isDatasetObject(n.validationData)?Z.assert(null==n.validationBatches||n.validationBatches>0&&Number.isInteger(n.validationBatches),function(){return "For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got "+n.validationBatches}):(s=standardizeTensorValidationData(n.validationData),a=s.xs,o=s.ys)),l=e.makeTrainFunction(),u=e.getDedupedMetricsNames(),c=void 0,c=i?u.slice().concat(u.map(function(e){return "val_"+e})):u.slice(),p=standardizeCallbacks(n.callbacks,n.yieldEvery),h=null==n.verbose?1:n.verbose,d=configureCallbacks(p,h,n.epochs,null,null,getStepsPerEpoch(t,n),null,i,c),f=d.callbackList,g=d.history,f.setModel(e),e.history=g,[4,f.onTrainBegin()];case 2:return P.sent(),e.stopTraining_=!1,m=null==n.initialEpoch?0:n.initialEpoch,[4,t.iterator()];case 3:y=P.sent(),P.label=4;case 4:return m=n.batchesPerEpoch:z.done)?i?(O=void 0,isDatasetObject(n.validationData)?(R=toList,[4,e.evaluateDataset(n.validationData,{batches:n.validationBatches})]):[3,17]):[3,19]:[3,20];case 16:return O=R.apply(void 0,[P.sent()]),[3,18];case 17:O=toList(e.evaluate(a,o,{batchSize:null==n.validationBatchSize?DEFAULT_VALIDATION_BATCH_SIZE:n.validationBatchSize,verbose:0})),P.label=18;case 18:for(M=0;M0)throw new NotImplementedError("Verbose mode is not implemented yet.");return Z.assert(!r||n.batches>0&&Number.isInteger(n.batches),function(){return "Test loop expects `batches` to be a positive integer, but received "+JSON.stringify(n.batches)}),isLazyIteratorObject(t)?(s=t,[3,3]):[3,1];case 1:return [4,t.iterator()];case 2:s=d.sent(),d.label=3;case 3:o=s,l=0,u=0,c=function(){var t;return __generator(this,function(s){switch(s.label){case 0:return [4,o.next()];case 1:return t=s.sent(),a=Pe(function(){if(t.value){var n=standardizeDataIteratorOutput(e,t.value),r=n.xs,o=n.ys,s=r.concat(o),c=Pe(function(){return i(s)});if(Le(s),0===u)for(var p=0;p0&&Le(n);};for(p=0;p0&&Number.isInteger(e),function(){return "batchSize is required to be a positive integer, but got "+e});}function sliceArrays(e,t,n){return null==e?[null]:Array.isArray(e)?e.map(function(e){return sliceAlongFirstAxis(e,t,n-t)}):sliceAlongFirstAxis(e,t,n-t)}function sliceArraysByIndices(e,t){return Pe(function(){return null==e?null:Array.isArray(e)?e.map(function(e){return sliceArraysByIndices(e,t)}):gather$1(e,"int32"===t.dtype?t:t.toInt())})}function makeBatches(e,t){for(var n=[],r=0,i=null;r=e&&(i=e),n.push([r,i]),r=i;return n}function fitLoop(e,t,n,r,i,a,o,s,l,u,c,p,h,d,f){return __awaiter(this,void 0,void 0,function(){var g,m,y,v,b,w,z,S;return __generator(this,function(A){switch(A.label){case 0:if(null==i&&(i=32),null==a&&(a=1),null==c&&(c=!0),null==h&&(h=0),g=!1,null!=l&&null!=u&&(g=!0),null!=f&&(g=!0,null==d))throw new ValueError("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");return null!=(m=e.checkNumSamples(n,i,d,"steps_per_epoch"))&&(y=range(0,m)),null==o&&(o=1),v=configureCallbacks(s,o,a,h,m,d,i,g,p),b=v.callbackList,w=v.history,b.setModel(e),e.history=w,[4,b.onTrainBegin()];case 1:A.sent(),e.stopTraining_=!1,z=function(a){var o,s,p,h,f;return __generator(this,function(v){switch(v.label){case 0:return [4,b.onEpochBegin(a)];case 1:if(v.sent(),o={},null==d)return [3,2];throw new NotImplementedError("stepsPerEpoch mode is not implemented yet.");case 2:if("batch"===c)throw new NotImplementedError("batch shuffling is not implemneted yet");c&&Z.shuffle(y),s=xn(y),p=makeBatches(m,i),h=function(a){var c;return __generator(this,function(h){switch(h.label){case 0:return c={},[4,b.onBatchBegin(a,c)];case 1:return h.sent(),Pe(function(){var h=p[a][0],d=p[a][1],f=sliceAlongFirstAxis(s,h,d-h);c.batch=a,c.size=d-h;for(var m=sliceArraysByIndices(n,f),y=t(m),v=0;v0))return [3,4];if(f=!0,2!==r.validationData.length)throw 3===r.validationData.length?new NotImplementedError("validationData including sample weights is not supported yet."):new ValueError("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; "+r.validationData+" is invalid.");return o=r.validationData[0],s=r.validationData[1],m=!0,[4,e.standardizeUserData(o,s,null,null,m,p)];case 3:return y=I.sent(),l=y[0],u=y[1],g=l.concat(u),[3,5];case 4:null!=r.validationSplit&&r.validationSplit>0&&r.validationSplit<1?(f=!0,v=Math.floor(i[0].shape[0]*(1-r.validationSplit)),b=i[0].shape[0],l=sliceArrays(i,v,b),i=sliceArrays(i,0,v),u=sliceArrays(a,v,b),a=sliceArrays(a,0,v),g=l.concat(u)):null!=r.validationSteps&&(f=!0),I.label=5;case 5:return w=i.concat(a).concat(c),e.checkTrainableWeightsConsistency(),z=e.makeTrainFunction(),S=e.getDedupedMetricsNames(),A=void 0,_=void 0,f?(e.makeTestFunction(),A=e.testFunction,_=S.slice().concat(S.map(function(e){return "val_"+e}))):(A=null,g=[],_=S.slice()),C=standardizeCallbacks(r.callbacks,r.yieldEvery),[4,fitLoop(e,z,w,S,p,r.epochs,r.verbose,C,A,g,r.shuffle,_,r.initialEpoch,null,null)];case 6:return [2,I.sent()];case 7:return e.isTraining=!1,disposeNewTensors(i,t),disposeNewTensors(a,n),disposeNewTensors(l,o),disposeNewTensors(u,s),null!=c&&Le(c),[7];case 8:return [2]}})})}function ensureTensorsRank2OrHigher(e){var t=[];e instanceof ft&&(e=[e]);for(var n=0;n0)a=!0;else if(isDataDict(e)){for(var o in e)if(e.hasOwnProperty(o)){a=!0;break}}else a=!0;if(a)throw new ValueError("Error when checking model "+i+" expected no data, but got "+e)}return []}if(null==e)return t.map(function(e){return null});var s;if(isDataDict(e)){e=e,s=[];for(var l=0,u=t;l1)throw new ValueError("The model "+i+" expects "+t.length+" Tensor(s), but only received one Tensor. Found: Tensor with shape "+e.shape);s=[e];}if(s=ensureTensorsRank2OrHigher(s),null!=n)for(var p=0;p=0&&f!==g)throw new ValueError("Error when checking "+i+": expected "+t[p]+" to have shape ["+n[p]+"], but got array with shape ["+h.shape+"].")}}return s}function checkArrayLengths(e,t,n){var r=unique(e.map(function(e){return e.shape[0]}));r.sort();var i=unique(t.map(function(e){return e.shape[0]}));if(i.sort(),r.length>1)throw new ValueError("All input Tensors (x) should have the same number of samples. Got array shapes: "+JSON.stringify(e.map(function(e){return e.shape})));if(i.length>1)throw new ValueError("All target Tensors (y) should have the same number of samples. Got array shapes: "+JSON.stringify(t.map(function(e){return e.shape})));if(r.length>0&&i.length>0&&!Z.arraysEqual(r,i))throw new ValueError("Input Tensors should have the same number of samples as target Tensors. Found "+r[0]+" input sample(s) and "+i[0]+" target sample(s).")}function checkLossAndTargetCompatibility(e,t,n){for(var r=[meanSquaredError,binaryCrossentropy,categoricalCrossentropy],i=0;i1)throw new ValueError("The model expects "+t.length+" "+i+" Tensors, but only received one Tensor. Found: array with shape "+JSON.stringify(e.shape)+".");a=[e];}if(null!=n)for(var o=0;o1&&(t.metricsTensors.push([n,e]),t.metricsNames.push(t.outputNames[e]+"_loss"));}});var d=collectMetrics(e.metrics,this.outputNames);nameScope("metric",function(){for(var e=function(e){if(-1!==h.indexOf(e))return "continue";!function(n){for(var r,i,a,o=function(n){if("string"==typeof n&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(n)){var o=t.internalOutputShapes[e];1===o[o.length-1]||t.lossFunctions[e]===binaryCrossentropy?-1!==["accuracy","acc"].indexOf(n)?i=binaryAccuracy:-1!==["crossentropy","ce"].indexOf(n)&&(i=binaryCrossentropy$1):t.lossFunctions[e]===sparseCategoricalCrossentropy?-1!==["accuracy","acc"].indexOf(n)?i=sparseCategoricalAccuracy:-1!==["crossentropy","ce"].indexOf(n)&&(i=sparseCategoricalCrossentropy$1):-1!==["accuracy","acc"].indexOf(n)?i=categoricalAccuracy:-1!==["crossentropy","ce"].indexOf(n)&&(i=categoricalCrossentropy$1);var s=void 0;-1!==["accuracy","acc"].indexOf(n)?s="acc":-1!==["crossentropy","ce"].indexOf(n)&&(s="ce"),a=i,r=""+s;}else{var l=get$1(n);a=l,r=""+getLossOrMetricName(n);}var u;nameScope(r,function(){u=a;}),function(e,n,r){t.outputNames.length>1&&(n=t.outputNames[e]+"_"+n),t.metricsNames.push(n),t.metricsTensors.push([r,e]);}(e,r,u);},s=0,l=n;s0){var c=[];throw t.forEach(function(t,n){null==t&&c.push(e[n]);}),new ValueError("Cannot find SymbolicTensors for output name(s): "+JSON.stringify(c))}return t},t.prototype.predictLoop=function(e,t,n){var r=this;return void 0===t&&(t=32),void 0===n&&(n=!1),Pe(function(){var i=r.checkNumSamples(e);if(n)throw new NotImplementedError("Verbose predictLoop() is not implemented yet.");for(var a=makeBatches(i,t),o=r.outputs.map(function(e){return []}),s=function(t){Pe(function(){var n=a[t][0],i=a[t][1],o=sliceArrays(e,n,i),s=[];if(Array.isArray(o))for(var l=0;l0&&e[0].shape[0]%r!=0)throw new ValueError("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size "+r+". Found: "+e[0].shape[0]+" sample(s).");return [e,t]},t.prototype.standardizeUserData=function(e,t,n,r,i,a){return void 0===i&&(i=!0),__awaiter(this,void 0,void 0,function(){var o,s,l,u,c,p,h,d;return __generator(this,function(f){switch(f.label){case 0:if(o=this.standardizeUserDataXY(e,t,i,a),s=o[0],l=o[1],null!=n)throw new Error("sample weight is not supported yet.");if(u=null,null==r)return [3,4];c=standardizeClassWeights(r,this.outputNames),u=[],p=0,f.label=1;case 1:return p0)throw new NotImplementedError("Verbose mode is not implemented yet.");if(null!=i)throw new NotImplementedError("steps mode in testLoop() is not implemented yet");for(var l=makeBatches(o,n),u=xn(range(0,o)),c=0;c1)i+="_"+count(e.slice(0,n),r);t.push(i);}return t},t.prototype.makeTrainFunction=function(){var e=this;return function(t){var n=[],r=t.slice(0,e.inputs.length),i=t.slice(e.inputs.length,e.inputs.length+e.outputs.length),a=t.slice(e.inputs.length+e.outputs.length,e.inputs.length+2*e.outputs.length),o=[],s=e.collectedTrainableWeights.map(function(e){return e.read()});return [e.optimizer_.minimize(function(){for(var t=[],s=0;s1&&s1)throw new ValueError("Found more than one ("+r.length+") save handlers for URL '"+e+"'");e=r[0];}if(null==e.save)throw new ValueError("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return [4,Nh.encodeWeights(this.getNamedWeights(t))];case 1:return i=g.sent(),a=!1,o=null,s=this.toJSON(o,a),l={modelTopology:s,format:LAYERS_MODEL_FORMAT_NAME,generatedBy:"TensorFlow.js tfjs-layers v"+version,convertedBy:null},null!=t&&t.includeOptimizer&&null!=this.optimizer?(l.trainingConfig=this.getTrainingConfig(),u="optimizer",f=(d=Nh).encodeWeights,[4,this.optimizer.getWeights()]):[3,4];case 2:return [4,f.apply(d,[g.sent(),u])];case 3:c=g.sent(),p=c.data,h=c.specs,(n=i.specs).push.apply(n,h),i.data=Nh.concatenateArrayBuffers([i.data,p]),g.label=4;case 4:return l.weightData=i.data,l.weightSpecs=i.specs,[2,e.save(l)]}})})},t.className="Model",t}(Container);function modelFromJSON(e,t){return __awaiter(this,void 0,void 0,function(){var n,r,i,a,o,s,l,u;return __generator(this,function(c){switch(c.label){case 0:return "modelTopology"in e||(e={modelTopology:e}),null!=(n=(e=e).modelTopology).model_config&&(n=n.model_config),r=convertPythonicToTs(n),i=deserialize(r,t),null==e.weightsManifest?[3,2]:[4,Nh.loadWeights(e.weightsManifest,e.pathPrefix,i.weights.map(function(e){return e.originalName}))];case 1:for(a=c.sent(),o={},s=0,l=i.weights;s1)throw new ValueError("Found more than one ("+n.length+") load handlers for URL '"+e+"'");e=n[0];}return [2,loadLayersModelFromIOHandler(e,void 0,t)]})})}function loadLayersModelFromIOHandler(e,t,n){return __awaiter(this,void 0,void 0,function(){var r,i,a,o,s,l,u,c,p;return __generator(this,function(h){switch(h.label){case 0:if(null==n&&(n={}),null==e.load)throw new ValueError("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return [4,e.load()];case 1:if(r=h.sent(),null!=(i=r.modelTopology).model_config&&(i=i.model_config),a=null==n.strict||n.strict,o=null!=r.weightData&&null!=r.weightSpecs&&a,s=deserialize(convertPythonicToTs(i),t,o),null!=(l=r.trainingConfig)&&s.loadTrainingConfig(l),null==r.weightData)return [3,4];if(null==r.weightSpecs)throw new ValueError("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");return u=decodeModelAndOptimizerWeights(r.weightData,r.weightSpecs),c=u.modelWeights,p=u.optimizerWeights,s.loadWeights(c,a),null!=s.optimizer&&p.length>0?[4,s.optimizer.setWeights(p)]:[3,3];case 2:h.sent(),h.label=3;case 3:Le(c),Le(p.map(function(e){return e.tensor})),h.label=4;case 4:return [2,s]}})})}function decodeModelAndOptimizerWeights(e,t){var n=Nh.decodeWeights(e,t),r={},i=[];return t.forEach(function(e){"optimizer"===e.group?i.push({name:e.name,tensor:n[e.name]}):r[e.name]=n[e.name];}),{modelWeights:r,optimizerWeights:i}}Fh.registerClass(LayersModel);var Sequential=function(e){function t(t){var n=e.call(this,{inputs:[],outputs:[]})||this;if(t=t||{},n.trainable=!0,n.built=!1,n.name=null!=t.name?t.name:getUid("sequential_"),null!=t.layers)for(var r=0,i=t.layers;r 0 but got "+JSON.stringify(e.filters))},t}(BaseConv),Conv2D=function(e){function t(n){var r=e.call(this,2,n)||this;return t.verifyArgs(n),r}return __extends(t,e),t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.rank,t},t.verifyArgs=function(e){if("number"!=typeof e.kernelSize&&!checkArrayTypeAndLength(e.kernelSize,"number",1,2))throw new ValueError("Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received "+JSON.stringify(e.kernelSize)+".")},t.className="Conv2D",t}(Conv);Fh.registerClass(Conv2D);var Conv3D=function(e){function t(n){var r=e.call(this,3,n)||this;return t.verifyArgs(n),r}return __extends(t,e),t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.rank,t},t.verifyArgs=function(e){if("number"!=typeof e.kernelSize&&(!Array.isArray(e.kernelSize)||1!==e.kernelSize.length&&3!==e.kernelSize.length))throw new ValueError("Conv3D expects config.kernelSize to be number or [number, number, number], but received "+JSON.stringify(e.kernelSize)+".")},t.className="Conv3D",t}(Conv);Fh.registerClass(Conv3D);var Conv2DTranspose=function(e){function t(t){var n=e.call(this,t)||this;if(n.inputSpec=[new InputSpec({ndim:4})],"same"!==n.padding&&"valid"!==n.padding)throw new ValueError("Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode "+n.padding);return n}return __extends(t,e),t.prototype.build=function(e){var t;if(4!==(e=getExactlyOneShape(e)).length)throw new ValueError("Input should have rank 4; Received input shape: "+JSON.stringify(e));var n="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[n])throw new ValueError("The channel dimension of the inputs should be defined. Found `None`.");var r=e[n],i=this.kernelSize.concat([this.filters,r]);this.kernel=this.addWeight("kernel",i,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new InputSpec({ndim:4,axes:(t={},t[n]=r,t)})],this.built=!0;},t.prototype.call=function(e,t){var n=this;return Pe(function(){var t=getExactlyOneTensor(e);if(4!==t.shape.length)throw new ValueError("Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-"+t.shape.length);var r,i,a=t.shape,o=a[0];"channelsFirst"===n.dataFormat?(r=2,i=3):(r=1,i=2);var s=a[r],l=a[i],u=n.kernelSize[0],c=n.kernelSize[1],p=n.strides[0],h=n.strides[1],d=[o,deconvLength(s,p,u,n.padding),deconvLength(l,h,c,n.padding),n.filters];"channelsLast"!==n.dataFormat&&(t=Dl(t,[0,2,3,1]));var f=cu(t,n.kernel.read(),d,n.strides,n.padding);return "channelsLast"!==n.dataFormat&&(f=Dl(f,[0,3,1,2])),null!=n.bias&&(f=biasAdd(f,n.bias.read(),n.dataFormat)),null!=n.activation&&(f=n.activation.apply(f)),f})},t.prototype.computeOutputShape=function(e){var t,n,r,i=(e=getExactlyOneShape(e)).slice();"channelsFirst"===this.dataFormat?(t=1,n=2,r=3):(t=3,n=1,r=2);var a=this.kernelSize[0],o=this.kernelSize[1],s=this.strides[0],l=this.strides[1];return i[t]=this.filters,i[n]=deconvLength(i[n],s,a,this.padding),i[r]=deconvLength(i[r],l,o,this.padding),i},t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.dilationRate,t},t.className="Conv2DTranspose",t}(Conv2D);Fh.registerClass(Conv2DTranspose);var SeparableConv=function(e){function t(t,n){var r=e.call(this,t,n)||this;if(r.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",r.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",r.depthwiseKernel=null,r.pointwiseKernel=null,null==n.filters)throw new ValueError("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=n.kernelInitializer||null!=n.kernelRegularizer||null!=n.kernelConstraint)throw new ValueError("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=n.padding&&"same"!==n.padding&&"valid"!==n.padding)throw new ValueError("SeparableConv"+r.rank+"D supports only padding modes: 'same' and 'valid', but received "+JSON.stringify(n.padding));return r.depthMultiplier=null==n.depthMultiplier?1:n.depthMultiplier,r.depthwiseInitializer=getInitializer(n.depthwiseInitializer||r.DEFAULT_DEPTHWISE_INITIALIZER),r.depthwiseRegularizer=getRegularizer(n.depthwiseRegularizer),r.depthwiseConstraint=getConstraint(n.depthwiseConstraint),r.pointwiseInitializer=getInitializer(n.depthwiseInitializer||r.DEFAULT_POINTWISE_INITIALIZER),r.pointwiseRegularizer=getRegularizer(n.pointwiseRegularizer),r.pointwiseConstraint=getConstraint(n.pointwiseConstraint),r}return __extends(t,e),t.prototype.build=function(e){var t;if((e=getExactlyOneShape(e)).length1)throw new ValueError("Can not merge tensors with different batch sizes. Got tensors with shapes: "+JSON.stringify(e)+".");for(var i=null==e[0]?null:e[0].slice(1),a=1;a1){var y=range(1,s).concat([0]);t.push(Dl(h,y)),u=!0;}else t.push(h);}var v=n.mergeFunction(t),b=v.rank;if(u)if(null==b){var w=v.shape;g=[f=w[w.length-1]].concat(w.slice(0,w.length-1));v=Dl(v.reshape([-1,f]),[1,0]).reshape(g);}else if(b>1){y=[b-1].concat(range(0,b-1));v=Dl(v,y);}return v}return n.mergeFunction(e)})},t.prototype.computeOutputShape=function(e){var t;t=null==(e=e)[0]?null:e[0].slice(1);for(var n=1;n1)throw new ValueError("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}},t.prototype.mergeFunction=function(e){var t=this;return Pe(function(){return concatenate(e,t.axis)})},t.prototype.computeOutputShape=function(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new ValueError("A `Concatenate` layer should be called on a list of inputs.");for(var t=e,n=t[0].slice(),r=this.axis<0?n.length+this.axis:this.axis,i=0,a=t.slice(1);i3||t.shape.length>3)throw new NotImplementedError("batchDot is not implemented for tensors of 4D or higher rank yet");if(Z.assert(e.shape.length>=2,function(){return "batchDot requires the rank of x to be >= 2, but got "+e.shape.length}),Z.assert(e.shape.length>=2,function(){return "batchDot requires the rank of y to be >= 2, but got "+t.shape.length}),"number"==typeof n&&(n=[n,n]),"complex64"===e.dtype||"complex64"===t.dtype)throw new NotImplementedError("batchDot is not implemented for complex64-type Tensors yet.");var r=e.shape.length,i=t.shape.length;null==n&&(n=[r-1,i-2]);var a=n;return Pe(function(){var n,o;if(r>i){n=r-i;for(var s=[],l=0;lr){n=i-r;for(s=[],l=0;l0){var p=void 0,h=[];for(l=p=r>i?r+i-3:r-1;l3||n.length>3)throw new NotImplementedError("Dot layer does not support tensors of 4D or higher rank yet.");var r=this.interpretAxes(t,n);if(t[r[0]]!==n[r[1]])throw new ValueError("Dimension incompatibility: "+t[r[0]]+" !== "+n[r[1]])},t.prototype.mergeFunction=function(e){if(2!==e.length)throw new ValueError("A `Dot` layer must be called on exactly 2 inputs, but received "+e.length+" input(s).");var t,n=e[0],r=e[1];return t=Array.isArray(this.axes)?this.axes.map(function(t,n){return interpretAxis(t,e[n].shape.length)}):[interpretAxis(this.axes,n.shape.length),interpretAxis(this.axes,r.shape.length)],this.normalize&&(n=l2Normalize(n,t[0]),r=l2Normalize(r,t[1])),batchDot(n,r,t)},t.prototype.interpretAxes=function(e,t){return Array.isArray(this.axes)?this.axes:[interpretAxis(this.axes,e.length),interpretAxis(this.axes,t.length)]},t.prototype.computeOutputShape=function(e){Z.assert(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),function(){return "A `Dot` layer should be called on a list of exactly 2 inputs."});var t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new NotImplementedError("Dot layer does not support tensors of 4D or higher rank yet.");var r=this.interpretAxes(t,n);t.splice(r[0],1),n.splice(r[1],1),n.splice(0,1);var i=t.concat(n);return 1===i.length&&i.push(1),i},t.prototype.computeMask=function(e,t){return null},t.prototype.getConfig=function(){var t={axes:this.axes,normalize:this.normalize},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="Dot",t}(Merge);Fh.registerClass(Dot);var GaussianNoise=function(e){function t(t){var n=e.call(this,t)||this;return n.supportsMasking=!0,n.stddev=t.stddev,n}return __extends(t,e),t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this),n={stddev:this.stddev};return Object.assign(n,t),n},t.prototype.call=function(e,t){var n=this;return Pe(function(){n.invokeCallHook(e,t);var r=getExactlyOneTensor(e);return inTrainPhase(function(){return randomNormal$1(r.shape,0,n.stddev).add(r)},function(){return r},t.training||!1)})},t.className="GaussianNoise",t}(Layer);Fh.registerClass(GaussianNoise);var GaussianDropout=function(e){function t(t){var n=e.call(this,t)||this;return n.supportsMasking=!0,n.rate=t.rate,n}return __extends(t,e),t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this),n={rate:this.rate};return Object.assign(n,t),n},t.prototype.call=function(e,t){var n=this;return Pe(function(){n.invokeCallHook(e,t);var r=getExactlyOneTensor(e);if(n.rate>0&&n.rate<1){return inTrainPhase(function(){var e=Math.sqrt(n.rate/(1-n.rate));return r.mul(randomNormal$1(r.shape,1,e))},function(){return r},t.training||!1)}return r})},t.className="GaussianDropout",t}(Layer);Fh.registerClass(GaussianDropout);var AlphaDropout=function(e){function t(t){var n=e.call(this,t)||this;return n.supportsMasking=!0,n.rate=t.rate,n.noiseShape=t.noiseShape,n}return __extends(t,e),t.prototype._getNoiseShape=function(e){return this.noiseShape||getExactlyOneTensor(e).shape},t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this),n={rate:this.rate};return Object.assign(n,t),n},t.prototype.call=function(e,t){var n=this;return Pe(function(){if(n.rate<1&&n.rate>0){var r=n._getNoiseShape(e);return inTrainPhase(function(){var t=getExactlyOneTensor(e),i=-1.7580993408473766,a=qu(fr(r),n.rate);a=cast$1(a,"float32");var o=Math.pow((1-n.rate)*(1+n.rate*Math.pow(i,2)),-.5),s=-o*i*n.rate;return t.mul(a).add(a.add(-1).mul(i)).mul(o).add(s)},function(){return getExactlyOneTensor(e)},t.training||!1)}return e})},t.className="AlphaDropout",t}(Layer);function batchNormalization(e,t,n,r,i,a){var o;if(void 0===a&&(a=.001),2===e.rank)o=Js(e,t,n,r,i,a);else if(3===e.rank)o=Zs(e,t,n,r,i,a);else{if(4!==e.rank)throw new NotImplementedError("batchNormalization is not implemented for array of rank "+e.rank+" yet");o=tu(e,t,n,r,i,a);}return o}function regularNormalizeBatchInTraining(e,t,n,r,i){return void 0===i&&(i=.001),Pe(function(){var a=Lu(e,r),o=a.mean,s=a.variance;return [batchNormalization(e,o,s,n,t,i),o,s]})}function broadcastNormalizeBatchInTraining(e,t,n,r,i){return void 0===i&&(i=.001),Pe(function(){for(var a=Lu(e,r),o=a.mean,s=a.variance,l=[],u=0,c=range(0,e.rank);u=0?this.axis:this.axis+e.length,r=e[n];if(null==r)throw new ValueError("Axis "+n+" of input tensor should have a defined dimension but the layer received an input with shape "+JSON.stringify(e)+".");this.inputSpec=[new InputSpec({ndim:e.length,axes:(t={},t[n]=r,t)})];var i=[r];this.scale&&(this.gamma=this.addWeight("gamma",i,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",i,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",i,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",i,null,this.movingVarianceInitializer,null,!1),this.built=!0;},t.prototype.call=function(e,t){var n=this;return Pe(function(){var r=null!=t.training&&t.training,i=getExactlyOneTensor(e),a=i.shape,o=a.length,s=range(0,o),l=n.axis>=0?n.axis:n.axis+o;s.splice(l,1);var u=pyListRepeat(1,o);u[l]=a[l];var c=s.slice();c.sort();var p=!Z.arraysEqual(c,range(0,o).slice(0,o-1));if(!r)return function(){if(p){var e=n.movingMean.read().reshape(u),t=n.movingVariance.read().reshape(u),r=n.center?n.beta.read().reshape(u):null,a=n.scale?n.gamma.read().reshape(u):null;return batchNormalization(i,e,t,r,a,n.epsilon)}return batchNormalization(i,n.movingMean.read(),n.movingVariance.read(),null==n.beta?null:n.beta.read(),null==n.gamma?null:n.gamma.read(),n.epsilon)}();var h=normalizeBatchInTraining(i,n.gamma.read(),n.beta.read(),s,n.epsilon),d=h[0],f=h[1],g=h[2],m=function(e,t,n){Pe(function(){var r=1-n,i=e.read(),a=i.sub(t).mul(r);e.write(i.sub(a));});};return m(n.movingMean,f,n.momentum),m(n.movingVariance,g,n.momentum),d})},t.prototype.getConfig=function(){var t={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:serializeInitializer(this.betaInitializer),gammaInitializer:serializeInitializer(this.gammaInitializer),movingMeanInitializer:serializeInitializer(this.movingMeanInitializer),movingVarianceInitializer:serializeInitializer(this.movingVarianceInitializer),betaRegularizer:serializeRegularizer(this.betaRegularizer),gammaRegularizer:serializeRegularizer(this.gammaRegularizer),betaConstraint:serializeConstraint(this.betaConstraint),gammaConstraint:serializeConstraint(this.gammaConstraint)},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="BatchNormalization",t}(Layer);function spatial2dPadding(e,t,n){return Pe(function(){if(4!==e.rank)throw new ValueError("temporalPadding expects input tensor to be 4-D, but received a "+e.rank+"-D tensor.");if(null==t&&(t=[[1,1],[1,1]]),2!==t.length||2!==t[0].length||2!==t[1].length)throw new ValueError("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==n&&(n=imageDataFormat()),"channelsLast"!==n&&"channelsFirst"!==n)throw new ValueError("Unknown data format: "+n+". Supported data formats are 'channelsLast' and 'channelsFirst.");var r;return r="channelsFirst"===n?[[0,0],[0,0],t[0],t[1]]:[[0,0],t[0],t[1],[0,0]],ir(e,r)})}Fh.registerClass(BatchNormalization);var ZeroPadding2D=function(e){function t(t){var n=this;if(null==t&&(t={}),(n=e.call(this,t)||this).dataFormat=null==t.dataFormat?imageDataFormat():t.dataFormat,null==t.padding)n.padding=[[1,1],[1,1]];else if("number"==typeof t.padding)n.padding=[[t.padding,t.padding],[t.padding,t.padding]];else{if(t.padding=t.padding,2!==t.padding.length)throw new ValueError("ZeroPadding2D expects padding to be a length-2 array, but received a length-"+t.padding.length+" array.");var r=void 0,i=void 0;if("number"==typeof t.padding[0])r=[t.padding[0],t.padding[0]],i=[t.padding[1],t.padding[1]];else{if(t.padding=t.padding,2!==t.padding[0].length)throw new ValueError("ZeroPadding2D expects height padding to be a length-2 array, but received a length-"+t.padding[0].length+" array.");if(r=t.padding[0],2!==t.padding[1].length)throw new ValueError("ZeroPadding2D expects width padding to be a length-2 array, but received a length-"+t.padding[1].length+" array.");i=t.padding[1];}n.padding=[r,i];}return n.inputSpec=[new InputSpec({ndim:4})],n}return __extends(t,e),t.prototype.computeOutputShape=function(e){var t,n;return e=getExactlyOneShape(e),"channelsFirst"===this.dataFormat?(t=null!=e[2]&&e[2]>=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[3]&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],t,n]):(t=null!=e[1]&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[2]&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],t,n,e[3]])},t.prototype.call=function(e,t){var n=this;return Pe(function(){return spatial2dPadding(getExactlyOneTensor(e),n.padding,n.dataFormat)})},t.prototype.getConfig=function(){var t={padding:this.padding,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t.className="ZeroPadding2D",t}(Layer);function pool2d(e,t,n,r,i,a){return Pe(function(){var o;checkDataFormat(i),checkPoolMode(a),checkPaddingMode(r),null==n&&(n=[1,1]),null==r&&(r="valid"),null==i&&(i=imageDataFormat()),null==a&&(a="max"),e=preprocessConv2DInput(e,i);var s="same"===r?"same":"valid";return o="max"===a?wu(e,t,n,s):Cu(e,t,n,s),"channelsFirst"===i&&(o=Dl(o,[0,3,1,2])),o})}Fh.registerClass(ZeroPadding2D);var Pooling1D=function(e){function t(t){var n=this;if(null==t.poolSize&&(t.poolSize=2),n=e.call(this,t)||this,"number"==typeof t.poolSize)n.poolSize=[t.poolSize];else{if(!Array.isArray(t.poolSize)||1!==t.poolSize.length||"number"!=typeof t.poolSize[0])throw new ValueError("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(t.poolSize));n.poolSize=t.poolSize;}if(assertPositiveInteger(n.poolSize,"poolSize"),null==t.strides)n.strides=n.poolSize;else if("number"==typeof t.strides)n.strides=[t.strides];else{if(!Array.isArray(t.strides)||1!==t.strides.length||"number"!=typeof t.strides[0])throw new ValueError("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(t.strides));n.strides=t.strides;}return assertPositiveInteger(n.strides,"strides"),n.padding=null==t.padding?"valid":t.padding,checkPaddingMode(n.padding),n.inputSpec=[new InputSpec({ndim:3})],n}return __extends(t,e),t.prototype.computeOutputShape=function(e){var t=convOutputLength((e=getExactlyOneShape(e))[1],this.poolSize[0],this.padding,this.strides[0]);return [e[0],t,e[2]]},t.prototype.call=function(e,t){var n=this;return Pe(function(){n.invokeCallHook(e,t),e=expandDims$1(getExactlyOneTensor(e),2);var r=n.poolingFunction(getExactlyOneTensor(e),[n.poolSize[0],1],[n.strides[0],1],n.padding,"channelsLast");return mr(r,[2])})},t.prototype.getConfig=function(){var t={poolSize:this.poolSize,padding:this.padding,strides:this.strides},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t}(Layer),MaxPooling1D=function(e){function t(t){return e.call(this,t)||this}return __extends(t,e),t.prototype.poolingFunction=function(e,t,n,r,i){return checkDataFormat(i),checkPaddingMode(r),pool2d(e,t,n,r,i,"max")},t.className="MaxPooling1D",t}(Pooling1D);Fh.registerClass(MaxPooling1D);var AveragePooling1D=function(e){function t(t){return e.call(this,t)||this}return __extends(t,e),t.prototype.poolingFunction=function(e,t,n,r,i){return checkDataFormat(i),checkPaddingMode(r),pool2d(e,t,n,r,i,"avg")},t.className="AveragePooling1D",t}(Pooling1D);Fh.registerClass(AveragePooling1D);var Pooling2D=function(e){function t(t){var n=this;if(null==t.poolSize&&(t.poolSize=[2,2]),(n=e.call(this,t)||this).poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize],null==t.strides)n.strides=n.poolSize;else if(Array.isArray(t.strides)){if(2!==t.strides.length)throw new ValueError("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length "+t.strides.length+".");n.strides=t.strides;}else n.strides=[t.strides,t.strides];return assertPositiveInteger(n.poolSize,"poolSize"),assertPositiveInteger(n.strides,"strides"),n.padding=null==t.padding?"valid":t.padding,n.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,checkDataFormat(n.dataFormat),checkPaddingMode(n.padding),n.inputSpec=[new InputSpec({ndim:4})],n}return __extends(t,e),t.prototype.computeOutputShape=function(e){e=getExactlyOneShape(e);var t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=convOutputLength(t,this.poolSize[0],this.padding,this.strides[0]),n=convOutputLength(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n]:[e[0],t,n,e[3]]},t.prototype.call=function(e,t){var n=this;return Pe(function(){return n.invokeCallHook(e,t),n.poolingFunction(getExactlyOneTensor(e),n.poolSize,n.strides,n.padding,n.dataFormat)})},t.prototype.getConfig=function(){var t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t}(Layer),MaxPooling2D=function(e){function t(t){return e.call(this,t)||this}return __extends(t,e),t.prototype.poolingFunction=function(e,t,n,r,i){return checkDataFormat(i),checkPaddingMode(r),pool2d(e,t,n,r,i,"max")},t.className="MaxPooling2D",t}(Pooling2D);Fh.registerClass(MaxPooling2D);var AveragePooling2D=function(e){function t(t){return e.call(this,t)||this}return __extends(t,e),t.prototype.poolingFunction=function(e,t,n,r,i){return checkDataFormat(i),checkPaddingMode(r),pool2d(e,t,n,r,i,"avg")},t.className="AveragePooling2D",t}(Pooling2D);Fh.registerClass(AveragePooling2D);var GlobalPooling1D=function(e){function t(t){var n=e.call(this,t)||this;return n.inputSpec=[new InputSpec({ndim:3})],n}return __extends(t,e),t.prototype.computeOutputShape=function(e){return [e[0],e[2]]},t.prototype.call=function(e,t){throw new NotImplementedError},t}(Layer),GlobalAveragePooling1D=function(e){function t(t){return e.call(this,t||{})||this}return __extends(t,e),t.prototype.call=function(e,t){return Pe(function(){var t=getExactlyOneTensor(e);return Bu(t,1)})},t.className="GlobalAveragePooling1D",t}(GlobalPooling1D);Fh.registerClass(GlobalAveragePooling1D);var GlobalMaxPooling1D=function(e){function t(t){return e.call(this,t||{})||this}return __extends(t,e),t.prototype.call=function(e,t){return Pe(function(){var t=getExactlyOneTensor(e);return Fu(t,1)})},t.className="GlobalMaxPooling1D",t}(GlobalPooling1D);Fh.registerClass(GlobalMaxPooling1D);var GlobalPooling2D=function(e){function t(t){var n=e.call(this,t)||this;return n.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,checkDataFormat(n.dataFormat),n.inputSpec=[new InputSpec({ndim:4})],n}return __extends(t,e),t.prototype.computeOutputShape=function(e){return e=e,"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]},t.prototype.call=function(e,t){throw new NotImplementedError},t.prototype.getConfig=function(){var t={dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},t}(Layer),GlobalAveragePooling2D=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),t.prototype.call=function(e,t){var n=this;return Pe(function(){var t=getExactlyOneTensor(e);return "channelsLast"===n.dataFormat?Bu(t,[1,2]):Bu(t,[2,3])})},t.className="GlobalAveragePooling2D",t}(GlobalPooling2D);Fh.registerClass(GlobalAveragePooling2D);var GlobalMaxPooling2D=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),t.prototype.call=function(e,t){var n=this;return Pe(function(){var t=getExactlyOneTensor(e);return "channelsLast"===n.dataFormat?Fu(t,[1,2]):Fu(t,[2,3])})},t.className="GlobalMaxPooling2D",t}(GlobalPooling2D);function standardizeArgs(e,t,n,r){if(Array.isArray(e)){if(null!=t||null!=n)throw new ValueError("When inputs is an array, neither initialState or constants should be provided");null!=r&&(n=e.slice(e.length-r,e.length),e=e.slice(0,e.length-r)),e.length>1&&(t=e.slice(1,e.length)),e=e[0];}function i(e){return null==e||Array.isArray(e)?e:[e]}return {inputs:e,initialState:t=i(t),constants:n=i(n)}}function rnn(e,t,n,r,i,a,o,s){return void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===s&&(s=!1),Pe(function(){var l=t.shape.length;if(l<3)throw new ValueError("Input should be at least 3D, but is "+l+"D.");var u=[1,0].concat(range(2,l));if(t=Dl(t,u),null!=a)throw new NotImplementedError("The rnn() functoin of the deeplearn.js backend does not support constants yet.");o&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),null!=i&&((i=i.asType("bool").asType("float32")).rank===l-1&&(i=nr(i,-1)),i=Dl(i,u)),r&&(t=du(t,0),null!=i&&(i=du(i,0)));var c,p,h=[],d=n,f=t.shape[0],g=br(t);null!=i&&(p=br(i));for(var m,y=function(t){var n=g[t],r=Pe(function(){return e(n,d)});if(null==i)c=r[0],d=r[1];else{var a=Pe(function(){var e=p[t],n=Tn(e).sub(e);return {output:r[0].mul(e).addStrict(d[0].mul(n)),newStates:d.map(function(t,i){return r[1][i].mul(e).addStrict(t.mul(n))})}});c=a.output,d=a.newStates;}s&&h.push(c);},v=0;v1?tile$1(n,[1,e]):n}):t.cell.stateSize>1?[tile$1(n,[1,t.cell.stateSize])]:[n]})},Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.trainable?this.cell.trainableWeights:[]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights},enumerable:!0,configurable:!0}),t.prototype.setFastWeightInitDuringBuild=function(t){e.prototype.setFastWeightInitDuringBuild.call(this,t),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(t);},t.prototype.getConfig=function(){var t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);var n=this.cell.getConfig();t.cell={className:this.cell.getClassName(),config:n};var r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},t.fromConfig=function(e,t,n){void 0===n&&(n={});var r=deserialize(t.cell,n);return new e(Object.assign(t,{cell:r}))},t.className="RNN",t}(Layer);Fh.registerClass(RNN);var RNNCell=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return __extends(t,e),t}(Layer),SimpleRNNCell=function(e){function t(t){var n=e.call(this,t)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=t.units,assertPositiveInteger(n.units,"units"),n.activation=getActivation(null==t.activation?n.DEFAULT_ACTIVATION:t.activation),n.useBias=null==t.useBias||t.useBias,n.kernelInitializer=getInitializer(t.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=getInitializer(t.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=getInitializer(t.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelRegularizer=getRegularizer(t.kernelRegularizer),n.recurrentRegularizer=getRegularizer(t.recurrentRegularizer),n.biasRegularizer=getRegularizer(t.biasRegularizer),n.kernelConstraint=getConstraint(t.kernelConstraint),n.recurrentConstraint=getConstraint(t.recurrentConstraint),n.biasConstraint=getConstraint(t.biasConstraint),n.dropout=min$1([1,max$1([0,null==t.dropout?0:t.dropout])]),n.recurrentDropout=min$1([1,max$1([0,null==t.recurrentDropout?0:t.recurrentDropout])]),n.stateSize=n.units,n.dropoutMask=null,n.recurrentDropoutMask=null,n}return __extends(t,e),t.prototype.build=function(e){e=getExactlyOneShape(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0;},t.prototype.call=function(e,t){var n=this;return Pe(function(){if(2!==(e=e).length)throw new ValueError("SimpleRNNCell expects 2 input Tensors, got "+e.length+".");var r=e[1];e=e[0];var i,a=null!=t.training&&t.training;01){for(var a=[],o=0;o= 3D, but received input shape "+JSON.stringify(t));this.inputSpec=[{shape:t}];var n=[t[0]].concat(t.slice(2));this.layer.built||(this.layer.build(n),this.layer.built=!0),e.prototype.build.call(this,t);},t.prototype.computeOutputShape=function(e){var t=[(e=getExactlyOneShape(e))[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),r=e[1];return [n[0],r].concat(n.slice(1))},t.prototype.call=function(e,t){var n=this;return Pe(function(){return rnn(function(e,r){return [getExactlyOneTensor(n.layer.call(e,t)),[]]},e=getExactlyOneTensor(e),[],!1,null,null,!1,!0)[1]})},t.className="TimeDistributed",t}(Wrapper);function checkBidirectionalMergeMode(e){checkStringTypeUnionValue(VALID_BIDIRECTIONAL_MERGE_MODES,"BidirectionalMergeMode",e);}Fh.registerClass(TimeDistributed);var DEFAULT_BIDIRECTIONAL_MERGE_MODE="concat",Bidirectional=function(e){function t(t){var n=e.call(this,t)||this,r=t.layer.getConfig(),i={};i.className=t.layer.getClassName(),i.config=r,n.forwardLayer=deserialize(i),r.goBackwards=!0!==r.goBackwards;var a={};if(a.className=t.layer.getClassName(),a.config=r,n.backwardLayer=deserialize(a),n.forwardLayer.name="forward_"+n.forwardLayer.name,n.backwardLayer.name="backward_"+n.backwardLayer.name,n.mergeMode=void 0===t.mergeMode?DEFAULT_BIDIRECTIONAL_MERGE_MODE:t.mergeMode,checkBidirectionalMergeMode(n.mergeMode),t.weights)throw new NotImplementedError("weights support is not implemented for Bidirectional layer yet.");return n._stateful=t.layer.stateful,n.returnSequences=t.layer.returnSequences,n.returnState=t.layer.returnState,n.supportsMasking=!0,n._trainable=!0,n.inputSpec=t.layer.inputSpec,n.numConstants=null,n}return __extends(t,e),Object.defineProperty(t.prototype,"trainable",{get:function(){return this._trainable},set:function(e){this._trainable=e,null!=this.forwardLayer&&(this.forwardLayer.trainable=e),null!=this.backwardLayer&&(this.backwardLayer.trainable=e);},enumerable:!0,configurable:!0}),t.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())},t.prototype.setWeights=function(e){var t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n));},t.prototype.computeOutputShape=function(e){var t,n,r,i=this.forwardLayer.computeOutputShape(e);return Array.isArray(i)&&Array.isArray(i[0])||(i=[i]),i=i,this.returnState?(r=i.slice(1),t=i[0]):t=i[0],t=t,"concat"===this.mergeMode?(t[t.length-1]*=2,n=[t]):n=null==this.mergeMode?[t,t.slice()]:[t],this.returnState?null==this.mergeMode?n.concat(r).concat(r.slice()):[t].concat(r).concat(r.slice()):singletonOrArray(n)},t.prototype.apply=function(t,n){var r=null==n?null:n.initialState,i=null==n?null:n.constants;null==n&&(n={});var a=standardizeArgs(t,r,i,this.numConstants);if(t=a.inputs,r=a.initialState,i=a.constants,Array.isArray(t)&&(r=t.slice(1),t=t[0]),(null==r||0===r.length)&&null==i)return e.prototype.apply.call(this,t,n);var o=[],s=[];if(null!=r){var l=r.length;if(l%2>0)throw new ValueError("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");n.initialState=r,o.push.apply(o,r);var u=r.map(function(e){return new InputSpec({shape:e.shape})});this.forwardLayer.stateSpec=u.slice(0,l/2),this.backwardLayer.stateSpec=u.slice(l/2),s.push.apply(s,u);}if(null!=i)throw new NotImplementedError("Support for constants in Bidirectional layers is not implemented yet.");for(var c=o[0]instanceof SymbolicTensor,p=0,h=o;pt}var EarlyStopping=function(e){function t(t){var n=e.call(this)||this;if(null==t&&(t={}),t.restoreBestWeights)throw new NotImplementedError("restoreBestWeights = True is not implemented in EarlyStopping yet.");return n.monitor=t.monitor||"val_loss",n.minDelta=Math.abs(t.minDelta||0),n.patience=t.patience||0,n.verbose=t.verbose||0,n.mode=t.mode||"auto",n.baseline=t.baseline,-1===["auto","min","max"].indexOf(n.mode)&&(console.warn("EarlyStopping mode '"+n.mode+"' is invalid. Falling back to mode 'auto'."),n.mode="auto"),"min"===n.mode?n.monitorFunc=less:"max"===n.mode?n.monitorFunc=greater$1:-1!==n.monitor.indexOf("acc")?n.monitorFunc=greater$1:n.monitorFunc=less,n.monitorFunc===less&&(n.minDelta*=-1),n}return __extends(t,e),t.prototype.onTrainBegin=function(e){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return this.wait=0,this.stoppedEpoch=0,null!=this.baseline?this.best=this.baseline:this.best=this.monitorFunc===less?1/0:-1/0,[2]})})},t.prototype.onEpochEnd=function(e,t){return __awaiter(this,void 0,void 0,function(){var n;return __generator(this,function(r){switch(r.label){case 0:return [4,resolveScalarsInLogs(t)];case 1:return r.sent(),null==(n=this.getMonitorValue(t))?[2]:(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)),[2])}})})},t.prototype.onTrainEnd=function(e){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(e){return this.stoppedEpoch>0&&this.verbose&&console.log("Epoch "+this.stoppedEpoch+": early stopping."),[2]})})},t.prototype.getMonitorValue=function(e){null==e&&(e={});var t=e[this.monitor];return null==t&&console.warn("Metric for EarlyStopping "+this.monitor+" is not available. Available metrics are: "+Object.keys(e)),t},t}(Callback); + + /** + * @license + * Copyright 2019 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. + * ============================================================================= + */ + var __assign$1=function(){return (__assign$1=Object.assign||function(e){for(var t,a=1,r=arguments.length;a0&&n[n.length-1])&&(6===s[0]||2===s[0])){o=0;continue}if(3===s[0]&&(!n||s[1]>n[0]&&s[1]=this.tensors.length)throw new Error("Tried to read from index "+e+", but array size is: "+this.tensors.length);var t=this.tensors[e];if(t.cleared)throw new Error("TensorArray "+this.name+": Could not read index "+e+" twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).");return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor},e.prototype.readMany=function(e){var t=this;return e.map(function(e){return t.read(e)})},e.prototype.write=function(e,t){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error("Tried to write to index "+e+", but array is not resizeable and size is: "+this.maxSize);var a=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+e+",\n because the value dtype is "+t.dtype+", but TensorArray dtype is "+this.dtype+".");if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=t.shape),this.assertShapesMatchAllowUndefinedSize(this.elementShape,t.shape,"TensorArray "+this.name+": Could not write to TensorArray index "+e+"."),a&&a.read)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+e+", because it has already been read.");if(a&&a.written)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+e+", because it has already been written.");a.tensor=t,a.written=!0,this.tensors[e]=a;},e.prototype.writeMany=function(e,t){var a=this;if(e.length!==t.length)throw new Error("TensorArray "+this.name+": could not write multiple tensors,because the index size: "+e.length+" is not the same as tensors size: "+t.length+".");e.forEach(function(e,r){return a.write(e,t[r])});},e.prototype.gather=function(e,t){if(t&&t!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but gather requested dtype "+t);if(!e){e=[];for(var a=0;a=this.maxSize)throw new Error("Max index must be < array size ("+a+" vs. "+this.maxSize+")");this.writeMany(e,br(t,0));},e.prototype.split=function(e,t){var a=this;if(t.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+t.dtype);var r=0,n=e.map(function(e){return r+=e});if(r!==t.shape[0])throw new Error("Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n "+r+", and tensor's shape is: "+t.shape);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+e.length+"), and the TensorArray is not marked as dynamically resizeable");var s=0===r?0:t.size/r,o=[];Pe(function(){t=t.reshape([1,r,s]);for(var p=0;p1)for(var g=1;g1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();},e.prototype.nextIteration=function(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");this.contexts=this.contexts.slice(),this.lastId++;var e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts));},e.prototype.getWeight=function(e){return this.weightMap[e]},e.prototype.addTensorArray=function(e){this.tensorArrayMap[e.id]=e;},e.prototype.getTensorArray=function(e){return this.tensorArrayMap[e]},e}();function getExecutionSubgraph(e,t,a){for(var r=new Set,n=[],s=null,o=null,p=new Set,u=t.slice();u.length>0;){var i=u.pop();(isControlFlow(i)||isDynamicShape(i))&&null==s&&(o=(s=i).children.map(function(e){return e.name}).filter(function(e){return r.has(e)})),r.add(i.name),null==a[i.name]&&(null==e[i.name]&&(0!==i.inputs.length?i.inputs.forEach(function(e){p.has(e.name)||(p.add(e.name),u.push(e));}):n.push(i.name)));}return {inputs:e,outputs:t,usedNodes:r,missingInputs:n,dynamicNode:s,syncInputs:o}}function getNodesInTopologicalOrder(e,t,a){var r=a.usedNodes,n=a.inputs,s=[];Object.keys(n).map(function(t){return e.nodes[t]}).forEach(function(e){r.has(e.name)&&s.push(e);}),e.weights.forEach(function(e){r.has(e.name)&&s.push(e);});for(var o=new Set,p=[];s.length>0;){var u=s.pop();o.add(u.name),t[u.name]||p.push(u),u.children.forEach(function(e){!o.has(e.name)&&r.has(e.name)&&e.inputs.every(function(e){return o.has(e.name)})&&s.push(e);});}return p}var CONTROL_FLOW_OPS=["Switch","Merge","Enter","Exit","NextIteration"],DYNAMIC_SHAPE_OPS=["NonMaxSuppressionV2","NonMaxSuppressionV3","Where"];function isControlFlow(e){return CONTROL_FLOW_OPS.indexOf(e.op)>=0}function isDynamicShape(e){return DYNAMIC_SHAPE_OPS.indexOf(e.op)>=0}function rewritePrelu(e,t){var a=function(a){var r=e.nodes[a];if(null==r||"Add"!==r.op&&"AddV2"!==r.op||2!==r.inputNames.length)return "continue";var n=r.inputs.find(function(e){return "Relu"===e.op});if(null==n||1!==n.inputNames.length)return "continue";var s=r.inputs.find(function(e){return "Mul"===e.op});if(null==s||2!==s.inputNames.length)return "continue";var o=s.inputs.find(function(e){return "Const"===e.op}),p=s.inputs.find(function(e){return "Relu"===e.op});if(null==o||null==p||1!==p.inputNames.length)return "continue";var u=p.inputs[0];if(null==u||"Neg"!==u.op||1!==u.inputNames.length)return "continue";if(n.inputNames[0]!==u.inputNames[0])return "continue";var i=n.inputs[0],m=r.children,c=o.name+"_neg",l={name:c,inputNames:[],inputs:[],attrParams:{},category:"graph",children:[],op:"Const",inputParams:{},rawAttrs:{}};t[c]=[Rs(t[o.name][0])],e.weights.push(l);var d={name:r.name+"_Prelu",inputNames:[i.name,l.name],inputs:[i,l],attrParams:{},category:"custom",children:m,op:"Prelu",inputParams:{x:{inputIndexStart:0,type:"tensor"},alpha:{inputIndexStart:1,type:"tensor"}}};l.children.push(d);var y=o.children.indexOf(s);y>-1&&o.children.splice(y,1);var f=i.children.indexOf(n);f>-1&&i.children.splice(f,1);var h=i.children.indexOf(u);if(h>-1&&i.children.splice(h,1),i.children.push(d),m.forEach(function(e){var t=e.inputNames.indexOf(r.name);t>-1&&(e.inputNames[t]=d.name,e.inputs[t]=d);}),0===m.length){var g=e.outputs.indexOf(r);g>-1&&e.outputs.splice(g,1),e.outputs.push(d);}delete e.nodes[r.name],delete e.nodes[s.name],delete e.nodes[n.name],delete e.nodes[p.name],delete e.nodes[u.name],e.nodes[d.name]=d,e.nodes[l.name]=l;};for(var r in e.nodes)a(r);}var GraphExecutor=function(){function e(e){this.graph=e,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this.placeholders=e.placeholders,this._outputs=e.outputs;}return Object.defineProperty(e.prototype,"weightMap",{get:function(){return this._weightMap},set:function(e){var t=Object.keys(e).map(function(t){return e[t].map(function(e){return e.id})});this.weightIds=[].concat.apply([],t),this._weightMap=e;},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputs",{get:function(){return this.placeholders.map(function(e){return {name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputs",{get:function(){return this._outputs.map(function(e){return {name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputNodes",{get:function(){return this.placeholders.map(function(e){return e.name})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputNodes",{get:function(){return this.outputs.map(function(e){return e.name})},enumerable:!0,configurable:!0}),e.prototype.getCompilationKey=function(e,t){var a=e.map(function(e){return e.name}).sort(),r=t.map(function(e){return e.name}).sort();return a.join(this.SEPERATOR)+"--"+r.join(this.SEPERATOR)},e.prototype.compile=function(e,t){var a=getExecutionSubgraph(e,t,this.weightMap),r=a.missingInputs,n=a.dynamicNode,s=a.syncInputs;if(null!=n)throw new Error("This execution contains the node '"+n.name+"', which has the dynamic op '"+n.op+"'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs ["+s+"]");if(r.length>0){var o=t.map(function(e){return e.name}),p=Object.keys(e);throw new Error("Cannot compute the outputs ["+o+"] from the provided inputs ["+p+"]. Missing the following inputs: ["+r+"]")}return getNodesInTopologicalOrder(this.graph,this.weightMap,a)},e.prototype.fusePrelu=function(){rewritePrelu(this.graph,this.weightMap);},e.prototype.execute=function(e,t){var a=this,r=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),this.checkOutputs(t);var n=r.map(function(e){return a.graph.nodes[e]}),s=t.map(function(e){return a.graph.nodes[parseNodeName(e)[0]]}),o=this.getCompilationKey(n,s),p=this.compiledMap.get(o);null==p&&(p=this.compile(e,s),this.compiledMap.set(o,p));var u={};return Pe(function(){var r=new ExecutionContext(a._weightMap,u),n=__assign$1({},a.weightMap);Object.keys(e).forEach(function(t){n[t]=[e[t]];});for(var s=a.getFrozenTensorIds(n),o={},i=0;i0?(h=this.processStack(n,c,t,l,f,y,a,d,p),[4,Promise.all(h)]):[3,3];case 2:return b.sent(),[3,1];case 3:if(null==i&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead."),(g=s.filter(function(e){return !isControlFlow(e)&&!getTensor(e.name,l,t)}).map(function(e){return e.name})).length>0)throw N="",null!=i&&(N="Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs ["+m+"]"),new Error("Cannot compute the outputs ["+g+"] from the provided inputs ["+r+"]. Consider providing the following inputs: ["+u+"]. "+N);return [2,l]}})})},e.prototype.processStack=function(e,t,a,r,n,s,o,p,u){for(var i=this,m=[],c=function(){var c=t.pop();a.currentContext=c.contexts;var d="";if("Enter"===c.node.op&&getParamValue("isConstant",c.node,r,a)&&(d=getNodeNameAndIndex(c.node.name,a)[0]),-1===e.indexOf(c.node)){var y=executeOp$16(c.node,r,a);d||(d=getNodeNameAndIndex(c.node.name,a)[0]);var f=a.currentContext;y instanceof Promise?m.push(y.then(function(e){return r[d]=e,a.currentContext=f,i.checkTensorForDisposal(d,c.node,r,a,s,o,p),i.processChildNodes(c.node,t,a,r,n,u),e})):(r[d]=y,l.checkTensorForDisposal(d,c.node,r,a,s,o,p),l.processChildNodes(c.node,t,a,r,n,u));}else l.processChildNodes(c.node,t,a,r,n,u);},l=this;t.length>0;)c();return m},e.prototype.processChildNodes=function(e,t,a,r,n,s){e.children.forEach(function(e){var o=getNodeNameAndIndex(e.name,a)[0];!n[o]&&s.has(e.name)&&("Merge"===e.op?e.inputNames.some(function(e){return !!getTensor(e,r,a)})&&(n[o]=!0,t.push({contexts:a.currentContext,node:e})):e.inputNames.every(function(e){return !!getTensor(e,r,a)})&&(n[o]=!0,t.push({contexts:a.currentContext,node:e})));});},e.prototype.dispose=function(){var e=this;Object.keys(this.weightMap).forEach(function(t){return e.weightMap[t].forEach(function(e){return e.dispose()})});},e.prototype.checkInputShapeAndType=function(e){var t=this;Object.keys(e).forEach(function(a){var r=e[a],n=t.graph.nodes[a];if(n.attrParams.shape&&n.attrParams.shape.value){var s=n.attrParams.shape.value,o=s.length===r.shape.length&&r.shape.every(function(e,t){return -1===s[t]||s[t]===e});Z.assert(o,function(){return "The shape of dict['"+n.name+"'] provided in model.execute(dict) must be ["+s+"], but was ["+r.shape+"]"});}n.attrParams.dtype&&n.attrParams.dtype.value&&Z.assert(r.dtype===n.attrParams.dtype.value,function(){return "The dtype of dict['"+n.name+"'] provided in model.execute(dict) must be "+n.attrParams.dtype.value+", but was "+r.dtype});});},e.prototype.checkInputs=function(e){var t=this,a=Object.keys(e).filter(function(e){return !t.graph.nodes[e]});if(a.length>0)throw new Error("The dict provided in model.execute(dict) has keys: ["+a+"] that are not part of graph")},e.prototype.checkOutputs=function(e){var t=this;e.forEach(function(e){var a=parseNodeName(e)[0];if(!t.graph.nodes[a])throw new Error("The output '"+e+"' is not found in the graph")});},e}(),GraphModel=function(){function e(e,t){void 0===t&&(t={}),this.modelUrl=e,this.loadOptions=t,this.version="n/a",null==t&&(this.loadOptions={});}return Object.defineProperty(e.prototype,"modelVersion",{get:function(){return this.version},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputNodes",{get:function(){return this.executor.inputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputNodes",{get:function(){return this.executor.outputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputs",{get:function(){return this.executor.inputs},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputs",{get:function(){return this.executor.outputs},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"weights",{get:function(){return this.executor.weightMap},enumerable:!0,configurable:!0}),e.prototype.fusePrelu=function(){this.executor.fusePrelu(),null==getRegisteredOp("Prelu")&®isterOp("Prelu",function(e){var t=e.inputs[0],a=e.inputs[1];return kl(t,a)});},e.prototype.findIOHandler=function(){var e=this.modelUrl;if(null!=e.load)this.handler=e;else if(null!=this.loadOptions.requestInit)this.handler=Nh.browserHTTPRequest(e,this.loadOptions);else{var t=Nh.getLoadHandlers(e,this.loadOptions.onProgress);if(0===t.length)t.push(Nh.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error("Found more than one ("+t.length+") load handlers for URL '"+[e]+"'");this.handler=t[0];}},e.prototype.load=function(){return __awaiter$1(this,void 0,void 0,function(){var e,t,a;return __generator$1(this,function(r){switch(r.label){case 0:if(this.findIOHandler(),null==this.handler.load)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return [4,this.handler.load()];case 1:return e=r.sent(),t=e.modelTopology,this.version=t.versions.producer+"."+t.versions.minConsumer,a=Nh.decodeWeights(e.weightData,e.weightSpecs),this.executor=new GraphExecutor(OperationMapper.Instance.transformGraph(t)),this.executor.weightMap=this.convertTensorMapToTensorsMap(a),[2,!0]}})})},e.prototype.predict=function(e,t){return this.execute(e,this.outputNodes)},e.prototype.normalizeInputs=function(e){if(!(e instanceof ft||Array.isArray(e)))return e;if((e=Array.isArray(e)?e:[e]).length!==this.inputNodes.length)throw new Error("Input tensor count mismatch,the graph model has "+this.inputNodes.length+" placeholders, while there are "+e.length+" input tensors.");return this.inputNodes.reduce(function(t,a,r){return t[a]=e[r],t},{})},e.prototype.normalizeOutputs=function(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]},e.prototype.execute=function(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);var a=this.executor.execute(e,t);return a.length>1?a:a[0]},e.prototype.executeAsync=function(e,t){return __awaiter$1(this,void 0,void 0,function(){var a;return __generator$1(this,function(r){switch(r.label){case 0:return e=this.normalizeInputs(e),t=this.normalizeOutputs(t),[4,this.executor.executeAsync(e,t)];case 1:return [2,(a=r.sent()).length>1?a:a[0]]}})})},e.prototype.convertTensorMapToTensorsMap=function(e){return Object.keys(e).reduce(function(t,a){return t[a]=[e[a]],t},{})},e.prototype.dispose=function(){this.executor.dispose();},e}(); + + /** + * @license + * Copyright 2019 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. + * ============================================================================= + */ + var extendStatics$1=function(t,e){return (extendStatics$1=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e;}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);})(t,e)};function __extends$1(t,e){function r(){this.constructor=t;}extendStatics$1(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r);}function __awaiter$2(t,e,r,n){return new(r||(r=Promise))(function(i,o){function a(t){try{u(n.next(t));}catch(t){o(t);}}function s(t){try{u(n.throw(t));}catch(t){o(t);}}function u(t){t.done?i(t.value):new r(function(e){e(t.value);}).then(a,s);}u((n=n.apply(t,e||[])).next());})}function __generator$2(t,e){var r,n,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;a;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,n=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=(i=a.trys).length>0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]>>0,e=(n*=e)>>>0,e+=4294967296*(n-=e);}return 2.3283064365386963e-10*(e>>>0)});r.next=function(){var t=2091639*r.s0+2.3283064365386963e-10*r.c;return r.s0=r.s1,r.s1=r.s2,r.s2=t-(r.c=0|t)},r.c=1,r.s0=n(" "),r.s1=n(" "),r.s2=n(" "),r.s0-=n(t),r.s0<0&&(r.s0+=1),r.s1-=n(t),r.s1<0&&(r.s1+=1),r.s2-=n(t),r.s2<0&&(r.s2+=1),n=null;}(t),i=e&&e.state,o=r.next;return o.int32=function(){return 4294967296*r.next()|0},o.double=function(){return o()+1.1102230246251565e-16*(2097152*o()|0)},o.quick=o,i&&("object"==typeof i&&n(i,r),o.state=function(){return n(r,{})}),o}e&&e.exports?e.exports=i:r&&r.amd?r(function(){return i}):this.alea=i;}(0,t,!1);}),xor128=createCommonjsModule(function(t){!function(t,e,r){function n(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function i(t,e){var r=new function(t){var e=this,r="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8},t===(0|t)?e.x=t:r+=t;for(var n=0;n>>0)/4294967296};return o.double=function(){do{var t=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21);}while(0===t);return t},o.int32=r.next,o.quick=o,i&&("object"==typeof i&&n(i,r),o.state=function(){return n(r,{})}),o}e&&e.exports?e.exports=i:r&&r.amd?r(function(){return i}):this.xor128=i;}(0,t,!1);}),xorwow=createCommonjsModule(function(t){!function(t,e,r){function n(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e}function i(t,e){var r=new function(t){var e=this,r="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:r+=t;for(var n=0;n>>4),e.next();}(t),i=e&&e.state,o=function(){return (r.next()>>>0)/4294967296};return o.double=function(){do{var t=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21);}while(0===t);return t},o.int32=r.next,o.quick=o,i&&("object"==typeof i&&n(i,r),o.state=function(){return n(r,{})}),o}e&&e.exports?e.exports=i:r&&r.amd?r(function(){return i}):this.xorwow=i;}(0,t,!1);}),xorshift7=createCommonjsModule(function(t){!function(t,e,r){function n(t,e){return e.x=t.x.slice(),e.i=t.i,e}function i(t,e){null==t&&(t=+new Date);var r=new function(t){var e=this;e.next=function(){var t,r,n=e.x,i=e.i;return t=n[i],r=(t^=t>>>7)^t<<24,r^=(t=n[i+1&7])^t>>>10,r^=(t=n[i+3&7])^t>>>3,r^=(t=n[i+4&7])^t<<7,t=n[i+7&7],r^=(t^=t<<13)^t<<9,n[i]=r,e.i=i+1&7,r},function(t,e){var r,n=[];if(e===(0|e))n[0]=e;else for(e=""+e,r=0;r0;--r)t.next();}(e,t);}(t),i=e&&e.state,o=function(){return (r.next()>>>0)/4294967296};return o.double=function(){do{var t=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21);}while(0===t);return t},o.int32=r.next,o.quick=o,i&&(i.x&&n(i,r),o.state=function(){return n(r,{})}),o}e&&e.exports?e.exports=i:r&&r.amd?r(function(){return i}):this.xorshift7=i;}(0,t,!1);}),xor4096=createCommonjsModule(function(t){!function(t,e,r){function n(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function i(t,e){null==t&&(t=+new Date);var r=new function(t){var e=this;e.next=function(){var t,r,n=e.w,i=e.X,o=e.i;return e.w=n=n+1640531527|0,r=i[o+34&127],t=i[o=o+1&127],r^=r<<13,t^=t<<17,r^=r>>>15,t^=t>>>12,r=i[o]=r^t,e.i=o,r+(n^n>>>16)|0},function(t,e){var r,n,i,o,a,s=[],u=128;for(e===(0|e)?(n=e,e=null):(e+="\0",n=0,u=Math.max(u,e.length)),i=0,o=-32;o>>15,n^=n<<4,n^=n>>>13,o>=0&&(a=a+1640531527|0,i=0==(r=s[127&o]^=n+a)?i+1:0);for(i>=128&&(s[127&(e&&e.length||0)]=-1),i=127,o=512;o>0;--o)n=s[i+34&127],r=s[i=i+1&127],n^=n<<13,r^=r<<17,n^=n>>>15,r^=r>>>12,s[i]=n^r;t.w=a,t.X=s,t.i=i;}(e,t);}(t),i=e&&e.state,o=function(){return (r.next()>>>0)/4294967296};return o.double=function(){do{var t=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21);}while(0===t);return t},o.int32=r.next,o.quick=o,i&&(i.X&&n(i,r),o.state=function(){return n(r,{})}),o}e&&e.exports?e.exports=i:r&&r.amd?r(function(){return i}):this.xor4096=i;}(0,t,!1);}),tychei=createCommonjsModule(function(t){!function(t,e,r){function n(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function i(t,e){var r=new function(t){var e=this,r="";e.next=function(){var t=e.b,r=e.c,n=e.d,i=e.a;return t=t<<25^t>>>7^r,r=r-n|0,n=n<<24^n>>>8^i,i=i-t|0,e.b=t=t<<20^t>>>12^r,e.c=r=r-n|0,e.d=n<<16^r>>>16^i,e.a=i-t|0},e.a=0,e.b=0,e.c=-1640531527,e.d=1367130551,t===Math.floor(t)?(e.a=t/4294967296|0,e.b=0|t):r+=t;for(var n=0;n>>0)/4294967296};return o.double=function(){do{var t=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21);}while(0===t);return t},o.int32=r.next,o.quick=o,i&&("object"==typeof i&&n(i,r),o.state=function(){return n(r,{})}),o}e&&e.exports?e.exports=i:r&&r.amd?r(function(){return i}):this.tychei=i;}(0,t,!1);}),seedrandom=createCommonjsModule(function(t){!function(e,r){var n,i=this,o=256,a=6,s="random",u=r.pow(o,a),c=r.pow(2,52),l=2*c,h=o-1;function f(t,f,v){var _=[],w=p(function t(e,r){var n,i=[],o=typeof e;if(r&&"object"==o)for(n in e)try{i.push(t(e[n],r-1));}catch(t){}return i.length?i:"string"==o?e:e+"\0"}((f=1==f?{entropy:!0}:f||{}).entropy?[t,m(e)]:null==t?function(){try{var t;return n&&(t=n.randomBytes)?t=t(o):(t=new Uint8Array(o),(i.crypto||i.msCrypto).getRandomValues(t)),m(t)}catch(t){var r=i.navigator,a=r&&r.plugins;return [+new Date,i,a,i.screen,m(e)]}}():t,3),_),y=new function(t){var e,r=t.length,n=this,i=0,a=n.i=n.j=0,s=n.S=[];r||(t=[r++]);for(;i=l;)t/=2,e/=2,r>>>=1;return (t+r)/e};return g.int32=function(){return 0|y.g(4)},g.quick=function(){return y.g(4)/4294967296},g.double=g,p(m(y.S),e),(f.pass||v||function(t,e,n,i){return i&&(i.S&&d(i,y),t.state=function(){return d(y,{})}),n?(r[s]=t,e):t})(g,w,"global"in f?f.global:this==r,f.state)}function d(t,e){return e.i=t.i,e.j=t.j,e.S=t.S.slice(),e}function p(t,e){for(var r,n=t+"",i=0;i=this.items.length?[2,{value:null,done:!0}]:(t=this.items[this.trav],this.trav++,[2,{value:deepClone(t),done:!1}])})})},e}(LazyIterator),FunctionCallIterator=function(t){function e(e){var r=t.call(this)||this;return r.nextFn=e,r}return __extends$1(e,t),e.prototype.summary=function(){return "Function call"},e.prototype.next=function(){return __awaiter$2(this,void 0,void 0,function(){return __generator$2(this,function(t){try{return [2,this.nextFn()]}catch(t){throw t.message="Error thrown while iterating through a dataset: "+t.message,t}return [2]})})},e}(LazyIterator),SerialIterator=function(t){function e(e){var r=t.call(this)||this;return r.upstream=e,r.lastRead=Promise.resolve({value:null,done:!1}),r}return __extends$1(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Serial"},e.prototype.next=function(){return __awaiter$2(this,void 0,void 0,function(){var t=this;return __generator$2(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return __awaiter$2(this,void 0,void 0,function(){return __generator$2(this,function(t){return [2,this.upstream.next()]})})},e}(LazyIterator),SkipIterator=function(t){function e(e,r){var n=t.call(this)||this;return n.upstream=e,n.maxCount=r,n.count=0,n.lastRead=Promise.resolve({value:null,done:!1}),n}return __extends$1(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Skip"},e.prototype.next=function(){return __awaiter$2(this,void 0,void 0,function(){var t=this;return __generator$2(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return __awaiter$2(this,void 0,void 0,function(){var t;return __generator$2(this,function(e){switch(e.label){case 0:return this.count++ Take"},e.prototype.next=function(){return __awaiter$2(this,void 0,void 0,function(){return __generator$2(this,function(t){return this.count++>=this.maxCount?[2,{value:null,done:!0}]:[2,this.upstream.next()]})})},e}(LazyIterator),RowMajorBatchIterator=function(t){function e(e,r,n){void 0===n&&(n=!0);var i=t.call(this)||this;return i.upstream=e,i.batchSize=r,i.enableSmallLastBatch=n,i.lastRead=Promise.resolve({value:null,done:!1}),i}return __extends$1(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> RowMajorBatch"},e.prototype.next=function(){return __awaiter$2(this,void 0,void 0,function(){var t=this;return __generator$2(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return __awaiter$2(this,void 0,void 0,function(){var t,e;return __generator$2(this,function(r){switch(r.label){case 0:t=[],r.label=1;case 1:return t.length0?[2,{value:t,done:!1}]:[2,{value:null,done:!0}]:(t.push(e.value),[3,1]);case 3:return [2,{value:t,done:!1}]}})})},e}(LazyIterator),FilterIterator=function(t){function e(e,r){var n=t.call(this)||this;return n.upstream=e,n.predicate=r,n.lastRead=Promise.resolve({value:null,done:!1}),n}return __extends$1(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Filter"},e.prototype.next=function(){return __awaiter$2(this,void 0,void 0,function(){var t=this;return __generator$2(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return __awaiter$2(this,void 0,void 0,function(){var t;return __generator$2(this,function(e){switch(e.label){case 0:return [4,this.upstream.next()];case 1:return (t=e.sent()).done||this.predicate(t.value)?[2,t]:(Le(t.value),[3,0]);case 2:return [2]}})})},e}(LazyIterator),MapIterator=function(t){function e(e,r){var n=t.call(this)||this;return n.upstream=e,n.transform=r,n}return __extends$1(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Map"},e.prototype.next=function(){return __awaiter$2(this,void 0,void 0,function(){var t,e,r,n,i,o,a;return __generator$2(this,function(s){switch(s.label){case 0:return [4,this.upstream.next()];case 1:if((t=s.sent()).done)return [2,{value:null,done:!0}];for(e=kt.getTensorsInContainer(t.value),r=this.transform(t.value),n=kt.getTensorsInContainer(r),i=0,o=e;i handleErrors"},e.prototype.next=function(){return __awaiter$2(this,void 0,void 0,function(){var t=this;return __generator$2(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return __awaiter$2(this,void 0,void 0,function(){var t;return __generator$2(this,function(e){switch(e.label){case 0:e.label=1;case 1:return e.trys.push([1,3,,4]),[4,this.upstream.next()];case 2:return [2,e.sent()];case 3:return t=e.sent(),this.handler(t)?[3,4]:[2,{value:null,done:!0}];case 4:return [3,0];case 5:return [2]}})})},e}(LazyIterator),AsyncMapIterator=function(t){function e(e,r){var n=t.call(this)||this;return n.upstream=e,n.transform=r,n}return __extends$1(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> AsyncMap"},e.prototype.next=function(){return __awaiter$2(this,void 0,void 0,function(){var t,e,r,n,i,o,a;return __generator$2(this,function(s){switch(s.label){case 0:return [4,this.upstream.next()];case 1:return (t=s.sent()).done?[2,{value:null,done:!0}]:(e=kt.getTensorsInContainer(t.value),[4,this.transform(t.value)]);case 2:for(r=s.sent(),n=kt.getTensorsInContainer(r),i=0,o=e;i Flatmap"},e.prototype.pump=function(){return __awaiter$2(this,void 0,void 0,function(){var t,e,r,n,i,o,a;return __generator$2(this,function(s){switch(s.label){case 0:return [4,this.upstream.next()];case 1:if((t=s.sent()).done)return [2,!1];for(e=kt.getTensorsInContainer(t.value),r=this.transform(t.value),n=kt.getTensorsInContainer(r),this.outputQueue.pushAll(r),i=0,o=e;i Chained"},e.prototype.next=function(){return __awaiter$2(this,void 0,void 0,function(){return __generator$2(this,function(t){return this.lastRead=this.readFromChain(this.lastRead),[2,this.lastRead]})})},e.prototype.readFromChain=function(t){return __awaiter$2(this,void 0,void 0,function(){var e,r;return __generator$2(this,function(n){switch(n.label){case 0:return [4,t];case 1:return n.sent(),null!=this.iterator?[3,3]:[4,this.moreIterators.next()];case 2:if((e=n.sent()).done)return [2,{value:null,done:!0}];this.iterator=e.value,null!=this.baseErrorHandler&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler)),n.label=3;case 3:return [4,this.iterator.next()];case 4:return (r=n.sent()).done?(this.iterator=null,[2,this.readFromChain(t)]):[2,r]}})})},e}(LazyIterator);!function(t){t[t.FAIL=0]="FAIL",t[t.SHORTEST=1]="SHORTEST",t[t.LONGEST=2]="LONGEST";}(ZipMismatchMode||(ZipMismatchMode={}));var ZipIterator=function(t){function e(e,r){void 0===r&&(r=ZipMismatchMode.FAIL);var n=t.call(this)||this;return n.iterators=e,n.mismatchMode=r,n.count=0,n.currentPromise=null,n}return __extends$1(e,t),e.prototype.summary=function(){return "{TODO: fill in upstream of zip summaries} -> Zip"},e.prototype.nextState=function(t){return __awaiter$2(this,void 0,void 0,function(){function e(t){return t instanceof LazyIterator?{value:t.next().then(function(t){return r++,t.done&&n++,t.value}),recurse:!1}:{value:null,recurse:!0}}var r,n,i;return __generator$2(this,function(o){switch(o.label){case 0:return [4,t];case 1:return o.sent(),r=0,n=0,[4,deepMapAndAwaitAll(this.iterators,e)];case 2:if(i=o.sent(),r===n)return [2,{value:null,done:!0}];if(n>0)switch(this.mismatchMode){case ZipMismatchMode.FAIL:throw new Error("Zipped streams should have the same length. Mismatched at element "+this.count+".");case ZipMismatchMode.SHORTEST:return [2,{value:null,done:!0}];case ZipMismatchMode.LONGEST:}return this.count++,[2,{value:i,done:!1}]}})})},e.prototype.next=function(){return __awaiter$2(this,void 0,void 0,function(){return __generator$2(this,function(t){switch(t.label){case 0:return this.currentPromise=this.nextState(this.currentPromise),[4,this.currentPromise];case 1:return [2,t.sent()]}})})},e}(LazyIterator),PrefetchIterator=function(t){function e(e,r){var n=t.call(this)||this;return n.upstream=e,n.bufferSize=r,n.buffer=new RingBuffer(r),n}return __extends$1(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Prefetch"},e.prototype.refill=function(){for(;!this.buffer.isFull();){var t=this.upstream.next();this.buffer.push(t);}},e.prototype.next=function(){return this.refill(),this.buffer.shift()},e}(LazyIterator),ShuffleIterator=function(t){function e(e,r,n){var i=t.call(this,e,r)||this;return i.upstream=e,i.windowSize=r,i.upstreamExhausted=!1,i.random=seedrandom_1(n||Z.now().toString()),i.lastRead=Promise.resolve({value:null,done:!1}),i}return __extends$1(e,t),e.prototype.next=function(){return __awaiter$2(this,void 0,void 0,function(){var t=this;return __generator$2(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.randomInt=function(t){return Math.floor(this.random()*t)},e.prototype.chooseIndex=function(){return this.randomInt(this.buffer.length())},e.prototype.serialNext=function(){return __awaiter$2(this,void 0,void 0,function(){var t,e;return __generator$2(this,function(r){switch(r.label){case 0:this.upstreamExhausted||this.refill(),r.label=1;case 1:return this.buffer.isEmpty()?[3,3]:(t=this.chooseIndex(),[4,this.buffer.shuffleExcise(t)]);case 2:return (e=r.sent()).done?(this.upstreamExhausted=!0,[3,1]):(this.refill(),[2,e]);case 3:return [2,{value:null,done:!0}]}})})},e}(PrefetchIterator),Dataset=function(){function t(){this.size=null;}return t.prototype.batch=function(t,e){var r=this;void 0===e&&(e=!0);var n=this;return Z.assert(t>0,function(){return "batchSize needs to be positive, but it is\n "+t}),datasetFromIteratorFn(function(){return __awaiter$2(r,void 0,void 0,function(){return __generator$2(this,function(r){switch(r.label){case 0:return [4,n.iterator()];case 1:return [2,r.sent().columnMajorBatch(t,e,deepBatchConcat)]}})})},this.size===1/0||null==this.size?this.size:e?Math.ceil(this.size/t):Math.floor(this.size/t))},t.prototype.concatenate=function(t){var e=this,r=this;return datasetFromIteratorFn(function(){return __awaiter$2(e,void 0,void 0,function(){var e,n;return __generator$2(this,function(i){switch(i.label){case 0:return [4,r.iterator()];case 1:return n=(e=i.sent()).concatenate,[4,t.iterator()];case 2:return [2,n.apply(e,[i.sent()])]}})})},this.size===1/0||t.size===1/0?1/0:null!=this.size&&null!=t.size?this.size+t.size:null)},t.prototype.filter=function(t){var e=this,r=this;return datasetFromIteratorFn(function(){return __awaiter$2(e,void 0,void 0,function(){return __generator$2(this,function(e){switch(e.label){case 0:return [4,r.iterator()];case 1:return [2,e.sent().filter(function(e){return Pe(function(){return t(e)})})]}})})},this.size===1/0?1/0:null)},t.prototype.forEachAsync=function(t){return __awaiter$2(this,void 0,void 0,function(){return __generator$2(this,function(e){switch(e.label){case 0:return [4,this.iterator()];case 1:return [2,e.sent().forEachAsync(t)]}})})},t.prototype.forEach=function(t){return __awaiter$2(this,void 0,void 0,function(){return __generator$2(this,function(e){return Oe("dataset.forEach() is deprecated and will be removed. Please use dataset.forEachAsync() instead"),[2,this.forEachAsync(t)]})})},t.prototype.map=function(t){var e=this,r=this;return datasetFromIteratorFn(function(){return __awaiter$2(e,void 0,void 0,function(){return __generator$2(this,function(e){switch(e.label){case 0:return [4,r.iterator()];case 1:return [2,e.sent().map(function(e){return Pe(function(){return t(e)})})]}})})},this.size)},t.prototype.mapAsync=function(t){var e=this,r=this;return datasetFromIteratorFn(function(){return __awaiter$2(e,void 0,void 0,function(){return __generator$2(this,function(e){switch(e.label){case 0:return [4,r.iterator()];case 1:return [2,e.sent().mapAsync(t)]}})})},this.size)},t.prototype.prefetch=function(t){var e=this;if(null==t)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");var r=this;return datasetFromIteratorFn(function(){return __awaiter$2(e,void 0,void 0,function(){return __generator$2(this,function(e){switch(e.label){case 0:return [4,r.iterator()];case 1:return [2,e.sent().prefetch(t)]}})})},this.size)},t.prototype.repeat=function(t){var e=this,r=this;return datasetFromIteratorFn(function(){return __awaiter$2(e,void 0,void 0,function(){var e=this;return __generator$2(this,function(n){return [2,iteratorFromConcatenated(iteratorFromFunction(function(){return __awaiter$2(e,void 0,void 0,function(){var t;return __generator$2(this,function(e){switch(e.label){case 0:return t={},[4,r.iterator()];case 1:return [2,(t.value=e.sent(),t.done=!1,t)]}})})}).take(t))]})})},null!=this.size&&t>0?this.size*t:0===t?0:null!=this.size&&(void 0===t||t<0)?1/0:null)},t.prototype.skip=function(t){var e=this,r=this;return datasetFromIteratorFn(function(){return __awaiter$2(e,void 0,void 0,function(){return __generator$2(this,function(e){switch(e.label){case 0:return [4,r.iterator()];case 1:return [2,e.sent().skip(t)]}})})},null!=this.size&&t>=0&&this.size>=t?this.size-t:null!=this.size&&(this.sizet?t:null!=this.size&&this.size<=t?this.size:null)},t.prototype.toArray=function(){return __awaiter$2(this,void 0,void 0,function(){return __generator$2(this,function(t){switch(t.label){case 0:if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return [4,this.iterator()];case 1:return [2,t.sent().toArray()]}})})},t.prototype.toArrayForTest=function(){return __awaiter$2(this,void 0,void 0,function(){return __generator$2(this,function(t){switch(t.label){case 0:if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return [4,this.iterator()];case 1:return [2,t.sent().toArrayForTest()]}})})},t.MAX_BUFFER_SIZE=1e4,t}();function datasetFromIteratorFn(t,e){return void 0===e&&(e=null),new(function(r){function n(){var t=null!==r&&r.apply(this,arguments)||this;return t.size=e,t}return __extends$1(n,r),n.prototype.iterator=function(){return __awaiter$2(this,void 0,void 0,function(){return __generator$2(this,function(e){return [2,t()]})})},n}(Dataset))}function deepBatchConcat(t){return null===t?null:canTensorify(t[0])?{value:batchConcat(t),recurse:!1}:{value:null,recurse:!0}}function batchConcat(t){if(0===t.length)throw new Error("Can't make a batch of zero elements.");return t[0]instanceof ft?gr(t):mn(t)}var TextLineDataset=function(t){function e(e){var r=t.call(this)||this;return r.input=e,r}return __extends$1(e,t),e.prototype.iterator=function(){return __awaiter$2(this,void 0,void 0,function(){var t,e;return __generator$2(this,function(r){switch(r.label){case 0:return [4,this.input.iterator()];case 1:return t=r.sent(),e=t.decodeUTF8(),[2,e.split("\n").map(function(t){return t.endsWith("\r")&&(t=t.slice(0,-1)),t})]}})})},e}(Dataset),CODE_QUOTE='"',STATE_OUT=Symbol("out"),STATE_FIELD=Symbol("field"),STATE_QUOTE=Symbol("quote"),STATE_QUOTE_AFTER_QUOTE=Symbol("quoteafterquote"),STATE_WITHIN_QUOTE_IN_QUOTE=Symbol("quoteinquote"),CSVDataset=function(t){function e(e,r){var n=t.call(this)||this;return n.input=e,n.hasHeader=!0,n.fullColumnNames=null,n.columnNamesValidated=!1,n.columnConfigs=null,n.configuredColumnsOnly=!1,n.delimiter=",",n.delimWhitespace=!1,n.base=new TextLineDataset(e),r||(r={}),n.hasHeader=!1!==r.hasHeader,n.fullColumnNames=r.columnNames,n.columnConfigs=r.columnConfigs,n.configuredColumnsOnly=r.configuredColumnsOnly,r.delimWhitespace?(Z.assert(null==r.delimiter,function(){return "Delimiter should not be provided when delimWhitespace is true."}),n.delimWhitespace=!0,n.delimiter=" "):n.delimiter=r.delimiter?r.delimiter:",",n}return __extends$1(e,t),e.prototype.columnNames=function(){return __awaiter$2(this,void 0,void 0,function(){return __generator$2(this,function(t){switch(t.label){case 0:return this.columnNamesValidated?[3,2]:[4,this.setColumnNames()];case 1:t.sent(),t.label=2;case 2:return [2,this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames]}})})},e.prototype.setColumnNames=function(){return __awaiter$2(this,void 0,void 0,function(){var t,e,r,n,i,o,a=this;return __generator$2(this,function(s){switch(s.label){case 0:return [4,this.maybeReadHeaderLine()];case 1:if(t=s.sent(),!this.fullColumnNames&&!t)throw new Error("Column names must be provided if there is no header line.");if(this.fullColumnNames&&t&&Z.assert(t.length===this.fullColumnNames.length,function(){return "The length of provided columnNames ("+a.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+t.length.toString()+")."}),this.fullColumnNames||(this.fullColumnNames=t),e=this.fullColumnNames.reduce(function(t,e){return t[e]=t[e]+1||1,t},{}),r=Object.keys(e).filter(function(t){return e[t]>1}),Z.assert(0===r.length,function(){return "Duplicate column names found: "+r.toString()}),this.columnConfigs)for(n=0,i=Object.keys(this.columnConfigs);n14||!Number.isInteger(n))throw new Error("Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got "+r.fftSize);if(r.numFrames=e.numFramesPerSpectrogram||43,r.sampleRateHz=e.sampleRateHz,r.columnTruncateLength=e.columnTruncateLength||r.fftSize,r.audioTrackConstraints=e.audioTrackConstraints,r.smoothingTimeConstant=e.smoothingTimeConstant||0,r.includeSpectrogram=!1!==e.includeSpectrogram,r.includeWaveform=!0===e.includeWaveform,!r.includeSpectrogram&&!r.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.");return r}return __extends$1(e,t),e.prototype.summary=function(){return "microphone"},e.create=function(t){return void 0===t&&(t={}),__awaiter$2(this,void 0,void 0,function(){var r;return __generator$2(this,function(n){switch(n.label){case 0:if(s.get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");return [4,(r=new e(t)).start()];case 1:return n.sent(),[2,r]}})})},e.prototype.start=function(){return __awaiter$2(this,void 0,void 0,function(){var t,e,r,n;return __generator$2(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),t=this,[4,navigator.mediaDevices.getUserMedia({audio:null==this.audioTrackConstraints||this.audioTrackConstraints,video:!1})];case 1:return t.stream=i.sent(),[3,3];case 2:throw e=i.sent(),new Error("Error thrown while initializing video stream: "+e.message);case 3:if(!this.stream)throw new Error("Could not obtain audio from microphone.");if(r=window.AudioContext||window.webkitAudioContext,this.audioContext=new r,this.sampleRateHz){if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error("Mismatch in sampling rate: Expected: "+this.sampleRateHz+"; Actual: "+this.audioContext.sampleRate)}else this.sampleRateHz=this.audioContext.sampleRate;return n=this.audioContext.createMediaStreamSource(this.stream),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2*this.fftSize,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,n.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize),[2]}})})},e.prototype.next=function(){return __awaiter$2(this,void 0,void 0,function(){var t,e,r,n,i;return __generator$2(this,function(o){switch(o.label){case 0:return this.isClosed?[2,{value:null,done:!0}]:[4,this.getAudioData()];case 1:return r=o.sent(),this.includeSpectrogram&&(n=this.flattenQueue(r.freqDataQueue),t=this.getTensorFromAudioDataArray(n,[this.numFrames,this.columnTruncateLength,1])),this.includeWaveform&&(i=this.flattenQueue(r.timeDataQueue),e=this.getTensorFromAudioDataArray(i,[this.numFrames*this.fftSize,1])),[2,{value:{spectrogram:t,waveform:e},done:!1}]}})})},e.prototype.capture=function(){return __awaiter$2(this,void 0,void 0,function(){return __generator$2(this,function(t){switch(t.label){case 0:return [4,this.next()];case 1:return [2,t.sent().value]}})})},e.prototype.getAudioData=function(){return __awaiter$2(this,void 0,void 0,function(){var t,e,r,n=this;return __generator$2(this,function(i){return t=[],e=[],r=0,[2,new Promise(function(i){var o=setInterval(function(){n.includeSpectrogram&&(n.analyser.getFloatFrequencyData(n.freqData),n.freqData[0]===-1/0&&i({freqDataQueue:t,timeDataQueue:e}),t.push(n.freqData.slice(0,n.columnTruncateLength))),n.includeWaveform&&(n.analyser.getFloatTimeDomainData(n.timeData),e.push(n.timeData.slice())),++r===n.numFrames&&(clearInterval(o),i({freqDataQueue:t,timeDataQueue:e}));},n.fftSize/n.sampleRateHz*1e3);})]})})},e.prototype.stop=function(){this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),null!=this.stream&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop();},e.prototype.toArray=function(){throw new Error("Can not convert infinite audio stream to array.")},e.prototype.getSampleRate=function(){return this.sampleRateHz},e.prototype.flattenQueue=function(t){var e=t[0].length,r=new Float32Array(t.length*e);return t.forEach(function(t,n){return r.set(t,n*e)}),r},e.prototype.getTensorFromAudioDataArray=function(t,e){var r=new Float32Array(Z.sizeFromShape(e));return r.set(t,r.length-t.length),mn(r,e)},e}(LazyIterator),WebcamIterator=function(t){function e(e,r){var n=t.call(this)||this;if(n.webcamVideoElement=e,n.webcamConfig=r,n.isClosed=!0,n.resize=!1,n.needToResize())if(n.resize=!0,n.cropSize=[n.webcamConfig.resizeHeight,n.webcamConfig.resizeWidth],n.cropBoxInd=xn([0],"int32"),n.webcamConfig.centerCrop){var i=1*n.webcamConfig.resizeWidth/n.webcamVideoElement.width,o=1*n.webcamConfig.resizeHeight/n.webcamVideoElement.height,a=(1-i)/2,s=(1-o)/2,u=a+i,c=o+s;n.cropBox=bn([s,a,c,u],[1,4]);}else n.cropBox=bn([0,0,1,1],[1,4]);return n}return __extends$1(e,t),e.prototype.summary=function(){return "webcam"},e.create=function(t,r){return void 0===r&&(r={}),__awaiter$2(this,void 0,void 0,function(){var n;return __generator$2(this,function(i){switch(i.label){case 0:if(s.get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!t){if(t=document.createElement("video"),!r.resizeWidth||!r.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");t.width=r.resizeWidth,t.height=r.resizeHeight;}return [4,(n=new e(t,r)).start()];case 1:return i.sent(),[2,n]}})})},e.prototype.start=function(){return __awaiter$2(this,void 0,void 0,function(){var t,e,r=this;return __generator$2(this,function(n){switch(n.label){case 0:this.webcamConfig.facingMode&&Z.assert("user"===this.webcamConfig.facingMode||"environment"===this.webcamConfig.facingMode,function(){return "Invalid webcam facing mode: "+r.webcamConfig.facingMode+". Please provide 'user' or 'environment'"}),n.label=1;case 1:return n.trys.push([1,3,,4]),t=this,[4,navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})];case 2:return t.stream=n.sent(),[3,4];case 3:throw(e=n.sent()).message="Error thrown while initializing video stream: "+e.message,e;case 4:if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream;}catch(t){console.log(t),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream);}return this.webcamVideoElement.play(),this.isClosed=!1,[2,new Promise(function(t){r.webcamVideoElement.onloadedmetadata=function(){t();};})]}})})},e.prototype.next=function(){return __awaiter$2(this,void 0,void 0,function(){var t;return __generator$2(this,function(e){if(this.isClosed)return [2,{value:null,done:!0}];try{t=Dh.fromPixels(this.webcamVideoElement);}catch(t){throw new Error("Error thrown converting video to pixels: "+JSON.stringify(t))}if(!this.resize)return [2,{value:t,done:!1}];try{return [2,{value:this.cropAndResizeFrame(t),done:!1}]}catch(t){throw new Error("Error thrown cropping the video: "+t.message)}finally{t.dispose();}return [2]})})},e.prototype.needToResize=function(){return !(!this.webcamConfig.resizeWidth||!this.webcamConfig.resizeHeight||this.webcamVideoElement.width===this.webcamConfig.resizeWidth&&this.webcamVideoElement.height===this.webcamConfig.resizeHeight)},e.prototype.cropAndResizeFrame=function(t){var e=this;return Pe(function(){var r,n=t.toFloat().expandDims(0),i=(r=Rc.cropAndResize(n,e.cropBox,e.cropBoxInd,e.cropSize,"bilinear")).shape;return r.reshape(i.slice(1))})},e.prototype.capture=function(){return __awaiter$2(this,void 0,void 0,function(){return __generator$2(this,function(t){switch(t.label){case 0:return [4,this.next()];case 1:return [2,t.sent().value]}})})},e.prototype.stop=function(){this.stream.getTracks().forEach(function(t){return t.stop()});try{this.webcamVideoElement.srcObject=null;}catch(t){console.log(t),this.webcamVideoElement.src=null;}this.isClosed=!0;},e.prototype.toArray=function(){throw new Error("Can not convert infinite video stream to array.")},e}(LazyIterator),DataSource=function(){return function(){}}(),StringIterator=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return __extends$1(e,t),e.prototype.split=function(t){return new SplitIterator(this,t)},e}(LazyIterator),SplitIterator=function(t){function e(e,r){var n=t.call(this)||this;return n.upstream=e,n.impl=new SplitIteratorImpl(e,r),n}return __extends$1(e,t),e.prototype.summary=function(){return this.impl.summary()},e.prototype.next=function(){return __awaiter$2(this,void 0,void 0,function(){return __generator$2(this,function(t){return [2,this.impl.next()]})})},e}(StringIterator),SplitIteratorImpl=function(t){function e(e,r){var n=t.call(this)||this;return n.upstream=e,n.separator=r,n.carryover="",n}return __extends$1(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Split('"+this.separator+"')"},e.prototype.pump=function(){return __awaiter$2(this,void 0,void 0,function(){var t,e,r,n,i;return __generator$2(this,function(o){switch(o.label){case 0:return [4,this.upstream.next()];case 1:if((t=o.sent()).done)return ""===this.carryover?[2,!1]:(this.outputQueue.push(this.carryover),this.carryover="",[2,!0]);for((e=t.value.split(this.separator))[0]=this.carryover+e[0],r=0,n=e.slice(0,-1);r Utf8"},e.prototype.pump=function(){return __awaiter$2(this,void 0,void 0,function(){var t,e,r;return __generator$2(this,function(n){switch(n.label){case 0:return [4,this.upstream.next()];case 1:return (t=n.sent()).done?[2,!1]:(e=t.value,r=s.get("IS_BROWSER")?this.decoder.decode(e,{stream:!0}):this.decoder.write(Buffer.from(e.buffer)),this.outputQueue.push(r),[2,!0])}})})},e}(OneToManyIterator),FileChunkIterator=function(t){function e(e,r){void 0===r&&(r={});var n=t.call(this)||this;return n.file=e,n.options=r,Z.assert(e instanceof Uint8Array||!!s.get("IS_BROWSER")&&(e instanceof File||e instanceof Blob),function(){return "FileChunkIterator only supports File, Blob and Uint8Array right now."}),n.offset=r.offset||0,n.chunkSize=r.chunkSize||1048576,n}return __extends$1(e,t),e.prototype.summary=function(){return "FileChunks "+this.file},e.prototype.next=function(){return __awaiter$2(this,void 0,void 0,function(){var t,e,r=this;return __generator$2(this,function(n){switch(n.label){case 0:return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?[2,{value:null,done:!0}]:(t=new Promise(function(t,e){var n=r.offset+r.chunkSize;if(r.file instanceof Uint8Array)t(new Uint8Array(r.file.slice(r.offset,n)));else{var i=new FileReader;i.onload=function(r){var n=i.result;if(n instanceof ArrayBuffer&&(n=new Uint8Array(n)),!(n instanceof Uint8Array))return e(new TypeError("FileReader returned unknown type."));t(n);},i.onabort=function(t){return e(new Error("Aborted"))},i.onerror=function(t){return e(new Error(t.type))};var o=r.file.slice(r.offset,n);i.readAsArrayBuffer(o);}r.offset=n;}),e={},[4,t]);case 1:return [2,(e.value=n.sent(),e.done=!1,e)]}})})},e}(ByteChunkIterator);function urlChunkIterator(t,e){return void 0===e&&(e={}),__awaiter$2(this,void 0,void 0,function(){var r,n,i,o,a;return __generator$2(this,function(s){switch(s.label){case 0:return "string"==typeof t?r=t:(r=t.url,n=getRequestInitFromRequest(t)),[4,Z.fetch(r,n)];case 1:return (i=s.sent()).ok?(a=Uint8Array.bind,[4,i.arrayBuffer()]):[3,3];case 2:return o=new(a.apply(Uint8Array,[void 0,s.sent()])),[2,new FileChunkIterator(o,e)];case 3:throw new Error(i.statusText)}})})}var getRequestInitFromRequest=function(t){return {method:t.method,headers:t.headers,body:t.body,mode:t.mode,credentials:t.credentials,cache:t.cache,redirect:t.redirect,referrer:t.referrer,integrity:t.integrity}};function isLocalPath(t){return "string"==typeof t&&"file://"===t.substr(0,7)}var FileDataSource=function(t){function e(e,r){void 0===r&&(r={});var n=t.call(this)||this;return n.input=e,n.options=r,n}return __extends$1(e,t),e.prototype.iterator=function(){return __awaiter$2(this,void 0,void 0,function(){var t;return __generator$2(this,function(e){return isLocalPath(this.input)&&s.get("IS_NODE")&&(t=require("fs"),this.input=t.readFileSync(this.input.substr(7))),[2,new FileChunkIterator(this.input,this.options)]})})},e}(DataSource),URLDataSource=function(t){function e(e,r){void 0===r&&(r={});var n=t.call(this)||this;return n.url=e,n.fileOptions=r,n}return __extends$1(e,t),e.prototype.iterator=function(){return __awaiter$2(this,void 0,void 0,function(){return __generator$2(this,function(t){return isLocalPath(this.url)?[2,new FileDataSource(this.url,this.fileOptions).iterator()]:[2,urlChunkIterator(this.url,this.fileOptions)]})})},e}(DataSource); + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + + var ensure = function ensure(context, object, keys) { + [].concat(keys).forEach(function (key) { + if (typeof object[key] === 'undefined') { + throw new Error('AutoSuggest: Missing required parameter, ' + context + '.' + key); + } + }); + }; + var ensureType = function ensureType(context, object, key, type) { + [].concat(object[key]).forEach(function (value) { + if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== type) { + throw new TypeError('AutoSuggest: Invalid Type for ' + context + '.' + key + ', expected ' + type); + } + }); + }; + + var cloneStyle = function cloneStyle(element1, element2) { + var allStyles = window.getComputedStyle(element1); + for (var style in allStyles) { + if (allStyles.hasOwnProperty(style)) { + element2.style.setProperty(style, allStyles[style]); + } + } + }; + + var getComputedStyle = function getComputedStyle(element, style) { + return window.getComputedStyle(element).getPropertyValue(style); + }; + + var getGlobalOffset = function getGlobalOffset($0) { + var node = $0, + top = 0, + left = 0; + + do { + left += node.offsetLeft; + top += node.offsetTop; + } while (node = node.offsetParent); + + return { left: left, top: top }; + }; + + var getScrollLeftForInput = function getScrollLeftForInput(input) { + if (input.createTextRange) { + var range = input.createTextRange(); + var inputStyle = window.getComputedStyle(input); + var paddingLeft = parseFloat(inputStyle.paddingLeft); + var rangeRect = range.getBoundingClientRect(); + return input.getBoundingClientRect().left + input.clientLeft + paddingLeft - rangeRect.left; + } else { + return input.scrollLeft; + } + }; + + var getCursorPosition = function getCursorPosition(input) { + return [input.selectionStart, input.selectionEnd].sort(function (a, b) { + return a - b; + }); + }; + + var getSelectedTextNodes = function getSelectedTextNodes() { + var range = window.getSelection().getRangeAt(0); + + var startContainer = range.startContainer, + startOffset = range.startOffset; + + if (startContainer.nodeType !== startContainer.TEXT_NODE) { + startContainer = startContainer.childNodes[startOffset]; + while (startContainer && startContainer.nodeType !== startContainer.TEXT_NODE) { + startContainer = startContainer.firstChild; + } + startOffset = 0; + } + + var endContainer = range.endContainer, + endOffset = range.endOffset; + + if (endContainer.nodeType !== endContainer.TEXT_NODE) { + endContainer = endContainer.childNodes[endOffset]; + while (endContainer && endContainer.nodeType !== endContainer.TEXT_NODE) { + endContainer = endContainer.lastChild; + } + endOffset = endContainer ? endContainer.nodeValue.length : endContainer; + } + + return { startContainer: startContainer, startOffset: startOffset, endContainer: endContainer, endOffset: endOffset }; + }; + + var makeAsyncQueueRunner = function makeAsyncQueueRunner() { + var i = 0; + var queue = []; + + return function (f, j) { + queue[j - i] = f; + while (queue[0]) { + ++i, queue.shift()(); + } + }; + }; + + var data = function data(element, key, value) { + key = 'autosuggest_' + key; + if (typeof value !== 'undefined') { + element.dataset[key] = JSON.stringify(value); + } else { + value = element.dataset[key]; + return typeof value !== 'undefined' ? JSON.parse(element.dataset[key]) : value; + } + }; + + var createNode = function createNode(html) { + var div = document.createElement('div'); + div.innerHTML = html.trim(); + return div.firstChild; + }; + + var _typeof$1 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + + function validateSuggestions(suggestions) { + return [].concat(suggestions).map(function (suggestion) { + var type = typeof suggestion === 'undefined' ? 'undefined' : _typeof$1(suggestion); + if (type === 'string') { + suggestion = { + on: [suggestion], + show: suggestion, + use: suggestion, + focus: [0, 0] + }; + } else if (type === 'object') { + try { + ensure('Suggestion', suggestion, 'value'); + ensureType('Suggestion', suggestion, 'value', 'string'); + } catch (e1) { + if (e1 instanceof TypeError) throw e1; + + try { + ensure('Suggestion', suggestion, ['on', 'show', 'use']); + } catch (e2) { + if (suggestion.on || suggestion.show || suggestion.use) { + throw e2; + } else { + throw e1; + } + } + + ensureType('Suggestion', suggestion, 'on', 'string'); + ensureType('Suggestion', suggestion, 'use', 'string'); + ensureType('Suggestion', suggestion, 'show', 'string'); + } + + suggestion.show = suggestion.show || suggestion.value; + suggestion.use = suggestion.use || suggestion.value; + suggestion.on = [suggestion.show].concat(suggestion.on || suggestion.value); + + suggestion.focus = suggestion.focus || [0, 0]; + if (suggestion.focus.constructor !== Array) { + suggestion.focus = [suggestion.focus, suggestion.focus]; + } + } + + return suggestion; + }); + } + + function SuggestionList(options) { + // validate options + if (options && !options.values) { + options = { + values: options + }; + } + + try { + ensure('SuggestionList', options, 'trigger'); + ensureType('Suggestion', options, 'trigger', 'string'); + } catch (e) { + if (e instanceof TypeError) throw e; + } + + ensure('SuggestionList', options, 'values'); + options.caseSensitive = Boolean(options.caseSensitive); + + if (typeof options.values === 'function') { + this.getSuggestions = function (keyword, callback) { + options.values(keyword, function (values) { + return callback(validateSuggestions(values)); + }); + }; + } else if (options.values.constructor === Array || typeof options.values === 'string') { + options.values = validateSuggestions(options.values); + this.getSuggestions = function (keyword, callback) { + var matcher = new RegExp('^' + keyword, !options.caseSensitive ? 'i' : ''); + callback(options.values.filter(function (value) { + var matchFound = false; + for (var i = 0; i < value.on.length; i++) { + if (value.on[i] !== keyword && (matchFound = matcher.test(value.on[i]))) { + break; + } + } + + return matchFound; + })); + }; + } + + this.trigger = options.trigger; + if (this.trigger) { + var escapedTrigger = '\\' + this.trigger.split('').join('\\'); + this.regex = new RegExp('(?:^|[^' + escapedTrigger + ']+?)' + escapedTrigger + '(\\S*)$'); + } else { + this.regex = new RegExp('(?:^|\\W+)(\\w+)$'); + } + } + + SuggestionList.prototype.getMatch = function (value) { + return value.match(this.regex)[1]; + }; + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var SuggestionDropdown = function () { + function SuggestionDropdown() { + _classCallCheck(this, SuggestionDropdown); + + this.width = 0; + this.isEmpty = true; + this.isActive = false; + + this.dropdownContent = document.createElement('ul'); + this.dropdownContent.className = 'dropdown-menu dropdown-menu-left'; + + this.dropdown = document.createElement('div'); + this.dropdown.className = 'dropdown open'; + this.dropdown.style.position = 'absolute'; + + this.hide(); + this.dropdown.appendChild(this.dropdownContent); + document.body.appendChild(this.dropdown); + } + + _createClass(SuggestionDropdown, [{ + key: 'show', + value: function show(position) { + if (position) { + this.dropdown.style.left = position.left + 'px'; + this.dropdown.style.top = position.top + 'px'; + + if (position.left + this.width > document.body.offsetWidth) { + this.dropdownContent.classList.remove('dropdown-menu-left'); + this.dropdownContent.classList.add('dropdown-menu-right'); + } else { + this.dropdownContent.classList.remove('dropdown-menu-right'); + this.dropdownContent.classList.add('dropdown-menu-left'); + } + } + + this.dropdown.style.display = 'block'; + this.isActive = true; + } + }, { + key: 'hide', + value: function hide() { + this.dropdown.style.display = 'none'; + this.isActive = false; + } + }, { + key: 'empty', + value: function empty() { + this.dropdownContent.innerHTML = ''; + this.isEmpty = true; + } + }, { + key: 'fill', + value: function fill(suggestions, onSet) { + var _this = this; + + this.empty(); + suggestions.forEach(function (suggestion) { + var dropdownLink = createNode('
  • ' + suggestion.show + '
  • '); + _this.dropdownContent.append(dropdownLink); + data(dropdownLink, 'suggestion', suggestion); + + dropdownLink.addEventListener('mouseenter', function () { + _this.getActive().classList.remove('active'); + dropdownLink.classList.add('active'); + }); + + dropdownLink.addEventListener('mousedown', function (e) { + onSet(suggestion); + _this.hide(); + e.preventDefault(); + e.stopPropagation(); + }); + }); + + // Calculate width + if (!this.isActive) { + this.show(); + } + + this.width = this.dropdownContent.offsetWidth; + + if (!this.isActive) { + this.hide(); + } + + this.setActive(); + this.isEmpty = false; + } + }, { + key: 'showLoader', + value: function showLoader(position) { + this.empty(); + this.dropdownContent.innerHTML = '
    Loading...
    '; + this.show(position); + } + }, { + key: 'getActive', + value: function getActive() { + var activeLinks = Array.prototype.slice.call(this.dropdownContent.querySelectorAll('li.active'), 0); + while (activeLinks[1]) { + activeLinks.pop().classList.remove('active'); + } + + return activeLinks[0]; + } + }, { + key: 'getValue', + value: function getValue(element) { + return data(element || this.getActive(), 'suggestion'); + } + }, { + key: 'setActive', + value: function setActive() { + var element = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.dropdownContent.firstElementChild; + var activeLink = arguments[1]; + + activeLink && activeLink.classList.remove('active'); + element.classList.add('active'); + } + }, { + key: 'selectNext', + value: function selectNext() { + var activeLink = this.getActive(); + var nextLink = activeLink.nextElementSibling || this.dropdownContent.firstElementChild; + this.setActive(nextLink, activeLink); + } + }, { + key: 'selectPrev', + value: function selectPrev() { + var activeLink = this.getActive(); + var prevLink = activeLink.previousElementSibling || this.dropdownContent.lastElementChild; + this.setActive(prevLink, activeLink); + } + }]); + + return SuggestionDropdown; + }(); + + var _createClass$1 = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); + + function _classCallCheck$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + function splitValue(originalValue, cursorPosition, trigger) { + var value = originalValue.slice(0, cursorPosition); + var textAfterTrigger = value.split(trigger || /\W/).pop(); + var textUptoTrigger = textAfterTrigger.length ? value.slice(0, 0 - textAfterTrigger.length) : value; + textAfterTrigger += originalValue.slice(cursorPosition); + return { textAfterTrigger: textAfterTrigger, textUptoTrigger: textUptoTrigger }; + } + + // Invisible character + var POSITIONER_CHARACTER = '\uFEFF'; + function getCaretPosition(element, trigger) { + if (data(element, 'isInput')) { + var _getCursorPosition = getCursorPosition(element), + _getCursorPosition2 = _slicedToArray(_getCursorPosition, 1), + cursorPosition = _getCursorPosition2[0]; + + var _splitValue = splitValue(element.value, cursorPosition, trigger), + textAfterTrigger = _splitValue.textAfterTrigger, + textUptoTrigger = _splitValue.textUptoTrigger; + + // pre to retain special characters + + + var clone = document.createElement('pre'); + clone.id = 'autosuggest-positionclone'; + + var positioner = document.createElement('span'); + positioner.appendChild(document.createTextNode(POSITIONER_CHARACTER)); + + clone.appendChild(document.createTextNode(textUptoTrigger.replace(/ /g, '\xA0'))); + clone.appendChild(positioner); + clone.appendChild(document.createTextNode(textAfterTrigger.replace(/ /g, '\xA0'))); + cloneStyle(element, clone); + + var elementPosition = getGlobalOffset(element); + clone.style.opacity = 0; + clone.style.position = 'absolute'; + clone.style.top = elementPosition.top + 'px'; + clone.style.left = elementPosition.left + 'px'; + document.body.appendChild(clone); + + // Extra styles for the clone depending on type of input + if (element.tagName === 'INPUT') { + clone.style.overflowX = 'auto'; + clone.style.whiteSpace = 'nowrap'; + if (cursorPosition === element.value.length) { + clone.scrollLeft = clone.scrollWidth - clone.clientWidth; + } else { + clone.scrollLeft = Math.min(getScrollLeftForInput(element), clone.scrollWidth - clone.clientWidth); + } + } else { + clone.style.maxWidth = '100%'; + clone.style.whiteSpace = 'pre-wrap'; + clone.scrollTop = element.scrollTop; + clone.scrollLeft = element.scrollLeft; + } + + var caretPosition = getGlobalOffset(positioner); + caretPosition.left -= clone.scrollLeft; + + var charHeight = parseFloat(getComputedStyle(positioner, 'line-height')); + caretPosition.top += charHeight - clone.scrollTop; + + document.body.removeChild(clone); + return caretPosition; + } else { + var _window$getSelection$ = window.getSelection().getRangeAt(0), + startContainer = _window$getSelection$.startContainer, + startOffset = _window$getSelection$.startOffset, + endContainer = _window$getSelection$.endContainer, + endOffset = _window$getSelection$.endOffset; + + var _getSelectedTextNodes = getSelectedTextNodes(), + containerTextNode = _getSelectedTextNodes.startContainer, + _cursorPosition = _getSelectedTextNodes.startOffset; + + var _splitValue2 = splitValue(containerTextNode.nodeValue, _cursorPosition, trigger), + _textAfterTrigger = _splitValue2.textAfterTrigger, + _textUptoTrigger = _splitValue2.textUptoTrigger; + + var parentNode = containerTextNode.parentNode; + var referenceNode = containerTextNode.nextSibling; + + var _positioner = document.createElement("span"); + _positioner.appendChild(document.createTextNode(POSITIONER_CHARACTER)); + parentNode.insertBefore(_positioner, referenceNode); + + if (_textAfterTrigger) { + containerTextNode.nodeValue = _textUptoTrigger; + var remainingTextNode = document.createTextNode(_textAfterTrigger); + parentNode.insertBefore(remainingTextNode, referenceNode); + } + + var _caretPosition = getGlobalOffset(_positioner); + var _charHeight = parseFloat(getComputedStyle(_positioner, 'line-height')); + _caretPosition.top += _charHeight; + + // Reset DOM to the state before changes + parentNode.removeChild(_positioner); + if (_textAfterTrigger) { + parentNode.removeChild(containerTextNode.nextSibling); + containerTextNode.nodeValue = _textUptoTrigger + _textAfterTrigger; + } + + var selection = window.getSelection().getRangeAt(0); + selection.setStart(startContainer, startOffset); + selection.setEnd(endContainer, endOffset); + + return _caretPosition; + } + } + + var getNextNode = function getNextNode(node) { + var nextNode = node.nextSibling || node.parentNode.nextSibling; + while (nextNode.firstChild) { + nextNode = nextNode.firstChild; + }return nextNode; + }; + + var setValue = function setValue(_ref) { + var element = _ref.element, + trigger = _ref.trigger, + suggestion = _ref.suggestion, + onChange = _ref.onChange; + + var insertText = suggestion.use; + var focus = suggestion.focus; + + if (data(element, 'isInput')) { + var _getCursorPosition3 = getCursorPosition(element), + _getCursorPosition4 = _slicedToArray(_getCursorPosition3, 2), + startPosition = _getCursorPosition4[0], + endPosition = _getCursorPosition4[1]; + + var originalValue = element.value; + var value = originalValue.slice(0, startPosition); + var currentValue = value.split(trigger || /\W/).pop(); + value = value.slice(0, 0 - currentValue.length - (trigger || '').length) + insertText; + element.value = value + originalValue.slice(endPosition); + element.focus(); + + var cursorStartPosition = value.length; + element.setSelectionRange(cursorStartPosition + focus[0], cursorStartPosition + focus[1]); + } else { + var _getSelectedTextNodes2 = getSelectedTextNodes(), + startContainer = _getSelectedTextNodes2.startContainer, + startOffset = _getSelectedTextNodes2.startOffset, + endContainer = _getSelectedTextNodes2.endContainer, + endOffset = _getSelectedTextNodes2.endOffset; + + var _value = startContainer.nodeValue.slice(0, startOffset); + var _currentValue = _value.split(trigger || /\W/).pop(); + _value = _value.slice(0, 0 - _currentValue.length - (trigger || '').length) + insertText; + startContainer.nodeValue = _value + endContainer.nodeValue.slice(endOffset); + + var node = startContainer; + if (node !== endContainer) { + node = getNextNode(startContainer); + } + while (node !== endContainer) { + node.parentNode.removeChild(node); + node = getNextNode(startContainer); + } + endContainer.parentNode.removeChild(endContainer); + + var _cursorStartPosition = _value.length; + var selection = window.getSelection().getRangeAt(0); + selection.setStart(startContainer, _cursorStartPosition + focus[0]); + selection.setEnd(startContainer, _cursorStartPosition + focus[1]); + } + + onChange(element, suggestion); + }; + + var AutoSuggest = function () { + function AutoSuggest(options) { + _classCallCheck$1(this, AutoSuggest); + + if (!options) { + throw new Error('AutoSuggest: Missing required parameter, options'); + } + + this.inputs = []; + this.dropdown = new SuggestionDropdown(); + this.onChange = options.onChange || Function.prototype; + this.maxSuggestions = options.maxSuggestions || 10; + + // validate suggestions + this.suggestionLists = options.suggestions || []; + for (var i = 0; i < this.suggestionLists.length; i++) { + var suggestionList = this.suggestionLists[i]; + if (!(suggestionList instanceof SuggestionList)) { + if (suggestionList.constructor !== Object) { + suggestionList = { values: suggestionList }; + } + + if (!suggestionList.hasOwnProperty('caseSensitive') && options.hasOwnProperty('caseSensitive')) { + suggestionList.caseSensitive = options.caseSensitive; + } + + this.suggestionLists[i] = new SuggestionList(suggestionList); + } + } + + events: { + var self = this; + var activeSuggestionList = null; + var handledInKeyDown = false; + + this.onBlurHandler = function () { + self.dropdown.hide(); + }; + + this.onKeyDownHandler = function (e) { + handledInKeyDown = false; + if (self.dropdown.isActive) { + var preventDefaultAction = function preventDefaultAction() { + e.preventDefault(); + handledInKeyDown = true; + }; + + if (e.keyCode === 13 || e.keyCode === 9) { + setValue({ + element: this, + trigger: activeSuggestionList.trigger, + suggestion: self.dropdown.getValue(), + onChange: self.onChange + }); + self.dropdown.hide(); + return preventDefaultAction(); + } else if (e.keyCode === 40) { + self.dropdown.selectNext(); + return preventDefaultAction(); + } else if (e.keyCode === 38) { + self.dropdown.selectPrev(); + return preventDefaultAction(); + } else if (e.keyCode === 27) { + self.dropdown.hide(); + return preventDefaultAction(); + } + } + }; + + var keyUpIndex = 0; + this.onKeyUpHandler = function () { + var _this = this; + + if (handledInKeyDown) return; + + var value = void 0; + if (data(this, 'isInput')) { + var _getCursorPosition5 = getCursorPosition(this), + _getCursorPosition6 = _slicedToArray(_getCursorPosition5, 2), + startPosition = _getCursorPosition6[0], + endPosition = _getCursorPosition6[1]; + + if (/[a-zA-Z_0-9]/.test(this.value.charAt(endPosition) || ' ')) { + self.dropdown.hide(); + return; + } + + value = this.value.slice(0, startPosition); + } else { + var _getSelectedTextNodes3 = getSelectedTextNodes(), + startContainer = _getSelectedTextNodes3.startContainer, + startOffset = _getSelectedTextNodes3.startOffset, + endContainer = _getSelectedTextNodes3.endContainer, + endOffset = _getSelectedTextNodes3.endOffset; + + if (!startContainer || !endContainer || /[a-zA-Z_0-9]/.test(endContainer.nodeValue.charAt(endOffset) || ' ')) { + self.dropdown.hide(); + return; + } + + value = startContainer.nodeValue.slice(0, startOffset); + } + + handleDropdown: { + (function () { + keyUpIndex++; + self.dropdown.empty(); + + var executeQueue = makeAsyncQueueRunner(); + var i = 0, + timer = void 0, + triggerMatchFound = false; + + var _loop = function _loop(_suggestionList) { + if (_suggestionList.regex.test(value)) { + triggerMatchFound = true; + + (function (i, asyncReference) { + var match = _suggestionList.getMatch(value); + var caretPosition = getCaretPosition(_this, _suggestionList.trigger); + + if (self.dropdown.isEmpty) { + timer && clearTimeout(timer); + timer = setTimeout(function () { + self.dropdown.showLoader(caretPosition); + }, 0); + } + + _suggestionList.getSuggestions(match, function (results) { + if (asyncReference !== keyUpIndex) return; + + executeQueue(function () { + timer && clearTimeout(timer); + if (self.dropdown.isEmpty) { + if (results.length) { + activeSuggestionList = _suggestionList; + self.dropdown.fill(results.slice(0, self.maxSuggestions), function (suggestion) { + setValue({ + element: _this, + trigger: _suggestionList.trigger, + suggestion: suggestion, + onChange: self.onChange + }); + }); + + self.dropdown.show(caretPosition); + } else { + self.dropdown.hide(); + } + } + }, i); + }); + })(i++, keyUpIndex); + } + }; + + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = self.suggestionLists[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _suggestionList = _step.value; + + _loop(_suggestionList); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + if (!triggerMatchFound) { + self.dropdown.hide(); + } + })(); + } + }; + } + + // initialize events on inputs + + for (var _len = arguments.length, inputs = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + inputs[_key - 1] = arguments[_key]; + } + + this.addInputs.apply(this, inputs); + } + + _createClass$1(AutoSuggest, [{ + key: 'addInputs', + value: function addInputs() { + var _this2 = this; + + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + var inputs = Array.prototype.concat.apply([], args.map(function (d) { + return d[0] ? Array.prototype.slice.call(d, 0) : d; + })); + + inputs.forEach(function (input) { + // validate element + if (input.isContentEditable) { + data(input, 'isInput', false); + } else if (input.tagName === 'TEXTAREA' || input.tagName === 'INPUT' && input.type === 'text') { + data(input, 'isInput', true); + } else { + throw new Error('AutoSuggest: Invalid input: only input[type = text], textarea and contenteditable elements are supported'); + } + + // init events + input.addEventListener('blur', _this2.onBlurHandler); + input.addEventListener('keyup', _this2.onKeyUpHandler); + input.addEventListener('click', _this2.onKeyUpHandler); + input.addEventListener('keydown', _this2.onKeyDownHandler, true); + + data(input, 'index', _this2.inputs.push(input) - 1); + }); + } + }, { + key: 'removeInputs', + value: function removeInputs() { + var _this3 = this; + + for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + + var inputs = Array.prototype.concat.apply([], args.map(function (d) { + return d[0] ? Array.prototype.slice.call(d, 0) : d; + })); + + inputs.forEach(function (input) { + var index = data(input, 'index'); + if (!isNaN(index)) { + _this3.inputs.splice(index, 1); + + // destroy events + input.removeEventListener('blur', _this3.onBlurHandler); + input.removeEventListener('keyup', _this3.onKeyUpHandler); + input.removeEventListener('click', _this3.onKeyUpHandler); + input.removeEventListener('keydown', _this3.onKeyDownHandler, true); + } + }); + } + }, { + key: 'destroy', + value: function destroy() { + this.removeInputs(this.inputs); + } + }]); + + return AutoSuggest; + }(); + + class Tlm { + constructor(key) { + this.maxSuggestions = 10; + this.minProbability = 0.0001; + var path = 'https://cdn.typelike.me/models/word-predict/' + key + '/'; + let tlm = this; + + var request = new XMLHttpRequest(); + request.open('GET', path + 'tokenizer.json', true); + request.onload = function () { + if (this.status >= 200 && this.status < 400) { + tlm.tokenizer = JSON.parse(this.response); + } + }; + request.send(); + + (async () => { + this.model = await loadLayersModel(path + 'model.json'); + })(); + } + + attach(input) { + let tlm = this; + let element = typeof input == 'string' ? document.getElementById(input) : input; + new AutoSuggest({ + caseSensitive: false, + suggestions: [ + { + trigger: ' ', + caseSensitive: true, + values: function (keyword, callback) { + keyword = keyword.toLowerCase(); + + var results = []; + + if (!keyword) { + var inputElement = element; + var text = inputElement.value; + var predictEnd = inputElement.selectionStart; + text = text.slice(0, predictEnd); + var predictStart = text.lastIndexOf('.') + 1; + text = text.substring(predictStart); + this.latestValues = tlm.predict(text); + } + if (!this.latestValues) { + this.latestValues = []; + } + this.latestValues.forEach(function (word) { + if ( + word.length >= 1 && + !word.indexOf(keyword) && + word !== keyword && + results.indexOf(word) === -1 + ) { + results.push(' ' + word); + } + }); + callback(results); + } + } + ] + }, element); + + element.addEventListener('focus', (event) => { + if (element.value.length == 0) { + element.value = ' '; + } + }); + } + + predict(text) { + let tlm = this; + var words = text.trim().split(' ').slice(-2); + words = words.map(function (value) { + return value.toLowerCase(); + }); + + console.log(words); + var indexes = words.map(x => tlm.tokenizer.word_index[x] ? tlm.tokenizer.word_index[x] : 0); + + while (indexes.length <= 1) { + indexes.unshift(0); + } + console.log(indexes); + var tensor = mn([indexes]); + var prediction = this.model.predict(tensor); + var suggestions = 0; + var filtered = prediction.dataSync().filter(function (element, index, array) { + tlm.maxSuggestions ++; + return element > tlm.minProbability && suggestions <= tlm.maxSuggestions; + }).sort(function (a, b) { return b - a; }); + console.log(filtered); + var suggestion_index = filtered.map(x => prediction.dataSync().indexOf(x)); + var suggestions = []; + suggestion_index.forEach(function (element) { + if(tlm.tokenizer.index_word[element]) { + suggestions.push(tlm.tokenizer.index_word[element]); + } + }); + return suggestions; + } + } + + chrome.storage.local.get( + ["active", "key", "attachInput", "attachTextarea"], + function(result) { + let isActive = result.active; + let key = result.key; + let attachToInput = result.attachInput; + let attachToTextarea = result.attachTextarea; + + if (isActive) { + let tlm = new Tlm(key); + if (attachToTextarea) { + let textareaList = document.getElementsByTagName("textarea"); + for (var i = 0; i < textareaList.length; i++) { + tlm.attach(textareaList[i]); + } + } + if (attachToInput) { + let inputList = document.querySelectorAll("input[type=text]"); + for (var i = 0; i < inputList.length; i++) { + tlm.attach(inputList[i]); + } + } + } + } + ); + +}()); diff --git a/dist/js/options.js b/dist/js/options.js new file mode 100644 index 0000000..3765302 --- /dev/null +++ b/dist/js/options.js @@ -0,0 +1,30 @@ +function refresh() { + chrome.storage.local.get(['active', 'attachInput', 'attachTextarea', 'key'], function (result) { + document.getElementById('active').checked = result.active; + document.getElementById('attach-to-input').checked = result.attachInput; + document.getElementById('attach-to-textarea').checked = result.attachTextarea; + document.getElementById('key').value = result.key; + }); +} +refresh(); + +document.getElementById('active').addEventListener('change', function(){ + chrome.storage.local.set({active: document.getElementById('active').checked}, function() { + refresh(); + }); +}); +document.getElementById('attach-to-input').addEventListener('change', function(){ + chrome.storage.local.set({attachInput: document.getElementById('attach-to-input').checked}, function() { + refresh(); + }); +}); +document.getElementById('attach-to-textarea').addEventListener('change', function(){ + chrome.storage.local.set({attachTextarea: document.getElementById('attach-to-textarea').checked}, function() { + refresh(); + }); +}); +document.getElementById('key').addEventListener('blur', function(){ + chrome.storage.local.set({key: document.getElementById('key').value}, function() { + refresh(); + }); +}); \ No newline at end of file diff --git a/dist/options.html b/dist/options.html new file mode 100644 index 0000000..853b290 --- /dev/null +++ b/dist/options.html @@ -0,0 +1,50 @@ + + + + + + +
    +
    +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    +
    + + + diff --git a/favicon.png b/favicon.png new file mode 100644 index 0000000..20be45e Binary files /dev/null and b/favicon.png differ diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..a8ebf1f --- /dev/null +++ b/manifest.json @@ -0,0 +1,27 @@ +{ + "name": "TypeLikeMe Typing Assistant", + "version": "0.1.0", + "description": "Chrome extention for leveraging text predictions based on machine learning models trained via typelike.me.", + "manifest_version": 2, + "permissions": ["storage", "activeTab"], + "background": { + "scripts": ["dist/js/background.js"], + "persistent": false + }, + "options_page": "dist/options.html", + "page_action": { + "default_icon": { + "32": "favicon.png" + } + }, + "content_scripts": [ + { + "matches": [""], + "js": ["dist/js/content.js"], + "css": ["dist/css/dropdown.min.css"] + } + ], + "icons": { + "32": "favicon.png" + } +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..59b1925 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,2088 @@ +{ + "name": "@typelikeme/chrome-extenstion", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@avcs/autosuggest": { + "version": "1.5.0-beta", + "resolved": "https://registry.npmjs.org/@avcs/autosuggest/-/autosuggest-1.5.0-beta.tgz", + "integrity": "sha512-LVFcrKbDkrO/4r7U9yqbDmlkQxV1mF6TQVyOpf53wc2t1yp6ZsiWBCqRJq/psDVh9khkvJADfp6Pcw1Bvt2Jeg==" + }, + "@babel/code-frame": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.5.5.tgz", + "integrity": "sha512-27d4lZoomVyo51VegxI20xZPuSHusqbQag/ztrBC7wegWoQ1nLREPVSKSW8byhTlzTKyNE4ifaTA6lCp7JjpFw==", + "dev": true, + "requires": { + "@babel/highlight": "^7.0.0" + } + }, + "@babel/core": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.5.5.tgz", + "integrity": "sha512-i4qoSr2KTtce0DmkuuQBV4AuQgGPUcPXMr9L5MyYAtk06z068lQ10a4O009fe5OB/DfNV+h+qqT7ddNV8UnRjg==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.5.5", + "@babel/generator": "^7.5.5", + "@babel/helpers": "^7.5.5", + "@babel/parser": "^7.5.5", + "@babel/template": "^7.4.4", + "@babel/traverse": "^7.5.5", + "@babel/types": "^7.5.5", + "convert-source-map": "^1.1.0", + "debug": "^4.1.0", + "json5": "^2.1.0", + "lodash": "^4.17.13", + "resolve": "^1.3.2", + "semver": "^5.4.1", + "source-map": "^0.5.0" + }, + "dependencies": { + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "semver": { + "version": "5.7.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.0.tgz", + "integrity": "sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==", + "dev": true + } + } + }, + "@babel/generator": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.5.5.tgz", + "integrity": "sha512-ETI/4vyTSxTzGnU2c49XHv2zhExkv9JHLTwDAFz85kmcwuShvYG2H08FwgIguQf4JC75CBnXAUM5PqeF4fj0nQ==", + "dev": true, + "requires": { + "@babel/types": "^7.5.5", + "jsesc": "^2.5.1", + "lodash": "^4.17.13", + "source-map": "^0.5.0", + "trim-right": "^1.0.1" + } + }, + "@babel/helper-function-name": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.1.0.tgz", + "integrity": "sha512-A95XEoCpb3TO+KZzJ4S/5uW5fNe26DjBGqf1o9ucyLyCmi1dXq/B3c8iaWTfBk3VvetUxl16e8tIrd5teOCfGw==", + "dev": true, + "requires": { + "@babel/helper-get-function-arity": "^7.0.0", + "@babel/template": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "@babel/helper-get-function-arity": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.0.0.tgz", + "integrity": "sha512-r2DbJeg4svYvt3HOS74U4eWKsUAMRH01Z1ds1zx8KNTPtpTL5JAsdFv8BNyOpVqdFhHkkRDIg5B4AsxmkjAlmQ==", + "dev": true, + "requires": { + "@babel/types": "^7.0.0" + } + }, + "@babel/helper-plugin-utils": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.0.0.tgz", + "integrity": "sha512-CYAOUCARwExnEixLdB6sDm2dIJ/YgEAKDM1MOeMeZu9Ld/bDgVo8aiWrXwcY7OBh+1Ea2uUcVRcxKk0GJvW7QA==", + "dev": true + }, + "@babel/helper-split-export-declaration": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.4.4.tgz", + "integrity": "sha512-Ro/XkzLf3JFITkW6b+hNxzZ1n5OQ80NvIUdmHspih1XAhtN3vPTuUFT4eQnela+2MaZ5ulH+iyP513KJrxbN7Q==", + "dev": true, + "requires": { + "@babel/types": "^7.4.4" + } + }, + "@babel/helpers": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.5.5.tgz", + "integrity": "sha512-nRq2BUhxZFnfEn/ciJuhklHvFOqjJUD5wpx+1bxUF2axL9C+v4DE/dmp5sT2dKnpOs4orZWzpAZqlCy8QqE/7g==", + "dev": true, + "requires": { + "@babel/template": "^7.4.4", + "@babel/traverse": "^7.5.5", + "@babel/types": "^7.5.5" + } + }, + "@babel/highlight": { + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.5.0.tgz", + "integrity": "sha512-7dV4eu9gBxoM0dAnj/BCFDW9LFU0zvTrkq0ugM7pnHEgguOEeOz1so2ZghEdzviYzQEED0r4EAgpsBChKy1TRQ==", + "dev": true, + "requires": { + "chalk": "^2.0.0", + "esutils": "^2.0.2", + "js-tokens": "^4.0.0" + } + }, + "@babel/parser": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.5.5.tgz", + "integrity": "sha512-E5BN68cqR7dhKan1SfqgPGhQ178bkVKpXTPEXnFJBrEt8/DKRZlybmy+IgYLTeN7tp1R5Ccmbm2rBk17sHYU3g==", + "dev": true + }, + "@babel/plugin-syntax-dynamic-import": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-dynamic-import/-/plugin-syntax-dynamic-import-7.2.0.tgz", + "integrity": "sha512-mVxuJ0YroI/h/tbFTPGZR8cv6ai+STMKNBq0f8hFxsxWjl94qqhsb+wXbpNMDPU3cfR1TIsVFzU3nXyZMqyK4w==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.4.4.tgz", + "integrity": "sha512-CiGzLN9KgAvgZsnivND7rkA+AeJ9JB0ciPOD4U59GKbQP2iQl+olF1l76kJOupqidozfZ32ghwBEJDhnk9MEcw==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "@babel/parser": "^7.4.4", + "@babel/types": "^7.4.4" + } + }, + "@babel/traverse": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.5.5.tgz", + "integrity": "sha512-MqB0782whsfffYfSjH4TM+LMjrJnhCNEDMDIjeTpl+ASaUvxcjoiVCo/sM1GhS1pHOXYfWVCYneLjMckuUxDaQ==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.5.5", + "@babel/generator": "^7.5.5", + "@babel/helper-function-name": "^7.1.0", + "@babel/helper-split-export-declaration": "^7.4.4", + "@babel/parser": "^7.5.5", + "@babel/types": "^7.5.5", + "debug": "^4.1.0", + "globals": "^11.1.0", + "lodash": "^4.17.13" + }, + "dependencies": { + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + } + } + }, + "@babel/types": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.5.5.tgz", + "integrity": "sha512-s63F9nJioLqOlW3UkyMd+BYhXt44YuaFm/VV0VwuteqjYwRrObkU7ra9pY4wAJR3oXi8hJrMcrcJdO/HH33vtw==", + "dev": true, + "requires": { + "esutils": "^2.0.2", + "lodash": "^4.17.13", + "to-fast-properties": "^2.0.0" + } + }, + "@comandeer/babel-plugin-banner": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@comandeer/babel-plugin-banner/-/babel-plugin-banner-5.0.0.tgz", + "integrity": "sha512-sR9Go0U6puXoXyW9UgIiIQhRcJ8jVOvGl4BptUiXAtheMs72WcakZ1udh6J0ZOivr3o8jAM+MTCHLP8FZMbVpQ==", + "dev": true + }, + "@nodelib/fs.scandir": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.1.tgz", + "integrity": "sha512-NT/skIZjgotDSiXs0WqYhgcuBKhUMgfekCmCGtkUAiLqZdOnrdjmZr9wRl3ll64J9NF79uZ4fk16Dx0yMc/Xbg==", + "dev": true, + "requires": { + "@nodelib/fs.stat": "2.0.1", + "run-parallel": "^1.1.9" + } + }, + "@nodelib/fs.stat": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.1.tgz", + "integrity": "sha512-+RqhBlLn6YRBGOIoVYthsG0J9dfpO79eJyN7BYBkZJtfqrBwf2KK+rD/M/yjZR6WBmIhAgOV7S60eCgaSWtbFw==", + "dev": true + }, + "@nodelib/fs.walk": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.2.tgz", + "integrity": "sha512-J/DR3+W12uCzAJkw7niXDcqcKBg6+5G5Q/ZpThpGNzAUz70eOR6RV4XnnSN01qHZiVl0eavoxJsBypQoKsV2QQ==", + "dev": true, + "requires": { + "@nodelib/fs.scandir": "2.1.1", + "fastq": "^1.6.0" + } + }, + "@tensorflow/tfjs": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@tensorflow/tfjs/-/tfjs-1.2.6.tgz", + "integrity": "sha512-ZUd2KCi9m+Psd8qx8//r7Kgr2C75wsS5oYdXgR/5XkpngNawWf6Y279t/ipJyKZg5+ls1y3rVdl1C6OS9rY4LA==", + "requires": { + "@tensorflow/tfjs-converter": "1.2.6", + "@tensorflow/tfjs-core": "1.2.6", + "@tensorflow/tfjs-data": "1.2.6", + "@tensorflow/tfjs-layers": "1.2.6" + } + }, + "@tensorflow/tfjs-converter": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@tensorflow/tfjs-converter/-/tfjs-converter-1.2.6.tgz", + "integrity": "sha512-iP4Ks7CvBZACpkW2sJUNfoSCl/v9uceWS5yBU8QCGLhmbRhMeHlJkusKNZRYvmbX6mMXOSmQWyRK25uPubcqfA==" + }, + "@tensorflow/tfjs-core": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@tensorflow/tfjs-core/-/tfjs-core-1.2.6.tgz", + "integrity": "sha512-BMq209hba/bBRnjnEgMAtNCDBLVL0ZUB8ZhoXuEI1Kmu8K2PnynMNK35rmkl5rAGTs1fdRRYezG/VN40Sq9qzw==", + "requires": { + "@types/offscreencanvas": "~2019.3.0", + "@types/seedrandom": "2.4.27", + "@types/webgl-ext": "0.0.30", + "@types/webgl2": "0.0.4", + "node-fetch": "~2.1.2", + "seedrandom": "2.4.3" + } + }, + "@tensorflow/tfjs-data": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@tensorflow/tfjs-data/-/tfjs-data-1.2.6.tgz", + "integrity": "sha512-e8LH+JDVZDJ4kJPDthxIu2U/JpyLl7wsFMeSNlb/eZR+HL9D6S8OVPP729HumFdMFmRIjhUUXTF9Uj+J2Eq/XQ==", + "requires": { + "@types/node-fetch": "^2.1.2", + "node-fetch": "~2.1.2" + } + }, + "@tensorflow/tfjs-layers": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@tensorflow/tfjs-layers/-/tfjs-layers-1.2.6.tgz", + "integrity": "sha512-fuf01dnOBHhaGoJtDWdP6WloZr32Ew6Mkp8XRmNeDVBDhAfiy7XdsGcPTrC+Bw8XfEniUd+MnHdtHW/3A1pjRw==" + }, + "@typelikeme/tlmjs": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@typelikeme/tlmjs/-/tlmjs-1.0.3.tgz", + "integrity": "sha512-HfmOxha6IpPgImng4HDKC6FJDpIEup5r5d96RhwINWaj1c4UWLhO8U05EGlGw1nvBpioHhjsv8edlOiSolgoEQ==", + "requires": { + "@avcs/autosuggest": "1.5.0-beta", + "@tensorflow/tfjs": "^1.2.6", + "http-server": "^0.11.1" + } + }, + "@types/estree": { + "version": "0.0.39", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz", + "integrity": "sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==", + "dev": true + }, + "@types/events": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/events/-/events-3.0.0.tgz", + "integrity": "sha512-EaObqwIvayI5a8dCzhFrjKzVwKLxjoG9T6Ppd5CEo07LRKfQ8Yokw54r5+Wq7FaBQ+yXRvQAYPrHwya1/UFt9g==", + "dev": true + }, + "@types/fs-extra": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-8.0.0.tgz", + "integrity": "sha512-bCtL5v9zdbQW86yexOlXWTEGvLNqWxMFyi7gQA7Gcthbezr2cPSOb8SkESVKA937QD5cIwOFLDFt0MQoXOEr9Q==", + "dev": true, + "requires": { + "@types/node": "*" + } + }, + "@types/glob": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/@types/glob/-/glob-7.1.1.tgz", + "integrity": "sha512-1Bh06cbWJUHMC97acuD6UMG29nMt0Aqz1vF3guLfG+kHHJhy3AyohZFFxYk2f7Q1SQIrNwvncxAE0N/9s70F2w==", + "dev": true, + "requires": { + "@types/events": "*", + "@types/minimatch": "*", + "@types/node": "*" + } + }, + "@types/minimatch": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.3.tgz", + "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==", + "dev": true + }, + "@types/node": { + "version": "12.6.9", + "resolved": "https://registry.npmjs.org/@types/node/-/node-12.6.9.tgz", + "integrity": "sha512-+YB9FtyxXGyD54p8rXwWaN1EWEyar5L58GlGWgtH2I9rGmLGBQcw63+0jw+ujqVavNuO47S1ByAjm9zdHMnskw==" + }, + "@types/node-fetch": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.5.0.tgz", + "integrity": "sha512-TLFRywthBgL68auWj+ziWu+vnmmcHCDFC/sqCOQf1xTz4hRq8cu79z8CtHU9lncExGBsB8fXA4TiLDLt6xvMzw==", + "requires": { + "@types/node": "*" + } + }, + "@types/offscreencanvas": { + "version": "2019.3.0", + "resolved": "https://registry.npmjs.org/@types/offscreencanvas/-/offscreencanvas-2019.3.0.tgz", + "integrity": "sha512-esIJx9bQg+QYF0ra8GnvfianIY8qWB0GBx54PK5Eps6m+xTj86KLavHv6qDhzKcu5UUOgNfJ2pWaIIV7TRUd9Q==" + }, + "@types/resolve": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-0.0.8.tgz", + "integrity": "sha512-auApPaJf3NPfe18hSoJkp8EbZzer2ISk7o8mCC3M9he/a04+gbMF97NkpD2S8riMGvm4BMRI59/SZQSaLTKpsQ==", + "dev": true, + "requires": { + "@types/node": "*" + } + }, + "@types/seedrandom": { + "version": "2.4.27", + "resolved": "https://registry.npmjs.org/@types/seedrandom/-/seedrandom-2.4.27.tgz", + "integrity": "sha1-nbVjk33YaRX2kJK8QyWdL0hXjkE=" + }, + "@types/webgl-ext": { + "version": "0.0.30", + "resolved": "https://registry.npmjs.org/@types/webgl-ext/-/webgl-ext-0.0.30.tgz", + "integrity": "sha512-LKVgNmBxN0BbljJrVUwkxwRYqzsAEPcZOe6S2T6ZaBDIrFp0qu4FNlpc5sM1tGbXUYFgdVQIoeLk1Y1UoblyEg==" + }, + "@types/webgl2": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/@types/webgl2/-/webgl2-0.0.4.tgz", + "integrity": "sha512-PACt1xdErJbMUOUweSrbVM7gSIYm1vTncW2hF6Os/EeWi6TXYAYMPp+8v6rzHmypE5gHrxaxZNXgMkJVIdZpHw==" + }, + "acorn": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.2.1.tgz", + "integrity": "sha512-JD0xT5FCRDNyjDda3Lrg/IxFscp9q4tiYtxE1/nOzlKCk7hIRuYjhq1kCNkbPjMRMZuFq20HNQn1I9k8Oj0E+Q==", + "dev": true + }, + "acorn-jsx": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.0.1.tgz", + "integrity": "sha512-HJ7CfNHrfJLlNTzIEUTj43LNWGkqpRLxm3YjAlcD0ACydk9XynzYsCBHxut+iqt+1aBXkx9UP/w/ZqMr13XIzg==", + "dev": true + }, + "ajv": { + "version": "6.10.2", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.10.2.tgz", + "integrity": "sha512-TXtUUEYHuaTEbLZWIKUr5pmBuhDLy+8KYtPYdcV8qC+pOZL+NKqYwvWSRrVXHn+ZmRRAu8vJTAznH7Oag6RVRw==", + "dev": true, + "requires": { + "fast-deep-equal": "^2.0.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + } + }, + "ansi-escapes": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==", + "dev": true + }, + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "dev": true + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "requires": { + "sprintf-js": "~1.0.2" + } + }, + "array-union": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", + "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", + "dev": true + }, + "astral-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-1.0.0.tgz", + "integrity": "sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg==", + "dev": true + }, + "async": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", + "integrity": "sha1-7GphrlZIDAw8skHJVhjiCJL5Zyo=" + }, + "babel-helper-evaluate-path": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/babel-helper-evaluate-path/-/babel-helper-evaluate-path-0.5.0.tgz", + "integrity": "sha512-mUh0UhS607bGh5wUMAQfOpt2JX2ThXMtppHRdRU1kL7ZLRWIXxoV2UIV1r2cAeeNeU1M5SB5/RSUgUxrK8yOkA==", + "dev": true + }, + "babel-helper-flip-expressions": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/babel-helper-flip-expressions/-/babel-helper-flip-expressions-0.4.3.tgz", + "integrity": "sha1-NpZzahKKwYvCUlS19AoizrPB0/0=", + "dev": true + }, + "babel-helper-is-nodes-equiv": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/babel-helper-is-nodes-equiv/-/babel-helper-is-nodes-equiv-0.0.1.tgz", + "integrity": "sha1-NOmzALFHnd2Y7HfqC76TQt/jloQ=", + "dev": true + }, + "babel-helper-is-void-0": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/babel-helper-is-void-0/-/babel-helper-is-void-0-0.4.3.tgz", + "integrity": "sha1-fZwBtFYee5Xb2g9u7kj1tg5nMT4=", + "dev": true + }, + "babel-helper-mark-eval-scopes": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/babel-helper-mark-eval-scopes/-/babel-helper-mark-eval-scopes-0.4.3.tgz", + "integrity": "sha1-0kSjvvmESHJgP/tG4izorN9VFWI=", + "dev": true + }, + "babel-helper-remove-or-void": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/babel-helper-remove-or-void/-/babel-helper-remove-or-void-0.4.3.tgz", + "integrity": "sha1-pPA7QAd6D/6I5F0HAQ3uJB/1rmA=", + "dev": true + }, + "babel-helper-to-multiple-sequence-expressions": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/babel-helper-to-multiple-sequence-expressions/-/babel-helper-to-multiple-sequence-expressions-0.5.0.tgz", + "integrity": "sha512-m2CvfDW4+1qfDdsrtf4dwOslQC3yhbgyBFptncp4wvtdrDHqueW7slsYv4gArie056phvQFhT2nRcGS4bnm6mA==", + "dev": true + }, + "babel-plugin-minify-builtins": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/babel-plugin-minify-builtins/-/babel-plugin-minify-builtins-0.5.0.tgz", + "integrity": "sha512-wpqbN7Ov5hsNwGdzuzvFcjgRlzbIeVv1gMIlICbPj0xkexnfoIDe7q+AZHMkQmAE/F9R5jkrB6TLfTegImlXag==", + "dev": true + }, + "babel-plugin-minify-constant-folding": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/babel-plugin-minify-constant-folding/-/babel-plugin-minify-constant-folding-0.5.0.tgz", + "integrity": "sha512-Vj97CTn/lE9hR1D+jKUeHfNy+m1baNiJ1wJvoGyOBUx7F7kJqDZxr9nCHjO/Ad+irbR3HzR6jABpSSA29QsrXQ==", + "dev": true, + "requires": { + "babel-helper-evaluate-path": "^0.5.0" + } + }, + "babel-plugin-minify-dead-code-elimination": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/babel-plugin-minify-dead-code-elimination/-/babel-plugin-minify-dead-code-elimination-0.5.0.tgz", + "integrity": "sha512-XQteBGXlgEoAKc/BhO6oafUdT4LBa7ARi55mxoyhLHNuA+RlzRmeMAfc31pb/UqU01wBzRc36YqHQzopnkd/6Q==", + "dev": true, + "requires": { + "babel-helper-evaluate-path": "^0.5.0", + "babel-helper-mark-eval-scopes": "^0.4.3", + "babel-helper-remove-or-void": "^0.4.3", + "lodash.some": "^4.6.0" + } + }, + "babel-plugin-minify-flip-comparisons": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/babel-plugin-minify-flip-comparisons/-/babel-plugin-minify-flip-comparisons-0.4.3.tgz", + "integrity": "sha1-AMqHDLjxO0XAOLPB68DyJyk8llo=", + "dev": true, + "requires": { + "babel-helper-is-void-0": "^0.4.3" + } + }, + "babel-plugin-minify-guarded-expressions": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/babel-plugin-minify-guarded-expressions/-/babel-plugin-minify-guarded-expressions-0.4.3.tgz", + "integrity": "sha1-zHCbRFP9IbHzAod0RMifiEJ845c=", + "dev": true, + "requires": { + "babel-helper-flip-expressions": "^0.4.3" + } + }, + "babel-plugin-minify-infinity": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/babel-plugin-minify-infinity/-/babel-plugin-minify-infinity-0.4.3.tgz", + "integrity": "sha1-37h2obCKBldjhO8/kuZTumB7Oco=", + "dev": true + }, + "babel-plugin-minify-mangle-names": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/babel-plugin-minify-mangle-names/-/babel-plugin-minify-mangle-names-0.5.0.tgz", + "integrity": "sha512-3jdNv6hCAw6fsX1p2wBGPfWuK69sfOjfd3zjUXkbq8McbohWy23tpXfy5RnToYWggvqzuMOwlId1PhyHOfgnGw==", + "dev": true, + "requires": { + "babel-helper-mark-eval-scopes": "^0.4.3" + } + }, + "babel-plugin-minify-numeric-literals": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/babel-plugin-minify-numeric-literals/-/babel-plugin-minify-numeric-literals-0.4.3.tgz", + "integrity": "sha1-jk/VYcefeAEob/YOjF/Z3u6TwLw=", + "dev": true + }, + "babel-plugin-minify-replace": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/babel-plugin-minify-replace/-/babel-plugin-minify-replace-0.5.0.tgz", + "integrity": "sha512-aXZiaqWDNUbyNNNpWs/8NyST+oU7QTpK7J9zFEFSA0eOmtUNMU3fczlTTTlnCxHmq/jYNFEmkkSG3DDBtW3Y4Q==", + "dev": true + }, + "babel-plugin-minify-simplify": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/babel-plugin-minify-simplify/-/babel-plugin-minify-simplify-0.5.0.tgz", + "integrity": "sha512-TM01J/YcKZ8XIQd1Z3nF2AdWHoDsarjtZ5fWPDksYZNsoOjQ2UO2EWm824Ym6sp127m44gPlLFiO5KFxU8pA5Q==", + "dev": true, + "requires": { + "babel-helper-flip-expressions": "^0.4.3", + "babel-helper-is-nodes-equiv": "^0.0.1", + "babel-helper-to-multiple-sequence-expressions": "^0.5.0" + } + }, + "babel-plugin-minify-type-constructors": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/babel-plugin-minify-type-constructors/-/babel-plugin-minify-type-constructors-0.4.3.tgz", + "integrity": "sha1-G8bxW4f3qxCF1CszC3F2V6IVZQA=", + "dev": true, + "requires": { + "babel-helper-is-void-0": "^0.4.3" + } + }, + "babel-plugin-transform-inline-consecutive-adds": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-inline-consecutive-adds/-/babel-plugin-transform-inline-consecutive-adds-0.4.3.tgz", + "integrity": "sha1-Mj1Ho+pjqDp6w8gRro5pQfrysNE=", + "dev": true + }, + "babel-plugin-transform-member-expression-literals": { + "version": "6.9.4", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-member-expression-literals/-/babel-plugin-transform-member-expression-literals-6.9.4.tgz", + "integrity": "sha1-NwOcmgwzE6OUlfqsL/OmtbnQOL8=", + "dev": true + }, + "babel-plugin-transform-merge-sibling-variables": { + "version": "6.9.4", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-merge-sibling-variables/-/babel-plugin-transform-merge-sibling-variables-6.9.4.tgz", + "integrity": "sha1-hbQi/DN3tEnJ0c3kQIcgNTJAHa4=", + "dev": true + }, + "babel-plugin-transform-minify-booleans": { + "version": "6.9.4", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-minify-booleans/-/babel-plugin-transform-minify-booleans-6.9.4.tgz", + "integrity": "sha1-rLs+VqNVXdI5KOS1gtKFFi3SsZg=", + "dev": true + }, + "babel-plugin-transform-property-literals": { + "version": "6.9.4", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-property-literals/-/babel-plugin-transform-property-literals-6.9.4.tgz", + "integrity": "sha1-mMHSHiVXNlc/k+zlRFn2ziSYXTk=", + "dev": true, + "requires": { + "esutils": "^2.0.2" + } + }, + "babel-plugin-transform-regexp-constructors": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-regexp-constructors/-/babel-plugin-transform-regexp-constructors-0.4.3.tgz", + "integrity": "sha1-WLd3W2OvzzMyj66aX4j71PsLSWU=", + "dev": true + }, + "babel-plugin-transform-remove-console": { + "version": "6.9.4", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-remove-console/-/babel-plugin-transform-remove-console-6.9.4.tgz", + "integrity": "sha1-uYA2DAZzhOJLNXpYjYB9PINSd4A=", + "dev": true + }, + "babel-plugin-transform-remove-debugger": { + "version": "6.9.4", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-remove-debugger/-/babel-plugin-transform-remove-debugger-6.9.4.tgz", + "integrity": "sha1-QrcnYxyXl44estGZp67IShgznvI=", + "dev": true + }, + "babel-plugin-transform-remove-undefined": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-remove-undefined/-/babel-plugin-transform-remove-undefined-0.5.0.tgz", + "integrity": "sha512-+M7fJYFaEE/M9CXa0/IRkDbiV3wRELzA1kKQFCJ4ifhrzLKn/9VCCgj9OFmYWwBd8IB48YdgPkHYtbYq+4vtHQ==", + "dev": true, + "requires": { + "babel-helper-evaluate-path": "^0.5.0" + } + }, + "babel-plugin-transform-simplify-comparison-operators": { + "version": "6.9.4", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-simplify-comparison-operators/-/babel-plugin-transform-simplify-comparison-operators-6.9.4.tgz", + "integrity": "sha1-9ir+CWyrDh9ootdT/fKDiIRxzrk=", + "dev": true + }, + "babel-plugin-transform-undefined-to-void": { + "version": "6.9.4", + "resolved": "https://registry.npmjs.org/babel-plugin-transform-undefined-to-void/-/babel-plugin-transform-undefined-to-void-6.9.4.tgz", + "integrity": "sha1-viQcqBQEAwZ4t0hxcyK4nQyP4oA=", + "dev": true + }, + "babel-preset-minify": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/babel-preset-minify/-/babel-preset-minify-0.5.0.tgz", + "integrity": "sha512-xj1s9Mon+RFubH569vrGCayA9Fm2GMsCgDRm1Jb8SgctOB7KFcrVc2o8K3YHUyMz+SWP8aea75BoS8YfsXXuiA==", + "dev": true, + "requires": { + "babel-plugin-minify-builtins": "^0.5.0", + "babel-plugin-minify-constant-folding": "^0.5.0", + "babel-plugin-minify-dead-code-elimination": "^0.5.0", + "babel-plugin-minify-flip-comparisons": "^0.4.3", + "babel-plugin-minify-guarded-expressions": "^0.4.3", + "babel-plugin-minify-infinity": "^0.4.3", + "babel-plugin-minify-mangle-names": "^0.5.0", + "babel-plugin-minify-numeric-literals": "^0.4.3", + "babel-plugin-minify-replace": "^0.5.0", + "babel-plugin-minify-simplify": "^0.5.0", + "babel-plugin-minify-type-constructors": "^0.4.3", + "babel-plugin-transform-inline-consecutive-adds": "^0.4.3", + "babel-plugin-transform-member-expression-literals": "^6.9.4", + "babel-plugin-transform-merge-sibling-variables": "^6.9.4", + "babel-plugin-transform-minify-booleans": "^6.9.4", + "babel-plugin-transform-property-literals": "^6.9.4", + "babel-plugin-transform-regexp-constructors": "^0.4.3", + "babel-plugin-transform-remove-console": "^6.9.4", + "babel-plugin-transform-remove-debugger": "^6.9.4", + "babel-plugin-transform-remove-undefined": "^0.5.0", + "babel-plugin-transform-simplify-comparison-operators": "^6.9.4", + "babel-plugin-transform-undefined-to-void": "^6.9.4", + "lodash.isplainobject": "^4.0.6" + } + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dev": true, + "requires": { + "fill-range": "^7.0.1" + } + }, + "builtin-modules": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-3.1.0.tgz", + "integrity": "sha512-k0KL0aWZuBt2lrxrcASWDfwOLMnodeQjodT/1SxEQAXsHANgo6ZC/VEaSEHCXt7aSTZ4/4H5LKa+tBXmW7Vtvw==", + "dev": true + }, + "callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "chardet": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", + "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", + "dev": true + }, + "cli-cursor": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-2.1.0.tgz", + "integrity": "sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU=", + "dev": true, + "requires": { + "restore-cursor": "^2.0.0" + } + }, + "cli-width": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-2.2.0.tgz", + "integrity": "sha1-/xnt6Kml5XkyQUewwR8PvLq+1jk=", + "dev": true + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "dev": true + }, + "colorette": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.1.0.tgz", + "integrity": "sha512-6S062WDQUXi6hOfkO/sBPVwE5ASXY4G2+b4atvhJfSsuUUhIaUKlkjLe9692Ipyt5/a+IPF5aVTu3V5gvXq5cg==", + "dev": true + }, + "colors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", + "integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=" + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "convert-source-map": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.6.0.tgz", + "integrity": "sha512-eFu7XigvxdZ1ETfbgPBohgyQ/Z++C0eEhTor0qRwBw9unw+L0/6V8wkSuGgzdThkiS5lSpdptOQPD8Ak40a+7A==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.1" + } + }, + "corser": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/corser/-/corser-2.0.1.tgz", + "integrity": "sha1-jtolLsqrWEDc2XXOuQ2TcMgZ/4c=" + }, + "cross-spawn": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "dev": true, + "requires": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + }, + "dependencies": { + "semver": { + "version": "5.7.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.0.tgz", + "integrity": "sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==", + "dev": true + } + } + }, + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "requires": { + "ms": "^2.1.1" + } + }, + "deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "dev": true + }, + "dir-glob": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", + "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", + "dev": true, + "requires": { + "path-type": "^4.0.0" + } + }, + "doctrine": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", + "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", + "dev": true, + "requires": { + "esutils": "^2.0.2" + } + }, + "ecstatic": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/ecstatic/-/ecstatic-3.3.2.tgz", + "integrity": "sha512-fLf9l1hnwrHI2xn9mEDT7KIi22UDqA2jaCwyCbSUJh9a1V+LEUSL/JO/6TIz/QyuBURWUHrFL5Kg2TtO1bkkog==", + "requires": { + "he": "^1.1.1", + "mime": "^1.6.0", + "minimist": "^1.1.0", + "url-join": "^2.0.5" + } + }, + "emoji-regex": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz", + "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", + "dev": true + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "eslint": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-6.1.0.tgz", + "integrity": "sha512-QhrbdRD7ofuV09IuE2ySWBz0FyXCq0rriLTZXZqaWSI79CVtHVRdkFuFTViiqzZhkCgfOh9USpriuGN2gIpZDQ==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "ajv": "^6.10.0", + "chalk": "^2.1.0", + "cross-spawn": "^6.0.5", + "debug": "^4.0.1", + "doctrine": "^3.0.0", + "eslint-scope": "^5.0.0", + "eslint-utils": "^1.3.1", + "eslint-visitor-keys": "^1.0.0", + "espree": "^6.0.0", + "esquery": "^1.0.1", + "esutils": "^2.0.2", + "file-entry-cache": "^5.0.1", + "functional-red-black-tree": "^1.0.1", + "glob-parent": "^5.0.0", + "globals": "^11.7.0", + "ignore": "^4.0.6", + "import-fresh": "^3.0.0", + "imurmurhash": "^0.1.4", + "inquirer": "^6.4.1", + "is-glob": "^4.0.0", + "js-yaml": "^3.13.1", + "json-stable-stringify-without-jsonify": "^1.0.1", + "levn": "^0.3.0", + "lodash": "^4.17.14", + "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", + "natural-compare": "^1.4.0", + "optionator": "^0.8.2", + "progress": "^2.0.0", + "regexpp": "^2.0.1", + "semver": "^6.1.2", + "strip-ansi": "^5.2.0", + "strip-json-comments": "^3.0.1", + "table": "^5.2.3", + "text-table": "^0.2.0", + "v8-compile-cache": "^2.0.3" + }, + "dependencies": { + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + } + } + }, + "eslint-scope": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.0.0.tgz", + "integrity": "sha512-oYrhJW7S0bxAFDvWqzvMPRm6pcgcnWc4QnofCAqRTRfQC0JcwenzGglTtsLyIuuWFfkqDG9vz67cnttSd53djw==", + "dev": true, + "requires": { + "esrecurse": "^4.1.0", + "estraverse": "^4.1.1" + } + }, + "eslint-utils": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-1.4.0.tgz", + "integrity": "sha512-7ehnzPaP5IIEh1r1tkjuIrxqhNkzUJa9z3R92tLJdZIVdWaczEhr3EbhGtsMrVxi1KeR8qA7Off6SWc5WNQqyQ==", + "dev": true, + "requires": { + "eslint-visitor-keys": "^1.0.0" + } + }, + "eslint-visitor-keys": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz", + "integrity": "sha512-qzm/XxIbxm/FHyH341ZrbnMUpe+5Bocte9xkmFMzPMjRaZMcXww+MpBptFvtU+79L362nqiLhekCxCxDPaUMBQ==", + "dev": true + }, + "espree": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-6.0.0.tgz", + "integrity": "sha512-lJvCS6YbCn3ImT3yKkPe0+tJ+mH6ljhGNjHQH9mRtiO6gjhVAOhVXW1yjnwqGwTkK3bGbye+hb00nFNmu0l/1Q==", + "dev": true, + "requires": { + "acorn": "^6.0.7", + "acorn-jsx": "^5.0.0", + "eslint-visitor-keys": "^1.0.0" + } + }, + "esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true + }, + "esquery": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.0.1.tgz", + "integrity": "sha512-SmiyZ5zIWH9VM+SRUReLS5Q8a7GxtRdxEBVZpm98rJM7Sb+A9DVCndXfkeFUd3byderg+EbDkfnevfCwynWaNA==", + "dev": true, + "requires": { + "estraverse": "^4.0.0" + } + }, + "esrecurse": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.1.tgz", + "integrity": "sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ==", + "dev": true, + "requires": { + "estraverse": "^4.1.0" + } + }, + "estraverse": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", + "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", + "dev": true + }, + "estree-walker": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-0.6.1.tgz", + "integrity": "sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w==", + "dev": true + }, + "esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true + }, + "eventemitter3": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-3.1.2.tgz", + "integrity": "sha512-tvtQIeLVHjDkJYnzf2dgVMxfuSGJeM/7UCG17TT4EumTfNtF+0nebF/4zWOIkCreAbtNqhGEboB6BWrwqNaw4Q==" + }, + "external-editor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", + "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", + "dev": true, + "requires": { + "chardet": "^0.7.0", + "iconv-lite": "^0.4.24", + "tmp": "^0.0.33" + } + }, + "fast-deep-equal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", + "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=", + "dev": true + }, + "fast-glob": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.0.4.tgz", + "integrity": "sha512-wkIbV6qg37xTJwqSsdnIphL1e+LaGz4AIQqr00mIubMaEhv1/HEmJ0uuCGZRNRUkZZmOB5mJKO0ZUTVq+SxMQg==", + "dev": true, + "requires": { + "@nodelib/fs.stat": "^2.0.1", + "@nodelib/fs.walk": "^1.2.1", + "glob-parent": "^5.0.0", + "is-glob": "^4.0.1", + "merge2": "^1.2.3", + "micromatch": "^4.0.2" + } + }, + "fast-json-stable-stringify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz", + "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=", + "dev": true + }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true + }, + "fastq": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.6.0.tgz", + "integrity": "sha512-jmxqQ3Z/nXoeyDmWAzF9kH1aGZSis6e/SbfPmJpUnyZ0ogr6iscHQaml4wsEepEWSdtmpy+eVXmCRIMpxaXqOA==", + "dev": true, + "requires": { + "reusify": "^1.0.0" + } + }, + "figures": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", + "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", + "dev": true, + "requires": { + "escape-string-regexp": "^1.0.5" + } + }, + "file-entry-cache": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-5.0.1.tgz", + "integrity": "sha512-bCg29ictuBaKUwwArK4ouCaqDgLZcysCFLmM/Yn/FDoqndh/9vNuQfXRDvTuXKLxfD/JtZQGKFT8MGcJBK644g==", + "dev": true, + "requires": { + "flat-cache": "^2.0.1" + } + }, + "fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dev": true, + "requires": { + "to-regex-range": "^5.0.1" + } + }, + "flat-cache": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-2.0.1.tgz", + "integrity": "sha512-LoQe6yDuUMDzQAEH8sgmh4Md6oZnc/7PjtwjNFSzveXqSHt6ka9fPBuso7IGf9Rz4uqnSnWiFH2B/zj24a5ReA==", + "dev": true, + "requires": { + "flatted": "^2.0.0", + "rimraf": "2.6.3", + "write": "1.0.3" + } + }, + "flatted": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-2.0.1.tgz", + "integrity": "sha512-a1hQMktqW9Nmqr5aktAux3JMNqaucxGcjtjWnZLHX7yyPCmlSV3M54nGYbqT8K+0GhF3NBgmJCc3ma+WOgX8Jg==", + "dev": true + }, + "follow-redirects": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.7.0.tgz", + "integrity": "sha512-m/pZQy4Gj287eNy94nivy5wchN3Kp+Q5WgUPNy5lJSZ3sgkVKSYV/ZChMAQVIgx1SqfZ2zBZtPA2YlXIWxxJOQ==", + "requires": { + "debug": "^3.2.6" + } + }, + "fs-extra": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", + "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", + "dev": true, + "requires": { + "graceful-fs": "^4.2.0", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "functional-red-black-tree": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", + "integrity": "sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc=", + "dev": true + }, + "glob": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.4.tgz", + "integrity": "sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "glob-parent": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.0.0.tgz", + "integrity": "sha512-Z2RwiujPRGluePM6j699ktJYxmPpJKCfpGA13jz2hmFZC7gKetzrWvg5KN3+OsIFmydGyZ1AVwERCq1w/ZZwRg==", + "dev": true, + "requires": { + "is-glob": "^4.0.1" + } + }, + "globals": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "dev": true + }, + "globby": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/globby/-/globby-10.0.1.tgz", + "integrity": "sha512-sSs4inE1FB2YQiymcmTv6NWENryABjUNPeWhOvmn4SjtKybglsyPZxFB3U1/+L1bYi0rNZDqCLlHyLYDl1Pq5A==", + "dev": true, + "requires": { + "@types/glob": "^7.1.1", + "array-union": "^2.1.0", + "dir-glob": "^3.0.1", + "fast-glob": "^3.0.3", + "glob": "^7.1.3", + "ignore": "^5.1.1", + "merge2": "^1.2.3", + "slash": "^3.0.0" + }, + "dependencies": { + "ignore": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.2.tgz", + "integrity": "sha512-vdqWBp7MyzdmHkkRWV5nY+PfGRbYbahfuvsBCh277tq+w9zyNi7h5CYJCK0kmzti9kU+O/cB7sE8HvKv6aXAKQ==", + "dev": true + } + } + }, + "graceful-fs": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.1.tgz", + "integrity": "sha512-b9usnbDGnD928gJB3LrCmxoibr3VE4U2SMo5PBuBnokWyDADTqDPXg4YpwKF1trpH+UbGp7QLicO3+aWEy0+mw==", + "dev": true + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true + }, + "he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==" + }, + "http-proxy": { + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.17.0.tgz", + "integrity": "sha512-Taqn+3nNvYRfJ3bGvKfBSRwy1v6eePlm3oc/aWVxZp57DQr5Eq3xhKJi7Z4hZpS8PC3H4qI+Yly5EmFacGuA/g==", + "requires": { + "eventemitter3": "^3.0.0", + "follow-redirects": "^1.0.0", + "requires-port": "^1.0.0" + } + }, + "http-server": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/http-server/-/http-server-0.11.1.tgz", + "integrity": "sha512-6JeGDGoujJLmhjiRGlt8yK8Z9Kl0vnl/dQoQZlc4oeqaUoAKQg94NILLfrY3oWzSyFaQCVNTcKE5PZ3cH8VP9w==", + "requires": { + "colors": "1.0.3", + "corser": "~2.0.0", + "ecstatic": "^3.0.0", + "http-proxy": "^1.8.1", + "opener": "~1.4.0", + "optimist": "0.6.x", + "portfinder": "^1.0.13", + "union": "~0.4.3" + } + }, + "iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dev": true, + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "ignore": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", + "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", + "dev": true + }, + "import-fresh": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.1.0.tgz", + "integrity": "sha512-PpuksHKGt8rXfWEr9m9EHIpgyyaltBy8+eF6GJM0QCAxMgxCfucMF3mjecK2QsJr0amJW7gTqh5/wht0z2UhEQ==", + "dev": true, + "requires": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + } + }, + "imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "inquirer": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.5.0.tgz", + "integrity": "sha512-scfHejeG/lVZSpvCXpsB4j/wQNPM5JC8kiElOI0OUTwmc1RTpXr4H32/HOlQHcZiYl2z2VElwuCVDRG8vFmbnA==", + "dev": true, + "requires": { + "ansi-escapes": "^3.2.0", + "chalk": "^2.4.2", + "cli-cursor": "^2.1.0", + "cli-width": "^2.0.0", + "external-editor": "^3.0.3", + "figures": "^2.0.0", + "lodash": "^4.17.12", + "mute-stream": "0.0.7", + "run-async": "^2.2.0", + "rxjs": "^6.4.0", + "string-width": "^2.1.0", + "strip-ansi": "^5.1.0", + "through": "^2.3.6" + } + }, + "is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", + "dev": true + }, + "is-glob": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", + "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", + "dev": true, + "requires": { + "is-extglob": "^2.1.1" + } + }, + "is-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", + "integrity": "sha1-Mlj7afeMFNW4FdZkM2tM/7ZEFZE=", + "dev": true + }, + "is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true + }, + "is-plain-object": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-3.0.0.tgz", + "integrity": "sha512-tZIpofR+P05k8Aocp7UI/2UTa9lTJSebCXpFFoR9aibpokDj/uXBsJ8luUu0tTVYKkMU6URDUuOfJZ7koewXvg==", + "dev": true, + "requires": { + "isobject": "^4.0.0" + } + }, + "is-promise": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz", + "integrity": "sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=", + "dev": true + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", + "dev": true + }, + "isobject": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-4.0.0.tgz", + "integrity": "sha512-S/2fF5wH8SJA/kmwr6HYhK/RI/OkhD84k8ntalo0iJjZikgq1XFvR5M8NPT1x5F7fBwCG3qHfnzeP/Vh/ZxCUA==", + "dev": true + }, + "js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + }, + "js-yaml": { + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.13.1.tgz", + "integrity": "sha512-YfbcO7jXDdyj0DGxYVSlSeQNHbD7XPWvrVWeVUujrQEoZzWJIRrCPoyk6kL6IAjAG2IolMK4T0hNUe0HOUs5Jw==", + "dev": true, + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, + "jsesc": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "dev": true + }, + "json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + }, + "json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", + "dev": true + }, + "json5": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.1.0.tgz", + "integrity": "sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ==", + "dev": true, + "requires": { + "minimist": "^1.2.0" + } + }, + "jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.6" + } + }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "requires": { + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" + } + }, + "lodash": { + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==", + "dev": true + }, + "lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=", + "dev": true + }, + "lodash.some": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.some/-/lodash.some-4.6.0.tgz", + "integrity": "sha1-G7nzFO9ri63tE7VJFpsqlF62jk0=", + "dev": true + }, + "merge2": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.2.4.tgz", + "integrity": "sha512-FYE8xI+6pjFOhokZu0We3S5NKCirLbCzSh2Usf3qEyr4X8U+0jNg9P8RZ4qz+V2UoECLVwSyzU3LxXBaLGtD3A==", + "dev": true + }, + "micromatch": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.2.tgz", + "integrity": "sha512-y7FpHSbMUMoyPbYUSzO6PaZ6FyRnQOpHuKwbo1G+Knck95XVU4QAiKdGEnj5wwoS7PlOgthX/09u5iFJ+aYf5Q==", + "dev": true, + "requires": { + "braces": "^3.0.1", + "picomatch": "^2.0.5" + } + }, + "mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==" + }, + "mimic-fn": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", + "integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==", + "dev": true + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=" + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "requires": { + "minimist": "0.0.8" + }, + "dependencies": { + "minimist": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=" + } + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "mute-stream": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.7.tgz", + "integrity": "sha1-MHXOk7whuPq0PhvE2n6BFe0ee6s=", + "dev": true + }, + "natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", + "dev": true + }, + "nice-try": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", + "dev": true + }, + "node-fetch": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.1.2.tgz", + "integrity": "sha1-q4hOjn5X44qUR1POxwb3iNF2i7U=" + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "onetime": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-2.0.1.tgz", + "integrity": "sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ=", + "dev": true, + "requires": { + "mimic-fn": "^1.0.0" + } + }, + "opener": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/opener/-/opener-1.4.3.tgz", + "integrity": "sha1-XG2ixdflgx6P+jlklQ+NZnSskLg=" + }, + "optimist": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/optimist/-/optimist-0.6.1.tgz", + "integrity": "sha1-2j6nRob6IaGaERwybpDrFaAZZoY=", + "requires": { + "minimist": "~0.0.1", + "wordwrap": "~0.0.2" + }, + "dependencies": { + "minimist": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.10.tgz", + "integrity": "sha1-3j+YVD2/lggr5IrRoMfNqDYwHc8=" + } + } + }, + "optionator": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", + "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", + "dev": true, + "requires": { + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.4", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "wordwrap": "~1.0.0" + }, + "dependencies": { + "wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", + "dev": true + } + } + }, + "os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", + "dev": true + }, + "parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "requires": { + "callsites": "^3.0.0" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", + "dev": true + }, + "path-parse": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", + "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==", + "dev": true + }, + "path-type": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", + "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", + "dev": true + }, + "picomatch": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.0.7.tgz", + "integrity": "sha512-oLHIdio3tZ0qH76NybpeneBhYVj0QFTfXEFTc/B3zKQspYfYYkWYgFsmzo+4kvId/bQRcNkVeguI3y+CD22BtA==", + "dev": true + }, + "portfinder": { + "version": "1.0.21", + "resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.21.tgz", + "integrity": "sha512-ESabpDCzmBS3ekHbmpAIiESq3udRsCBGiBZLsC+HgBKv2ezb0R4oG+7RnYEVZ/ZCfhel5Tx3UzdNWA0Lox2QCA==", + "requires": { + "async": "^1.5.2", + "debug": "^2.2.0", + "mkdirp": "0.5.x" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + } + } + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true + }, + "progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", + "dev": true + }, + "punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "dev": true + }, + "qs": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-2.3.3.tgz", + "integrity": "sha1-6eha2+ddoLvkyOBHaghikPhjtAQ=" + }, + "regexpp": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-2.0.1.tgz", + "integrity": "sha512-lv0M6+TkDVniA3aD1Eg0DVpfU/booSu7Eev3TDO/mZKHBfVjgCGTV4t4buppESEYDtkArYFOxTJWv6S5C+iaNw==", + "dev": true + }, + "requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=" + }, + "resolve": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.12.0.tgz", + "integrity": "sha512-B/dOmuoAik5bKcD6s6nXDCjzUKnaDvdkRyAk6rsmsKLipWj4797iothd7jmmUhWTfinVMU+wc56rYKsit2Qy4w==", + "dev": true, + "requires": { + "path-parse": "^1.0.6" + } + }, + "resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true + }, + "restore-cursor": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-2.0.0.tgz", + "integrity": "sha1-n37ih/gv0ybU/RYpI9YhKe7g368=", + "dev": true, + "requires": { + "onetime": "^2.0.0", + "signal-exit": "^3.0.2" + } + }, + "reusify": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", + "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", + "dev": true + }, + "rimraf": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, + "rollup": { + "version": "1.18.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-1.18.0.tgz", + "integrity": "sha512-MBAWr6ectF948gW/bs/yfi0jW7DzwI8n0tEYG/ZMQutmK+blF/Oazyhg3oPqtScCGV8bzCtL9KzlzPtTriEOJA==", + "dev": true, + "requires": { + "@types/estree": "0.0.39", + "@types/node": "^12.6.3", + "acorn": "^6.2.0" + } + }, + "rollup-plugin-babel-minify": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/rollup-plugin-babel-minify/-/rollup-plugin-babel-minify-9.0.0.tgz", + "integrity": "sha512-5aJVWpuoZUbQrIaRF7Jvjo7bBnYqaChOhrhsGtz72wJ3lyo7ygIL85hsuPkvrk/3Fj5AUlNZV3IaSZ98fHyoTw==", + "dev": true, + "requires": { + "@babel/core": "^7.4.5", + "@babel/plugin-syntax-dynamic-import": "^7.2.0", + "@comandeer/babel-plugin-banner": "^5.0.0", + "babel-preset-minify": "^0.5.0", + "sourcemap-codec": "^1.4.4" + } + }, + "rollup-plugin-copy": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/rollup-plugin-copy/-/rollup-plugin-copy-3.1.0.tgz", + "integrity": "sha512-oVw3ljRV5jv7Yw/6eCEHntVs9Mc+NFglc0iU0J8ei76gldYmtBQ0M/j6WAkZUFVRSrhgfCrEakUllnN87V2f4w==", + "dev": true, + "requires": { + "@types/fs-extra": "^8.0.0", + "colorette": "^1.1.0", + "fs-extra": "^8.1.0", + "globby": "10.0.1", + "is-plain-object": "^3.0.0" + } + }, + "rollup-plugin-eslint": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/rollup-plugin-eslint/-/rollup-plugin-eslint-7.0.0.tgz", + "integrity": "sha512-u35kXiY11ULeNQGTlRkYx7uGJ/hS/Dx3wj8f9YVC3oMLTGU9fOqQJsAKYtBFZU3gJ8Vt3gu8ppB1vnKl+7gatQ==", + "dev": true, + "requires": { + "eslint": "^6.0.0", + "rollup-pluginutils": "^2.7.1" + } + }, + "rollup-plugin-node-resolve": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/rollup-plugin-node-resolve/-/rollup-plugin-node-resolve-5.2.0.tgz", + "integrity": "sha512-jUlyaDXts7TW2CqQ4GaO5VJ4PwwaV8VUGA7+km3n6k6xtOEacf61u0VXwN80phY/evMcaS+9eIeJ9MOyDxt5Zw==", + "dev": true, + "requires": { + "@types/resolve": "0.0.8", + "builtin-modules": "^3.1.0", + "is-module": "^1.0.0", + "resolve": "^1.11.1", + "rollup-pluginutils": "^2.8.1" + } + }, + "rollup-pluginutils": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/rollup-pluginutils/-/rollup-pluginutils-2.8.1.tgz", + "integrity": "sha512-J5oAoysWar6GuZo0s+3bZ6sVZAC0pfqKz68De7ZgDi5z63jOVZn1uJL/+z1jeKHNbGII8kAyHF5q8LnxSX5lQg==", + "dev": true, + "requires": { + "estree-walker": "^0.6.1" + } + }, + "run-async": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.3.0.tgz", + "integrity": "sha1-A3GrSuC91yDUFm19/aZP96RFpsA=", + "dev": true, + "requires": { + "is-promise": "^2.1.0" + } + }, + "run-parallel": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.1.9.tgz", + "integrity": "sha512-DEqnSRTDw/Tc3FXf49zedI638Z9onwUotBMiUFKmrO2sdFKIbXamXGQ3Axd4qgphxKB4kw/qP1w5kTxnfU1B9Q==", + "dev": true + }, + "rxjs": { + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.5.2.tgz", + "integrity": "sha512-HUb7j3kvb7p7eCUHE3FqjoDsC1xfZQ4AHFWfTKSpZ+sAhhz5X1WX0ZuUqWbzB2QhSLp3DoLUG+hMdEDKqWo2Zg==", + "dev": true, + "requires": { + "tslib": "^1.9.0" + } + }, + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true + }, + "seedrandom": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/seedrandom/-/seedrandom-2.4.3.tgz", + "integrity": "sha1-JDhQTa0zkXMUv/GKxNeU8W1qrsw=" + }, + "semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "dev": true + }, + "shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "dev": true, + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", + "dev": true + }, + "signal-exit": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", + "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", + "dev": true + }, + "slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true + }, + "slice-ansi": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-2.1.0.tgz", + "integrity": "sha512-Qu+VC3EwYLldKa1fCxuuvULvSJOKEgk9pi8dZeCVK7TqBfUNTH4sFkk4joj8afVSfAYgJoSOetjx9QWOJ5mYoQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.0", + "astral-regex": "^1.0.0", + "is-fullwidth-code-point": "^2.0.0" + } + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + }, + "sourcemap-codec": { + "version": "1.4.6", + "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.6.tgz", + "integrity": "sha512-1ZooVLYFxC448piVLBbtOxFcXwnymH9oUF8nRd3CuYDVvkRBxRl6pB4Mtas5a4drtL+E8LDgFkQNcgIw6tc8Hg==", + "dev": true + }, + "sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", + "dev": true + }, + "string-width": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", + "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", + "dev": true, + "requires": { + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^4.0.0" + }, + "dependencies": { + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "dev": true, + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, + "strip-ansi": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", + "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "dev": true, + "requires": { + "ansi-regex": "^4.1.0" + }, + "dependencies": { + "ansi-regex": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", + "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "dev": true + } + } + }, + "strip-json-comments": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.0.1.tgz", + "integrity": "sha512-VTyMAUfdm047mwKl+u79WIdrZxtFtn+nBxHeb844XBQ9uMNTuTHdx2hc5RiAJYqwTj3wc/xe5HLSdJSkJ+WfZw==", + "dev": true + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "table": { + "version": "5.4.5", + "resolved": "https://registry.npmjs.org/table/-/table-5.4.5.tgz", + "integrity": "sha512-oGa2Hl7CQjfoaogtrOHEJroOcYILTx7BZWLGsJIlzoWmB2zmguhNfPJZsWPKYek/MgCxfco54gEi31d1uN2hFA==", + "dev": true, + "requires": { + "ajv": "^6.10.2", + "lodash": "^4.17.14", + "slice-ansi": "^2.1.0", + "string-width": "^3.0.0" + }, + "dependencies": { + "string-width": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", + "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "dev": true, + "requires": { + "emoji-regex": "^7.0.1", + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^5.1.0" + } + } + } + }, + "text-table": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", + "integrity": "sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=", + "dev": true + }, + "through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", + "dev": true + }, + "tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "dev": true, + "requires": { + "os-tmpdir": "~1.0.2" + } + }, + "to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", + "dev": true + }, + "to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "requires": { + "is-number": "^7.0.0" + } + }, + "trim-right": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", + "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=", + "dev": true + }, + "tslib": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.10.0.tgz", + "integrity": "sha512-qOebF53frne81cf0S9B41ByenJ3/IuH8yJKngAX35CmiZySA0khhkovshKK+jGCaMnVomla7gVlIcc3EvKPbTQ==", + "dev": true + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "requires": { + "prelude-ls": "~1.1.2" + } + }, + "union": { + "version": "0.4.6", + "resolved": "https://registry.npmjs.org/union/-/union-0.4.6.tgz", + "integrity": "sha1-GY+9rrolTniLDvy2MLwR8kopWeA=", + "requires": { + "qs": "~2.3.3" + } + }, + "universalify": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", + "dev": true + }, + "uri-js": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz", + "integrity": "sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==", + "dev": true, + "requires": { + "punycode": "^2.1.0" + } + }, + "url-join": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/url-join/-/url-join-2.0.5.tgz", + "integrity": "sha1-WvIvGMBSoACkjXuCxenC4v7tpyg=" + }, + "v8-compile-cache": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.0.3.tgz", + "integrity": "sha512-CNmdbwQMBjwr9Gsmohvm0pbL954tJrNzf6gWL3K+QMQf00PF7ERGrEiLgjuU3mKreLC2MeGhUsNV9ybTbLgd3w==", + "dev": true + }, + "which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + }, + "wordwrap": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.3.tgz", + "integrity": "sha1-o9XabNXAvAAI03I0u68b7WMFkQc=" + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "write": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/write/-/write-1.0.3.tgz", + "integrity": "sha512-/lg70HAjtkUgWPVZhZcm+T4hkL8Zbtp1nFNOn3lRrxnlv50SRBv7cR7RqR+GMsd3hUXy9hWBo4CHTbFTcOYwig==", + "dev": true, + "requires": { + "mkdirp": "^0.5.1" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..1df3b9f --- /dev/null +++ b/package.json @@ -0,0 +1,36 @@ +{ + "name": "@typelikeme/chrome-extenstion", + "version": "1.0.0", + "description": "Chrome extention for leveraging text predictions based on machine learning models trained via typelike.me", + "main": "src/js/index.ts", + "repository": { + "type": "git", + "url": "git+https://github.com/typelikeme/chrome-extension.git" + }, + "keywords": [ + "text", + "prediction", + "machine", + "learning", + "tensorflow", + "chrome", + "extenstion" + ], + "author": "Sergiu Ionescu", + "license": "MIT", + "bugs": { + "url": "https://github.com/typelikeme/chrome-extension/issues" + }, + "homepage": "https://github.com/typelikeme/chrome-extension#readme", + "devDependencies": { + "@babel/core": "^7.5.5", + "rollup": "^1.17.0", + "rollup-plugin-babel-minify": "^9.0.0", + "rollup-plugin-copy": "^3.1.0", + "rollup-plugin-eslint": "^7.0.0", + "rollup-plugin-node-resolve": "^5.2.0" + }, + "dependencies": { + "@typelikeme/tlmjs": "^1.0.3" + } +} diff --git a/rollup.config.js b/rollup.config.js new file mode 100644 index 0000000..7b00513 --- /dev/null +++ b/rollup.config.js @@ -0,0 +1,22 @@ +import { eslint } from 'rollup-plugin-eslint'; +import resolve from 'rollup-plugin-node-resolve'; + +export default { + input: 'src/js/index.ts', + output: { + file: 'dist/js/content.js', + format: 'iife', + name: 'tlmcontent' + }, + plugins: [ + resolve({ + mainFields: ['jsnext', 'module', 'main', 'browser'], + browser: true + }), + eslint({ + exclude: [ + 'src/styles/**', + ] + }) + ] +}; \ No newline at end of file diff --git a/src/js/index.ts b/src/js/index.ts new file mode 100644 index 0000000..e4d7a78 --- /dev/null +++ b/src/js/index.ts @@ -0,0 +1,29 @@ +import { Tlm } from "@typelikeme/tlmjs/src/js/tlm"; + +let tlm = []; + +chrome.storage.local.get( + ["active", "key", "attachInput", "attachTextarea"], + function(result) { + let isActive = result.active; + let key = result.key; + let attachToInput = result.attachInput; + let attachToTextarea = result.attachTextarea; + + if (isActive) { + let tlm = new Tlm(key); + if (attachToTextarea) { + let textareaList = document.getElementsByTagName("textarea"); + for (var i = 0; i < textareaList.length; i++) { + tlm.attach(textareaList[i]); + } + } + if (attachToInput) { + let inputList = document.querySelectorAll("input[type=text]"); + for (var i = 0; i < inputList.length; i++) { + tlm.attach(inputList[i]); + } + } + } + } +); diff --git a/tests/index.html b/tests/index.html new file mode 100644 index 0000000..499d7da --- /dev/null +++ b/tests/index.html @@ -0,0 +1,9 @@ + + + + + + + + +