!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.faceapi=t.faceapi||{})}(this,function(t){"use strict";var r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};function s(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var n=Object.assign||function(t){for(var e,n=1,r=arguments.length;na[0]&&e[1]i)&&1===t[i]&&(n.push(t[i]),r.push(i)),e[o]<=i&&o++}1!==t[i]&&(n.push(t[i]),r.push(i))}return{newShape:n,keptDims:r}}function b(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 x(t,e,n){if("float32"===e)for(var r=0;r {...}) to avoid memory leaks.");return this.keepTensors.add(t.id),t},t.prototype.startScope=function(t,e){void 0===e&&(e=!1),e&&0===this.gradientScopeCount&&(this.activeTape=[]),e&&this.gradientScopeCount++;var n={track:[],name:"unnamed scope"};t&&(n.name=t),this.scopeStack.push(n),this.activeScope=n},t.prototype.endScope=function(t,e){var n=this;void 0===e&&(e=!1),e&&(this.gradientScopeCount--,0===this.gradientScopeCount&&(this.activeTape=null));var r=new Set(this.keepTensors),o=tt(t);o.forEach(function(t){return r.add(t.id)});for(var i=0;i {op();...}); to avoid memory leaks.");return this.activeScope.track.push(t),t},t}();(nt=et||(et={}))[nt.NUMBER=0]="NUMBER",nt[nt.BOOLEAN=1]="BOOLEAN",nt[nt.STRING=2]="STRING";var ot,it=[{name:"DEBUG",type:et.BOOLEAN},{name:"IS_BROWSER",type:et.BOOLEAN},{name:"WEBGL_PACK_BATCHNORMALIZATION",type:et.BOOLEAN},{name:"WEBGL_CONV_IM2COL",type:et.BOOLEAN},{name:"WEBGL_MAX_TEXTURE_SIZE",type:et.NUMBER},{name:"WEBGL_PAGING_ENABLED",type:et.BOOLEAN},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",type:et.NUMBER},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",type:et.BOOLEAN},{name:"WEBGL_VERSION",type:et.NUMBER},{name:"WEBGL_RENDER_FLOAT32_ENABLED",type:et.BOOLEAN},{name:"WEBGL_DOWNLOAD_FLOAT_ENABLED",type:et.BOOLEAN},{name:"WEBGL_FENCE_API_ENABLED",type:et.BOOLEAN},{name:"WEBGL_SIZE_UPLOAD_UNIFORM",type:et.NUMBER},{name:"BACKEND",type:et.STRING},{name:"EPSILON",type:et.NUMBER},{name:"PROD",type:et.BOOLEAN},{name:"TENSORLIKE_CHECK_SHAPE_CONSISTENCY",type:et.BOOLEAN}];function at(t,e){var n;try{n=lt(t,e)}catch(t){return!1}return null!=n&&(ht(n),!0)}var st="tfjsflags";function ut(){var e={};if("undefined"==typeof window||void 0===window.location)return e;var t,a,n=(t=window.location.search,a={},t.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,function(t){for(var e=[],n=1;nt.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,i=0;i=l[e]:r<=l[e]);r+=o[e])n+=1;return n}),[c,f,h]}function jt(t,e,n,r,o){var i=e[o];t&1<o}).sort(function(t,e){return e.score-t.score}),a=[],s=0;s=r){h=!0;break}if(!h&&(a.push(l),a.length>=n))break}return re(a,"int32")}function Fe(t,e,n){var r=t.subarray(4*e,4*e+4),o=t.subarray(4*n,4*n+4),i=Math.min(r[0],r[2]),a=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),c=Math.min(o[0],o[2]),l=Math.min(o[1],o[3]),h=Math.max(o[0],o[2]),p=Math.max(o[1],o[3]),f=(s-i)*(u-a),d=(h-c)*(p-l);if(f<=0||d<=0)return 0;var m=Math.max(i,c),v=Math.max(a,l),g=Math.min(s,h),y=Math.min(u,p),x=Math.max(g-m,0)*Math.max(y-v,0);return x/(f+d-x)}function Le(n,t,r){var o=Array(n.rank).fill(0),i=n.shape.slice();return t.map(function(t){i[r]=t;var e=n.slice(o,i);return o[r]+=t,e})}function Be(t,e,n,r,o){for(var i=e[e.length-1],a=[t.length/i,i],s=a[0],u=a[1],c=b(n,s*r),l=b("int32",s*r),h=0;h":"<",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 "},We=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,i=t.dilationHeight,a=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,c=s-1-t.padInfo.top,l=u-1-t.padInfo.left,h=1/(e*n);this.userCode="\n const ivec2 pads = ivec2("+c+", "+l+");\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 += "+i+") {\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+= "+a+") {\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 "};function Ue(t,e){for(var n=t.length,r=[],o=0;o= "+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 "},rn=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,i=e-1-t.padInfo.top,a=n-1-t.padInfo.left;this.userCode="\n const ivec2 pads = ivec2("+i+", "+a+");\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 "},on=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,i=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 * "+i+" + 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 "},an=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,i=e-1-t.padInfo.top,a=n-1-t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode="\n const ivec2 pads = ivec2("+i+", "+a+");\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 "},sn=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,i=t.dilationHeight,a=t.dilationWidth,s=t.filterHeight,u=t.filterWidth,c=4*Math.floor(t.inChannels/4),l=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 * "+i+";\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 * "+a+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+c+"; 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===l)+") {\n dotProd +=\n getX(batch, xR, xC, "+c+") *\n getW(wR, wC, "+c+", d2);\n } else if ("+(2===l)+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+c+"),\n getX(batch, xR, xC, "+c+" + 1)\n );\n vec2 wValues = vec2(\n getW(wR, wC, "+c+", d2),\n getW(wR, wC, "+c+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===l)+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+c+"),\n getX(batch, xR, xC, "+c+" + 1),\n getX(batch, xR, xC, "+c+" + 2)\n );\n vec3 wValues = vec3(\n getW(wR, wC, "+c+", d2),\n getW(wR, wC, "+c+" + 1, d2),\n getW(wR, wC, "+c+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n setOutput(dotProd);\n }\n "},un=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,i=t.strideHeight,a=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,c=t.filterHeight,l=t.filterWidth,h=t.outChannels/t.inChannels;this.userCode="\n const ivec2 strides = ivec2("+i+", "+a+");\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 < "+c+"; wR++) {\n int xR = xRCorner + wR * "+s+";\n\n if (xR < 0 || xR >= "+e+") {\n continue;\n }\n\n for (int wC = 0; wC < "+l+"; 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 "},cn=function(t,e,n,r,o){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var i=t[0],a=t[1],s=t[2],u=t[3],c=e[0],l=n[0],h=n[1];this.outputShape=[c,l,h,u];var p="bilinear"===r?1:0,f=[a-1+".0",s-1+".0"],d=f[0],m=f[1],v=1= "+i+") {\n return;\n }\n\n float height_scale = "+y+";\n float width_scale = "+E+";\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 = "+S+";\n if( in_x < 0.0 || in_x > "+m+" ) {\n setOutput(float("+o+"));\n return;\n }\n\n vec2 sourceFracIndexRC = vec2(in_y,in_x);\n if("+p+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(ceil(sourceFracIndexRC));\n\n float topLeft = getImage(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getImage(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getImage(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getImage(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 setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(floor(\n sourceFracIndexRC + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestRC.x, sourceNearestRC.y, d);\n setOutput(newValue);\n }\n }\n "};function ln(t,i,e,a){var n=t.map(function(t){var e=B(t.shapeInfo.logicalShape);return t.shapeInfo.isUniform?"uniform float "+t.name+(1";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+o+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+vn(r)+" coords = getOutputCoords();\n int end = "+bn(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 "+i+" end) {\n continue;\n }\n if (idx == end && "+e+") {\n continue;\n }\n "+bn(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 bn(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 wn=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}(),En=function(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\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\n void main() {\n float x = getAAtOutCoords();\n gl_FragColor = encode_float(x);\n }\n "},Sn="return real * expR - imag * expI;",_n="return real * expI + imag * expR;",Cn=function(t,e){this.variableNames=["real","imag"];var n=e[1];this.outputShape=e,this.userCode="\n const float negativeTwoPi = -2.0 * 3.1415926535897932384626433832795;\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("+n+");\n float negativeTwoPiTimesIndexRatio = negativeTwoPi * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < "+n+"; i++) {\n // x = (-2 * PI / N) * index * i;\n float x = negativeTwoPiTimesIndexRatio * 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 += unaryOpComplex(real, expR, imag, expI);\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n "},Rn=function(t){this.variableNames=["A"];var e=t[0],n=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("+n+".0, "+e+".0);\n\n vec4 values = 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 "},Tn=function(t,e,n){this.variableNames=["A","indices"];var r=t.slice();r[n]=e,this.outputShape=r,this.rank=r.length;var o=vn(this.rank),i=function(t,e){var n=t.length;if(4= "+r);for(var o=0,i=0;i=n.length-2?_(n[e]):n[e]})),2!==n.length){var r=y(n);n=r.newShape}var o=B(n);return n.length<=1&&o<=e?[o,1]:2===n.length&&n[0]<=e&&n[1]<=e?n:3===n.length&&n[0]*n[1]<=e&&n[2]<=e?[n[0]*n[1],n[2]]:3===n.length&&n[0]<=e&&n[1]*n[2]<=e?[n[0],n[1]*n[2]]:4===n.length&&n[0]*n[1]*n[2]<=e&&n[3]<=e?[n[0]*n[1]*n[2],n[3]]:4===n.length&&n[0]<=e&&n[1]*n[2]*n[3]<=e?[n[0],n[1]*n[2]*n[3]]:p(o)}var vr=Object.freeze({createWebGLRenderingContext:Bn,createWebGLRenderingContextFromCanvas:zn,callAndCheck:Wn,enableDebugWebGLErrorChecking:Vn,checkWebGLError:Gn,getWebGLErrorMessage:qn,getExtensionOrThrow:jn,createVertexShader:Hn,createFragmentShader:$n,createProgram:Xn,linkProgram:Yn,validateProgram:Qn,createStaticVertexBuffer:Jn,createStaticIndexBuffer:Zn,getNumChannels:tr,createTexture:er,validateTextureSize:nr,createFramebuffer:rr,bindVertexBufferToProgramAttribute:or,bindTextureUnit:ir,unbindTextureUnit:function(t,e){dr(t,e),Wn(t,function(){return t.activeTexture(t.TEXTURE0+e)}),Wn(t,function(){return t.bindTexture(t.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:ar,getProgramUniformLocation:sr,bindTextureToProgramUniformSampler:ur,bindCanvasToFramebuffer:function(t){Wn(t,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)}),Wn(t,function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)}),Wn(t,function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)})},bindColorTextureToFramebuffer:cr,unbindColorTextureFromFramebuffer:lr,validateFramebuffer:hr,getFramebufferErrorMessage:pr,getTextureShapeFromLogicalShape:mr});function gr(){return{alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0}}function yr(t){var e,n={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};return Wn(e=null!=t?zn(t,n):Bn(n),function(){return e.disable(e.DEPTH_TEST)}),Wn(e,function(){return e.disable(e.STENCIL_TEST)}),Wn(e,function(){return e.disable(e.BLEND)}),Wn(e,function(){return e.disable(e.DITHER)}),Wn(e,function(){return e.disable(e.POLYGON_OFFSET_FILL)}),Wn(e,function(){return e.disable(e.SAMPLE_COVERAGE)}),Wn(e,function(){return e.enable(e.SCISSOR_TEST)}),Wn(e,function(){return e.enable(e.CULL_FACE)}),Wn(e,function(){return e.cullFace(e.BACK)}),e}function xr(t){return Hn(t,"\n precision highp float;\n attribute vec3 clipSpacePos;\n attribute vec2 uv;\n varying vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function br(t){return Jn(t,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function wr(t){return Zn(t,new Uint16Array([0,1,2,2,1,3]))}function Er(t,e){var n,r,o,i,a,s,u,c=t;return 2===mt.get("WEBGL_VERSION")?(n=c.R32F,r=c.R16F,o=c.RGBA32F,i=c.RED,a=4,s=1,u=c.HALF_FLOAT):(n=t.RGBA,r=t.RGBA,o=c.RGBA,i=t.RGBA,s=a=4,u=null!=e?e.HALF_FLOAT_OES:null),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedFloat:o,textureFormatFloat:i,downloadTextureFormat:t.RGBA,downloadUnpackNumChannels:a,defaultNumChannels:s,textureTypeHalfFloat:u}}function Sr(t,e,n,r,o,i){nr(e,n);var a=er(t),s=t.TEXTURE_2D;return Wn(t,function(){return t.bindTexture(s,a)}),Wn(t,function(){return t.texParameteri(s,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)}),Wn(t,function(){return t.texParameteri(s,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)}),Wn(t,function(){return t.texParameteri(s,t.TEXTURE_MIN_FILTER,t.NEAREST)}),Wn(t,function(){return t.texParameteri(s,t.TEXTURE_MAG_FILTER,t.NEAREST)}),Wn(t,function(){return t.texImage2D(s,0,r,e,n,0,o,i,null)}),Wn(t,function(){return t.bindTexture(t.TEXTURE_2D,null)}),a}function _r(t,e,n,r){var o=Mn(e,n);return Sr(t,o[0],o[1],r.internalFormatFloat,r.textureFormatFloat,t.FLOAT)}function Cr(t,e,n,r){var o=Mn(e,n);return Sr(t,o[0],o[1],r.internalFormatFloat,r.textureFormatFloat,r.textureTypeHalfFloat)}function Rr(t,e,n,r){var o=Mn(e,n);return Sr(t,o[0],o[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function Tr(t,e,n,r){var o=Fn(e,n);return Sr(t,o[0],o[1],r.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function kr(t,e,n,r){var o=Fn(e,n);return Sr(t,o[0],o[1],r.internalFormatHalfFloat,t.RGBA,r.textureTypeHalfFloat)}function Ir(t,e,n){return Wn(t,function(){return t.bindBuffer(t.ARRAY_BUFFER,n)}),or(t,e,"clipSpacePos",n,3,20,0)&&or(t,e,"uv",n,2,20,12)}function Dr(t,e,n){Wn(t,function(){return t.bindTexture(t.TEXTURE_2D,e)}),Wn(t,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,n)}),Wn(t,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function Nr(t,e,n,r,o,i){nr(n,r),Wn(t,function(){return t.bindTexture(t.TEXTURE_2D,e)}),Wn(t,function(){return t.texSubImage2D(t.TEXTURE_2D,0,0,0,n,r,i,t.FLOAT,o)}),Wn(t,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function Ar(t,e,n,r,o,i,a){var s,u=Mn(n,r),c=u[0],l=u[1];1===a.defaultNumChannels?s=o:function(t,e,n){var r=On(t.length,n);if(e.length= "+r);for(var o=0,i=0;i=\n "+i);for(var a=r%2==1,s=n%2==1,u=Math.floor(r/2),c=Math.floor(n/2),l=Math.ceil(r/2),h=l*Math.ceil(n/2),p=_(n)*_(r),f=0;f= "+i);for(var a=r%2==1,s=n%2==1,u=Math.floor(r/2),c=Math.floor(n/2),l=Math.ceil(r/2),h=l*Math.ceil(n/2),p=_(n)*_(r),f=0;f>1;t[o]()?e=(r=o)+1:n=o-1}return r}(this.itemsToPoll.map(function(t){return t.isDoneFn})),e=0;e<=t;++e)(0,this.itemsToPoll[e].resolveFn)();this.itemsToPoll=this.itemsToPoll.slice(t+1)},t.prototype.addItemToPoll=function(t,e){var n=this;this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),1= "+t[1]+" || pos >= "+t[0]+") continue;\n\n int offsetY = int(blockIndex / ("+u+")) * "+a+" - "+p+";\n int d0 = offsetY + "+l+" * (pos / "+f+");\n\n if(d0 >= "+e[0]+" || d0 < 0) continue;\n\n int offsetX = int(mod(float(blockIndex), "+u+".) * "+i+". - "+h+".);\n int d1 = offsetX + "+c+" * (int(mod(float(pos), "+f+".) / "+o+".));\n\n if(d1 >= "+e[1]+" || d1 < 0) continue;\n\n result[row * 2 + col] = getA(d0, d1, int(mod(float(pos), "+o+".)));\n }\n }\n\n gl_FragColor = result;\n }\n "},Gr=function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[];var i,a=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";i=.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 = -"+a+"; j <= "+a+"; 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 * "+i+";\n setOutput(val);\n }\n "},qr=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 "},jr=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,o=t.effectiveFilterHeight,i=t.effectiveFilterWidth,a=o-1-t.padInfo.top,s=i-1-t.padInfo.left,u=o*i-1;this.userCode="\n const ivec2 pads = ivec2("+a+", "+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 < "+i+"; 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 * "+i+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "},Hr=function(t,e,n,r){void 0===n&&(n=!1),void 0===r&&(r=!1),this.variableNames=["matrixA","matrixB"];var o=t[0],i=n?t[2]:t[1],a=r?e[1]:e[2],s=n?t[1]:t[2];this.outputShape=[o,i,a];var u=function(t,e){return n?"batch, "+e+" + "+t+", aRow":"batch, aRow, "+e+" + "+t},c=function(t,e){return r?"batch, bCol, "+e+" + "+t:"batch, "+e+" + "+t+", bCol"},l=4*Math.floor(s/4),h=s%4;this.userCode=" float dotARowBCol(int batch, int aRow, int bCol) {\n float result = 0.0;\n for (int i = 0; i < "+l+"; i += 4) {\n vec4 a = vec4(\n getMatrixA("+u(0,"i")+"),\n getMatrixA("+u(1,"i")+"),\n getMatrixA("+u(2,"i")+"),\n getMatrixA("+u(3,"i")+")\n );\n vec4 b = vec4(\n getMatrixB("+c(0,"i")+"),\n getMatrixB("+c(1,"i")+"),\n getMatrixB("+c(2,"i")+"),\n getMatrixB("+c(3,"i")+")\n );\n\n result += dot(a, b);\n }\n\n if ("+(1===h)+") {\n result += getMatrixA("+u(0,l)+") *\n getMatrixB("+c(0,l)+");\n } else if ("+(2===h)+") {\n vec2 a = vec2(\n getMatrixA("+u(0,l)+"),\n getMatrixA("+u(1,l)+")\n );\n vec2 b = vec2(\n getMatrixB("+c(0,l)+"),\n getMatrixB("+c(1,l)+")\n );\n result += dot(a, b);\n } else if ("+(3===h)+") {\n vec3 a = vec3(\n getMatrixA("+u(0,l)+"),\n getMatrixA("+u(1,l)+"),\n getMatrixA("+u(2,l)+")\n );\n vec3 b = vec3(\n getMatrixB("+c(0,l)+"),\n getMatrixB("+c(1,l)+"),\n getMatrixB("+c(2,l)+")\n );\n result += dot(a, b);\n }\n\n return result;\n }\n\n void main() {\n ivec3 resBRC = getOutputCoords();\n setOutput(dotARowBCol(resBRC.x, resBRC.y, resBRC.z));\n }\n "},$r=function(t,e,n,r,o){void 0===r&&(r=!1),void 0===o&&(o=!1),this.variableNames=["matrixA","matrixB"],this.usesPackedTextures=!0,this.outputShape=n;var i=r?t[0]:t[1],a=Math.ceil(i/2),s=r?"i * 2, rc.x":"rc.x, i * 2",u=o?"rc.y, i * 2":"i * 2, rc.y",c=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],l=o?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];this.userCode="\n const float sharedDimension = "+a+".0;\n\n vec4 dot2x2ARowBCol(ivec2 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+a+"; i++) {\n vec4 a = getMatrixA("+s+");\n vec4 b = getMatrixB("+u+");\n\n result += ("+c[0]+" * "+l[0]+") + ("+c[1]+" * "+l[1]+");\n }\n return result;\n }\n\n void main() {\n ivec2 rc = getOutputCoords();\n setOutput(dot2x2ARowBCol(rc));\n }\n "},Kr=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(n){var r=this;return function(t,e){null==r.seedLoc&&(r.seedLoc=t.getUniformLocation(e,"seed")),t.gl.uniform1f(r.seedLoc,n)}},t}(),Xr=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 "};function Yr(e){return["x","y","z","w"].map(function(t){return e+"."+t})}function Qr(t,e){return e.slice(0,t).slice(-2)}var Jr=function(t){this.variableNames=["A"];var e,n,r,o,i=(this.outputShape=t).length,a=Yr("rc"),s=vn(i),u=function(t,e,n){if(1===t)return"rc > "+e[0];for(var r="",o=0;o= "+e[o],o= "+e+";\n bool rEdge = rp1 >= "+n+";\n "}(i,t[t.length-1],t[t.length-2],a),l=(n=a,r=(e=t).length,o=function(t,e){for(var n=[],r=0;r<=1;r++)for(var o=0;o<=1;o++){for(var i=(0===r?"r":"rp1")+", "+(0===o?"c":"cp1"),a=2;a= "+e[0]+" ? 0. : getA(rc + 1),\n 0, 0":"getA("+o[0]+"),\n cEdge ? 0. : getA("+o[1]+"),\n rEdge ? 0. : getA("+o[2]+"),\n rEdge || cEdge ? 0. : getA("+o[3]+")");this.userCode="\n void main() {\n "+s+" rc = getOutputCoords();\n\n if("+u+") {\n gl_FragColor = vec4(0);\n } else {\n "+c+"\n\n setOutput(vec4("+l+"));\n }\n }\n "};var Zr=function(n,t,e){this.variableNames=["x"],this.outputShape=t.map(function(t,e){return t[0]+n[e]+t[1]});var r=n.length,o=vn(r),i=t.map(function(t){return t[0]}).join(","),a=t.map(function(t,e){return t[0]+n[e]}).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n "+o+" start = "+o+"("+i+");\n "+o+" end = "+o+"("+a+");\n\n void main() {\n "+o+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+e+"));\n } else {\n "+o+" coords = outC - start;\n setOutput(getX("+s+"));\n }\n }\n ":"\n int start = "+i+";\n int end = "+a+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+e+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "},to=function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var r=t.filterWidth,o=t.strideHeight,i=t.strideWidth,a=t.dilationHeight,s=t.dilationWidth,u=t.effectiveFilterHeight,c=t.effectiveFilterWidth,l=t.padInfo.top,h=t.padInfo.left;this.outputShape=t.outShape;var p="avg"===e,f="0.0";if(p||(f="-1.0 / 0.0"),n)this.userCode="\n const ivec2 strides = ivec2("+o+", "+i+");\n const ivec2 pads = ivec2("+l+", "+h+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < "+u+";\n wR += "+a+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+c+";\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 * "+c+" + 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 m=4*Math.floor(r/4),v=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+", "+i+");\n const ivec2 pads = ivec2("+l+", "+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 += "+a+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+m+"; 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 + "+m+";\n if ("+(1===v)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+g+"\n } else if ("+(2===v)+") {\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===v)+") {\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 "}},eo=function(t,e){this.variableNames=["x"];var n=t.windowSize,r=t.batchSize,o=t.inSize,i=Math.ceil(o/n);this.outputShape=[r,i];var a="0.0",s="";"prod"===e?a="1.0":"min"===e?(a="1.0 / 0.0",s="min"):"max"===e&&(a="-1.0 / 0.0",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 c=4*Math.floor(n/4),l=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?(a="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&&(a="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="";0= "+o+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+a+";\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("+a+");\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 < "+c+"; 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 + "+c+";\n if ("+(1===l)+") {\n "+p+" values = "+p+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+h+"\n } else if ("+(2===l)+") {\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===l)+") {\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 "},no=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],i=r[2],a=t.shape,s=a[1],u=a[2],c=[n&&1= "+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), "+(i-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 "},ro=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],i=t[1],a=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&1= "+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("+c[0]+") *\n (float(dyR) / float("+l[0]+"));\n\n float sourceFracCol =\n float("+c[1]+") *\n (float(dyC) / float("+l[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("+i+") - 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 "},io=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],i=t[1],a=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&1= 1.0) {\n setOutput(getA("+o+"));\n } else {\n setOutput(getB("+o+"));\n }\n }\n "},lo=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e=vn(this.rank),n=function(t){if(1===t)return"sourceLoc";if(2===t)return"sourceLoc.x, sourceLoc.y";if(3===t)return"sourceLoc.x, sourceLoc.y, sourceLoc.z";if(4===t)return"sourceLoc.x, sourceLoc.y, sourceLoc.z, sourceLoc.w";throw Error("Slicing for rank "+t+" is not yet supported")}(this.rank);this.userCode="\n uniform "+e+" start;\n\n void main() {\n "+e+" sourceLoc = start + getOutputCoords();\n setOutput(getSource("+n+"));\n }\n "}return t.prototype.getCustomSetupFunc=function(n){var r=this;if(n.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+n.length+")");return function(t,e){if(null!=r.startLoc||(r.startLoc=t.getUniformLocationNoThrow(e,"start"),null!=r.startLoc))if(1===r.rank)t.gl.uniform1i(r.startLoc,n[0]);else if(2===r.rank)t.gl.uniform2i(r.startLoc,n[0],n[1]);else if(3===r.rank)t.gl.uniform3i(r.startLoc,n[0],n[1],n[2]);else{if(4!==r.rank)throw Error("Slicing for rank "+r.rank+" is not yet supported");t.gl.uniform4i(r.startLoc,n[0],n[1],n[2],n[3])}}},t}();var ho=function(t,e,n,r){this.variableNames=["x"];var o=n.filter(function(t,e){return-1===r.indexOf(e)});this.outputShape=o;var i=n.length,a=vn(n.length),s=vn(o.length),u="";if(1===i)u="coords * strides + begin";else{var c=0;u=n.map(function(t,e){return-1===r.indexOf(e)?(c++,1===o.length?"coords * strides["+e+"] + begin["+e+"]":"coords["+(c-1)+"] * strides["+e+"] + begin["+e+"]"):"begin["+e+"]"}).join(",")}this.userCode="\n "+a+" begin = "+a+"("+t+");\n "+a+" strides = "+a+"("+e+");\n\n void main() {\n "+s+" coords = getOutputCoords();\n setOutput(getX("+u+"));\n }\n "},po=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=fo(e,n),i=mo(t,o,n);if(i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]),0>>0,r=(n*=r)>>>0,r+=4294967296*(n-=r)}return 2.3283064365386963e-10*(r>>>0)});e.next=function(){var t=2091639*e.s0+2.3283064365386963e-10*e.c;return e.s0=e.s1,e.s1=e.s2,e.s2=t-(e.c=0|t)},e.c=1,e.s0=n(" "),e.s1=n(" "),e.s2=n(" "),e.s0-=n(t),e.s0<0&&(e.s0+=1),e.s1-=n(t),e.s1<0&&(e.s1+=1),e.s2-=n(t),e.s2<0&&(e.s2+=1),n=null}(t),r=e&&e.state,o=n.next;return o.int32=function(){return 4294967296*n.next()|0},o.double=function(){return o()+11102230246251565e-32*(2097152*o()|0)},o.quick=o,r&&("object"==typeof r&&i(r,n),o.state=function(){return i(n,{})}),o}e&&e.exports?e.exports=r:this.alea=r}(0,t)}),No=Io(function(t){!function(t,e,n){function i(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function r(t,e){var n=new function(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 o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,r&&("object"==typeof r&&i(r,n),o.state=function(){return i(n,{})}),o}e&&e.exports?e.exports=r:this.xor128=r}(0,t)}),Ao=Io(function(t){!function(t,e,n){function i(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 r(t,e){var n=new function(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,t===((e.v=0)|t)?e.x=t:n+=t;for(var r=0;r>>4),e.next()}(t),r=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,r&&("object"==typeof r&&i(r,n),o.state=function(){return i(n,{})}),o}e&&e.exports?e.exports=r:this.xorwow=r}(0,t)}),Mo=Io(function(t){!function(t,e,n){function i(t,e){return e.x=t.x.slice(),e.i=t.i,e}function r(t,e){null==t&&(t=+new Date);var n=new function(t){var o=this;o.next=function(){var t,e,n=o.x,r=o.i;return t=n[r],e=(t^=t>>>7)^t<<24,e^=(t=n[r+1&7])^t>>>10,e^=(t=n[r+3&7])^t>>>3,e^=(t=n[r+4&7])^t<<7,t=n[r+7&7],e^=(t^=t<<13)^t<<9,n[r]=e,o.i=r+1&7,e},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,r&&(r.x&&i(r,n),o.state=function(){return i(n,{})}),o}e&&e.exports?e.exports=r:this.xorshift7=r}(0,t)}),Oo=Io(function(t){!function(t,e,n){function i(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function r(t,e){null==t&&(t=+new Date);var n=new function(t){var i=this;i.next=function(){var t,e,n=i.w,r=i.X,o=i.i;return i.w=n=n+1640531527|0,e=r[o+34&127],t=r[o=o+1&127],e^=e<<13,t^=t<<17,e^=e>>>15,t^=t>>>12,e=r[o]=e^t,i.i=o,e+(n^n>>>16)|0},function(t,e){var n,r,o,i,a,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),o=0,i=-32;i>>15,r^=r<<4,r^=r>>>13,0<=i&&(a=a+1640531527|0,o=0==(n=s[127&i]^=r+a)?o+1:0);for(128<=o&&(s[127&(e&&e.length||0)]=-1),o=127,i=512;0>>15,n^=n>>>12,s[o]=r^n;t.w=a,t.X=s,t.i=o}(i,t)}(t),r=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,r&&(r.X&&i(r,n),o.state=function(){return i(n,{})}),o}e&&e.exports?e.exports=r:this.xor4096=r}(0,t)}),Po=Io(function(t){!function(t,e,n){function i(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function r(t,e){var n=new function(t){var o=this,e="";o.next=function(){var t=o.b,e=o.c,n=o.d,r=o.a;return t=t<<25^t>>>7^e,e=e-n|0,n=n<<24^n>>>8^r,r=r-t|0,o.b=t=t<<20^t>>>12^e,o.c=e=e-n|0,o.d=n<<16^e>>>16^r,o.a=r-t|0},o.a=0,o.b=0,o.c=-1640531527,o.d=1367130551,t===Math.floor(t)?(o.a=t/4294967296|0,o.b=0|t):e+=t;for(var n=0;n>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,r&&("object"==typeof r&&i(r,n),o.state=function(){return i(n,{})}),o}e&&e.exports?e.exports=r:this.tychei=r}(0,t)}),Fo=Io(function(e){!function(s,u){var c,l=this,h=256,p=6,f="random",d=u.pow(h,p),m=u.pow(2,52),v=2*m,g=h-1;function t(t,e,n){var r=[],o=x(function t(e,n){var r,o=[],i=typeof e;if(n&&"object"==i)for(r in e)try{o.push(t(e[r],n-1))}catch(t){}return o.length?o:"string"==i?e:e+"\0"}((e=1==e?{entropy:!0}:e||{}).entropy?[t,b(s)]:null==t?function(){try{var t;return c&&(t=c.randomBytes)?t=t(h):(t=new Uint8Array(h),(l.crypto||l.msCrypto).getRandomValues(t)),b(t)}catch(t){var e=l.navigator,n=e&&e.plugins;return[+new Date,l,n,l.screen,b(s)]}}():t,3),r),i=new function(t){var e,n=t.length,a=this,r=0,o=a.i=a.j=0,i=a.S=[];for(n||(t=[n++]);r>>=1;return(t+n)/e};return a.int32=function(){return 0|i.g(4)},a.quick=function(){return i.g(4)/4294967296},a.double=a,x(b(i.S),s),(e.pass||n||function(t,e,n,r){return r&&(r.S&&y(r,i),t.state=function(){return y(i,{})}),n?(u[f]=t,e):t})(a,o,"global"in e?e.global:this==u,e.state)}function y(t,e){return e.i=t.i,e.j=t.j,e.S=t.S.slice(),e}function x(t,e){for(var n,r=t+"",o=0;o=this.lower},t}();function zo(w,E){return m(this,void 0,void 0,function(){var e,n,r,o,i,a,s,u,c,l,h,p,f,d,m,v,g,y,x,b;return S(this,function(t){switch(t.label){case 0:if(2!==(e=Kt(w,"img","toPixels","int32")).rank&&3!==e.rank)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+e.rank+".");if(n=e.shape.slice(0,2),r=n[0],o=n[1],4<(i=2===e.rank?1:e.shape[2])||2===i)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+i);return a=e.min(),s=e.max(),[4,a.data()];case 1:return u=t.sent()[0],[4,s.data()];case 2:if(c=t.sent()[0],a.dispose(),s.dispose(),"float32"===e.dtype){if(u<0||1=1+e.length,"input rank is "+r.rank+" but should be > than blockShape.length "+e.length),D(n.length===e.length,"crops.length is "+n.length+" but should be equal to blockShape.length "+e.length),D(r.shape[0]%o==0,"input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+e.join(" * ")+" === "+o),mt.engine.runKernel(function(t){return t.batchToSpaceND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}})}}),Go=Yt({cast_:function(t,e){var n=Kt(t,"x","cast");return mt.engine.runKernel(function(t){return t.cast(n,e)},{$x:n},function(t){return{$x:function(){return t.clone()}}})}}),qo=Yt({clone_:function(t){var e=Kt(t,"x","clone");return mt.engine.runKernel(function(t){return Y.make(e.shape,{dataId:e.dataId},e.dtype)},{$x:e},function(t){return{$x:function(){return t.toFloat()}}})}}),jo=Yt({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var o=Kt(t,"x","cumsum"),i=Ft([e|=0],o.rank),a=o;null!=i&&(a=o.transpose(i));var s=Bt(1,o.rank)[0],u=mt.engine.runKernel(function(t){return t.cumsum(a,s,n,r)},{permutedX:a},function(t){return{permutedX:function(){return t.cumsum(e,n,!r)}}});return null!=i&&(u=u.transpose(i)),u}}),Ho=Yt({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=Kt(t,"x","depthToSpace"),o="NHWC"===n?r.shape[1]:r.shape[2],i="NHWC"===n?r.shape[2]:r.shape[3],a="NHWC"===n?r.shape[3]:r.shape[1];return D(0<=o*e,"Negative dimension size caused by overflow when multiplying\n "+o+" and "+e+" for depthToSpace with input shape\n "+r.shape),D(0<=i*e,"Negative dimension size caused by overflow when multiplying\n "+i+" and "+e+" for depthToSpace with input shape\n "+r.shape),D(a%(e*e)==0,"Dimension size must be evenly divisible by "+e*e+" but is "+a+" for depthToSpace with input shape "+r.shape),mt.engine.runKernel(function(t){return t.depthToSpace(r,e,n)},{$x:r})}}),$o=Yt({expandDims_:function(t,e){void 0===e&&(e=0);var n=Kt(t,"x","expandDims");D(e<=n.rank,"Axis must be <= rank of the tensor");var r=n.shape.slice();return e<0&&(D(-(n.rank+1)<=e,"Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]"),e=n.rank+e+1),r.splice(e,0,1),ai(n,r)}}),Ko=Yt({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var o=Wo([t,e],r),i=t<=e?t:e,a=0;a=2, but it is "+e);return mt.engine.runKernel(function(t){return t.oneHot(o,e,n,r)},{$indices:o},function(t){return{$indices:function(){return Te(o)}}})}}),Jo=Yt({pad_:function(t,e,n){void 0===n&&(n=0);var r=Kt(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 mt.engine.runKernel(function(t){return t.pad(r,e,n)},{$x:r},function(t){return{$x:function(){return t.slice(o,r.shape)}}})}}),Zo=Yt({pad1d_:function(t,e,n){return void 0===n&&(n=0),D(2===e.length,"Invalid number of paddings. Must be length of 2."),Jo(t,[e],n)}}),ti=Yt({pad2d_:function(t,e,n){return void 0===n&&(n=0),D(2===e.length&&2===e[0].length&&2===e[1].length,"Invalid number of paddings. Must be length of 2 each."),Jo(t,e,n)}}),ei=Yt({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,"Invalid number of paddings. Must be length of 2 each."),Jo(t,e,n)}}),ni=Yt({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,"Invalid number of paddings. Must be length of 2 each."),Jo(t,e,n)}}),ri=Yt({rand_:function(t,e,n){var r=B(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 i=0;i=1+r.length,"input rank "+e.rank+" should be > than [blockShape] "+r.length),D(o.length===r.length,"paddings.shape[0] "+o.length+" must be equal to [blockShape] "+r.length),D(e.shape.reduce(function(t,e,n){return 0 4 with a WebGL backend not implemented yet");var r=e.reduce(function(t,e){return t*e}),o=Rt(t.shape,e,r),i=Tt(o.length,e.length),a=kt(t.shape,e,r),s=It(n,e.length),u=Dt(a,n,e.length);return t.reshape(o).transpose(i).reshape(a).slice(s,u)},t.prototype.spaceToBatchND=function(t,e,n){D(t.rank<=4,"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 i=1+e.length;i b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r)},t.prototype.greaterEqual=function(t,e){var n=new Je("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 bo(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},t.prototype.logicalAnd=function(t,e){var n=new Je("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){var n=new Je("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 co(t.rank,e.shape,e.rank),o=this.makeOutputArray(r.outputShape,Ie(e.dtype,n.dtype));return this.compileAndRun(r,[t,e,n],o)},t.prototype.where=function(t){Ct("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return fi(t.shape,e)},t.prototype.topk=function(t,e,n){return Be(t.dataSync(),t.shape,t.dtype,e)},t.prototype.min=function(t,e){Pt("min",e,t.rank);var n=At(t.shape,e),r=n[0],o=B(n[1]),i=t.as2D(-1,o);return this.reduce(i,"min",i.dtype).reshape(r)},t.prototype.minimum=function(t,e){var n=new Je("\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=new Je("if (b == 0.0) return NAN;\n return mod(a, b);",t.shape,e.shape),r=n.getCustomSetupFunc();return this.compileAndRun(n,[t,e],null,r)},t.prototype.max=function(t,e){Pt("max",e,t.rank);var n=At(t.shape,e),r=n[0],o=B(n[1]),i=t.as2D(-1,o);return this.reduce(i,"max",i.dtype).reshape(r)},t.prototype.maximum=function(t,e){var n=new Je("\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){Pt("all",e,t.rank);var n=At(t.shape,e),r=n[0],o=B(n[1]),i=t.as2D(-1,o);return this.reduce(i,"all",i.dtype).reshape(r)},t.prototype.any=function(t,e){Pt("any",e,t.rank);var n=At(t.shape,e),r=n[0],o=B(n[1]),i=t.as2D(-1,o);return this.reduce(i,"any",i.dtype).reshape(r)},t.prototype.squaredDifference=function(t,e){var n=new Je("return (a - b) * (a - b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.realDivide=function(t,e){var n=new Je("if (a == b) return 1.0;\n return 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){var n=new Je("\n float resultSign = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n int result = ia / ib;\n int amodb = ia - ib * result;\n\n if (resultSign < 0.0 && amodb != 0) {\n result -= 1;\n }\n return float(result);\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,Ye);var n=new Je(Ye,t.shape,e.shape),r=this.makeOutputArray(n.outputShape,Ie(t.dtype,e.dtype));return this.compileAndRun(n,[t,e],r)},t.prototype.complexSeparableBinaryOp=function(s,u,c){var l=this,t=this.texData.get(s.dataId),e=this.texData.get(u.dataId),n=[[t.complexTensors.real,e.complexTensors.real],[t.complexTensors.imag,e.complexTensors.imag]].map(function(t){var e=t[0],n=t[1],r=new Je(c,s.shape,u.shape),o=l.makeOutputArray(r.outputShape,Ie(e.dtype,n.dtype)),i=l.makeComplexComponentTensorHandle(s,e),a=l.makeComplexComponentTensorHandle(u,n);return l.compileAndRun(r,[i,a],o)}),r=n[0],o=n[1],i=this.complex(r,o);return r.dispose(),o.dispose(),i},t.prototype.makeComplexComponentTensorHandle=function(t,e){return{dataId:e.dataId,dtype:e.dtype,shape:t.shape}},t.prototype.addN=function(t){for(var e=t[0],n=1;n 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=new bo(t.shape,"return exp(x);");return this.compileAndRun(e,[t])},t.prototype.expm1=function(t){var e=new bo(t.shape,"return exp(x) - 1.0;");return this.compileAndRun(e,[t])},t.prototype.log=function(t){var e=new bo(t.shape,"if (x < 0.0) return NAN;\n return log(x);"),n=e.getCustomSetupFunc();return this.compileAndRun(e,[t],null,n)},t.prototype.log1p=function(t){var e=new bo(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},t.prototype.sqrt=function(t){var e=new bo(t.shape,"return sqrt(x);");return this.compileAndRun(e,[t])},t.prototype.rsqrt=function(t){var e=new bo(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},t.prototype.square=function(t){var e=new bo(t.shape,"return x * x;");return this.compileAndRun(e,[t])},t.prototype.reciprocal=function(t){var e=new bo(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},t.prototype.relu=function(t){var e=new bo(t.shape,"if (isNaN(x)) return x;\n return (x < 0.0) ? 0.0 : x;\n");return this.compileAndRun(e,[t])},t.prototype.elu=function(t){var e=new bo(t.shape,"return (x >= 0.0) ? x : (exp(x) - 1.0);");return this.compileAndRun(e,[t])},t.prototype.eluDer=function(t,e){var n=new Je("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 bo(t.shape,"\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = 1.7580993408473768;\n float scale = 1.0507009873554805;\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n");return this.compileAndRun(e,[t])},t.prototype.int=function(t){var e=new bo(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=new Ze(t.shape,e,n);return this.compileAndRun(r,[t])},t.prototype.abs=function(t){if("complex64"===t.dtype){var e=this.texData.get(t.dataId),n=new tn(t.shape),r=[this.makeComplexComponentTensorHandle(t,e.complexTensors.real),this.makeComplexComponentTensorHandle(t,e.complexTensors.imag)];return this.compileAndRun(n,r)}var o=new bo(t.shape,"return abs(x);");return this.compileAndRun(o,[t])},t.prototype.sigmoid=function(t){var e=new bo(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},t.prototype.softplus=function(t){var e=new bo(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 bo(t.shape,"if (isNaN(x)) return x;\n return sin(x);\n");return this.compileAndRun(e,[t])},t.prototype.cos=function(t){var e=new bo(t.shape,"if (isNaN(x)) return x;\n return cos(x);\n");return this.compileAndRun(e,[t])},t.prototype.tan=function(t){var e=new bo(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},t.prototype.asin=function(t){var e=new bo(t.shape,"return asin(x);");return this.compileAndRun(e,[t])},t.prototype.acos=function(t){var e=new bo(t.shape,"return acos(x);");return this.compileAndRun(e,[t])},t.prototype.atan=function(t){var e=new bo(t.shape,"if (isNaN(x)) return x;\n return atan(x);\n");return this.compileAndRun(e,[t])},t.prototype.atan2=function(t,e){var n=new Je("\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 bo(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 bo(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 bo(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 bo(t.shape,"return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(e,[t])},t.prototype.acosh=function(t){var e=new bo(t.shape,"if (isNaN(x)) return x;\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));"),n=e.getCustomSetupFunc();return this.compileAndRun(e,[t],null,n)},t.prototype.atanh=function(t){var e=new bo(t.shape,"if (isNaN(x)) return x;\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;"),n=e.getCustomSetupFunc();return this.compileAndRun(e,[t],null,n)},t.prototype.erf=function(t){var e=new bo(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,r=new bo(t.shape,(void 0===(n=e)&&(n=0),wo+"\n return x > 0.0 ? 1.0 : float("+n+");\n "));return this.compileAndRun(r,[t])},t.prototype.conv2dWithIm2Row=function(t,e,n){var r=n.filterWidth,o=n.filterHeight,i=n.inChannels,a=n.outWidth,s=n.outHeight,u=r*o*i,c=s*a,l=[u,c],h=t.squeeze([0]),p=e.reshape([u,-1]),f=new Vr(l,h.shape,n),d=this.compileAndRun(f,[h],this.makePackedTensor(l)),m=new $r(d.shape,p.shape,[c,n.outChannels],!0,!1);return this.unpackTensor(this.compileAndRun(m,[d,p],this.makePackedTensor(m.outputShape))).reshape([1,s,a,n.outChannels])},t.prototype.conv2d=function(t,e,n){if(mt.get("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,e,n);var r=new sn(n);return this.compileAndRun(r,[t,e])},t.prototype.conv2dDerInput=function(t,e,n){var r=new rn(n);return this.compileAndRun(r,[t,e])},t.prototype.conv2dDerFilter=function(t,e,n){var r=new nn(n);return this.compileAndRun(r,[t,e])},t.prototype.depthwiseConv2D=function(t,e,n){var r=new un(n);return this.compileAndRun(r,[t,e])},t.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new an(n);return this.compileAndRun(r,[t,e])},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new on(n);return this.compileAndRun(r,[t,e])},t.prototype.maxPool=function(t,e){var n=new to(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 to(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 to(r,"max",!0),i=this.compileAndRun(o,[e]),a=new jr(r),s=this.makeOutputArray(a.outputShape,e.dtype),u=this.compileAndRun(a,[t,i],s);return i.dispose(),u},t.prototype.avgPoolBackprop=function(t,e,n){var r=new We(n),o=this.makeOutputArray(r.outputShape,e.dtype);return this.compileAndRun(r,[t],o)},t.prototype.cast=function(t,e){return Ae(t,e,this)},t.prototype.reshape=function(t,e){return Me(t,e)},t.prototype.resizeBilinear=function(t,e,n,r){var o=new ro(t.shape,e,n,r);return this.compileAndRun(o,[t])},t.prototype.resizeBilinearBackprop=function(t,e,n){var r=new no(t,e,n);return this.compileAndRun(r,[t])},t.prototype.resizeNearestNeighbor=function(t,e,n,r){var o=new io(t.shape,e,n,r);return this.compileAndRun(o,[t])},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){var r=new oo(t,e,n);return this.compileAndRun(r,[t])},t.prototype.multinomial=function(t,e,n,r){var o=e?t:Qt(t),i=o.shape[0],a=o.shape[1],s=new Kr(i,a,n),u=this.makeOutputArray(s.outputShape,"int32"),c=s.getCustomSetupFunc(r);return this.compileAndRun(s,[o],u,c)},t.prototype.oneHot=function(t,e,n,r){var o=new Xr(t.size,e,n,r);return this.compileAndRun(o,[t])},t.prototype.nonMaxSuppression=function(t,e,n,r,o){return Ct("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),Pe(t.dataSync(),e.dataSync(),n,r,o)},t.prototype.cropAndResize=function(t,e,n,r,o,i){var a=new cn(t.shape,e.shape,r,o,i);return this.compileAndRun(a,[t,e,n])},t.prototype.depthToSpace=function(t,e,n){D(1 1 for depthToSpace, but was: "+e);var r=t.shape[0],o=("NHWC"===n?t.shape[1]:t.shape[2])*e,i=("NHWC"===n?t.shape[2]:t.shape[3])*e,a=("NHWC"===n?t.shape[3]:t.shape[1])/(e*e),s=new wn("NHWC"===n?[r,o,i,a]:[r,a,o,i],e,n);return this.compileAndRun(s,[t])},t.prototype.split=function(t,e,n){return Le(t,e,n)},t.prototype.scatterND=function(t,e,n){var r=Gt(0,t,n),o=r.sliceRank,i=r.numUpdates,a=r.sliceSize,s=r.strides,u=r.outputSize,c=[u/a,a],l=t.reshape([i,o]),h=e.reshape([i,a]);if(0===u)return Me(ee([]),n);var p=ne(0),f=new so(i,o,l.rank,h.rank,s,c);return this.compileAndRun(f,[h,l,p]).reshape(n)},t.prototype.sparseToDense=function(t,e,n,r){var o=Gt(0,t,n),i=o.sliceRank,a=o.numUpdates,s=o.strides,u=o.outputSize,c=new so(a,i,t.rank,e.rank,s,[u,1],!1);return this.compileAndRun(c,[e,t,r]).reshape(n)},t.prototype.fft=function(t){var e=this.texData.get(t.dataId),n=new Cn(Sn,t.shape),r=new Cn(_n,t.shape),o=[this.makeComplexComponentTensorHandle(t,e.complexTensors.real),this.makeComplexComponentTensorHandle(t,e.complexTensors.imag)],i=this.compileAndRun(n,o),a=this.compileAndRun(r,o),s=this.complex(i,a).as2D(t.shape[0],t.shape[1]);return i.dispose(),a.dispose(),s},t.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],o=Wt(t,e),i=o[0],a=o[1],s=o[2],u=o[3],c=e.reshape([a,r]),l=t.reshape([t.size/s,s]),h=new An(r,u,[a,s]);return this.compileAndRun(h,[l,c]).reshape(i)},t.prototype.makeOutputArray=function(t,e){return Y.make(t,{},e)},t.prototype.makePackedTensor=function(t){var e=Y.make(t,{});return this.texData.get(e.dataId).isPacked=!0,e},t.prototype.unpackTensor=function(t){var e=new Eo(t.shape);return this.compileAndRun(e,[t])},t.prototype.compileAndRun=function(o,t,e,n,r){var i=this;if(void 0===r&&(r=!0),null==e&&(e=this.makeOutputArray(o.outputShape,t[0].dtype)),0===e.size)return this.texData.get(e.dataId).values=b(e.dtype,0),e;var a=t.map(function(t){if("complex64"===t.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var e=i.texData.get(t.dataId);if(null==e.texture&&(e.isPacked||!o.usesPackedTextures)&&B(t.shape)<=mt.get("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:t.shape,texData:null,isUniform:!0,uniformValues:i.readSync(t.dataId)};if(e.isPacked!==!!o.usesPackedTextures){var n=void 0,r=void 0;e.isPacked?(n=new Eo(t.shape),r=i.compileAndRun(n,[t])):(n=new Jr(t.shape),r=i.compileAndRun(n,[t],i.makePackedTensor(t.shape))),e=i.texData.get(r.dataId),t=r}return i.uploadToGPU(t.dataId),{shape:t.shape,texData:e,isUniform:!1}});this.uploadToGPU(e.dataId);var s,u={shape:e.shape,texData:this.texData.get(e.dataId),isUniform:!1},c=function(t,e,n){var r="";e.concat(n).forEach(function(t){r+=t.shape+"_"+(t.isUniform?"uniform":t.texData.texShape)});var o=t.userCode,i=(!0===t.supportsBroadcasting).toString();return t.constructor.name+"_"+i+"_"+r+"_"+o}(o,a,u),l=this.getAndSaveBinary(c,function(){return function(t,r,e,n){for(var o=r.userCode,i=e.map(function(t,e){var n={logicalShape:t.shape,texShape:t.isUniform?null:t.texData.texShape,isUniform:t.isUniform,isPacked:!t.isUniform&&t.texData.isPacked};return{name:r.variableNames[e],shapeInfo:n}}),a=i.map(function(t){return t.shapeInfo}),s={logicalShape:n.shape,texShape:n.texData.texShape,isUniform:!1,isPacked:n.texData.isPacked},u=ln(i,s,o,!0===r.supportsBroadcasting),c=t.createProgram(u),l={},h=0;hthis.NUM_BYTES_BEFORE_PAGING)for(var p=this.numBytesInGPU-this.NUM_BYTES_BEFORE_PAGING;0= 2, but got rank "+t.rank);if(2===t.rank)return cu(t,o);var e=t.shape.slice(0,t.shape.length-2).reduce(function(t,e){return t*e}),i=[],a=[];return pi(t.reshape([e,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0).forEach(function(t){var e=cu(t,o),n=e[0],r=e[1];i.push(n),a.push(r)}),[ci(i,0).reshape(t.shape),ci(a,0).reshape(t.shape)]}}),pu=Object.freeze({gramSchmidt:lu,qr:hu});function fu(t,e,n,r,o){null==r&&(r=.5),null==o&&(o=Number.NEGATIVE_INFINITY);var i=t.shape[0];return n=Math.min(n,i),D(0<=r&&r<=1,"iouThreshold must be in [0, 1], but was '"+r+"'"),D(2===t.rank,"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"),D(4===t.shape[1],"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]),D(1===e.rank,"scores must be a 1D tensor"),D(e.shape[0]===i,"scores has incompatible shape with boxes. Expected "+i+", but was "+e.shape[0]),{maxOutputSize:n,iouThreshold:r,scoreThreshold:o}}var du=Yt({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=Kt(t,"images","resizeBilinear");D(3===r.rank||4===r.rank,"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."),D(2===e.length,"Error in resizeBilinear: new shape must 2D, but got shape "+e+".");var o=r,i=!1;3===r.rank&&(i=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var a=e[0],s=e[1],u=mt.engine.runKernel(function(t,e){return t.resizeBilinear(o,a,s,n)},{batchImages:o},function(e,t){return{batchImages:function(){return mt.engine.runKernel(function(t){return t.resizeBilinearBackprop(e,o,n)},{})}}});return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),mu=Yt({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=Kt(t,"images","resizeNearestNeighbor");D(3===r.rank||4===r.rank,"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."),D(2===e.length,"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."),D("float32"===r.dtype||"int32"===r.dtype,"`images` must have `int32` or `float32` as dtype");var o=r,i=!1;3===r.rank&&(i=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var a=e[0],s=e[1],u=mt.engine.runKernel(function(t,e){return t.resizeNearestNeighbor(o,a,s,n)},{batchImages:o},function(e,t){return{batchImages:function(){return mt.engine.runKernel(function(t){return t.resizeNearestNeighborBackprop(e,o,n)},{})}}});return i?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),vu=Yt({nonMaxSuppression_:function(t,e,n,r,o){void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY);var i=Kt(t,"boxes","nonMaxSuppression"),a=Kt(e,"scores","nonMaxSuppression"),s=fu(i,a,n,r,o);return n=s.maxOutputSize,r=s.iouThreshold,o=s.scoreThreshold,mt.engine.runKernel(function(t){return t.nonMaxSuppression(i,a,n,r,o)},{$boxes:i})}}),gu=function(s,u,c,l,h){return void 0===l&&(l=.5),void 0===h&&(h=Number.NEGATIVE_INFINITY),m(this,void 0,void 0,function(){var e,n,r,o,i,a;return S(this,function(t){switch(t.label){case 0:return e=Kt(s,"boxes","nonMaxSuppressionAsync"),n=Kt(u,"scores","nonMaxSuppressionAsync"),r=fu(e,n,c,l,h),c=r.maxOutputSize,l=r.iouThreshold,h=r.scoreThreshold,[4,e.data()];case 1:return o=t.sent(),[4,n.data()];case 2:return i=t.sent(),a=Pe(o,i,c,l,h),e!==s&&e.dispose(),n!==u&&n.dispose(),[2,a]}})})},yu=function(t,e,n,r,o,i){var a=Kt(t,"image","cropAndResize","float32"),s=Kt(e,"boxes","cropAndResize","float32"),u=Kt(n,"boxInd","cropAndResize","int32");o=o||"bilinear",i=i||0;var c=s.shape[0];return D(4===a.rank,"Error in cropAndResize: image must be rank 4,but got rank "+a.rank+"."),D(2===s.rank&&4===s.shape[1],"Error in cropAndResize: boxes must be have size ["+c+",4] but had shape "+s.shape+"."),D(1===u.rank&&u.shape[0]===c,"Error in cropAndResize: boxInd must be have size ["+c+"] but had shape "+s.shape+"."),D("int32"===u.dtype,"Error in cropAndResize: boxInd must be of dtype int32, but got dtype "+u.dtype+"."),D(2===r.length,"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."),D(1<=r[0]&&1<=r[1],"cropSize must be atleast [1,1], but was "+r),D("bilinear"===o||"nearest"===o,"method must be bilinear or nearest, but was "+o),mt.engine.runKernel(function(t,e){return t.cropAndResize(a,s,u,r,o,i)},{$image:a,$boxes:s})},xu=Object.freeze({resizeBilinear:du,resizeNearestNeighbor:mu,nonMaxSuppression:vu,nonMaxSuppressionAsync:gu,cropAndResize:yu}),bu=Object.freeze({image:xu,linalg:pu,losses:uu,spectral:Ks,op:Yt,batchNormalization2d:Xi,batchNormalization3d:Yi,batchNormalization4d:Qi,batchNormalization:Ji,complex:Jt,real:Zt,imag:te,concat:So,concat1d:_o,concat2d:Co,concat3d:Ro,concat4d:To,split:ko,conv1d:ha,conv2d:pa,conv2dDerFilter:fa,depthwiseConv2d:da,separableConv2d:ma,conv2dTranspose:va,matMul:aa,dot:sa,outerProduct:ua,reverse:ga,reverse1d:ya,reverse2d:xa,reverse3d:ba,reverse4d:wa,maxPool:_a,avgPool:Ca,pool:Ra,slice:Ta,slice1d:ka,slice2d:Ia,slice3d:Da,slice4d:Na,abs:vi,acos:gi,acosh:yi,asin:xi,asinh:bi,atan:wi,atanh:Ei,ceil:Si,clipByValue:_i,cos:Ci,cosh:Ri,erf:Ti,exp:ki,expm1:Ii,floor:Di,log:Ni,log1p:Ai,logSigmoid:Mi,neg:Oi,reciprocal:Pi,round:Fi,rsqrt:Li,sigmoid:Bi,sign:zi,sin:Wi,sinh:Ui,softplus:Vi,sqrt:Gi,square:qi,step:ji,tan:Hi,tanh:$i,all:Ma,any:Oa,argMax:Pa,argMin:Fa,logSumExp:La,max:Ba,mean:za,min:Wa,moments:Ua,sum:Va,prod:Ga,equal:qa,equalStrict:ja,greater:Ha,greaterEqual:$a,greaterEqualStrict:Ka,greaterStrict:Xa,less:Ya,lessEqual:Qa,lessEqualStrict:Ja,lessStrict:Za,notEqual:ts,notEqualStrict:es,add:ns,addN:rs,addStrict:os,atan2:is,div:as,divStrict:ss,floorDiv:us,maximum:cs,maximumStrict:ls,minimum:hs,minimumStrict:ps,mod:fs,modStrict:ds,mul:ms,mulStrict:vs,pow:gs,powStrict:ys,squaredDifference:xs,squaredDifferenceStrict:bs,sub:ws,subStrict:Es,elu:Is,leakyRelu:Ds,prelu:Ns,relu:As,selu:Ms,logicalAnd:Ss,logicalNot:_s,logicalOr:Cs,logicalXor:Rs,where:Ts,whereAsync:ks,buffer:Wo,toPixels:zo,print:Uo,batchToSpaceND:Vo,cast:Go,clone:qo,cumsum:jo,depthToSpace:Ho,expandDims:$o,eye:Ko,fromPixels:Xo,multinomial:Yo,oneHot:Qo,pad:Jo,pad1d:Zo,pad2d:ti,pad3d:ei,pad4d:ni,rand:ri,randomNormal:oi,randomUniform:ii,reshape:ai,spaceToBatchND:si,squeeze:ui,stack:ci,tile:li,truncatedNormal:hi,unstack:pi,fill:he,linspace:pe,ones:ce,range:fe,scalar:ne,tensor:ee,tensor1d:re,tensor2d:oe,tensor3d:ie,tensor4d:ae,tensor5d:se,tensor6d:ue,zeros:le,onesLike:Re,zerosLike:Te,transpose:Os,softmax:Qt,localResponseNormalization:Ps,norm:Fs,gather:zs,unsortedSegmentSum:Ws,basicLSTMCell:Us,multiRNNCell:Vs,movingAverage:Gs,stridedSlice:qs,topk:js,scatterND:Hs,fft:$s,sparseToDense:Xs,gatherND:Js}),wu=function(){function t(){this.blockSize=48,this.firstUse=!0,mt.get("IS_BROWSER")&&(this.canvas=document.createElement("canvas"))}return t.prototype.setDataMover=function(t){this.data=new Ne(t)},t.prototype.register=function(t,e,n){if(this.firstUse&&(this.firstUse=!1,mt.get("IS_NODE")&&Ct("\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.fromPixels() can not be null");var n,r;if(mt.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(t instanceof ImageData)n=t.data;else{if(!(t instanceof HTMLImageElement||t instanceof HTMLVideoElement))throw new Error("pixels passed to tf.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement or ImageData, but was "+t.constructor.name);if(null==this.canvas)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");this.canvas.width=t.width,this.canvas.height=t.height,this.canvas.getContext("2d").drawImage(t,0,0,t.width,t.height),n=this.canvas.getContext("2d").getImageData(0,0,t.width,t.height).data}if(4===e)r=new Int32Array(n);else{var o=t.width*t.height;r=new Int32Array(o*e);for(var i=0;i-e,s=r[o]=n.inHeight))for(var w=x*e.strides[0],E=d+b*t.strides[1],S=0;S=n.inWidth))for(var k=w+R*e.strides[1],I=E+T*n.inChannels,D=k,N=0;N=n.inHeight))for(var E=b*e.strides[0],S=m+w*t.strides[1],_=0;_=n.inWidth))for(var I=E+T*e.strides[1],D=S+k*n.inChannels,N=C,A=I,M=0;M=r.outHeight||Math.floor(E)!==E))for(var S=0;S=r.outWidth||Math.floor(_)!==_)){var C=c*l-1-o.get(d,E,_,m)===w*l+S?1:0;0!==C&&(b+=t.get(d,E,_,m)*C)}}}f.set(b,d,v,g,m)}return f.toTensor()},t.prototype.avgPoolBackprop=function(t,e,n){this.assertNotComplex([t,e],"avgPoolBackprop");for(var r=n.strideHeight,o=n.strideWidth,i=n.filterHeight,a=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,c=n.effectiveFilterHeight,l=n.effectiveFilterWidth,h=l-1-n.padInfo.left,p=c-1-n.padInfo.top,f=Wo(e.shape,"float32"),d=1/(i*a),m=0;m=n.outHeight||Math.floor(S)!==S))for(var _=0;_=n.outWidth||Math.floor(C)!==C||(w+=t.get(m,S,C,v))}}f.set(w*d,m,g,y,v)}return f.toTensor()},t.prototype.cast=function(t,e){return Ae(t,e,this)},t.prototype.reshape=function(t,e){return Me(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,i=o[0],a=o[1],s=o[2],u=o[3],c=t.dataSync(),l=new Float32Array(B([i,e,n,u])),h=[r&&1 1 for depthToSpace, but was: "+e);for(var r=t.shape[0],o=t.shape[1],i=t.shape[2],a=t.shape[3],s=o*e,u=i*e,c=a/(e*e),l=t.dataSync(),h=new Float32Array(r*s*u*c),p=0,f=0;f=t.size/s)throw new Error("Invalid indices: "+f+" does not index into "+t.shape);for(var g=0;gn)}var Ec=Object.freeze({WEBGL_ENVS:{HAS_WEBGL:!0},NODE_ENVS:{IS_NODE:!0},CHROME_ENVS:{IS_CHROME:!0},BROWSER_ENVS:{IS_BROWSER:!0},CPU_ENVS:{HAS_WEBGL:!1},BROWSER_CPU_ENVS:{BACKEND:"test-cpu"},ALL_ENVS:{},expectArraysClose:bc,expectPromiseToFail:function(t,e){t().then(function(){return e.fail()},function(){return e()})},expectArraysEqual:function(t,e){return bc(t,e,0)},expectNumbersClose:function(t,e,n){if(null==n&&(n=mt.get("TEST_EPSILON")),!wc(t,e,n))throw new Error("Numbers differ: actual === "+t+", expected === "+e)},expectValuesInRange:function(t,e,n){var r;r=t instanceof Y?t.dataSync():t;for(var o=0;on)throw new Error("Value out of range:"+r[o]+" low: "+e+", high: "+n)},expectArrayBuffersEqual:function(t,e){expect(new Float32Array(t)).toEqual(new Float32Array(e))}}),Sc=Object.freeze({gpgpu_util:zr,webgl_util:vr,MathBackendWebGL:di,GPGPUContext:Wr}),_c=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return s(e,t),e.prototype.minimize=function(t,e,n){void 0===e&&(e=!1);var r=this.computeGradients(t,n),o=r.value,i=r.grads;return this.applyGradients(i),Object.keys(i).forEach(function(t){return i[t].dispose()}),e?o:(o.dispose(),null)},e.prototype.computeGradients=function(t,e){return gt(t,e)},e}(vc),Cc=function(o){function t(t,e,n){void 0===n&&(n=null);var r=o.call(this)||this;return r.learningRate=t,r.rho=e,r.epsilon=n,r.accumulatedGrads={},r.accumulatedUpdates={},r.c=wt(ne(-t)),r.rhoScalar=wt(ne(e)),r.oneMinusRho=wt(ne(1-e)),null===n&&(n=mt.get("EPSILON")),r.epsilonScalar=wt(ne(n)),r}return s(t,o),t.prototype.applyGradients=function(t){var c=this,e=function(o){var i=mt.engine.registeredVariables[o];null==n.accumulatedGrads[o]&&bt(function(){c.accumulatedGrads[o]=Te(i).variable(!1)}),null==n.accumulatedUpdates[o]&&bt(function(){c.accumulatedUpdates[o]=Te(i).variable(!1)});var a=t[o],s=n.accumulatedGrads[o],u=n.accumulatedUpdates[o];bt(function(){var t=c.rhoScalar.mul(s).add(c.oneMinusRho.mul(a.square())),e=u.add(c.epsilonScalar).sqrt().div(s.add(c.epsilonScalar).sqrt()).mul(a),n=c.rhoScalar.mul(u).add(c.oneMinusRho.mul(e.square()));c.accumulatedGrads[o].assign(t),c.accumulatedUpdates[o].assign(n);var r=c.c.mul(e).add(i);i.assign(r)})},n=this;for(var r in t)e(r)},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsilonScalar.dispose(),this.rhoScalar.dispose(),this.oneMinusRho.dispose(),null!=this.accumulatedUpdates&&(Object.keys(this.accumulatedUpdates).forEach(function(t){return e.accumulatedUpdates[t].dispose()}),Object.keys(this.accumulatedGrads).forEach(function(t){return e.accumulatedGrads[t].dispose()}))},t.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},t.fromConfig=function(t,e){return new t(e.learningRate,e.rho,e.epsilon)},t.className="AdadeltaOptimizer",t}(_c);yc(Cc);var Rc=function(r){function t(t,e){void 0===e&&(e=.1);var n=r.call(this)||this;return n.learningRate=t,n.initialAccumulatorValue=e,n.accumulatedGrads={},n.c=wt(ne(-t)),n.epsilon=wt(ne(mt.get("EPSILON"))),n}return s(t,r),t.prototype.applyGradients=function(t){var a=this,e=function(n){var r=mt.engine.registeredVariables[n];null==s.accumulatedGrads[n]&&bt(function(){a.accumulatedGrads[n]=he(r.shape,a.initialAccumulatorValue).variable(!1)});var o=t[n],i=s.accumulatedGrads[n];bt(function(){var t=i.add(o.square());a.accumulatedGrads[n].assign(t);var e=a.c.mul(o.div(t.add(a.epsilon).sqrt())).add(r);r.assign(e)})},s=this;for(var n in t)e(n)},t.prototype.dispose=function(){var e=this;this.epsilon.dispose(),this.c.dispose(),null!=this.accumulatedGrads&&Object.keys(this.accumulatedGrads).forEach(function(t){return e.accumulatedGrads[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},t.fromConfig=function(t,e){return new t(e.learningRate,e.initialAccumulatorValue)},t.className="AdagradOptimizer",t}(_c);yc(Rc);var Tc=function(i){function t(t,e,n,r){void 0===r&&(r=null);var o=i.call(this)||this;return o.learningRate=t,o.beta1=e,o.beta2=n,o.epsilon=r,o.accumulatedFirstMoment={},o.accumulatedSecondMoment={},o.c=wt(ne(-t)),o.beta1Scalar=wt(ne(e)),o.beta2Scalar=wt(ne(n)),bt(function(){o.accBeta1=ne(e).variable(),o.accBeta2=ne(n).variable()}),o.oneMinusBeta1=wt(ne(1-e)),o.oneMinusBeta2=wt(ne(1-n)),o.one=wt(ne(1)),null===r&&(r=mt.get("EPSILON")),o.epsScalar=wt(ne(r)),o}return s(t,i),t.prototype.applyGradients=function(f){var d=this;bt(function(){var t=d.one.sub(d.accBeta1),e=d.one.sub(d.accBeta2);for(var n in f){var r=mt.engine.registeredVariables[n];if(null==d.accumulatedFirstMoment[n]){var o=!1;d.accumulatedFirstMoment[n]=Te(r).variable(o)}null==d.accumulatedSecondMoment[n]&&(o=!1,d.accumulatedSecondMoment[n]=Te(r).variable(o));var i=f[n],a=d.accumulatedFirstMoment[n],s=d.accumulatedSecondMoment[n],u=d.beta1Scalar.mul(a).add(d.oneMinusBeta1.mul(i)),c=d.beta2Scalar.mul(s).add(d.oneMinusBeta2.mul(i.square())),l=u.div(t),h=c.div(e);d.accumulatedFirstMoment[n].assign(u),d.accumulatedSecondMoment[n].assign(c);var p=d.c.mul(l.div(d.epsScalar.add(h.sqrt()))).add(r);r.assign(p)}d.accBeta1.assign(d.accBeta1.mul(d.beta1Scalar)),d.accBeta2.assign(d.accBeta2.mul(d.beta2Scalar))})},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsScalar.dispose(),this.beta1Scalar.dispose(),this.beta2Scalar.dispose(),this.accBeta1.dispose(),this.accBeta2.dispose(),this.oneMinusBeta1.dispose(),this.oneMinusBeta2.dispose(),this.one.dispose(),null!=this.accumulatedFirstMoment&&Object.keys(this.accumulatedFirstMoment).forEach(function(t){return e.accumulatedFirstMoment[t].dispose()}),null!=this.accumulatedSecondMoment&&Object.keys(this.accumulatedSecondMoment).forEach(function(t){return e.accumulatedSecondMoment[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},t.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon)},t.className="AdamOptimizer",t}(_c);yc(Tc);var kc=function(a){function t(t,e,n,r,o){void 0===r&&(r=null),void 0===o&&(o=0);var i=a.call(this)||this;return i.learningRate=t,i.beta1=e,i.beta2=n,i.epsilon=r,i.decay=o,i.accumulatedFirstMoment={},i.accumulatedWeightedInfNorm={},i.c=wt(ne(-t)),i.beta1Scalar=wt(ne(e)),i.beta2Scalar=wt(ne(n)),i.decayScalar=wt(ne(o)),bt(function(){i.iteration=ne(0).variable(),i.accBeta1=ne(e).variable()}),i.oneMinusBeta1=wt(ne(1-e)),i.one=wt(ne(1)),null===r&&(r=mt.get("EPSILON")),i.epsScalar=wt(ne(r)),i}return s(t,a),t.prototype.applyGradients=function(f){var d=this;bt(function(){var t=d.one.sub(d.accBeta1),e=d.c.div(d.one.add(d.decayScalar.mul(d.iteration)));for(var n in f){var r=mt.engine.registeredVariables[n];if(null==d.accumulatedFirstMoment[n]){var o=!1;d.accumulatedFirstMoment[n]=Te(r).variable(o)}null==d.accumulatedWeightedInfNorm[n]&&(o=!1,d.accumulatedWeightedInfNorm[n]=Te(r).variable(o));var i=f[n],a=d.accumulatedFirstMoment[n],s=d.accumulatedWeightedInfNorm[n],u=d.beta1Scalar.mul(a).add(d.oneMinusBeta1.mul(i)),c=d.beta2Scalar.mul(s),l=i.abs(),h=c.maximum(l);d.accumulatedFirstMoment[n].assign(u),d.accumulatedWeightedInfNorm[n].assign(h);var p=e.div(t).mul(u.div(d.epsScalar.add(h))).add(r);r.assign(p)}d.iteration.assign(d.iteration.add(d.one)),d.accBeta1.assign(d.accBeta1.mul(d.beta1Scalar))})},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsScalar.dispose(),this.accBeta1.dispose(),this.beta1Scalar.dispose(),this.beta2Scalar.dispose(),this.oneMinusBeta1.dispose(),this.decayScalar.dispose(),this.iteration.dispose(),this.one.dispose(),null!=this.accumulatedFirstMoment&&Object.keys(this.accumulatedFirstMoment).forEach(function(t){return e.accumulatedFirstMoment[t].dispose()}),null!=this.accumulatedWeightedInfNorm&&Object.keys(this.accumulatedWeightedInfNorm).forEach(function(t){return e.accumulatedWeightedInfNorm[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},t.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon,e.decay)},t.className="AdamaxOptimizer",t}(_c);yc(kc);var Ic=function(n){function t(t){var e=n.call(this)||this;return e.learningRate=t,e.setLearningRate(t),e}return s(t,n),t.prototype.applyGradients=function(r){var o=this;Object.keys(r).forEach(function(t){var e=r[t],n=mt.engine.registeredVariables[t];bt(function(){var t=o.c.mul(e).add(n);n.assign(t)})})},t.prototype.setLearningRate=function(t){this.learningRate=t,null!=this.c&&this.c.dispose(),this.c=wt(ne(-t))},t.prototype.dispose=function(){this.c.dispose()},t.prototype.getConfig=function(){return{learningRate:this.learningRate}},t.fromConfig=function(t,e){return new t(e.learningRate)},t.className="SGDOptimizer",t}(_c);yc(Ic);var Dc=function(o){function t(t,e,n){void 0===n&&(n=!1);var r=o.call(this,t)||this;return r.learningRate=t,r.momentum=e,r.useNesterov=n,r.m=ne(r.momentum),r.accumulations={},r}return s(t,o),t.prototype.applyGradients=function(t){var a=this,e=function(n){var r=mt.engine.registeredVariables[n];null==s.accumulations[n]&&bt(function(){a.accumulations[n]=Te(r).variable(!1)});var o=s.accumulations[n],i=t[n];bt(function(){var t,e=a.m.mul(o).add(i);t=a.useNesterov?a.c.mul(i.add(e.mul(a.m))).add(r):a.c.mul(e).add(r),a.accumulations[n].assign(e),r.assign(t)})},s=this;for(var n in t)e(n)},t.prototype.dispose=function(){if(o.prototype.dispose.call(this),this.m.dispose(),null!=this.accumulations)for(var t in this.accumulations)this.accumulations[t].dispose()},t.prototype.setMomentum=function(t){this.momentum=t},t.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},t.fromConfig=function(t,e){return new t(e.learningRate,e.momentum,e.useNesterov)},t.className="MomentumOptimizer",t}(Ic);yc(Dc);var Nc=function(a){function t(t,e,n,r,o){void 0===e&&(e=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===o&&(o=!1);var i=a.call(this)||this;return i.learningRate=t,i.decay=e,i.momentum=n,i.epsilon=r,i.accumulatedMeanSquares={},i.accumulatedMeanGrads={},i.accumulatedMoments={},i.c=wt(ne(t)),i.decayScalar=wt(ne(e)),i.momentumScalar=wt(ne(n)),i.oneMinusDecay=wt(ne(1-e)),i.centered=o,null===r&&(r=mt.get("EPSILON")),i.epsilonScalar=wt(ne(r)),i}return s(t,a),t.prototype.applyGradients=function(t){var h=this,e=function(i){var a=mt.engine.registeredVariables[i];null==n.accumulatedMeanSquares[i]&&bt(function(){h.accumulatedMeanSquares[i]=Te(a).variable(!1)}),null==n.accumulatedMeanGrads[i]&&n.centered&&bt(function(){h.accumulatedMeanGrads[i]=Te(a).variable(!1)}),null==n.accumulatedMoments[i]&&bt(function(){h.accumulatedMoments[i]=Te(a).variable(!1)});var s=n.accumulatedMeanSquares[i],u=n.accumulatedMeanGrads[i],c=n.accumulatedMoments[i],l=t[i];bt(function(){var t=h.decayScalar.mul(s).add(h.oneMinusDecay.mul(l.square()));if(h.centered){var e=h.decayScalar.mul(u).add(h.oneMinusDecay.mul(l)),n=h.momentumScalar.mul(c).add(h.c.mul(l).div(t.sub(e.square().add(h.epsilonScalar)).sqrt()));h.accumulatedMeanSquares[i].assign(t),h.accumulatedMeanGrads[i].assign(e),h.accumulatedMoments[i].assign(n);var r=a.sub(n);a.assign(r)}else{var o=h.decayScalar.mul(s).add(h.oneMinusDecay.mul(l.square()));n=h.momentumScalar.mul(c).add(h.c.mul(l).div(o.add(h.epsilonScalar).sqrt())),h.accumulatedMeanSquares[i].assign(o),h.accumulatedMoments[i].assign(n),r=a.sub(n),a.assign(r)}})},n=this;for(var r in t)e(r)},t.prototype.dispose=function(){var e=this;this.c.dispose(),this.epsilonScalar.dispose(),this.decayScalar.dispose(),this.momentumScalar.dispose(),this.oneMinusDecay.dispose(),null!=this.accumulatedMeanSquares&&Object.keys(this.accumulatedMeanSquares).forEach(function(t){return e.accumulatedMeanSquares[t].dispose()}),null!=this.accumulatedMeanGrads&&this.centered&&Object.keys(this.accumulatedMeanGrads).forEach(function(t){return e.accumulatedMeanGrads[t].dispose()}),null!=this.accumulatedMoments&&Object.keys(this.accumulatedMoments).forEach(function(t){return e.accumulatedMoments[t].dispose()})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},t.fromConfig=function(t,e){return new t(e.learningRate,e.decay,e.momentum,e.epsilon,e.centered)},t.className="RMSPropOptimizer",t}(_c);yc(Nc);var Ac=function(){function t(){}return t.sgd=function(t){return new Ic(t)},t.momentum=function(t,e,n){return void 0===n&&(n=!1),new Dc(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 Nc(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 Tc(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 Cc(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 kc(t,e,n,r,o)},t.adagrad=function(t,e){return void 0===e&&(e=.1),new Rc(t,e)},t}(),Mc={sgd:Ac.sgd,momentum:Ac.momentum,adadelta:Ac.adadelta,adagrad:Ac.adagrad,rmsprop:Ac.rmsprop,adamax:Ac.adamax,adam:Ac.adam},Oc=ft.setBackend,Pc=ft.getBackend,Fc=ft.disposeVariables,Lc=ft.memory;K=bu;var Bc=Object.freeze({setBackend:Oc,getBackend:Pc,disposeVariables:Fc,memory:Lc,version_core:"0.13.8",nextFrame:function(){return new Promise(function(t){return Eu(function(){return t()})})},environment:vt,io:fc,math:mc,serialization:xc,test_util:Ec,util:L,webgl:Sc,AdadeltaOptimizer:Cc,AdagradOptimizer:Rc,AdamOptimizer:Tc,AdamaxOptimizer:kc,MomentumOptimizer:Dc,Optimizer:_c,RMSPropOptimizer:Nc,SGDOptimizer:Ic,Tensor:Y,TensorBuffer:H,variable:J,Variable:Q,get Rank(){return me},get Reduction(){return Ys},ENV:mt,Environment:ft,DataStorage:Ne,image:xu,linalg:pu,losses:uu,spectral:Ks,op:Yt,batchNormalization2d:Xi,batchNormalization3d:Yi,batchNormalization4d:Qi,batchNormalization:Ji,complex:Jt,real:Zt,imag:te,concat:So,concat1d:_o,concat2d:Co,concat3d:Ro,concat4d:To,split:ko,conv1d:ha,conv2d:pa,conv2dDerFilter:fa,depthwiseConv2d:da,separableConv2d:ma,conv2dTranspose:va,matMul:aa,dot:sa,outerProduct:ua,reverse:ga,reverse1d:ya,reverse2d:xa,reverse3d:ba,reverse4d:wa,maxPool:_a,avgPool:Ca,pool:Ra,slice:Ta,slice1d:ka,slice2d:Ia,slice3d:Da,slice4d:Na,abs:vi,acos:gi,acosh:yi,asin:xi,asinh:bi,atan:wi,atanh:Ei,ceil:Si,clipByValue:_i,cos:Ci,cosh:Ri,erf:Ti,exp:ki,expm1:Ii,floor:Di,log:Ni,log1p:Ai,logSigmoid:Mi,neg:Oi,reciprocal:Pi,round:Fi,rsqrt:Li,sigmoid:Bi,sign:zi,sin:Wi,sinh:Ui,softplus:Vi,sqrt:Gi,square:qi,step:ji,tan:Hi,tanh:$i,all:Ma,any:Oa,argMax:Pa,argMin:Fa,logSumExp:La,max:Ba,mean:za,min:Wa,moments:Ua,sum:Va,prod:Ga,equal:qa,equalStrict:ja,greater:Ha,greaterEqual:$a,greaterEqualStrict:Ka,greaterStrict:Xa,less:Ya,lessEqual:Qa,lessEqualStrict:Ja,lessStrict:Za,notEqual:ts,notEqualStrict:es,add:ns,addN:rs,addStrict:os,atan2:is,div:as,divStrict:ss,floorDiv:us,maximum:cs,maximumStrict:ls,minimum:hs,minimumStrict:ps,mod:fs,modStrict:ds,mul:ms,mulStrict:vs,pow:gs,powStrict:ys,squaredDifference:xs,squaredDifferenceStrict:bs,sub:ws,subStrict:Es,elu:Is,leakyRelu:Ds,prelu:Ns,relu:As,selu:Ms,logicalAnd:Ss,logicalNot:_s,logicalOr:Cs,logicalXor:Rs,where:Ts,whereAsync:ks,buffer:Wo,toPixels:zo,print:Uo,batchToSpaceND:Vo,cast:Go,clone:qo,cumsum:jo,depthToSpace:Ho,expandDims:$o,eye:Ko,fromPixels:Xo,multinomial:Yo,oneHot:Qo,pad:Jo,pad1d:Zo,pad2d:ti,pad3d:ei,pad4d:ni,rand:ri,randomNormal:oi,randomUniform:ii,reshape:ai,spaceToBatchND:si,squeeze:ui,stack:ci,tile:li,truncatedNormal:hi,unstack:pi,fill:he,linspace:pe,ones:ce,range:fe,scalar:ne,tensor:ee,tensor1d:re,tensor2d:oe,tensor3d:ie,tensor4d:ae,tensor5d:se,tensor6d:ue,zeros:le,onesLike:Re,zerosLike:Te,transpose:Os,softmax:Qt,localResponseNormalization:Ps,norm:Fs,gather:zs,unsortedSegmentSum:Ws,basicLSTMCell:Us,multiRNNCell:Vs,movingAverage:Gs,stridedSlice:qs,topk:js,scatterND:Hs,fft:$s,sparseToDense:Xs,gatherND:Js,train:Mc,tidy:bt,keep:wt,dispose:Et,time:St,profile:_t,customGrad:yt,grad:function(i){return D(k(i),"The f passed in grad(f) must be a function"),function(r,o){return D(r instanceof Y,"The x passed in grad(f)(x) must be a tensor"),D(null==o||o instanceof Y,"The dy passed in grad(f)(x, dy) must be a tensor"),mt.engine.tidy(function(){var t=mt.engine.gradients(function(){return i(r)},[r],o),e=t.value,n=t.grads;return null!=o&&f(e.shape,o.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),xt(n),n[0]})}},grads:function(i){return D(k(i),"The f passed in grads(f) must be a function"),function(r,o){return D(Array.isArray(r)&&r.every(function(t){return t instanceof Y}),"The args passed in grads(f)(args) must be an array of tensors"),D(null==o||o instanceof Y,"The dy passed in grads(f)(args, dy) must be a tensor"),mt.engine.tidy(function(){var t=mt.engine.gradients(function(){return i.apply(void 0,r)},r,o),e=t.value,n=t.grads;return null!=o&&f(e.shape,o.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),xt(n),n})}},valueAndGrad:function(i){return D(k(i),"The f passed in valueAndGrad(f) must be a function"),function(t,e){D(t instanceof Y,"The x passed in valueAndGrad(f)(x) must be a tensor"),D(null==e||e instanceof Y,"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");var n=mt.engine.gradients(function(){return i(t)},[t],e),r=n.grads,o=n.value;return xt(r),{grad:r[0],value:o}}},valueAndGrads:function(r){return D(k(r),"The f passed in valueAndGrads(f) must be a function"),function(t,e){D(Array.isArray(t)&&t.every(function(t){return t instanceof Y}),"The args passed in valueAndGrads(f)(args) must be array of tensors"),D(null==e||e instanceof Y,"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");var n=mt.engine.gradients(function(){return r.apply(void 0,t)},t,e);return null!=e&&f(n.value.shape,e.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),xt(n.grads),n}},variableGrads:gt}),zc=function(t,e){return(zc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function Wc(t,e){function n(){this.constructor=t}zc(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var Uc=function(){return(Uc=Object.assign||function(t){for(var e,n=1,r=arguments.length;na[0]&&e[1] 1 not supported");return(o=r.getInput(0))instanceof e?(i=o,[3,4]):[3,2];case 2:return[4,Ol(o)];case 3:i=t.sent(),t.label=4;case 4:n=i,t.label=5;case 5:return a=_l(n),[2,u.map(function(t){return t instanceof $l?t.forSize(n.width,n.height).box.floor():t}).map(function(t){return t.clipAtImageBorders(n.width,n.height)}).map(function(t){var e=t.x,n=t.y,r=t.width,o=t.height,i=Rl({width:r,height:o});return _l(i).putImageData(a.getImageData(e,n,r,o),0,0),i})]}})})}function rh(u,e){return Vc(this,void 0,void 0,function(){return Gc(this,function(t){if(!Kc(u)&&!Xc(u))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(Xc(u)&&1 1 not supported");return[2,bt(function(){var t=u.shape.slice(Xc(u)?1:0),i=t[0],a=t[1],s=t[2];return e.map(function(t){return t instanceof $l?t.forSize(a,i).box:t}).map(function(t){return t.clipAtImageBorders(a,i)}).map(function(t){var e=t.x,n=t.y,r=t.width,o=t.height;return Da(u.as3D(i,a,s),[n,e,0],[o,r,s])})})]})})}function oh(e,n,r){return bt(function(){var t=ma(e,n.depthwise_filter,n.pointwise_filter,r,"same");return t=ns(t,n.bias)})}function ih(e,n,r,o){return void 0===r&&(r="same"),void 0===o&&(o=!1),bt(function(){var t=ns(pa(e,n.filters,[1,1],r),n.bias);return o?As(t):t})}function ah(a,s){return function(t,e,n,r){var o=ae(a(t*e*n*n),[n,n,t,e]),i=re(a(e));return s.push({paramPath:r+"/filters"},{paramPath:r+"/bias"}),{filters:o,bias:i}}}var sh=function(t,e,n){this.depthwise_filter=t,this.pointwise_filter=e,this.bias=n};var uh=function(t){return"number"==typeof t};function ch(t){if(![t.noObjectScale,t.objectScale,t.coordScale,t.classScale].every(uh))throw new Error("for training you have to specify noObjectScale, objectScale, coordScale, classScale parameters in your config.json file");return t}var lh,hh,ph=[3,16,32,64,128,256,512,1024,1024];function fh(e){return bt(function(){var t=ms(e,ne(.10000000149011612));return ns(As(ws(e,t)),t)})}function dh(e,n){return bt(function(){var t=Jo(e,[[0,0],[1,1],[1,1],[0,0]]);return t=pa(t,n.conv.filters,[1,1],"valid"),t=ws(t,n.bn.sub),t=ms(t,n.bn.truediv),fh(t=ns(t,n.conv.bias))})}function mh(e,n){return bt(function(){var t=Jo(e,[[0,0],[1,1],[1,1],[0,0]]);return t=ma(t,n.depthwise_filter,n.pointwise_filter,[1,1],"valid"),fh(t=ns(t,n.bias))})}function vh(s,u){var c=ah(s,u);var a,l,t=(a=s,l=u,function(t,e,n){var r=ae(a(9*t),[3,3,t,1]),o=ae(a(t*e),[1,1,t,e]),i=re(a(e));return l.push({paramPath:n+"/depthwise_filter"},{paramPath:n+"/pointwise_filter"},{paramPath:n+"/bias"}),new sh(r,o,i)});return{extractConvParams:c,extractConvWithBatchNormParams:function(t,e,n){var r,o,i,a;return{conv:c(t,e,3,n+"/conv"),bn:(o=n+"/bn",i=re(s(r=e)),a=re(s(r)),u.push({paramPath:o+"/sub"},{paramPath:o+"/truediv"}),{sub:i,truediv:a})}},extractSeparableConvParams:t}}function gh(t,e){var o,n=dl(t,e);function r(t){return{filters:n(t+"/filters",4),bias:n(t+"/bias",1)}}return{extractConvParams:r,extractConvWithBatchNormParams:function(t){var e;return{conv:r(t+"/conv"),bn:{sub:n((e=t+"/bn")+"/sub",1),truediv:n(e+"/truediv",1)}}},extractSeparableConvParams:(o=n,function(t){var e=o(t+"/depthwise_filter",4),n=o(t+"/pointwise_filter",4),r=o(t+"/bias",1);return new sh(e,n,r)})}}(hh=lh||(lh={}))[hh.XS=224]="XS",hh[hh.SM=320]="SM",hh[hh.MD=416]="MD",hh[hh.LG=608]="LG";var yh=function(){function t(t){var e=void 0===t?{}:t,n=e.inputSize,r=e.scoreThreshold;if(this._name="TinyYolov2Options",this._inputSize=n||416,this._scoreThreshold=r||.5,"number"!=typeof this._inputSize||this._inputSize%32!=0)throw new Error(this._name+" - expected inputSize to be a number divisible by 32");if("number"!=typeof this._scoreThreshold||this._scoreThreshold<=0||1<=this._scoreThreshold)throw new Error(this._name+" - expected scoreThreshold to be a number between 0 and 1")}return Object.defineProperty(t.prototype,"inputSize",{get:function(){return this._inputSize},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scoreThreshold",{get:function(){return this._scoreThreshold},enumerable:!0,configurable:!0}),t}(),xh=function(n){function t(t){var e=n.call(this,"TinyYolov2")||this;return function(t){if(!t)throw new Error("invalid config: "+t);if("boolean"!=typeof t.withSeparableConvs)throw new Error("config.withSeparableConvs has to be a boolean, have: "+t.withSeparableConvs);if(!uh(t.iouThreshold)||t.iouThreshold<0||1e.classScore?t:e})},t}(Hl),bh=function(){function t(t,e,n,r,o){this._config=o,this._reshapedImgDims=new qc(r.width,r.height),this._outputTensor=t,this._predictedBoxes=n,this.validateGroundTruthBoxes(e),this._groundTruth=this.assignGroundTruthToAnchors(e);var i=this.createGroundTruthMask(),a=this.createCoordAndScoreMasks(),s=a.coordBoxOffsetMask,u=a.coordBoxSizeMask,c=a.scoreMask;this.noObjectLossMask=bt(function(){return ms(c,ws(ne(1),i))}),this.objectLossMask=bt(function(){return ms(c,i)}),this.coordBoxOffsetMask=bt(function(){return ms(s,i)}),this.coordBoxSizeMask=bt(function(){return ms(u,i)});var l=bt(function(){return ws(ne(1),s.add(u).add(c))});this.groundTruthClassScoresMask=bt(function(){return ms(l,i)})}return Object.defineProperty(t.prototype,"config",{get:function(){return this._config},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"reshapedImgDims",{get:function(){return this._reshapedImgDims},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputTensor",{get:function(){return this._outputTensor},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"groundTruth",{get:function(){return this._groundTruth},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"predictedBoxes",{get:function(){return this._predictedBoxes},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputSize",{get:function(){return Math.max(this.reshapedImgDims.width,this.reshapedImgDims.height)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"withClassScores",{get:function(){return this._config.withClassScores||1a.config.classes.length-1)throw new Error("invalid ground truth data, expected label to be a number in [0, "+(a.config.classes.length-1)+"]");if(e<0||1 0");if("number"!=typeof this._scaleFactor||this._scaleFactor<=0||1<=this._scaleFactor)throw new Error(this._name+" - expected scaleFactor to be a number between 0 and 1");if("number"!=typeof this._maxNumScales||this._maxNumScales<0)throw new Error(this._name+" - expected maxNumScales to be a number > 0");if(!Array.isArray(this._scoreThresholds)||3!==this._scoreThresholds.length||this._scoreThresholds.some(function(t){return"number"!=typeof t}))throw new Error(this._name+" - expected scoreThresholds to be an array of numbers of length 3");if(this._scaleSteps&&(!Array.isArray(this._scaleSteps)||this._scaleSteps.some(function(t){return"number"!=typeof t})))throw new Error(this._name+" - expected scaleSteps to be an array of numbers")}return Object.defineProperty(t.prototype,"minFaceSize",{get:function(){return this._minFaceSize},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaleFactor",{get:function(){return this._scaleFactor},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxNumScales",{get:function(){return this._maxNumScales},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scoreThresholds",{get:function(){return this._scoreThresholds},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"scaleSteps",{get:function(){return this._scaleSteps},enumerable:!0,configurable:!0}),t}();function zh(l,h){function i(t,e,n,r,o){var i=ae(l(t*e*n*n),[n,n,t,e]),a=re(l(e));return h.push({paramPath:r+"/filters"},{paramPath:r+"/"+(o?"batch_norm_offset":"bias")}),{filters:i,bias:a}}function p(t,e,n,r){var o=i(t,e,n,r,!0);return{filters:o.filters,batch_norm_offset:o.bias}}function t(t,e,n){var r,o,i,a,s,u,c;return{depthwise_conv:(o=n+"/depthwise_conv",i=ae(l(9*(r=t)),[3,3,r,1]),a=re(l(r)),s=re(l(r)),u=re(l(r)),c=re(l(r)),h.push({paramPath:o+"/filters"},{paramPath:o+"/batch_norm_scale"},{paramPath:o+"/batch_norm_offset"},{paramPath:o+"/batch_norm_mean"},{paramPath:o+"/batch_norm_variance"}),{filters:i,batch_norm_scale:a,batch_norm_offset:s,batch_norm_mean:u,batch_norm_variance:c}),pointwise_conv:p(t,e,1,n+"/pointwise_conv")}}return{extractMobilenetV1Params:function(){return{conv_0:p(3,32,3,"mobilenetv1/conv_0"),conv_1:t(32,64,"mobilenetv1/conv_1"),conv_2:t(64,128,"mobilenetv1/conv_2"),conv_3:t(128,128,"mobilenetv1/conv_3"),conv_4:t(128,256,"mobilenetv1/conv_4"),conv_5:t(256,256,"mobilenetv1/conv_5"),conv_6:t(256,512,"mobilenetv1/conv_6"),conv_7:t(512,512,"mobilenetv1/conv_7"),conv_8:t(512,512,"mobilenetv1/conv_8"),conv_9:t(512,512,"mobilenetv1/conv_9"),conv_10:t(512,512,"mobilenetv1/conv_10"),conv_11:t(512,512,"mobilenetv1/conv_11"),conv_12:t(512,1024,"mobilenetv1/conv_12"),conv_13:t(1024,1024,"mobilenetv1/conv_13")}},extractPredictionLayerParams:function(){return{conv_0:p(1024,256,1,"prediction_layer/conv_0"),conv_1:p(256,512,3,"prediction_layer/conv_1"),conv_2:p(512,128,1,"prediction_layer/conv_2"),conv_3:p(128,256,3,"prediction_layer/conv_3"),conv_4:p(256,128,1,"prediction_layer/conv_4"),conv_5:p(128,256,3,"prediction_layer/conv_5"),conv_6:p(256,64,1,"prediction_layer/conv_6"),conv_7:p(64,128,3,"prediction_layer/conv_7"),box_predictor_0:{box_encoding_predictor:i(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),class_predictor:i(512,9,1,"prediction_layer/box_predictor_0/class_predictor")},box_predictor_1:{box_encoding_predictor:i(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),class_predictor:i(1024,18,1,"prediction_layer/box_predictor_1/class_predictor")},box_predictor_2:{box_encoding_predictor:i(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),class_predictor:i(512,18,1,"prediction_layer/box_predictor_2/class_predictor")},box_predictor_3:{box_encoding_predictor:i(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),class_predictor:i(256,18,1,"prediction_layer/box_predictor_3/class_predictor")},box_predictor_4:{box_encoding_predictor:i(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),class_predictor:i(256,18,1,"prediction_layer/box_predictor_4/class_predictor")},box_predictor_5:{box_encoding_predictor:i(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),class_predictor:i(128,18,1,"prediction_layer/box_predictor_5/class_predictor")}}}}}function Wh(t){var e=[],n=function(t,e){var i=dl(t,e);function a(t,e,n){return{filters:i(t+"/Conv2d_"+e+"_pointwise/weights",4,n+"/filters"),batch_norm_offset:i(t+"/Conv2d_"+e+"_pointwise/convolution_bn_offset",1,n+"/batch_norm_offset")}}function n(t){var e="mobilenetv1/conv_"+t,n="MobilenetV1/Conv2d_"+t+"_depthwise",r=e+"/depthwise_conv",o=e+"/pointwise_conv";return{depthwise_conv:{filters:i(n+"/depthwise_weights",4,r+"/filters"),batch_norm_scale:i(n+"/BatchNorm/gamma",1,r+"/batch_norm_scale"),batch_norm_offset:i(n+"/BatchNorm/beta",1,r+"/batch_norm_offset"),batch_norm_mean:i(n+"/BatchNorm/moving_mean",1,r+"/batch_norm_mean"),batch_norm_variance:i(n+"/BatchNorm/moving_variance",1,r+"/batch_norm_variance")},pointwise_conv:a("MobilenetV1",t,o)}}function r(t,e){return{filters:i(t+"/weights",4,e+"/filters"),bias:i(t+"/biases",1,e+"/bias")}}function o(t){return{box_encoding_predictor:r("Prediction/BoxPredictor_"+t+"/BoxEncodingPredictor","prediction_layer/box_predictor_"+t+"/box_encoding_predictor"),class_predictor:r("Prediction/BoxPredictor_"+t+"/ClassPredictor","prediction_layer/box_predictor_"+t+"/class_predictor")}}return{extractMobilenetV1Params:function(){return{conv_0:a("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:n(1),conv_2:n(2),conv_3:n(3),conv_4:n(4),conv_5:n(5),conv_6:n(6),conv_7:n(7),conv_8:n(8),conv_9:n(9),conv_10:n(10),conv_11:n(11),conv_12:n(12),conv_13:n(13)}},extractPredictionLayerParams:function(){return{conv_0:a("Prediction",0,"prediction_layer/conv_0"),conv_1:a("Prediction",1,"prediction_layer/conv_1"),conv_2:a("Prediction",2,"prediction_layer/conv_2"),conv_3:a("Prediction",3,"prediction_layer/conv_3"),conv_4:a("Prediction",4,"prediction_layer/conv_4"),conv_5:a("Prediction",5,"prediction_layer/conv_5"),conv_6:a("Prediction",6,"prediction_layer/conv_6"),conv_7:a("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:o(0),box_predictor_1:o(1),box_predictor_2:o(2),box_predictor_3:o(3),box_predictor_4:o(4),box_predictor_5:o(5)}}}}(t,e),r=n.extractMobilenetV1Params,o=n.extractPredictionLayerParams,i=t["Output/extra_dim"];if(e.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!Kc(i))throw new Error("expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have "+i);var a={mobilenetv1:r(),prediction_layer:o(),output_layer:{extra_dim:i}};return fl(t,e),{params:a,paramMappings:e}}function Uh(e,n,r){return bt(function(){var t=pa(e,n.filters,r,"same");return t=ns(t,n.batch_norm_offset),_i(t,0,6)})}var Vh=.0010000000474974513;function Gh(t,e){return bt(function(){var u=null,c=Uh(t,e.conv_0,[2,2]);if([e.conv_1,e.conv_2,e.conv_3,e.conv_4,e.conv_5,e.conv_6,e.conv_7,e.conv_8,e.conv_9,e.conv_10,e.conv_11,e.conv_12,e.conv_13].forEach(function(t,e){var n,r,o,i,a=e+1,s=(n=a,[2,4,6,12].some(function(t){return t===n})?[2,2]:[1,1]);r=c,o=t.depthwise_conv,i=s,c=Uh(c=bt(function(){var t=da(r,o.filters,i,"same");return t=Ji(t,o.batch_norm_mean,o.batch_norm_variance,Vh,o.batch_norm_scale,o.batch_norm_offset),_i(t,0,6)}),t.pointwise_conv,[1,1]),11===a&&(u=c)}),null===u)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:c,conv11:u}})}function qh(t,e,n){var r=Math.min(t.get(e,0),t.get(e,2)),o=Math.min(t.get(e,1),t.get(e,3)),i=Math.max(t.get(e,0),t.get(e,2)),a=Math.max(t.get(e,1),t.get(e,3)),s=Math.min(t.get(n,0),t.get(n,2)),u=Math.min(t.get(n,1),t.get(n,3)),c=Math.max(t.get(n,0),t.get(n,2)),l=Math.max(t.get(n,1),t.get(n,3)),h=(i-r)*(a-o),p=(c-s)*(l-u);if(h<=0||p<=0)return 0;var f=Math.max(r,s),d=Math.max(o,u),m=Math.min(i,c),v=Math.min(a,l),g=Math.max(m-f,0)*Math.max(v-d,0);return g/(h+p-g)}function jh(t,e){var n,r,o=(n=pi(Os(t,[1,0])),{sizes:r=[ws(n[2],n[0]),ws(n[3],n[1])],centers:[ns(n[0],as(r[0],ne(2))),ns(n[1],as(r[1],ne(2)))]}),i=o.sizes,a=o.centers,s=pi(Os(e,[1,0])),u=as(ms(ki(as(s[2],ne(5))),i[0]),ne(2)),c=ns(ms(as(s[0],ne(10)),i[0]),a[0]),l=as(ms(ki(as(s[3],ne(5))),i[1]),ne(2)),h=ns(ms(as(s[1],ne(10)),i[1]),a[1]);return Os(ci([ws(c,u),ws(h,l),ns(c,u),ns(h,l)]),[1,0])}function Hh(e,n){return bt(function(){var t=e.shape[0];return{boxPredictionEncoding:ai(ih(e,n.box_encoding_predictor),[t,-1,1,4]),classPrediction:ai(ih(e,n.class_predictor),[t,-1,3])}})}var $h=function(){function t(t){var e=void 0===t?{}:t,n=e.minConfidence,r=e.maxResults;if(this._name="SsdMobilenetv1Options",this._minConfidence=n||.5,this._maxResults=r||100,"number"!=typeof this._minConfidence||this._minConfidence<=0||1<=this._minConfidence)throw new Error(this._name+" - expected minConfidence to be a number between 0 and 1");if("number"!=typeof this._maxResults)throw new Error(this._name+" - expected maxResults to be a number")}return Object.defineProperty(t.prototype,"minConfidence",{get:function(){return this._minConfidence},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"maxResults",{get:function(){return this._maxResults},enumerable:!0,configurable:!0}),t}(),Kh=function(t){function e(){return t.call(this,"SsdMobilenetv1")||this}return Wc(e,t),e.prototype.forwardInput=function(u){var c=this.params;if(!c)throw new Error("SsdMobilenetv1 - load model before inference");return bt(function(){var l,h,p,o,i,a,t=u.toBatchTensor(512,!1).toFloat(),e=Gh(ws(ms(t,ne(.007843137718737125)),ne(1)),c.mobilenetv1),n=(l=e.out,h=e.conv11,p=c.prediction_layer,bt(function(){var t=Uh(Uh(l,p.conv_0,[1,1]),p.conv_1,[2,2]),e=Uh(Uh(t,p.conv_2,[1,1]),p.conv_3,[2,2]),n=Uh(Uh(e,p.conv_4,[1,1]),p.conv_5,[2,2]),r=Uh(Uh(n,p.conv_6,[1,1]),p.conv_7,[2,2]),o=Hh(h,p.box_predictor_0),i=Hh(l,p.box_predictor_1),a=Hh(t,p.box_predictor_2),s=Hh(e,p.box_predictor_3),u=Hh(n,p.box_predictor_4),c=Hh(r,p.box_predictor_5);return{boxPredictions:So([o.boxPredictionEncoding,i.boxPredictionEncoding,a.boxPredictionEncoding,s.boxPredictionEncoding,u.boxPredictionEncoding,c.boxPredictionEncoding],1),classPredictions:So([o.classPrediction,i.classPrediction,a.classPrediction,s.classPrediction,u.classPrediction,c.classPrediction],1)}})),r=n.boxPredictions,s=n.classPredictions;return o=r,i=s,a=c.output_layer,bt(function(){var t=o.shape[0],e=jh(ai(li(a.extra_dim,[t,1,1]),[-1,4]),ai(o,[-1,4]));e=ai(e,[t,e.shape[0]/t,4]);var n=Bi(Ta(i,[0,0,1],[-1,-1,-1])),r=Ta(n,[0,0,0],[-1,-1,1]);return r=ai(r,[t,r.shape[1]]),{boxes:pi(e),scores:pi(r)}})})},e.prototype.forward=function(n){return Vc(this,void 0,void 0,function(){var e;return Gc(this,function(t){switch(t.label){case 0:return e=this.forwardInput,[4,Wl(n)];case 1:return[2,e.apply(this,[t.sent()])]}})})},e.prototype.locateFaces=function(I,D){return void 0===D&&(D={}),Vc(this,void 0,void 0,function(){var l,h,p,f,d,m,v,g,y,x,b,w,E,S,_,C,R,T,k;return Gc(this,function(t){switch(t.label){case 0:return l=new $h(D),h=l.maxResults,p=l.minConfidence,[4,Wl(I)];case 1:for(f=t.sent(),d=this.forwardInput(f),m=d.boxes,v=d.scores,g=m[0],y=v[0],x=1;xa}).sort(function(t,e){return e.score-t.score}),c=[],u.forEach(function(t){if(!(c.length>=s)){for(var e=t.score,n=c.length-1;0<=n;--n){var r=qh(o,t.boxIndex,c[n]);if(0!==r&&(t.score*=r<=i?1:0,t.score<=a))break}e===t.score&&c.push(t.boxIndex)}}),S=c,_=f.getReshapedInputDimensions(0),C=f.inputSize,R=C/_.width,T=C/_.height,k=S.map(function(t){var e=[Math.max(0,g.get(t,0)),Math.min(1,g.get(t,2))].map(function(t){return t*T}),n=e[0],r=e[1],o=[Math.max(0,g.get(t,1)),Math.min(1,g.get(t,3))].map(function(t){return t*R}),i=o[0],a=o[1];return new $l(b[t],new pl(i,n,a-i,r-n),{height:f.getInputHeight(0),width:f.getInputWidth(0)})}),g.dispose(),y.dispose(),[2,k]}var o,e,n,i,a,r,s,u,c})})},e.prototype.getDefaultModelName=function(){return"ssd_mobilenetv1_model"},e.prototype.extractParamsFromWeigthMap=function(t){return Wh(t)},e.prototype.extractParams=function(t){return function(t){var e=[],n=ml(t),r=n.extractWeights,o=n.getRemainingWeights,i=zh(r,e),a=i.extractMobilenetV1Params,s=i.extractPredictionLayerParams,u=a(),c=s(),l={extra_dim:ie(r(20472),[1,5118,4])};if(e.push({paramPath:"output_layer/extra_dim"}),0!==o().length)throw new Error("weights remaing after extract: "+o().length);return{params:{mobilenetv1:u,prediction_layer:c,output_layer:l},paramMappings:e}}(t)},e}(Hl);function Xh(t){var e=new Kh;return e.extractWeights(t),e}var Yh=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Wc(e,t),e}(Kh),Qh=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._name="TinyFaceDetectorOptions",t}return Wc(t,e),t}(yh),Jh=function(){function t(){}return t.prototype.then=function(n){return Vc(this,void 0,void 0,function(){var e;return Gc(this,function(t){switch(t.label){case 0:return e=n,[4,this.run()];case 1:return[2,e.apply(void 0,[t.sent()])]}})})},t.prototype.run=function(){return Vc(this,void 0,void 0,function(){return Gc(this,function(t){throw new Error("ComposableTask - run is not implemented")})})},t}();var Zh=2,tp=12;function ep(r,o){var i,a,u=ah(r,o),c=(i=r,a=o,function(t,e,n){var r=oe(i(t*e),[t,e]),o=re(i(e));return a.push({paramPath:n+"/weights"},{paramPath:n+"/bias"}),{weights:r,bias:o}});function l(t,e){var n=re(r(t));return o.push({paramPath:e}),n}function h(t,e,n){return void 0===n&&(n=!1),{conv1:u(t[0],t[1],3,e+"/conv1"),prelu1_alpha:l(t[1],e+"/prelu1_alpha"),conv2:u(t[1],t[2],3,e+"/conv2"),prelu2_alpha:l(t[2],e+"/prelu2_alpha"),conv3:u(t[2],t[3],n?2:3,e+"/conv3"),prelu3_alpha:l(t[3],e+"/prelu3_alpha")}}return{extractPNetParams:function(){var t=h([3,10,16,32],"pnet"),e=u(32,2,1,"pnet/conv4_1"),n=u(32,4,1,"pnet/conv4_2");return Uc({},t,{conv4_1:e,conv4_2:n})},extractRNetParams:function(){var t=h([3,28,48,64],"rnet",!0),e=c(576,128,"rnet/fc1"),n=l(128,"rnet/prelu4_alpha"),r=c(128,2,"rnet/fc2_1"),o=c(128,4,"rnet/fc2_2");return Uc({},t,{fc1:e,prelu4_alpha:n,fc2_1:r,fc2_2:o})},extractONetParams:function(){var t=h([3,32,64,64],"onet"),e=u(64,128,2,"onet/conv4"),n=l(128,"onet/prelu4_alpha"),r=c(1152,256,"onet/fc1"),o=l(256,"onet/prelu5_alpha"),i=c(256,2,"onet/fc2_1"),a=c(256,4,"onet/fc2_2"),s=c(256,10,"onet/fc2_3");return Uc({},t,{conv4:e,prelu4_alpha:n,fc1:r,prelu5_alpha:o,fc2_1:i,fc2_2:a,fc2_3:s})}}}function np(t){var e=[],n=function(t,e){var n=dl(t,e);function u(t){return{filters:n(t+"/weights",4,t+"/filters"),bias:n(t+"/bias",1)}}function c(t){return{weights:n(t+"/weights",2),bias:n(t+"/bias",1)}}function l(t){return n(t,1)}function h(t){return{conv1:u(t+"/conv1"),prelu1_alpha:l(t+"/prelu1_alpha"),conv2:u(t+"/conv2"),prelu2_alpha:l(t+"/prelu2_alpha"),conv3:u(t+"/conv3"),prelu3_alpha:l(t+"/prelu3_alpha")}}return{extractPNetParams:function(){var t=h("pnet"),e=u("pnet/conv4_1"),n=u("pnet/conv4_2");return Uc({},t,{conv4_1:e,conv4_2:n})},extractRNetParams:function(){var t=h("rnet"),e=c("rnet/fc1"),n=l("rnet/prelu4_alpha"),r=c("rnet/fc2_1"),o=c("rnet/fc2_2");return Uc({},t,{fc1:e,prelu4_alpha:n,fc2_1:r,fc2_2:o})},extractONetParams:function(){var t=h("onet"),e=u("onet/conv4"),n=l("onet/prelu4_alpha"),r=c("onet/fc1"),o=l("onet/prelu5_alpha"),i=c("onet/fc2_1"),a=c("onet/fc2_2"),s=c("onet/fc2_3");return Uc({},t,{conv4:e,prelu4_alpha:n,fc1:r,prelu5_alpha:o,fc2_1:i,fc2_2:a,fc2_3:s})}}}(t,e),r=n.extractPNetParams,o=n.extractRNetParams,i=n.extractONetParams,a=r(),s=o(),u=i();return fl(t,e),{params:{pnet:a,rnet:s,onet:u},paramMappings:e}}function rp(t,e){var n=e[0],r=e[1];return{height:Math.floor(n*t),width:Math.floor(r*t)}}var op=function(o){function t(t,e,n,r){return o.call(this,{left:t,top:e,right:n,bottom:r},!0)||this}return Wc(t,o),t}(al);function ip(t){return bt(function(){return ms(ws(t,ne(127.5)),ne(.0078125))})}function ap(t,e){return bt(function(){return ns(As(t),ms(e,Oi(As(Oi(t)))))})}function sp(e,n,r){return void 0===r&&(r=!1),bt(function(){var t=ih(e,n.conv1,"valid");return t=ap(t,n.prelu1_alpha),t=ap(t=ih(t=_a(t,r?[2,2]:[3,3],[2,2],"same"),n.conv2,"valid"),n.prelu2_alpha),t=ap(t=ih(t=r?t:_a(t,[3,3],[2,2],"valid"),n.conv3,"valid"),n.prelu3_alpha)})}function up(h,t,u,p,c){c.stage1=[];var e=t.map(function(l){return bt(function(){var o,i,r,a,t={scale:l},e=(o=h,i=l,bt(function(){var t=rp(i,o.shape.slice(1)),e=t.height,n=t.width,r=ip(xu.resizeBilinear(o,[e,n]));return Os(r,[0,2,1,3])})),n=Date.now(),s=(r=e,a=p,bt(function(){var t=sp(r,a,!0),e=ih(t,a.conv4_1,"valid"),n=$o(Ba(e,3),3);return{prob:Qt(ws(e,n),3),regions:ih(t,a.conv4_2,"valid")}})),u=s.prob,c=s.regions;return t.pnet=Date.now()-n,{scoresTensor:pi(pi(u,3)[1])[0],regionsTensor:pi(c)[0],scale:l,statsForScale:t}})}).map(function(t){var e=t.scoresTensor,n=t.regionsTensor,r=t.scale,o=t.statsForScale,i=function(e,n,r,t){for(var o=[],i=0;i=t&&o.push(new jc(a,i));return o.map(function(t){return{cell:new sl(Math.round((t.y*Zh+1)/r),Math.round((t.x*Zh+1)/r),Math.round((t.y*Zh+tp)/r),Math.round((t.x*Zh+tp)/r)),score:e.get(t.y,t.x),region:new op(n.get(t.y,t.x,0),n.get(t.y,t.x,1),n.get(t.y,t.x,2),n.get(t.y,t.x,3))}})}(e,n,r,u);if(e.dispose(),n.dispose(),!i.length)return c.stage1.push(o),[];var a=Date.now(),s=Vl(i.map(function(t){return t.cell}),i.map(function(t){return t.score}),.5);return o.nms=Date.now()-a,o.numBoxes=s.length,c.stage1.push(o),s.map(function(t){return i[t]})}).reduce(function(t,e){return t.concat(e)},[]),n=[],r=[];if(0g}).map(function(t){return t.idx}),c=u.map(function(t){return v[t]}),l=u.map(function(t){return i[t]}),h=[],p=[],0y}).map(function(t){return t.idx}),c=u.map(function(t){return new op(o[t].regions.get(0,0),o[t].regions.get(0,1),o[t].regions.get(0,2),o[t].regions.get(0,3))}),l=u.map(function(t,e){return g[t].calibrate(c[e])}),h=u.map(function(t){return i[t]}),p=[],f=[],d=[],0tp}).slice(0,f),r.scales=v,r.pyramid=v.map(function(t){return rp(t,[u,c])}),g=Date.now(),[4,up(i,v,d[0],e.pnet,r)];case 1:return y=t.sent(),r.total_stage1=Date.now()-g,y.boxes.length?(r.stage2_numInputBoxes=y.boxes.length,g=Date.now(),[4,lp(n,y.boxes,d[1],e.rnet,r)]):[2,a({results:[],stats:r})];case 2:return x=t.sent(),r.total_stage2=Date.now()-g,x.boxes.length?(r.stage3_numInputBoxes=x.boxes.length,g=Date.now(),[4,hp(n,x.boxes,d[2],e.onet,r)]):[2,a({results:[],stats:r})];case 3:return b=t.sent(),r.total_stage3=Date.now()-g,w=b.boxes.map(function(e,t){return new Kl(new $l(b.scores[t],new pl(e.left/c,e.top/u,e.width/c,e.height/u),{height:u,width:c}),new Yl(b.points[t].map(function(t){return t.sub(new jc(e.left,e.top)).div(new jc(e.width,e.height))}),{width:e.width,height:e.height}))}),[2,a({results:w,stats:r})]}})})},e.prototype.forward=function(n,r){return void 0===r&&(r={}),Vc(this,void 0,void 0,function(){var e;return Gc(this,function(t){switch(t.label){case 0:return e=this.forwardInput,[4,Wl(n)];case 1:return[4,e.apply(this,[t.sent(),r])];case 2:return[2,t.sent().results]}})})},e.prototype.forwardWithStats=function(n,r){return void 0===r&&(r={}),Vc(this,void 0,void 0,function(){var e;return Gc(this,function(t){switch(t.label){case 0:return e=this.forwardInput,[4,Wl(n)];case 1:return[2,e.apply(this,[t.sent(),r])]}})})},e.prototype.getDefaultModelName=function(){return"mtcnn_model"},e.prototype.extractParamsFromWeigthMap=function(t){return np(t)},e.prototype.extractParams=function(t){return function(t){var e=ml(t),n=e.extractWeights,r=e.getRemainingWeights,o=[],i=ep(n,o),a=i.extractPNetParams,s=i.extractRNetParams,u=i.extractONetParams,c=a(),l=s(),h=u();if(0!==r().length)throw new Error("weights remaing after extract: "+r().length);return{params:{pnet:c,rnet:l,onet:h},paramMappings:o}}(t)},e}(Hl),fp=[new jc(1.603231,2.094468),new jc(6.041143,7.080126),new jc(2.882459,3.518061),new jc(4.266906,5.178857),new jc(9.041765,10.66308)],dp=[117.001,114.697,97.404],mp=function(e){function t(){var t={withSeparableConvs:!0,iouThreshold:.4,classes:["face"],anchors:fp,meanRgb:dp,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};return e.call(this,t)||this}return Wc(t,e),Object.defineProperty(t.prototype,"anchors",{get:function(){return this.config.anchors},enumerable:!0,configurable:!0}),t.prototype.locateFaces=function(e,n){return Vc(this,void 0,void 0,function(){return Gc(this,function(t){switch(t.label){case 0:return[4,this.detect(e,n)];case 1:return[2,t.sent().map(function(t){return new $l(t.score,t.relativeBox,{width:t.imageWidth,height:t.imageHeight})})]}})})},t.prototype.getDefaultModelName=function(){return"tiny_face_detector_model"},t.prototype.extractParamsFromWeigthMap=function(t){return e.prototype.extractParamsFromWeigthMap.call(this,t)},t}(xh),vp=[new jc(.738768,.874946),new jc(2.42204,2.65704),new jc(4.30971,7.04493),new jc(10.246,4.59428),new jc(12.6868,11.8741)],gp=[new jc(1.603231,2.094468),new jc(6.041143,7.080126),new jc(2.882459,3.518061),new jc(4.266906,5.178857),new jc(9.041765,10.66308)],yp=[117.001,114.697,97.404],xp=function(n){function t(t){void 0===t&&(t=!0);var e=Object.assign({},{withSeparableConvs:t,iouThreshold:.4,classes:["face"]},t?{anchors:gp,meanRgb:yp}:{anchors:vp,withClassScores:!0});return n.call(this,e)||this}return Wc(t,n),Object.defineProperty(t.prototype,"withSeparableConvs",{get:function(){return this.config.withSeparableConvs},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"anchors",{get:function(){return this.config.anchors},enumerable:!0,configurable:!0}),t.prototype.locateFaces=function(e,n){return Vc(this,void 0,void 0,function(){return Gc(this,function(t){switch(t.label){case 0:return[4,this.detect(e,n)];case 1:return[2,t.sent().map(function(t){return new $l(t.score,t.relativeBox,{width:t.imageWidth,height:t.imageHeight})})]}})})},t.prototype.getDefaultModelName=function(){return this.withSeparableConvs?"tiny_yolov2_separable_conv_model":"tiny_yolov2_model"},t.prototype.extractParamsFromWeigthMap=function(t){return n.prototype.extractParamsFromWeigthMap.call(this,t)},t}(xh),bp={ssdMobilenetv1:new Kh,tinyFaceDetector:new mp,tinyYolov2:new xp,mtcnn:new pp,faceLandmark68Net:new Rh,faceLandmark68TinyNet:new kh,faceRecognitionNet:new Lh},wp=function(t,e){return bp.ssdMobilenetv1.locateFaces(t,e)},Ep=function(t){return bp.faceLandmark68Net.detectLandmarks(t)},Sp=function(t){return bp.ssdMobilenetv1.load(t)},_p=Sp,Cp=wp,Rp=Ep,Tp=function(r){function t(t,e){var n=r.call(this)||this;return n.detectFaceLandmarksTask=t,n.input=e,n}return Wc(t,r),t}(Jh),kp=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Wc(e,t),e.prototype.run=function(){return Vc(this,void 0,void 0,function(){var e,n,i,r,o,a=this;return Gc(this,function(t){switch(t.label){case 0:return[4,this.detectFaceLandmarksTask];case 1:return e=t.sent(),n=e.map(function(t){return t.alignedRect}),this.input instanceof Y?[4,rh(this.input,n)]:[3,3];case 2:return r=t.sent(),[3,5];case 3:return[4,nh(this.input,n)];case 4:r=t.sent(),t.label=5;case 5:return i=r,[4,Promise.all(e.map(function(t,n){var r=t.detection,o=t.landmarks;return Vc(a,void 0,void 0,function(){var e;return Gc(this,function(t){switch(t.label){case 0:return[4,bp.faceRecognitionNet.computeFaceDescriptor(i[n])];case 1:return e=t.sent(),[2,new Zl(r,o,e)]}})})}))];case 6:return o=t.sent(),i.forEach(function(t){return t instanceof Y&&t.dispose()}),[2,o]}})})},e}(Tp),Ip=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Wc(e,t),e.prototype.run=function(){return Vc(this,void 0,void 0,function(){var e,n,r,o,i,a,s;return Gc(this,function(t){switch(t.label){case 0:return[4,this.detectFaceLandmarksTask];case 1:return(e=t.sent())?(n=e.detection,r=e.landmarks,o=e.alignedRect,this.input instanceof Y?[4,rh(this.input,[o])]:[3,3]):[2];case 2:return a=t.sent(),[3,5];case 3:return[4,nh(this.input,[o])];case 4:a=t.sent(),t.label=5;case 5:return i=a,[4,bp.faceRecognitionNet.computeFaceDescriptor(i[0])];case 6:return s=t.sent(),i.forEach(function(t){return t instanceof Y&&t.dispose()}),[2,new Zl(n,r,s)]}})})},e}(Tp),Dp=function(o){function t(t,e,n){var r=o.call(this)||this;return r.detectFacesTask=t,r.input=e,r.useTinyLandmarkNet=n,r}return Wc(t,o),Object.defineProperty(t.prototype,"landmarkNet",{get:function(){return this.useTinyLandmarkNet?bp.faceLandmark68TinyNet:bp.faceLandmark68Net},enumerable:!0,configurable:!0}),t}(Jh),Np=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Wc(e,t),e.prototype.run=function(){return Vc(this,void 0,void 0,function(){var e,n,r,o,i=this;return Gc(this,function(t){switch(t.label){case 0:return[4,this.detectFacesTask];case 1:return e=t.sent(),this.input instanceof Y?[4,rh(this.input,e)]:[3,3];case 2:return r=t.sent(),[3,5];case 3:return[4,nh(this.input,e)];case 4:r=t.sent(),t.label=5;case 5:return n=r,[4,Promise.all(n.map(function(t){return i.landmarkNet.detectLandmarks(t)}))];case 6:return o=t.sent(),n.forEach(function(t){return t instanceof Y&&t.dispose()}),[2,e.map(function(t,e){return new Kl(t,o[e])})]}})})},e.prototype.withFaceDescriptors=function(){return new kp(this,this.input)},e}(Dp),Ap=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Wc(e,t),e.prototype.run=function(){return Vc(this,void 0,void 0,function(){var e,n,r,o;return Gc(this,function(t){switch(t.label){case 0:return[4,this.detectFacesTask];case 1:return(e=t.sent())?this.input instanceof Y?[4,rh(this.input,[e])]:[3,3]:[2];case 2:return r=t.sent(),[3,5];case 3:return[4,nh(this.input,[e])];case 4:r=t.sent(),t.label=5;case 5:return n=r,[4,this.landmarkNet.detectLandmarks(n[0])];case 6:return o=t.sent(),n.forEach(function(t){return t instanceof Y&&t.dispose()}),[2,new Kl(e,o)]}})})},e.prototype.withFaceDescriptor=function(){return new Ip(this,this.input)},e}(Dp),Mp=function(r){function t(t,e){void 0===e&&(e=new $h);var n=r.call(this)||this;return n.input=t,n.options=e,n}return Wc(t,r),t}(Jh),Op=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Wc(e,t),e.prototype.run=function(){return Vc(this,void 0,void 0,function(){var e,n,r,o;return Gc(this,function(t){switch(t.label){case 0:return n=(e=this).input,(r=e.options)instanceof Bh?[4,bp.mtcnn.forward(n,r)]:[3,2];case 1:return[2,t.sent().map(function(t){return t.faceDetection})];case 2:if(!(o=r instanceof Qh?function(t){return bp.tinyFaceDetector.locateFaces(t,r)}:r instanceof $h?function(t){return bp.ssdMobilenetv1.locateFaces(t,r)}:r instanceof yh?function(t){return bp.tinyYolov2.locateFaces(t,r)}:null))throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options");return[2,o(n)]}})})},e.prototype.withFaceLandmarks=function(t){return void 0===t&&(t=!1),new Np(this,this.input,t)},e}(Mp),Pp=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Wc(e,t),e.prototype.run=function(){return Vc(this,void 0,void 0,function(){var e,n;return Gc(this,function(t){switch(t.label){case 0:return[4,new Op(this.input,this.options)];case 1:return e=t.sent(),n=e[0],e.forEach(function(t){t.score>n.score&&(n=t)}),[2,n]}})})},e.prototype.withFaceLandmarks=function(t){return void 0===t&&(t=!1),new Ap(this,this.input,t)},e}(Mp);function Fp(t,e){return void 0===e&&(e=new $h),new Op(t,e)}function Lp(e,n){return Vc(this,void 0,void 0,function(){return Gc(this,function(t){switch(t.label){case 0:return[4,Fp(e,new $h(n?{minConfidence:n}:{})).withFaceLandmarks().withFaceDescriptors()];case 1:return[2,t.sent()]}})})}var Bp=Lp;function zp(t,e){if(t.length!==e.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");var n=Array.from(t),r=Array.from(e);return Math.sqrt(n.map(function(t,e){return t-r[e]}).reduce(function(t,e){return t+Math.pow(e,2)},0))}var Wp=function(){function t(t,e){void 0===e&&(e=.6),this._distanceThreshold=e;var n=Array.isArray(t)?t:[t];if(!n.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");var r=1,o=function(){return"person "+r++};this._labeledDescriptors=n.map(function(t){if(t instanceof th)return t;if(t instanceof Zl)return new th(o(),[t.descriptor]);if(t instanceof Float32Array)return new th(o(),[t]);throw new Error("FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | FullFaceDescription | Float32Array | Array")})}return Object.defineProperty(t.prototype,"labeledDescriptors",{get:function(){return this._labeledDescriptors},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"distanceThreshold",{get:function(){return this._distanceThreshold},enumerable:!0,configurable:!0}),t.prototype.computeMeanDistance=function(e,t){return t.map(function(t){return zp(t,e)}).reduce(function(t,e){return t+e},0)/(t.length||1)},t.prototype.matchDescriptor=function(r){var o=this;return this.labeledDescriptors.map(function(t){var e=t.descriptors,n=t.label;return new Jl(n,o.computeMeanDistance(r,e))}).reduce(function(t,e){return t.distance