From 7c4cf75d73960eedecc647d6edec6f7841391d91 Mon Sep 17 00:00:00 2001 From: Vladimir Mandic Date: Tue, 20 Oct 2020 07:58:20 -0400 Subject: [PATCH] log initialization --- dist/human.cjs | 9 +- dist/human.cjs.json | 8 +- dist/human.cjs.map | 4 +- dist/human.esm-nobundle.js | 12 +- dist/human.esm-nobundle.js.map | 4 +- dist/human.esm-nobundle.json | 8 +- dist/human.esm.js | 344 ++++++++++++++++----------------- dist/human.esm.js.map | 4 +- dist/human.esm.json | 8 +- dist/human.js | 344 ++++++++++++++++----------------- dist/human.js.map | 4 +- dist/human.json | 8 +- src/human.js | 6 +- 13 files changed, 383 insertions(+), 380 deletions(-) diff --git a/dist/human.cjs b/dist/human.cjs index b31d0bb4..56108a78 100644 --- a/dist/human.cjs +++ b/dist/human.cjs @@ -5777,7 +5777,7 @@ var require_config = __commonJS((exports2) => { var require_package = __commonJS((exports2, module2) => { module2.exports = { name: "@vladmandic/human", - version: "0.3.9", + version: "0.4.1", description: "human: 3D Face Detection, Iris Tracking and Age & Gender Prediction", sideEffects: false, main: "dist/human.cjs", @@ -5816,7 +5816,7 @@ var require_package = __commonJS((exports2, module2) => { scripts: { start: "node --trace-warnings --unhandled-rejections=strict --trace-uncaught --no-deprecation src/node.js", lint: "eslint src/*.js demo/*.js", - "build-iife": "esbuild --bundle --platform=browser --sourcemap --target=esnext --format=iife --minify --external:fs --global-name=human --metafile=dist/human.json --outfile=dist/human.js src/human.js", + "build-iife": "esbuild --bundle --platform=browser --sourcemap --target=esnext --format=iife --minify --external:fs --global-name=Human --metafile=dist/human.json --outfile=dist/human.js src/human.js", "build-esm-bundle": "esbuild --bundle --platform=browser --sourcemap --target=esnext --format=esm --minify --external:fs --metafile=dist/human.esm.json --outfile=dist/human.esm.js src/human.js", "build-esm-nobundle": "esbuild --bundle --platform=browser --sourcemap --target=esnext --format=esm --minify --external:@tensorflow --external:fs --metafile=dist/human.esm-nobundle.json --outfile=dist/human.esm-nobundle.js src/human.js", "build-node": "esbuild --bundle --platform=node --sourcemap --target=esnext --format=cjs --external:@tensorflow --metafile=dist/human.cjs.json --outfile=dist/human.cjs src/human.js", @@ -5852,6 +5852,7 @@ const handpose = require_handpose(); const fxImage = require_imagefx(); const defaults = require_config().default; const app = require_package(); +let first = true; const override = { face: {detector: {skipFrames: 0}, age: {skipFrames: 0}, emotion: {skipFrames: 0}}, hand: {skipFrames: 0} @@ -6038,11 +6039,11 @@ class Human { await tf.ready(); } perf.backend = Math.trunc(now() - timeStamp); - const loadedModels = Object.values(this.models).filter((a) => a).length; - if (loadedModels === 0) { + if (first) { this.log("Human library starting"); this.log("Configuration:", this.config); this.log("Flags:", tf.ENV.flags); + first = false; } timeStamp = now(); this.state = "load"; diff --git a/dist/human.cjs.json b/dist/human.cjs.json index f5641c89..db053455 100644 --- a/dist/human.cjs.json +++ b/dist/human.cjs.json @@ -116,7 +116,7 @@ "imports": [] }, "src/human.js": { - "bytes": 11405, + "bytes": 11355, "imports": [ { "path": "src/facemesh/facemesh.js" @@ -260,7 +260,7 @@ "dist/human.cjs.map": { "imports": [], "inputs": {}, - "bytes": 264025 + "bytes": 263891 }, "dist/human.cjs": { "imports": [], @@ -359,10 +359,10 @@ "bytesInOutput": 47 }, "src/human.js": { - "bytesInOutput": 10244 + "bytesInOutput": 10193 } }, - "bytes": 154612 + "bytes": 154561 } } } diff --git a/dist/human.cjs.map b/dist/human.cjs.map index 472cb1c4..c7027ea6 100644 --- a/dist/human.cjs.map +++ b/dist/human.cjs.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["../src/facemesh/blazeface.js", "../src/facemesh/keypoints.js", "../src/facemesh/box.js", "../src/facemesh/util.js", "../src/facemesh/pipeline.js", "../src/facemesh/uvcoords.js", "../src/facemesh/triangulation.js", "../src/facemesh/facemesh.js", "../src/ssrnet/ssrnet.js", "../src/emotion/emotion.js", "../src/posenet/modelBase.js", "../src/posenet/modelMobileNet.js", "../src/posenet/heapSort.js", "../src/posenet/buildParts.js", "../src/posenet/keypoints.js", "../src/posenet/vectors.js", "../src/posenet/decodePose.js", "../src/posenet/decodeMultiple.js", "../src/posenet/util.js", "../src/posenet/modelPoseNet.js", "../src/posenet/posenet.js", "../src/handpose/box.js", "../src/handpose/handdetector.js", "../src/handpose/keypoints.js", "../src/handpose/util.js", "../src/handpose/pipeline.js", "../src/handpose/handpose.js", "../src/imagefx.js", "../config.js", "../src/human.js", "../src/human.js"], - "sourcesContent": ["const tf = require('@tensorflow/tfjs');\n\nconst NUM_LANDMARKS = 6;\n\nfunction generateAnchors(inputSize) {\n const spec = { strides: [inputSize / 16, inputSize / 8], anchors: [2, 6] };\n const anchors = [];\n for (let i = 0; i < spec.strides.length; i++) {\n const stride = spec.strides[i];\n const gridRows = Math.floor((inputSize + stride - 1) / stride);\n const gridCols = Math.floor((inputSize + stride - 1) / stride);\n const anchorsNum = spec.anchors[i];\n for (let gridY = 0; gridY < gridRows; gridY++) {\n const anchorY = stride * (gridY + 0.5);\n for (let gridX = 0; gridX < gridCols; gridX++) {\n const anchorX = stride * (gridX + 0.5);\n for (let n = 0; n < anchorsNum; n++) {\n anchors.push([anchorX, anchorY]);\n }\n }\n }\n }\n return anchors;\n}\n\nconst disposeBox = (box) => {\n box.startEndTensor.dispose();\n box.startPoint.dispose();\n box.endPoint.dispose();\n};\n\nconst createBox = (startEndTensor) => ({\n startEndTensor,\n startPoint: tf.slice(startEndTensor, [0, 0], [-1, 2]),\n endPoint: tf.slice(startEndTensor, [0, 2], [-1, 2]),\n});\n\nconst scaleBox = (box, factors) => {\n const starts = tf.mul(box.startPoint, factors);\n const ends = tf.mul(box.endPoint, factors);\n const newCoordinates = tf.concat2d([starts, ends], 1);\n return createBox(newCoordinates);\n};\n\nfunction decodeBounds(boxOutputs, anchors, inputSize) {\n const boxStarts = tf.slice(boxOutputs, [0, 1], [-1, 2]);\n const centers = tf.add(boxStarts, anchors);\n const boxSizes = tf.slice(boxOutputs, [0, 3], [-1, 2]);\n const boxSizesNormalized = tf.div(boxSizes, inputSize);\n const centersNormalized = tf.div(centers, inputSize);\n const halfBoxSize = tf.div(boxSizesNormalized, 2);\n const starts = tf.sub(centersNormalized, halfBoxSize);\n const ends = tf.add(centersNormalized, halfBoxSize);\n const startNormalized = tf.mul(starts, inputSize);\n const endNormalized = tf.mul(ends, inputSize);\n const concatAxis = 1;\n return tf.concat2d([startNormalized, endNormalized], concatAxis);\n}\n\nfunction scaleBoxFromPrediction(face, scaleFactor) {\n return tf.tidy(() => {\n const box = face['box'] ? face['box'] : face;\n return scaleBox(box, scaleFactor).startEndTensor.squeeze();\n });\n}\n\nclass BlazeFaceModel {\n constructor(model, config) {\n this.blazeFaceModel = model;\n this.width = config.detector.inputSize;\n this.height = config.detector.inputSize;\n this.maxFaces = config.detector.maxFaces;\n this.anchorsData = generateAnchors(config.detector.inputSize);\n this.anchors = tf.tensor2d(this.anchorsData);\n this.inputSize = tf.tensor1d([this.width, this.height]);\n this.iouThreshold = config.detector.iouThreshold;\n this.scaleFaces = 0.8;\n this.scoreThreshold = config.detector.scoreThreshold;\n }\n\n // toto blazeface leaks two tensors per run\n async getBoundingBoxes(inputImage) {\n // sanity check on input\n if ((!inputImage) || (inputImage.isDisposedInternal) || (inputImage.shape.length !== 4) || (inputImage.shape[1] < 1) || (inputImage.shape[2] < 1)) return null;\n const [detectedOutputs, boxes, scores] = tf.tidy(() => {\n const resizedImage = inputImage.resizeBilinear([this.width, this.height]);\n const normalizedImage = tf.mul(tf.sub(resizedImage.div(255), 0.5), 2);\n const batchedPrediction = this.blazeFaceModel.predict(normalizedImage);\n let prediction;\n // are we using tfhub or pinto converted model?\n if (Array.isArray(batchedPrediction)) {\n const sorted = batchedPrediction.sort((a, b) => a.size - b.size);\n const concat384 = tf.concat([sorted[0], sorted[2]], 2); // dim: 384, 1 + 16\n const concat512 = tf.concat([sorted[1], sorted[3]], 2); // dim: 512, 1 + 16\n const concat = tf.concat([concat512, concat384], 1);\n prediction = concat.squeeze(0);\n } else {\n prediction = batchedPrediction.squeeze(); // when using tfhub model\n }\n const decodedBounds = decodeBounds(prediction, this.anchors, this.inputSize);\n const logits = tf.slice(prediction, [0, 0], [-1, 1]);\n const scoresOut = tf.sigmoid(logits).squeeze();\n return [prediction, decodedBounds, scoresOut];\n });\n const boxIndicesTensor = await tf.image.nonMaxSuppressionAsync(boxes, scores, this.maxFaces, this.iouThreshold, this.scoreThreshold);\n const boxIndices = await boxIndicesTensor.array();\n boxIndicesTensor.dispose();\n const boundingBoxesMap = boxIndices.map((boxIndex) => tf.slice(boxes, [boxIndex, 0], [1, -1]));\n const boundingBoxes = await Promise.all(boundingBoxesMap.map(async (boundingBox) => {\n const vals = await boundingBox.array();\n boundingBox.dispose();\n return vals;\n }));\n const annotatedBoxes = [];\n for (let i = 0; i < boundingBoxes.length; i++) {\n const boundingBox = boundingBoxes[i];\n const box = createBox(boundingBox);\n const boxIndex = boxIndices[i];\n const anchor = this.anchorsData[boxIndex];\n const sliced = tf.slice(detectedOutputs, [boxIndex, NUM_LANDMARKS - 1], [1, -1]);\n const squeezed = sliced.squeeze();\n const landmarks = squeezed.reshape([NUM_LANDMARKS, -1]);\n /*\n const landmarks = tf\n .slice(detectedOutputs, [boxIndex, NUM_LANDMARKS - 1], [1, -1])\n .squeeze()\n .reshape([NUM_LANDMARKS, -1]);\n */\n const probability = tf.slice(scores, [boxIndex], [1]);\n const annotatedBox = { box, landmarks, probability, anchor };\n annotatedBoxes.push(annotatedBox);\n sliced.dispose();\n squeezed.dispose();\n // landmarks.dispose();\n }\n detectedOutputs.dispose();\n boxes.dispose();\n scores.dispose();\n detectedOutputs.dispose();\n return {\n boxes: annotatedBoxes,\n scaleFactor: [inputImage.shape[2] / this.width, inputImage.shape[1] / this.height],\n };\n }\n\n async estimateFaces(input) {\n const { boxes, scaleFactor } = await this.getBoundingBoxes(input);\n return Promise.all(boxes.map(async (face) => {\n const scaledBox = scaleBoxFromPrediction(face, scaleFactor);\n const [landmarkData, boxData, probabilityData] = await Promise.all([face.landmarks, scaledBox, face.probability].map(async (d) => d.array()));\n const anchor = face.anchor;\n const [scaleFactorX, scaleFactorY] = scaleFactor;\n const scaledLandmarks = landmarkData\n .map((landmark) => ([\n (landmark[0] + anchor[0]) * scaleFactorX,\n (landmark[1] + anchor[1]) * scaleFactorY,\n ]));\n const normalizedFace = {\n topLeft: boxData.slice(0, 2),\n bottomRight: boxData.slice(2),\n landmarks: scaledLandmarks,\n probability: probabilityData,\n };\n disposeBox(face.box);\n face.landmarks.dispose();\n face.probability.dispose();\n scaledBox.dispose();\n return normalizedFace;\n }));\n }\n}\n\nasync function load(config) {\n const blazeface = await tf.loadGraphModel(config.detector.modelPath, { fromTFHub: config.detector.modelPath.includes('tfhub.dev') });\n const model = new BlazeFaceModel(blazeface, config);\n return model;\n}\n\nexports.load = load;\nexports.BlazeFaceModel = BlazeFaceModel;\nexports.disposeBox = disposeBox;\n", "exports.MESH_ANNOTATIONS = {\n silhouette: [\n 10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288,\n 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136,\n 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109,\n ],\n lipsUpperOuter: [61, 185, 40, 39, 37, 0, 267, 269, 270, 409, 291],\n lipsLowerOuter: [146, 91, 181, 84, 17, 314, 405, 321, 375, 291],\n lipsUpperInner: [78, 191, 80, 81, 82, 13, 312, 311, 310, 415, 308],\n lipsLowerInner: [78, 95, 88, 178, 87, 14, 317, 402, 318, 324, 308],\n rightEyeUpper0: [246, 161, 160, 159, 158, 157, 173],\n rightEyeLower0: [33, 7, 163, 144, 145, 153, 154, 155, 133],\n rightEyeUpper1: [247, 30, 29, 27, 28, 56, 190],\n rightEyeLower1: [130, 25, 110, 24, 23, 22, 26, 112, 243],\n rightEyeUpper2: [113, 225, 224, 223, 222, 221, 189],\n rightEyeLower2: [226, 31, 228, 229, 230, 231, 232, 233, 244],\n rightEyeLower3: [143, 111, 117, 118, 119, 120, 121, 128, 245],\n rightEyebrowUpper: [156, 70, 63, 105, 66, 107, 55, 193],\n rightEyebrowLower: [35, 124, 46, 53, 52, 65],\n rightEyeIris: [473, 474, 475, 476, 477],\n leftEyeUpper0: [466, 388, 387, 386, 385, 384, 398],\n leftEyeLower0: [263, 249, 390, 373, 374, 380, 381, 382, 362],\n leftEyeUpper1: [467, 260, 259, 257, 258, 286, 414],\n leftEyeLower1: [359, 255, 339, 254, 253, 252, 256, 341, 463],\n leftEyeUpper2: [342, 445, 444, 443, 442, 441, 413],\n leftEyeLower2: [446, 261, 448, 449, 450, 451, 452, 453, 464],\n leftEyeLower3: [372, 340, 346, 347, 348, 349, 350, 357, 465],\n leftEyebrowUpper: [383, 300, 293, 334, 296, 336, 285, 417],\n leftEyebrowLower: [265, 353, 276, 283, 282, 295],\n leftEyeIris: [468, 469, 470, 471, 472],\n midwayBetweenEyes: [168],\n noseTip: [1],\n noseBottom: [2],\n noseRightCorner: [98],\n noseLeftCorner: [327],\n rightCheek: [205],\n leftCheek: [425],\n};\nexports.MESH_TO_IRIS_INDICES_MAP = [ // A mapping from facemesh model keypoints to iris model keypoints.\n { key: 'EyeUpper0', indices: [9, 10, 11, 12, 13, 14, 15] },\n { key: 'EyeUpper1', indices: [25, 26, 27, 28, 29, 30, 31] },\n { key: 'EyeUpper2', indices: [41, 42, 43, 44, 45, 46, 47] },\n { key: 'EyeLower0', indices: [0, 1, 2, 3, 4, 5, 6, 7, 8] },\n { key: 'EyeLower1', indices: [16, 17, 18, 19, 20, 21, 22, 23, 24] },\n { key: 'EyeLower2', indices: [32, 33, 34, 35, 36, 37, 38, 39, 40] },\n { key: 'EyeLower3', indices: [54, 55, 56, 57, 58, 59, 60, 61, 62] },\n { key: 'EyebrowUpper', indices: [63, 64, 65, 66, 67, 68, 69, 70] },\n { key: 'EyebrowLower', indices: [48, 49, 50, 51, 52, 53] },\n];\n", "const tf = require('@tensorflow/tfjs');\n\nfunction scaleBoxCoordinates(box, factor) {\n const startPoint = [box.startPoint[0] * factor[0], box.startPoint[1] * factor[1]];\n const endPoint = [box.endPoint[0] * factor[0], box.endPoint[1] * factor[1]];\n return { startPoint, endPoint };\n}\nexports.scaleBoxCoordinates = scaleBoxCoordinates;\nfunction getBoxSize(box) {\n return [\n Math.abs(box.endPoint[0] - box.startPoint[0]),\n Math.abs(box.endPoint[1] - box.startPoint[1]),\n ];\n}\nexports.getBoxSize = getBoxSize;\nfunction getBoxCenter(box) {\n return [\n box.startPoint[0] + (box.endPoint[0] - box.startPoint[0]) / 2,\n box.startPoint[1] + (box.endPoint[1] - box.startPoint[1]) / 2,\n ];\n}\nexports.getBoxCenter = getBoxCenter;\nfunction cutBoxFromImageAndResize(box, image, cropSize) {\n const h = image.shape[1];\n const w = image.shape[2];\n const boxes = [[\n box.startPoint[1] / h, box.startPoint[0] / w, box.endPoint[1] / h,\n box.endPoint[0] / w,\n ]];\n return tf.image.cropAndResize(image, boxes, [0], cropSize);\n}\nexports.cutBoxFromImageAndResize = cutBoxFromImageAndResize;\nfunction enlargeBox(box, factor = 1.5) {\n const center = getBoxCenter(box);\n const size = getBoxSize(box);\n const newHalfSize = [factor * size[0] / 2, factor * size[1] / 2];\n const startPoint = [center[0] - newHalfSize[0], center[1] - newHalfSize[1]];\n const endPoint = [center[0] + newHalfSize[0], center[1] + newHalfSize[1]];\n return { startPoint, endPoint, landmarks: box.landmarks };\n}\nexports.enlargeBox = enlargeBox;\nfunction squarifyBox(box) {\n const centers = getBoxCenter(box);\n const size = getBoxSize(box);\n const maxEdge = Math.max(...size);\n const halfSize = maxEdge / 2;\n const startPoint = [centers[0] - halfSize, centers[1] - halfSize];\n const endPoint = [centers[0] + halfSize, centers[1] + halfSize];\n return { startPoint, endPoint, landmarks: box.landmarks };\n}\nexports.squarifyBox = squarifyBox;\n", "exports.IDENTITY_MATRIX = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];\n/**\n * Normalizes the provided angle to the range -pi to pi.\n * @param angle The angle in radians to be normalized.\n */\nfunction normalizeRadians(angle) {\n return angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));\n}\nexports.normalizeRadians = normalizeRadians;\n/**\n * Computes the angle of rotation between two anchor points.\n * @param point1 First anchor point\n * @param point2 Second anchor point\n */\nfunction computeRotation(point1, point2) {\n const radians = Math.PI / 2 - Math.atan2(-(point2[1] - point1[1]), point2[0] - point1[0]);\n return normalizeRadians(radians);\n}\nexports.computeRotation = computeRotation;\nfunction radToDegrees(rad) {\n return rad * 180 / Math.PI;\n}\nexports.radToDegrees = radToDegrees;\nfunction buildTranslationMatrix(x, y) {\n return [[1, 0, x], [0, 1, y], [0, 0, 1]];\n}\nfunction dot(v1, v2) {\n let product = 0;\n for (let i = 0; i < v1.length; i++) {\n product += v1[i] * v2[i];\n }\n return product;\n}\nexports.dot = dot;\nfunction getColumnFrom2DArr(arr, columnIndex) {\n const column = [];\n for (let i = 0; i < arr.length; i++) {\n column.push(arr[i][columnIndex]);\n }\n return column;\n}\nexports.getColumnFrom2DArr = getColumnFrom2DArr;\nfunction multiplyTransformMatrices(mat1, mat2) {\n const product = [];\n const size = mat1.length;\n for (let row = 0; row < size; row++) {\n product.push([]);\n for (let col = 0; col < size; col++) {\n product[row].push(dot(mat1[row], getColumnFrom2DArr(mat2, col)));\n }\n }\n return product;\n}\nfunction buildRotationMatrix(rotation, center) {\n const cosA = Math.cos(rotation);\n const sinA = Math.sin(rotation);\n const rotationMatrix = [[cosA, -sinA, 0], [sinA, cosA, 0], [0, 0, 1]];\n const translationMatrix = buildTranslationMatrix(center[0], center[1]);\n const translationTimesRotation = multiplyTransformMatrices(translationMatrix, rotationMatrix);\n const negativeTranslationMatrix = buildTranslationMatrix(-center[0], -center[1]);\n return multiplyTransformMatrices(translationTimesRotation, negativeTranslationMatrix);\n}\nexports.buildRotationMatrix = buildRotationMatrix;\nfunction invertTransformMatrix(matrix) {\n const rotationComponent = [[matrix[0][0], matrix[1][0]], [matrix[0][1], matrix[1][1]]];\n const translationComponent = [matrix[0][2], matrix[1][2]];\n const invertedTranslation = [\n -dot(rotationComponent[0], translationComponent),\n -dot(rotationComponent[1], translationComponent),\n ];\n return [\n rotationComponent[0].concat(invertedTranslation[0]),\n rotationComponent[1].concat(invertedTranslation[1]),\n [0, 0, 1],\n ];\n}\nexports.invertTransformMatrix = invertTransformMatrix;\nfunction rotatePoint(homogeneousCoordinate, rotationMatrix) {\n return [\n dot(homogeneousCoordinate, rotationMatrix[0]),\n dot(homogeneousCoordinate, rotationMatrix[1]),\n ];\n}\nexports.rotatePoint = rotatePoint;\nfunction xyDistanceBetweenPoints(a, b) {\n return Math.sqrt(((a[0] - b[0]) ** 2) + ((a[1] - b[1]) ** 2));\n}\nexports.xyDistanceBetweenPoints = xyDistanceBetweenPoints;\n", "/* eslint-disable class-methods-use-this */\nconst tf = require('@tensorflow/tfjs');\nconst bounding = require('./box');\nconst keypoints = require('./keypoints');\nconst util = require('./util');\n\nconst LANDMARKS_COUNT = 468;\nconst UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD = 0.25;\nconst MESH_MOUTH_INDEX = 13;\nconst MESH_KEYPOINTS_LINE_OF_SYMMETRY_INDICES = [MESH_MOUTH_INDEX, keypoints.MESH_ANNOTATIONS['midwayBetweenEyes'][0]];\nconst BLAZEFACE_MOUTH_INDEX = 3;\nconst BLAZEFACE_NOSE_INDEX = 2;\nconst BLAZEFACE_KEYPOINTS_LINE_OF_SYMMETRY_INDICES = [BLAZEFACE_MOUTH_INDEX, BLAZEFACE_NOSE_INDEX];\nconst LEFT_EYE_OUTLINE = keypoints.MESH_ANNOTATIONS['leftEyeLower0'];\nconst LEFT_EYE_BOUNDS = [LEFT_EYE_OUTLINE[0], LEFT_EYE_OUTLINE[LEFT_EYE_OUTLINE.length - 1]];\nconst RIGHT_EYE_OUTLINE = keypoints.MESH_ANNOTATIONS['rightEyeLower0'];\nconst RIGHT_EYE_BOUNDS = [RIGHT_EYE_OUTLINE[0], RIGHT_EYE_OUTLINE[RIGHT_EYE_OUTLINE.length - 1]];\nconst IRIS_UPPER_CENTER_INDEX = 3;\nconst IRIS_LOWER_CENTER_INDEX = 4;\nconst IRIS_IRIS_INDEX = 71;\nconst IRIS_NUM_COORDINATES = 76;\n\n// Replace the raw coordinates returned by facemesh with refined iris model coordinates. Update the z coordinate to be an average of the original and the new. This produces the best visual effect.\nfunction replaceRawCoordinates(rawCoords, newCoords, prefix, keys) {\n for (let i = 0; i < keypoints.MESH_TO_IRIS_INDICES_MAP.length; i++) {\n const { key, indices } = keypoints.MESH_TO_IRIS_INDICES_MAP[i];\n const originalIndices = keypoints.MESH_ANNOTATIONS[`${prefix}${key}`];\n const shouldReplaceAllKeys = keys == null;\n if (shouldReplaceAllKeys || keys.includes(key)) {\n for (let j = 0; j < indices.length; j++) {\n const index = indices[j];\n rawCoords[originalIndices[j]] = [\n newCoords[index][0], newCoords[index][1],\n (newCoords[index][2] + rawCoords[originalIndices[j]][2]) / 2,\n ];\n }\n }\n }\n}\n// The Pipeline coordinates between the bounding box and skeleton models.\nclass Pipeline {\n constructor(boundingBoxDetector, meshDetector, irisModel, config) {\n // An array of facial bounding boxes.\n this.regionsOfInterest = [];\n this.runsWithoutFaceDetector = 0;\n this.boundingBoxDetector = boundingBoxDetector;\n this.meshDetector = meshDetector;\n this.irisModel = irisModel;\n this.meshWidth = config.mesh.inputSize;\n this.meshHeight = config.mesh.inputSize;\n this.irisSize = config.iris.inputSize;\n this.irisEnlarge = config.iris.enlargeFactor;\n }\n\n transformRawCoords(rawCoords, box, angle, rotationMatrix) {\n const boxSize = bounding.getBoxSize({ startPoint: box.startPoint, endPoint: box.endPoint });\n const scaleFactor = [boxSize[0] / this.meshWidth, boxSize[1] / this.meshHeight];\n const coordsScaled = rawCoords.map((coord) => ([\n scaleFactor[0] * (coord[0] - this.meshWidth / 2),\n scaleFactor[1] * (coord[1] - this.meshHeight / 2), coord[2],\n ]));\n const coordsRotationMatrix = util.buildRotationMatrix(angle, [0, 0]);\n const coordsRotated = coordsScaled.map((coord) => ([...util.rotatePoint(coord, coordsRotationMatrix), coord[2]]));\n const inverseRotationMatrix = util.invertTransformMatrix(rotationMatrix);\n const boxCenter = [...bounding.getBoxCenter({ startPoint: box.startPoint, endPoint: box.endPoint }), 1];\n const originalBoxCenter = [\n util.dot(boxCenter, inverseRotationMatrix[0]),\n util.dot(boxCenter, inverseRotationMatrix[1]),\n ];\n return coordsRotated.map((coord) => ([\n coord[0] + originalBoxCenter[0],\n coord[1] + originalBoxCenter[1], coord[2],\n ]));\n }\n\n getLeftToRightEyeDepthDifference(rawCoords) {\n const leftEyeZ = rawCoords[LEFT_EYE_BOUNDS[0]][2];\n const rightEyeZ = rawCoords[RIGHT_EYE_BOUNDS[0]][2];\n return leftEyeZ - rightEyeZ;\n }\n\n // Returns a box describing a cropped region around the eye fit for passing to the iris model.\n getEyeBox(rawCoords, face, eyeInnerCornerIndex, eyeOuterCornerIndex, flip = false) {\n const box = bounding.squarifyBox(bounding.enlargeBox(this.calculateLandmarksBoundingBox([rawCoords[eyeInnerCornerIndex], rawCoords[eyeOuterCornerIndex]]), this.irisEnlarge));\n const boxSize = bounding.getBoxSize(box);\n let crop = tf.image.cropAndResize(face, [[\n box.startPoint[1] / this.meshHeight,\n box.startPoint[0] / this.meshWidth, box.endPoint[1] / this.meshHeight,\n box.endPoint[0] / this.meshWidth,\n ]], [0], [this.irisSize, this.irisSize]);\n if (flip) {\n crop = tf.image.flipLeftRight(crop);\n }\n return { box, boxSize, crop };\n }\n\n // Given a cropped image of an eye, returns the coordinates of the contours surrounding the eye and the iris.\n getEyeCoords(eyeData, eyeBox, eyeBoxSize, flip = false) {\n const eyeRawCoords = [];\n for (let i = 0; i < IRIS_NUM_COORDINATES; i++) {\n const x = eyeData[i * 3];\n const y = eyeData[i * 3 + 1];\n const z = eyeData[i * 3 + 2];\n eyeRawCoords.push([\n (flip\n ? (1 - (x / this.irisSize))\n : (x / this.irisSize)) * eyeBoxSize[0] + eyeBox.startPoint[0],\n (y / this.irisSize) * eyeBoxSize[1] + eyeBox.startPoint[1], z,\n ]);\n }\n return { rawCoords: eyeRawCoords, iris: eyeRawCoords.slice(IRIS_IRIS_INDEX) };\n }\n\n // The z-coordinates returned for the iris are unreliable, so we take the z values from the surrounding keypoints.\n getAdjustedIrisCoords(rawCoords, irisCoords, direction) {\n const upperCenterZ = rawCoords[keypoints.MESH_ANNOTATIONS[`${direction}EyeUpper0`][IRIS_UPPER_CENTER_INDEX]][2];\n const lowerCenterZ = rawCoords[keypoints.MESH_ANNOTATIONS[`${direction}EyeLower0`][IRIS_LOWER_CENTER_INDEX]][2];\n const averageZ = (upperCenterZ + lowerCenterZ) / 2;\n // Iris indices: 0: center | 1: right | 2: above | 3: left | 4: below\n return irisCoords.map((coord, i) => {\n let z = averageZ;\n if (i === 2) {\n z = upperCenterZ;\n } else if (i === 4) {\n z = lowerCenterZ;\n }\n return [coord[0], coord[1], z];\n });\n }\n\n async predict(input, config) {\n this.skipFrames = config.detector.skipFrames;\n this.maxFaces = config.detector.maxFaces;\n this.runsWithoutFaceDetector++;\n if (this.shouldUpdateRegionsOfInterest()) {\n const detector = await this.boundingBoxDetector.getBoundingBoxes(input);\n if (detector.boxes.length === 0) {\n this.regionsOfInterest = [];\n return null;\n }\n const scaledBoxes = detector.boxes.map((prediction) => {\n const startPoint = prediction.box.startPoint.squeeze();\n const endPoint = prediction.box.endPoint.squeeze();\n const predictionBox = {\n startPoint: startPoint.arraySync(),\n endPoint: endPoint.arraySync(),\n };\n startPoint.dispose();\n endPoint.dispose();\n const scaledBox = bounding.scaleBoxCoordinates(predictionBox, detector.scaleFactor);\n const enlargedBox = bounding.enlargeBox(scaledBox);\n const landmarks = prediction.landmarks.arraySync();\n prediction.box.startPoint.dispose();\n prediction.box.endPoint.dispose();\n prediction.landmarks.dispose();\n prediction.probability.dispose();\n return { ...enlargedBox, landmarks };\n });\n this.updateRegionsOfInterest(scaledBoxes);\n this.runsWithoutFaceDetector = 0;\n }\n const results = tf.tidy(() => this.regionsOfInterest.map((box, i) => {\n let angle = 0;\n // The facial bounding box landmarks could come either from blazeface (if we are using a fresh box), or from the mesh model (if we are reusing an old box).\n const boxLandmarksFromMeshModel = box.landmarks.length >= LANDMARKS_COUNT;\n let [indexOfMouth, indexOfForehead] = MESH_KEYPOINTS_LINE_OF_SYMMETRY_INDICES;\n if (boxLandmarksFromMeshModel === false) {\n [indexOfMouth, indexOfForehead] = BLAZEFACE_KEYPOINTS_LINE_OF_SYMMETRY_INDICES;\n }\n angle = util.computeRotation(box.landmarks[indexOfMouth], box.landmarks[indexOfForehead]);\n const faceCenter = bounding.getBoxCenter({ startPoint: box.startPoint, endPoint: box.endPoint });\n const faceCenterNormalized = [faceCenter[0] / input.shape[2], faceCenter[1] / input.shape[1]];\n let rotatedImage = input;\n let rotationMatrix = util.IDENTITY_MATRIX;\n if (angle !== 0) {\n rotatedImage = tf.image.rotateWithOffset(input, angle, 0, faceCenterNormalized);\n rotationMatrix = util.buildRotationMatrix(-angle, faceCenter);\n }\n const boxCPU = { startPoint: box.startPoint, endPoint: box.endPoint };\n const face = bounding.cutBoxFromImageAndResize(boxCPU, rotatedImage, [this.meshHeight, this.meshWidth]).div(255);\n // The first returned tensor represents facial contours, which are included in the coordinates.\n const [, flag, coords] = this.meshDetector.predict(face);\n const coordsReshaped = tf.reshape(coords, [-1, 3]);\n let rawCoords = coordsReshaped.arraySync();\n if (config.iris.enabled) {\n const { box: leftEyeBox, boxSize: leftEyeBoxSize, crop: leftEyeCrop } = this.getEyeBox(rawCoords, face, LEFT_EYE_BOUNDS[0], LEFT_EYE_BOUNDS[1], true);\n const { box: rightEyeBox, boxSize: rightEyeBoxSize, crop: rightEyeCrop } = this.getEyeBox(rawCoords, face, RIGHT_EYE_BOUNDS[0], RIGHT_EYE_BOUNDS[1]);\n const eyePredictions = (this.irisModel.predict(tf.concat([leftEyeCrop, rightEyeCrop])));\n const eyePredictionsData = eyePredictions.dataSync();\n eyePredictions.dispose();\n const leftEyeData = eyePredictionsData.slice(0, IRIS_NUM_COORDINATES * 3);\n const { rawCoords: leftEyeRawCoords, iris: leftIrisRawCoords } = this.getEyeCoords(leftEyeData, leftEyeBox, leftEyeBoxSize, true);\n const rightEyeData = eyePredictionsData.slice(IRIS_NUM_COORDINATES * 3);\n const { rawCoords: rightEyeRawCoords, iris: rightIrisRawCoords } = this.getEyeCoords(rightEyeData, rightEyeBox, rightEyeBoxSize);\n const leftToRightEyeDepthDifference = this.getLeftToRightEyeDepthDifference(rawCoords);\n if (Math.abs(leftToRightEyeDepthDifference) < 30) { // User is looking straight ahead.\n replaceRawCoordinates(rawCoords, leftEyeRawCoords, 'left');\n replaceRawCoordinates(rawCoords, rightEyeRawCoords, 'right');\n // If the user is looking to the left or to the right, the iris coordinates tend to diverge too much from the mesh coordinates for them to be merged. So we only update a single contour line above and below the eye.\n } else if (leftToRightEyeDepthDifference < 1) { // User is looking towards the right.\n replaceRawCoordinates(rawCoords, leftEyeRawCoords, 'left', ['EyeUpper0', 'EyeLower0']);\n } else { // User is looking towards the left.\n replaceRawCoordinates(rawCoords, rightEyeRawCoords, 'right', ['EyeUpper0', 'EyeLower0']);\n }\n const adjustedLeftIrisCoords = this.getAdjustedIrisCoords(rawCoords, leftIrisRawCoords, 'left');\n const adjustedRightIrisCoords = this.getAdjustedIrisCoords(rawCoords, rightIrisRawCoords, 'right');\n rawCoords = rawCoords.concat(adjustedLeftIrisCoords).concat(adjustedRightIrisCoords);\n }\n const transformedCoordsData = this.transformRawCoords(rawCoords, box, angle, rotationMatrix);\n tf.dispose(rawCoords);\n const landmarksBox = bounding.enlargeBox(this.calculateLandmarksBoundingBox(transformedCoordsData));\n const confidence = flag.squeeze();\n tf.dispose(flag);\n if (config.mesh.enabled) {\n const transformedCoords = tf.tensor2d(transformedCoordsData);\n this.regionsOfInterest[i] = { ...landmarksBox, landmarks: transformedCoords.arraySync() };\n const prediction = {\n coords: transformedCoords,\n box: landmarksBox,\n confidence,\n image: face,\n };\n return prediction;\n }\n const prediction = {\n coords: null,\n box: landmarksBox,\n confidence,\n image: face,\n };\n return prediction;\n }));\n return results;\n }\n\n // Updates regions of interest if the intersection over union between the incoming and previous regions falls below a threshold.\n updateRegionsOfInterest(boxes) {\n for (let i = 0; i < boxes.length; i++) {\n const box = boxes[i];\n const previousBox = this.regionsOfInterest[i];\n let iou = 0;\n if (previousBox && previousBox.startPoint) {\n const [boxStartX, boxStartY] = box.startPoint;\n const [boxEndX, boxEndY] = box.endPoint;\n const [previousBoxStartX, previousBoxStartY] = previousBox.startPoint;\n const [previousBoxEndX, previousBoxEndY] = previousBox.endPoint;\n const xStartMax = Math.max(boxStartX, previousBoxStartX);\n const yStartMax = Math.max(boxStartY, previousBoxStartY);\n const xEndMin = Math.min(boxEndX, previousBoxEndX);\n const yEndMin = Math.min(boxEndY, previousBoxEndY);\n const intersection = (xEndMin - xStartMax) * (yEndMin - yStartMax);\n const boxArea = (boxEndX - boxStartX) * (boxEndY - boxStartY);\n const previousBoxArea = (previousBoxEndX - previousBoxStartX) * (previousBoxEndY - boxStartY);\n iou = intersection / (boxArea + previousBoxArea - intersection);\n }\n if (iou < UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD) {\n this.regionsOfInterest[i] = box;\n }\n }\n this.regionsOfInterest = this.regionsOfInterest.slice(0, boxes.length);\n }\n\n clearRegionOfInterest(index) {\n if (this.regionsOfInterest[index] != null) {\n this.regionsOfInterest = [\n ...this.regionsOfInterest.slice(0, index),\n ...this.regionsOfInterest.slice(index + 1),\n ];\n }\n }\n\n shouldUpdateRegionsOfInterest() {\n if (this.regionsOfInterest.length === 0) return true; // nothing detected, so run detector on the next frame\n return (this.regionsOfInterest.length !== this.maxFaces) && (this.runsWithoutFaceDetector >= this.skipFrames);\n }\n\n calculateLandmarksBoundingBox(landmarks) {\n const xs = landmarks.map((d) => d[0]);\n const ys = landmarks.map((d) => d[1]);\n const startPoint = [Math.min(...xs), Math.min(...ys)];\n const endPoint = [Math.max(...xs), Math.max(...ys)];\n return { startPoint, endPoint, landmarks };\n }\n}\nexports.Pipeline = Pipeline;\n", "exports.UV_COORDS = [\n [0.499976992607117, 0.652534008026123],\n [0.500025987625122, 0.547487020492554],\n [0.499974012374878, 0.602371990680695],\n [0.482113003730774, 0.471979022026062],\n [0.500150978565216, 0.527155995368958],\n [0.499909996986389, 0.498252987861633],\n [0.499523013830185, 0.40106201171875],\n [0.289712011814117, 0.380764007568359],\n [0.499954998493195, 0.312398016452789],\n [0.499987006187439, 0.269918978214264],\n [0.500023007392883, 0.107050001621246],\n [0.500023007392883, 0.666234016418457],\n [0.5000159740448, 0.679224014282227],\n [0.500023007392883, 0.692348003387451],\n [0.499976992607117, 0.695277988910675],\n [0.499976992607117, 0.70593398809433],\n [0.499976992607117, 0.719385027885437],\n [0.499976992607117, 0.737019002437592],\n [0.499967992305756, 0.781370997428894],\n [0.499816000461578, 0.562981009483337],\n [0.473773002624512, 0.573909997940063],\n [0.104906998574734, 0.254140973091125],\n [0.365929991006851, 0.409575998783112],\n [0.338757991790771, 0.41302502155304],\n [0.311120003461838, 0.409460008144379],\n [0.274657994508743, 0.389131009578705],\n [0.393361985683441, 0.403706014156342],\n [0.345234006643295, 0.344011008739471],\n [0.370094001293182, 0.346076011657715],\n [0.319321990013123, 0.347265005111694],\n [0.297903001308441, 0.353591024875641],\n [0.24779200553894, 0.410809993743896],\n [0.396889001131058, 0.842755019664764],\n [0.280097991228104, 0.375599980354309],\n [0.106310002505779, 0.399955987930298],\n [0.2099249958992, 0.391353011131287],\n [0.355807989835739, 0.534406006336212],\n [0.471751004457474, 0.65040397644043],\n [0.474155008792877, 0.680191993713379],\n [0.439785003662109, 0.657229006290436],\n [0.414617002010345, 0.66654098033905],\n [0.450374007225037, 0.680860996246338],\n [0.428770989179611, 0.682690978050232],\n [0.374971002340317, 0.727805018424988],\n [0.486716985702515, 0.547628998756409],\n [0.485300987958908, 0.527395009994507],\n [0.257764995098114, 0.314490020275116],\n [0.401223003864288, 0.455172002315521],\n [0.429818987846375, 0.548614978790283],\n [0.421351999044418, 0.533740997314453],\n [0.276895999908447, 0.532056987285614],\n [0.483370006084442, 0.499586999416351],\n [0.33721199631691, 0.282882988452911],\n [0.296391993761063, 0.293242990970612],\n [0.169294998049736, 0.193813979625702],\n [0.447580009698868, 0.302609980106354],\n [0.392390012741089, 0.353887975215912],\n [0.354490011930466, 0.696784019470215],\n [0.067304998636246, 0.730105042457581],\n [0.442739009857178, 0.572826027870178],\n [0.457098007202148, 0.584792017936707],\n [0.381974011659622, 0.694710969924927],\n [0.392388999462128, 0.694203019142151],\n [0.277076005935669, 0.271932005882263],\n [0.422551989555359, 0.563233017921448],\n [0.385919004678726, 0.281364023685455],\n [0.383103013038635, 0.255840003490448],\n [0.331431001424789, 0.119714021682739],\n [0.229923993349075, 0.232002973556519],\n [0.364500999450684, 0.189113974571228],\n [0.229622006416321, 0.299540996551514],\n [0.173287004232407, 0.278747975826263],\n [0.472878992557526, 0.666198015213013],\n [0.446828007698059, 0.668527007102966],\n [0.422762006521225, 0.673889994621277],\n [0.445307999849319, 0.580065965652466],\n [0.388103008270264, 0.693961024284363],\n [0.403039008378983, 0.706539988517761],\n [0.403629004955292, 0.693953037261963],\n [0.460041999816895, 0.557139039039612],\n [0.431158006191254, 0.692366003990173],\n [0.452181994915009, 0.692366003990173],\n [0.475387006998062, 0.692366003990173],\n [0.465828001499176, 0.779190003871918],\n [0.472328990697861, 0.736225962638855],\n [0.473087012767792, 0.717857003211975],\n [0.473122000694275, 0.704625964164734],\n [0.473033010959625, 0.695277988910675],\n [0.427942007780075, 0.695277988910675],\n [0.426479011774063, 0.703539967536926],\n [0.423162013292313, 0.711845993995667],\n [0.4183090031147, 0.720062971115112],\n [0.390094995498657, 0.639572978019714],\n [0.013953999616206, 0.560034036636353],\n [0.499913990497589, 0.58014702796936],\n [0.413199990987778, 0.69539999961853],\n [0.409626007080078, 0.701822996139526],\n [0.468080013990402, 0.601534962654114],\n [0.422728985548019, 0.585985004901886],\n [0.463079988956451, 0.593783974647522],\n [0.37211999297142, 0.47341400384903],\n [0.334562003612518, 0.496073007583618],\n [0.411671012639999, 0.546965003013611],\n [0.242175996303558, 0.14767599105835],\n [0.290776997804642, 0.201445996761322],\n [0.327338010072708, 0.256527006626129],\n [0.399509996175766, 0.748921036720276],\n [0.441727995872498, 0.261676013469696],\n [0.429764986038208, 0.187834024429321],\n [0.412198007106781, 0.108901023864746],\n [0.288955003023148, 0.398952007293701],\n [0.218936994671822, 0.435410976409912],\n [0.41278201341629, 0.398970007896423],\n [0.257135003805161, 0.355440020561218],\n [0.427684992551804, 0.437960982322693],\n [0.448339998722076, 0.536936044692993],\n [0.178560003638268, 0.45755398273468],\n [0.247308000922203, 0.457193970680237],\n [0.286267012357712, 0.467674970626831],\n [0.332827985286713, 0.460712015628815],\n [0.368755996227264, 0.447206974029541],\n [0.398963987827301, 0.432654976844788],\n [0.476410001516342, 0.405806005001068],\n [0.189241006970406, 0.523923993110657],\n [0.228962004184723, 0.348950982093811],\n [0.490725994110107, 0.562400996685028],\n [0.404670000076294, 0.485132992267609],\n [0.019469000399113, 0.401564002037048],\n [0.426243007183075, 0.420431017875671],\n [0.396993011236191, 0.548797011375427],\n [0.266469985246658, 0.376977026462555],\n [0.439121007919312, 0.51895797252655],\n [0.032313998788595, 0.644356966018677],\n [0.419054001569748, 0.387154996395111],\n [0.462783008813858, 0.505746960639954],\n [0.238978996872902, 0.779744982719421],\n [0.198220998048782, 0.831938028335571],\n [0.107550002634525, 0.540755033493042],\n [0.183610007166862, 0.740257024765015],\n [0.134409993886948, 0.333683013916016],\n [0.385764002799988, 0.883153975009918],\n [0.490967005491257, 0.579378008842468],\n [0.382384985685349, 0.508572995662689],\n [0.174399003386497, 0.397670984268188],\n [0.318785011768341, 0.39623498916626],\n [0.343364000320435, 0.400596976280212],\n [0.396100014448166, 0.710216999053955],\n [0.187885001301765, 0.588537991046906],\n [0.430987000465393, 0.944064974784851],\n [0.318993002176285, 0.898285031318665],\n [0.266247987747192, 0.869701027870178],\n [0.500023007392883, 0.190576016902924],\n [0.499976992607117, 0.954452991485596],\n [0.366169989109039, 0.398822009563446],\n [0.393207013607025, 0.39553701877594],\n [0.410373002290726, 0.391080021858215],\n [0.194993004202843, 0.342101991176605],\n [0.388664990663528, 0.362284004688263],\n [0.365961998701096, 0.355970978736877],\n [0.343364000320435, 0.355356991291046],\n [0.318785011768341, 0.35834002494812],\n [0.301414996385574, 0.363156020641327],\n [0.058132998645306, 0.319076001644135],\n [0.301414996385574, 0.387449026107788],\n [0.499987989664078, 0.618434011936188],\n [0.415838003158569, 0.624195992946625],\n [0.445681989192963, 0.566076993942261],\n [0.465844005346298, 0.620640993118286],\n [0.49992299079895, 0.351523995399475],\n [0.288718998432159, 0.819945991039276],\n [0.335278987884521, 0.852819979190826],\n [0.440512001514435, 0.902418971061707],\n [0.128294005990028, 0.791940987110138],\n [0.408771991729736, 0.373893976211548],\n [0.455606997013092, 0.451801002025604],\n [0.499877005815506, 0.908990025520325],\n [0.375436991453171, 0.924192011356354],\n [0.11421000212431, 0.615022003650665],\n [0.448662012815475, 0.695277988910675],\n [0.4480200111866, 0.704632043838501],\n [0.447111994028091, 0.715808033943176],\n [0.444831997156143, 0.730794012546539],\n [0.430011987686157, 0.766808986663818],\n [0.406787008047104, 0.685672998428345],\n [0.400738000869751, 0.681069016456604],\n [0.392399996519089, 0.677703022956848],\n [0.367855995893478, 0.663918972015381],\n [0.247923001646996, 0.601333022117615],\n [0.452769994735718, 0.420849978923798],\n [0.43639200925827, 0.359887003898621],\n [0.416164010763168, 0.368713974952698],\n [0.413385987281799, 0.692366003990173],\n [0.228018000721931, 0.683571994304657],\n [0.468268007040024, 0.352671027183533],\n [0.411361992359161, 0.804327011108398],\n [0.499989002943039, 0.469825029373169],\n [0.479153990745544, 0.442654013633728],\n [0.499974012374878, 0.439637005329132],\n [0.432112008333206, 0.493588984012604],\n [0.499886006116867, 0.866917014122009],\n [0.49991300702095, 0.821729004383087],\n [0.456548988819122, 0.819200992584229],\n [0.344549000263214, 0.745438992977142],\n [0.37890899181366, 0.574010014533997],\n [0.374292999505997, 0.780184984207153],\n [0.319687992334366, 0.570737957954407],\n [0.357154995203018, 0.604269981384277],\n [0.295284003019333, 0.621580958366394],\n [0.447750002145767, 0.862477004528046],\n [0.410986006259918, 0.508723020553589],\n [0.31395098567009, 0.775308012962341],\n [0.354128003120422, 0.812552988529205],\n [0.324548006057739, 0.703992962837219],\n [0.189096003770828, 0.646299958229065],\n [0.279776990413666, 0.71465802192688],\n [0.1338230073452, 0.682700991630554],\n [0.336768001317978, 0.644733011722565],\n [0.429883986711502, 0.466521978378296],\n [0.455527991056442, 0.548622965812683],\n [0.437114000320435, 0.558896005153656],\n [0.467287987470627, 0.529924988746643],\n [0.414712011814117, 0.335219979286194],\n [0.37704598903656, 0.322777986526489],\n [0.344107985496521, 0.320150971412659],\n [0.312875986099243, 0.32233202457428],\n [0.283526003360748, 0.333190023899078],\n [0.241245999932289, 0.382785975933075],\n [0.102986000478268, 0.468762993812561],\n [0.267612010240555, 0.424560010433197],\n [0.297879010438919, 0.433175981044769],\n [0.333433985710144, 0.433878004550934],\n [0.366427004337311, 0.426115989685059],\n [0.396012008190155, 0.416696012020111],\n [0.420121014118195, 0.41022801399231],\n [0.007561000064015, 0.480777025222778],\n [0.432949006557465, 0.569517970085144],\n [0.458638995885849, 0.479089021682739],\n [0.473466008901596, 0.545744001865387],\n [0.476087987422943, 0.563830018043518],\n [0.468472003936768, 0.555056989192963],\n [0.433990985155106, 0.582361996173859],\n [0.483518004417419, 0.562983989715576],\n [0.482482999563217, 0.57784903049469],\n [0.42645001411438, 0.389798998832703],\n [0.438998997211456, 0.39649498462677],\n [0.450067013502121, 0.400434017181396],\n [0.289712011814117, 0.368252992630005],\n [0.276670008897781, 0.363372981548309],\n [0.517862021923065, 0.471948027610779],\n [0.710287988185883, 0.380764007568359],\n [0.526226997375488, 0.573909997940063],\n [0.895093023777008, 0.254140973091125],\n [0.634069979190826, 0.409575998783112],\n [0.661242008209229, 0.41302502155304],\n [0.688880026340485, 0.409460008144379],\n [0.725341975688934, 0.389131009578705],\n [0.606630027294159, 0.40370500087738],\n [0.654766023159027, 0.344011008739471],\n [0.629905998706818, 0.346076011657715],\n [0.680678009986877, 0.347265005111694],\n [0.702096998691559, 0.353591024875641],\n [0.75221198797226, 0.410804986953735],\n [0.602918028831482, 0.842862963676453],\n [0.719901978969574, 0.375599980354309],\n [0.893692970275879, 0.399959981441498],\n [0.790081977844238, 0.391354024410248],\n [0.643998026847839, 0.534487962722778],\n [0.528249025344849, 0.65040397644043],\n [0.525849997997284, 0.680191040039062],\n [0.560214996337891, 0.657229006290436],\n [0.585384011268616, 0.66654098033905],\n [0.549625992774963, 0.680860996246338],\n [0.57122802734375, 0.682691991329193],\n [0.624852001667023, 0.72809898853302],\n [0.513050019741058, 0.547281980514526],\n [0.51509702205658, 0.527251958847046],\n [0.742246985435486, 0.314507007598877],\n [0.598631024360657, 0.454979002475739],\n [0.570338010787964, 0.548575043678284],\n [0.578631997108459, 0.533622980117798],\n [0.723087012767792, 0.532054007053375],\n [0.516445994377136, 0.499638974666595],\n [0.662801027297974, 0.282917976379395],\n [0.70362401008606, 0.293271005153656],\n [0.830704987049103, 0.193813979625702],\n [0.552385985851288, 0.302568018436432],\n [0.607609987258911, 0.353887975215912],\n [0.645429015159607, 0.696707010269165],\n [0.932694971561432, 0.730105042457581],\n [0.557260990142822, 0.572826027870178],\n [0.542901992797852, 0.584792017936707],\n [0.6180260181427, 0.694710969924927],\n [0.607590973377228, 0.694203019142151],\n [0.722943007946014, 0.271963000297546],\n [0.577413976192474, 0.563166975975037],\n [0.614082992076874, 0.281386971473694],\n [0.616907000541687, 0.255886018276215],\n [0.668509006500244, 0.119913995265961],\n [0.770092010498047, 0.232020974159241],\n [0.635536015033722, 0.189248979091644],\n [0.77039098739624, 0.299556016921997],\n [0.826722025871277, 0.278755009174347],\n [0.527121007442474, 0.666198015213013],\n [0.553171992301941, 0.668527007102966],\n [0.577238023281097, 0.673889994621277],\n [0.554691970348358, 0.580065965652466],\n [0.611896991729736, 0.693961024284363],\n [0.59696102142334, 0.706539988517761],\n [0.596370995044708, 0.693953037261963],\n [0.539958000183105, 0.557139039039612],\n [0.568841993808746, 0.692366003990173],\n [0.547818005084991, 0.692366003990173],\n [0.52461302280426, 0.692366003990173],\n [0.534089982509613, 0.779141008853912],\n [0.527670979499817, 0.736225962638855],\n [0.526912987232208, 0.717857003211975],\n [0.526877999305725, 0.704625964164734],\n [0.526966989040375, 0.695277988910675],\n [0.572058022022247, 0.695277988910675],\n [0.573521018028259, 0.703539967536926],\n [0.57683801651001, 0.711845993995667],\n [0.581691026687622, 0.720062971115112],\n [0.609944999217987, 0.639909982681274],\n [0.986046016216278, 0.560034036636353],\n [0.5867999792099, 0.69539999961853],\n [0.590372025966644, 0.701822996139526],\n [0.531915009021759, 0.601536989212036],\n [0.577268004417419, 0.585934996604919],\n [0.536915004253387, 0.593786001205444],\n [0.627542972564697, 0.473352015018463],\n [0.665585994720459, 0.495950996875763],\n [0.588353991508484, 0.546862006187439],\n [0.757824003696442, 0.14767599105835],\n [0.709249973297119, 0.201507985591888],\n [0.672684013843536, 0.256581008434296],\n [0.600408971309662, 0.74900496006012],\n [0.55826598405838, 0.261672019958496],\n [0.570303976535797, 0.187870979309082],\n [0.588165998458862, 0.109044015407562],\n [0.711045026779175, 0.398952007293701],\n [0.781069993972778, 0.435405015945435],\n [0.587247014045715, 0.398931980133057],\n [0.742869973182678, 0.355445981025696],\n [0.572156012058258, 0.437651991844177],\n [0.55186802148819, 0.536570012569427],\n [0.821442008018494, 0.457556009292603],\n [0.752701997756958, 0.457181990146637],\n [0.71375697851181, 0.467626988887787],\n [0.66711300611496, 0.460672974586487],\n [0.631101012229919, 0.447153985500336],\n [0.6008620262146, 0.432473003864288],\n [0.523481011390686, 0.405627012252808],\n [0.810747981071472, 0.523926019668579],\n [0.771045982837677, 0.348959028720856],\n [0.509127020835876, 0.562718033790588],\n [0.595292985439301, 0.485023975372314],\n [0.980530977249146, 0.401564002037048],\n [0.573499977588654, 0.420000016689301],\n [0.602994978427887, 0.548687994480133],\n [0.733529984951019, 0.376977026462555],\n [0.560611009597778, 0.519016981124878],\n [0.967685997486115, 0.644356966018677],\n [0.580985009670258, 0.387160003185272],\n [0.537728011608124, 0.505385041236877],\n [0.760966002941132, 0.779752969741821],\n [0.801778972148895, 0.831938028335571],\n [0.892440974712372, 0.54076099395752],\n [0.816350996494293, 0.740260004997253],\n [0.865594983100891, 0.333687007427216],\n [0.614073991775513, 0.883246004581451],\n [0.508952975273132, 0.579437971115112],\n [0.617941975593567, 0.508316040039062],\n [0.825608015060425, 0.397674977779388],\n [0.681214988231659, 0.39623498916626],\n [0.656635999679565, 0.400596976280212],\n [0.603900015354156, 0.710216999053955],\n [0.81208598613739, 0.588539004325867],\n [0.56801301240921, 0.944564998149872],\n [0.681007981300354, 0.898285031318665],\n [0.733752012252808, 0.869701027870178],\n [0.633830010890961, 0.398822009563446],\n [0.606792986392975, 0.39553701877594],\n [0.589659988880157, 0.391062021255493],\n [0.805015981197357, 0.342108011245728],\n [0.611334979534149, 0.362284004688263],\n [0.634037971496582, 0.355970978736877],\n [0.656635999679565, 0.355356991291046],\n [0.681214988231659, 0.35834002494812],\n [0.698584973812103, 0.363156020641327],\n [0.941866993904114, 0.319076001644135],\n [0.698584973812103, 0.387449026107788],\n [0.584177017211914, 0.624107003211975],\n [0.554318010807037, 0.566076993942261],\n [0.534153997898102, 0.62064003944397],\n [0.711217999458313, 0.819975018501282],\n [0.664629995822906, 0.852871000766754],\n [0.559099972248077, 0.902631998062134],\n [0.871706008911133, 0.791940987110138],\n [0.591234028339386, 0.373893976211548],\n [0.544341027736664, 0.451583981513977],\n [0.624562978744507, 0.924192011356354],\n [0.88577002286911, 0.615028977394104],\n [0.551338016986847, 0.695277988910675],\n [0.551980018615723, 0.704632043838501],\n [0.552887976169586, 0.715808033943176],\n [0.555167973041534, 0.730794012546539],\n [0.569944024085999, 0.767035007476807],\n [0.593203008174896, 0.685675978660583],\n [0.599261999130249, 0.681069016456604],\n [0.607599973678589, 0.677703022956848],\n [0.631937980651855, 0.663500010967255],\n [0.752032995223999, 0.601315021514893],\n [0.547226011753082, 0.420395016670227],\n [0.563543975353241, 0.359827995300293],\n [0.583841025829315, 0.368713974952698],\n [0.586614012718201, 0.692366003990173],\n [0.771915018558502, 0.683578014373779],\n [0.531597018241882, 0.352482974529266],\n [0.588370978832245, 0.804440975189209],\n [0.52079701423645, 0.442565023899078],\n [0.567984998226166, 0.493479013442993],\n [0.543282985687256, 0.819254994392395],\n [0.655317008495331, 0.745514988899231],\n [0.621008992195129, 0.574018001556396],\n [0.625559985637665, 0.78031200170517],\n [0.680198013782501, 0.570719003677368],\n [0.64276397228241, 0.604337990283966],\n [0.704662978649139, 0.621529996395111],\n [0.552012026309967, 0.862591981887817],\n [0.589071989059448, 0.508637011051178],\n [0.685944974422455, 0.775357007980347],\n [0.645735025405884, 0.812640011310577],\n [0.675342977046967, 0.703978002071381],\n [0.810858011245728, 0.646304965019226],\n [0.72012197971344, 0.714666962623596],\n [0.866151988506317, 0.682704985141754],\n [0.663187026977539, 0.644596993923187],\n [0.570082008838654, 0.466325998306274],\n [0.544561982154846, 0.548375964164734],\n [0.562758982181549, 0.558784961700439],\n [0.531987011432648, 0.530140042304993],\n [0.585271000862122, 0.335177004337311],\n [0.622952997684479, 0.32277899980545],\n [0.655896008014679, 0.320163011550903],\n [0.687132000923157, 0.322345972061157],\n [0.716481983661652, 0.333200991153717],\n [0.758756995201111, 0.382786989212036],\n [0.897013008594513, 0.468769013881683],\n [0.732392013072968, 0.424547016620636],\n [0.70211398601532, 0.433162987232208],\n [0.66652500629425, 0.433866024017334],\n [0.633504986763, 0.426087975502014],\n [0.603875994682312, 0.416586995124817],\n [0.579657971858978, 0.409945011138916],\n [0.992439985275269, 0.480777025222778],\n [0.567192018032074, 0.569419980049133],\n [0.54136598110199, 0.478899002075195],\n [0.526564002037048, 0.546118021011353],\n [0.523913025856018, 0.563830018043518],\n [0.531529009342194, 0.555056989192963],\n [0.566035985946655, 0.582329034805298],\n [0.51631098985672, 0.563053965568542],\n [0.5174720287323, 0.577877044677734],\n [0.573594987392426, 0.389806985855103],\n [0.560697972774506, 0.395331978797913],\n [0.549755990505219, 0.399751007556915],\n [0.710287988185883, 0.368252992630005],\n [0.723330020904541, 0.363372981548309],\n];\n", "export default [\n 127, 34, 139, 11, 0, 37, 232, 231, 120, 72, 37, 39, 128, 121, 47, 232, 121,\n 128, 104, 69, 67, 175, 171, 148, 157, 154, 155, 118, 50, 101, 73, 39, 40, 9,\n 151, 108, 48, 115, 131, 194, 204, 211, 74, 40, 185, 80, 42, 183, 40, 92,\n 186, 230, 229, 118, 202, 212, 214, 83, 18, 17, 76, 61, 146, 160, 29, 30, 56,\n 157, 173, 106, 204, 194, 135, 214, 192, 203, 165, 98, 21, 71, 68, 51, 45, 4,\n 144, 24, 23, 77, 146, 91, 205, 50, 187, 201, 200, 18, 91, 106, 182, 90, 91,\n 181, 85, 84, 17, 206, 203, 36, 148, 171, 140, 92, 40, 39, 193, 189, 244,\n 159, 158, 28, 247, 246, 161, 236, 3, 196, 54, 68, 104, 193, 168, 8, 117,\n 228, 31, 189, 193, 55, 98, 97, 99, 126, 47, 100, 166, 79, 218, 155, 154, 26,\n 209, 49, 131, 135, 136, 150, 47, 126, 217, 223, 52, 53, 45, 51, 134, 211,\n 170, 140, 67, 69, 108, 43, 106, 91, 230, 119, 120, 226, 130, 247, 63, 53,\n 52, 238, 20, 242, 46, 70, 156, 78, 62, 96, 46, 53, 63, 143, 34, 227, 173,\n 155, 133, 123, 117, 111, 44, 125, 19, 236, 134, 51, 216, 206, 205, 154, 153,\n 22, 39, 37, 167, 200, 201, 208, 36, 142, 100, 57, 212, 202, 20, 60, 99, 28,\n 158, 157, 35, 226, 113, 160, 159, 27, 204, 202, 210, 113, 225, 46, 43, 202,\n 204, 62, 76, 77, 137, 123, 116, 41, 38, 72, 203, 129, 142, 64, 98, 240, 49,\n 102, 64, 41, 73, 74, 212, 216, 207, 42, 74, 184, 169, 170, 211, 170, 149,\n 176, 105, 66, 69, 122, 6, 168, 123, 147, 187, 96, 77, 90, 65, 55, 107, 89,\n 90, 180, 101, 100, 120, 63, 105, 104, 93, 137, 227, 15, 86, 85, 129, 102,\n 49, 14, 87, 86, 55, 8, 9, 100, 47, 121, 145, 23, 22, 88, 89, 179, 6, 122,\n 196, 88, 95, 96, 138, 172, 136, 215, 58, 172, 115, 48, 219, 42, 80, 81, 195,\n 3, 51, 43, 146, 61, 171, 175, 199, 81, 82, 38, 53, 46, 225, 144, 163, 110,\n 246, 33, 7, 52, 65, 66, 229, 228, 117, 34, 127, 234, 107, 108, 69, 109, 108,\n 151, 48, 64, 235, 62, 78, 191, 129, 209, 126, 111, 35, 143, 163, 161, 246,\n 117, 123, 50, 222, 65, 52, 19, 125, 141, 221, 55, 65, 3, 195, 197, 25, 7,\n 33, 220, 237, 44, 70, 71, 139, 122, 193, 245, 247, 130, 33, 71, 21, 162,\n 153, 158, 159, 170, 169, 150, 188, 174, 196, 216, 186, 92, 144, 160, 161, 2,\n 97, 167, 141, 125, 241, 164, 167, 37, 72, 38, 12, 145, 159, 160, 38, 82, 13,\n 63, 68, 71, 226, 35, 111, 158, 153, 154, 101, 50, 205, 206, 92, 165, 209,\n 198, 217, 165, 167, 97, 220, 115, 218, 133, 112, 243, 239, 238, 241, 214,\n 135, 169, 190, 173, 133, 171, 208, 32, 125, 44, 237, 86, 87, 178, 85, 86,\n 179, 84, 85, 180, 83, 84, 181, 201, 83, 182, 137, 93, 132, 76, 62, 183, 61,\n 76, 184, 57, 61, 185, 212, 57, 186, 214, 207, 187, 34, 143, 156, 79, 239,\n 237, 123, 137, 177, 44, 1, 4, 201, 194, 32, 64, 102, 129, 213, 215, 138, 59,\n 166, 219, 242, 99, 97, 2, 94, 141, 75, 59, 235, 24, 110, 228, 25, 130, 226,\n 23, 24, 229, 22, 23, 230, 26, 22, 231, 112, 26, 232, 189, 190, 243, 221, 56,\n 190, 28, 56, 221, 27, 28, 222, 29, 27, 223, 30, 29, 224, 247, 30, 225, 238,\n 79, 20, 166, 59, 75, 60, 75, 240, 147, 177, 215, 20, 79, 166, 187, 147, 213,\n 112, 233, 244, 233, 128, 245, 128, 114, 188, 114, 217, 174, 131, 115, 220,\n 217, 198, 236, 198, 131, 134, 177, 132, 58, 143, 35, 124, 110, 163, 7, 228,\n 110, 25, 356, 389, 368, 11, 302, 267, 452, 350, 349, 302, 303, 269, 357,\n 343, 277, 452, 453, 357, 333, 332, 297, 175, 152, 377, 384, 398, 382, 347,\n 348, 330, 303, 304, 270, 9, 336, 337, 278, 279, 360, 418, 262, 431, 304,\n 408, 409, 310, 415, 407, 270, 409, 410, 450, 348, 347, 422, 430, 434, 313,\n 314, 17, 306, 307, 375, 387, 388, 260, 286, 414, 398, 335, 406, 418, 364,\n 367, 416, 423, 358, 327, 251, 284, 298, 281, 5, 4, 373, 374, 253, 307, 320,\n 321, 425, 427, 411, 421, 313, 18, 321, 405, 406, 320, 404, 405, 315, 16, 17,\n 426, 425, 266, 377, 400, 369, 322, 391, 269, 417, 465, 464, 386, 257, 258,\n 466, 260, 388, 456, 399, 419, 284, 332, 333, 417, 285, 8, 346, 340, 261,\n 413, 441, 285, 327, 460, 328, 355, 371, 329, 392, 439, 438, 382, 341, 256,\n 429, 420, 360, 364, 394, 379, 277, 343, 437, 443, 444, 283, 275, 440, 363,\n 431, 262, 369, 297, 338, 337, 273, 375, 321, 450, 451, 349, 446, 342, 467,\n 293, 334, 282, 458, 461, 462, 276, 353, 383, 308, 324, 325, 276, 300, 293,\n 372, 345, 447, 382, 398, 362, 352, 345, 340, 274, 1, 19, 456, 248, 281, 436,\n 427, 425, 381, 256, 252, 269, 391, 393, 200, 199, 428, 266, 330, 329, 287,\n 273, 422, 250, 462, 328, 258, 286, 384, 265, 353, 342, 387, 259, 257, 424,\n 431, 430, 342, 353, 276, 273, 335, 424, 292, 325, 307, 366, 447, 345, 271,\n 303, 302, 423, 266, 371, 294, 455, 460, 279, 278, 294, 271, 272, 304, 432,\n 434, 427, 272, 407, 408, 394, 430, 431, 395, 369, 400, 334, 333, 299, 351,\n 417, 168, 352, 280, 411, 325, 319, 320, 295, 296, 336, 319, 403, 404, 330,\n 348, 349, 293, 298, 333, 323, 454, 447, 15, 16, 315, 358, 429, 279, 14, 15,\n 316, 285, 336, 9, 329, 349, 350, 374, 380, 252, 318, 402, 403, 6, 197, 419,\n 318, 319, 325, 367, 364, 365, 435, 367, 397, 344, 438, 439, 272, 271, 311,\n 195, 5, 281, 273, 287, 291, 396, 428, 199, 311, 271, 268, 283, 444, 445,\n 373, 254, 339, 263, 466, 249, 282, 334, 296, 449, 347, 346, 264, 447, 454,\n 336, 296, 299, 338, 10, 151, 278, 439, 455, 292, 407, 415, 358, 371, 355,\n 340, 345, 372, 390, 249, 466, 346, 347, 280, 442, 443, 282, 19, 94, 370,\n 441, 442, 295, 248, 419, 197, 263, 255, 359, 440, 275, 274, 300, 383, 368,\n 351, 412, 465, 263, 467, 466, 301, 368, 389, 380, 374, 386, 395, 378, 379,\n 412, 351, 419, 436, 426, 322, 373, 390, 388, 2, 164, 393, 370, 462, 461,\n 164, 0, 267, 302, 11, 12, 374, 373, 387, 268, 12, 13, 293, 300, 301, 446,\n 261, 340, 385, 384, 381, 330, 266, 425, 426, 423, 391, 429, 355, 437, 391,\n 327, 326, 440, 457, 438, 341, 382, 362, 459, 457, 461, 434, 430, 394, 414,\n 463, 362, 396, 369, 262, 354, 461, 457, 316, 403, 402, 315, 404, 403, 314,\n 405, 404, 313, 406, 405, 421, 418, 406, 366, 401, 361, 306, 408, 407, 291,\n 409, 408, 287, 410, 409, 432, 436, 410, 434, 416, 411, 264, 368, 383, 309,\n 438, 457, 352, 376, 401, 274, 275, 4, 421, 428, 262, 294, 327, 358, 433,\n 416, 367, 289, 455, 439, 462, 370, 326, 2, 326, 370, 305, 460, 455, 254,\n 449, 448, 255, 261, 446, 253, 450, 449, 252, 451, 450, 256, 452, 451, 341,\n 453, 452, 413, 464, 463, 441, 413, 414, 258, 442, 441, 257, 443, 442, 259,\n 444, 443, 260, 445, 444, 467, 342, 445, 459, 458, 250, 289, 392, 290, 290,\n 328, 460, 376, 433, 435, 250, 290, 392, 411, 416, 433, 341, 463, 464, 453,\n 464, 465, 357, 465, 412, 343, 412, 399, 360, 363, 440, 437, 399, 456, 420,\n 456, 363, 401, 435, 288, 372, 383, 353, 339, 255, 249, 448, 261, 255, 133,\n 243, 190, 133, 155, 112, 33, 246, 247, 33, 130, 25, 398, 384, 286, 362, 398,\n 414, 362, 463, 341, 263, 359, 467, 263, 249, 255, 466, 467, 260, 75, 60,\n 166, 238, 239, 79, 162, 127, 139, 72, 11, 37, 121, 232, 120, 73, 72, 39,\n 114, 128, 47, 233, 232, 128, 103, 104, 67, 152, 175, 148, 173, 157, 155,\n 119, 118, 101, 74, 73, 40, 107, 9, 108, 49, 48, 131, 32, 194, 211, 184, 74,\n 185, 191, 80, 183, 185, 40, 186, 119, 230, 118, 210, 202, 214, 84, 83, 17,\n 77, 76, 146, 161, 160, 30, 190, 56, 173, 182, 106, 194, 138, 135, 192, 129,\n 203, 98, 54, 21, 68, 5, 51, 4, 145, 144, 23, 90, 77, 91, 207, 205, 187, 83,\n 201, 18, 181, 91, 182, 180, 90, 181, 16, 85, 17, 205, 206, 36, 176, 148,\n 140, 165, 92, 39, 245, 193, 244, 27, 159, 28, 30, 247, 161, 174, 236, 196,\n 103, 54, 104, 55, 193, 8, 111, 117, 31, 221, 189, 55, 240, 98, 99, 142, 126,\n 100, 219, 166, 218, 112, 155, 26, 198, 209, 131, 169, 135, 150, 114, 47,\n 217, 224, 223, 53, 220, 45, 134, 32, 211, 140, 109, 67, 108, 146, 43, 91,\n 231, 230, 120, 113, 226, 247, 105, 63, 52, 241, 238, 242, 124, 46, 156, 95,\n 78, 96, 70, 46, 63, 116, 143, 227, 116, 123, 111, 1, 44, 19, 3, 236, 51,\n 207, 216, 205, 26, 154, 22, 165, 39, 167, 199, 200, 208, 101, 36, 100, 43,\n 57, 202, 242, 20, 99, 56, 28, 157, 124, 35, 113, 29, 160, 27, 211, 204, 210,\n 124, 113, 46, 106, 43, 204, 96, 62, 77, 227, 137, 116, 73, 41, 72, 36, 203,\n 142, 235, 64, 240, 48, 49, 64, 42, 41, 74, 214, 212, 207, 183, 42, 184, 210,\n 169, 211, 140, 170, 176, 104, 105, 69, 193, 122, 168, 50, 123, 187, 89, 96,\n 90, 66, 65, 107, 179, 89, 180, 119, 101, 120, 68, 63, 104, 234, 93, 227, 16,\n 15, 85, 209, 129, 49, 15, 14, 86, 107, 55, 9, 120, 100, 121, 153, 145, 22,\n 178, 88, 179, 197, 6, 196, 89, 88, 96, 135, 138, 136, 138, 215, 172, 218,\n 115, 219, 41, 42, 81, 5, 195, 51, 57, 43, 61, 208, 171, 199, 41, 81, 38,\n 224, 53, 225, 24, 144, 110, 105, 52, 66, 118, 229, 117, 227, 34, 234, 66,\n 107, 69, 10, 109, 151, 219, 48, 235, 183, 62, 191, 142, 129, 126, 116, 111,\n 143, 7, 163, 246, 118, 117, 50, 223, 222, 52, 94, 19, 141, 222, 221, 65,\n 196, 3, 197, 45, 220, 44, 156, 70, 139, 188, 122, 245, 139, 71, 162, 145,\n 153, 159, 149, 170, 150, 122, 188, 196, 206, 216, 92, 163, 144, 161, 164, 2,\n 167, 242, 141, 241, 0, 164, 37, 11, 72, 12, 144, 145, 160, 12, 38, 13, 70,\n 63, 71, 31, 226, 111, 157, 158, 154, 36, 101, 205, 203, 206, 165, 126, 209,\n 217, 98, 165, 97, 237, 220, 218, 237, 239, 241, 210, 214, 169, 140, 171, 32,\n 241, 125, 237, 179, 86, 178, 180, 85, 179, 181, 84, 180, 182, 83, 181, 194,\n 201, 182, 177, 137, 132, 184, 76, 183, 185, 61, 184, 186, 57, 185, 216, 212,\n 186, 192, 214, 187, 139, 34, 156, 218, 79, 237, 147, 123, 177, 45, 44, 4,\n 208, 201, 32, 98, 64, 129, 192, 213, 138, 235, 59, 219, 141, 242, 97, 97, 2,\n 141, 240, 75, 235, 229, 24, 228, 31, 25, 226, 230, 23, 229, 231, 22, 230,\n 232, 26, 231, 233, 112, 232, 244, 189, 243, 189, 221, 190, 222, 28, 221,\n 223, 27, 222, 224, 29, 223, 225, 30, 224, 113, 247, 225, 99, 60, 240, 213,\n 147, 215, 60, 20, 166, 192, 187, 213, 243, 112, 244, 244, 233, 245, 245,\n 128, 188, 188, 114, 174, 134, 131, 220, 174, 217, 236, 236, 198, 134, 215,\n 177, 58, 156, 143, 124, 25, 110, 7, 31, 228, 25, 264, 356, 368, 0, 11, 267,\n 451, 452, 349, 267, 302, 269, 350, 357, 277, 350, 452, 357, 299, 333, 297,\n 396, 175, 377, 381, 384, 382, 280, 347, 330, 269, 303, 270, 151, 9, 337,\n 344, 278, 360, 424, 418, 431, 270, 304, 409, 272, 310, 407, 322, 270, 410,\n 449, 450, 347, 432, 422, 434, 18, 313, 17, 291, 306, 375, 259, 387, 260,\n 424, 335, 418, 434, 364, 416, 391, 423, 327, 301, 251, 298, 275, 281, 4,\n 254, 373, 253, 375, 307, 321, 280, 425, 411, 200, 421, 18, 335, 321, 406,\n 321, 320, 405, 314, 315, 17, 423, 426, 266, 396, 377, 369, 270, 322, 269,\n 413, 417, 464, 385, 386, 258, 248, 456, 419, 298, 284, 333, 168, 417, 8,\n 448, 346, 261, 417, 413, 285, 326, 327, 328, 277, 355, 329, 309, 392, 438,\n 381, 382, 256, 279, 429, 360, 365, 364, 379, 355, 277, 437, 282, 443, 283,\n 281, 275, 363, 395, 431, 369, 299, 297, 337, 335, 273, 321, 348, 450, 349,\n 359, 446, 467, 283, 293, 282, 250, 458, 462, 300, 276, 383, 292, 308, 325,\n 283, 276, 293, 264, 372, 447, 346, 352, 340, 354, 274, 19, 363, 456, 281,\n 426, 436, 425, 380, 381, 252, 267, 269, 393, 421, 200, 428, 371, 266, 329,\n 432, 287, 422, 290, 250, 328, 385, 258, 384, 446, 265, 342, 386, 387, 257,\n 422, 424, 430, 445, 342, 276, 422, 273, 424, 306, 292, 307, 352, 366, 345,\n 268, 271, 302, 358, 423, 371, 327, 294, 460, 331, 279, 294, 303, 271, 304,\n 436, 432, 427, 304, 272, 408, 395, 394, 431, 378, 395, 400, 296, 334, 299,\n 6, 351, 168, 376, 352, 411, 307, 325, 320, 285, 295, 336, 320, 319, 404,\n 329, 330, 349, 334, 293, 333, 366, 323, 447, 316, 15, 315, 331, 358, 279,\n 317, 14, 316, 8, 285, 9, 277, 329, 350, 253, 374, 252, 319, 318, 403, 351,\n 6, 419, 324, 318, 325, 397, 367, 365, 288, 435, 397, 278, 344, 439, 310,\n 272, 311, 248, 195, 281, 375, 273, 291, 175, 396, 199, 312, 311, 268, 276,\n 283, 445, 390, 373, 339, 295, 282, 296, 448, 449, 346, 356, 264, 454, 337,\n 336, 299, 337, 338, 151, 294, 278, 455, 308, 292, 415, 429, 358, 355, 265,\n 340, 372, 388, 390, 466, 352, 346, 280, 295, 442, 282, 354, 19, 370, 285,\n 441, 295, 195, 248, 197, 457, 440, 274, 301, 300, 368, 417, 351, 465, 251,\n 301, 389, 385, 380, 386, 394, 395, 379, 399, 412, 419, 410, 436, 322, 387,\n 373, 388, 326, 2, 393, 354, 370, 461, 393, 164, 267, 268, 302, 12, 386, 374,\n 387, 312, 268, 13, 298, 293, 301, 265, 446, 340, 380, 385, 381, 280, 330,\n 425, 322, 426, 391, 420, 429, 437, 393, 391, 326, 344, 440, 438, 458, 459,\n 461, 364, 434, 394, 428, 396, 262, 274, 354, 457, 317, 316, 402, 316, 315,\n 403, 315, 314, 404, 314, 313, 405, 313, 421, 406, 323, 366, 361, 292, 306,\n 407, 306, 291, 408, 291, 287, 409, 287, 432, 410, 427, 434, 411, 372, 264,\n 383, 459, 309, 457, 366, 352, 401, 1, 274, 4, 418, 421, 262, 331, 294, 358,\n 435, 433, 367, 392, 289, 439, 328, 462, 326, 94, 2, 370, 289, 305, 455, 339,\n 254, 448, 359, 255, 446, 254, 253, 449, 253, 252, 450, 252, 256, 451, 256,\n 341, 452, 414, 413, 463, 286, 441, 414, 286, 258, 441, 258, 257, 442, 257,\n 259, 443, 259, 260, 444, 260, 467, 445, 309, 459, 250, 305, 289, 290, 305,\n 290, 460, 401, 376, 435, 309, 250, 392, 376, 411, 433, 453, 341, 464, 357,\n 453, 465, 343, 357, 412, 437, 343, 399, 344, 360, 440, 420, 437, 456, 360,\n 420, 363, 361, 401, 288, 265, 372, 353, 390, 339, 249, 339, 448, 255];\n", "const tf = require('@tensorflow/tfjs');\nconst blazeface = require('./blazeface');\nconst keypoints = require('./keypoints');\nconst pipe = require('./pipeline');\nconst uv_coords = require('./uvcoords');\nconst triangulation = require('./triangulation').default;\n\nclass MediaPipeFaceMesh {\n constructor(blazeFace, blazeMeshModel, irisModel, config) {\n this.pipeline = new pipe.Pipeline(blazeFace, blazeMeshModel, irisModel, config);\n if (config) this.config = config;\n }\n\n async estimateFaces(input, config) {\n if (config) this.config = config;\n const predictions = await this.pipeline.predict(input, config);\n const results = [];\n for (const prediction of (predictions || [])) {\n // guard against disposed tensors on long running operations such as pause in middle of processing\n if (prediction.isDisposedInternal) continue;\n const confidence = prediction.confidence.arraySync();\n if (confidence >= this.config.detector.minConfidence) {\n const mesh = prediction.coords ? prediction.coords.arraySync() : null;\n const annotations = {};\n if (mesh && mesh.length > 0) {\n for (const key in keypoints.MESH_ANNOTATIONS) {\n if (this.config.iris.enabled || key.includes('Iris') === false) {\n annotations[key] = keypoints.MESH_ANNOTATIONS[key].map((index) => mesh[index]);\n }\n }\n }\n results.push({\n confidence: confidence || 0,\n box: prediction.box ? [prediction.box.startPoint[0], prediction.box.startPoint[1], prediction.box.endPoint[0] - prediction.box.startPoint[0], prediction.box.endPoint[1] - prediction.box.startPoint[1]] : 0,\n mesh,\n annotations,\n image: prediction.image ? tf.clone(prediction.image) : null,\n });\n }\n if (prediction.confidence) prediction.confidence.dispose();\n if (prediction.coords) prediction.coords.dispose();\n if (prediction.image) prediction.image.dispose();\n }\n return results;\n }\n}\n\nasync function load(config) {\n const models = await Promise.all([\n blazeface.load(config),\n tf.loadGraphModel(config.mesh.modelPath, { fromTFHub: config.mesh.modelPath.includes('tfhub.dev') }),\n tf.loadGraphModel(config.iris.modelPath, { fromTFHub: config.iris.modelPath.includes('tfhub.dev') }),\n ]);\n const faceMesh = new MediaPipeFaceMesh(models[0], models[1], models[2], config);\n return faceMesh;\n}\n\nexports.load = load;\nexports.MediaPipeFaceMesh = MediaPipeFaceMesh;\nexports.uv_coords = uv_coords;\nexports.triangulation = triangulation;\n", "const tf = require('@tensorflow/tfjs');\n\nconst models = {};\nlet last = { age: 0, gender: '' };\nlet frame = 0;\n\nasync function loadAge(config) {\n if (!models.age) models.age = await tf.loadGraphModel(config.face.age.modelPath);\n return models.age;\n}\n\nasync function loadGender(config) {\n if (!models.gender) models.gender = await tf.loadGraphModel(config.face.gender.modelPath);\n return models.gender;\n}\n\nasync function predict(image, config) {\n if (frame < config.face.age.skipFrames) {\n frame += 1;\n return last;\n }\n frame = 0;\n const resize = tf.image.resizeBilinear(image, [config.face.age.inputSize, config.face.age.inputSize], false);\n const enhance = tf.mul(resize, [255.0]);\n tf.dispose(resize);\n\n const promises = [];\n let ageT;\n let genderT;\n if (config.face.age.enabled) promises.push(ageT = models.age.predict(enhance));\n if (config.face.gender.enabled) promises.push(genderT = models.gender.predict(enhance));\n await Promise.all(promises);\n\n const obj = {};\n if (ageT) {\n const data = await ageT.data();\n obj.age = Math.trunc(10 * data[0]) / 10;\n tf.dispose(ageT);\n }\n if (genderT) {\n const data = await genderT.data();\n const confidence = Math.trunc(Math.abs(1.9 * 100 * (data[0] - 0.5))) / 100;\n if (confidence > config.face.gender.minConfidence) {\n obj.gender = data[0] <= 0.5 ? 'female' : 'male';\n obj.confidence = confidence;\n }\n tf.dispose(genderT);\n }\n\n tf.dispose(enhance);\n last = obj;\n return obj;\n}\n\nexports.predict = predict;\nexports.loadAge = loadAge;\nexports.loadGender = loadGender;\n", "const tf = require('@tensorflow/tfjs');\n\nconst annotations = ['angry', 'discust', 'fear', 'happy', 'sad', 'surpise', 'neutral'];\nconst models = {};\nlet last = [];\nlet frame = 0;\nconst multiplier = 1.5;\n\nasync function load(config) {\n if (!models.emotion) models.emotion = await tf.loadGraphModel(config.face.emotion.modelPath);\n return models.emotion;\n}\n\nasync function predict(image, config) {\n if (frame < config.face.emotion.skipFrames) {\n frame += 1;\n return last;\n }\n frame = 0;\n const resize = tf.image.resizeBilinear(image, [config.face.emotion.inputSize, config.face.emotion.inputSize], false);\n const [red, green, blue] = tf.split(resize, 3, 3);\n resize.dispose();\n // weighted rgb to grayscale: https://www.mathworks.com/help/matlab/ref/rgb2gray.html\n const redNorm = tf.mul(red, [0.2989]);\n const greenNorm = tf.mul(green, [0.5870]);\n const blueNorm = tf.mul(blue, [0.1140]);\n red.dispose();\n green.dispose();\n blue.dispose();\n const grayscale = tf.addN([redNorm, greenNorm, blueNorm]);\n redNorm.dispose();\n greenNorm.dispose();\n blueNorm.dispose();\n const obj = [];\n if (config.face.emotion.enabled) {\n const emotionT = await models.emotion.predict(grayscale);\n const data = await emotionT.data();\n for (let i = 0; i < data.length; i++) {\n if (multiplier * data[i] > config.face.emotion.minConfidence) obj.push({ score: Math.min(0.99, Math.trunc(100 * multiplier * data[i]) / 100), emotion: annotations[i] });\n }\n obj.sort((a, b) => b.score - a.score);\n tf.dispose(emotionT);\n }\n tf.dispose(grayscale);\n last = obj;\n return obj;\n}\n\nexports.predict = predict;\nexports.load = load;\n", "const tf = require('@tensorflow/tfjs');\n\nclass BaseModel {\n constructor(model, outputStride) {\n this.model = model;\n this.outputStride = outputStride;\n const inputShape = this.model.inputs[0].shape;\n tf.util.assert((inputShape[1] === -1) && (inputShape[2] === -1), () => `Input shape [${inputShape[1]}, ${inputShape[2]}] must both be equal to or -1`);\n }\n\n /**\n * Predicts intermediate Tensor representations.\n *\n * @param input The input RGB image of the base model.\n * A Tensor of shape: [`inputResolution`, `inputResolution`, 3].\n *\n * @return A dictionary of base model's intermediate predictions.\n * The returned dictionary should contains the following elements:\n * heatmapScores: A Tensor3D that represents the heatmapScores.\n * offsets: A Tensor3D that represents the offsets.\n * displacementFwd: A Tensor3D that represents the forward displacement.\n * displacementBwd: A Tensor3D that represents the backward displacement.\n */\n predict(input) {\n return tf.tidy(() => {\n const asFloat = this.preprocessInput(input.toFloat());\n const asBatch = asFloat.expandDims(0);\n const results = this.model.predict(asBatch);\n const results3d = results.map((y) => y.squeeze([0]));\n const namedResults = this.nameOutputResults(results3d);\n return {\n heatmapScores: namedResults.heatmap.sigmoid(),\n offsets: namedResults.offsets,\n displacementFwd: namedResults.displacementFwd,\n displacementBwd: namedResults.displacementBwd,\n };\n });\n }\n\n /**\n * Releases the CPU and GPU memory allocated by the model.\n */\n dispose() {\n this.model.dispose();\n }\n}\nexports.BaseModel = BaseModel;\n", "const tf = require('@tensorflow/tfjs');\nconst modelBase = require('./modelBase');\n\nclass MobileNet extends modelBase.BaseModel {\n // eslint-disable-next-line class-methods-use-this\n preprocessInput(input) {\n // Normalize the pixels [0, 255] to be between [-1, 1].\n return tf.tidy(() => tf.div(input, 127.5).sub(1.0));\n }\n\n // eslint-disable-next-line class-methods-use-this\n nameOutputResults(results) {\n const [offsets, heatmap, displacementFwd, displacementBwd] = results;\n return { offsets, heatmap, displacementFwd, displacementBwd };\n }\n}\nexports.MobileNet = MobileNet;\n", "// algorithm based on Coursera Lecture from Algorithms, Part 1: https://www.coursera.org/learn/algorithms-part1/lecture/ZjoSM/heapsort\nfunction half(k) {\n return Math.floor(k / 2);\n}\nclass MaxHeap {\n constructor(maxSize, getElementValue) {\n this.priorityQueue = new Array(maxSize);\n this.numberOfElements = -1;\n this.getElementValue = getElementValue;\n }\n\n enqueue(x) {\n this.priorityQueue[++this.numberOfElements] = x;\n this.swim(this.numberOfElements);\n }\n\n dequeue() {\n const max = this.priorityQueue[0];\n this.exchange(0, this.numberOfElements--);\n this.sink(0);\n this.priorityQueue[this.numberOfElements + 1] = null;\n return max;\n }\n\n empty() {\n return this.numberOfElements === -1;\n }\n\n size() {\n return this.numberOfElements + 1;\n }\n\n all() {\n return this.priorityQueue.slice(0, this.numberOfElements + 1);\n }\n\n max() {\n return this.priorityQueue[0];\n }\n\n swim(k) {\n while (k > 0 && this.less(half(k), k)) {\n this.exchange(k, half(k));\n k = half(k);\n }\n }\n\n sink(k) {\n while (2 * k <= this.numberOfElements) {\n let j = 2 * k;\n if (j < this.numberOfElements && this.less(j, j + 1)) j++;\n if (!this.less(k, j)) break;\n this.exchange(k, j);\n k = j;\n }\n }\n\n getValueAt(i) {\n return this.getElementValue(this.priorityQueue[i]);\n }\n\n less(i, j) {\n return this.getValueAt(i) < this.getValueAt(j);\n }\n\n exchange(i, j) {\n const t = this.priorityQueue[i];\n this.priorityQueue[i] = this.priorityQueue[j];\n this.priorityQueue[j] = t;\n }\n}\nexports.MaxHeap = MaxHeap;\n", "const heapSort = require('./heapSort');\n\nfunction scoreIsMaximumInLocalWindow(keypointId, score, heatmapY, heatmapX, localMaximumRadius, scores) {\n const [height, width] = scores.shape;\n let localMaximum = true;\n const yStart = Math.max(heatmapY - localMaximumRadius, 0);\n const yEnd = Math.min(heatmapY + localMaximumRadius + 1, height);\n for (let yCurrent = yStart; yCurrent < yEnd; ++yCurrent) {\n const xStart = Math.max(heatmapX - localMaximumRadius, 0);\n const xEnd = Math.min(heatmapX + localMaximumRadius + 1, width);\n for (let xCurrent = xStart; xCurrent < xEnd; ++xCurrent) {\n if (scores.get(yCurrent, xCurrent, keypointId) > score) {\n localMaximum = false;\n break;\n }\n }\n if (!localMaximum) {\n break;\n }\n }\n return localMaximum;\n}\n/**\n * Builds a priority queue with part candidate positions for a specific image in\n * the batch. For this we find all local maxima in the score maps with score\n * values above a threshold. We create a single priority queue across all parts.\n */\nfunction buildPartWithScoreQueue(scoreThreshold, localMaximumRadius, scores) {\n const [height, width, numKeypoints] = scores.shape;\n const queue = new heapSort.MaxHeap(height * width * numKeypoints, ({ score }) => score);\n for (let heatmapY = 0; heatmapY < height; ++heatmapY) {\n for (let heatmapX = 0; heatmapX < width; ++heatmapX) {\n for (let keypointId = 0; keypointId < numKeypoints; ++keypointId) {\n const score = scores.get(heatmapY, heatmapX, keypointId);\n // Only consider parts with score greater or equal to threshold as root candidates.\n if (score < scoreThreshold) continue;\n // Only consider keypoints whose score is maximum in a local window.\n if (scoreIsMaximumInLocalWindow(keypointId, score, heatmapY, heatmapX, localMaximumRadius, scores)) {\n queue.enqueue({ score, part: { heatmapY, heatmapX, id: keypointId } });\n }\n }\n }\n }\n return queue;\n}\nexports.buildPartWithScoreQueue = buildPartWithScoreQueue;\n", "exports.partNames = [\n 'nose', 'leftEye', 'rightEye', 'leftEar', 'rightEar', 'leftShoulder',\n 'rightShoulder', 'leftElbow', 'rightElbow', 'leftWrist', 'rightWrist',\n 'leftHip', 'rightHip', 'leftKnee', 'rightKnee', 'leftAnkle', 'rightAnkle',\n];\nexports.NUM_KEYPOINTS = exports.partNames.length;\nexports.partIds = exports.partNames.reduce((result, jointName, i) => {\n result[jointName] = i;\n return result;\n}, {});\nconst connectedPartNames = [\n ['leftHip', 'leftShoulder'], ['leftElbow', 'leftShoulder'],\n ['leftElbow', 'leftWrist'], ['leftHip', 'leftKnee'],\n ['leftKnee', 'leftAnkle'], ['rightHip', 'rightShoulder'],\n ['rightElbow', 'rightShoulder'], ['rightElbow', 'rightWrist'],\n ['rightHip', 'rightKnee'], ['rightKnee', 'rightAnkle'],\n ['leftShoulder', 'rightShoulder'], ['leftHip', 'rightHip'],\n];\n/*\n * Define the skeleton. This defines the parent->child relationships of our\n * tree. Arbitrarily this defines the nose as the root of the tree, however\n * since we will infer the displacement for both parent->child and\n * child->parent, we can define the tree root as any node.\n */\nexports.poseChain = [\n ['nose', 'leftEye'], ['leftEye', 'leftEar'], ['nose', 'rightEye'],\n ['rightEye', 'rightEar'], ['nose', 'leftShoulder'],\n ['leftShoulder', 'leftElbow'], ['leftElbow', 'leftWrist'],\n ['leftShoulder', 'leftHip'], ['leftHip', 'leftKnee'],\n ['leftKnee', 'leftAnkle'], ['nose', 'rightShoulder'],\n ['rightShoulder', 'rightElbow'], ['rightElbow', 'rightWrist'],\n ['rightShoulder', 'rightHip'], ['rightHip', 'rightKnee'],\n ['rightKnee', 'rightAnkle'],\n];\nexports.connectedPartIndices = connectedPartNames.map(([jointNameA, jointNameB]) => ([exports.partIds[jointNameA], exports.partIds[jointNameB]]));\nexports.partChannels = [\n 'left_face',\n 'right_face',\n 'right_upper_leg_front',\n 'right_lower_leg_back',\n 'right_upper_leg_back',\n 'left_lower_leg_front',\n 'left_upper_leg_front',\n 'left_upper_leg_back',\n 'left_lower_leg_back',\n 'right_feet',\n 'right_lower_leg_front',\n 'left_feet',\n 'torso_front',\n 'torso_back',\n 'right_upper_arm_front',\n 'right_upper_arm_back',\n 'right_lower_arm_back',\n 'left_lower_arm_front',\n 'left_upper_arm_front',\n 'left_upper_arm_back',\n 'left_lower_arm_back',\n 'right_hand',\n 'right_lower_arm_front',\n 'left_hand',\n];\n", "const kpt = require('./keypoints');\n\nfunction getOffsetPoint(y, x, keypoint, offsets) {\n return {\n y: offsets.get(y, x, keypoint),\n x: offsets.get(y, x, keypoint + kpt.NUM_KEYPOINTS),\n };\n}\nexports.getOffsetPoint = getOffsetPoint;\n\nfunction getImageCoords(part, outputStride, offsets) {\n const { heatmapY, heatmapX, id: keypoint } = part;\n const { y, x } = getOffsetPoint(heatmapY, heatmapX, keypoint, offsets);\n return {\n x: part.heatmapX * outputStride + x,\n y: part.heatmapY * outputStride + y,\n };\n}\nexports.getImageCoords = getImageCoords;\n\nfunction fillArray(element, size) {\n const result = new Array(size);\n for (let i = 0; i < size; i++) {\n result[i] = element;\n }\n return result;\n}\nexports.fillArray = fillArray;\n\nfunction clamp(a, min, max) {\n if (a < min) return min;\n if (a > max) return max;\n return a;\n}\nexports.clamp = clamp;\n\nfunction squaredDistance(y1, x1, y2, x2) {\n const dy = y2 - y1;\n const dx = x2 - x1;\n return dy * dy + dx * dx;\n}\nexports.squaredDistance = squaredDistance;\n\nfunction addVectors(a, b) {\n return { x: a.x + b.x, y: a.y + b.y };\n}\nexports.addVectors = addVectors;\n\nfunction clampVector(a, min, max) {\n return { y: clamp(a.y, min, max), x: clamp(a.x, min, max) };\n}\nexports.clampVector = clampVector;\n", "const keypoints = require('./keypoints');\nconst vectors = require('./vectors');\n\nconst parentChildrenTuples = keypoints.poseChain.map(([parentJoinName, childJoinName]) => ([keypoints.partIds[parentJoinName], keypoints.partIds[childJoinName]]));\nconst parentToChildEdges = parentChildrenTuples.map(([, childJointId]) => childJointId);\nconst childToParentEdges = parentChildrenTuples.map(([parentJointId]) => parentJointId);\nfunction getDisplacement(edgeId, point, displacements) {\n const numEdges = displacements.shape[2] / 2;\n return {\n y: displacements.get(point.y, point.x, edgeId),\n x: displacements.get(point.y, point.x, numEdges + edgeId),\n };\n}\nfunction getStridedIndexNearPoint(point, outputStride, height, width) {\n return {\n y: vectors.clamp(Math.round(point.y / outputStride), 0, height - 1),\n x: vectors.clamp(Math.round(point.x / outputStride), 0, width - 1),\n };\n}\n/**\n * We get a new keypoint along the `edgeId` for the pose instance, assuming\n * that the position of the `idSource` part is already known. For this, we\n * follow the displacement vector from the source to target part (stored in\n * the `i`-t channel of the displacement tensor). The displaced keypoint\n * vector is refined using the offset vector by `offsetRefineStep` times.\n */\nfunction traverseToTargetKeypoint(edgeId, sourceKeypoint, targetKeypointId, scoresBuffer, offsets, outputStride, displacements, offsetRefineStep = 2) {\n const [height, width] = scoresBuffer.shape;\n // Nearest neighbor interpolation for the source->target displacements.\n const sourceKeypointIndices = getStridedIndexNearPoint(sourceKeypoint.position, outputStride, height, width);\n const displacement = getDisplacement(edgeId, sourceKeypointIndices, displacements);\n const displacedPoint = vectors.addVectors(sourceKeypoint.position, displacement);\n let targetKeypoint = displacedPoint;\n for (let i = 0; i < offsetRefineStep; i++) {\n const targetKeypointIndices = getStridedIndexNearPoint(targetKeypoint, outputStride, height, width);\n const offsetPoint = vectors.getOffsetPoint(targetKeypointIndices.y, targetKeypointIndices.x, targetKeypointId, offsets);\n targetKeypoint = vectors.addVectors({\n x: targetKeypointIndices.x * outputStride,\n y: targetKeypointIndices.y * outputStride,\n }, { x: offsetPoint.x, y: offsetPoint.y });\n }\n const targetKeyPointIndices = getStridedIndexNearPoint(targetKeypoint, outputStride, height, width);\n const score = scoresBuffer.get(targetKeyPointIndices.y, targetKeyPointIndices.x, targetKeypointId);\n return { position: targetKeypoint, part: keypoints.partNames[targetKeypointId], score };\n}\n/**\n * Follows the displacement fields to decode the full pose of the object\n * instance given the position of a part that acts as root.\n *\n * @return An array of decoded keypoints and their scores for a single pose\n */\nfunction decodePose(root, scores, offsets, outputStride, displacementsFwd, displacementsBwd) {\n const numParts = scores.shape[2];\n const numEdges = parentToChildEdges.length;\n const instanceKeypoints = new Array(numParts);\n // Start a new detection instance at the position of the root.\n const { part: rootPart, score: rootScore } = root;\n const rootPoint = vectors.getImageCoords(rootPart, outputStride, offsets);\n instanceKeypoints[rootPart.id] = {\n score: rootScore,\n part: keypoints.partNames[rootPart.id],\n position: rootPoint,\n };\n // Decode the part positions upwards in the tree, following the backward\n // displacements.\n for (let edge = numEdges - 1; edge >= 0; --edge) {\n const sourceKeypointId = parentToChildEdges[edge];\n const targetKeypointId = childToParentEdges[edge];\n if (instanceKeypoints[sourceKeypointId] && !instanceKeypoints[targetKeypointId]) {\n instanceKeypoints[targetKeypointId] = traverseToTargetKeypoint(edge, instanceKeypoints[sourceKeypointId], targetKeypointId, scores, offsets, outputStride, displacementsBwd);\n }\n }\n // Decode the part positions downwards in the tree, following the forward\n // displacements.\n for (let edge = 0; edge < numEdges; ++edge) {\n const sourceKeypointId = childToParentEdges[edge];\n const targetKeypointId = parentToChildEdges[edge];\n if (instanceKeypoints[sourceKeypointId] && !instanceKeypoints[targetKeypointId]) {\n instanceKeypoints[targetKeypointId] = traverseToTargetKeypoint(edge, instanceKeypoints[sourceKeypointId], targetKeypointId, scores, offsets, outputStride, displacementsFwd);\n }\n }\n return instanceKeypoints;\n}\nexports.decodePose = decodePose;\n", "const buildParts = require('./buildParts');\nconst decodePose = require('./decodePose');\nconst vectors = require('./vectors');\n\nfunction withinNmsRadiusOfCorrespondingPoint(poses, squaredNmsRadius, { x, y }, keypointId) {\n return poses.some(({ keypoints }) => {\n const correspondingKeypoint = keypoints[keypointId].position;\n return vectors.squaredDistance(y, x, correspondingKeypoint.y, correspondingKeypoint.x) <= squaredNmsRadius;\n });\n}\n/* Score the newly proposed object instance without taking into account\n * the scores of the parts that overlap with any previously detected\n * instance.\n */\nfunction getInstanceScore(existingPoses, squaredNmsRadius, instanceKeypoints) {\n const notOverlappedKeypointScores = instanceKeypoints.reduce((result, { position, score }, keypointId) => {\n if (!withinNmsRadiusOfCorrespondingPoint(existingPoses, squaredNmsRadius, position, keypointId)) {\n result += score;\n }\n return result;\n }, 0.0);\n return notOverlappedKeypointScores / instanceKeypoints.length;\n}\n// A point (y, x) is considered as root part candidate if its score is a\n// maximum in a window |y - y'| <= kLocalMaximumRadius, |x - x'| <=\n// kLocalMaximumRadius.\nconst kLocalMaximumRadius = 1;\n/**\n * Detects multiple poses and finds their parts from part scores and\n * displacement vectors. It returns up to `maxDetections` object instance\n * detections in decreasing root score order. It works as follows: We first\n * create a priority queue with local part score maxima above\n * `scoreThreshold`, considering all parts at the same time. Then we\n * iteratively pull the top element of the queue (in decreasing score order)\n * and treat it as a root candidate for a new object instance. To avoid\n * duplicate detections, we reject the root candidate if it is within a disk\n * of `nmsRadius` pixels from the corresponding part of a previously detected\n * instance, which is a form of part-based non-maximum suppression (NMS). If\n * the root candidate passes the NMS check, we start a new object instance\n * detection, treating the corresponding part as root and finding the\n * positions of the remaining parts by following the displacement vectors\n * along the tree-structured part graph. We assign to the newly detected\n * instance a score equal to the sum of scores of its parts which have not\n * been claimed by a previous instance (i.e., those at least `nmsRadius`\n * pixels away from the corresponding part of all previously detected\n * instances), divided by the total number of parts `numParts`.\n *\n * @param heatmapScores 3-D tensor with shape `[height, width, numParts]`.\n * The value of heatmapScores[y, x, k]` is the score of placing the `k`-th\n * object part at position `(y, x)`.\n *\n * @param offsets 3-D tensor with shape `[height, width, numParts * 2]`.\n * The value of [offsets[y, x, k], offsets[y, x, k + numParts]]` is the\n * short range offset vector of the `k`-th object part at heatmap\n * position `(y, x)`.\n *\n * @param displacementsFwd 3-D tensor of shape\n * `[height, width, 2 * num_edges]`, where `num_edges = num_parts - 1` is the\n * number of edges (parent-child pairs) in the tree. It contains the forward\n * displacements between consecutive part from the root towards the leaves.\n *\n * @param displacementsBwd 3-D tensor of shape\n * `[height, width, 2 * num_edges]`, where `num_edges = num_parts - 1` is the\n * number of edges (parent-child pairs) in the tree. It contains the backward\n * displacements between consecutive part from the root towards the leaves.\n *\n * @param outputStride The output stride that was used when feed-forwarding\n * through the PoseNet model. Must be 32, 16, or 8.\n *\n * @param maxPoseDetections Maximum number of returned instance detections per\n * image.\n *\n * @param scoreThreshold Only return instance detections that have root part\n * score greater or equal to this value. Defaults to 0.5.\n *\n * @param nmsRadius Non-maximum suppression part distance. It needs to be\n * strictly positive. Two parts suppress each other if they are less than\n * `nmsRadius` pixels away. Defaults to 20.\n *\n * @return An array of poses and their scores, each containing keypoints and\n * the corresponding keypoint scores.\n */\nfunction decodeMultiplePoses(scoresBuffer, offsetsBuffer, displacementsFwdBuffer, displacementsBwdBuffer, outputStride, maxPoseDetections, scoreThreshold = 0.5, nmsRadius = 20) {\n const poses = [];\n const queue = buildParts.buildPartWithScoreQueue(scoreThreshold, kLocalMaximumRadius, scoresBuffer);\n const squaredNmsRadius = nmsRadius * nmsRadius;\n // Generate at most maxDetections object instances per image in\n // decreasing root part score order.\n while (poses.length < maxPoseDetections && !queue.empty()) {\n // The top element in the queue is the next root candidate.\n const root = queue.dequeue();\n // Part-based non-maximum suppression: We reject a root candidate if it\n // is within a disk of `nmsRadius` pixels from the corresponding part of\n // a previously detected instance.\n const rootImageCoords = vectors.getImageCoords(root.part, outputStride, offsetsBuffer);\n if (withinNmsRadiusOfCorrespondingPoint(poses, squaredNmsRadius, rootImageCoords, root.part.id)) continue;\n // Start a new detection instance at the position of the root.\n const keypoints = decodePose.decodePose(root, scoresBuffer, offsetsBuffer, outputStride, displacementsFwdBuffer, displacementsBwdBuffer);\n const score = getInstanceScore(poses, squaredNmsRadius, keypoints);\n poses.push({ keypoints, score });\n }\n return poses;\n}\nexports.decodeMultiplePoses = decodeMultiplePoses;\n", "const kpt = require('./keypoints');\n\nfunction eitherPointDoesntMeetConfidence(a, b, minConfidence) {\n return (a < minConfidence || b < minConfidence);\n}\n\nfunction getAdjacentKeyPoints(keypoints, minConfidence) {\n return kpt.connectedPartIndices.reduce((result, [leftJoint, rightJoint]) => {\n if (eitherPointDoesntMeetConfidence(keypoints[leftJoint].score, keypoints[rightJoint].score, minConfidence)) {\n return result;\n }\n result.push([keypoints[leftJoint], keypoints[rightJoint]]);\n return result;\n }, []);\n}\nexports.getAdjacentKeyPoints = getAdjacentKeyPoints;\n\nconst { NEGATIVE_INFINITY, POSITIVE_INFINITY } = Number;\nfunction getBoundingBox(keypoints) {\n return keypoints.reduce(({ maxX, maxY, minX, minY }, { position: { x, y } }) => ({\n maxX: Math.max(maxX, x),\n maxY: Math.max(maxY, y),\n minX: Math.min(minX, x),\n minY: Math.min(minY, y),\n }), {\n maxX: NEGATIVE_INFINITY,\n maxY: NEGATIVE_INFINITY,\n minX: POSITIVE_INFINITY,\n minY: POSITIVE_INFINITY,\n });\n}\nexports.getBoundingBox = getBoundingBox;\nfunction getBoundingBoxPoints(keypoints) {\n const { minX, minY, maxX, maxY } = getBoundingBox(keypoints);\n return [{ x: minX, y: minY }, { x: maxX, y: minY }, { x: maxX, y: maxY }, { x: minX, y: maxY }];\n}\nexports.getBoundingBoxPoints = getBoundingBoxPoints;\nasync function toTensorBuffers3D(tensors) {\n return Promise.all(tensors.map((tensor) => tensor.buffer()));\n}\nexports.toTensorBuffers3D = toTensorBuffers3D;\n\nfunction scalePose(pose, scaleY, scaleX) {\n return {\n score: pose.score,\n keypoints: pose.keypoints.map(({ score, part, position }) => ({\n score,\n part,\n position: { x: position.x * scaleX, y: position.y * scaleY },\n })),\n };\n}\nexports.scalePose = scalePose;\n\nfunction resizeTo(image, [targetH, targetW]) {\n const input = image.squeeze(0);\n const resized = input.resizeBilinear([targetH, targetW]);\n input.dispose();\n return resized;\n}\nexports.resizeTo = resizeTo;\n\nfunction scaleAndFlipPoses(poses, [height, width], [inputResolutionHeight, inputResolutionWidth]) {\n const scaledPoses = poses.map((pose) => scalePose(pose, height / inputResolutionHeight, width / inputResolutionWidth));\n return scaledPoses;\n}\nexports.scaleAndFlipPoses = scaleAndFlipPoses;\n", "const tf = require('@tensorflow/tfjs');\nconst modelMobileNet = require('./modelMobileNet');\nconst decodeMultiple = require('./decodeMultiple');\nconst util = require('./util');\n\nclass PoseNet {\n constructor(net) {\n this.baseModel = net;\n }\n\n /**\n * Infer through PoseNet, and estimates multiple poses using the outputs.\n * This does standard ImageNet pre-processing before inferring through the\n * model. The image should pixels should have values [0-255]. It detects\n * multiple poses and finds their parts from part scores and displacement\n * vectors using a fast greedy decoding algorithm. It returns up to\n * `config.maxDetections` object instance detections in decreasing root\n * score order.\n *\n * @param input\n * ImageData|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement) The input\n * image to feed through the network.\n *\n * @param config MultiPoseEstimationConfig object that contains parameters\n * for the PoseNet inference using multiple pose estimation.\n *\n * @return An array of poses and their scores, each containing keypoints and\n * the corresponding keypoint scores. The positions of the keypoints are\n * in the same scale as the original image\n */\n async estimatePoses(input, config) {\n const outputStride = config.outputStride;\n // const inputResolution = config.inputResolution;\n const height = input.shape[1];\n const width = input.shape[2];\n const resized = util.resizeTo(input, [config.inputResolution, config.inputResolution]);\n const { heatmapScores, offsets, displacementFwd, displacementBwd } = this.baseModel.predict(resized);\n const allTensorBuffers = await util.toTensorBuffers3D([heatmapScores, offsets, displacementFwd, displacementBwd]);\n const scoresBuffer = allTensorBuffers[0];\n const offsetsBuffer = allTensorBuffers[1];\n const displacementsFwdBuffer = allTensorBuffers[2];\n const displacementsBwdBuffer = allTensorBuffers[3];\n const poses = await decodeMultiple.decodeMultiplePoses(scoresBuffer, offsetsBuffer, displacementsFwdBuffer, displacementsBwdBuffer, outputStride, config.maxDetections, config.scoreThreshold, config.nmsRadius);\n const resultPoses = util.scaleAndFlipPoses(poses, [height, width], [config.inputResolution, config.inputResolution]);\n heatmapScores.dispose();\n offsets.dispose();\n displacementFwd.dispose();\n displacementBwd.dispose();\n resized.dispose();\n return resultPoses;\n }\n\n dispose() {\n this.baseModel.dispose();\n }\n}\nexports.PoseNet = PoseNet;\nasync function loadMobileNet(config) {\n const graphModel = await tf.loadGraphModel(config.modelPath);\n const mobilenet = new modelMobileNet.MobileNet(graphModel, config.outputStride);\n return new PoseNet(mobilenet);\n}\n/**\n * Loads the PoseNet model instance from a checkpoint, with the MobileNet architecture. The model to be loaded is configurable using the\n * config dictionary ModelConfig. Please find more details in the documentation of the ModelConfig.\n *\n * @param config ModelConfig dictionary that contains parameters for\n * the PoseNet loading process. Please find more details of each parameters\n * in the documentation of the ModelConfig interface. The predefined\n * `MOBILENET_V1_CONFIG` and `RESNET_CONFIG` can also be used as references\n * for defining your customized config.\n */\nasync function load(config) {\n return loadMobileNet(config);\n}\nexports.load = load;\n", "const modelMobileNet = require('./modelMobileNet');\nconst modelPoseNet = require('./modelPoseNet');\nconst decodeMultiple = require('./decodeMultiple');\nconst keypoints = require('./keypoints');\nconst util = require('./util');\n\nexports.load = modelPoseNet.load;\nexports.PoseNet = modelPoseNet.PoseNet;\n\nexports.MobileNet = modelMobileNet.MobileNet;\nexports.decodeMultiplePoses = decodeMultiple.decodeMultiplePoses;\nexports.partChannels = keypoints.partChannels;\nexports.partIds = keypoints.partIds;\nexports.partNames = keypoints.partNames;\nexports.poseChain = keypoints.poseChain;\nexports.getAdjacentKeyPoints = util.getAdjacentKeyPoints;\nexports.getBoundingBox = util.getBoundingBox;\nexports.getBoundingBoxPoints = util.getBoundingBoxPoints;\nexports.scaleAndFlipPoses = util.scaleAndFlipPoses;\nexports.scalePose = util.scalePose;\n", "const tf = require('@tensorflow/tfjs');\n\nfunction getBoxSize(box) {\n return [\n Math.abs(box.endPoint[0] - box.startPoint[0]),\n Math.abs(box.endPoint[1] - box.startPoint[1]),\n ];\n}\nexports.getBoxSize = getBoxSize;\n\nfunction getBoxCenter(box) {\n return [\n box.startPoint[0] + (box.endPoint[0] - box.startPoint[0]) / 2,\n box.startPoint[1] + (box.endPoint[1] - box.startPoint[1]) / 2,\n ];\n}\nexports.getBoxCenter = getBoxCenter;\n\nfunction cutBoxFromImageAndResize(box, image, cropSize) {\n const h = image.shape[1];\n const w = image.shape[2];\n const boxes = [[\n box.startPoint[1] / h, box.startPoint[0] / w, box.endPoint[1] / h,\n box.endPoint[0] / w,\n ]];\n return tf.image.cropAndResize(image, boxes, [0], cropSize);\n}\nexports.cutBoxFromImageAndResize = cutBoxFromImageAndResize;\n\nfunction scaleBoxCoordinates(box, factor) {\n const startPoint = [box.startPoint[0] * factor[0], box.startPoint[1] * factor[1]];\n const endPoint = [box.endPoint[0] * factor[0], box.endPoint[1] * factor[1]];\n const palmLandmarks = box.palmLandmarks.map((coord) => {\n const scaledCoord = [coord[0] * factor[0], coord[1] * factor[1]];\n return scaledCoord;\n });\n return { startPoint, endPoint, palmLandmarks };\n}\nexports.scaleBoxCoordinates = scaleBoxCoordinates;\n\nfunction enlargeBox(box, factor = 1.5) {\n const center = getBoxCenter(box);\n const size = getBoxSize(box);\n const newHalfSize = [factor * size[0] / 2, factor * size[1] / 2];\n const startPoint = [center[0] - newHalfSize[0], center[1] - newHalfSize[1]];\n const endPoint = [center[0] + newHalfSize[0], center[1] + newHalfSize[1]];\n return { startPoint, endPoint, palmLandmarks: box.palmLandmarks };\n}\nexports.enlargeBox = enlargeBox;\n\nfunction squarifyBox(box) {\n const centers = getBoxCenter(box);\n const size = getBoxSize(box);\n const maxEdge = Math.max(...size);\n const halfSize = maxEdge / 2;\n const startPoint = [centers[0] - halfSize, centers[1] - halfSize];\n const endPoint = [centers[0] + halfSize, centers[1] + halfSize];\n return { startPoint, endPoint, palmLandmarks: box.palmLandmarks };\n}\nexports.squarifyBox = squarifyBox;\n\nfunction shiftBox(box, shiftFactor) {\n const boxSize = [\n box.endPoint[0] - box.startPoint[0], box.endPoint[1] - box.startPoint[1],\n ];\n const shiftVector = [boxSize[0] * shiftFactor[0], boxSize[1] * shiftFactor[1]];\n const startPoint = [box.startPoint[0] + shiftVector[0], box.startPoint[1] + shiftVector[1]];\n const endPoint = [box.endPoint[0] + shiftVector[0], box.endPoint[1] + shiftVector[1]];\n return { startPoint, endPoint, palmLandmarks: box.palmLandmarks };\n}\nexports.shiftBox = shiftBox;\n", "const tf = require('@tensorflow/tfjs');\nconst bounding = require('./box');\n\nclass HandDetector {\n constructor(model, anchors, config) {\n this.model = model;\n this.width = config.inputSize;\n this.height = config.inputSize;\n this.anchors = anchors.map((anchor) => [anchor.x_center, anchor.y_center]);\n this.anchorsTensor = tf.tensor2d(this.anchors);\n this.inputSizeTensor = tf.tensor1d([config.inputSize, config.inputSize]);\n this.doubleInputSizeTensor = tf.tensor1d([config.inputSize * 2, config.inputSize * 2]);\n }\n\n normalizeBoxes(boxes) {\n return tf.tidy(() => {\n const boxOffsets = tf.slice(boxes, [0, 0], [-1, 2]);\n const boxSizes = tf.slice(boxes, [0, 2], [-1, 2]);\n const boxCenterPoints = tf.add(tf.div(boxOffsets, this.inputSizeTensor), this.anchorsTensor);\n const halfBoxSizes = tf.div(boxSizes, this.doubleInputSizeTensor);\n const startPoints = tf.mul(tf.sub(boxCenterPoints, halfBoxSizes), this.inputSizeTensor);\n const endPoints = tf.mul(tf.add(boxCenterPoints, halfBoxSizes), this.inputSizeTensor);\n return tf.concat2d([startPoints, endPoints], 1);\n });\n }\n\n normalizeLandmarks(rawPalmLandmarks, index) {\n return tf.tidy(() => {\n const landmarks = tf.add(tf.div(rawPalmLandmarks.reshape([-1, 7, 2]), this.inputSizeTensor), this.anchors[index]);\n return tf.mul(landmarks, this.inputSizeTensor);\n });\n }\n\n async getBoundingBoxes(input) {\n const batchedPrediction = this.model.predict(input);\n const prediction = batchedPrediction.squeeze();\n // Regression score for each anchor point.\n const scores = tf.tidy(() => tf.sigmoid(tf.slice(prediction, [0, 0], [-1, 1])).squeeze());\n // Bounding box for each anchor point.\n const rawBoxes = tf.slice(prediction, [0, 1], [-1, 4]);\n const boxes = this.normalizeBoxes(rawBoxes);\n const boxesWithHandsTensor = await tf.image.nonMaxSuppressionAsync(boxes, scores, this.maxHands, this.iouThreshold, this.scoreThreshold);\n const boxesWithHands = await boxesWithHandsTensor.array();\n const toDispose = [batchedPrediction, boxesWithHandsTensor, prediction, boxes, rawBoxes, scores];\n const detectedHands = tf.tidy(() => {\n const detectedBoxes = [];\n for (const i in boxesWithHands) {\n const boxIndex = boxesWithHands[i];\n const matchingBox = tf.slice(boxes, [boxIndex, 0], [1, -1]);\n const rawPalmLandmarks = tf.slice(prediction, [boxIndex, 5], [1, 14]);\n const palmLandmarks = tf.tidy(() => this.normalizeLandmarks(rawPalmLandmarks, boxIndex).reshape([-1, 2]));\n detectedBoxes.push({ boxes: matchingBox, palmLandmarks });\n }\n return detectedBoxes;\n });\n toDispose.forEach((tensor) => tensor.dispose());\n return detectedHands;\n }\n\n /**\n * Returns a Box identifying the bounding box of a hand within the image.\n * Returns null if there is no hand in the image.\n *\n * @param input The image to classify.\n */\n async estimateHandBounds(input, config) {\n // const inputHeight = input.shape[2];\n // const inputWidth = input.shape[1];\n this.iouThreshold = config.iouThreshold;\n this.scoreThreshold = config.scoreThreshold;\n this.maxHands = config.maxHands;\n const resized = input.resizeBilinear([this.width, this.height]);\n const divided = resized.div(255);\n const normalized = divided.sub(0.5);\n const image = normalized.mul(2.0);\n resized.dispose();\n divided.dispose();\n normalized.dispose();\n const predictions = await this.getBoundingBoxes(image);\n image.dispose();\n if (!predictions || (predictions.length === 0)) return null;\n const hands = [];\n for (const i in predictions) {\n const prediction = predictions[i];\n const boundingBoxes = await prediction.boxes.array();\n const startPoint = boundingBoxes[0].slice(0, 2);\n const endPoint = boundingBoxes[0].slice(2, 4);\n const palmLandmarks = await prediction.palmLandmarks.array();\n prediction.boxes.dispose();\n prediction.palmLandmarks.dispose();\n hands.push(bounding.scaleBoxCoordinates({ startPoint, endPoint, palmLandmarks }, [input.shape[2] / this.width, input.shape[1] / this.height]));\n }\n return hands;\n }\n}\nexports.HandDetector = HandDetector;\n", "exports.MESH_ANNOTATIONS = {\n thumb: [1, 2, 3, 4],\n indexFinger: [5, 6, 7, 8],\n middleFinger: [9, 10, 11, 12],\n ringFinger: [13, 14, 15, 16],\n pinky: [17, 18, 19, 20],\n palmBase: [0],\n};\n", "function normalizeRadians(angle) {\n return angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));\n}\nexports.normalizeRadians = normalizeRadians;\n\nfunction computeRotation(point1, point2) {\n const radians = Math.PI / 2 - Math.atan2(-(point2[1] - point1[1]), point2[0] - point1[0]);\n return normalizeRadians(radians);\n}\nexports.computeRotation = computeRotation;\n\nconst buildTranslationMatrix = (x, y) => ([[1, 0, x], [0, 1, y], [0, 0, 1]]);\nfunction dot(v1, v2) {\n let product = 0;\n for (let i = 0; i < v1.length; i++) {\n product += v1[i] * v2[i];\n }\n return product;\n}\nexports.dot = dot;\n\nfunction getColumnFrom2DArr(arr, columnIndex) {\n const column = [];\n for (let i = 0; i < arr.length; i++) {\n column.push(arr[i][columnIndex]);\n }\n return column;\n}\nexports.getColumnFrom2DArr = getColumnFrom2DArr;\n\nfunction multiplyTransformMatrices(mat1, mat2) {\n const product = [];\n const size = mat1.length;\n for (let row = 0; row < size; row++) {\n product.push([]);\n for (let col = 0; col < size; col++) {\n product[row].push(dot(mat1[row], getColumnFrom2DArr(mat2, col)));\n }\n }\n return product;\n}\nfunction buildRotationMatrix(rotation, center) {\n const cosA = Math.cos(rotation);\n const sinA = Math.sin(rotation);\n const rotationMatrix = [[cosA, -sinA, 0], [sinA, cosA, 0], [0, 0, 1]];\n const translationMatrix = buildTranslationMatrix(center[0], center[1]);\n const translationTimesRotation = multiplyTransformMatrices(translationMatrix, rotationMatrix);\n const negativeTranslationMatrix = buildTranslationMatrix(-center[0], -center[1]);\n return multiplyTransformMatrices(translationTimesRotation, negativeTranslationMatrix);\n}\nexports.buildRotationMatrix = buildRotationMatrix;\n\nfunction invertTransformMatrix(matrix) {\n const rotationComponent = [[matrix[0][0], matrix[1][0]], [matrix[0][1], matrix[1][1]]];\n const translationComponent = [matrix[0][2], matrix[1][2]];\n const invertedTranslation = [\n -dot(rotationComponent[0], translationComponent),\n -dot(rotationComponent[1], translationComponent),\n ];\n return [\n rotationComponent[0].concat(invertedTranslation[0]),\n rotationComponent[1].concat(invertedTranslation[1]),\n [0, 0, 1],\n ];\n}\nexports.invertTransformMatrix = invertTransformMatrix;\n\nfunction rotatePoint(homogeneousCoordinate, rotationMatrix) {\n return [\n dot(homogeneousCoordinate, rotationMatrix[0]),\n dot(homogeneousCoordinate, rotationMatrix[1]),\n ];\n}\nexports.rotatePoint = rotatePoint;\n", "const tf = require('@tensorflow/tfjs');\nconst bounding = require('./box');\nconst util = require('./util');\n\nconst UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD = 0.8;\nconst PALM_BOX_SHIFT_VECTOR = [0, -0.4];\nconst HAND_BOX_SHIFT_VECTOR = [0, -0.1];\nconst HAND_BOX_ENLARGE_FACTOR = 1.65;\nconst PALM_LANDMARK_IDS = [0, 5, 9, 13, 17, 1, 2];\nconst PALM_LANDMARKS_INDEX_OF_PALM_BASE = 0;\nconst PALM_LANDMARKS_INDEX_OF_MIDDLE_FINGER_BASE = 2;\n\n// The Pipeline coordinates between the bounding box and skeleton models.\nclass HandPipeline {\n constructor(boundingBoxDetector, meshDetector, config) {\n this.regionsOfInterest = [];\n this.runsWithoutHandDetector = 0;\n this.boundingBoxDetector = boundingBoxDetector;\n this.meshDetector = meshDetector;\n this.meshWidth = config.inputSize;\n this.meshHeight = config.inputSize;\n this.enlargeFactor = config.enlargeFactor;\n }\n\n // Get the bounding box surrounding the hand, given palm landmarks.\n getBoxForPalmLandmarks(palmLandmarks, rotationMatrix) {\n const rotatedPalmLandmarks = palmLandmarks.map((coord) => {\n const homogeneousCoordinate = [...coord, 1];\n return util.rotatePoint(homogeneousCoordinate, rotationMatrix);\n });\n const boxAroundPalm = this.calculateLandmarksBoundingBox(rotatedPalmLandmarks);\n // boxAroundPalm only surrounds the palm - therefore we shift it\n // upwards so it will capture fingers once enlarged + squarified.\n return bounding.enlargeBox(bounding.squarifyBox(bounding.shiftBox(boxAroundPalm, PALM_BOX_SHIFT_VECTOR)), this.enlargeFactor);\n }\n\n // Get the bounding box surrounding the hand, given all hand landmarks.\n getBoxForHandLandmarks(landmarks) {\n // The MediaPipe hand mesh model is trained on hands with empty space\n // around them, so we still need to shift / enlarge boxAroundHand even\n // though it surrounds the entire hand.\n const boundingBox = this.calculateLandmarksBoundingBox(landmarks);\n const boxAroundHand = bounding.enlargeBox(bounding.squarifyBox(bounding.shiftBox(boundingBox, HAND_BOX_SHIFT_VECTOR)), HAND_BOX_ENLARGE_FACTOR);\n const palmLandmarks = [];\n for (let i = 0; i < PALM_LANDMARK_IDS.length; i++) {\n palmLandmarks.push(landmarks[PALM_LANDMARK_IDS[i]].slice(0, 2));\n }\n boxAroundHand.palmLandmarks = palmLandmarks;\n return boxAroundHand;\n }\n\n // Scale, rotate, and translate raw keypoints from the model so they map to\n // the input coordinates.\n transformRawCoords(rawCoords, box, angle, rotationMatrix) {\n const boxSize = bounding.getBoxSize(box);\n const scaleFactor = [boxSize[0] / this.meshWidth, boxSize[1] / this.meshHeight];\n const coordsScaled = rawCoords.map((coord) => [\n scaleFactor[0] * (coord[0] - this.meshWidth / 2),\n scaleFactor[1] * (coord[1] - this.meshHeight / 2), coord[2],\n ]);\n const coordsRotationMatrix = util.buildRotationMatrix(angle, [0, 0]);\n const coordsRotated = coordsScaled.map((coord) => {\n const rotated = util.rotatePoint(coord, coordsRotationMatrix);\n return [...rotated, coord[2]];\n });\n const inverseRotationMatrix = util.invertTransformMatrix(rotationMatrix);\n const boxCenter = [...bounding.getBoxCenter(box), 1];\n const originalBoxCenter = [\n util.dot(boxCenter, inverseRotationMatrix[0]),\n util.dot(boxCenter, inverseRotationMatrix[1]),\n ];\n return coordsRotated.map((coord) => [\n coord[0] + originalBoxCenter[0], coord[1] + originalBoxCenter[1],\n coord[2],\n ]);\n }\n\n async estimateHands(image, config) {\n this.skipFrames = config.skipFrames;\n this.detectionConfidence = config.minConfidence;\n this.maxHands = config.maxHands;\n this.runsWithoutHandDetector++;\n const useFreshBox = this.shouldUpdateRegionsOfInterest();\n if (useFreshBox === true) {\n const boundingBoxPredictions = await this.boundingBoxDetector.estimateHandBounds(image, config);\n this.regionsOfInterest = [];\n for (const i in boundingBoxPredictions) {\n this.updateRegionsOfInterest(boundingBoxPredictions[i], true /* force update */, i);\n }\n this.runsWithoutHandDetector = 0;\n }\n // Rotate input so the hand is vertically oriented.\n const hands = [];\n if (!this.regionsOfInterest) return hands;\n for (const i in this.regionsOfInterest) {\n const currentBox = this.regionsOfInterest[i][0];\n if (!currentBox) return hands;\n const angle = util.computeRotation(currentBox.palmLandmarks[PALM_LANDMARKS_INDEX_OF_PALM_BASE], currentBox.palmLandmarks[PALM_LANDMARKS_INDEX_OF_MIDDLE_FINGER_BASE]);\n const palmCenter = bounding.getBoxCenter(currentBox);\n const palmCenterNormalized = [palmCenter[0] / image.shape[2], palmCenter[1] / image.shape[1]];\n const rotatedImage = tf.image.rotateWithOffset(image, angle, 0, palmCenterNormalized);\n const rotationMatrix = util.buildRotationMatrix(-angle, palmCenter);\n const box = useFreshBox ? this.getBoxForPalmLandmarks(currentBox.palmLandmarks, rotationMatrix) : currentBox;\n const croppedInput = bounding.cutBoxFromImageAndResize(box, rotatedImage, [this.meshWidth, this.meshHeight]);\n const handImage = croppedInput.div(255);\n croppedInput.dispose();\n rotatedImage.dispose();\n const prediction = this.meshDetector.predict(handImage);\n const [flag, keypoints] = prediction;\n handImage.dispose();\n const flagValue = flag.dataSync()[0];\n flag.dispose();\n if (flagValue < config.minConfidence) {\n keypoints.dispose();\n this.regionsOfInterest[i] = [];\n return hands;\n }\n const keypointsReshaped = tf.reshape(keypoints, [-1, 3]);\n const rawCoords = await keypointsReshaped.array();\n keypoints.dispose();\n keypointsReshaped.dispose();\n const coords = this.transformRawCoords(rawCoords, box, angle, rotationMatrix);\n const nextBoundingBox = this.getBoxForHandLandmarks(coords);\n this.updateRegionsOfInterest(nextBoundingBox, false /* force replace */, i);\n const result = {\n landmarks: coords,\n confidence: flagValue,\n box: {\n topLeft: nextBoundingBox.startPoint,\n bottomRight: nextBoundingBox.endPoint,\n },\n };\n hands.push(result);\n }\n return hands;\n }\n\n // eslint-disable-next-line class-methods-use-this\n calculateLandmarksBoundingBox(landmarks) {\n const xs = landmarks.map((d) => d[0]);\n const ys = landmarks.map((d) => d[1]);\n const startPoint = [Math.min(...xs), Math.min(...ys)];\n const endPoint = [Math.max(...xs), Math.max(...ys)];\n return { startPoint, endPoint };\n }\n\n // Updates regions of interest if the intersection over union between\n // the incoming and previous regions falls below a threshold.\n updateRegionsOfInterest(box, forceUpdate, index) {\n if (forceUpdate) {\n this.regionsOfInterest[index] = [box];\n } else {\n const previousBox = this.regionsOfInterest[index][0];\n let iou = 0;\n if (previousBox != null && previousBox.startPoint != null) {\n const [boxStartX, boxStartY] = box.startPoint;\n const [boxEndX, boxEndY] = box.endPoint;\n const [previousBoxStartX, previousBoxStartY] = previousBox.startPoint;\n const [previousBoxEndX, previousBoxEndY] = previousBox.endPoint;\n const xStartMax = Math.max(boxStartX, previousBoxStartX);\n const yStartMax = Math.max(boxStartY, previousBoxStartY);\n const xEndMin = Math.min(boxEndX, previousBoxEndX);\n const yEndMin = Math.min(boxEndY, previousBoxEndY);\n const intersection = (xEndMin - xStartMax) * (yEndMin - yStartMax);\n const boxArea = (boxEndX - boxStartX) * (boxEndY - boxStartY);\n const previousBoxArea = (previousBoxEndX - previousBoxStartX) * (previousBoxEndY - boxStartY);\n iou = intersection / (boxArea + previousBoxArea - intersection);\n }\n this.regionsOfInterest[index][0] = iou > UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD ? previousBox : box;\n }\n }\n\n shouldUpdateRegionsOfInterest() {\n return !this.regionsOfInterest || (this.regionsOfInterest.length === 0) || (this.runsWithoutHandDetector >= this.skipFrames);\n }\n}\nexports.HandPipeline = HandPipeline;\n", "const tf = require('@tensorflow/tfjs');\nconst hand = require('./handdetector');\nconst keypoints = require('./keypoints');\nconst pipe = require('./pipeline');\n\nclass HandPose {\n constructor(pipeline) {\n this.pipeline = pipeline;\n }\n\n async estimateHands(input, config) {\n this.skipFrames = config.skipFrames;\n this.detectionConfidence = config.minConfidence;\n this.maxHands = config.maxHands;\n const predictions = await this.pipeline.estimateHands(input, config);\n const hands = [];\n if (!predictions) return hands;\n for (const prediction of predictions) {\n if (!prediction) return [];\n const annotations = {};\n for (const key of Object.keys(keypoints.MESH_ANNOTATIONS)) {\n annotations[key] = keypoints.MESH_ANNOTATIONS[key].map((index) => prediction.landmarks[index]);\n }\n hands.push({\n confidence: prediction.confidence || 0,\n box: prediction.box ? [prediction.box.topLeft[0], prediction.box.topLeft[1], prediction.box.bottomRight[0] - prediction.box.topLeft[0], prediction.box.bottomRight[1] - prediction.box.topLeft[1]] : 0,\n landmarks: prediction.landmarks,\n annotations,\n });\n }\n return hands;\n }\n}\nexports.HandPose = HandPose;\n\nasync function loadAnchors(url) {\n if (tf.env().features.IS_NODE) {\n // eslint-disable-next-line global-require\n const fs = require('fs');\n const data = await fs.readFileSync(url.replace('file://', ''));\n return JSON.parse(data);\n }\n return tf.util.fetch(url).then((d) => d.json());\n}\n\nasync function load(config) {\n const [anchors, handDetectorModel, handPoseModel] = await Promise.all([\n loadAnchors(config.detector.anchors),\n tf.loadGraphModel(config.detector.modelPath, { fromTFHub: config.detector.modelPath.includes('tfhub.dev') }),\n tf.loadGraphModel(config.skeleton.modelPath, { fromTFHub: config.skeleton.modelPath.includes('tfhub.dev') }),\n ]);\n const detector = new hand.HandDetector(handDetectorModel, anchors, config);\n const pipeline = new pipe.HandPipeline(detector, handPoseModel, config);\n const handpose = new HandPose(pipeline);\n return handpose;\n}\nexports.load = load;\n", "/* eslint-disable no-shadow */\n/* eslint-disable prefer-rest-params */\n/* eslint-disable no-sequences */\n/* eslint-disable no-unused-vars */\n/* eslint-disable no-unused-expressions */\n/* eslint-disable no-multi-assign */\n/* eslint-disable no-use-before-define */\n/*\nWebGLImageFilter - MIT Licensed\n2013, Dominic Szablewski - phoboslab.org\n*/\n\nconst WebGLProgram = function (gl, vertexSource, fragmentSource) {\n const _collect = function (source, prefix, collection) {\n const r = new RegExp('\\\\b' + prefix + ' \\\\w+ (\\\\w+)', 'ig');\n source.replace(r, (match, name) => {\n collection[name] = 0;\n return match;\n });\n };\n\n const _compile = function (gl, source, type) {\n const shader = gl.createShader(type);\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n throw new Error('Filter: GL compile failed', gl.getShaderInfoLog(shader));\n }\n return shader;\n };\n\n this.uniform = {};\n this.attribute = {};\n\n const _vsh = _compile(gl, vertexSource, gl.VERTEX_SHADER);\n const _fsh = _compile(gl, fragmentSource, gl.FRAGMENT_SHADER);\n\n this.id = gl.createProgram();\n gl.attachShader(this.id, _vsh);\n gl.attachShader(this.id, _fsh);\n gl.linkProgram(this.id);\n\n if (!gl.getProgramParameter(this.id, gl.LINK_STATUS)) {\n throw new Error('Filter: GL link failed', gl.getProgramInfoLog(this.id));\n }\n\n gl.useProgram(this.id);\n\n // Collect attributes\n _collect(vertexSource, 'attribute', this.attribute);\n for (const a in this.attribute) {\n this.attribute[a] = gl.getAttribLocation(this.id, a);\n }\n\n // Collect uniforms\n _collect(vertexSource, 'uniform', this.uniform);\n _collect(fragmentSource, 'uniform', this.uniform);\n for (const u in this.uniform) {\n this.uniform[u] = gl.getUniformLocation(this.id, u);\n }\n};\n\nconst WebGLImageFilter = function (params) {\n if (!params) params = { };\n let _drawCount = 0;\n let _sourceTexture = null;\n let _lastInChain = false;\n let _currentFramebufferIndex = -1;\n let _tempFramebuffers = [null, null];\n let _filterChain = [];\n let _width = -1;\n let _height = -1;\n let _vertexBuffer = null;\n let _currentProgram = null;\n const _canvas = params.canvas || document.createElement('canvas');\n\n // key is the shader program source, value is the compiled program\n const _shaderProgramCache = { };\n\n const gl = _canvas.getContext('webgl') || _canvas.getContext('experimental-webgl');\n if (!gl) throw new Error('Filter: getContext() failed');\n\n this.addFilter = function (name) {\n const args = Array.prototype.slice.call(arguments, 1);\n const filter = _filter[name];\n\n _filterChain.push({ func: filter, args });\n };\n\n this.reset = function () {\n _filterChain = [];\n };\n\n this.apply = function (image) {\n _resize(image.width, image.height);\n _drawCount = 0;\n\n // Create the texture for the input image if we haven't yet\n if (!_sourceTexture) _sourceTexture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, _sourceTexture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);\n\n // No filters? Just draw\n if (_filterChain.length === 0) {\n const program = _compileShader(SHADER.FRAGMENT_IDENTITY);\n _draw();\n return _canvas;\n }\n\n for (let i = 0; i < _filterChain.length; i++) {\n _lastInChain = (i === _filterChain.length - 1);\n const f = _filterChain[i];\n f.func.apply(this, f.args || []);\n }\n\n return _canvas;\n };\n\n const _resize = function (width, height) {\n // Same width/height? Nothing to do here\n if (width === _width && height === _height) { return; }\n\n _canvas.width = _width = width;\n _canvas.height = _height = height;\n\n // Create the context if we don't have it yet\n if (!_vertexBuffer) {\n // Create the vertex buffer for the two triangles [x, y, u, v] * 6\n const vertices = new Float32Array([\n -1, -1, 0, 1, 1, -1, 1, 1, -1, 1, 0, 0,\n -1, 1, 0, 0, 1, -1, 1, 1, 1, 1, 1, 0,\n ]);\n _vertexBuffer = gl.createBuffer(),\n gl.bindBuffer(gl.ARRAY_BUFFER, _vertexBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);\n\n // Note sure if this is a good idea; at least it makes texture loading\n // in Ejecta instant.\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);\n }\n\n gl.viewport(0, 0, _width, _height);\n\n // Delete old temp framebuffers\n _tempFramebuffers = [null, null];\n };\n\n const _getTempFramebuffer = function (index) {\n _tempFramebuffers[index] = _tempFramebuffers[index]\n || _createFramebufferTexture(_width, _height);\n\n return _tempFramebuffers[index];\n };\n\n const _createFramebufferTexture = function (width, height) {\n const fbo = gl.createFramebuffer();\n gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);\n\n const renderbuffer = gl.createRenderbuffer();\n gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer);\n\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);\n\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n\n return { fbo, texture };\n };\n\n const _draw = function (flags) {\n let source = null;\n let target = null;\n let flipY = false;\n\n // Set up the source\n if (_drawCount === 0) {\n // First draw call - use the source texture\n source = _sourceTexture;\n } else {\n // All following draw calls use the temp buffer last drawn to\n source = _getTempFramebuffer(_currentFramebufferIndex).texture;\n }\n _drawCount++;\n\n // Set up the target\n if (_lastInChain && !(flags & DRAW.INTERMEDIATE)) {\n // Last filter in our chain - draw directly to the WebGL Canvas. We may\n // also have to flip the image vertically now\n target = null;\n flipY = _drawCount % 2 === 0;\n } else {\n // Intermediate draw call - get a temp buffer to draw to\n _currentFramebufferIndex = (_currentFramebufferIndex + 1) % 2;\n target = _getTempFramebuffer(_currentFramebufferIndex).fbo;\n }\n\n // Bind the source and target and draw the two triangles\n gl.bindTexture(gl.TEXTURE_2D, source);\n gl.bindFramebuffer(gl.FRAMEBUFFER, target);\n\n gl.uniform1f(_currentProgram.uniform.flipY, (flipY ? -1 : 1));\n gl.drawArrays(gl.TRIANGLES, 0, 6);\n };\n\n const _compileShader = function (fragmentSource) {\n if (_shaderProgramCache[fragmentSource]) {\n _currentProgram = _shaderProgramCache[fragmentSource];\n gl.useProgram(_currentProgram.id);\n return _currentProgram;\n }\n\n // Compile shaders\n _currentProgram = new WebGLProgram(gl, SHADER.VERTEX_IDENTITY, fragmentSource);\n\n const floatSize = Float32Array.BYTES_PER_ELEMENT;\n const vertSize = 4 * floatSize;\n gl.enableVertexAttribArray(_currentProgram.attribute.pos);\n gl.vertexAttribPointer(_currentProgram.attribute.pos, 2, gl.FLOAT, false, vertSize, 0 * floatSize);\n gl.enableVertexAttribArray(_currentProgram.attribute.uv);\n gl.vertexAttribPointer(_currentProgram.attribute.uv, 2, gl.FLOAT, false, vertSize, 2 * floatSize);\n\n _shaderProgramCache[fragmentSource] = _currentProgram;\n return _currentProgram;\n };\n\n let DRAW = { INTERMEDIATE: 1 };\n\n let SHADER = {};\n SHADER.VERTEX_IDENTITY = [\n 'precision highp float;',\n 'attribute vec2 pos;',\n 'attribute vec2 uv;',\n 'varying vec2 vUv;',\n 'uniform float flipY;',\n\n 'void main(void) {',\n 'vUv = uv;',\n 'gl_Position = vec4(pos.x, pos.y*flipY, 0.0, 1.);',\n '}',\n ].join('\\n');\n\n SHADER.FRAGMENT_IDENTITY = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n\n 'void main(void) {',\n 'gl_FragColor = texture2D(texture, vUv);',\n '}',\n ].join('\\n');\n\n let _filter = {};\n\n // -------------------------------------------------------------------------\n // Color Matrix Filter\n\n _filter.colorMatrix = function (matrix) {\n // Create a Float32 Array and normalize the offset component to 0-1\n const m = new Float32Array(matrix);\n m[4] /= 255;\n m[9] /= 255;\n m[14] /= 255;\n m[19] /= 255;\n\n // Can we ignore the alpha value? Makes things a bit faster.\n const shader = (m[18] === 1 && m[3] === 0 && m[8] === 0 && m[13] === 0 && m[15] === 0 && m[16] === 0 && m[17] === 0 && m[19] === 0)\n ? _filter.colorMatrix.SHADER.WITHOUT_ALPHA\n : _filter.colorMatrix.SHADER.WITH_ALPHA;\n\n const program = _compileShader(shader);\n gl.uniform1fv(program.uniform.m, m);\n _draw();\n };\n\n _filter.colorMatrix.SHADER = {};\n _filter.colorMatrix.SHADER.WITH_ALPHA = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform float m[20];',\n\n 'void main(void) {',\n 'vec4 c = texture2D(texture, vUv);',\n 'gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[3] * c.a + m[4];',\n 'gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[8] * c.a + m[9];',\n 'gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[13] * c.a + m[14];',\n 'gl_FragColor.a = m[15] * c.r + m[16] * c.g + m[17] * c.b + m[18] * c.a + m[19];',\n '}',\n ].join('\\n');\n _filter.colorMatrix.SHADER.WITHOUT_ALPHA = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform float m[20];',\n\n 'void main(void) {',\n 'vec4 c = texture2D(texture, vUv);',\n 'gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[4];',\n 'gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[9];',\n 'gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[14];',\n 'gl_FragColor.a = c.a;',\n '}',\n ].join('\\n');\n\n _filter.brightness = function (brightness) {\n const b = (brightness || 0) + 1;\n _filter.colorMatrix([\n b, 0, 0, 0, 0,\n 0, b, 0, 0, 0,\n 0, 0, b, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.saturation = function (amount) {\n const x = (amount || 0) * 2 / 3 + 1;\n const y = ((x - 1) * -0.5);\n _filter.colorMatrix([\n x, y, y, 0, 0,\n y, x, y, 0, 0,\n y, y, x, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.desaturate = function () {\n _filter.saturation(-1);\n };\n\n _filter.contrast = function (amount) {\n const v = (amount || 0) + 1;\n const o = -128 * (v - 1);\n\n _filter.colorMatrix([\n v, 0, 0, 0, o,\n 0, v, 0, 0, o,\n 0, 0, v, 0, o,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.negative = function () {\n _filter.contrast(-2);\n };\n\n _filter.hue = function (rotation) {\n rotation = (rotation || 0) / 180 * Math.PI;\n const cos = Math.cos(rotation);\n const sin = Math.sin(rotation);\n const lumR = 0.213;\n const lumG = 0.715;\n const lumB = 0.072;\n\n _filter.colorMatrix([\n lumR + cos * (1 - lumR) + sin * (-lumR), lumG + cos * (-lumG) + sin * (-lumG), lumB + cos * (-lumB) + sin * (1 - lumB), 0, 0,\n lumR + cos * (-lumR) + sin * (0.143), lumG + cos * (1 - lumG) + sin * (0.140), lumB + cos * (-lumB) + sin * (-0.283), 0, 0,\n lumR + cos * (-lumR) + sin * (-(1 - lumR)), lumG + cos * (-lumG) + sin * (lumG), lumB + cos * (1 - lumB) + sin * (lumB), 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.desaturateLuminance = function () {\n _filter.colorMatrix([\n 0.2764723, 0.9297080, 0.0938197, 0, -37.1,\n 0.2764723, 0.9297080, 0.0938197, 0, -37.1,\n 0.2764723, 0.9297080, 0.0938197, 0, -37.1,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.sepia = function () {\n _filter.colorMatrix([\n 0.393, 0.7689999, 0.18899999, 0, 0,\n 0.349, 0.6859999, 0.16799999, 0, 0,\n 0.272, 0.5339999, 0.13099999, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.brownie = function () {\n _filter.colorMatrix([\n 0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873,\n -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127,\n 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.vintagePinhole = function () {\n _filter.colorMatrix([\n 0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123,\n 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591,\n 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.kodachrome = function () {\n _filter.colorMatrix([\n 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502,\n -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203,\n -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.technicolor = function () {\n _filter.colorMatrix([\n 1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337,\n -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398,\n -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.polaroid = function () {\n _filter.colorMatrix([\n 1.438, -0.062, -0.062, 0, 0,\n -0.122, 1.378, -0.122, 0, 0,\n -0.016, -0.016, 1.483, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.shiftToBGR = function () {\n _filter.colorMatrix([\n 0, 0, 1, 0, 0,\n 0, 1, 0, 0, 0,\n 1, 0, 0, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n // -------------------------------------------------------------------------\n // Convolution Filter\n\n _filter.convolution = function (matrix) {\n const m = new Float32Array(matrix);\n const pixelSizeX = 1 / _width;\n const pixelSizeY = 1 / _height;\n\n const program = _compileShader(_filter.convolution.SHADER);\n gl.uniform1fv(program.uniform.m, m);\n gl.uniform2f(program.uniform.px, pixelSizeX, pixelSizeY);\n _draw();\n };\n\n _filter.convolution.SHADER = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform vec2 px;',\n 'uniform float m[9];',\n\n 'void main(void) {',\n 'vec4 c11 = texture2D(texture, vUv - px);', // top left\n 'vec4 c12 = texture2D(texture, vec2(vUv.x, vUv.y - px.y));', // top center\n 'vec4 c13 = texture2D(texture, vec2(vUv.x + px.x, vUv.y - px.y));', // top right\n\n 'vec4 c21 = texture2D(texture, vec2(vUv.x - px.x, vUv.y) );', // mid left\n 'vec4 c22 = texture2D(texture, vUv);', // mid center\n 'vec4 c23 = texture2D(texture, vec2(vUv.x + px.x, vUv.y) );', // mid right\n\n 'vec4 c31 = texture2D(texture, vec2(vUv.x - px.x, vUv.y + px.y) );', // bottom left\n 'vec4 c32 = texture2D(texture, vec2(vUv.x, vUv.y + px.y) );', // bottom center\n 'vec4 c33 = texture2D(texture, vUv + px );', // bottom right\n\n 'gl_FragColor = ',\n 'c11 * m[0] + c12 * m[1] + c22 * m[2] +',\n 'c21 * m[3] + c22 * m[4] + c23 * m[5] +',\n 'c31 * m[6] + c32 * m[7] + c33 * m[8];',\n 'gl_FragColor.a = c22.a;',\n '}',\n ].join('\\n');\n\n _filter.detectEdges = function () {\n _filter.convolution.call(this, [\n 0, 1, 0,\n 1, -4, 1,\n 0, 1, 0,\n ]);\n };\n\n _filter.sobelX = function () {\n _filter.convolution.call(this, [\n -1, 0, 1,\n -2, 0, 2,\n -1, 0, 1,\n ]);\n };\n\n _filter.sobelY = function () {\n _filter.convolution.call(this, [\n -1, -2, -1,\n 0, 0, 0,\n 1, 2, 1,\n ]);\n };\n\n _filter.sharpen = function (amount) {\n const a = amount || 1;\n _filter.convolution.call(this, [\n 0, -1 * a, 0,\n -1 * a, 1 + 4 * a, -1 * a,\n 0, -1 * a, 0,\n ]);\n };\n\n _filter.emboss = function (size) {\n const s = size || 1;\n _filter.convolution.call(this, [\n -2 * s, -1 * s, 0,\n -1 * s, 1, 1 * s,\n 0, 1 * s, 2 * s,\n ]);\n };\n\n // -------------------------------------------------------------------------\n // Blur Filter\n\n _filter.blur = function (size) {\n const blurSizeX = (size / 7) / _width;\n const blurSizeY = (size / 7) / _height;\n\n const program = _compileShader(_filter.blur.SHADER);\n\n // Vertical\n gl.uniform2f(program.uniform.px, 0, blurSizeY);\n _draw(DRAW.INTERMEDIATE);\n\n // Horizontal\n gl.uniform2f(program.uniform.px, blurSizeX, 0);\n _draw();\n };\n\n _filter.blur.SHADER = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform vec2 px;',\n\n 'void main(void) {',\n 'gl_FragColor = vec4(0.0);',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-7.0*px.x, -7.0*px.y))*0.0044299121055113265;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-6.0*px.x, -6.0*px.y))*0.00895781211794;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-5.0*px.x, -5.0*px.y))*0.0215963866053;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-4.0*px.x, -4.0*px.y))*0.0443683338718;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-3.0*px.x, -3.0*px.y))*0.0776744219933;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-2.0*px.x, -2.0*px.y))*0.115876621105;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-1.0*px.x, -1.0*px.y))*0.147308056121;',\n 'gl_FragColor += texture2D(texture, vUv )*0.159576912161;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 1.0*px.x, 1.0*px.y))*0.147308056121;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 2.0*px.x, 2.0*px.y))*0.115876621105;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 3.0*px.x, 3.0*px.y))*0.0776744219933;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 4.0*px.x, 4.0*px.y))*0.0443683338718;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 5.0*px.x, 5.0*px.y))*0.0215963866053;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 6.0*px.x, 6.0*px.y))*0.00895781211794;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 7.0*px.x, 7.0*px.y))*0.0044299121055113265;',\n '}',\n ].join('\\n');\n\n // -------------------------------------------------------------------------\n // Pixelate Filter\n\n _filter.pixelate = function (size) {\n const blurSizeX = (size) / _width;\n const blurSizeY = (size) / _height;\n\n const program = _compileShader(_filter.pixelate.SHADER);\n\n // Horizontal\n gl.uniform2f(program.uniform.size, blurSizeX, blurSizeY);\n _draw();\n };\n\n _filter.pixelate.SHADER = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform vec2 size;',\n 'uniform sampler2D texture;',\n\n 'vec2 pixelate(vec2 coord, vec2 size) {',\n 'return floor( coord / size ) * size;',\n '}',\n\n 'void main(void) {',\n 'gl_FragColor = vec4(0.0);',\n 'vec2 coord = pixelate(vUv, size);',\n 'gl_FragColor += texture2D(texture, coord);',\n '}',\n ].join('\\n');\n};\n\nexports.Canvas = WebGLImageFilter;\n", "/* eslint-disable indent */\n/* eslint-disable no-multi-spaces */\n\nexport default {\n backend: 'webgl', // select tfjs backend to use\n console: true, // enable debugging output to console\n scoped: false, // enable scoped runs\n // some models *may* have memory leaks, this wrapps everything in a local scope at a cost of performance\n // typically not needed\n videoOptimized: true, // perform additional optimizations when input is video, must be disabled for images\n filter: {\n enabled: true, // enable image pre-processing filters\n return: true, // return processed canvas imagedata in result\n brightness: 0, // range: -1 (darken) to 1 (lighten)\n contrast: 0, // range: -1 (reduce contrast) to 1 (increase contrast)\n sharpness: 0, // range: 0 (no sharpening) to 1 (maximum sharpening)\n blur: 0, // range: 0 (no blur) to N (blur radius in pixels)\n saturation: 0, // range: -1 (reduce saturation) to 1 (increase saturation)\n hue: 0, // range: 0 (no change) to 360 (hue rotation in degrees)\n negative: false, // image negative\n sepia: false, // image sepia colors\n vintage: false, // image vintage colors\n kodachrome: false, // image kodachrome colors\n technicolor: false, // image technicolor colors\n polaroid: false, // image polaroid camera effect\n pixelate: 0, // range: 0 (no pixelate) to N (number of pixels to pixelate)\n },\n face: {\n enabled: true, // controls if specified modul is enabled\n // face.enabled is required for all face models: detector, mesh, iris, age, gender, emotion\n // (note: module is not loaded until it is required)\n detector: {\n modelPath: '../models/blazeface/back/model.json', // can be 'front' or 'back'.\n // 'front' is optimized for large faces such as front-facing camera and 'back' is optimized for distanct faces.\n inputSize: 256, // fixed value: 128 for front and 256 for 'back'\n maxFaces: 10, // maximum number of faces detected in the input, should be set to the minimum number for performance\n skipFrames: 10, // how many frames to go without re-running the face bounding box detector, only used for video inputs\n // if model is running st 25 FPS, we can re-use existing bounding box for updated face mesh analysis\n // as face probably hasn't moved much in short time (10 * 1/25 = 0.25 sec)\n minConfidence: 0.5, // threshold for discarding a prediction\n iouThreshold: 0.3, // threshold for deciding whether boxes overlap too much in non-maximum suppression\n scoreThreshold: 0.7, // threshold for deciding when to remove boxes based on score in non-maximum suppression\n },\n mesh: {\n enabled: true,\n modelPath: '../models/facemesh/model.json',\n inputSize: 192, // fixed value\n },\n iris: {\n enabled: true,\n modelPath: '../models/iris/model.json',\n enlargeFactor: 2.3, // empiric tuning\n inputSize: 64, // fixed value\n },\n age: {\n enabled: true,\n modelPath: '../models/ssrnet-age/imdb/model.json', // can be 'imdb' or 'wiki'\n // which determines training set for model\n inputSize: 64, // fixed value\n skipFrames: 10, // how many frames to go without re-running the detector, only used for video inputs\n },\n gender: {\n enabled: true,\n minConfidence: 0.8, // threshold for discarding a prediction\n modelPath: '../models/ssrnet-gender/imdb/model.json',\n },\n emotion: {\n enabled: true,\n inputSize: 64, // fixed value\n minConfidence: 0.5, // threshold for discarding a prediction\n skipFrames: 10, // how many frames to go without re-running the detector\n modelPath: '../models/emotion/model.json',\n },\n },\n body: {\n enabled: true,\n modelPath: '../models/posenet/model.json',\n inputResolution: 257, // fixed value\n outputStride: 16, // fixed value\n maxDetections: 10, // maximum number of people detected in the input, should be set to the minimum number for performance\n scoreThreshold: 0.7, // threshold for deciding when to remove boxes based on score in non-maximum suppression\n nmsRadius: 20, // radius for deciding points are too close in non-maximum suppression\n },\n hand: {\n enabled: true,\n inputSize: 256, // fixed value\n skipFrames: 10, // how many frames to go without re-running the hand bounding box detector, only used for video inputs\n // if model is running st 25 FPS, we can re-use existing bounding box for updated hand skeleton analysis\n // as the hand probably hasn't moved much in short time (10 * 1/25 = 0.25 sec)\n minConfidence: 0.5, // threshold for discarding a prediction\n iouThreshold: 0.3, // threshold for deciding whether boxes overlap too much in non-maximum suppression\n scoreThreshold: 0.7, // threshold for deciding when to remove boxes based on score in non-maximum suppression\n enlargeFactor: 1.65, // empiric tuning as skeleton prediction prefers hand box with some whitespace\n maxHands: 10, // maximum number of hands detected in the input, should be set to the minimum number for performance\n detector: {\n anchors: '../models/handdetect/anchors.json',\n modelPath: '../models/handdetect/model.json',\n },\n skeleton: {\n modelPath: '../models/handskeleton/model.json',\n },\n },\n};\n", "const tf = require('@tensorflow/tfjs');\nconst facemesh = require('./facemesh/facemesh.js');\nconst ssrnet = require('./ssrnet/ssrnet.js');\nconst emotion = require('./emotion/emotion.js');\nconst posenet = require('./posenet/posenet.js');\nconst handpose = require('./handpose/handpose.js');\nconst fxImage = require('./imagefx.js');\nconst defaults = require('../config.js').default;\nconst app = require('../package.json');\n\n// static config override for non-video detection\nconst override = {\n face: { detector: { skipFrames: 0 }, age: { skipFrames: 0 }, emotion: { skipFrames: 0 } },\n hand: { skipFrames: 0 },\n};\n\n// helper function: gets elapsed time on both browser and nodejs\nconst now = () => {\n if (typeof performance !== 'undefined') return performance.now();\n return parseInt(Number(process.hrtime.bigint()) / 1000 / 1000);\n};\n\n// helper function: perform deep merge of multiple objects so it allows full inheriance with overrides\nfunction mergeDeep(...objects) {\n const isObject = (obj) => obj && typeof obj === 'object';\n return objects.reduce((prev, obj) => {\n Object.keys(obj || {}).forEach((key) => {\n const pVal = prev[key];\n const oVal = obj[key];\n if (Array.isArray(pVal) && Array.isArray(oVal)) {\n prev[key] = pVal.concat(...oVal);\n } else if (isObject(pVal) && isObject(oVal)) {\n prev[key] = mergeDeep(pVal, oVal);\n } else {\n prev[key] = oVal;\n }\n });\n return prev;\n }, {});\n}\n\nfunction sanity(input) {\n if (!input) return 'input is not defined';\n if (tf.ENV.flags.IS_NODE && !(input instanceof tf.Tensor)) {\n return 'input must be a tensor';\n }\n try {\n tf.getBackend();\n } catch {\n return 'backend not loaded';\n }\n return null;\n}\n\nclass Human {\n constructor() {\n this.tf = tf;\n this.version = app.version;\n this.defaults = defaults;\n this.config = defaults;\n this.fx = (tf.ENV.flags.IS_BROWSER && (typeof document !== 'undefined')) ? new fxImage.Canvas() : null;\n this.state = 'idle';\n this.numTensors = 0;\n this.analyzeMemoryLeaks = false;\n // object that contains all initialized models\n this.models = {\n facemesh: null,\n posenet: null,\n handpose: null,\n iris: null,\n age: null,\n gender: null,\n emotion: null,\n };\n // export raw access to underlying models\n this.facemesh = facemesh;\n this.ssrnet = ssrnet;\n this.emotion = emotion;\n this.posenet = posenet;\n this.handpose = handpose;\n }\n\n // helper function: wrapper around console output\n log(...msg) {\n // eslint-disable-next-line no-console\n if (msg && this.config.console) console.log(...msg);\n }\n\n // helper function: measure tensor leak\n analyze(...msg) {\n if (!this.analyzeMemoryLeaks) return;\n const current = tf.engine().state.numTensors;\n const previous = this.numTensors;\n this.numTensors = current;\n const leaked = current - previous;\n if (leaked !== 0) this.log(...msg, leaked);\n }\n\n async load(userConfig) {\n if (userConfig) this.config = mergeDeep(defaults, userConfig);\n if (this.config.face.enabled && !this.models.facemesh) {\n this.log('Load model: Face');\n this.models.facemesh = await facemesh.load(this.config.face);\n }\n if (this.config.body.enabled && !this.models.posenet) {\n this.log('Load model: Body');\n this.models.posenet = await posenet.load(this.config.body);\n }\n if (this.config.hand.enabled && !this.models.handpose) {\n this.log('Load model: Hand');\n this.models.handpose = await handpose.load(this.config.hand);\n }\n if (this.config.face.enabled && this.config.face.age.enabled && !this.models.age) {\n this.log('Load model: Age');\n this.models.age = await ssrnet.loadAge(this.config);\n }\n if (this.config.face.enabled && this.config.face.gender.enabled && !this.models.gender) {\n this.log('Load model: Gender');\n this.models.gender = await ssrnet.loadGender(this.config);\n }\n if (this.config.face.enabled && this.config.face.emotion.enabled && !this.models.emotion) {\n this.log('Load model: Emotion');\n this.models.emotion = await emotion.load(this.config);\n }\n }\n\n tfImage(input) {\n // let imageData;\n let filtered;\n if (this.fx && this.config.filter.enabled && !(input instanceof tf.Tensor)) {\n const width = input.naturalWidth || input.videoWidth || input.width || (input.shape && (input.shape[1] > 0));\n const height = input.naturalHeight || input.videoHeight || input.height || (input.shape && (input.shape[2] > 0));\n const offscreenCanvas = new OffscreenCanvas(width, height);\n const ctx = offscreenCanvas.getContext('2d');\n if (input instanceof ImageData) ctx.putImageData(input, 0, 0);\n else ctx.drawImage(input, 0, 0, width, height, 0, 0, offscreenCanvas.width, offscreenCanvas.height);\n this.fx.reset();\n this.fx.addFilter('brightness', this.config.filter.brightness); // must have at least one filter enabled\n if (this.config.filter.contrast !== 0) this.fx.addFilter('contrast', this.config.filter.contrast);\n if (this.config.filter.sharpness !== 0) this.fx.addFilter('sharpen', this.config.filter.sharpness);\n if (this.config.filter.blur !== 0) this.fx.addFilter('blur', this.config.filter.blur);\n if (this.config.filter.saturation !== 0) this.fx.addFilter('saturation', this.config.filter.saturation);\n if (this.config.filter.hue !== 0) this.fx.addFilter('hue', this.config.filter.hue);\n if (this.config.filter.negative) this.fx.addFilter('negative');\n if (this.config.filter.sepia) this.fx.addFilter('sepia');\n if (this.config.filter.vintage) this.fx.addFilter('brownie');\n if (this.config.filter.sepia) this.fx.addFilter('sepia');\n if (this.config.filter.kodachrome) this.fx.addFilter('kodachrome');\n if (this.config.filter.technicolor) this.fx.addFilter('technicolor');\n if (this.config.filter.polaroid) this.fx.addFilter('polaroid');\n if (this.config.filter.pixelate !== 0) this.fx.addFilter('pixelate', this.config.filter.pixelate);\n filtered = this.fx.apply(offscreenCanvas);\n }\n let tensor;\n if (input instanceof tf.Tensor) {\n tensor = tf.clone(input);\n } else {\n const pixels = tf.browser.fromPixels(filtered || input);\n const casted = pixels.toFloat();\n tensor = casted.expandDims(0);\n pixels.dispose();\n casted.dispose();\n }\n return { tensor, canvas: this.config.filter.return ? filtered : null };\n }\n\n async detect(input, userConfig = {}) {\n this.state = 'config';\n const perf = {};\n let timeStamp;\n\n timeStamp = now();\n this.config = mergeDeep(defaults, userConfig);\n if (!this.config.videoOptimized) this.config = mergeDeep(this.config, override);\n perf.config = Math.trunc(now() - timeStamp);\n\n // sanity checks\n timeStamp = now();\n this.state = 'check';\n const error = sanity(input);\n if (error) {\n this.log(error, input);\n return { error };\n }\n perf.sanity = Math.trunc(now() - timeStamp);\n\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve) => {\n const timeStart = now();\n\n // configure backend\n timeStamp = now();\n if (tf.getBackend() !== this.config.backend) {\n this.state = 'backend';\n this.log('Human library setting backend:', this.config.backend);\n await tf.setBackend(this.config.backend);\n await tf.ready();\n }\n perf.backend = Math.trunc(now() - timeStamp);\n\n // check number of loaded models\n const loadedModels = Object.values(this.models).filter((a) => a).length;\n if (loadedModels === 0) {\n this.log('Human library starting');\n this.log('Configuration:', this.config);\n this.log('Flags:', tf.ENV.flags);\n }\n\n // load models if enabled\n timeStamp = now();\n this.state = 'load';\n await this.load();\n perf.load = Math.trunc(now() - timeStamp);\n\n if (this.config.scoped) tf.engine().startScope();\n\n this.analyze('Start Detect:');\n\n timeStamp = now();\n const image = this.tfImage(input);\n perf.image = Math.trunc(now() - timeStamp);\n const imageTensor = image.tensor;\n\n // run posenet\n this.state = 'run:body';\n timeStamp = now();\n this.analyze('Start PoseNet');\n const poseRes = this.config.body.enabled ? await this.models.posenet.estimatePoses(imageTensor, this.config.body) : [];\n this.analyze('End PoseNet:');\n perf.body = Math.trunc(now() - timeStamp);\n\n // run handpose\n this.state = 'run:hand';\n timeStamp = now();\n this.analyze('Start HandPose:');\n const handRes = this.config.hand.enabled ? await this.models.handpose.estimateHands(imageTensor, this.config.hand) : [];\n this.analyze('End HandPose:');\n perf.hand = Math.trunc(now() - timeStamp);\n\n // run facemesh, includes blazeface and iris\n const faceRes = [];\n if (this.config.face.enabled) {\n this.state = 'run:face';\n timeStamp = now();\n this.analyze('Start FaceMesh:');\n const faces = await this.models.facemesh.estimateFaces(imageTensor, this.config.face);\n perf.face = Math.trunc(now() - timeStamp);\n for (const face of faces) {\n // is something went wrong, skip the face\n if (!face.image || face.image.isDisposedInternal) {\n this.log('face object is disposed:', face.image);\n continue;\n }\n // run ssr-net age & gender, inherits face from blazeface\n this.state = 'run:agegender';\n timeStamp = now();\n const ssrData = (this.config.face.age.enabled || this.config.face.gender.enabled) ? await ssrnet.predict(face.image, this.config) : {};\n perf.agegender = Math.trunc(now() - timeStamp);\n // run emotion, inherits face from blazeface\n this.state = 'run:emotion';\n timeStamp = now();\n const emotionData = this.config.face.emotion.enabled ? await emotion.predict(face.image, this.config) : {};\n perf.emotion = Math.trunc(now() - timeStamp);\n\n // dont need face anymore\n face.image.dispose();\n // calculate iris distance\n // iris: array[ bottom, left, top, right, center ]\n const iris = (face.annotations.leftEyeIris && face.annotations.rightEyeIris)\n ? Math.max(face.annotations.leftEyeIris[3][0] - face.annotations.leftEyeIris[1][0], face.annotations.rightEyeIris[3][0] - face.annotations.rightEyeIris[1][0])\n : 0;\n faceRes.push({\n confidence: face.confidence,\n box: face.box,\n mesh: face.mesh,\n annotations: face.annotations,\n age: ssrData.age,\n gender: ssrData.gender,\n agConfidence: ssrData.confidence,\n emotion: emotionData,\n iris: (iris !== 0) ? Math.trunc(100 * 11.7 /* human iris size in mm */ / iris) / 100 : 0,\n });\n this.analyze('End FaceMesh:');\n }\n }\n\n imageTensor.dispose();\n this.state = 'idle';\n\n if (this.config.scoped) tf.engine().endScope();\n this.analyze('End Scope:');\n\n perf.total = Math.trunc(now() - timeStart);\n resolve({ face: faceRes, body: poseRes, hand: handRes, performance: perf, canvas: image.canvas });\n });\n }\n}\n\nexport { Human as default };\n", "const tf = require('@tensorflow/tfjs');\nconst facemesh = require('./facemesh/facemesh.js');\nconst ssrnet = require('./ssrnet/ssrnet.js');\nconst emotion = require('./emotion/emotion.js');\nconst posenet = require('./posenet/posenet.js');\nconst handpose = require('./handpose/handpose.js');\nconst fxImage = require('./imagefx.js');\nconst defaults = require('../config.js').default;\nconst app = require('../package.json');\n\n// static config override for non-video detection\nconst override = {\n face: { detector: { skipFrames: 0 }, age: { skipFrames: 0 }, emotion: { skipFrames: 0 } },\n hand: { skipFrames: 0 },\n};\n\n// helper function: gets elapsed time on both browser and nodejs\nconst now = () => {\n if (typeof performance !== 'undefined') return performance.now();\n return parseInt(Number(process.hrtime.bigint()) / 1000 / 1000);\n};\n\n// helper function: perform deep merge of multiple objects so it allows full inheriance with overrides\nfunction mergeDeep(...objects) {\n const isObject = (obj) => obj && typeof obj === 'object';\n return objects.reduce((prev, obj) => {\n Object.keys(obj || {}).forEach((key) => {\n const pVal = prev[key];\n const oVal = obj[key];\n if (Array.isArray(pVal) && Array.isArray(oVal)) {\n prev[key] = pVal.concat(...oVal);\n } else if (isObject(pVal) && isObject(oVal)) {\n prev[key] = mergeDeep(pVal, oVal);\n } else {\n prev[key] = oVal;\n }\n });\n return prev;\n }, {});\n}\n\nfunction sanity(input) {\n if (!input) return 'input is not defined';\n if (tf.ENV.flags.IS_NODE && !(input instanceof tf.Tensor)) {\n return 'input must be a tensor';\n }\n try {\n tf.getBackend();\n } catch {\n return 'backend not loaded';\n }\n return null;\n}\n\nclass Human {\n constructor() {\n this.tf = tf;\n this.version = app.version;\n this.defaults = defaults;\n this.config = defaults;\n this.fx = (tf.ENV.flags.IS_BROWSER && (typeof document !== 'undefined')) ? new fxImage.Canvas() : null;\n this.state = 'idle';\n this.numTensors = 0;\n this.analyzeMemoryLeaks = false;\n // object that contains all initialized models\n this.models = {\n facemesh: null,\n posenet: null,\n handpose: null,\n iris: null,\n age: null,\n gender: null,\n emotion: null,\n };\n // export raw access to underlying models\n this.facemesh = facemesh;\n this.ssrnet = ssrnet;\n this.emotion = emotion;\n this.posenet = posenet;\n this.handpose = handpose;\n }\n\n // helper function: wrapper around console output\n log(...msg) {\n // eslint-disable-next-line no-console\n if (msg && this.config.console) console.log(...msg);\n }\n\n // helper function: measure tensor leak\n analyze(...msg) {\n if (!this.analyzeMemoryLeaks) return;\n const current = tf.engine().state.numTensors;\n const previous = this.numTensors;\n this.numTensors = current;\n const leaked = current - previous;\n if (leaked !== 0) this.log(...msg, leaked);\n }\n\n async load(userConfig) {\n if (userConfig) this.config = mergeDeep(defaults, userConfig);\n if (this.config.face.enabled && !this.models.facemesh) {\n this.log('Load model: Face');\n this.models.facemesh = await facemesh.load(this.config.face);\n }\n if (this.config.body.enabled && !this.models.posenet) {\n this.log('Load model: Body');\n this.models.posenet = await posenet.load(this.config.body);\n }\n if (this.config.hand.enabled && !this.models.handpose) {\n this.log('Load model: Hand');\n this.models.handpose = await handpose.load(this.config.hand);\n }\n if (this.config.face.enabled && this.config.face.age.enabled && !this.models.age) {\n this.log('Load model: Age');\n this.models.age = await ssrnet.loadAge(this.config);\n }\n if (this.config.face.enabled && this.config.face.gender.enabled && !this.models.gender) {\n this.log('Load model: Gender');\n this.models.gender = await ssrnet.loadGender(this.config);\n }\n if (this.config.face.enabled && this.config.face.emotion.enabled && !this.models.emotion) {\n this.log('Load model: Emotion');\n this.models.emotion = await emotion.load(this.config);\n }\n }\n\n tfImage(input) {\n // let imageData;\n let filtered;\n if (this.fx && this.config.filter.enabled && !(input instanceof tf.Tensor)) {\n const width = input.naturalWidth || input.videoWidth || input.width || (input.shape && (input.shape[1] > 0));\n const height = input.naturalHeight || input.videoHeight || input.height || (input.shape && (input.shape[2] > 0));\n const offscreenCanvas = new OffscreenCanvas(width, height);\n const ctx = offscreenCanvas.getContext('2d');\n if (input instanceof ImageData) ctx.putImageData(input, 0, 0);\n else ctx.drawImage(input, 0, 0, width, height, 0, 0, offscreenCanvas.width, offscreenCanvas.height);\n this.fx.reset();\n this.fx.addFilter('brightness', this.config.filter.brightness); // must have at least one filter enabled\n if (this.config.filter.contrast !== 0) this.fx.addFilter('contrast', this.config.filter.contrast);\n if (this.config.filter.sharpness !== 0) this.fx.addFilter('sharpen', this.config.filter.sharpness);\n if (this.config.filter.blur !== 0) this.fx.addFilter('blur', this.config.filter.blur);\n if (this.config.filter.saturation !== 0) this.fx.addFilter('saturation', this.config.filter.saturation);\n if (this.config.filter.hue !== 0) this.fx.addFilter('hue', this.config.filter.hue);\n if (this.config.filter.negative) this.fx.addFilter('negative');\n if (this.config.filter.sepia) this.fx.addFilter('sepia');\n if (this.config.filter.vintage) this.fx.addFilter('brownie');\n if (this.config.filter.sepia) this.fx.addFilter('sepia');\n if (this.config.filter.kodachrome) this.fx.addFilter('kodachrome');\n if (this.config.filter.technicolor) this.fx.addFilter('technicolor');\n if (this.config.filter.polaroid) this.fx.addFilter('polaroid');\n if (this.config.filter.pixelate !== 0) this.fx.addFilter('pixelate', this.config.filter.pixelate);\n filtered = this.fx.apply(offscreenCanvas);\n }\n let tensor;\n if (input instanceof tf.Tensor) {\n tensor = tf.clone(input);\n } else {\n const pixels = tf.browser.fromPixels(filtered || input);\n const casted = pixels.toFloat();\n tensor = casted.expandDims(0);\n pixels.dispose();\n casted.dispose();\n }\n return { tensor, canvas: this.config.filter.return ? filtered : null };\n }\n\n async detect(input, userConfig = {}) {\n this.state = 'config';\n const perf = {};\n let timeStamp;\n\n timeStamp = now();\n this.config = mergeDeep(defaults, userConfig);\n if (!this.config.videoOptimized) this.config = mergeDeep(this.config, override);\n perf.config = Math.trunc(now() - timeStamp);\n\n // sanity checks\n timeStamp = now();\n this.state = 'check';\n const error = sanity(input);\n if (error) {\n this.log(error, input);\n return { error };\n }\n perf.sanity = Math.trunc(now() - timeStamp);\n\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve) => {\n const timeStart = now();\n\n // configure backend\n timeStamp = now();\n if (tf.getBackend() !== this.config.backend) {\n this.state = 'backend';\n this.log('Human library setting backend:', this.config.backend);\n await tf.setBackend(this.config.backend);\n await tf.ready();\n }\n perf.backend = Math.trunc(now() - timeStamp);\n\n // check number of loaded models\n const loadedModels = Object.values(this.models).filter((a) => a).length;\n if (loadedModels === 0) {\n this.log('Human library starting');\n this.log('Configuration:', this.config);\n this.log('Flags:', tf.ENV.flags);\n }\n\n // load models if enabled\n timeStamp = now();\n this.state = 'load';\n await this.load();\n perf.load = Math.trunc(now() - timeStamp);\n\n if (this.config.scoped) tf.engine().startScope();\n\n this.analyze('Start Detect:');\n\n timeStamp = now();\n const image = this.tfImage(input);\n perf.image = Math.trunc(now() - timeStamp);\n const imageTensor = image.tensor;\n\n // run posenet\n this.state = 'run:body';\n timeStamp = now();\n this.analyze('Start PoseNet');\n const poseRes = this.config.body.enabled ? await this.models.posenet.estimatePoses(imageTensor, this.config.body) : [];\n this.analyze('End PoseNet:');\n perf.body = Math.trunc(now() - timeStamp);\n\n // run handpose\n this.state = 'run:hand';\n timeStamp = now();\n this.analyze('Start HandPose:');\n const handRes = this.config.hand.enabled ? await this.models.handpose.estimateHands(imageTensor, this.config.hand) : [];\n this.analyze('End HandPose:');\n perf.hand = Math.trunc(now() - timeStamp);\n\n // run facemesh, includes blazeface and iris\n const faceRes = [];\n if (this.config.face.enabled) {\n this.state = 'run:face';\n timeStamp = now();\n this.analyze('Start FaceMesh:');\n const faces = await this.models.facemesh.estimateFaces(imageTensor, this.config.face);\n perf.face = Math.trunc(now() - timeStamp);\n for (const face of faces) {\n // is something went wrong, skip the face\n if (!face.image || face.image.isDisposedInternal) {\n this.log('face object is disposed:', face.image);\n continue;\n }\n // run ssr-net age & gender, inherits face from blazeface\n this.state = 'run:agegender';\n timeStamp = now();\n const ssrData = (this.config.face.age.enabled || this.config.face.gender.enabled) ? await ssrnet.predict(face.image, this.config) : {};\n perf.agegender = Math.trunc(now() - timeStamp);\n // run emotion, inherits face from blazeface\n this.state = 'run:emotion';\n timeStamp = now();\n const emotionData = this.config.face.emotion.enabled ? await emotion.predict(face.image, this.config) : {};\n perf.emotion = Math.trunc(now() - timeStamp);\n\n // dont need face anymore\n face.image.dispose();\n // calculate iris distance\n // iris: array[ bottom, left, top, right, center ]\n const iris = (face.annotations.leftEyeIris && face.annotations.rightEyeIris)\n ? Math.max(face.annotations.leftEyeIris[3][0] - face.annotations.leftEyeIris[1][0], face.annotations.rightEyeIris[3][0] - face.annotations.rightEyeIris[1][0])\n : 0;\n faceRes.push({\n confidence: face.confidence,\n box: face.box,\n mesh: face.mesh,\n annotations: face.annotations,\n age: ssrData.age,\n gender: ssrData.gender,\n agConfidence: ssrData.confidence,\n emotion: emotionData,\n iris: (iris !== 0) ? Math.trunc(100 * 11.7 /* human iris size in mm */ / iris) / 100 : 0,\n });\n this.analyze('End FaceMesh:');\n }\n }\n\n imageTensor.dispose();\n this.state = 'idle';\n\n if (this.config.scoped) tf.engine().endScope();\n this.analyze('End Scope:');\n\n perf.total = Math.trunc(now() - timeStart);\n resolve({ face: faceRes, body: poseRes, hand: handRes, performance: perf, canvas: image.canvas });\n });\n }\n}\n\nexport { Human as default };\n"], - "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA,QAAM,MAAK;AAEX,QAAM,gBAAgB;AAEtB,2BAAyB;AACvB,UAAM,OAAO,CAAE,SAAS,CAAC,YAAY,IAAI,YAAY,IAAI,SAAS,CAAC,GAAG;AACtE,UAAM,UAAU;AAChB,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,QAAQ;AACvC,YAAM,SAAS,KAAK,QAAQ;AAC5B,YAAM,WAAW,KAAK,MAAO,aAAY,SAAS,KAAK;AACvD,YAAM,WAAW,KAAK,MAAO,aAAY,SAAS,KAAK;AACvD,YAAM,aAAa,KAAK,QAAQ;AAChC,eAAS,QAAQ,GAAG,QAAQ,UAAU;AACpC,cAAM,UAAU,SAAU,SAAQ;AAClC,iBAAS,QAAQ,GAAG,QAAQ,UAAU;AACpC,gBAAM,UAAU,SAAU,SAAQ;AAClC,mBAAS,IAAI,GAAG,IAAI,YAAY;AAC9B,oBAAQ,KAAK,CAAC,SAAS;AAAA;AAAA;AAAA;AAAA;AAK/B,WAAO;AAAA;AAGT,QAAM,aAAa,CAAC;AAClB,QAAI,eAAe;AACnB,QAAI,WAAW;AACf,QAAI,SAAS;AAAA;AAGf,QAAM,YAAY,CAAC,mBAAoB;AAAA,IACrC;AAAA,IACA,YAAY,IAAG,MAAM,gBAAgB,CAAC,GAAG,IAAI,CAAC,IAAI;AAAA,IAClD,UAAU,IAAG,MAAM,gBAAgB,CAAC,GAAG,IAAI,CAAC,IAAI;AAAA;AAGlD,QAAM,WAAW,CAAC,KAAK;AACrB,UAAM,SA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AY;AACZ,WAAK,QAAQ;AAEb,UAAI,KAAK,OAAO;AAAQ,WAAG,SAAS;AACpC,WAAK,QAAQ;AAEb,WAAK,QAAQ,KAAK,MAAM,QAAQ;AAChC,cAAQ,CAAE,MAAM,SAAS,MAAM,SAAS,MAAM,SAAS,aAAa,MAAM,QAAQ,MAAM;AAAA;AAAA;AAAA;", + "sourcesContent": ["const tf = require('@tensorflow/tfjs');\n\nconst NUM_LANDMARKS = 6;\n\nfunction generateAnchors(inputSize) {\n const spec = { strides: [inputSize / 16, inputSize / 8], anchors: [2, 6] };\n const anchors = [];\n for (let i = 0; i < spec.strides.length; i++) {\n const stride = spec.strides[i];\n const gridRows = Math.floor((inputSize + stride - 1) / stride);\n const gridCols = Math.floor((inputSize + stride - 1) / stride);\n const anchorsNum = spec.anchors[i];\n for (let gridY = 0; gridY < gridRows; gridY++) {\n const anchorY = stride * (gridY + 0.5);\n for (let gridX = 0; gridX < gridCols; gridX++) {\n const anchorX = stride * (gridX + 0.5);\n for (let n = 0; n < anchorsNum; n++) {\n anchors.push([anchorX, anchorY]);\n }\n }\n }\n }\n return anchors;\n}\n\nconst disposeBox = (box) => {\n box.startEndTensor.dispose();\n box.startPoint.dispose();\n box.endPoint.dispose();\n};\n\nconst createBox = (startEndTensor) => ({\n startEndTensor,\n startPoint: tf.slice(startEndTensor, [0, 0], [-1, 2]),\n endPoint: tf.slice(startEndTensor, [0, 2], [-1, 2]),\n});\n\nconst scaleBox = (box, factors) => {\n const starts = tf.mul(box.startPoint, factors);\n const ends = tf.mul(box.endPoint, factors);\n const newCoordinates = tf.concat2d([starts, ends], 1);\n return createBox(newCoordinates);\n};\n\nfunction decodeBounds(boxOutputs, anchors, inputSize) {\n const boxStarts = tf.slice(boxOutputs, [0, 1], [-1, 2]);\n const centers = tf.add(boxStarts, anchors);\n const boxSizes = tf.slice(boxOutputs, [0, 3], [-1, 2]);\n const boxSizesNormalized = tf.div(boxSizes, inputSize);\n const centersNormalized = tf.div(centers, inputSize);\n const halfBoxSize = tf.div(boxSizesNormalized, 2);\n const starts = tf.sub(centersNormalized, halfBoxSize);\n const ends = tf.add(centersNormalized, halfBoxSize);\n const startNormalized = tf.mul(starts, inputSize);\n const endNormalized = tf.mul(ends, inputSize);\n const concatAxis = 1;\n return tf.concat2d([startNormalized, endNormalized], concatAxis);\n}\n\nfunction scaleBoxFromPrediction(face, scaleFactor) {\n return tf.tidy(() => {\n const box = face['box'] ? face['box'] : face;\n return scaleBox(box, scaleFactor).startEndTensor.squeeze();\n });\n}\n\nclass BlazeFaceModel {\n constructor(model, config) {\n this.blazeFaceModel = model;\n this.width = config.detector.inputSize;\n this.height = config.detector.inputSize;\n this.maxFaces = config.detector.maxFaces;\n this.anchorsData = generateAnchors(config.detector.inputSize);\n this.anchors = tf.tensor2d(this.anchorsData);\n this.inputSize = tf.tensor1d([this.width, this.height]);\n this.iouThreshold = config.detector.iouThreshold;\n this.scaleFaces = 0.8;\n this.scoreThreshold = config.detector.scoreThreshold;\n }\n\n // toto blazeface leaks two tensors per run\n async getBoundingBoxes(inputImage) {\n // sanity check on input\n if ((!inputImage) || (inputImage.isDisposedInternal) || (inputImage.shape.length !== 4) || (inputImage.shape[1] < 1) || (inputImage.shape[2] < 1)) return null;\n const [detectedOutputs, boxes, scores] = tf.tidy(() => {\n const resizedImage = inputImage.resizeBilinear([this.width, this.height]);\n const normalizedImage = tf.mul(tf.sub(resizedImage.div(255), 0.5), 2);\n const batchedPrediction = this.blazeFaceModel.predict(normalizedImage);\n let prediction;\n // are we using tfhub or pinto converted model?\n if (Array.isArray(batchedPrediction)) {\n const sorted = batchedPrediction.sort((a, b) => a.size - b.size);\n const concat384 = tf.concat([sorted[0], sorted[2]], 2); // dim: 384, 1 + 16\n const concat512 = tf.concat([sorted[1], sorted[3]], 2); // dim: 512, 1 + 16\n const concat = tf.concat([concat512, concat384], 1);\n prediction = concat.squeeze(0);\n } else {\n prediction = batchedPrediction.squeeze(); // when using tfhub model\n }\n const decodedBounds = decodeBounds(prediction, this.anchors, this.inputSize);\n const logits = tf.slice(prediction, [0, 0], [-1, 1]);\n const scoresOut = tf.sigmoid(logits).squeeze();\n return [prediction, decodedBounds, scoresOut];\n });\n const boxIndicesTensor = await tf.image.nonMaxSuppressionAsync(boxes, scores, this.maxFaces, this.iouThreshold, this.scoreThreshold);\n const boxIndices = await boxIndicesTensor.array();\n boxIndicesTensor.dispose();\n const boundingBoxesMap = boxIndices.map((boxIndex) => tf.slice(boxes, [boxIndex, 0], [1, -1]));\n const boundingBoxes = await Promise.all(boundingBoxesMap.map(async (boundingBox) => {\n const vals = await boundingBox.array();\n boundingBox.dispose();\n return vals;\n }));\n const annotatedBoxes = [];\n for (let i = 0; i < boundingBoxes.length; i++) {\n const boundingBox = boundingBoxes[i];\n const box = createBox(boundingBox);\n const boxIndex = boxIndices[i];\n const anchor = this.anchorsData[boxIndex];\n const sliced = tf.slice(detectedOutputs, [boxIndex, NUM_LANDMARKS - 1], [1, -1]);\n const squeezed = sliced.squeeze();\n const landmarks = squeezed.reshape([NUM_LANDMARKS, -1]);\n /*\n const landmarks = tf\n .slice(detectedOutputs, [boxIndex, NUM_LANDMARKS - 1], [1, -1])\n .squeeze()\n .reshape([NUM_LANDMARKS, -1]);\n */\n const probability = tf.slice(scores, [boxIndex], [1]);\n const annotatedBox = { box, landmarks, probability, anchor };\n annotatedBoxes.push(annotatedBox);\n sliced.dispose();\n squeezed.dispose();\n // landmarks.dispose();\n }\n detectedOutputs.dispose();\n boxes.dispose();\n scores.dispose();\n detectedOutputs.dispose();\n return {\n boxes: annotatedBoxes,\n scaleFactor: [inputImage.shape[2] / this.width, inputImage.shape[1] / this.height],\n };\n }\n\n async estimateFaces(input) {\n const { boxes, scaleFactor } = await this.getBoundingBoxes(input);\n return Promise.all(boxes.map(async (face) => {\n const scaledBox = scaleBoxFromPrediction(face, scaleFactor);\n const [landmarkData, boxData, probabilityData] = await Promise.all([face.landmarks, scaledBox, face.probability].map(async (d) => d.array()));\n const anchor = face.anchor;\n const [scaleFactorX, scaleFactorY] = scaleFactor;\n const scaledLandmarks = landmarkData\n .map((landmark) => ([\n (landmark[0] + anchor[0]) * scaleFactorX,\n (landmark[1] + anchor[1]) * scaleFactorY,\n ]));\n const normalizedFace = {\n topLeft: boxData.slice(0, 2),\n bottomRight: boxData.slice(2),\n landmarks: scaledLandmarks,\n probability: probabilityData,\n };\n disposeBox(face.box);\n face.landmarks.dispose();\n face.probability.dispose();\n scaledBox.dispose();\n return normalizedFace;\n }));\n }\n}\n\nasync function load(config) {\n const blazeface = await tf.loadGraphModel(config.detector.modelPath, { fromTFHub: config.detector.modelPath.includes('tfhub.dev') });\n const model = new BlazeFaceModel(blazeface, config);\n return model;\n}\n\nexports.load = load;\nexports.BlazeFaceModel = BlazeFaceModel;\nexports.disposeBox = disposeBox;\n", "exports.MESH_ANNOTATIONS = {\n silhouette: [\n 10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288,\n 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136,\n 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109,\n ],\n lipsUpperOuter: [61, 185, 40, 39, 37, 0, 267, 269, 270, 409, 291],\n lipsLowerOuter: [146, 91, 181, 84, 17, 314, 405, 321, 375, 291],\n lipsUpperInner: [78, 191, 80, 81, 82, 13, 312, 311, 310, 415, 308],\n lipsLowerInner: [78, 95, 88, 178, 87, 14, 317, 402, 318, 324, 308],\n rightEyeUpper0: [246, 161, 160, 159, 158, 157, 173],\n rightEyeLower0: [33, 7, 163, 144, 145, 153, 154, 155, 133],\n rightEyeUpper1: [247, 30, 29, 27, 28, 56, 190],\n rightEyeLower1: [130, 25, 110, 24, 23, 22, 26, 112, 243],\n rightEyeUpper2: [113, 225, 224, 223, 222, 221, 189],\n rightEyeLower2: [226, 31, 228, 229, 230, 231, 232, 233, 244],\n rightEyeLower3: [143, 111, 117, 118, 119, 120, 121, 128, 245],\n rightEyebrowUpper: [156, 70, 63, 105, 66, 107, 55, 193],\n rightEyebrowLower: [35, 124, 46, 53, 52, 65],\n rightEyeIris: [473, 474, 475, 476, 477],\n leftEyeUpper0: [466, 388, 387, 386, 385, 384, 398],\n leftEyeLower0: [263, 249, 390, 373, 374, 380, 381, 382, 362],\n leftEyeUpper1: [467, 260, 259, 257, 258, 286, 414],\n leftEyeLower1: [359, 255, 339, 254, 253, 252, 256, 341, 463],\n leftEyeUpper2: [342, 445, 444, 443, 442, 441, 413],\n leftEyeLower2: [446, 261, 448, 449, 450, 451, 452, 453, 464],\n leftEyeLower3: [372, 340, 346, 347, 348, 349, 350, 357, 465],\n leftEyebrowUpper: [383, 300, 293, 334, 296, 336, 285, 417],\n leftEyebrowLower: [265, 353, 276, 283, 282, 295],\n leftEyeIris: [468, 469, 470, 471, 472],\n midwayBetweenEyes: [168],\n noseTip: [1],\n noseBottom: [2],\n noseRightCorner: [98],\n noseLeftCorner: [327],\n rightCheek: [205],\n leftCheek: [425],\n};\nexports.MESH_TO_IRIS_INDICES_MAP = [ // A mapping from facemesh model keypoints to iris model keypoints.\n { key: 'EyeUpper0', indices: [9, 10, 11, 12, 13, 14, 15] },\n { key: 'EyeUpper1', indices: [25, 26, 27, 28, 29, 30, 31] },\n { key: 'EyeUpper2', indices: [41, 42, 43, 44, 45, 46, 47] },\n { key: 'EyeLower0', indices: [0, 1, 2, 3, 4, 5, 6, 7, 8] },\n { key: 'EyeLower1', indices: [16, 17, 18, 19, 20, 21, 22, 23, 24] },\n { key: 'EyeLower2', indices: [32, 33, 34, 35, 36, 37, 38, 39, 40] },\n { key: 'EyeLower3', indices: [54, 55, 56, 57, 58, 59, 60, 61, 62] },\n { key: 'EyebrowUpper', indices: [63, 64, 65, 66, 67, 68, 69, 70] },\n { key: 'EyebrowLower', indices: [48, 49, 50, 51, 52, 53] },\n];\n", "const tf = require('@tensorflow/tfjs');\n\nfunction scaleBoxCoordinates(box, factor) {\n const startPoint = [box.startPoint[0] * factor[0], box.startPoint[1] * factor[1]];\n const endPoint = [box.endPoint[0] * factor[0], box.endPoint[1] * factor[1]];\n return { startPoint, endPoint };\n}\nexports.scaleBoxCoordinates = scaleBoxCoordinates;\nfunction getBoxSize(box) {\n return [\n Math.abs(box.endPoint[0] - box.startPoint[0]),\n Math.abs(box.endPoint[1] - box.startPoint[1]),\n ];\n}\nexports.getBoxSize = getBoxSize;\nfunction getBoxCenter(box) {\n return [\n box.startPoint[0] + (box.endPoint[0] - box.startPoint[0]) / 2,\n box.startPoint[1] + (box.endPoint[1] - box.startPoint[1]) / 2,\n ];\n}\nexports.getBoxCenter = getBoxCenter;\nfunction cutBoxFromImageAndResize(box, image, cropSize) {\n const h = image.shape[1];\n const w = image.shape[2];\n const boxes = [[\n box.startPoint[1] / h, box.startPoint[0] / w, box.endPoint[1] / h,\n box.endPoint[0] / w,\n ]];\n return tf.image.cropAndResize(image, boxes, [0], cropSize);\n}\nexports.cutBoxFromImageAndResize = cutBoxFromImageAndResize;\nfunction enlargeBox(box, factor = 1.5) {\n const center = getBoxCenter(box);\n const size = getBoxSize(box);\n const newHalfSize = [factor * size[0] / 2, factor * size[1] / 2];\n const startPoint = [center[0] - newHalfSize[0], center[1] - newHalfSize[1]];\n const endPoint = [center[0] + newHalfSize[0], center[1] + newHalfSize[1]];\n return { startPoint, endPoint, landmarks: box.landmarks };\n}\nexports.enlargeBox = enlargeBox;\nfunction squarifyBox(box) {\n const centers = getBoxCenter(box);\n const size = getBoxSize(box);\n const maxEdge = Math.max(...size);\n const halfSize = maxEdge / 2;\n const startPoint = [centers[0] - halfSize, centers[1] - halfSize];\n const endPoint = [centers[0] + halfSize, centers[1] + halfSize];\n return { startPoint, endPoint, landmarks: box.landmarks };\n}\nexports.squarifyBox = squarifyBox;\n", "exports.IDENTITY_MATRIX = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];\n/**\n * Normalizes the provided angle to the range -pi to pi.\n * @param angle The angle in radians to be normalized.\n */\nfunction normalizeRadians(angle) {\n return angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));\n}\nexports.normalizeRadians = normalizeRadians;\n/**\n * Computes the angle of rotation between two anchor points.\n * @param point1 First anchor point\n * @param point2 Second anchor point\n */\nfunction computeRotation(point1, point2) {\n const radians = Math.PI / 2 - Math.atan2(-(point2[1] - point1[1]), point2[0] - point1[0]);\n return normalizeRadians(radians);\n}\nexports.computeRotation = computeRotation;\nfunction radToDegrees(rad) {\n return rad * 180 / Math.PI;\n}\nexports.radToDegrees = radToDegrees;\nfunction buildTranslationMatrix(x, y) {\n return [[1, 0, x], [0, 1, y], [0, 0, 1]];\n}\nfunction dot(v1, v2) {\n let product = 0;\n for (let i = 0; i < v1.length; i++) {\n product += v1[i] * v2[i];\n }\n return product;\n}\nexports.dot = dot;\nfunction getColumnFrom2DArr(arr, columnIndex) {\n const column = [];\n for (let i = 0; i < arr.length; i++) {\n column.push(arr[i][columnIndex]);\n }\n return column;\n}\nexports.getColumnFrom2DArr = getColumnFrom2DArr;\nfunction multiplyTransformMatrices(mat1, mat2) {\n const product = [];\n const size = mat1.length;\n for (let row = 0; row < size; row++) {\n product.push([]);\n for (let col = 0; col < size; col++) {\n product[row].push(dot(mat1[row], getColumnFrom2DArr(mat2, col)));\n }\n }\n return product;\n}\nfunction buildRotationMatrix(rotation, center) {\n const cosA = Math.cos(rotation);\n const sinA = Math.sin(rotation);\n const rotationMatrix = [[cosA, -sinA, 0], [sinA, cosA, 0], [0, 0, 1]];\n const translationMatrix = buildTranslationMatrix(center[0], center[1]);\n const translationTimesRotation = multiplyTransformMatrices(translationMatrix, rotationMatrix);\n const negativeTranslationMatrix = buildTranslationMatrix(-center[0], -center[1]);\n return multiplyTransformMatrices(translationTimesRotation, negativeTranslationMatrix);\n}\nexports.buildRotationMatrix = buildRotationMatrix;\nfunction invertTransformMatrix(matrix) {\n const rotationComponent = [[matrix[0][0], matrix[1][0]], [matrix[0][1], matrix[1][1]]];\n const translationComponent = [matrix[0][2], matrix[1][2]];\n const invertedTranslation = [\n -dot(rotationComponent[0], translationComponent),\n -dot(rotationComponent[1], translationComponent),\n ];\n return [\n rotationComponent[0].concat(invertedTranslation[0]),\n rotationComponent[1].concat(invertedTranslation[1]),\n [0, 0, 1],\n ];\n}\nexports.invertTransformMatrix = invertTransformMatrix;\nfunction rotatePoint(homogeneousCoordinate, rotationMatrix) {\n return [\n dot(homogeneousCoordinate, rotationMatrix[0]),\n dot(homogeneousCoordinate, rotationMatrix[1]),\n ];\n}\nexports.rotatePoint = rotatePoint;\nfunction xyDistanceBetweenPoints(a, b) {\n return Math.sqrt(((a[0] - b[0]) ** 2) + ((a[1] - b[1]) ** 2));\n}\nexports.xyDistanceBetweenPoints = xyDistanceBetweenPoints;\n", "/* eslint-disable class-methods-use-this */\nconst tf = require('@tensorflow/tfjs');\nconst bounding = require('./box');\nconst keypoints = require('./keypoints');\nconst util = require('./util');\n\nconst LANDMARKS_COUNT = 468;\nconst UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD = 0.25;\nconst MESH_MOUTH_INDEX = 13;\nconst MESH_KEYPOINTS_LINE_OF_SYMMETRY_INDICES = [MESH_MOUTH_INDEX, keypoints.MESH_ANNOTATIONS['midwayBetweenEyes'][0]];\nconst BLAZEFACE_MOUTH_INDEX = 3;\nconst BLAZEFACE_NOSE_INDEX = 2;\nconst BLAZEFACE_KEYPOINTS_LINE_OF_SYMMETRY_INDICES = [BLAZEFACE_MOUTH_INDEX, BLAZEFACE_NOSE_INDEX];\nconst LEFT_EYE_OUTLINE = keypoints.MESH_ANNOTATIONS['leftEyeLower0'];\nconst LEFT_EYE_BOUNDS = [LEFT_EYE_OUTLINE[0], LEFT_EYE_OUTLINE[LEFT_EYE_OUTLINE.length - 1]];\nconst RIGHT_EYE_OUTLINE = keypoints.MESH_ANNOTATIONS['rightEyeLower0'];\nconst RIGHT_EYE_BOUNDS = [RIGHT_EYE_OUTLINE[0], RIGHT_EYE_OUTLINE[RIGHT_EYE_OUTLINE.length - 1]];\nconst IRIS_UPPER_CENTER_INDEX = 3;\nconst IRIS_LOWER_CENTER_INDEX = 4;\nconst IRIS_IRIS_INDEX = 71;\nconst IRIS_NUM_COORDINATES = 76;\n\n// Replace the raw coordinates returned by facemesh with refined iris model coordinates. Update the z coordinate to be an average of the original and the new. This produces the best visual effect.\nfunction replaceRawCoordinates(rawCoords, newCoords, prefix, keys) {\n for (let i = 0; i < keypoints.MESH_TO_IRIS_INDICES_MAP.length; i++) {\n const { key, indices } = keypoints.MESH_TO_IRIS_INDICES_MAP[i];\n const originalIndices = keypoints.MESH_ANNOTATIONS[`${prefix}${key}`];\n const shouldReplaceAllKeys = keys == null;\n if (shouldReplaceAllKeys || keys.includes(key)) {\n for (let j = 0; j < indices.length; j++) {\n const index = indices[j];\n rawCoords[originalIndices[j]] = [\n newCoords[index][0], newCoords[index][1],\n (newCoords[index][2] + rawCoords[originalIndices[j]][2]) / 2,\n ];\n }\n }\n }\n}\n// The Pipeline coordinates between the bounding box and skeleton models.\nclass Pipeline {\n constructor(boundingBoxDetector, meshDetector, irisModel, config) {\n // An array of facial bounding boxes.\n this.regionsOfInterest = [];\n this.runsWithoutFaceDetector = 0;\n this.boundingBoxDetector = boundingBoxDetector;\n this.meshDetector = meshDetector;\n this.irisModel = irisModel;\n this.meshWidth = config.mesh.inputSize;\n this.meshHeight = config.mesh.inputSize;\n this.irisSize = config.iris.inputSize;\n this.irisEnlarge = config.iris.enlargeFactor;\n }\n\n transformRawCoords(rawCoords, box, angle, rotationMatrix) {\n const boxSize = bounding.getBoxSize({ startPoint: box.startPoint, endPoint: box.endPoint });\n const scaleFactor = [boxSize[0] / this.meshWidth, boxSize[1] / this.meshHeight];\n const coordsScaled = rawCoords.map((coord) => ([\n scaleFactor[0] * (coord[0] - this.meshWidth / 2),\n scaleFactor[1] * (coord[1] - this.meshHeight / 2), coord[2],\n ]));\n const coordsRotationMatrix = util.buildRotationMatrix(angle, [0, 0]);\n const coordsRotated = coordsScaled.map((coord) => ([...util.rotatePoint(coord, coordsRotationMatrix), coord[2]]));\n const inverseRotationMatrix = util.invertTransformMatrix(rotationMatrix);\n const boxCenter = [...bounding.getBoxCenter({ startPoint: box.startPoint, endPoint: box.endPoint }), 1];\n const originalBoxCenter = [\n util.dot(boxCenter, inverseRotationMatrix[0]),\n util.dot(boxCenter, inverseRotationMatrix[1]),\n ];\n return coordsRotated.map((coord) => ([\n coord[0] + originalBoxCenter[0],\n coord[1] + originalBoxCenter[1], coord[2],\n ]));\n }\n\n getLeftToRightEyeDepthDifference(rawCoords) {\n const leftEyeZ = rawCoords[LEFT_EYE_BOUNDS[0]][2];\n const rightEyeZ = rawCoords[RIGHT_EYE_BOUNDS[0]][2];\n return leftEyeZ - rightEyeZ;\n }\n\n // Returns a box describing a cropped region around the eye fit for passing to the iris model.\n getEyeBox(rawCoords, face, eyeInnerCornerIndex, eyeOuterCornerIndex, flip = false) {\n const box = bounding.squarifyBox(bounding.enlargeBox(this.calculateLandmarksBoundingBox([rawCoords[eyeInnerCornerIndex], rawCoords[eyeOuterCornerIndex]]), this.irisEnlarge));\n const boxSize = bounding.getBoxSize(box);\n let crop = tf.image.cropAndResize(face, [[\n box.startPoint[1] / this.meshHeight,\n box.startPoint[0] / this.meshWidth, box.endPoint[1] / this.meshHeight,\n box.endPoint[0] / this.meshWidth,\n ]], [0], [this.irisSize, this.irisSize]);\n if (flip) {\n crop = tf.image.flipLeftRight(crop);\n }\n return { box, boxSize, crop };\n }\n\n // Given a cropped image of an eye, returns the coordinates of the contours surrounding the eye and the iris.\n getEyeCoords(eyeData, eyeBox, eyeBoxSize, flip = false) {\n const eyeRawCoords = [];\n for (let i = 0; i < IRIS_NUM_COORDINATES; i++) {\n const x = eyeData[i * 3];\n const y = eyeData[i * 3 + 1];\n const z = eyeData[i * 3 + 2];\n eyeRawCoords.push([\n (flip\n ? (1 - (x / this.irisSize))\n : (x / this.irisSize)) * eyeBoxSize[0] + eyeBox.startPoint[0],\n (y / this.irisSize) * eyeBoxSize[1] + eyeBox.startPoint[1], z,\n ]);\n }\n return { rawCoords: eyeRawCoords, iris: eyeRawCoords.slice(IRIS_IRIS_INDEX) };\n }\n\n // The z-coordinates returned for the iris are unreliable, so we take the z values from the surrounding keypoints.\n getAdjustedIrisCoords(rawCoords, irisCoords, direction) {\n const upperCenterZ = rawCoords[keypoints.MESH_ANNOTATIONS[`${direction}EyeUpper0`][IRIS_UPPER_CENTER_INDEX]][2];\n const lowerCenterZ = rawCoords[keypoints.MESH_ANNOTATIONS[`${direction}EyeLower0`][IRIS_LOWER_CENTER_INDEX]][2];\n const averageZ = (upperCenterZ + lowerCenterZ) / 2;\n // Iris indices: 0: center | 1: right | 2: above | 3: left | 4: below\n return irisCoords.map((coord, i) => {\n let z = averageZ;\n if (i === 2) {\n z = upperCenterZ;\n } else if (i === 4) {\n z = lowerCenterZ;\n }\n return [coord[0], coord[1], z];\n });\n }\n\n async predict(input, config) {\n this.skipFrames = config.detector.skipFrames;\n this.maxFaces = config.detector.maxFaces;\n this.runsWithoutFaceDetector++;\n if (this.shouldUpdateRegionsOfInterest()) {\n const detector = await this.boundingBoxDetector.getBoundingBoxes(input);\n if (detector.boxes.length === 0) {\n this.regionsOfInterest = [];\n return null;\n }\n const scaledBoxes = detector.boxes.map((prediction) => {\n const startPoint = prediction.box.startPoint.squeeze();\n const endPoint = prediction.box.endPoint.squeeze();\n const predictionBox = {\n startPoint: startPoint.arraySync(),\n endPoint: endPoint.arraySync(),\n };\n startPoint.dispose();\n endPoint.dispose();\n const scaledBox = bounding.scaleBoxCoordinates(predictionBox, detector.scaleFactor);\n const enlargedBox = bounding.enlargeBox(scaledBox);\n const landmarks = prediction.landmarks.arraySync();\n prediction.box.startPoint.dispose();\n prediction.box.endPoint.dispose();\n prediction.landmarks.dispose();\n prediction.probability.dispose();\n return { ...enlargedBox, landmarks };\n });\n this.updateRegionsOfInterest(scaledBoxes);\n this.runsWithoutFaceDetector = 0;\n }\n const results = tf.tidy(() => this.regionsOfInterest.map((box, i) => {\n let angle = 0;\n // The facial bounding box landmarks could come either from blazeface (if we are using a fresh box), or from the mesh model (if we are reusing an old box).\n const boxLandmarksFromMeshModel = box.landmarks.length >= LANDMARKS_COUNT;\n let [indexOfMouth, indexOfForehead] = MESH_KEYPOINTS_LINE_OF_SYMMETRY_INDICES;\n if (boxLandmarksFromMeshModel === false) {\n [indexOfMouth, indexOfForehead] = BLAZEFACE_KEYPOINTS_LINE_OF_SYMMETRY_INDICES;\n }\n angle = util.computeRotation(box.landmarks[indexOfMouth], box.landmarks[indexOfForehead]);\n const faceCenter = bounding.getBoxCenter({ startPoint: box.startPoint, endPoint: box.endPoint });\n const faceCenterNormalized = [faceCenter[0] / input.shape[2], faceCenter[1] / input.shape[1]];\n let rotatedImage = input;\n let rotationMatrix = util.IDENTITY_MATRIX;\n if (angle !== 0) {\n rotatedImage = tf.image.rotateWithOffset(input, angle, 0, faceCenterNormalized);\n rotationMatrix = util.buildRotationMatrix(-angle, faceCenter);\n }\n const boxCPU = { startPoint: box.startPoint, endPoint: box.endPoint };\n const face = bounding.cutBoxFromImageAndResize(boxCPU, rotatedImage, [this.meshHeight, this.meshWidth]).div(255);\n // The first returned tensor represents facial contours, which are included in the coordinates.\n const [, flag, coords] = this.meshDetector.predict(face);\n const coordsReshaped = tf.reshape(coords, [-1, 3]);\n let rawCoords = coordsReshaped.arraySync();\n if (config.iris.enabled) {\n const { box: leftEyeBox, boxSize: leftEyeBoxSize, crop: leftEyeCrop } = this.getEyeBox(rawCoords, face, LEFT_EYE_BOUNDS[0], LEFT_EYE_BOUNDS[1], true);\n const { box: rightEyeBox, boxSize: rightEyeBoxSize, crop: rightEyeCrop } = this.getEyeBox(rawCoords, face, RIGHT_EYE_BOUNDS[0], RIGHT_EYE_BOUNDS[1]);\n const eyePredictions = (this.irisModel.predict(tf.concat([leftEyeCrop, rightEyeCrop])));\n const eyePredictionsData = eyePredictions.dataSync();\n eyePredictions.dispose();\n const leftEyeData = eyePredictionsData.slice(0, IRIS_NUM_COORDINATES * 3);\n const { rawCoords: leftEyeRawCoords, iris: leftIrisRawCoords } = this.getEyeCoords(leftEyeData, leftEyeBox, leftEyeBoxSize, true);\n const rightEyeData = eyePredictionsData.slice(IRIS_NUM_COORDINATES * 3);\n const { rawCoords: rightEyeRawCoords, iris: rightIrisRawCoords } = this.getEyeCoords(rightEyeData, rightEyeBox, rightEyeBoxSize);\n const leftToRightEyeDepthDifference = this.getLeftToRightEyeDepthDifference(rawCoords);\n if (Math.abs(leftToRightEyeDepthDifference) < 30) { // User is looking straight ahead.\n replaceRawCoordinates(rawCoords, leftEyeRawCoords, 'left');\n replaceRawCoordinates(rawCoords, rightEyeRawCoords, 'right');\n // If the user is looking to the left or to the right, the iris coordinates tend to diverge too much from the mesh coordinates for them to be merged. So we only update a single contour line above and below the eye.\n } else if (leftToRightEyeDepthDifference < 1) { // User is looking towards the right.\n replaceRawCoordinates(rawCoords, leftEyeRawCoords, 'left', ['EyeUpper0', 'EyeLower0']);\n } else { // User is looking towards the left.\n replaceRawCoordinates(rawCoords, rightEyeRawCoords, 'right', ['EyeUpper0', 'EyeLower0']);\n }\n const adjustedLeftIrisCoords = this.getAdjustedIrisCoords(rawCoords, leftIrisRawCoords, 'left');\n const adjustedRightIrisCoords = this.getAdjustedIrisCoords(rawCoords, rightIrisRawCoords, 'right');\n rawCoords = rawCoords.concat(adjustedLeftIrisCoords).concat(adjustedRightIrisCoords);\n }\n const transformedCoordsData = this.transformRawCoords(rawCoords, box, angle, rotationMatrix);\n tf.dispose(rawCoords);\n const landmarksBox = bounding.enlargeBox(this.calculateLandmarksBoundingBox(transformedCoordsData));\n const confidence = flag.squeeze();\n tf.dispose(flag);\n if (config.mesh.enabled) {\n const transformedCoords = tf.tensor2d(transformedCoordsData);\n this.regionsOfInterest[i] = { ...landmarksBox, landmarks: transformedCoords.arraySync() };\n const prediction = {\n coords: transformedCoords,\n box: landmarksBox,\n confidence,\n image: face,\n };\n return prediction;\n }\n const prediction = {\n coords: null,\n box: landmarksBox,\n confidence,\n image: face,\n };\n return prediction;\n }));\n return results;\n }\n\n // Updates regions of interest if the intersection over union between the incoming and previous regions falls below a threshold.\n updateRegionsOfInterest(boxes) {\n for (let i = 0; i < boxes.length; i++) {\n const box = boxes[i];\n const previousBox = this.regionsOfInterest[i];\n let iou = 0;\n if (previousBox && previousBox.startPoint) {\n const [boxStartX, boxStartY] = box.startPoint;\n const [boxEndX, boxEndY] = box.endPoint;\n const [previousBoxStartX, previousBoxStartY] = previousBox.startPoint;\n const [previousBoxEndX, previousBoxEndY] = previousBox.endPoint;\n const xStartMax = Math.max(boxStartX, previousBoxStartX);\n const yStartMax = Math.max(boxStartY, previousBoxStartY);\n const xEndMin = Math.min(boxEndX, previousBoxEndX);\n const yEndMin = Math.min(boxEndY, previousBoxEndY);\n const intersection = (xEndMin - xStartMax) * (yEndMin - yStartMax);\n const boxArea = (boxEndX - boxStartX) * (boxEndY - boxStartY);\n const previousBoxArea = (previousBoxEndX - previousBoxStartX) * (previousBoxEndY - boxStartY);\n iou = intersection / (boxArea + previousBoxArea - intersection);\n }\n if (iou < UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD) {\n this.regionsOfInterest[i] = box;\n }\n }\n this.regionsOfInterest = this.regionsOfInterest.slice(0, boxes.length);\n }\n\n clearRegionOfInterest(index) {\n if (this.regionsOfInterest[index] != null) {\n this.regionsOfInterest = [\n ...this.regionsOfInterest.slice(0, index),\n ...this.regionsOfInterest.slice(index + 1),\n ];\n }\n }\n\n shouldUpdateRegionsOfInterest() {\n if (this.regionsOfInterest.length === 0) return true; // nothing detected, so run detector on the next frame\n return (this.regionsOfInterest.length !== this.maxFaces) && (this.runsWithoutFaceDetector >= this.skipFrames);\n }\n\n calculateLandmarksBoundingBox(landmarks) {\n const xs = landmarks.map((d) => d[0]);\n const ys = landmarks.map((d) => d[1]);\n const startPoint = [Math.min(...xs), Math.min(...ys)];\n const endPoint = [Math.max(...xs), Math.max(...ys)];\n return { startPoint, endPoint, landmarks };\n }\n}\nexports.Pipeline = Pipeline;\n", "exports.UV_COORDS = [\n [0.499976992607117, 0.652534008026123],\n [0.500025987625122, 0.547487020492554],\n [0.499974012374878, 0.602371990680695],\n [0.482113003730774, 0.471979022026062],\n [0.500150978565216, 0.527155995368958],\n [0.499909996986389, 0.498252987861633],\n [0.499523013830185, 0.40106201171875],\n [0.289712011814117, 0.380764007568359],\n [0.499954998493195, 0.312398016452789],\n [0.499987006187439, 0.269918978214264],\n [0.500023007392883, 0.107050001621246],\n [0.500023007392883, 0.666234016418457],\n [0.5000159740448, 0.679224014282227],\n [0.500023007392883, 0.692348003387451],\n [0.499976992607117, 0.695277988910675],\n [0.499976992607117, 0.70593398809433],\n [0.499976992607117, 0.719385027885437],\n [0.499976992607117, 0.737019002437592],\n [0.499967992305756, 0.781370997428894],\n [0.499816000461578, 0.562981009483337],\n [0.473773002624512, 0.573909997940063],\n [0.104906998574734, 0.254140973091125],\n [0.365929991006851, 0.409575998783112],\n [0.338757991790771, 0.41302502155304],\n [0.311120003461838, 0.409460008144379],\n [0.274657994508743, 0.389131009578705],\n [0.393361985683441, 0.403706014156342],\n [0.345234006643295, 0.344011008739471],\n [0.370094001293182, 0.346076011657715],\n [0.319321990013123, 0.347265005111694],\n [0.297903001308441, 0.353591024875641],\n [0.24779200553894, 0.410809993743896],\n [0.396889001131058, 0.842755019664764],\n [0.280097991228104, 0.375599980354309],\n [0.106310002505779, 0.399955987930298],\n [0.2099249958992, 0.391353011131287],\n [0.355807989835739, 0.534406006336212],\n [0.471751004457474, 0.65040397644043],\n [0.474155008792877, 0.680191993713379],\n [0.439785003662109, 0.657229006290436],\n [0.414617002010345, 0.66654098033905],\n [0.450374007225037, 0.680860996246338],\n [0.428770989179611, 0.682690978050232],\n [0.374971002340317, 0.727805018424988],\n [0.486716985702515, 0.547628998756409],\n [0.485300987958908, 0.527395009994507],\n [0.257764995098114, 0.314490020275116],\n [0.401223003864288, 0.455172002315521],\n [0.429818987846375, 0.548614978790283],\n [0.421351999044418, 0.533740997314453],\n [0.276895999908447, 0.532056987285614],\n [0.483370006084442, 0.499586999416351],\n [0.33721199631691, 0.282882988452911],\n [0.296391993761063, 0.293242990970612],\n [0.169294998049736, 0.193813979625702],\n [0.447580009698868, 0.302609980106354],\n [0.392390012741089, 0.353887975215912],\n [0.354490011930466, 0.696784019470215],\n [0.067304998636246, 0.730105042457581],\n [0.442739009857178, 0.572826027870178],\n [0.457098007202148, 0.584792017936707],\n [0.381974011659622, 0.694710969924927],\n [0.392388999462128, 0.694203019142151],\n [0.277076005935669, 0.271932005882263],\n [0.422551989555359, 0.563233017921448],\n [0.385919004678726, 0.281364023685455],\n [0.383103013038635, 0.255840003490448],\n [0.331431001424789, 0.119714021682739],\n [0.229923993349075, 0.232002973556519],\n [0.364500999450684, 0.189113974571228],\n [0.229622006416321, 0.299540996551514],\n [0.173287004232407, 0.278747975826263],\n [0.472878992557526, 0.666198015213013],\n [0.446828007698059, 0.668527007102966],\n [0.422762006521225, 0.673889994621277],\n [0.445307999849319, 0.580065965652466],\n [0.388103008270264, 0.693961024284363],\n [0.403039008378983, 0.706539988517761],\n [0.403629004955292, 0.693953037261963],\n [0.460041999816895, 0.557139039039612],\n [0.431158006191254, 0.692366003990173],\n [0.452181994915009, 0.692366003990173],\n [0.475387006998062, 0.692366003990173],\n [0.465828001499176, 0.779190003871918],\n [0.472328990697861, 0.736225962638855],\n [0.473087012767792, 0.717857003211975],\n [0.473122000694275, 0.704625964164734],\n [0.473033010959625, 0.695277988910675],\n [0.427942007780075, 0.695277988910675],\n [0.426479011774063, 0.703539967536926],\n [0.423162013292313, 0.711845993995667],\n [0.4183090031147, 0.720062971115112],\n [0.390094995498657, 0.639572978019714],\n [0.013953999616206, 0.560034036636353],\n [0.499913990497589, 0.58014702796936],\n [0.413199990987778, 0.69539999961853],\n [0.409626007080078, 0.701822996139526],\n [0.468080013990402, 0.601534962654114],\n [0.422728985548019, 0.585985004901886],\n [0.463079988956451, 0.593783974647522],\n [0.37211999297142, 0.47341400384903],\n [0.334562003612518, 0.496073007583618],\n [0.411671012639999, 0.546965003013611],\n [0.242175996303558, 0.14767599105835],\n [0.290776997804642, 0.201445996761322],\n [0.327338010072708, 0.256527006626129],\n [0.399509996175766, 0.748921036720276],\n [0.441727995872498, 0.261676013469696],\n [0.429764986038208, 0.187834024429321],\n [0.412198007106781, 0.108901023864746],\n [0.288955003023148, 0.398952007293701],\n [0.218936994671822, 0.435410976409912],\n [0.41278201341629, 0.398970007896423],\n [0.257135003805161, 0.355440020561218],\n [0.427684992551804, 0.437960982322693],\n [0.448339998722076, 0.536936044692993],\n [0.178560003638268, 0.45755398273468],\n [0.247308000922203, 0.457193970680237],\n [0.286267012357712, 0.467674970626831],\n [0.332827985286713, 0.460712015628815],\n [0.368755996227264, 0.447206974029541],\n [0.398963987827301, 0.432654976844788],\n [0.476410001516342, 0.405806005001068],\n [0.189241006970406, 0.523923993110657],\n [0.228962004184723, 0.348950982093811],\n [0.490725994110107, 0.562400996685028],\n [0.404670000076294, 0.485132992267609],\n [0.019469000399113, 0.401564002037048],\n [0.426243007183075, 0.420431017875671],\n [0.396993011236191, 0.548797011375427],\n [0.266469985246658, 0.376977026462555],\n [0.439121007919312, 0.51895797252655],\n [0.032313998788595, 0.644356966018677],\n [0.419054001569748, 0.387154996395111],\n [0.462783008813858, 0.505746960639954],\n [0.238978996872902, 0.779744982719421],\n [0.198220998048782, 0.831938028335571],\n [0.107550002634525, 0.540755033493042],\n [0.183610007166862, 0.740257024765015],\n [0.134409993886948, 0.333683013916016],\n [0.385764002799988, 0.883153975009918],\n [0.490967005491257, 0.579378008842468],\n [0.382384985685349, 0.508572995662689],\n [0.174399003386497, 0.397670984268188],\n [0.318785011768341, 0.39623498916626],\n [0.343364000320435, 0.400596976280212],\n [0.396100014448166, 0.710216999053955],\n [0.187885001301765, 0.588537991046906],\n [0.430987000465393, 0.944064974784851],\n [0.318993002176285, 0.898285031318665],\n [0.266247987747192, 0.869701027870178],\n [0.500023007392883, 0.190576016902924],\n [0.499976992607117, 0.954452991485596],\n [0.366169989109039, 0.398822009563446],\n [0.393207013607025, 0.39553701877594],\n [0.410373002290726, 0.391080021858215],\n [0.194993004202843, 0.342101991176605],\n [0.388664990663528, 0.362284004688263],\n [0.365961998701096, 0.355970978736877],\n [0.343364000320435, 0.355356991291046],\n [0.318785011768341, 0.35834002494812],\n [0.301414996385574, 0.363156020641327],\n [0.058132998645306, 0.319076001644135],\n [0.301414996385574, 0.387449026107788],\n [0.499987989664078, 0.618434011936188],\n [0.415838003158569, 0.624195992946625],\n [0.445681989192963, 0.566076993942261],\n [0.465844005346298, 0.620640993118286],\n [0.49992299079895, 0.351523995399475],\n [0.288718998432159, 0.819945991039276],\n [0.335278987884521, 0.852819979190826],\n [0.440512001514435, 0.902418971061707],\n [0.128294005990028, 0.791940987110138],\n [0.408771991729736, 0.373893976211548],\n [0.455606997013092, 0.451801002025604],\n [0.499877005815506, 0.908990025520325],\n [0.375436991453171, 0.924192011356354],\n [0.11421000212431, 0.615022003650665],\n [0.448662012815475, 0.695277988910675],\n [0.4480200111866, 0.704632043838501],\n [0.447111994028091, 0.715808033943176],\n [0.444831997156143, 0.730794012546539],\n [0.430011987686157, 0.766808986663818],\n [0.406787008047104, 0.685672998428345],\n [0.400738000869751, 0.681069016456604],\n [0.392399996519089, 0.677703022956848],\n [0.367855995893478, 0.663918972015381],\n [0.247923001646996, 0.601333022117615],\n [0.452769994735718, 0.420849978923798],\n [0.43639200925827, 0.359887003898621],\n [0.416164010763168, 0.368713974952698],\n [0.413385987281799, 0.692366003990173],\n [0.228018000721931, 0.683571994304657],\n [0.468268007040024, 0.352671027183533],\n [0.411361992359161, 0.804327011108398],\n [0.499989002943039, 0.469825029373169],\n [0.479153990745544, 0.442654013633728],\n [0.499974012374878, 0.439637005329132],\n [0.432112008333206, 0.493588984012604],\n [0.499886006116867, 0.866917014122009],\n [0.49991300702095, 0.821729004383087],\n [0.456548988819122, 0.819200992584229],\n [0.344549000263214, 0.745438992977142],\n [0.37890899181366, 0.574010014533997],\n [0.374292999505997, 0.780184984207153],\n [0.319687992334366, 0.570737957954407],\n [0.357154995203018, 0.604269981384277],\n [0.295284003019333, 0.621580958366394],\n [0.447750002145767, 0.862477004528046],\n [0.410986006259918, 0.508723020553589],\n [0.31395098567009, 0.775308012962341],\n [0.354128003120422, 0.812552988529205],\n [0.324548006057739, 0.703992962837219],\n [0.189096003770828, 0.646299958229065],\n [0.279776990413666, 0.71465802192688],\n [0.1338230073452, 0.682700991630554],\n [0.336768001317978, 0.644733011722565],\n [0.429883986711502, 0.466521978378296],\n [0.455527991056442, 0.548622965812683],\n [0.437114000320435, 0.558896005153656],\n [0.467287987470627, 0.529924988746643],\n [0.414712011814117, 0.335219979286194],\n [0.37704598903656, 0.322777986526489],\n [0.344107985496521, 0.320150971412659],\n [0.312875986099243, 0.32233202457428],\n [0.283526003360748, 0.333190023899078],\n [0.241245999932289, 0.382785975933075],\n [0.102986000478268, 0.468762993812561],\n [0.267612010240555, 0.424560010433197],\n [0.297879010438919, 0.433175981044769],\n [0.333433985710144, 0.433878004550934],\n [0.366427004337311, 0.426115989685059],\n [0.396012008190155, 0.416696012020111],\n [0.420121014118195, 0.41022801399231],\n [0.007561000064015, 0.480777025222778],\n [0.432949006557465, 0.569517970085144],\n [0.458638995885849, 0.479089021682739],\n [0.473466008901596, 0.545744001865387],\n [0.476087987422943, 0.563830018043518],\n [0.468472003936768, 0.555056989192963],\n [0.433990985155106, 0.582361996173859],\n [0.483518004417419, 0.562983989715576],\n [0.482482999563217, 0.57784903049469],\n [0.42645001411438, 0.389798998832703],\n [0.438998997211456, 0.39649498462677],\n [0.450067013502121, 0.400434017181396],\n [0.289712011814117, 0.368252992630005],\n [0.276670008897781, 0.363372981548309],\n [0.517862021923065, 0.471948027610779],\n [0.710287988185883, 0.380764007568359],\n [0.526226997375488, 0.573909997940063],\n [0.895093023777008, 0.254140973091125],\n [0.634069979190826, 0.409575998783112],\n [0.661242008209229, 0.41302502155304],\n [0.688880026340485, 0.409460008144379],\n [0.725341975688934, 0.389131009578705],\n [0.606630027294159, 0.40370500087738],\n [0.654766023159027, 0.344011008739471],\n [0.629905998706818, 0.346076011657715],\n [0.680678009986877, 0.347265005111694],\n [0.702096998691559, 0.353591024875641],\n [0.75221198797226, 0.410804986953735],\n [0.602918028831482, 0.842862963676453],\n [0.719901978969574, 0.375599980354309],\n [0.893692970275879, 0.399959981441498],\n [0.790081977844238, 0.391354024410248],\n [0.643998026847839, 0.534487962722778],\n [0.528249025344849, 0.65040397644043],\n [0.525849997997284, 0.680191040039062],\n [0.560214996337891, 0.657229006290436],\n [0.585384011268616, 0.66654098033905],\n [0.549625992774963, 0.680860996246338],\n [0.57122802734375, 0.682691991329193],\n [0.624852001667023, 0.72809898853302],\n [0.513050019741058, 0.547281980514526],\n [0.51509702205658, 0.527251958847046],\n [0.742246985435486, 0.314507007598877],\n [0.598631024360657, 0.454979002475739],\n [0.570338010787964, 0.548575043678284],\n [0.578631997108459, 0.533622980117798],\n [0.723087012767792, 0.532054007053375],\n [0.516445994377136, 0.499638974666595],\n [0.662801027297974, 0.282917976379395],\n [0.70362401008606, 0.293271005153656],\n [0.830704987049103, 0.193813979625702],\n [0.552385985851288, 0.302568018436432],\n [0.607609987258911, 0.353887975215912],\n [0.645429015159607, 0.696707010269165],\n [0.932694971561432, 0.730105042457581],\n [0.557260990142822, 0.572826027870178],\n [0.542901992797852, 0.584792017936707],\n [0.6180260181427, 0.694710969924927],\n [0.607590973377228, 0.694203019142151],\n [0.722943007946014, 0.271963000297546],\n [0.577413976192474, 0.563166975975037],\n [0.614082992076874, 0.281386971473694],\n [0.616907000541687, 0.255886018276215],\n [0.668509006500244, 0.119913995265961],\n [0.770092010498047, 0.232020974159241],\n [0.635536015033722, 0.189248979091644],\n [0.77039098739624, 0.299556016921997],\n [0.826722025871277, 0.278755009174347],\n [0.527121007442474, 0.666198015213013],\n [0.553171992301941, 0.668527007102966],\n [0.577238023281097, 0.673889994621277],\n [0.554691970348358, 0.580065965652466],\n [0.611896991729736, 0.693961024284363],\n [0.59696102142334, 0.706539988517761],\n [0.596370995044708, 0.693953037261963],\n [0.539958000183105, 0.557139039039612],\n [0.568841993808746, 0.692366003990173],\n [0.547818005084991, 0.692366003990173],\n [0.52461302280426, 0.692366003990173],\n [0.534089982509613, 0.779141008853912],\n [0.527670979499817, 0.736225962638855],\n [0.526912987232208, 0.717857003211975],\n [0.526877999305725, 0.704625964164734],\n [0.526966989040375, 0.695277988910675],\n [0.572058022022247, 0.695277988910675],\n [0.573521018028259, 0.703539967536926],\n [0.57683801651001, 0.711845993995667],\n [0.581691026687622, 0.720062971115112],\n [0.609944999217987, 0.639909982681274],\n [0.986046016216278, 0.560034036636353],\n [0.5867999792099, 0.69539999961853],\n [0.590372025966644, 0.701822996139526],\n [0.531915009021759, 0.601536989212036],\n [0.577268004417419, 0.585934996604919],\n [0.536915004253387, 0.593786001205444],\n [0.627542972564697, 0.473352015018463],\n [0.665585994720459, 0.495950996875763],\n [0.588353991508484, 0.546862006187439],\n [0.757824003696442, 0.14767599105835],\n [0.709249973297119, 0.201507985591888],\n [0.672684013843536, 0.256581008434296],\n [0.600408971309662, 0.74900496006012],\n [0.55826598405838, 0.261672019958496],\n [0.570303976535797, 0.187870979309082],\n [0.588165998458862, 0.109044015407562],\n [0.711045026779175, 0.398952007293701],\n [0.781069993972778, 0.435405015945435],\n [0.587247014045715, 0.398931980133057],\n [0.742869973182678, 0.355445981025696],\n [0.572156012058258, 0.437651991844177],\n [0.55186802148819, 0.536570012569427],\n [0.821442008018494, 0.457556009292603],\n [0.752701997756958, 0.457181990146637],\n [0.71375697851181, 0.467626988887787],\n [0.66711300611496, 0.460672974586487],\n [0.631101012229919, 0.447153985500336],\n [0.6008620262146, 0.432473003864288],\n [0.523481011390686, 0.405627012252808],\n [0.810747981071472, 0.523926019668579],\n [0.771045982837677, 0.348959028720856],\n [0.509127020835876, 0.562718033790588],\n [0.595292985439301, 0.485023975372314],\n [0.980530977249146, 0.401564002037048],\n [0.573499977588654, 0.420000016689301],\n [0.602994978427887, 0.548687994480133],\n [0.733529984951019, 0.376977026462555],\n [0.560611009597778, 0.519016981124878],\n [0.967685997486115, 0.644356966018677],\n [0.580985009670258, 0.387160003185272],\n [0.537728011608124, 0.505385041236877],\n [0.760966002941132, 0.779752969741821],\n [0.801778972148895, 0.831938028335571],\n [0.892440974712372, 0.54076099395752],\n [0.816350996494293, 0.740260004997253],\n [0.865594983100891, 0.333687007427216],\n [0.614073991775513, 0.883246004581451],\n [0.508952975273132, 0.579437971115112],\n [0.617941975593567, 0.508316040039062],\n [0.825608015060425, 0.397674977779388],\n [0.681214988231659, 0.39623498916626],\n [0.656635999679565, 0.400596976280212],\n [0.603900015354156, 0.710216999053955],\n [0.81208598613739, 0.588539004325867],\n [0.56801301240921, 0.944564998149872],\n [0.681007981300354, 0.898285031318665],\n [0.733752012252808, 0.869701027870178],\n [0.633830010890961, 0.398822009563446],\n [0.606792986392975, 0.39553701877594],\n [0.589659988880157, 0.391062021255493],\n [0.805015981197357, 0.342108011245728],\n [0.611334979534149, 0.362284004688263],\n [0.634037971496582, 0.355970978736877],\n [0.656635999679565, 0.355356991291046],\n [0.681214988231659, 0.35834002494812],\n [0.698584973812103, 0.363156020641327],\n [0.941866993904114, 0.319076001644135],\n [0.698584973812103, 0.387449026107788],\n [0.584177017211914, 0.624107003211975],\n [0.554318010807037, 0.566076993942261],\n [0.534153997898102, 0.62064003944397],\n [0.711217999458313, 0.819975018501282],\n [0.664629995822906, 0.852871000766754],\n [0.559099972248077, 0.902631998062134],\n [0.871706008911133, 0.791940987110138],\n [0.591234028339386, 0.373893976211548],\n [0.544341027736664, 0.451583981513977],\n [0.624562978744507, 0.924192011356354],\n [0.88577002286911, 0.615028977394104],\n [0.551338016986847, 0.695277988910675],\n [0.551980018615723, 0.704632043838501],\n [0.552887976169586, 0.715808033943176],\n [0.555167973041534, 0.730794012546539],\n [0.569944024085999, 0.767035007476807],\n [0.593203008174896, 0.685675978660583],\n [0.599261999130249, 0.681069016456604],\n [0.607599973678589, 0.677703022956848],\n [0.631937980651855, 0.663500010967255],\n [0.752032995223999, 0.601315021514893],\n [0.547226011753082, 0.420395016670227],\n [0.563543975353241, 0.359827995300293],\n [0.583841025829315, 0.368713974952698],\n [0.586614012718201, 0.692366003990173],\n [0.771915018558502, 0.683578014373779],\n [0.531597018241882, 0.352482974529266],\n [0.588370978832245, 0.804440975189209],\n [0.52079701423645, 0.442565023899078],\n [0.567984998226166, 0.493479013442993],\n [0.543282985687256, 0.819254994392395],\n [0.655317008495331, 0.745514988899231],\n [0.621008992195129, 0.574018001556396],\n [0.625559985637665, 0.78031200170517],\n [0.680198013782501, 0.570719003677368],\n [0.64276397228241, 0.604337990283966],\n [0.704662978649139, 0.621529996395111],\n [0.552012026309967, 0.862591981887817],\n [0.589071989059448, 0.508637011051178],\n [0.685944974422455, 0.775357007980347],\n [0.645735025405884, 0.812640011310577],\n [0.675342977046967, 0.703978002071381],\n [0.810858011245728, 0.646304965019226],\n [0.72012197971344, 0.714666962623596],\n [0.866151988506317, 0.682704985141754],\n [0.663187026977539, 0.644596993923187],\n [0.570082008838654, 0.466325998306274],\n [0.544561982154846, 0.548375964164734],\n [0.562758982181549, 0.558784961700439],\n [0.531987011432648, 0.530140042304993],\n [0.585271000862122, 0.335177004337311],\n [0.622952997684479, 0.32277899980545],\n [0.655896008014679, 0.320163011550903],\n [0.687132000923157, 0.322345972061157],\n [0.716481983661652, 0.333200991153717],\n [0.758756995201111, 0.382786989212036],\n [0.897013008594513, 0.468769013881683],\n [0.732392013072968, 0.424547016620636],\n [0.70211398601532, 0.433162987232208],\n [0.66652500629425, 0.433866024017334],\n [0.633504986763, 0.426087975502014],\n [0.603875994682312, 0.416586995124817],\n [0.579657971858978, 0.409945011138916],\n [0.992439985275269, 0.480777025222778],\n [0.567192018032074, 0.569419980049133],\n [0.54136598110199, 0.478899002075195],\n [0.526564002037048, 0.546118021011353],\n [0.523913025856018, 0.563830018043518],\n [0.531529009342194, 0.555056989192963],\n [0.566035985946655, 0.582329034805298],\n [0.51631098985672, 0.563053965568542],\n [0.5174720287323, 0.577877044677734],\n [0.573594987392426, 0.389806985855103],\n [0.560697972774506, 0.395331978797913],\n [0.549755990505219, 0.399751007556915],\n [0.710287988185883, 0.368252992630005],\n [0.723330020904541, 0.363372981548309],\n];\n", "export default [\n 127, 34, 139, 11, 0, 37, 232, 231, 120, 72, 37, 39, 128, 121, 47, 232, 121,\n 128, 104, 69, 67, 175, 171, 148, 157, 154, 155, 118, 50, 101, 73, 39, 40, 9,\n 151, 108, 48, 115, 131, 194, 204, 211, 74, 40, 185, 80, 42, 183, 40, 92,\n 186, 230, 229, 118, 202, 212, 214, 83, 18, 17, 76, 61, 146, 160, 29, 30, 56,\n 157, 173, 106, 204, 194, 135, 214, 192, 203, 165, 98, 21, 71, 68, 51, 45, 4,\n 144, 24, 23, 77, 146, 91, 205, 50, 187, 201, 200, 18, 91, 106, 182, 90, 91,\n 181, 85, 84, 17, 206, 203, 36, 148, 171, 140, 92, 40, 39, 193, 189, 244,\n 159, 158, 28, 247, 246, 161, 236, 3, 196, 54, 68, 104, 193, 168, 8, 117,\n 228, 31, 189, 193, 55, 98, 97, 99, 126, 47, 100, 166, 79, 218, 155, 154, 26,\n 209, 49, 131, 135, 136, 150, 47, 126, 217, 223, 52, 53, 45, 51, 134, 211,\n 170, 140, 67, 69, 108, 43, 106, 91, 230, 119, 120, 226, 130, 247, 63, 53,\n 52, 238, 20, 242, 46, 70, 156, 78, 62, 96, 46, 53, 63, 143, 34, 227, 173,\n 155, 133, 123, 117, 111, 44, 125, 19, 236, 134, 51, 216, 206, 205, 154, 153,\n 22, 39, 37, 167, 200, 201, 208, 36, 142, 100, 57, 212, 202, 20, 60, 99, 28,\n 158, 157, 35, 226, 113, 160, 159, 27, 204, 202, 210, 113, 225, 46, 43, 202,\n 204, 62, 76, 77, 137, 123, 116, 41, 38, 72, 203, 129, 142, 64, 98, 240, 49,\n 102, 64, 41, 73, 74, 212, 216, 207, 42, 74, 184, 169, 170, 211, 170, 149,\n 176, 105, 66, 69, 122, 6, 168, 123, 147, 187, 96, 77, 90, 65, 55, 107, 89,\n 90, 180, 101, 100, 120, 63, 105, 104, 93, 137, 227, 15, 86, 85, 129, 102,\n 49, 14, 87, 86, 55, 8, 9, 100, 47, 121, 145, 23, 22, 88, 89, 179, 6, 122,\n 196, 88, 95, 96, 138, 172, 136, 215, 58, 172, 115, 48, 219, 42, 80, 81, 195,\n 3, 51, 43, 146, 61, 171, 175, 199, 81, 82, 38, 53, 46, 225, 144, 163, 110,\n 246, 33, 7, 52, 65, 66, 229, 228, 117, 34, 127, 234, 107, 108, 69, 109, 108,\n 151, 48, 64, 235, 62, 78, 191, 129, 209, 126, 111, 35, 143, 163, 161, 246,\n 117, 123, 50, 222, 65, 52, 19, 125, 141, 221, 55, 65, 3, 195, 197, 25, 7,\n 33, 220, 237, 44, 70, 71, 139, 122, 193, 245, 247, 130, 33, 71, 21, 162,\n 153, 158, 159, 170, 169, 150, 188, 174, 196, 216, 186, 92, 144, 160, 161, 2,\n 97, 167, 141, 125, 241, 164, 167, 37, 72, 38, 12, 145, 159, 160, 38, 82, 13,\n 63, 68, 71, 226, 35, 111, 158, 153, 154, 101, 50, 205, 206, 92, 165, 209,\n 198, 217, 165, 167, 97, 220, 115, 218, 133, 112, 243, 239, 238, 241, 214,\n 135, 169, 190, 173, 133, 171, 208, 32, 125, 44, 237, 86, 87, 178, 85, 86,\n 179, 84, 85, 180, 83, 84, 181, 201, 83, 182, 137, 93, 132, 76, 62, 183, 61,\n 76, 184, 57, 61, 185, 212, 57, 186, 214, 207, 187, 34, 143, 156, 79, 239,\n 237, 123, 137, 177, 44, 1, 4, 201, 194, 32, 64, 102, 129, 213, 215, 138, 59,\n 166, 219, 242, 99, 97, 2, 94, 141, 75, 59, 235, 24, 110, 228, 25, 130, 226,\n 23, 24, 229, 22, 23, 230, 26, 22, 231, 112, 26, 232, 189, 190, 243, 221, 56,\n 190, 28, 56, 221, 27, 28, 222, 29, 27, 223, 30, 29, 224, 247, 30, 225, 238,\n 79, 20, 166, 59, 75, 60, 75, 240, 147, 177, 215, 20, 79, 166, 187, 147, 213,\n 112, 233, 244, 233, 128, 245, 128, 114, 188, 114, 217, 174, 131, 115, 220,\n 217, 198, 236, 198, 131, 134, 177, 132, 58, 143, 35, 124, 110, 163, 7, 228,\n 110, 25, 356, 389, 368, 11, 302, 267, 452, 350, 349, 302, 303, 269, 357,\n 343, 277, 452, 453, 357, 333, 332, 297, 175, 152, 377, 384, 398, 382, 347,\n 348, 330, 303, 304, 270, 9, 336, 337, 278, 279, 360, 418, 262, 431, 304,\n 408, 409, 310, 415, 407, 270, 409, 410, 450, 348, 347, 422, 430, 434, 313,\n 314, 17, 306, 307, 375, 387, 388, 260, 286, 414, 398, 335, 406, 418, 364,\n 367, 416, 423, 358, 327, 251, 284, 298, 281, 5, 4, 373, 374, 253, 307, 320,\n 321, 425, 427, 411, 421, 313, 18, 321, 405, 406, 320, 404, 405, 315, 16, 17,\n 426, 425, 266, 377, 400, 369, 322, 391, 269, 417, 465, 464, 386, 257, 258,\n 466, 260, 388, 456, 399, 419, 284, 332, 333, 417, 285, 8, 346, 340, 261,\n 413, 441, 285, 327, 460, 328, 355, 371, 329, 392, 439, 438, 382, 341, 256,\n 429, 420, 360, 364, 394, 379, 277, 343, 437, 443, 444, 283, 275, 440, 363,\n 431, 262, 369, 297, 338, 337, 273, 375, 321, 450, 451, 349, 446, 342, 467,\n 293, 334, 282, 458, 461, 462, 276, 353, 383, 308, 324, 325, 276, 300, 293,\n 372, 345, 447, 382, 398, 362, 352, 345, 340, 274, 1, 19, 456, 248, 281, 436,\n 427, 425, 381, 256, 252, 269, 391, 393, 200, 199, 428, 266, 330, 329, 287,\n 273, 422, 250, 462, 328, 258, 286, 384, 265, 353, 342, 387, 259, 257, 424,\n 431, 430, 342, 353, 276, 273, 335, 424, 292, 325, 307, 366, 447, 345, 271,\n 303, 302, 423, 266, 371, 294, 455, 460, 279, 278, 294, 271, 272, 304, 432,\n 434, 427, 272, 407, 408, 394, 430, 431, 395, 369, 400, 334, 333, 299, 351,\n 417, 168, 352, 280, 411, 325, 319, 320, 295, 296, 336, 319, 403, 404, 330,\n 348, 349, 293, 298, 333, 323, 454, 447, 15, 16, 315, 358, 429, 279, 14, 15,\n 316, 285, 336, 9, 329, 349, 350, 374, 380, 252, 318, 402, 403, 6, 197, 419,\n 318, 319, 325, 367, 364, 365, 435, 367, 397, 344, 438, 439, 272, 271, 311,\n 195, 5, 281, 273, 287, 291, 396, 428, 199, 311, 271, 268, 283, 444, 445,\n 373, 254, 339, 263, 466, 249, 282, 334, 296, 449, 347, 346, 264, 447, 454,\n 336, 296, 299, 338, 10, 151, 278, 439, 455, 292, 407, 415, 358, 371, 355,\n 340, 345, 372, 390, 249, 466, 346, 347, 280, 442, 443, 282, 19, 94, 370,\n 441, 442, 295, 248, 419, 197, 263, 255, 359, 440, 275, 274, 300, 383, 368,\n 351, 412, 465, 263, 467, 466, 301, 368, 389, 380, 374, 386, 395, 378, 379,\n 412, 351, 419, 436, 426, 322, 373, 390, 388, 2, 164, 393, 370, 462, 461,\n 164, 0, 267, 302, 11, 12, 374, 373, 387, 268, 12, 13, 293, 300, 301, 446,\n 261, 340, 385, 384, 381, 330, 266, 425, 426, 423, 391, 429, 355, 437, 391,\n 327, 326, 440, 457, 438, 341, 382, 362, 459, 457, 461, 434, 430, 394, 414,\n 463, 362, 396, 369, 262, 354, 461, 457, 316, 403, 402, 315, 404, 403, 314,\n 405, 404, 313, 406, 405, 421, 418, 406, 366, 401, 361, 306, 408, 407, 291,\n 409, 408, 287, 410, 409, 432, 436, 410, 434, 416, 411, 264, 368, 383, 309,\n 438, 457, 352, 376, 401, 274, 275, 4, 421, 428, 262, 294, 327, 358, 433,\n 416, 367, 289, 455, 439, 462, 370, 326, 2, 326, 370, 305, 460, 455, 254,\n 449, 448, 255, 261, 446, 253, 450, 449, 252, 451, 450, 256, 452, 451, 341,\n 453, 452, 413, 464, 463, 441, 413, 414, 258, 442, 441, 257, 443, 442, 259,\n 444, 443, 260, 445, 444, 467, 342, 445, 459, 458, 250, 289, 392, 290, 290,\n 328, 460, 376, 433, 435, 250, 290, 392, 411, 416, 433, 341, 463, 464, 453,\n 464, 465, 357, 465, 412, 343, 412, 399, 360, 363, 440, 437, 399, 456, 420,\n 456, 363, 401, 435, 288, 372, 383, 353, 339, 255, 249, 448, 261, 255, 133,\n 243, 190, 133, 155, 112, 33, 246, 247, 33, 130, 25, 398, 384, 286, 362, 398,\n 414, 362, 463, 341, 263, 359, 467, 263, 249, 255, 466, 467, 260, 75, 60,\n 166, 238, 239, 79, 162, 127, 139, 72, 11, 37, 121, 232, 120, 73, 72, 39,\n 114, 128, 47, 233, 232, 128, 103, 104, 67, 152, 175, 148, 173, 157, 155,\n 119, 118, 101, 74, 73, 40, 107, 9, 108, 49, 48, 131, 32, 194, 211, 184, 74,\n 185, 191, 80, 183, 185, 40, 186, 119, 230, 118, 210, 202, 214, 84, 83, 17,\n 77, 76, 146, 161, 160, 30, 190, 56, 173, 182, 106, 194, 138, 135, 192, 129,\n 203, 98, 54, 21, 68, 5, 51, 4, 145, 144, 23, 90, 77, 91, 207, 205, 187, 83,\n 201, 18, 181, 91, 182, 180, 90, 181, 16, 85, 17, 205, 206, 36, 176, 148,\n 140, 165, 92, 39, 245, 193, 244, 27, 159, 28, 30, 247, 161, 174, 236, 196,\n 103, 54, 104, 55, 193, 8, 111, 117, 31, 221, 189, 55, 240, 98, 99, 142, 126,\n 100, 219, 166, 218, 112, 155, 26, 198, 209, 131, 169, 135, 150, 114, 47,\n 217, 224, 223, 53, 220, 45, 134, 32, 211, 140, 109, 67, 108, 146, 43, 91,\n 231, 230, 120, 113, 226, 247, 105, 63, 52, 241, 238, 242, 124, 46, 156, 95,\n 78, 96, 70, 46, 63, 116, 143, 227, 116, 123, 111, 1, 44, 19, 3, 236, 51,\n 207, 216, 205, 26, 154, 22, 165, 39, 167, 199, 200, 208, 101, 36, 100, 43,\n 57, 202, 242, 20, 99, 56, 28, 157, 124, 35, 113, 29, 160, 27, 211, 204, 210,\n 124, 113, 46, 106, 43, 204, 96, 62, 77, 227, 137, 116, 73, 41, 72, 36, 203,\n 142, 235, 64, 240, 48, 49, 64, 42, 41, 74, 214, 212, 207, 183, 42, 184, 210,\n 169, 211, 140, 170, 176, 104, 105, 69, 193, 122, 168, 50, 123, 187, 89, 96,\n 90, 66, 65, 107, 179, 89, 180, 119, 101, 120, 68, 63, 104, 234, 93, 227, 16,\n 15, 85, 209, 129, 49, 15, 14, 86, 107, 55, 9, 120, 100, 121, 153, 145, 22,\n 178, 88, 179, 197, 6, 196, 89, 88, 96, 135, 138, 136, 138, 215, 172, 218,\n 115, 219, 41, 42, 81, 5, 195, 51, 57, 43, 61, 208, 171, 199, 41, 81, 38,\n 224, 53, 225, 24, 144, 110, 105, 52, 66, 118, 229, 117, 227, 34, 234, 66,\n 107, 69, 10, 109, 151, 219, 48, 235, 183, 62, 191, 142, 129, 126, 116, 111,\n 143, 7, 163, 246, 118, 117, 50, 223, 222, 52, 94, 19, 141, 222, 221, 65,\n 196, 3, 197, 45, 220, 44, 156, 70, 139, 188, 122, 245, 139, 71, 162, 145,\n 153, 159, 149, 170, 150, 122, 188, 196, 206, 216, 92, 163, 144, 161, 164, 2,\n 167, 242, 141, 241, 0, 164, 37, 11, 72, 12, 144, 145, 160, 12, 38, 13, 70,\n 63, 71, 31, 226, 111, 157, 158, 154, 36, 101, 205, 203, 206, 165, 126, 209,\n 217, 98, 165, 97, 237, 220, 218, 237, 239, 241, 210, 214, 169, 140, 171, 32,\n 241, 125, 237, 179, 86, 178, 180, 85, 179, 181, 84, 180, 182, 83, 181, 194,\n 201, 182, 177, 137, 132, 184, 76, 183, 185, 61, 184, 186, 57, 185, 216, 212,\n 186, 192, 214, 187, 139, 34, 156, 218, 79, 237, 147, 123, 177, 45, 44, 4,\n 208, 201, 32, 98, 64, 129, 192, 213, 138, 235, 59, 219, 141, 242, 97, 97, 2,\n 141, 240, 75, 235, 229, 24, 228, 31, 25, 226, 230, 23, 229, 231, 22, 230,\n 232, 26, 231, 233, 112, 232, 244, 189, 243, 189, 221, 190, 222, 28, 221,\n 223, 27, 222, 224, 29, 223, 225, 30, 224, 113, 247, 225, 99, 60, 240, 213,\n 147, 215, 60, 20, 166, 192, 187, 213, 243, 112, 244, 244, 233, 245, 245,\n 128, 188, 188, 114, 174, 134, 131, 220, 174, 217, 236, 236, 198, 134, 215,\n 177, 58, 156, 143, 124, 25, 110, 7, 31, 228, 25, 264, 356, 368, 0, 11, 267,\n 451, 452, 349, 267, 302, 269, 350, 357, 277, 350, 452, 357, 299, 333, 297,\n 396, 175, 377, 381, 384, 382, 280, 347, 330, 269, 303, 270, 151, 9, 337,\n 344, 278, 360, 424, 418, 431, 270, 304, 409, 272, 310, 407, 322, 270, 410,\n 449, 450, 347, 432, 422, 434, 18, 313, 17, 291, 306, 375, 259, 387, 260,\n 424, 335, 418, 434, 364, 416, 391, 423, 327, 301, 251, 298, 275, 281, 4,\n 254, 373, 253, 375, 307, 321, 280, 425, 411, 200, 421, 18, 335, 321, 406,\n 321, 320, 405, 314, 315, 17, 423, 426, 266, 396, 377, 369, 270, 322, 269,\n 413, 417, 464, 385, 386, 258, 248, 456, 419, 298, 284, 333, 168, 417, 8,\n 448, 346, 261, 417, 413, 285, 326, 327, 328, 277, 355, 329, 309, 392, 438,\n 381, 382, 256, 279, 429, 360, 365, 364, 379, 355, 277, 437, 282, 443, 283,\n 281, 275, 363, 395, 431, 369, 299, 297, 337, 335, 273, 321, 348, 450, 349,\n 359, 446, 467, 283, 293, 282, 250, 458, 462, 300, 276, 383, 292, 308, 325,\n 283, 276, 293, 264, 372, 447, 346, 352, 340, 354, 274, 19, 363, 456, 281,\n 426, 436, 425, 380, 381, 252, 267, 269, 393, 421, 200, 428, 371, 266, 329,\n 432, 287, 422, 290, 250, 328, 385, 258, 384, 446, 265, 342, 386, 387, 257,\n 422, 424, 430, 445, 342, 276, 422, 273, 424, 306, 292, 307, 352, 366, 345,\n 268, 271, 302, 358, 423, 371, 327, 294, 460, 331, 279, 294, 303, 271, 304,\n 436, 432, 427, 304, 272, 408, 395, 394, 431, 378, 395, 400, 296, 334, 299,\n 6, 351, 168, 376, 352, 411, 307, 325, 320, 285, 295, 336, 320, 319, 404,\n 329, 330, 349, 334, 293, 333, 366, 323, 447, 316, 15, 315, 331, 358, 279,\n 317, 14, 316, 8, 285, 9, 277, 329, 350, 253, 374, 252, 319, 318, 403, 351,\n 6, 419, 324, 318, 325, 397, 367, 365, 288, 435, 397, 278, 344, 439, 310,\n 272, 311, 248, 195, 281, 375, 273, 291, 175, 396, 199, 312, 311, 268, 276,\n 283, 445, 390, 373, 339, 295, 282, 296, 448, 449, 346, 356, 264, 454, 337,\n 336, 299, 337, 338, 151, 294, 278, 455, 308, 292, 415, 429, 358, 355, 265,\n 340, 372, 388, 390, 466, 352, 346, 280, 295, 442, 282, 354, 19, 370, 285,\n 441, 295, 195, 248, 197, 457, 440, 274, 301, 300, 368, 417, 351, 465, 251,\n 301, 389, 385, 380, 386, 394, 395, 379, 399, 412, 419, 410, 436, 322, 387,\n 373, 388, 326, 2, 393, 354, 370, 461, 393, 164, 267, 268, 302, 12, 386, 374,\n 387, 312, 268, 13, 298, 293, 301, 265, 446, 340, 380, 385, 381, 280, 330,\n 425, 322, 426, 391, 420, 429, 437, 393, 391, 326, 344, 440, 438, 458, 459,\n 461, 364, 434, 394, 428, 396, 262, 274, 354, 457, 317, 316, 402, 316, 315,\n 403, 315, 314, 404, 314, 313, 405, 313, 421, 406, 323, 366, 361, 292, 306,\n 407, 306, 291, 408, 291, 287, 409, 287, 432, 410, 427, 434, 411, 372, 264,\n 383, 459, 309, 457, 366, 352, 401, 1, 274, 4, 418, 421, 262, 331, 294, 358,\n 435, 433, 367, 392, 289, 439, 328, 462, 326, 94, 2, 370, 289, 305, 455, 339,\n 254, 448, 359, 255, 446, 254, 253, 449, 253, 252, 450, 252, 256, 451, 256,\n 341, 452, 414, 413, 463, 286, 441, 414, 286, 258, 441, 258, 257, 442, 257,\n 259, 443, 259, 260, 444, 260, 467, 445, 309, 459, 250, 305, 289, 290, 305,\n 290, 460, 401, 376, 435, 309, 250, 392, 376, 411, 433, 453, 341, 464, 357,\n 453, 465, 343, 357, 412, 437, 343, 399, 344, 360, 440, 420, 437, 456, 360,\n 420, 363, 361, 401, 288, 265, 372, 353, 390, 339, 249, 339, 448, 255];\n", "const tf = require('@tensorflow/tfjs');\nconst blazeface = require('./blazeface');\nconst keypoints = require('./keypoints');\nconst pipe = require('./pipeline');\nconst uv_coords = require('./uvcoords');\nconst triangulation = require('./triangulation').default;\n\nclass MediaPipeFaceMesh {\n constructor(blazeFace, blazeMeshModel, irisModel, config) {\n this.pipeline = new pipe.Pipeline(blazeFace, blazeMeshModel, irisModel, config);\n if (config) this.config = config;\n }\n\n async estimateFaces(input, config) {\n if (config) this.config = config;\n const predictions = await this.pipeline.predict(input, config);\n const results = [];\n for (const prediction of (predictions || [])) {\n // guard against disposed tensors on long running operations such as pause in middle of processing\n if (prediction.isDisposedInternal) continue;\n const confidence = prediction.confidence.arraySync();\n if (confidence >= this.config.detector.minConfidence) {\n const mesh = prediction.coords ? prediction.coords.arraySync() : null;\n const annotations = {};\n if (mesh && mesh.length > 0) {\n for (const key in keypoints.MESH_ANNOTATIONS) {\n if (this.config.iris.enabled || key.includes('Iris') === false) {\n annotations[key] = keypoints.MESH_ANNOTATIONS[key].map((index) => mesh[index]);\n }\n }\n }\n results.push({\n confidence: confidence || 0,\n box: prediction.box ? [prediction.box.startPoint[0], prediction.box.startPoint[1], prediction.box.endPoint[0] - prediction.box.startPoint[0], prediction.box.endPoint[1] - prediction.box.startPoint[1]] : 0,\n mesh,\n annotations,\n image: prediction.image ? tf.clone(prediction.image) : null,\n });\n }\n if (prediction.confidence) prediction.confidence.dispose();\n if (prediction.coords) prediction.coords.dispose();\n if (prediction.image) prediction.image.dispose();\n }\n return results;\n }\n}\n\nasync function load(config) {\n const models = await Promise.all([\n blazeface.load(config),\n tf.loadGraphModel(config.mesh.modelPath, { fromTFHub: config.mesh.modelPath.includes('tfhub.dev') }),\n tf.loadGraphModel(config.iris.modelPath, { fromTFHub: config.iris.modelPath.includes('tfhub.dev') }),\n ]);\n const faceMesh = new MediaPipeFaceMesh(models[0], models[1], models[2], config);\n return faceMesh;\n}\n\nexports.load = load;\nexports.MediaPipeFaceMesh = MediaPipeFaceMesh;\nexports.uv_coords = uv_coords;\nexports.triangulation = triangulation;\n", "const tf = require('@tensorflow/tfjs');\n\nconst models = {};\nlet last = { age: 0, gender: '' };\nlet frame = 0;\n\nasync function loadAge(config) {\n if (!models.age) models.age = await tf.loadGraphModel(config.face.age.modelPath);\n return models.age;\n}\n\nasync function loadGender(config) {\n if (!models.gender) models.gender = await tf.loadGraphModel(config.face.gender.modelPath);\n return models.gender;\n}\n\nasync function predict(image, config) {\n if (frame < config.face.age.skipFrames) {\n frame += 1;\n return last;\n }\n frame = 0;\n const resize = tf.image.resizeBilinear(image, [config.face.age.inputSize, config.face.age.inputSize], false);\n const enhance = tf.mul(resize, [255.0]);\n tf.dispose(resize);\n\n const promises = [];\n let ageT;\n let genderT;\n if (config.face.age.enabled) promises.push(ageT = models.age.predict(enhance));\n if (config.face.gender.enabled) promises.push(genderT = models.gender.predict(enhance));\n await Promise.all(promises);\n\n const obj = {};\n if (ageT) {\n const data = await ageT.data();\n obj.age = Math.trunc(10 * data[0]) / 10;\n tf.dispose(ageT);\n }\n if (genderT) {\n const data = await genderT.data();\n const confidence = Math.trunc(Math.abs(1.9 * 100 * (data[0] - 0.5))) / 100;\n if (confidence > config.face.gender.minConfidence) {\n obj.gender = data[0] <= 0.5 ? 'female' : 'male';\n obj.confidence = confidence;\n }\n tf.dispose(genderT);\n }\n\n tf.dispose(enhance);\n last = obj;\n return obj;\n}\n\nexports.predict = predict;\nexports.loadAge = loadAge;\nexports.loadGender = loadGender;\n", "const tf = require('@tensorflow/tfjs');\n\nconst annotations = ['angry', 'discust', 'fear', 'happy', 'sad', 'surpise', 'neutral'];\nconst models = {};\nlet last = [];\nlet frame = 0;\nconst multiplier = 1.5;\n\nasync function load(config) {\n if (!models.emotion) models.emotion = await tf.loadGraphModel(config.face.emotion.modelPath);\n return models.emotion;\n}\n\nasync function predict(image, config) {\n if (frame < config.face.emotion.skipFrames) {\n frame += 1;\n return last;\n }\n frame = 0;\n const resize = tf.image.resizeBilinear(image, [config.face.emotion.inputSize, config.face.emotion.inputSize], false);\n const [red, green, blue] = tf.split(resize, 3, 3);\n resize.dispose();\n // weighted rgb to grayscale: https://www.mathworks.com/help/matlab/ref/rgb2gray.html\n const redNorm = tf.mul(red, [0.2989]);\n const greenNorm = tf.mul(green, [0.5870]);\n const blueNorm = tf.mul(blue, [0.1140]);\n red.dispose();\n green.dispose();\n blue.dispose();\n const grayscale = tf.addN([redNorm, greenNorm, blueNorm]);\n redNorm.dispose();\n greenNorm.dispose();\n blueNorm.dispose();\n const obj = [];\n if (config.face.emotion.enabled) {\n const emotionT = await models.emotion.predict(grayscale);\n const data = await emotionT.data();\n for (let i = 0; i < data.length; i++) {\n if (multiplier * data[i] > config.face.emotion.minConfidence) obj.push({ score: Math.min(0.99, Math.trunc(100 * multiplier * data[i]) / 100), emotion: annotations[i] });\n }\n obj.sort((a, b) => b.score - a.score);\n tf.dispose(emotionT);\n }\n tf.dispose(grayscale);\n last = obj;\n return obj;\n}\n\nexports.predict = predict;\nexports.load = load;\n", "const tf = require('@tensorflow/tfjs');\n\nclass BaseModel {\n constructor(model, outputStride) {\n this.model = model;\n this.outputStride = outputStride;\n const inputShape = this.model.inputs[0].shape;\n tf.util.assert((inputShape[1] === -1) && (inputShape[2] === -1), () => `Input shape [${inputShape[1]}, ${inputShape[2]}] must both be equal to or -1`);\n }\n\n /**\n * Predicts intermediate Tensor representations.\n *\n * @param input The input RGB image of the base model.\n * A Tensor of shape: [`inputResolution`, `inputResolution`, 3].\n *\n * @return A dictionary of base model's intermediate predictions.\n * The returned dictionary should contains the following elements:\n * heatmapScores: A Tensor3D that represents the heatmapScores.\n * offsets: A Tensor3D that represents the offsets.\n * displacementFwd: A Tensor3D that represents the forward displacement.\n * displacementBwd: A Tensor3D that represents the backward displacement.\n */\n predict(input) {\n return tf.tidy(() => {\n const asFloat = this.preprocessInput(input.toFloat());\n const asBatch = asFloat.expandDims(0);\n const results = this.model.predict(asBatch);\n const results3d = results.map((y) => y.squeeze([0]));\n const namedResults = this.nameOutputResults(results3d);\n return {\n heatmapScores: namedResults.heatmap.sigmoid(),\n offsets: namedResults.offsets,\n displacementFwd: namedResults.displacementFwd,\n displacementBwd: namedResults.displacementBwd,\n };\n });\n }\n\n /**\n * Releases the CPU and GPU memory allocated by the model.\n */\n dispose() {\n this.model.dispose();\n }\n}\nexports.BaseModel = BaseModel;\n", "const tf = require('@tensorflow/tfjs');\nconst modelBase = require('./modelBase');\n\nclass MobileNet extends modelBase.BaseModel {\n // eslint-disable-next-line class-methods-use-this\n preprocessInput(input) {\n // Normalize the pixels [0, 255] to be between [-1, 1].\n return tf.tidy(() => tf.div(input, 127.5).sub(1.0));\n }\n\n // eslint-disable-next-line class-methods-use-this\n nameOutputResults(results) {\n const [offsets, heatmap, displacementFwd, displacementBwd] = results;\n return { offsets, heatmap, displacementFwd, displacementBwd };\n }\n}\nexports.MobileNet = MobileNet;\n", "// algorithm based on Coursera Lecture from Algorithms, Part 1: https://www.coursera.org/learn/algorithms-part1/lecture/ZjoSM/heapsort\nfunction half(k) {\n return Math.floor(k / 2);\n}\nclass MaxHeap {\n constructor(maxSize, getElementValue) {\n this.priorityQueue = new Array(maxSize);\n this.numberOfElements = -1;\n this.getElementValue = getElementValue;\n }\n\n enqueue(x) {\n this.priorityQueue[++this.numberOfElements] = x;\n this.swim(this.numberOfElements);\n }\n\n dequeue() {\n const max = this.priorityQueue[0];\n this.exchange(0, this.numberOfElements--);\n this.sink(0);\n this.priorityQueue[this.numberOfElements + 1] = null;\n return max;\n }\n\n empty() {\n return this.numberOfElements === -1;\n }\n\n size() {\n return this.numberOfElements + 1;\n }\n\n all() {\n return this.priorityQueue.slice(0, this.numberOfElements + 1);\n }\n\n max() {\n return this.priorityQueue[0];\n }\n\n swim(k) {\n while (k > 0 && this.less(half(k), k)) {\n this.exchange(k, half(k));\n k = half(k);\n }\n }\n\n sink(k) {\n while (2 * k <= this.numberOfElements) {\n let j = 2 * k;\n if (j < this.numberOfElements && this.less(j, j + 1)) j++;\n if (!this.less(k, j)) break;\n this.exchange(k, j);\n k = j;\n }\n }\n\n getValueAt(i) {\n return this.getElementValue(this.priorityQueue[i]);\n }\n\n less(i, j) {\n return this.getValueAt(i) < this.getValueAt(j);\n }\n\n exchange(i, j) {\n const t = this.priorityQueue[i];\n this.priorityQueue[i] = this.priorityQueue[j];\n this.priorityQueue[j] = t;\n }\n}\nexports.MaxHeap = MaxHeap;\n", "const heapSort = require('./heapSort');\n\nfunction scoreIsMaximumInLocalWindow(keypointId, score, heatmapY, heatmapX, localMaximumRadius, scores) {\n const [height, width] = scores.shape;\n let localMaximum = true;\n const yStart = Math.max(heatmapY - localMaximumRadius, 0);\n const yEnd = Math.min(heatmapY + localMaximumRadius + 1, height);\n for (let yCurrent = yStart; yCurrent < yEnd; ++yCurrent) {\n const xStart = Math.max(heatmapX - localMaximumRadius, 0);\n const xEnd = Math.min(heatmapX + localMaximumRadius + 1, width);\n for (let xCurrent = xStart; xCurrent < xEnd; ++xCurrent) {\n if (scores.get(yCurrent, xCurrent, keypointId) > score) {\n localMaximum = false;\n break;\n }\n }\n if (!localMaximum) {\n break;\n }\n }\n return localMaximum;\n}\n/**\n * Builds a priority queue with part candidate positions for a specific image in\n * the batch. For this we find all local maxima in the score maps with score\n * values above a threshold. We create a single priority queue across all parts.\n */\nfunction buildPartWithScoreQueue(scoreThreshold, localMaximumRadius, scores) {\n const [height, width, numKeypoints] = scores.shape;\n const queue = new heapSort.MaxHeap(height * width * numKeypoints, ({ score }) => score);\n for (let heatmapY = 0; heatmapY < height; ++heatmapY) {\n for (let heatmapX = 0; heatmapX < width; ++heatmapX) {\n for (let keypointId = 0; keypointId < numKeypoints; ++keypointId) {\n const score = scores.get(heatmapY, heatmapX, keypointId);\n // Only consider parts with score greater or equal to threshold as root candidates.\n if (score < scoreThreshold) continue;\n // Only consider keypoints whose score is maximum in a local window.\n if (scoreIsMaximumInLocalWindow(keypointId, score, heatmapY, heatmapX, localMaximumRadius, scores)) {\n queue.enqueue({ score, part: { heatmapY, heatmapX, id: keypointId } });\n }\n }\n }\n }\n return queue;\n}\nexports.buildPartWithScoreQueue = buildPartWithScoreQueue;\n", "exports.partNames = [\n 'nose', 'leftEye', 'rightEye', 'leftEar', 'rightEar', 'leftShoulder',\n 'rightShoulder', 'leftElbow', 'rightElbow', 'leftWrist', 'rightWrist',\n 'leftHip', 'rightHip', 'leftKnee', 'rightKnee', 'leftAnkle', 'rightAnkle',\n];\nexports.NUM_KEYPOINTS = exports.partNames.length;\nexports.partIds = exports.partNames.reduce((result, jointName, i) => {\n result[jointName] = i;\n return result;\n}, {});\nconst connectedPartNames = [\n ['leftHip', 'leftShoulder'], ['leftElbow', 'leftShoulder'],\n ['leftElbow', 'leftWrist'], ['leftHip', 'leftKnee'],\n ['leftKnee', 'leftAnkle'], ['rightHip', 'rightShoulder'],\n ['rightElbow', 'rightShoulder'], ['rightElbow', 'rightWrist'],\n ['rightHip', 'rightKnee'], ['rightKnee', 'rightAnkle'],\n ['leftShoulder', 'rightShoulder'], ['leftHip', 'rightHip'],\n];\n/*\n * Define the skeleton. This defines the parent->child relationships of our\n * tree. Arbitrarily this defines the nose as the root of the tree, however\n * since we will infer the displacement for both parent->child and\n * child->parent, we can define the tree root as any node.\n */\nexports.poseChain = [\n ['nose', 'leftEye'], ['leftEye', 'leftEar'], ['nose', 'rightEye'],\n ['rightEye', 'rightEar'], ['nose', 'leftShoulder'],\n ['leftShoulder', 'leftElbow'], ['leftElbow', 'leftWrist'],\n ['leftShoulder', 'leftHip'], ['leftHip', 'leftKnee'],\n ['leftKnee', 'leftAnkle'], ['nose', 'rightShoulder'],\n ['rightShoulder', 'rightElbow'], ['rightElbow', 'rightWrist'],\n ['rightShoulder', 'rightHip'], ['rightHip', 'rightKnee'],\n ['rightKnee', 'rightAnkle'],\n];\nexports.connectedPartIndices = connectedPartNames.map(([jointNameA, jointNameB]) => ([exports.partIds[jointNameA], exports.partIds[jointNameB]]));\nexports.partChannels = [\n 'left_face',\n 'right_face',\n 'right_upper_leg_front',\n 'right_lower_leg_back',\n 'right_upper_leg_back',\n 'left_lower_leg_front',\n 'left_upper_leg_front',\n 'left_upper_leg_back',\n 'left_lower_leg_back',\n 'right_feet',\n 'right_lower_leg_front',\n 'left_feet',\n 'torso_front',\n 'torso_back',\n 'right_upper_arm_front',\n 'right_upper_arm_back',\n 'right_lower_arm_back',\n 'left_lower_arm_front',\n 'left_upper_arm_front',\n 'left_upper_arm_back',\n 'left_lower_arm_back',\n 'right_hand',\n 'right_lower_arm_front',\n 'left_hand',\n];\n", "const kpt = require('./keypoints');\n\nfunction getOffsetPoint(y, x, keypoint, offsets) {\n return {\n y: offsets.get(y, x, keypoint),\n x: offsets.get(y, x, keypoint + kpt.NUM_KEYPOINTS),\n };\n}\nexports.getOffsetPoint = getOffsetPoint;\n\nfunction getImageCoords(part, outputStride, offsets) {\n const { heatmapY, heatmapX, id: keypoint } = part;\n const { y, x } = getOffsetPoint(heatmapY, heatmapX, keypoint, offsets);\n return {\n x: part.heatmapX * outputStride + x,\n y: part.heatmapY * outputStride + y,\n };\n}\nexports.getImageCoords = getImageCoords;\n\nfunction fillArray(element, size) {\n const result = new Array(size);\n for (let i = 0; i < size; i++) {\n result[i] = element;\n }\n return result;\n}\nexports.fillArray = fillArray;\n\nfunction clamp(a, min, max) {\n if (a < min) return min;\n if (a > max) return max;\n return a;\n}\nexports.clamp = clamp;\n\nfunction squaredDistance(y1, x1, y2, x2) {\n const dy = y2 - y1;\n const dx = x2 - x1;\n return dy * dy + dx * dx;\n}\nexports.squaredDistance = squaredDistance;\n\nfunction addVectors(a, b) {\n return { x: a.x + b.x, y: a.y + b.y };\n}\nexports.addVectors = addVectors;\n\nfunction clampVector(a, min, max) {\n return { y: clamp(a.y, min, max), x: clamp(a.x, min, max) };\n}\nexports.clampVector = clampVector;\n", "const keypoints = require('./keypoints');\nconst vectors = require('./vectors');\n\nconst parentChildrenTuples = keypoints.poseChain.map(([parentJoinName, childJoinName]) => ([keypoints.partIds[parentJoinName], keypoints.partIds[childJoinName]]));\nconst parentToChildEdges = parentChildrenTuples.map(([, childJointId]) => childJointId);\nconst childToParentEdges = parentChildrenTuples.map(([parentJointId]) => parentJointId);\nfunction getDisplacement(edgeId, point, displacements) {\n const numEdges = displacements.shape[2] / 2;\n return {\n y: displacements.get(point.y, point.x, edgeId),\n x: displacements.get(point.y, point.x, numEdges + edgeId),\n };\n}\nfunction getStridedIndexNearPoint(point, outputStride, height, width) {\n return {\n y: vectors.clamp(Math.round(point.y / outputStride), 0, height - 1),\n x: vectors.clamp(Math.round(point.x / outputStride), 0, width - 1),\n };\n}\n/**\n * We get a new keypoint along the `edgeId` for the pose instance, assuming\n * that the position of the `idSource` part is already known. For this, we\n * follow the displacement vector from the source to target part (stored in\n * the `i`-t channel of the displacement tensor). The displaced keypoint\n * vector is refined using the offset vector by `offsetRefineStep` times.\n */\nfunction traverseToTargetKeypoint(edgeId, sourceKeypoint, targetKeypointId, scoresBuffer, offsets, outputStride, displacements, offsetRefineStep = 2) {\n const [height, width] = scoresBuffer.shape;\n // Nearest neighbor interpolation for the source->target displacements.\n const sourceKeypointIndices = getStridedIndexNearPoint(sourceKeypoint.position, outputStride, height, width);\n const displacement = getDisplacement(edgeId, sourceKeypointIndices, displacements);\n const displacedPoint = vectors.addVectors(sourceKeypoint.position, displacement);\n let targetKeypoint = displacedPoint;\n for (let i = 0; i < offsetRefineStep; i++) {\n const targetKeypointIndices = getStridedIndexNearPoint(targetKeypoint, outputStride, height, width);\n const offsetPoint = vectors.getOffsetPoint(targetKeypointIndices.y, targetKeypointIndices.x, targetKeypointId, offsets);\n targetKeypoint = vectors.addVectors({\n x: targetKeypointIndices.x * outputStride,\n y: targetKeypointIndices.y * outputStride,\n }, { x: offsetPoint.x, y: offsetPoint.y });\n }\n const targetKeyPointIndices = getStridedIndexNearPoint(targetKeypoint, outputStride, height, width);\n const score = scoresBuffer.get(targetKeyPointIndices.y, targetKeyPointIndices.x, targetKeypointId);\n return { position: targetKeypoint, part: keypoints.partNames[targetKeypointId], score };\n}\n/**\n * Follows the displacement fields to decode the full pose of the object\n * instance given the position of a part that acts as root.\n *\n * @return An array of decoded keypoints and their scores for a single pose\n */\nfunction decodePose(root, scores, offsets, outputStride, displacementsFwd, displacementsBwd) {\n const numParts = scores.shape[2];\n const numEdges = parentToChildEdges.length;\n const instanceKeypoints = new Array(numParts);\n // Start a new detection instance at the position of the root.\n const { part: rootPart, score: rootScore } = root;\n const rootPoint = vectors.getImageCoords(rootPart, outputStride, offsets);\n instanceKeypoints[rootPart.id] = {\n score: rootScore,\n part: keypoints.partNames[rootPart.id],\n position: rootPoint,\n };\n // Decode the part positions upwards in the tree, following the backward\n // displacements.\n for (let edge = numEdges - 1; edge >= 0; --edge) {\n const sourceKeypointId = parentToChildEdges[edge];\n const targetKeypointId = childToParentEdges[edge];\n if (instanceKeypoints[sourceKeypointId] && !instanceKeypoints[targetKeypointId]) {\n instanceKeypoints[targetKeypointId] = traverseToTargetKeypoint(edge, instanceKeypoints[sourceKeypointId], targetKeypointId, scores, offsets, outputStride, displacementsBwd);\n }\n }\n // Decode the part positions downwards in the tree, following the forward\n // displacements.\n for (let edge = 0; edge < numEdges; ++edge) {\n const sourceKeypointId = childToParentEdges[edge];\n const targetKeypointId = parentToChildEdges[edge];\n if (instanceKeypoints[sourceKeypointId] && !instanceKeypoints[targetKeypointId]) {\n instanceKeypoints[targetKeypointId] = traverseToTargetKeypoint(edge, instanceKeypoints[sourceKeypointId], targetKeypointId, scores, offsets, outputStride, displacementsFwd);\n }\n }\n return instanceKeypoints;\n}\nexports.decodePose = decodePose;\n", "const buildParts = require('./buildParts');\nconst decodePose = require('./decodePose');\nconst vectors = require('./vectors');\n\nfunction withinNmsRadiusOfCorrespondingPoint(poses, squaredNmsRadius, { x, y }, keypointId) {\n return poses.some(({ keypoints }) => {\n const correspondingKeypoint = keypoints[keypointId].position;\n return vectors.squaredDistance(y, x, correspondingKeypoint.y, correspondingKeypoint.x) <= squaredNmsRadius;\n });\n}\n/* Score the newly proposed object instance without taking into account\n * the scores of the parts that overlap with any previously detected\n * instance.\n */\nfunction getInstanceScore(existingPoses, squaredNmsRadius, instanceKeypoints) {\n const notOverlappedKeypointScores = instanceKeypoints.reduce((result, { position, score }, keypointId) => {\n if (!withinNmsRadiusOfCorrespondingPoint(existingPoses, squaredNmsRadius, position, keypointId)) {\n result += score;\n }\n return result;\n }, 0.0);\n return notOverlappedKeypointScores / instanceKeypoints.length;\n}\n// A point (y, x) is considered as root part candidate if its score is a\n// maximum in a window |y - y'| <= kLocalMaximumRadius, |x - x'| <=\n// kLocalMaximumRadius.\nconst kLocalMaximumRadius = 1;\n/**\n * Detects multiple poses and finds their parts from part scores and\n * displacement vectors. It returns up to `maxDetections` object instance\n * detections in decreasing root score order. It works as follows: We first\n * create a priority queue with local part score maxima above\n * `scoreThreshold`, considering all parts at the same time. Then we\n * iteratively pull the top element of the queue (in decreasing score order)\n * and treat it as a root candidate for a new object instance. To avoid\n * duplicate detections, we reject the root candidate if it is within a disk\n * of `nmsRadius` pixels from the corresponding part of a previously detected\n * instance, which is a form of part-based non-maximum suppression (NMS). If\n * the root candidate passes the NMS check, we start a new object instance\n * detection, treating the corresponding part as root and finding the\n * positions of the remaining parts by following the displacement vectors\n * along the tree-structured part graph. We assign to the newly detected\n * instance a score equal to the sum of scores of its parts which have not\n * been claimed by a previous instance (i.e., those at least `nmsRadius`\n * pixels away from the corresponding part of all previously detected\n * instances), divided by the total number of parts `numParts`.\n *\n * @param heatmapScores 3-D tensor with shape `[height, width, numParts]`.\n * The value of heatmapScores[y, x, k]` is the score of placing the `k`-th\n * object part at position `(y, x)`.\n *\n * @param offsets 3-D tensor with shape `[height, width, numParts * 2]`.\n * The value of [offsets[y, x, k], offsets[y, x, k + numParts]]` is the\n * short range offset vector of the `k`-th object part at heatmap\n * position `(y, x)`.\n *\n * @param displacementsFwd 3-D tensor of shape\n * `[height, width, 2 * num_edges]`, where `num_edges = num_parts - 1` is the\n * number of edges (parent-child pairs) in the tree. It contains the forward\n * displacements between consecutive part from the root towards the leaves.\n *\n * @param displacementsBwd 3-D tensor of shape\n * `[height, width, 2 * num_edges]`, where `num_edges = num_parts - 1` is the\n * number of edges (parent-child pairs) in the tree. It contains the backward\n * displacements between consecutive part from the root towards the leaves.\n *\n * @param outputStride The output stride that was used when feed-forwarding\n * through the PoseNet model. Must be 32, 16, or 8.\n *\n * @param maxPoseDetections Maximum number of returned instance detections per\n * image.\n *\n * @param scoreThreshold Only return instance detections that have root part\n * score greater or equal to this value. Defaults to 0.5.\n *\n * @param nmsRadius Non-maximum suppression part distance. It needs to be\n * strictly positive. Two parts suppress each other if they are less than\n * `nmsRadius` pixels away. Defaults to 20.\n *\n * @return An array of poses and their scores, each containing keypoints and\n * the corresponding keypoint scores.\n */\nfunction decodeMultiplePoses(scoresBuffer, offsetsBuffer, displacementsFwdBuffer, displacementsBwdBuffer, outputStride, maxPoseDetections, scoreThreshold = 0.5, nmsRadius = 20) {\n const poses = [];\n const queue = buildParts.buildPartWithScoreQueue(scoreThreshold, kLocalMaximumRadius, scoresBuffer);\n const squaredNmsRadius = nmsRadius * nmsRadius;\n // Generate at most maxDetections object instances per image in\n // decreasing root part score order.\n while (poses.length < maxPoseDetections && !queue.empty()) {\n // The top element in the queue is the next root candidate.\n const root = queue.dequeue();\n // Part-based non-maximum suppression: We reject a root candidate if it\n // is within a disk of `nmsRadius` pixels from the corresponding part of\n // a previously detected instance.\n const rootImageCoords = vectors.getImageCoords(root.part, outputStride, offsetsBuffer);\n if (withinNmsRadiusOfCorrespondingPoint(poses, squaredNmsRadius, rootImageCoords, root.part.id)) continue;\n // Start a new detection instance at the position of the root.\n const keypoints = decodePose.decodePose(root, scoresBuffer, offsetsBuffer, outputStride, displacementsFwdBuffer, displacementsBwdBuffer);\n const score = getInstanceScore(poses, squaredNmsRadius, keypoints);\n poses.push({ keypoints, score });\n }\n return poses;\n}\nexports.decodeMultiplePoses = decodeMultiplePoses;\n", "const kpt = require('./keypoints');\n\nfunction eitherPointDoesntMeetConfidence(a, b, minConfidence) {\n return (a < minConfidence || b < minConfidence);\n}\n\nfunction getAdjacentKeyPoints(keypoints, minConfidence) {\n return kpt.connectedPartIndices.reduce((result, [leftJoint, rightJoint]) => {\n if (eitherPointDoesntMeetConfidence(keypoints[leftJoint].score, keypoints[rightJoint].score, minConfidence)) {\n return result;\n }\n result.push([keypoints[leftJoint], keypoints[rightJoint]]);\n return result;\n }, []);\n}\nexports.getAdjacentKeyPoints = getAdjacentKeyPoints;\n\nconst { NEGATIVE_INFINITY, POSITIVE_INFINITY } = Number;\nfunction getBoundingBox(keypoints) {\n return keypoints.reduce(({ maxX, maxY, minX, minY }, { position: { x, y } }) => ({\n maxX: Math.max(maxX, x),\n maxY: Math.max(maxY, y),\n minX: Math.min(minX, x),\n minY: Math.min(minY, y),\n }), {\n maxX: NEGATIVE_INFINITY,\n maxY: NEGATIVE_INFINITY,\n minX: POSITIVE_INFINITY,\n minY: POSITIVE_INFINITY,\n });\n}\nexports.getBoundingBox = getBoundingBox;\nfunction getBoundingBoxPoints(keypoints) {\n const { minX, minY, maxX, maxY } = getBoundingBox(keypoints);\n return [{ x: minX, y: minY }, { x: maxX, y: minY }, { x: maxX, y: maxY }, { x: minX, y: maxY }];\n}\nexports.getBoundingBoxPoints = getBoundingBoxPoints;\nasync function toTensorBuffers3D(tensors) {\n return Promise.all(tensors.map((tensor) => tensor.buffer()));\n}\nexports.toTensorBuffers3D = toTensorBuffers3D;\n\nfunction scalePose(pose, scaleY, scaleX) {\n return {\n score: pose.score,\n keypoints: pose.keypoints.map(({ score, part, position }) => ({\n score,\n part,\n position: { x: position.x * scaleX, y: position.y * scaleY },\n })),\n };\n}\nexports.scalePose = scalePose;\n\nfunction resizeTo(image, [targetH, targetW]) {\n const input = image.squeeze(0);\n const resized = input.resizeBilinear([targetH, targetW]);\n input.dispose();\n return resized;\n}\nexports.resizeTo = resizeTo;\n\nfunction scaleAndFlipPoses(poses, [height, width], [inputResolutionHeight, inputResolutionWidth]) {\n const scaledPoses = poses.map((pose) => scalePose(pose, height / inputResolutionHeight, width / inputResolutionWidth));\n return scaledPoses;\n}\nexports.scaleAndFlipPoses = scaleAndFlipPoses;\n", "const tf = require('@tensorflow/tfjs');\nconst modelMobileNet = require('./modelMobileNet');\nconst decodeMultiple = require('./decodeMultiple');\nconst util = require('./util');\n\nclass PoseNet {\n constructor(net) {\n this.baseModel = net;\n }\n\n /**\n * Infer through PoseNet, and estimates multiple poses using the outputs.\n * This does standard ImageNet pre-processing before inferring through the\n * model. The image should pixels should have values [0-255]. It detects\n * multiple poses and finds their parts from part scores and displacement\n * vectors using a fast greedy decoding algorithm. It returns up to\n * `config.maxDetections` object instance detections in decreasing root\n * score order.\n *\n * @param input\n * ImageData|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement) The input\n * image to feed through the network.\n *\n * @param config MultiPoseEstimationConfig object that contains parameters\n * for the PoseNet inference using multiple pose estimation.\n *\n * @return An array of poses and their scores, each containing keypoints and\n * the corresponding keypoint scores. The positions of the keypoints are\n * in the same scale as the original image\n */\n async estimatePoses(input, config) {\n const outputStride = config.outputStride;\n // const inputResolution = config.inputResolution;\n const height = input.shape[1];\n const width = input.shape[2];\n const resized = util.resizeTo(input, [config.inputResolution, config.inputResolution]);\n const { heatmapScores, offsets, displacementFwd, displacementBwd } = this.baseModel.predict(resized);\n const allTensorBuffers = await util.toTensorBuffers3D([heatmapScores, offsets, displacementFwd, displacementBwd]);\n const scoresBuffer = allTensorBuffers[0];\n const offsetsBuffer = allTensorBuffers[1];\n const displacementsFwdBuffer = allTensorBuffers[2];\n const displacementsBwdBuffer = allTensorBuffers[3];\n const poses = await decodeMultiple.decodeMultiplePoses(scoresBuffer, offsetsBuffer, displacementsFwdBuffer, displacementsBwdBuffer, outputStride, config.maxDetections, config.scoreThreshold, config.nmsRadius);\n const resultPoses = util.scaleAndFlipPoses(poses, [height, width], [config.inputResolution, config.inputResolution]);\n heatmapScores.dispose();\n offsets.dispose();\n displacementFwd.dispose();\n displacementBwd.dispose();\n resized.dispose();\n return resultPoses;\n }\n\n dispose() {\n this.baseModel.dispose();\n }\n}\nexports.PoseNet = PoseNet;\nasync function loadMobileNet(config) {\n const graphModel = await tf.loadGraphModel(config.modelPath);\n const mobilenet = new modelMobileNet.MobileNet(graphModel, config.outputStride);\n return new PoseNet(mobilenet);\n}\n/**\n * Loads the PoseNet model instance from a checkpoint, with the MobileNet architecture. The model to be loaded is configurable using the\n * config dictionary ModelConfig. Please find more details in the documentation of the ModelConfig.\n *\n * @param config ModelConfig dictionary that contains parameters for\n * the PoseNet loading process. Please find more details of each parameters\n * in the documentation of the ModelConfig interface. The predefined\n * `MOBILENET_V1_CONFIG` and `RESNET_CONFIG` can also be used as references\n * for defining your customized config.\n */\nasync function load(config) {\n return loadMobileNet(config);\n}\nexports.load = load;\n", "const modelMobileNet = require('./modelMobileNet');\nconst modelPoseNet = require('./modelPoseNet');\nconst decodeMultiple = require('./decodeMultiple');\nconst keypoints = require('./keypoints');\nconst util = require('./util');\n\nexports.load = modelPoseNet.load;\nexports.PoseNet = modelPoseNet.PoseNet;\n\nexports.MobileNet = modelMobileNet.MobileNet;\nexports.decodeMultiplePoses = decodeMultiple.decodeMultiplePoses;\nexports.partChannels = keypoints.partChannels;\nexports.partIds = keypoints.partIds;\nexports.partNames = keypoints.partNames;\nexports.poseChain = keypoints.poseChain;\nexports.getAdjacentKeyPoints = util.getAdjacentKeyPoints;\nexports.getBoundingBox = util.getBoundingBox;\nexports.getBoundingBoxPoints = util.getBoundingBoxPoints;\nexports.scaleAndFlipPoses = util.scaleAndFlipPoses;\nexports.scalePose = util.scalePose;\n", "const tf = require('@tensorflow/tfjs');\n\nfunction getBoxSize(box) {\n return [\n Math.abs(box.endPoint[0] - box.startPoint[0]),\n Math.abs(box.endPoint[1] - box.startPoint[1]),\n ];\n}\nexports.getBoxSize = getBoxSize;\n\nfunction getBoxCenter(box) {\n return [\n box.startPoint[0] + (box.endPoint[0] - box.startPoint[0]) / 2,\n box.startPoint[1] + (box.endPoint[1] - box.startPoint[1]) / 2,\n ];\n}\nexports.getBoxCenter = getBoxCenter;\n\nfunction cutBoxFromImageAndResize(box, image, cropSize) {\n const h = image.shape[1];\n const w = image.shape[2];\n const boxes = [[\n box.startPoint[1] / h, box.startPoint[0] / w, box.endPoint[1] / h,\n box.endPoint[0] / w,\n ]];\n return tf.image.cropAndResize(image, boxes, [0], cropSize);\n}\nexports.cutBoxFromImageAndResize = cutBoxFromImageAndResize;\n\nfunction scaleBoxCoordinates(box, factor) {\n const startPoint = [box.startPoint[0] * factor[0], box.startPoint[1] * factor[1]];\n const endPoint = [box.endPoint[0] * factor[0], box.endPoint[1] * factor[1]];\n const palmLandmarks = box.palmLandmarks.map((coord) => {\n const scaledCoord = [coord[0] * factor[0], coord[1] * factor[1]];\n return scaledCoord;\n });\n return { startPoint, endPoint, palmLandmarks };\n}\nexports.scaleBoxCoordinates = scaleBoxCoordinates;\n\nfunction enlargeBox(box, factor = 1.5) {\n const center = getBoxCenter(box);\n const size = getBoxSize(box);\n const newHalfSize = [factor * size[0] / 2, factor * size[1] / 2];\n const startPoint = [center[0] - newHalfSize[0], center[1] - newHalfSize[1]];\n const endPoint = [center[0] + newHalfSize[0], center[1] + newHalfSize[1]];\n return { startPoint, endPoint, palmLandmarks: box.palmLandmarks };\n}\nexports.enlargeBox = enlargeBox;\n\nfunction squarifyBox(box) {\n const centers = getBoxCenter(box);\n const size = getBoxSize(box);\n const maxEdge = Math.max(...size);\n const halfSize = maxEdge / 2;\n const startPoint = [centers[0] - halfSize, centers[1] - halfSize];\n const endPoint = [centers[0] + halfSize, centers[1] + halfSize];\n return { startPoint, endPoint, palmLandmarks: box.palmLandmarks };\n}\nexports.squarifyBox = squarifyBox;\n\nfunction shiftBox(box, shiftFactor) {\n const boxSize = [\n box.endPoint[0] - box.startPoint[0], box.endPoint[1] - box.startPoint[1],\n ];\n const shiftVector = [boxSize[0] * shiftFactor[0], boxSize[1] * shiftFactor[1]];\n const startPoint = [box.startPoint[0] + shiftVector[0], box.startPoint[1] + shiftVector[1]];\n const endPoint = [box.endPoint[0] + shiftVector[0], box.endPoint[1] + shiftVector[1]];\n return { startPoint, endPoint, palmLandmarks: box.palmLandmarks };\n}\nexports.shiftBox = shiftBox;\n", "const tf = require('@tensorflow/tfjs');\nconst bounding = require('./box');\n\nclass HandDetector {\n constructor(model, anchors, config) {\n this.model = model;\n this.width = config.inputSize;\n this.height = config.inputSize;\n this.anchors = anchors.map((anchor) => [anchor.x_center, anchor.y_center]);\n this.anchorsTensor = tf.tensor2d(this.anchors);\n this.inputSizeTensor = tf.tensor1d([config.inputSize, config.inputSize]);\n this.doubleInputSizeTensor = tf.tensor1d([config.inputSize * 2, config.inputSize * 2]);\n }\n\n normalizeBoxes(boxes) {\n return tf.tidy(() => {\n const boxOffsets = tf.slice(boxes, [0, 0], [-1, 2]);\n const boxSizes = tf.slice(boxes, [0, 2], [-1, 2]);\n const boxCenterPoints = tf.add(tf.div(boxOffsets, this.inputSizeTensor), this.anchorsTensor);\n const halfBoxSizes = tf.div(boxSizes, this.doubleInputSizeTensor);\n const startPoints = tf.mul(tf.sub(boxCenterPoints, halfBoxSizes), this.inputSizeTensor);\n const endPoints = tf.mul(tf.add(boxCenterPoints, halfBoxSizes), this.inputSizeTensor);\n return tf.concat2d([startPoints, endPoints], 1);\n });\n }\n\n normalizeLandmarks(rawPalmLandmarks, index) {\n return tf.tidy(() => {\n const landmarks = tf.add(tf.div(rawPalmLandmarks.reshape([-1, 7, 2]), this.inputSizeTensor), this.anchors[index]);\n return tf.mul(landmarks, this.inputSizeTensor);\n });\n }\n\n async getBoundingBoxes(input) {\n const batchedPrediction = this.model.predict(input);\n const prediction = batchedPrediction.squeeze();\n // Regression score for each anchor point.\n const scores = tf.tidy(() => tf.sigmoid(tf.slice(prediction, [0, 0], [-1, 1])).squeeze());\n // Bounding box for each anchor point.\n const rawBoxes = tf.slice(prediction, [0, 1], [-1, 4]);\n const boxes = this.normalizeBoxes(rawBoxes);\n const boxesWithHandsTensor = await tf.image.nonMaxSuppressionAsync(boxes, scores, this.maxHands, this.iouThreshold, this.scoreThreshold);\n const boxesWithHands = await boxesWithHandsTensor.array();\n const toDispose = [batchedPrediction, boxesWithHandsTensor, prediction, boxes, rawBoxes, scores];\n const detectedHands = tf.tidy(() => {\n const detectedBoxes = [];\n for (const i in boxesWithHands) {\n const boxIndex = boxesWithHands[i];\n const matchingBox = tf.slice(boxes, [boxIndex, 0], [1, -1]);\n const rawPalmLandmarks = tf.slice(prediction, [boxIndex, 5], [1, 14]);\n const palmLandmarks = tf.tidy(() => this.normalizeLandmarks(rawPalmLandmarks, boxIndex).reshape([-1, 2]));\n detectedBoxes.push({ boxes: matchingBox, palmLandmarks });\n }\n return detectedBoxes;\n });\n toDispose.forEach((tensor) => tensor.dispose());\n return detectedHands;\n }\n\n /**\n * Returns a Box identifying the bounding box of a hand within the image.\n * Returns null if there is no hand in the image.\n *\n * @param input The image to classify.\n */\n async estimateHandBounds(input, config) {\n // const inputHeight = input.shape[2];\n // const inputWidth = input.shape[1];\n this.iouThreshold = config.iouThreshold;\n this.scoreThreshold = config.scoreThreshold;\n this.maxHands = config.maxHands;\n const resized = input.resizeBilinear([this.width, this.height]);\n const divided = resized.div(255);\n const normalized = divided.sub(0.5);\n const image = normalized.mul(2.0);\n resized.dispose();\n divided.dispose();\n normalized.dispose();\n const predictions = await this.getBoundingBoxes(image);\n image.dispose();\n if (!predictions || (predictions.length === 0)) return null;\n const hands = [];\n for (const i in predictions) {\n const prediction = predictions[i];\n const boundingBoxes = await prediction.boxes.array();\n const startPoint = boundingBoxes[0].slice(0, 2);\n const endPoint = boundingBoxes[0].slice(2, 4);\n const palmLandmarks = await prediction.palmLandmarks.array();\n prediction.boxes.dispose();\n prediction.palmLandmarks.dispose();\n hands.push(bounding.scaleBoxCoordinates({ startPoint, endPoint, palmLandmarks }, [input.shape[2] / this.width, input.shape[1] / this.height]));\n }\n return hands;\n }\n}\nexports.HandDetector = HandDetector;\n", "exports.MESH_ANNOTATIONS = {\n thumb: [1, 2, 3, 4],\n indexFinger: [5, 6, 7, 8],\n middleFinger: [9, 10, 11, 12],\n ringFinger: [13, 14, 15, 16],\n pinky: [17, 18, 19, 20],\n palmBase: [0],\n};\n", "function normalizeRadians(angle) {\n return angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));\n}\nexports.normalizeRadians = normalizeRadians;\n\nfunction computeRotation(point1, point2) {\n const radians = Math.PI / 2 - Math.atan2(-(point2[1] - point1[1]), point2[0] - point1[0]);\n return normalizeRadians(radians);\n}\nexports.computeRotation = computeRotation;\n\nconst buildTranslationMatrix = (x, y) => ([[1, 0, x], [0, 1, y], [0, 0, 1]]);\nfunction dot(v1, v2) {\n let product = 0;\n for (let i = 0; i < v1.length; i++) {\n product += v1[i] * v2[i];\n }\n return product;\n}\nexports.dot = dot;\n\nfunction getColumnFrom2DArr(arr, columnIndex) {\n const column = [];\n for (let i = 0; i < arr.length; i++) {\n column.push(arr[i][columnIndex]);\n }\n return column;\n}\nexports.getColumnFrom2DArr = getColumnFrom2DArr;\n\nfunction multiplyTransformMatrices(mat1, mat2) {\n const product = [];\n const size = mat1.length;\n for (let row = 0; row < size; row++) {\n product.push([]);\n for (let col = 0; col < size; col++) {\n product[row].push(dot(mat1[row], getColumnFrom2DArr(mat2, col)));\n }\n }\n return product;\n}\nfunction buildRotationMatrix(rotation, center) {\n const cosA = Math.cos(rotation);\n const sinA = Math.sin(rotation);\n const rotationMatrix = [[cosA, -sinA, 0], [sinA, cosA, 0], [0, 0, 1]];\n const translationMatrix = buildTranslationMatrix(center[0], center[1]);\n const translationTimesRotation = multiplyTransformMatrices(translationMatrix, rotationMatrix);\n const negativeTranslationMatrix = buildTranslationMatrix(-center[0], -center[1]);\n return multiplyTransformMatrices(translationTimesRotation, negativeTranslationMatrix);\n}\nexports.buildRotationMatrix = buildRotationMatrix;\n\nfunction invertTransformMatrix(matrix) {\n const rotationComponent = [[matrix[0][0], matrix[1][0]], [matrix[0][1], matrix[1][1]]];\n const translationComponent = [matrix[0][2], matrix[1][2]];\n const invertedTranslation = [\n -dot(rotationComponent[0], translationComponent),\n -dot(rotationComponent[1], translationComponent),\n ];\n return [\n rotationComponent[0].concat(invertedTranslation[0]),\n rotationComponent[1].concat(invertedTranslation[1]),\n [0, 0, 1],\n ];\n}\nexports.invertTransformMatrix = invertTransformMatrix;\n\nfunction rotatePoint(homogeneousCoordinate, rotationMatrix) {\n return [\n dot(homogeneousCoordinate, rotationMatrix[0]),\n dot(homogeneousCoordinate, rotationMatrix[1]),\n ];\n}\nexports.rotatePoint = rotatePoint;\n", "const tf = require('@tensorflow/tfjs');\nconst bounding = require('./box');\nconst util = require('./util');\n\nconst UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD = 0.8;\nconst PALM_BOX_SHIFT_VECTOR = [0, -0.4];\nconst HAND_BOX_SHIFT_VECTOR = [0, -0.1];\nconst HAND_BOX_ENLARGE_FACTOR = 1.65;\nconst PALM_LANDMARK_IDS = [0, 5, 9, 13, 17, 1, 2];\nconst PALM_LANDMARKS_INDEX_OF_PALM_BASE = 0;\nconst PALM_LANDMARKS_INDEX_OF_MIDDLE_FINGER_BASE = 2;\n\n// The Pipeline coordinates between the bounding box and skeleton models.\nclass HandPipeline {\n constructor(boundingBoxDetector, meshDetector, config) {\n this.regionsOfInterest = [];\n this.runsWithoutHandDetector = 0;\n this.boundingBoxDetector = boundingBoxDetector;\n this.meshDetector = meshDetector;\n this.meshWidth = config.inputSize;\n this.meshHeight = config.inputSize;\n this.enlargeFactor = config.enlargeFactor;\n }\n\n // Get the bounding box surrounding the hand, given palm landmarks.\n getBoxForPalmLandmarks(palmLandmarks, rotationMatrix) {\n const rotatedPalmLandmarks = palmLandmarks.map((coord) => {\n const homogeneousCoordinate = [...coord, 1];\n return util.rotatePoint(homogeneousCoordinate, rotationMatrix);\n });\n const boxAroundPalm = this.calculateLandmarksBoundingBox(rotatedPalmLandmarks);\n // boxAroundPalm only surrounds the palm - therefore we shift it\n // upwards so it will capture fingers once enlarged + squarified.\n return bounding.enlargeBox(bounding.squarifyBox(bounding.shiftBox(boxAroundPalm, PALM_BOX_SHIFT_VECTOR)), this.enlargeFactor);\n }\n\n // Get the bounding box surrounding the hand, given all hand landmarks.\n getBoxForHandLandmarks(landmarks) {\n // The MediaPipe hand mesh model is trained on hands with empty space\n // around them, so we still need to shift / enlarge boxAroundHand even\n // though it surrounds the entire hand.\n const boundingBox = this.calculateLandmarksBoundingBox(landmarks);\n const boxAroundHand = bounding.enlargeBox(bounding.squarifyBox(bounding.shiftBox(boundingBox, HAND_BOX_SHIFT_VECTOR)), HAND_BOX_ENLARGE_FACTOR);\n const palmLandmarks = [];\n for (let i = 0; i < PALM_LANDMARK_IDS.length; i++) {\n palmLandmarks.push(landmarks[PALM_LANDMARK_IDS[i]].slice(0, 2));\n }\n boxAroundHand.palmLandmarks = palmLandmarks;\n return boxAroundHand;\n }\n\n // Scale, rotate, and translate raw keypoints from the model so they map to\n // the input coordinates.\n transformRawCoords(rawCoords, box, angle, rotationMatrix) {\n const boxSize = bounding.getBoxSize(box);\n const scaleFactor = [boxSize[0] / this.meshWidth, boxSize[1] / this.meshHeight];\n const coordsScaled = rawCoords.map((coord) => [\n scaleFactor[0] * (coord[0] - this.meshWidth / 2),\n scaleFactor[1] * (coord[1] - this.meshHeight / 2), coord[2],\n ]);\n const coordsRotationMatrix = util.buildRotationMatrix(angle, [0, 0]);\n const coordsRotated = coordsScaled.map((coord) => {\n const rotated = util.rotatePoint(coord, coordsRotationMatrix);\n return [...rotated, coord[2]];\n });\n const inverseRotationMatrix = util.invertTransformMatrix(rotationMatrix);\n const boxCenter = [...bounding.getBoxCenter(box), 1];\n const originalBoxCenter = [\n util.dot(boxCenter, inverseRotationMatrix[0]),\n util.dot(boxCenter, inverseRotationMatrix[1]),\n ];\n return coordsRotated.map((coord) => [\n coord[0] + originalBoxCenter[0], coord[1] + originalBoxCenter[1],\n coord[2],\n ]);\n }\n\n async estimateHands(image, config) {\n this.skipFrames = config.skipFrames;\n this.detectionConfidence = config.minConfidence;\n this.maxHands = config.maxHands;\n this.runsWithoutHandDetector++;\n const useFreshBox = this.shouldUpdateRegionsOfInterest();\n if (useFreshBox === true) {\n const boundingBoxPredictions = await this.boundingBoxDetector.estimateHandBounds(image, config);\n this.regionsOfInterest = [];\n for (const i in boundingBoxPredictions) {\n this.updateRegionsOfInterest(boundingBoxPredictions[i], true /* force update */, i);\n }\n this.runsWithoutHandDetector = 0;\n }\n // Rotate input so the hand is vertically oriented.\n const hands = [];\n if (!this.regionsOfInterest) return hands;\n for (const i in this.regionsOfInterest) {\n const currentBox = this.regionsOfInterest[i][0];\n if (!currentBox) return hands;\n const angle = util.computeRotation(currentBox.palmLandmarks[PALM_LANDMARKS_INDEX_OF_PALM_BASE], currentBox.palmLandmarks[PALM_LANDMARKS_INDEX_OF_MIDDLE_FINGER_BASE]);\n const palmCenter = bounding.getBoxCenter(currentBox);\n const palmCenterNormalized = [palmCenter[0] / image.shape[2], palmCenter[1] / image.shape[1]];\n const rotatedImage = tf.image.rotateWithOffset(image, angle, 0, palmCenterNormalized);\n const rotationMatrix = util.buildRotationMatrix(-angle, palmCenter);\n const box = useFreshBox ? this.getBoxForPalmLandmarks(currentBox.palmLandmarks, rotationMatrix) : currentBox;\n const croppedInput = bounding.cutBoxFromImageAndResize(box, rotatedImage, [this.meshWidth, this.meshHeight]);\n const handImage = croppedInput.div(255);\n croppedInput.dispose();\n rotatedImage.dispose();\n const prediction = this.meshDetector.predict(handImage);\n const [flag, keypoints] = prediction;\n handImage.dispose();\n const flagValue = flag.dataSync()[0];\n flag.dispose();\n if (flagValue < config.minConfidence) {\n keypoints.dispose();\n this.regionsOfInterest[i] = [];\n return hands;\n }\n const keypointsReshaped = tf.reshape(keypoints, [-1, 3]);\n const rawCoords = await keypointsReshaped.array();\n keypoints.dispose();\n keypointsReshaped.dispose();\n const coords = this.transformRawCoords(rawCoords, box, angle, rotationMatrix);\n const nextBoundingBox = this.getBoxForHandLandmarks(coords);\n this.updateRegionsOfInterest(nextBoundingBox, false /* force replace */, i);\n const result = {\n landmarks: coords,\n confidence: flagValue,\n box: {\n topLeft: nextBoundingBox.startPoint,\n bottomRight: nextBoundingBox.endPoint,\n },\n };\n hands.push(result);\n }\n return hands;\n }\n\n // eslint-disable-next-line class-methods-use-this\n calculateLandmarksBoundingBox(landmarks) {\n const xs = landmarks.map((d) => d[0]);\n const ys = landmarks.map((d) => d[1]);\n const startPoint = [Math.min(...xs), Math.min(...ys)];\n const endPoint = [Math.max(...xs), Math.max(...ys)];\n return { startPoint, endPoint };\n }\n\n // Updates regions of interest if the intersection over union between\n // the incoming and previous regions falls below a threshold.\n updateRegionsOfInterest(box, forceUpdate, index) {\n if (forceUpdate) {\n this.regionsOfInterest[index] = [box];\n } else {\n const previousBox = this.regionsOfInterest[index][0];\n let iou = 0;\n if (previousBox != null && previousBox.startPoint != null) {\n const [boxStartX, boxStartY] = box.startPoint;\n const [boxEndX, boxEndY] = box.endPoint;\n const [previousBoxStartX, previousBoxStartY] = previousBox.startPoint;\n const [previousBoxEndX, previousBoxEndY] = previousBox.endPoint;\n const xStartMax = Math.max(boxStartX, previousBoxStartX);\n const yStartMax = Math.max(boxStartY, previousBoxStartY);\n const xEndMin = Math.min(boxEndX, previousBoxEndX);\n const yEndMin = Math.min(boxEndY, previousBoxEndY);\n const intersection = (xEndMin - xStartMax) * (yEndMin - yStartMax);\n const boxArea = (boxEndX - boxStartX) * (boxEndY - boxStartY);\n const previousBoxArea = (previousBoxEndX - previousBoxStartX) * (previousBoxEndY - boxStartY);\n iou = intersection / (boxArea + previousBoxArea - intersection);\n }\n this.regionsOfInterest[index][0] = iou > UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD ? previousBox : box;\n }\n }\n\n shouldUpdateRegionsOfInterest() {\n return !this.regionsOfInterest || (this.regionsOfInterest.length === 0) || (this.runsWithoutHandDetector >= this.skipFrames);\n }\n}\nexports.HandPipeline = HandPipeline;\n", "const tf = require('@tensorflow/tfjs');\nconst hand = require('./handdetector');\nconst keypoints = require('./keypoints');\nconst pipe = require('./pipeline');\n\nclass HandPose {\n constructor(pipeline) {\n this.pipeline = pipeline;\n }\n\n async estimateHands(input, config) {\n this.skipFrames = config.skipFrames;\n this.detectionConfidence = config.minConfidence;\n this.maxHands = config.maxHands;\n const predictions = await this.pipeline.estimateHands(input, config);\n const hands = [];\n if (!predictions) return hands;\n for (const prediction of predictions) {\n if (!prediction) return [];\n const annotations = {};\n for (const key of Object.keys(keypoints.MESH_ANNOTATIONS)) {\n annotations[key] = keypoints.MESH_ANNOTATIONS[key].map((index) => prediction.landmarks[index]);\n }\n hands.push({\n confidence: prediction.confidence || 0,\n box: prediction.box ? [prediction.box.topLeft[0], prediction.box.topLeft[1], prediction.box.bottomRight[0] - prediction.box.topLeft[0], prediction.box.bottomRight[1] - prediction.box.topLeft[1]] : 0,\n landmarks: prediction.landmarks,\n annotations,\n });\n }\n return hands;\n }\n}\nexports.HandPose = HandPose;\n\nasync function loadAnchors(url) {\n if (tf.env().features.IS_NODE) {\n // eslint-disable-next-line global-require\n const fs = require('fs');\n const data = await fs.readFileSync(url.replace('file://', ''));\n return JSON.parse(data);\n }\n return tf.util.fetch(url).then((d) => d.json());\n}\n\nasync function load(config) {\n const [anchors, handDetectorModel, handPoseModel] = await Promise.all([\n loadAnchors(config.detector.anchors),\n tf.loadGraphModel(config.detector.modelPath, { fromTFHub: config.detector.modelPath.includes('tfhub.dev') }),\n tf.loadGraphModel(config.skeleton.modelPath, { fromTFHub: config.skeleton.modelPath.includes('tfhub.dev') }),\n ]);\n const detector = new hand.HandDetector(handDetectorModel, anchors, config);\n const pipeline = new pipe.HandPipeline(detector, handPoseModel, config);\n const handpose = new HandPose(pipeline);\n return handpose;\n}\nexports.load = load;\n", "/* eslint-disable no-shadow */\n/* eslint-disable prefer-rest-params */\n/* eslint-disable no-sequences */\n/* eslint-disable no-unused-vars */\n/* eslint-disable no-unused-expressions */\n/* eslint-disable no-multi-assign */\n/* eslint-disable no-use-before-define */\n/*\nWebGLImageFilter - MIT Licensed\n2013, Dominic Szablewski - phoboslab.org\n*/\n\nconst WebGLProgram = function (gl, vertexSource, fragmentSource) {\n const _collect = function (source, prefix, collection) {\n const r = new RegExp('\\\\b' + prefix + ' \\\\w+ (\\\\w+)', 'ig');\n source.replace(r, (match, name) => {\n collection[name] = 0;\n return match;\n });\n };\n\n const _compile = function (gl, source, type) {\n const shader = gl.createShader(type);\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n throw new Error('Filter: GL compile failed', gl.getShaderInfoLog(shader));\n }\n return shader;\n };\n\n this.uniform = {};\n this.attribute = {};\n\n const _vsh = _compile(gl, vertexSource, gl.VERTEX_SHADER);\n const _fsh = _compile(gl, fragmentSource, gl.FRAGMENT_SHADER);\n\n this.id = gl.createProgram();\n gl.attachShader(this.id, _vsh);\n gl.attachShader(this.id, _fsh);\n gl.linkProgram(this.id);\n\n if (!gl.getProgramParameter(this.id, gl.LINK_STATUS)) {\n throw new Error('Filter: GL link failed', gl.getProgramInfoLog(this.id));\n }\n\n gl.useProgram(this.id);\n\n // Collect attributes\n _collect(vertexSource, 'attribute', this.attribute);\n for (const a in this.attribute) {\n this.attribute[a] = gl.getAttribLocation(this.id, a);\n }\n\n // Collect uniforms\n _collect(vertexSource, 'uniform', this.uniform);\n _collect(fragmentSource, 'uniform', this.uniform);\n for (const u in this.uniform) {\n this.uniform[u] = gl.getUniformLocation(this.id, u);\n }\n};\n\nconst WebGLImageFilter = function (params) {\n if (!params) params = { };\n let _drawCount = 0;\n let _sourceTexture = null;\n let _lastInChain = false;\n let _currentFramebufferIndex = -1;\n let _tempFramebuffers = [null, null];\n let _filterChain = [];\n let _width = -1;\n let _height = -1;\n let _vertexBuffer = null;\n let _currentProgram = null;\n const _canvas = params.canvas || document.createElement('canvas');\n\n // key is the shader program source, value is the compiled program\n const _shaderProgramCache = { };\n\n const gl = _canvas.getContext('webgl') || _canvas.getContext('experimental-webgl');\n if (!gl) throw new Error('Filter: getContext() failed');\n\n this.addFilter = function (name) {\n const args = Array.prototype.slice.call(arguments, 1);\n const filter = _filter[name];\n\n _filterChain.push({ func: filter, args });\n };\n\n this.reset = function () {\n _filterChain = [];\n };\n\n this.apply = function (image) {\n _resize(image.width, image.height);\n _drawCount = 0;\n\n // Create the texture for the input image if we haven't yet\n if (!_sourceTexture) _sourceTexture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, _sourceTexture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);\n\n // No filters? Just draw\n if (_filterChain.length === 0) {\n const program = _compileShader(SHADER.FRAGMENT_IDENTITY);\n _draw();\n return _canvas;\n }\n\n for (let i = 0; i < _filterChain.length; i++) {\n _lastInChain = (i === _filterChain.length - 1);\n const f = _filterChain[i];\n f.func.apply(this, f.args || []);\n }\n\n return _canvas;\n };\n\n const _resize = function (width, height) {\n // Same width/height? Nothing to do here\n if (width === _width && height === _height) { return; }\n\n _canvas.width = _width = width;\n _canvas.height = _height = height;\n\n // Create the context if we don't have it yet\n if (!_vertexBuffer) {\n // Create the vertex buffer for the two triangles [x, y, u, v] * 6\n const vertices = new Float32Array([\n -1, -1, 0, 1, 1, -1, 1, 1, -1, 1, 0, 0,\n -1, 1, 0, 0, 1, -1, 1, 1, 1, 1, 1, 0,\n ]);\n _vertexBuffer = gl.createBuffer(),\n gl.bindBuffer(gl.ARRAY_BUFFER, _vertexBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);\n\n // Note sure if this is a good idea; at least it makes texture loading\n // in Ejecta instant.\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);\n }\n\n gl.viewport(0, 0, _width, _height);\n\n // Delete old temp framebuffers\n _tempFramebuffers = [null, null];\n };\n\n const _getTempFramebuffer = function (index) {\n _tempFramebuffers[index] = _tempFramebuffers[index]\n || _createFramebufferTexture(_width, _height);\n\n return _tempFramebuffers[index];\n };\n\n const _createFramebufferTexture = function (width, height) {\n const fbo = gl.createFramebuffer();\n gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);\n\n const renderbuffer = gl.createRenderbuffer();\n gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer);\n\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);\n\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n\n return { fbo, texture };\n };\n\n const _draw = function (flags) {\n let source = null;\n let target = null;\n let flipY = false;\n\n // Set up the source\n if (_drawCount === 0) {\n // First draw call - use the source texture\n source = _sourceTexture;\n } else {\n // All following draw calls use the temp buffer last drawn to\n source = _getTempFramebuffer(_currentFramebufferIndex).texture;\n }\n _drawCount++;\n\n // Set up the target\n if (_lastInChain && !(flags & DRAW.INTERMEDIATE)) {\n // Last filter in our chain - draw directly to the WebGL Canvas. We may\n // also have to flip the image vertically now\n target = null;\n flipY = _drawCount % 2 === 0;\n } else {\n // Intermediate draw call - get a temp buffer to draw to\n _currentFramebufferIndex = (_currentFramebufferIndex + 1) % 2;\n target = _getTempFramebuffer(_currentFramebufferIndex).fbo;\n }\n\n // Bind the source and target and draw the two triangles\n gl.bindTexture(gl.TEXTURE_2D, source);\n gl.bindFramebuffer(gl.FRAMEBUFFER, target);\n\n gl.uniform1f(_currentProgram.uniform.flipY, (flipY ? -1 : 1));\n gl.drawArrays(gl.TRIANGLES, 0, 6);\n };\n\n const _compileShader = function (fragmentSource) {\n if (_shaderProgramCache[fragmentSource]) {\n _currentProgram = _shaderProgramCache[fragmentSource];\n gl.useProgram(_currentProgram.id);\n return _currentProgram;\n }\n\n // Compile shaders\n _currentProgram = new WebGLProgram(gl, SHADER.VERTEX_IDENTITY, fragmentSource);\n\n const floatSize = Float32Array.BYTES_PER_ELEMENT;\n const vertSize = 4 * floatSize;\n gl.enableVertexAttribArray(_currentProgram.attribute.pos);\n gl.vertexAttribPointer(_currentProgram.attribute.pos, 2, gl.FLOAT, false, vertSize, 0 * floatSize);\n gl.enableVertexAttribArray(_currentProgram.attribute.uv);\n gl.vertexAttribPointer(_currentProgram.attribute.uv, 2, gl.FLOAT, false, vertSize, 2 * floatSize);\n\n _shaderProgramCache[fragmentSource] = _currentProgram;\n return _currentProgram;\n };\n\n let DRAW = { INTERMEDIATE: 1 };\n\n let SHADER = {};\n SHADER.VERTEX_IDENTITY = [\n 'precision highp float;',\n 'attribute vec2 pos;',\n 'attribute vec2 uv;',\n 'varying vec2 vUv;',\n 'uniform float flipY;',\n\n 'void main(void) {',\n 'vUv = uv;',\n 'gl_Position = vec4(pos.x, pos.y*flipY, 0.0, 1.);',\n '}',\n ].join('\\n');\n\n SHADER.FRAGMENT_IDENTITY = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n\n 'void main(void) {',\n 'gl_FragColor = texture2D(texture, vUv);',\n '}',\n ].join('\\n');\n\n let _filter = {};\n\n // -------------------------------------------------------------------------\n // Color Matrix Filter\n\n _filter.colorMatrix = function (matrix) {\n // Create a Float32 Array and normalize the offset component to 0-1\n const m = new Float32Array(matrix);\n m[4] /= 255;\n m[9] /= 255;\n m[14] /= 255;\n m[19] /= 255;\n\n // Can we ignore the alpha value? Makes things a bit faster.\n const shader = (m[18] === 1 && m[3] === 0 && m[8] === 0 && m[13] === 0 && m[15] === 0 && m[16] === 0 && m[17] === 0 && m[19] === 0)\n ? _filter.colorMatrix.SHADER.WITHOUT_ALPHA\n : _filter.colorMatrix.SHADER.WITH_ALPHA;\n\n const program = _compileShader(shader);\n gl.uniform1fv(program.uniform.m, m);\n _draw();\n };\n\n _filter.colorMatrix.SHADER = {};\n _filter.colorMatrix.SHADER.WITH_ALPHA = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform float m[20];',\n\n 'void main(void) {',\n 'vec4 c = texture2D(texture, vUv);',\n 'gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[3] * c.a + m[4];',\n 'gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[8] * c.a + m[9];',\n 'gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[13] * c.a + m[14];',\n 'gl_FragColor.a = m[15] * c.r + m[16] * c.g + m[17] * c.b + m[18] * c.a + m[19];',\n '}',\n ].join('\\n');\n _filter.colorMatrix.SHADER.WITHOUT_ALPHA = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform float m[20];',\n\n 'void main(void) {',\n 'vec4 c = texture2D(texture, vUv);',\n 'gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[4];',\n 'gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[9];',\n 'gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[14];',\n 'gl_FragColor.a = c.a;',\n '}',\n ].join('\\n');\n\n _filter.brightness = function (brightness) {\n const b = (brightness || 0) + 1;\n _filter.colorMatrix([\n b, 0, 0, 0, 0,\n 0, b, 0, 0, 0,\n 0, 0, b, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.saturation = function (amount) {\n const x = (amount || 0) * 2 / 3 + 1;\n const y = ((x - 1) * -0.5);\n _filter.colorMatrix([\n x, y, y, 0, 0,\n y, x, y, 0, 0,\n y, y, x, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.desaturate = function () {\n _filter.saturation(-1);\n };\n\n _filter.contrast = function (amount) {\n const v = (amount || 0) + 1;\n const o = -128 * (v - 1);\n\n _filter.colorMatrix([\n v, 0, 0, 0, o,\n 0, v, 0, 0, o,\n 0, 0, v, 0, o,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.negative = function () {\n _filter.contrast(-2);\n };\n\n _filter.hue = function (rotation) {\n rotation = (rotation || 0) / 180 * Math.PI;\n const cos = Math.cos(rotation);\n const sin = Math.sin(rotation);\n const lumR = 0.213;\n const lumG = 0.715;\n const lumB = 0.072;\n\n _filter.colorMatrix([\n lumR + cos * (1 - lumR) + sin * (-lumR), lumG + cos * (-lumG) + sin * (-lumG), lumB + cos * (-lumB) + sin * (1 - lumB), 0, 0,\n lumR + cos * (-lumR) + sin * (0.143), lumG + cos * (1 - lumG) + sin * (0.140), lumB + cos * (-lumB) + sin * (-0.283), 0, 0,\n lumR + cos * (-lumR) + sin * (-(1 - lumR)), lumG + cos * (-lumG) + sin * (lumG), lumB + cos * (1 - lumB) + sin * (lumB), 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.desaturateLuminance = function () {\n _filter.colorMatrix([\n 0.2764723, 0.9297080, 0.0938197, 0, -37.1,\n 0.2764723, 0.9297080, 0.0938197, 0, -37.1,\n 0.2764723, 0.9297080, 0.0938197, 0, -37.1,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.sepia = function () {\n _filter.colorMatrix([\n 0.393, 0.7689999, 0.18899999, 0, 0,\n 0.349, 0.6859999, 0.16799999, 0, 0,\n 0.272, 0.5339999, 0.13099999, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.brownie = function () {\n _filter.colorMatrix([\n 0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873,\n -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127,\n 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.vintagePinhole = function () {\n _filter.colorMatrix([\n 0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123,\n 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591,\n 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.kodachrome = function () {\n _filter.colorMatrix([\n 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502,\n -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203,\n -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.technicolor = function () {\n _filter.colorMatrix([\n 1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337,\n -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398,\n -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.polaroid = function () {\n _filter.colorMatrix([\n 1.438, -0.062, -0.062, 0, 0,\n -0.122, 1.378, -0.122, 0, 0,\n -0.016, -0.016, 1.483, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.shiftToBGR = function () {\n _filter.colorMatrix([\n 0, 0, 1, 0, 0,\n 0, 1, 0, 0, 0,\n 1, 0, 0, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n // -------------------------------------------------------------------------\n // Convolution Filter\n\n _filter.convolution = function (matrix) {\n const m = new Float32Array(matrix);\n const pixelSizeX = 1 / _width;\n const pixelSizeY = 1 / _height;\n\n const program = _compileShader(_filter.convolution.SHADER);\n gl.uniform1fv(program.uniform.m, m);\n gl.uniform2f(program.uniform.px, pixelSizeX, pixelSizeY);\n _draw();\n };\n\n _filter.convolution.SHADER = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform vec2 px;',\n 'uniform float m[9];',\n\n 'void main(void) {',\n 'vec4 c11 = texture2D(texture, vUv - px);', // top left\n 'vec4 c12 = texture2D(texture, vec2(vUv.x, vUv.y - px.y));', // top center\n 'vec4 c13 = texture2D(texture, vec2(vUv.x + px.x, vUv.y - px.y));', // top right\n\n 'vec4 c21 = texture2D(texture, vec2(vUv.x - px.x, vUv.y) );', // mid left\n 'vec4 c22 = texture2D(texture, vUv);', // mid center\n 'vec4 c23 = texture2D(texture, vec2(vUv.x + px.x, vUv.y) );', // mid right\n\n 'vec4 c31 = texture2D(texture, vec2(vUv.x - px.x, vUv.y + px.y) );', // bottom left\n 'vec4 c32 = texture2D(texture, vec2(vUv.x, vUv.y + px.y) );', // bottom center\n 'vec4 c33 = texture2D(texture, vUv + px );', // bottom right\n\n 'gl_FragColor = ',\n 'c11 * m[0] + c12 * m[1] + c22 * m[2] +',\n 'c21 * m[3] + c22 * m[4] + c23 * m[5] +',\n 'c31 * m[6] + c32 * m[7] + c33 * m[8];',\n 'gl_FragColor.a = c22.a;',\n '}',\n ].join('\\n');\n\n _filter.detectEdges = function () {\n _filter.convolution.call(this, [\n 0, 1, 0,\n 1, -4, 1,\n 0, 1, 0,\n ]);\n };\n\n _filter.sobelX = function () {\n _filter.convolution.call(this, [\n -1, 0, 1,\n -2, 0, 2,\n -1, 0, 1,\n ]);\n };\n\n _filter.sobelY = function () {\n _filter.convolution.call(this, [\n -1, -2, -1,\n 0, 0, 0,\n 1, 2, 1,\n ]);\n };\n\n _filter.sharpen = function (amount) {\n const a = amount || 1;\n _filter.convolution.call(this, [\n 0, -1 * a, 0,\n -1 * a, 1 + 4 * a, -1 * a,\n 0, -1 * a, 0,\n ]);\n };\n\n _filter.emboss = function (size) {\n const s = size || 1;\n _filter.convolution.call(this, [\n -2 * s, -1 * s, 0,\n -1 * s, 1, 1 * s,\n 0, 1 * s, 2 * s,\n ]);\n };\n\n // -------------------------------------------------------------------------\n // Blur Filter\n\n _filter.blur = function (size) {\n const blurSizeX = (size / 7) / _width;\n const blurSizeY = (size / 7) / _height;\n\n const program = _compileShader(_filter.blur.SHADER);\n\n // Vertical\n gl.uniform2f(program.uniform.px, 0, blurSizeY);\n _draw(DRAW.INTERMEDIATE);\n\n // Horizontal\n gl.uniform2f(program.uniform.px, blurSizeX, 0);\n _draw();\n };\n\n _filter.blur.SHADER = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform vec2 px;',\n\n 'void main(void) {',\n 'gl_FragColor = vec4(0.0);',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-7.0*px.x, -7.0*px.y))*0.0044299121055113265;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-6.0*px.x, -6.0*px.y))*0.00895781211794;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-5.0*px.x, -5.0*px.y))*0.0215963866053;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-4.0*px.x, -4.0*px.y))*0.0443683338718;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-3.0*px.x, -3.0*px.y))*0.0776744219933;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-2.0*px.x, -2.0*px.y))*0.115876621105;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-1.0*px.x, -1.0*px.y))*0.147308056121;',\n 'gl_FragColor += texture2D(texture, vUv )*0.159576912161;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 1.0*px.x, 1.0*px.y))*0.147308056121;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 2.0*px.x, 2.0*px.y))*0.115876621105;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 3.0*px.x, 3.0*px.y))*0.0776744219933;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 4.0*px.x, 4.0*px.y))*0.0443683338718;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 5.0*px.x, 5.0*px.y))*0.0215963866053;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 6.0*px.x, 6.0*px.y))*0.00895781211794;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 7.0*px.x, 7.0*px.y))*0.0044299121055113265;',\n '}',\n ].join('\\n');\n\n // -------------------------------------------------------------------------\n // Pixelate Filter\n\n _filter.pixelate = function (size) {\n const blurSizeX = (size) / _width;\n const blurSizeY = (size) / _height;\n\n const program = _compileShader(_filter.pixelate.SHADER);\n\n // Horizontal\n gl.uniform2f(program.uniform.size, blurSizeX, blurSizeY);\n _draw();\n };\n\n _filter.pixelate.SHADER = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform vec2 size;',\n 'uniform sampler2D texture;',\n\n 'vec2 pixelate(vec2 coord, vec2 size) {',\n 'return floor( coord / size ) * size;',\n '}',\n\n 'void main(void) {',\n 'gl_FragColor = vec4(0.0);',\n 'vec2 coord = pixelate(vUv, size);',\n 'gl_FragColor += texture2D(texture, coord);',\n '}',\n ].join('\\n');\n};\n\nexports.Canvas = WebGLImageFilter;\n", "/* eslint-disable indent */\n/* eslint-disable no-multi-spaces */\n\nexport default {\n backend: 'webgl', // select tfjs backend to use\n console: true, // enable debugging output to console\n scoped: false, // enable scoped runs\n // some models *may* have memory leaks, this wrapps everything in a local scope at a cost of performance\n // typically not needed\n videoOptimized: true, // perform additional optimizations when input is video, must be disabled for images\n filter: {\n enabled: true, // enable image pre-processing filters\n return: true, // return processed canvas imagedata in result\n brightness: 0, // range: -1 (darken) to 1 (lighten)\n contrast: 0, // range: -1 (reduce contrast) to 1 (increase contrast)\n sharpness: 0, // range: 0 (no sharpening) to 1 (maximum sharpening)\n blur: 0, // range: 0 (no blur) to N (blur radius in pixels)\n saturation: 0, // range: -1 (reduce saturation) to 1 (increase saturation)\n hue: 0, // range: 0 (no change) to 360 (hue rotation in degrees)\n negative: false, // image negative\n sepia: false, // image sepia colors\n vintage: false, // image vintage colors\n kodachrome: false, // image kodachrome colors\n technicolor: false, // image technicolor colors\n polaroid: false, // image polaroid camera effect\n pixelate: 0, // range: 0 (no pixelate) to N (number of pixels to pixelate)\n },\n face: {\n enabled: true, // controls if specified modul is enabled\n // face.enabled is required for all face models: detector, mesh, iris, age, gender, emotion\n // (note: module is not loaded until it is required)\n detector: {\n modelPath: '../models/blazeface/back/model.json', // can be 'front' or 'back'.\n // 'front' is optimized for large faces such as front-facing camera and 'back' is optimized for distanct faces.\n inputSize: 256, // fixed value: 128 for front and 256 for 'back'\n maxFaces: 10, // maximum number of faces detected in the input, should be set to the minimum number for performance\n skipFrames: 10, // how many frames to go without re-running the face bounding box detector, only used for video inputs\n // if model is running st 25 FPS, we can re-use existing bounding box for updated face mesh analysis\n // as face probably hasn't moved much in short time (10 * 1/25 = 0.25 sec)\n minConfidence: 0.5, // threshold for discarding a prediction\n iouThreshold: 0.3, // threshold for deciding whether boxes overlap too much in non-maximum suppression\n scoreThreshold: 0.7, // threshold for deciding when to remove boxes based on score in non-maximum suppression\n },\n mesh: {\n enabled: true,\n modelPath: '../models/facemesh/model.json',\n inputSize: 192, // fixed value\n },\n iris: {\n enabled: true,\n modelPath: '../models/iris/model.json',\n enlargeFactor: 2.3, // empiric tuning\n inputSize: 64, // fixed value\n },\n age: {\n enabled: true,\n modelPath: '../models/ssrnet-age/imdb/model.json', // can be 'imdb' or 'wiki'\n // which determines training set for model\n inputSize: 64, // fixed value\n skipFrames: 10, // how many frames to go without re-running the detector, only used for video inputs\n },\n gender: {\n enabled: true,\n minConfidence: 0.8, // threshold for discarding a prediction\n modelPath: '../models/ssrnet-gender/imdb/model.json',\n },\n emotion: {\n enabled: true,\n inputSize: 64, // fixed value\n minConfidence: 0.5, // threshold for discarding a prediction\n skipFrames: 10, // how many frames to go without re-running the detector\n modelPath: '../models/emotion/model.json',\n },\n },\n body: {\n enabled: true,\n modelPath: '../models/posenet/model.json',\n inputResolution: 257, // fixed value\n outputStride: 16, // fixed value\n maxDetections: 10, // maximum number of people detected in the input, should be set to the minimum number for performance\n scoreThreshold: 0.7, // threshold for deciding when to remove boxes based on score in non-maximum suppression\n nmsRadius: 20, // radius for deciding points are too close in non-maximum suppression\n },\n hand: {\n enabled: true,\n inputSize: 256, // fixed value\n skipFrames: 10, // how many frames to go without re-running the hand bounding box detector, only used for video inputs\n // if model is running st 25 FPS, we can re-use existing bounding box for updated hand skeleton analysis\n // as the hand probably hasn't moved much in short time (10 * 1/25 = 0.25 sec)\n minConfidence: 0.5, // threshold for discarding a prediction\n iouThreshold: 0.3, // threshold for deciding whether boxes overlap too much in non-maximum suppression\n scoreThreshold: 0.7, // threshold for deciding when to remove boxes based on score in non-maximum suppression\n enlargeFactor: 1.65, // empiric tuning as skeleton prediction prefers hand box with some whitespace\n maxHands: 10, // maximum number of hands detected in the input, should be set to the minimum number for performance\n detector: {\n anchors: '../models/handdetect/anchors.json',\n modelPath: '../models/handdetect/model.json',\n },\n skeleton: {\n modelPath: '../models/handskeleton/model.json',\n },\n },\n};\n", "const tf = require('@tensorflow/tfjs');\nconst facemesh = require('./facemesh/facemesh.js');\nconst ssrnet = require('./ssrnet/ssrnet.js');\nconst emotion = require('./emotion/emotion.js');\nconst posenet = require('./posenet/posenet.js');\nconst handpose = require('./handpose/handpose.js');\nconst fxImage = require('./imagefx.js');\nconst defaults = require('../config.js').default;\nconst app = require('../package.json');\n\nlet first = true;\n\n// static config override for non-video detection\nconst override = {\n face: { detector: { skipFrames: 0 }, age: { skipFrames: 0 }, emotion: { skipFrames: 0 } },\n hand: { skipFrames: 0 },\n};\n\n// helper function: gets elapsed time on both browser and nodejs\nconst now = () => {\n if (typeof performance !== 'undefined') return performance.now();\n return parseInt(Number(process.hrtime.bigint()) / 1000 / 1000);\n};\n\n// helper function: perform deep merge of multiple objects so it allows full inheriance with overrides\nfunction mergeDeep(...objects) {\n const isObject = (obj) => obj && typeof obj === 'object';\n return objects.reduce((prev, obj) => {\n Object.keys(obj || {}).forEach((key) => {\n const pVal = prev[key];\n const oVal = obj[key];\n if (Array.isArray(pVal) && Array.isArray(oVal)) {\n prev[key] = pVal.concat(...oVal);\n } else if (isObject(pVal) && isObject(oVal)) {\n prev[key] = mergeDeep(pVal, oVal);\n } else {\n prev[key] = oVal;\n }\n });\n return prev;\n }, {});\n}\n\nfunction sanity(input) {\n if (!input) return 'input is not defined';\n if (tf.ENV.flags.IS_NODE && !(input instanceof tf.Tensor)) {\n return 'input must be a tensor';\n }\n try {\n tf.getBackend();\n } catch {\n return 'backend not loaded';\n }\n return null;\n}\n\nclass Human {\n constructor() {\n this.tf = tf;\n this.version = app.version;\n this.defaults = defaults;\n this.config = defaults;\n this.fx = (tf.ENV.flags.IS_BROWSER && (typeof document !== 'undefined')) ? new fxImage.Canvas() : null;\n this.state = 'idle';\n this.numTensors = 0;\n this.analyzeMemoryLeaks = false;\n // object that contains all initialized models\n this.models = {\n facemesh: null,\n posenet: null,\n handpose: null,\n iris: null,\n age: null,\n gender: null,\n emotion: null,\n };\n // export raw access to underlying models\n this.facemesh = facemesh;\n this.ssrnet = ssrnet;\n this.emotion = emotion;\n this.posenet = posenet;\n this.handpose = handpose;\n }\n\n // helper function: wrapper around console output\n log(...msg) {\n // eslint-disable-next-line no-console\n if (msg && this.config.console) console.log(...msg);\n }\n\n // helper function: measure tensor leak\n analyze(...msg) {\n if (!this.analyzeMemoryLeaks) return;\n const current = tf.engine().state.numTensors;\n const previous = this.numTensors;\n this.numTensors = current;\n const leaked = current - previous;\n if (leaked !== 0) this.log(...msg, leaked);\n }\n\n async load(userConfig) {\n if (userConfig) this.config = mergeDeep(defaults, userConfig);\n if (this.config.face.enabled && !this.models.facemesh) {\n this.log('Load model: Face');\n this.models.facemesh = await facemesh.load(this.config.face);\n }\n if (this.config.body.enabled && !this.models.posenet) {\n this.log('Load model: Body');\n this.models.posenet = await posenet.load(this.config.body);\n }\n if (this.config.hand.enabled && !this.models.handpose) {\n this.log('Load model: Hand');\n this.models.handpose = await handpose.load(this.config.hand);\n }\n if (this.config.face.enabled && this.config.face.age.enabled && !this.models.age) {\n this.log('Load model: Age');\n this.models.age = await ssrnet.loadAge(this.config);\n }\n if (this.config.face.enabled && this.config.face.gender.enabled && !this.models.gender) {\n this.log('Load model: Gender');\n this.models.gender = await ssrnet.loadGender(this.config);\n }\n if (this.config.face.enabled && this.config.face.emotion.enabled && !this.models.emotion) {\n this.log('Load model: Emotion');\n this.models.emotion = await emotion.load(this.config);\n }\n }\n\n tfImage(input) {\n // let imageData;\n let filtered;\n if (this.fx && this.config.filter.enabled && !(input instanceof tf.Tensor)) {\n const width = input.naturalWidth || input.videoWidth || input.width || (input.shape && (input.shape[1] > 0));\n const height = input.naturalHeight || input.videoHeight || input.height || (input.shape && (input.shape[2] > 0));\n const offscreenCanvas = new OffscreenCanvas(width, height);\n const ctx = offscreenCanvas.getContext('2d');\n if (input instanceof ImageData) ctx.putImageData(input, 0, 0);\n else ctx.drawImage(input, 0, 0, width, height, 0, 0, offscreenCanvas.width, offscreenCanvas.height);\n this.fx.reset();\n this.fx.addFilter('brightness', this.config.filter.brightness); // must have at least one filter enabled\n if (this.config.filter.contrast !== 0) this.fx.addFilter('contrast', this.config.filter.contrast);\n if (this.config.filter.sharpness !== 0) this.fx.addFilter('sharpen', this.config.filter.sharpness);\n if (this.config.filter.blur !== 0) this.fx.addFilter('blur', this.config.filter.blur);\n if (this.config.filter.saturation !== 0) this.fx.addFilter('saturation', this.config.filter.saturation);\n if (this.config.filter.hue !== 0) this.fx.addFilter('hue', this.config.filter.hue);\n if (this.config.filter.negative) this.fx.addFilter('negative');\n if (this.config.filter.sepia) this.fx.addFilter('sepia');\n if (this.config.filter.vintage) this.fx.addFilter('brownie');\n if (this.config.filter.sepia) this.fx.addFilter('sepia');\n if (this.config.filter.kodachrome) this.fx.addFilter('kodachrome');\n if (this.config.filter.technicolor) this.fx.addFilter('technicolor');\n if (this.config.filter.polaroid) this.fx.addFilter('polaroid');\n if (this.config.filter.pixelate !== 0) this.fx.addFilter('pixelate', this.config.filter.pixelate);\n filtered = this.fx.apply(offscreenCanvas);\n }\n let tensor;\n if (input instanceof tf.Tensor) {\n tensor = tf.clone(input);\n } else {\n const pixels = tf.browser.fromPixels(filtered || input);\n const casted = pixels.toFloat();\n tensor = casted.expandDims(0);\n pixels.dispose();\n casted.dispose();\n }\n return { tensor, canvas: this.config.filter.return ? filtered : null };\n }\n\n async detect(input, userConfig = {}) {\n this.state = 'config';\n const perf = {};\n let timeStamp;\n\n timeStamp = now();\n this.config = mergeDeep(defaults, userConfig);\n if (!this.config.videoOptimized) this.config = mergeDeep(this.config, override);\n perf.config = Math.trunc(now() - timeStamp);\n\n // sanity checks\n timeStamp = now();\n this.state = 'check';\n const error = sanity(input);\n if (error) {\n this.log(error, input);\n return { error };\n }\n perf.sanity = Math.trunc(now() - timeStamp);\n\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve) => {\n const timeStart = now();\n\n // configure backend\n timeStamp = now();\n if (tf.getBackend() !== this.config.backend) {\n this.state = 'backend';\n this.log('Human library setting backend:', this.config.backend);\n await tf.setBackend(this.config.backend);\n await tf.ready();\n }\n perf.backend = Math.trunc(now() - timeStamp);\n\n // check number of loaded models\n if (first) {\n this.log('Human library starting');\n this.log('Configuration:', this.config);\n this.log('Flags:', tf.ENV.flags);\n first = false;\n }\n\n // load models if enabled\n timeStamp = now();\n this.state = 'load';\n await this.load();\n perf.load = Math.trunc(now() - timeStamp);\n\n if (this.config.scoped) tf.engine().startScope();\n\n this.analyze('Start Detect:');\n\n timeStamp = now();\n const image = this.tfImage(input);\n perf.image = Math.trunc(now() - timeStamp);\n const imageTensor = image.tensor;\n\n // run posenet\n this.state = 'run:body';\n timeStamp = now();\n this.analyze('Start PoseNet');\n const poseRes = this.config.body.enabled ? await this.models.posenet.estimatePoses(imageTensor, this.config.body) : [];\n this.analyze('End PoseNet:');\n perf.body = Math.trunc(now() - timeStamp);\n\n // run handpose\n this.state = 'run:hand';\n timeStamp = now();\n this.analyze('Start HandPose:');\n const handRes = this.config.hand.enabled ? await this.models.handpose.estimateHands(imageTensor, this.config.hand) : [];\n this.analyze('End HandPose:');\n perf.hand = Math.trunc(now() - timeStamp);\n\n // run facemesh, includes blazeface and iris\n const faceRes = [];\n if (this.config.face.enabled) {\n this.state = 'run:face';\n timeStamp = now();\n this.analyze('Start FaceMesh:');\n const faces = await this.models.facemesh.estimateFaces(imageTensor, this.config.face);\n perf.face = Math.trunc(now() - timeStamp);\n for (const face of faces) {\n // is something went wrong, skip the face\n if (!face.image || face.image.isDisposedInternal) {\n this.log('face object is disposed:', face.image);\n continue;\n }\n // run ssr-net age & gender, inherits face from blazeface\n this.state = 'run:agegender';\n timeStamp = now();\n const ssrData = (this.config.face.age.enabled || this.config.face.gender.enabled) ? await ssrnet.predict(face.image, this.config) : {};\n perf.agegender = Math.trunc(now() - timeStamp);\n // run emotion, inherits face from blazeface\n this.state = 'run:emotion';\n timeStamp = now();\n const emotionData = this.config.face.emotion.enabled ? await emotion.predict(face.image, this.config) : {};\n perf.emotion = Math.trunc(now() - timeStamp);\n\n // dont need face anymore\n face.image.dispose();\n // calculate iris distance\n // iris: array[ bottom, left, top, right, center ]\n const iris = (face.annotations.leftEyeIris && face.annotations.rightEyeIris)\n ? Math.max(face.annotations.leftEyeIris[3][0] - face.annotations.leftEyeIris[1][0], face.annotations.rightEyeIris[3][0] - face.annotations.rightEyeIris[1][0])\n : 0;\n faceRes.push({\n confidence: face.confidence,\n box: face.box,\n mesh: face.mesh,\n annotations: face.annotations,\n age: ssrData.age,\n gender: ssrData.gender,\n agConfidence: ssrData.confidence,\n emotion: emotionData,\n iris: (iris !== 0) ? Math.trunc(100 * 11.7 /* human iris size in mm */ / iris) / 100 : 0,\n });\n this.analyze('End FaceMesh:');\n }\n }\n\n imageTensor.dispose();\n this.state = 'idle';\n\n if (this.config.scoped) tf.engine().endScope();\n this.analyze('End Scope:');\n\n perf.total = Math.trunc(now() - timeStart);\n resolve({ face: faceRes, body: poseRes, hand: handRes, performance: perf, canvas: image.canvas });\n });\n }\n}\n\nexport { Human as default };\n", "const tf = require('@tensorflow/tfjs');\nconst facemesh = require('./facemesh/facemesh.js');\nconst ssrnet = require('./ssrnet/ssrnet.js');\nconst emotion = require('./emotion/emotion.js');\nconst posenet = require('./posenet/posenet.js');\nconst handpose = require('./handpose/handpose.js');\nconst fxImage = require('./imagefx.js');\nconst defaults = require('../config.js').default;\nconst app = require('../package.json');\n\nlet first = true;\n\n// static config override for non-video detection\nconst override = {\n face: { detector: { skipFrames: 0 }, age: { skipFrames: 0 }, emotion: { skipFrames: 0 } },\n hand: { skipFrames: 0 },\n};\n\n// helper function: gets elapsed time on both browser and nodejs\nconst now = () => {\n if (typeof performance !== 'undefined') return performance.now();\n return parseInt(Number(process.hrtime.bigint()) / 1000 / 1000);\n};\n\n// helper function: perform deep merge of multiple objects so it allows full inheriance with overrides\nfunction mergeDeep(...objects) {\n const isObject = (obj) => obj && typeof obj === 'object';\n return objects.reduce((prev, obj) => {\n Object.keys(obj || {}).forEach((key) => {\n const pVal = prev[key];\n const oVal = obj[key];\n if (Array.isArray(pVal) && Array.isArray(oVal)) {\n prev[key] = pVal.concat(...oVal);\n } else if (isObject(pVal) && isObject(oVal)) {\n prev[key] = mergeDeep(pVal, oVal);\n } else {\n prev[key] = oVal;\n }\n });\n return prev;\n }, {});\n}\n\nfunction sanity(input) {\n if (!input) return 'input is not defined';\n if (tf.ENV.flags.IS_NODE && !(input instanceof tf.Tensor)) {\n return 'input must be a tensor';\n }\n try {\n tf.getBackend();\n } catch {\n return 'backend not loaded';\n }\n return null;\n}\n\nclass Human {\n constructor() {\n this.tf = tf;\n this.version = app.version;\n this.defaults = defaults;\n this.config = defaults;\n this.fx = (tf.ENV.flags.IS_BROWSER && (typeof document !== 'undefined')) ? new fxImage.Canvas() : null;\n this.state = 'idle';\n this.numTensors = 0;\n this.analyzeMemoryLeaks = false;\n // object that contains all initialized models\n this.models = {\n facemesh: null,\n posenet: null,\n handpose: null,\n iris: null,\n age: null,\n gender: null,\n emotion: null,\n };\n // export raw access to underlying models\n this.facemesh = facemesh;\n this.ssrnet = ssrnet;\n this.emotion = emotion;\n this.posenet = posenet;\n this.handpose = handpose;\n }\n\n // helper function: wrapper around console output\n log(...msg) {\n // eslint-disable-next-line no-console\n if (msg && this.config.console) console.log(...msg);\n }\n\n // helper function: measure tensor leak\n analyze(...msg) {\n if (!this.analyzeMemoryLeaks) return;\n const current = tf.engine().state.numTensors;\n const previous = this.numTensors;\n this.numTensors = current;\n const leaked = current - previous;\n if (leaked !== 0) this.log(...msg, leaked);\n }\n\n async load(userConfig) {\n if (userConfig) this.config = mergeDeep(defaults, userConfig);\n if (this.config.face.enabled && !this.models.facemesh) {\n this.log('Load model: Face');\n this.models.facemesh = await facemesh.load(this.config.face);\n }\n if (this.config.body.enabled && !this.models.posenet) {\n this.log('Load model: Body');\n this.models.posenet = await posenet.load(this.config.body);\n }\n if (this.config.hand.enabled && !this.models.handpose) {\n this.log('Load model: Hand');\n this.models.handpose = await handpose.load(this.config.hand);\n }\n if (this.config.face.enabled && this.config.face.age.enabled && !this.models.age) {\n this.log('Load model: Age');\n this.models.age = await ssrnet.loadAge(this.config);\n }\n if (this.config.face.enabled && this.config.face.gender.enabled && !this.models.gender) {\n this.log('Load model: Gender');\n this.models.gender = await ssrnet.loadGender(this.config);\n }\n if (this.config.face.enabled && this.config.face.emotion.enabled && !this.models.emotion) {\n this.log('Load model: Emotion');\n this.models.emotion = await emotion.load(this.config);\n }\n }\n\n tfImage(input) {\n // let imageData;\n let filtered;\n if (this.fx && this.config.filter.enabled && !(input instanceof tf.Tensor)) {\n const width = input.naturalWidth || input.videoWidth || input.width || (input.shape && (input.shape[1] > 0));\n const height = input.naturalHeight || input.videoHeight || input.height || (input.shape && (input.shape[2] > 0));\n const offscreenCanvas = new OffscreenCanvas(width, height);\n const ctx = offscreenCanvas.getContext('2d');\n if (input instanceof ImageData) ctx.putImageData(input, 0, 0);\n else ctx.drawImage(input, 0, 0, width, height, 0, 0, offscreenCanvas.width, offscreenCanvas.height);\n this.fx.reset();\n this.fx.addFilter('brightness', this.config.filter.brightness); // must have at least one filter enabled\n if (this.config.filter.contrast !== 0) this.fx.addFilter('contrast', this.config.filter.contrast);\n if (this.config.filter.sharpness !== 0) this.fx.addFilter('sharpen', this.config.filter.sharpness);\n if (this.config.filter.blur !== 0) this.fx.addFilter('blur', this.config.filter.blur);\n if (this.config.filter.saturation !== 0) this.fx.addFilter('saturation', this.config.filter.saturation);\n if (this.config.filter.hue !== 0) this.fx.addFilter('hue', this.config.filter.hue);\n if (this.config.filter.negative) this.fx.addFilter('negative');\n if (this.config.filter.sepia) this.fx.addFilter('sepia');\n if (this.config.filter.vintage) this.fx.addFilter('brownie');\n if (this.config.filter.sepia) this.fx.addFilter('sepia');\n if (this.config.filter.kodachrome) this.fx.addFilter('kodachrome');\n if (this.config.filter.technicolor) this.fx.addFilter('technicolor');\n if (this.config.filter.polaroid) this.fx.addFilter('polaroid');\n if (this.config.filter.pixelate !== 0) this.fx.addFilter('pixelate', this.config.filter.pixelate);\n filtered = this.fx.apply(offscreenCanvas);\n }\n let tensor;\n if (input instanceof tf.Tensor) {\n tensor = tf.clone(input);\n } else {\n const pixels = tf.browser.fromPixels(filtered || input);\n const casted = pixels.toFloat();\n tensor = casted.expandDims(0);\n pixels.dispose();\n casted.dispose();\n }\n return { tensor, canvas: this.config.filter.return ? filtered : null };\n }\n\n async detect(input, userConfig = {}) {\n this.state = 'config';\n const perf = {};\n let timeStamp;\n\n timeStamp = now();\n this.config = mergeDeep(defaults, userConfig);\n if (!this.config.videoOptimized) this.config = mergeDeep(this.config, override);\n perf.config = Math.trunc(now() - timeStamp);\n\n // sanity checks\n timeStamp = now();\n this.state = 'check';\n const error = sanity(input);\n if (error) {\n this.log(error, input);\n return { error };\n }\n perf.sanity = Math.trunc(now() - timeStamp);\n\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve) => {\n const timeStart = now();\n\n // configure backend\n timeStamp = now();\n if (tf.getBackend() !== this.config.backend) {\n this.state = 'backend';\n this.log('Human library setting backend:', this.config.backend);\n await tf.setBackend(this.config.backend);\n await tf.ready();\n }\n perf.backend = Math.trunc(now() - timeStamp);\n\n // check number of loaded models\n if (first) {\n this.log('Human library starting');\n this.log('Configuration:', this.config);\n this.log('Flags:', tf.ENV.flags);\n first = false;\n }\n\n // load models if enabled\n timeStamp = now();\n this.state = 'load';\n await this.load();\n perf.load = Math.trunc(now() - timeStamp);\n\n if (this.config.scoped) tf.engine().startScope();\n\n this.analyze('Start Detect:');\n\n timeStamp = now();\n const image = this.tfImage(input);\n perf.image = Math.trunc(now() - timeStamp);\n const imageTensor = image.tensor;\n\n // run posenet\n this.state = 'run:body';\n timeStamp = now();\n this.analyze('Start PoseNet');\n const poseRes = this.config.body.enabled ? await this.models.posenet.estimatePoses(imageTensor, this.config.body) : [];\n this.analyze('End PoseNet:');\n perf.body = Math.trunc(now() - timeStamp);\n\n // run handpose\n this.state = 'run:hand';\n timeStamp = now();\n this.analyze('Start HandPose:');\n const handRes = this.config.hand.enabled ? await this.models.handpose.estimateHands(imageTensor, this.config.hand) : [];\n this.analyze('End HandPose:');\n perf.hand = Math.trunc(now() - timeStamp);\n\n // run facemesh, includes blazeface and iris\n const faceRes = [];\n if (this.config.face.enabled) {\n this.state = 'run:face';\n timeStamp = now();\n this.analyze('Start FaceMesh:');\n const faces = await this.models.facemesh.estimateFaces(imageTensor, this.config.face);\n perf.face = Math.trunc(now() - timeStamp);\n for (const face of faces) {\n // is something went wrong, skip the face\n if (!face.image || face.image.isDisposedInternal) {\n this.log('face object is disposed:', face.image);\n continue;\n }\n // run ssr-net age & gender, inherits face from blazeface\n this.state = 'run:agegender';\n timeStamp = now();\n const ssrData = (this.config.face.age.enabled || this.config.face.gender.enabled) ? await ssrnet.predict(face.image, this.config) : {};\n perf.agegender = Math.trunc(now() - timeStamp);\n // run emotion, inherits face from blazeface\n this.state = 'run:emotion';\n timeStamp = now();\n const emotionData = this.config.face.emotion.enabled ? await emotion.predict(face.image, this.config) : {};\n perf.emotion = Math.trunc(now() - timeStamp);\n\n // dont need face anymore\n face.image.dispose();\n // calculate iris distance\n // iris: array[ bottom, left, top, right, center ]\n const iris = (face.annotations.leftEyeIris && face.annotations.rightEyeIris)\n ? Math.max(face.annotations.leftEyeIris[3][0] - face.annotations.leftEyeIris[1][0], face.annotations.rightEyeIris[3][0] - face.annotations.rightEyeIris[1][0])\n : 0;\n faceRes.push({\n confidence: face.confidence,\n box: face.box,\n mesh: face.mesh,\n annotations: face.annotations,\n age: ssrData.age,\n gender: ssrData.gender,\n agConfidence: ssrData.confidence,\n emotion: emotionData,\n iris: (iris !== 0) ? Math.trunc(100 * 11.7 /* human iris size in mm */ / iris) / 100 : 0,\n });\n this.analyze('End FaceMesh:');\n }\n }\n\n imageTensor.dispose();\n this.state = 'idle';\n\n if (this.config.scoped) tf.engine().endScope();\n this.analyze('End Scope:');\n\n perf.total = Math.trunc(now() - timeStart);\n resolve({ face: faceRes, body: poseRes, hand: handRes, performance: perf, canvas: image.canvas });\n });\n }\n}\n\nexport { Human as default };\n"], + "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA,QAAM,MAAK;AAEX,QAAM,gBAAgB;AAEtB,2BAAyB;AACvB,UAAM,OAAO,CAAE,SAAS,CAAC,YAAY,IAAI,YAAY,IAAI,SAAS,CAAC,GAAG;AACtE,UAAM,UAAU;AAChB,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,QAAQ;AACvC,YAAM,SAAS,KAAK,QAAQ;AAC5B,YAAM,WAAW,KAAK,MAAO,aAAY,SAAS,KAAK;AACvD,YAAM,WAAW,KAAK,MAAO,aAAY,SAAS,KAAK;AACvD,YAAM,aAAa,KAAK,QAAQ;AAChC,eAAS,QAAQ,GAAG,QAAQ,UAAU;AACpC,cAAM,UAAU,SAAU,SAAQ;AAClC,iBAAS,QAAQ,GAAG,QAAQ,UAAU;AACpC,gBAAM,UAAU,SAAU,SAAQ;AAClC,mBAAS,IAAI,GAAG,IAAI,YAAY;AAC9B,oBAAQ,KAAK,CAAC,SAAS;AAAA;AAAA;AAAA;AAAA;AAK/B,WAAO;AAAA;AAGT,QAAM,aAAa,CAAC;AAClB,QAAI,eAAe;AACnB,QAAI,WAAW;AACf,QAAI,SAAS;AAAA;AAGf,QAAM,YAAY,CAAC,mBAAoB;AAAA,IACrC;AAAA,IACA,YAAY,IAAG,MAAM,gBAAgB,CAAC,GAAG,IAAI,CAAC,IAAI;AAAA,IAClD,UAAU,IAAG,MAAM,gBAAgB,CAAC,GAAG,IAAI,CAAC,IAAI;AAAA;AAGlD,QAAM,WAAW,CAAC,KAAK;AACrB,UAAM,SAAS,IAAG,IAAI,IAAI,YAAY;AACtC,UAAM,OAAO,IAAG,IAAI,IAAI,UAAU;AAClC,UAAM,iB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ChC,cAAQ,CAAE,MAAM,SAAS,MAAM,SAAS,MAAM,SAAS,aAAa,MAAM,QAAQ,MAAM;AAAA;AAAA;AAAA;", "names": [] } diff --git a/dist/human.esm-nobundle.js b/dist/human.esm-nobundle.js index a62528bf..427b2b3e 100644 --- a/dist/human.esm-nobundle.js +++ b/dist/human.esm-nobundle.js @@ -1,9 +1,9 @@ -var We=Object.defineProperty;var E=(e,t)=>()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),w0=e=>We(e,"__esModule",{value:!0}),Ge=(e,t)=>{w0(e);for(var o in t)We(e,o,{get:t[o],enumerable:!0})};var Ze=E(ne=>{const w=require("@tensorflow/tfjs"),Ye=6;function E0(e){const t={strides:[e/16,e/8],anchors:[2,6]},o=[];for(let n=0;n{e.startEndTensor.dispose(),e.startPoint.dispose(),e.endPoint.dispose()},Ve=e=>({startEndTensor:e,startPoint:w.slice(e,[0,0],[-1,2]),endPoint:w.slice(e,[0,2],[-1,2])}),v0=(e,t)=>{const o=w.mul(e.startPoint,t),n=w.mul(e.endPoint,t),s=w.concat2d([o,n],1);return Ve(s)};function P0(e,t,o){const n=w.slice(e,[0,1],[-1,2]),s=w.add(n,t),i=w.slice(e,[0,3],[-1,2]),a=w.div(i,o),c=w.div(s,o),d=w.div(a,2),l=w.sub(c,d),u=w.add(c,d),f=w.mul(l,o),h=w.mul(u,o),r=1;return w.concat2d([f,h],r)}function T0(e,t){return w.tidy(()=>{const o=e.box?e.box:e;return v0(o,t).startEndTensor.squeeze()})}class Qe{constructor(e,t){this.blazeFaceModel=e,this.width=t.detector.inputSize,this.height=t.detector.inputSize,this.maxFaces=t.detector.maxFaces,this.anchorsData=E0(t.detector.inputSize),this.anchors=w.tensor2d(this.anchorsData),this.inputSize=w.tensor1d([this.width,this.height]),this.iouThreshold=t.detector.iouThreshold,this.scaleFaces=.8,this.scoreThreshold=t.detector.scoreThreshold}async getBoundingBoxes(e){if(!e||e.isDisposedInternal||e.shape.length!==4||e.shape[1]<1||e.shape[2]<1)return null;const[t,o,n]=w.tidy(()=>{const l=e.resizeBilinear([this.width,this.height]),u=w.mul(w.sub(l.div(255),.5),2),f=this.blazeFaceModel.predict(u);let h;if(Array.isArray(f)){const _=f.sort((F,p)=>F.size-p.size),v=w.concat([_[0],_[2]],2),y=w.concat([_[1],_[3]],2),B=w.concat([y,v],1);h=B.squeeze(0)}else h=f.squeeze();const r=P0(h,this.anchors,this.inputSize),g=w.slice(h,[0,0],[-1,1]),P=w.sigmoid(g).squeeze();return[h,r,P]}),s=await w.image.nonMaxSuppressionAsync(o,n,this.maxFaces,this.iouThreshold,this.scoreThreshold),i=await s.array();s.dispose();const a=i.map(l=>w.slice(o,[l,0],[1,-1])),c=await Promise.all(a.map(async l=>{const u=await l.array();return l.dispose(),u})),d=[];for(let l=0;l{const s=T0(n,o),[i,a,c]=await Promise.all([n.landmarks,s,n.probability].map(async r=>r.array())),d=n.anchor,[l,u]=o,f=i.map(r=>[(r[0]+d[0])*l,(r[1]+d[1])*u]),h={topLeft:a.slice(0,2),bottomRight:a.slice(2),landmarks:f,probability:c};return Ke(n.box),n.landmarks.dispose(),n.probability.dispose(),s.dispose(),h}))}}async function _0(e){const t=await w.loadGraphModel(e.detector.modelPath,{fromTFHub:e.detector.modelPath.includes("tfhub.dev")}),o=new Qe(t,e);return o}ne.load=_0;ne.BlazeFaceModel=Qe;ne.disposeBox=Ke});var me=E(ue=>{ue.MESH_ANNOTATIONS={silhouette:[10,338,297,332,284,251,389,356,454,323,361,288,397,365,379,378,400,377,152,148,176,149,150,136,172,58,132,93,234,127,162,21,54,103,67,109],lipsUpperOuter:[61,185,40,39,37,0,267,269,270,409,291],lipsLowerOuter:[146,91,181,84,17,314,405,321,375,291],lipsUpperInner:[78,191,80,81,82,13,312,311,310,415,308],lipsLowerInner:[78,95,88,178,87,14,317,402,318,324,308],rightEyeUpper0:[246,161,160,159,158,157,173],rightEyeLower0:[33,7,163,144,145,153,154,155,133],rightEyeUpper1:[247,30,29,27,28,56,190],rightEyeLower1:[130,25,110,24,23,22,26,112,243],rightEyeUpper2:[113,225,224,223,222,221,189],rightEyeLower2:[226,31,228,229,230,231,232,233,244],rightEyeLower3:[143,111,117,118,119,120,121,128,245],rightEyebrowUpper:[156,70,63,105,66,107,55,193],rightEyebrowLower:[35,124,46,53,52,65],rightEyeIris:[473,474,475,476,477],leftEyeUpper0:[466,388,387,386,385,384,398],leftEyeLower0:[263,249,390,373,374,380,381,382,362],leftEyeUpper1:[467,260,259,257,258,286,414],leftEyeLower1:[359,255,339,254,253,252,256,341,463],leftEyeUpper2:[342,445,444,443,442,441,413],leftEyeLower2:[446,261,448,449,450,451,452,453,464],leftEyeLower3:[372,340,346,347,348,349,350,357,465],leftEyebrowUpper:[383,300,293,334,296,336,285,417],leftEyebrowLower:[265,353,276,283,282,295],leftEyeIris:[468,469,470,471,472],midwayBetweenEyes:[168],noseTip:[1],noseBottom:[2],noseRightCorner:[98],noseLeftCorner:[327],rightCheek:[205],leftCheek:[425]};ue.MESH_TO_IRIS_INDICES_MAP=[{key:"EyeUpper0",indices:[9,10,11,12,13,14,15]},{key:"EyeUpper1",indices:[25,26,27,28,29,30,31]},{key:"EyeUpper2",indices:[41,42,43,44,45,46,47]},{key:"EyeLower0",indices:[0,1,2,3,4,5,6,7,8]},{key:"EyeLower1",indices:[16,17,18,19,20,21,22,23,24]},{key:"EyeLower2",indices:[32,33,34,35,36,37,38,39,40]},{key:"EyeLower3",indices:[54,55,56,57,58,59,60,61,62]},{key:"EyebrowUpper",indices:[63,64,65,66,67,68,69,70]},{key:"EyebrowLower",indices:[48,49,50,51,52,53]}]});var $e=E(V=>{const M0=require("@tensorflow/tfjs");function I0(e,t){const o=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],n=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]];return{startPoint:o,endPoint:n}}V.scaleBoxCoordinates=I0;function fe(e){return[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])]}V.getBoxSize=fe;function pe(e){return[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2]}V.getBoxCenter=pe;function S0(e,t,o){const n=t.shape[1],s=t.shape[2],i=[[e.startPoint[1]/n,e.startPoint[0]/s,e.endPoint[1]/n,e.endPoint[0]/s]];return M0.image.cropAndResize(t,i,[0],o)}V.cutBoxFromImageAndResize=S0;function R0(e,t=1.5){const o=pe(e),n=fe(e),s=[t*n[0]/2,t*n[1]/2],i=[o[0]-s[0],o[1]-s[1]],a=[o[0]+s[0],o[1]+s[1]];return{startPoint:i,endPoint:a,landmarks:e.landmarks}}V.enlargeBox=R0;function A0(e){const t=pe(e),o=fe(e),n=Math.max(...o),s=n/2,i=[t[0]-s,t[1]-s],a=[t[0]+s,t[1]+s];return{startPoint:i,endPoint:a,landmarks:e.landmarks}}V.squarifyBox=A0});var nt=E(D=>{D.IDENTITY_MATRIX=[[1,0,0],[0,1,0],[0,0,1]];function Je(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}D.normalizeRadians=Je;function B0(e,t){const o=Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]);return Je(o)}D.computeRotation=B0;function F0(e){return e*180/Math.PI}D.radToDegrees=F0;function et(e,t){return[[1,0,e],[0,1,t],[0,0,1]]}function Q(e,t){let o=0;for(let n=0;n{const O=require("@tensorflow/tfjs"),C=$e(),H=me(),U=nt(),z0=468,O0=.25,L0=13,H0=[L0,H.MESH_ANNOTATIONS.midwayBetweenEyes[0]],U0=3,j0=2,q0=[U0,j0],ge=H.MESH_ANNOTATIONS.leftEyeLower0,xe=[ge[0],ge[ge.length-1]],be=H.MESH_ANNOTATIONS.rightEyeLower0,ye=[be[0],be[be.length-1]],X0=3,W0=4,G0=71,we=76;function se(e,t,o,n){for(let s=0;s[i[0]*(h[0]-this.meshWidth/2),i[1]*(h[1]-this.meshHeight/2),h[2]]),c=U.buildRotationMatrix(o,[0,0]),d=a.map(h=>[...U.rotatePoint(h,c),h[2]]),l=U.invertTransformMatrix(n),u=[...C.getBoxCenter({startPoint:t.startPoint,endPoint:t.endPoint}),1],f=[U.dot(u,l[0]),U.dot(u,l[1])];return d.map(h=>[h[0]+f[0],h[1]+f[1],h[2]])}getLeftToRightEyeDepthDifference(e){const t=e[xe[0]][2],o=e[ye[0]][2];return t-o}getEyeBox(e,t,o,n,s=!1){const i=C.squarifyBox(C.enlargeBox(this.calculateLandmarksBoundingBox([e[o],e[n]]),this.irisEnlarge)),a=C.getBoxSize(i);let c=O.image.cropAndResize(t,[[i.startPoint[1]/this.meshHeight,i.startPoint[0]/this.meshWidth,i.endPoint[1]/this.meshHeight,i.endPoint[0]/this.meshWidth]],[0],[this.irisSize,this.irisSize]);return s&&(c=O.image.flipLeftRight(c)),{box:i,boxSize:a,crop:c}}getEyeCoords(e,t,o,n=!1){const s=[];for(let i=0;i{let d=i;return c===2?d=n:c===4&&(d=s),[a[0],a[1],d]})}async predict(e,t){if(this.skipFrames=t.detector.skipFrames,this.maxFaces=t.detector.maxFaces,this.runsWithoutFaceDetector++,this.shouldUpdateRegionsOfInterest()){const n=await this.boundingBoxDetector.getBoundingBoxes(e);if(n.boxes.length===0)return this.regionsOfInterest=[],null;const s=n.boxes.map(i=>{const a=i.box.startPoint.squeeze(),c=i.box.endPoint.squeeze(),d={startPoint:a.arraySync(),endPoint:c.arraySync()};a.dispose(),c.dispose();const l=C.scaleBoxCoordinates(d,n.scaleFactor),u=C.enlargeBox(l),f=i.landmarks.arraySync();return i.box.startPoint.dispose(),i.box.endPoint.dispose(),i.landmarks.dispose(),i.probability.dispose(),{...u,landmarks:f}});this.updateRegionsOfInterest(s),this.runsWithoutFaceDetector=0}const o=O.tidy(()=>this.regionsOfInterest.map((n,s)=>{let i=0;const a=n.landmarks.length>=z0;let[c,d]=H0;a===!1&&([c,d]=q0),i=U.computeRotation(n.landmarks[c],n.landmarks[d]);const l=C.getBoxCenter({startPoint:n.startPoint,endPoint:n.endPoint}),u=[l[0]/e.shape[2],l[1]/e.shape[1]];let f=e,h=U.IDENTITY_MATRIX;i!==0&&(f=O.image.rotateWithOffset(e,i,0,u),h=U.buildRotationMatrix(-i,l));const r={startPoint:n.startPoint,endPoint:n.endPoint},g=C.cutBoxFromImageAndResize(r,f,[this.meshHeight,this.meshWidth]).div(255),[,P,_]=this.meshDetector.predict(g),v=O.reshape(_,[-1,3]);let y=v.arraySync();if(t.iris.enabled){const{box:m,boxSize:b,crop:M}=this.getEyeBox(y,g,xe[0],xe[1],!0),{box:S,boxSize:N,crop:m0}=this.getEyeBox(y,g,ye[0],ye[1]),He=this.irisModel.predict(O.concat([M,m0])),Ue=He.dataSync();He.dispose();const f0=Ue.slice(0,we*3),{rawCoords:je,iris:p0}=this.getEyeCoords(f0,m,b,!0),g0=Ue.slice(we*3),{rawCoords:qe,iris:x0}=this.getEyeCoords(g0,S,N),Xe=this.getLeftToRightEyeDepthDifference(y);Math.abs(Xe)<30?(se(y,je,"left"),se(y,qe,"right")):Xe<1?se(y,je,"left",["EyeUpper0","EyeLower0"]):se(y,qe,"right",["EyeUpper0","EyeLower0"]);const b0=this.getAdjustedIrisCoords(y,p0,"left"),y0=this.getAdjustedIrisCoords(y,x0,"right");y=y.concat(b0).concat(y0)}const B=this.transformRawCoords(y,n,i,h);O.dispose(y);const F=C.enlargeBox(this.calculateLandmarksBoundingBox(B)),p=P.squeeze();if(O.dispose(P),t.mesh.enabled){const m=O.tensor2d(B);this.regionsOfInterest[s]={...F,landmarks:m.arraySync()};const b={coords:m,box:F,confidence:p,image:g};return b}const x={coords:null,box:F,confidence:p,image:g};return x}));return o}updateRegionsOfInterest(e){for(let t=0;t=this.skipFrames}calculateLandmarksBoundingBox(e){const t=e.map(i=>i[0]),o=e.map(i=>i[1]),n=[Math.min(...t),Math.min(...o)],s=[Math.max(...t),Math.max(...o)];return{startPoint:n,endPoint:s,landmarks:e}}}st.Pipeline=Y0});var at=E(rt=>{rt.UV_COORDS=[[.499976992607117,.652534008026123],[.500025987625122,.547487020492554],[.499974012374878,.602371990680695],[.482113003730774,.471979022026062],[.500150978565216,.527155995368958],[.499909996986389,.498252987861633],[.499523013830185,.40106201171875],[.289712011814117,.380764007568359],[.499954998493195,.312398016452789],[.499987006187439,.269918978214264],[.500023007392883,.107050001621246],[.500023007392883,.666234016418457],[.5000159740448,.679224014282227],[.500023007392883,.692348003387451],[.499976992607117,.695277988910675],[.499976992607117,.70593398809433],[.499976992607117,.719385027885437],[.499976992607117,.737019002437592],[.499967992305756,.781370997428894],[.499816000461578,.562981009483337],[.473773002624512,.573909997940063],[.104906998574734,.254140973091125],[.365929991006851,.409575998783112],[.338757991790771,.41302502155304],[.311120003461838,.409460008144379],[.274657994508743,.389131009578705],[.393361985683441,.403706014156342],[.345234006643295,.344011008739471],[.370094001293182,.346076011657715],[.319321990013123,.347265005111694],[.297903001308441,.353591024875641],[.24779200553894,.410809993743896],[.396889001131058,.842755019664764],[.280097991228104,.375599980354309],[.106310002505779,.399955987930298],[.2099249958992,.391353011131287],[.355807989835739,.534406006336212],[.471751004457474,.65040397644043],[.474155008792877,.680191993713379],[.439785003662109,.657229006290436],[.414617002010345,.66654098033905],[.450374007225037,.680860996246338],[.428770989179611,.682690978050232],[.374971002340317,.727805018424988],[.486716985702515,.547628998756409],[.485300987958908,.527395009994507],[.257764995098114,.314490020275116],[.401223003864288,.455172002315521],[.429818987846375,.548614978790283],[.421351999044418,.533740997314453],[.276895999908447,.532056987285614],[.483370006084442,.499586999416351],[.33721199631691,.282882988452911],[.296391993761063,.293242990970612],[.169294998049736,.193813979625702],[.447580009698868,.302609980106354],[.392390012741089,.353887975215912],[.354490011930466,.696784019470215],[.067304998636246,.730105042457581],[.442739009857178,.572826027870178],[.457098007202148,.584792017936707],[.381974011659622,.694710969924927],[.392388999462128,.694203019142151],[.277076005935669,.271932005882263],[.422551989555359,.563233017921448],[.385919004678726,.281364023685455],[.383103013038635,.255840003490448],[.331431001424789,.119714021682739],[.229923993349075,.232002973556519],[.364500999450684,.189113974571228],[.229622006416321,.299540996551514],[.173287004232407,.278747975826263],[.472878992557526,.666198015213013],[.446828007698059,.668527007102966],[.422762006521225,.673889994621277],[.445307999849319,.580065965652466],[.388103008270264,.693961024284363],[.403039008378983,.706539988517761],[.403629004955292,.693953037261963],[.460041999816895,.557139039039612],[.431158006191254,.692366003990173],[.452181994915009,.692366003990173],[.475387006998062,.692366003990173],[.465828001499176,.779190003871918],[.472328990697861,.736225962638855],[.473087012767792,.717857003211975],[.473122000694275,.704625964164734],[.473033010959625,.695277988910675],[.427942007780075,.695277988910675],[.426479011774063,.703539967536926],[.423162013292313,.711845993995667],[.4183090031147,.720062971115112],[.390094995498657,.639572978019714],[.013953999616206,.560034036636353],[.499913990497589,.58014702796936],[.413199990987778,.69539999961853],[.409626007080078,.701822996139526],[.468080013990402,.601534962654114],[.422728985548019,.585985004901886],[.463079988956451,.593783974647522],[.37211999297142,.47341400384903],[.334562003612518,.496073007583618],[.411671012639999,.546965003013611],[.242175996303558,.14767599105835],[.290776997804642,.201445996761322],[.327338010072708,.256527006626129],[.399509996175766,.748921036720276],[.441727995872498,.261676013469696],[.429764986038208,.187834024429321],[.412198007106781,.108901023864746],[.288955003023148,.398952007293701],[.218936994671822,.435410976409912],[.41278201341629,.398970007896423],[.257135003805161,.355440020561218],[.427684992551804,.437960982322693],[.448339998722076,.536936044692993],[.178560003638268,.45755398273468],[.247308000922203,.457193970680237],[.286267012357712,.467674970626831],[.332827985286713,.460712015628815],[.368755996227264,.447206974029541],[.398963987827301,.432654976844788],[.476410001516342,.405806005001068],[.189241006970406,.523923993110657],[.228962004184723,.348950982093811],[.490725994110107,.562400996685028],[.404670000076294,.485132992267609],[.019469000399113,.401564002037048],[.426243007183075,.420431017875671],[.396993011236191,.548797011375427],[.266469985246658,.376977026462555],[.439121007919312,.51895797252655],[.032313998788595,.644356966018677],[.419054001569748,.387154996395111],[.462783008813858,.505746960639954],[.238978996872902,.779744982719421],[.198220998048782,.831938028335571],[.107550002634525,.540755033493042],[.183610007166862,.740257024765015],[.134409993886948,.333683013916016],[.385764002799988,.883153975009918],[.490967005491257,.579378008842468],[.382384985685349,.508572995662689],[.174399003386497,.397670984268188],[.318785011768341,.39623498916626],[.343364000320435,.400596976280212],[.396100014448166,.710216999053955],[.187885001301765,.588537991046906],[.430987000465393,.944064974784851],[.318993002176285,.898285031318665],[.266247987747192,.869701027870178],[.500023007392883,.190576016902924],[.499976992607117,.954452991485596],[.366169989109039,.398822009563446],[.393207013607025,.39553701877594],[.410373002290726,.391080021858215],[.194993004202843,.342101991176605],[.388664990663528,.362284004688263],[.365961998701096,.355970978736877],[.343364000320435,.355356991291046],[.318785011768341,.35834002494812],[.301414996385574,.363156020641327],[.058132998645306,.319076001644135],[.301414996385574,.387449026107788],[.499987989664078,.618434011936188],[.415838003158569,.624195992946625],[.445681989192963,.566076993942261],[.465844005346298,.620640993118286],[.49992299079895,.351523995399475],[.288718998432159,.819945991039276],[.335278987884521,.852819979190826],[.440512001514435,.902418971061707],[.128294005990028,.791940987110138],[.408771991729736,.373893976211548],[.455606997013092,.451801002025604],[.499877005815506,.908990025520325],[.375436991453171,.924192011356354],[.11421000212431,.615022003650665],[.448662012815475,.695277988910675],[.4480200111866,.704632043838501],[.447111994028091,.715808033943176],[.444831997156143,.730794012546539],[.430011987686157,.766808986663818],[.406787008047104,.685672998428345],[.400738000869751,.681069016456604],[.392399996519089,.677703022956848],[.367855995893478,.663918972015381],[.247923001646996,.601333022117615],[.452769994735718,.420849978923798],[.43639200925827,.359887003898621],[.416164010763168,.368713974952698],[.413385987281799,.692366003990173],[.228018000721931,.683571994304657],[.468268007040024,.352671027183533],[.411361992359161,.804327011108398],[.499989002943039,.469825029373169],[.479153990745544,.442654013633728],[.499974012374878,.439637005329132],[.432112008333206,.493588984012604],[.499886006116867,.866917014122009],[.49991300702095,.821729004383087],[.456548988819122,.819200992584229],[.344549000263214,.745438992977142],[.37890899181366,.574010014533997],[.374292999505997,.780184984207153],[.319687992334366,.570737957954407],[.357154995203018,.604269981384277],[.295284003019333,.621580958366394],[.447750002145767,.862477004528046],[.410986006259918,.508723020553589],[.31395098567009,.775308012962341],[.354128003120422,.812552988529205],[.324548006057739,.703992962837219],[.189096003770828,.646299958229065],[.279776990413666,.71465802192688],[.1338230073452,.682700991630554],[.336768001317978,.644733011722565],[.429883986711502,.466521978378296],[.455527991056442,.548622965812683],[.437114000320435,.558896005153656],[.467287987470627,.529924988746643],[.414712011814117,.335219979286194],[.37704598903656,.322777986526489],[.344107985496521,.320150971412659],[.312875986099243,.32233202457428],[.283526003360748,.333190023899078],[.241245999932289,.382785975933075],[.102986000478268,.468762993812561],[.267612010240555,.424560010433197],[.297879010438919,.433175981044769],[.333433985710144,.433878004550934],[.366427004337311,.426115989685059],[.396012008190155,.416696012020111],[.420121014118195,.41022801399231],[.007561000064015,.480777025222778],[.432949006557465,.569517970085144],[.458638995885849,.479089021682739],[.473466008901596,.545744001865387],[.476087987422943,.563830018043518],[.468472003936768,.555056989192963],[.433990985155106,.582361996173859],[.483518004417419,.562983989715576],[.482482999563217,.57784903049469],[.42645001411438,.389798998832703],[.438998997211456,.39649498462677],[.450067013502121,.400434017181396],[.289712011814117,.368252992630005],[.276670008897781,.363372981548309],[.517862021923065,.471948027610779],[.710287988185883,.380764007568359],[.526226997375488,.573909997940063],[.895093023777008,.254140973091125],[.634069979190826,.409575998783112],[.661242008209229,.41302502155304],[.688880026340485,.409460008144379],[.725341975688934,.389131009578705],[.606630027294159,.40370500087738],[.654766023159027,.344011008739471],[.629905998706818,.346076011657715],[.680678009986877,.347265005111694],[.702096998691559,.353591024875641],[.75221198797226,.410804986953735],[.602918028831482,.842862963676453],[.719901978969574,.375599980354309],[.893692970275879,.399959981441498],[.790081977844238,.391354024410248],[.643998026847839,.534487962722778],[.528249025344849,.65040397644043],[.525849997997284,.680191040039062],[.560214996337891,.657229006290436],[.585384011268616,.66654098033905],[.549625992774963,.680860996246338],[.57122802734375,.682691991329193],[.624852001667023,.72809898853302],[.513050019741058,.547281980514526],[.51509702205658,.527251958847046],[.742246985435486,.314507007598877],[.598631024360657,.454979002475739],[.570338010787964,.548575043678284],[.578631997108459,.533622980117798],[.723087012767792,.532054007053375],[.516445994377136,.499638974666595],[.662801027297974,.282917976379395],[.70362401008606,.293271005153656],[.830704987049103,.193813979625702],[.552385985851288,.302568018436432],[.607609987258911,.353887975215912],[.645429015159607,.696707010269165],[.932694971561432,.730105042457581],[.557260990142822,.572826027870178],[.542901992797852,.584792017936707],[.6180260181427,.694710969924927],[.607590973377228,.694203019142151],[.722943007946014,.271963000297546],[.577413976192474,.563166975975037],[.614082992076874,.281386971473694],[.616907000541687,.255886018276215],[.668509006500244,.119913995265961],[.770092010498047,.232020974159241],[.635536015033722,.189248979091644],[.77039098739624,.299556016921997],[.826722025871277,.278755009174347],[.527121007442474,.666198015213013],[.553171992301941,.668527007102966],[.577238023281097,.673889994621277],[.554691970348358,.580065965652466],[.611896991729736,.693961024284363],[.59696102142334,.706539988517761],[.596370995044708,.693953037261963],[.539958000183105,.557139039039612],[.568841993808746,.692366003990173],[.547818005084991,.692366003990173],[.52461302280426,.692366003990173],[.534089982509613,.779141008853912],[.527670979499817,.736225962638855],[.526912987232208,.717857003211975],[.526877999305725,.704625964164734],[.526966989040375,.695277988910675],[.572058022022247,.695277988910675],[.573521018028259,.703539967536926],[.57683801651001,.711845993995667],[.581691026687622,.720062971115112],[.609944999217987,.639909982681274],[.986046016216278,.560034036636353],[.5867999792099,.69539999961853],[.590372025966644,.701822996139526],[.531915009021759,.601536989212036],[.577268004417419,.585934996604919],[.536915004253387,.593786001205444],[.627542972564697,.473352015018463],[.665585994720459,.495950996875763],[.588353991508484,.546862006187439],[.757824003696442,.14767599105835],[.709249973297119,.201507985591888],[.672684013843536,.256581008434296],[.600408971309662,.74900496006012],[.55826598405838,.261672019958496],[.570303976535797,.187870979309082],[.588165998458862,.109044015407562],[.711045026779175,.398952007293701],[.781069993972778,.435405015945435],[.587247014045715,.398931980133057],[.742869973182678,.355445981025696],[.572156012058258,.437651991844177],[.55186802148819,.536570012569427],[.821442008018494,.457556009292603],[.752701997756958,.457181990146637],[.71375697851181,.467626988887787],[.66711300611496,.460672974586487],[.631101012229919,.447153985500336],[.6008620262146,.432473003864288],[.523481011390686,.405627012252808],[.810747981071472,.523926019668579],[.771045982837677,.348959028720856],[.509127020835876,.562718033790588],[.595292985439301,.485023975372314],[.980530977249146,.401564002037048],[.573499977588654,.420000016689301],[.602994978427887,.548687994480133],[.733529984951019,.376977026462555],[.560611009597778,.519016981124878],[.967685997486115,.644356966018677],[.580985009670258,.387160003185272],[.537728011608124,.505385041236877],[.760966002941132,.779752969741821],[.801778972148895,.831938028335571],[.892440974712372,.54076099395752],[.816350996494293,.740260004997253],[.865594983100891,.333687007427216],[.614073991775513,.883246004581451],[.508952975273132,.579437971115112],[.617941975593567,.508316040039062],[.825608015060425,.397674977779388],[.681214988231659,.39623498916626],[.656635999679565,.400596976280212],[.603900015354156,.710216999053955],[.81208598613739,.588539004325867],[.56801301240921,.944564998149872],[.681007981300354,.898285031318665],[.733752012252808,.869701027870178],[.633830010890961,.398822009563446],[.606792986392975,.39553701877594],[.589659988880157,.391062021255493],[.805015981197357,.342108011245728],[.611334979534149,.362284004688263],[.634037971496582,.355970978736877],[.656635999679565,.355356991291046],[.681214988231659,.35834002494812],[.698584973812103,.363156020641327],[.941866993904114,.319076001644135],[.698584973812103,.387449026107788],[.584177017211914,.624107003211975],[.554318010807037,.566076993942261],[.534153997898102,.62064003944397],[.711217999458313,.819975018501282],[.664629995822906,.852871000766754],[.559099972248077,.902631998062134],[.871706008911133,.791940987110138],[.591234028339386,.373893976211548],[.544341027736664,.451583981513977],[.624562978744507,.924192011356354],[.88577002286911,.615028977394104],[.551338016986847,.695277988910675],[.551980018615723,.704632043838501],[.552887976169586,.715808033943176],[.555167973041534,.730794012546539],[.569944024085999,.767035007476807],[.593203008174896,.685675978660583],[.599261999130249,.681069016456604],[.607599973678589,.677703022956848],[.631937980651855,.663500010967255],[.752032995223999,.601315021514893],[.547226011753082,.420395016670227],[.563543975353241,.359827995300293],[.583841025829315,.368713974952698],[.586614012718201,.692366003990173],[.771915018558502,.683578014373779],[.531597018241882,.352482974529266],[.588370978832245,.804440975189209],[.52079701423645,.442565023899078],[.567984998226166,.493479013442993],[.543282985687256,.819254994392395],[.655317008495331,.745514988899231],[.621008992195129,.574018001556396],[.625559985637665,.78031200170517],[.680198013782501,.570719003677368],[.64276397228241,.604337990283966],[.704662978649139,.621529996395111],[.552012026309967,.862591981887817],[.589071989059448,.508637011051178],[.685944974422455,.775357007980347],[.645735025405884,.812640011310577],[.675342977046967,.703978002071381],[.810858011245728,.646304965019226],[.72012197971344,.714666962623596],[.866151988506317,.682704985141754],[.663187026977539,.644596993923187],[.570082008838654,.466325998306274],[.544561982154846,.548375964164734],[.562758982181549,.558784961700439],[.531987011432648,.530140042304993],[.585271000862122,.335177004337311],[.622952997684479,.32277899980545],[.655896008014679,.320163011550903],[.687132000923157,.322345972061157],[.716481983661652,.333200991153717],[.758756995201111,.382786989212036],[.897013008594513,.468769013881683],[.732392013072968,.424547016620636],[.70211398601532,.433162987232208],[.66652500629425,.433866024017334],[.633504986763,.426087975502014],[.603875994682312,.416586995124817],[.579657971858978,.409945011138916],[.992439985275269,.480777025222778],[.567192018032074,.569419980049133],[.54136598110199,.478899002075195],[.526564002037048,.546118021011353],[.523913025856018,.563830018043518],[.531529009342194,.555056989192963],[.566035985946655,.582329034805298],[.51631098985672,.563053965568542],[.5174720287323,.577877044677734],[.573594987392426,.389806985855103],[.560697972774506,.395331978797913],[.549755990505219,.399751007556915],[.710287988185883,.368252992630005],[.723330020904541,.363372981548309]]});var ct=E(K0=>{Ge(K0,{default:()=>V0});var V0=[127,34,139,11,0,37,232,231,120,72,37,39,128,121,47,232,121,128,104,69,67,175,171,148,157,154,155,118,50,101,73,39,40,9,151,108,48,115,131,194,204,211,74,40,185,80,42,183,40,92,186,230,229,118,202,212,214,83,18,17,76,61,146,160,29,30,56,157,173,106,204,194,135,214,192,203,165,98,21,71,68,51,45,4,144,24,23,77,146,91,205,50,187,201,200,18,91,106,182,90,91,181,85,84,17,206,203,36,148,171,140,92,40,39,193,189,244,159,158,28,247,246,161,236,3,196,54,68,104,193,168,8,117,228,31,189,193,55,98,97,99,126,47,100,166,79,218,155,154,26,209,49,131,135,136,150,47,126,217,223,52,53,45,51,134,211,170,140,67,69,108,43,106,91,230,119,120,226,130,247,63,53,52,238,20,242,46,70,156,78,62,96,46,53,63,143,34,227,173,155,133,123,117,111,44,125,19,236,134,51,216,206,205,154,153,22,39,37,167,200,201,208,36,142,100,57,212,202,20,60,99,28,158,157,35,226,113,160,159,27,204,202,210,113,225,46,43,202,204,62,76,77,137,123,116,41,38,72,203,129,142,64,98,240,49,102,64,41,73,74,212,216,207,42,74,184,169,170,211,170,149,176,105,66,69,122,6,168,123,147,187,96,77,90,65,55,107,89,90,180,101,100,120,63,105,104,93,137,227,15,86,85,129,102,49,14,87,86,55,8,9,100,47,121,145,23,22,88,89,179,6,122,196,88,95,96,138,172,136,215,58,172,115,48,219,42,80,81,195,3,51,43,146,61,171,175,199,81,82,38,53,46,225,144,163,110,246,33,7,52,65,66,229,228,117,34,127,234,107,108,69,109,108,151,48,64,235,62,78,191,129,209,126,111,35,143,163,161,246,117,123,50,222,65,52,19,125,141,221,55,65,3,195,197,25,7,33,220,237,44,70,71,139,122,193,245,247,130,33,71,21,162,153,158,159,170,169,150,188,174,196,216,186,92,144,160,161,2,97,167,141,125,241,164,167,37,72,38,12,145,159,160,38,82,13,63,68,71,226,35,111,158,153,154,101,50,205,206,92,165,209,198,217,165,167,97,220,115,218,133,112,243,239,238,241,214,135,169,190,173,133,171,208,32,125,44,237,86,87,178,85,86,179,84,85,180,83,84,181,201,83,182,137,93,132,76,62,183,61,76,184,57,61,185,212,57,186,214,207,187,34,143,156,79,239,237,123,137,177,44,1,4,201,194,32,64,102,129,213,215,138,59,166,219,242,99,97,2,94,141,75,59,235,24,110,228,25,130,226,23,24,229,22,23,230,26,22,231,112,26,232,189,190,243,221,56,190,28,56,221,27,28,222,29,27,223,30,29,224,247,30,225,238,79,20,166,59,75,60,75,240,147,177,215,20,79,166,187,147,213,112,233,244,233,128,245,128,114,188,114,217,174,131,115,220,217,198,236,198,131,134,177,132,58,143,35,124,110,163,7,228,110,25,356,389,368,11,302,267,452,350,349,302,303,269,357,343,277,452,453,357,333,332,297,175,152,377,384,398,382,347,348,330,303,304,270,9,336,337,278,279,360,418,262,431,304,408,409,310,415,407,270,409,410,450,348,347,422,430,434,313,314,17,306,307,375,387,388,260,286,414,398,335,406,418,364,367,416,423,358,327,251,284,298,281,5,4,373,374,253,307,320,321,425,427,411,421,313,18,321,405,406,320,404,405,315,16,17,426,425,266,377,400,369,322,391,269,417,465,464,386,257,258,466,260,388,456,399,419,284,332,333,417,285,8,346,340,261,413,441,285,327,460,328,355,371,329,392,439,438,382,341,256,429,420,360,364,394,379,277,343,437,443,444,283,275,440,363,431,262,369,297,338,337,273,375,321,450,451,349,446,342,467,293,334,282,458,461,462,276,353,383,308,324,325,276,300,293,372,345,447,382,398,362,352,345,340,274,1,19,456,248,281,436,427,425,381,256,252,269,391,393,200,199,428,266,330,329,287,273,422,250,462,328,258,286,384,265,353,342,387,259,257,424,431,430,342,353,276,273,335,424,292,325,307,366,447,345,271,303,302,423,266,371,294,455,460,279,278,294,271,272,304,432,434,427,272,407,408,394,430,431,395,369,400,334,333,299,351,417,168,352,280,411,325,319,320,295,296,336,319,403,404,330,348,349,293,298,333,323,454,447,15,16,315,358,429,279,14,15,316,285,336,9,329,349,350,374,380,252,318,402,403,6,197,419,318,319,325,367,364,365,435,367,397,344,438,439,272,271,311,195,5,281,273,287,291,396,428,199,311,271,268,283,444,445,373,254,339,263,466,249,282,334,296,449,347,346,264,447,454,336,296,299,338,10,151,278,439,455,292,407,415,358,371,355,340,345,372,390,249,466,346,347,280,442,443,282,19,94,370,441,442,295,248,419,197,263,255,359,440,275,274,300,383,368,351,412,465,263,467,466,301,368,389,380,374,386,395,378,379,412,351,419,436,426,322,373,390,388,2,164,393,370,462,461,164,0,267,302,11,12,374,373,387,268,12,13,293,300,301,446,261,340,385,384,381,330,266,425,426,423,391,429,355,437,391,327,326,440,457,438,341,382,362,459,457,461,434,430,394,414,463,362,396,369,262,354,461,457,316,403,402,315,404,403,314,405,404,313,406,405,421,418,406,366,401,361,306,408,407,291,409,408,287,410,409,432,436,410,434,416,411,264,368,383,309,438,457,352,376,401,274,275,4,421,428,262,294,327,358,433,416,367,289,455,439,462,370,326,2,326,370,305,460,455,254,449,448,255,261,446,253,450,449,252,451,450,256,452,451,341,453,452,413,464,463,441,413,414,258,442,441,257,443,442,259,444,443,260,445,444,467,342,445,459,458,250,289,392,290,290,328,460,376,433,435,250,290,392,411,416,433,341,463,464,453,464,465,357,465,412,343,412,399,360,363,440,437,399,456,420,456,363,401,435,288,372,383,353,339,255,249,448,261,255,133,243,190,133,155,112,33,246,247,33,130,25,398,384,286,362,398,414,362,463,341,263,359,467,263,249,255,466,467,260,75,60,166,238,239,79,162,127,139,72,11,37,121,232,120,73,72,39,114,128,47,233,232,128,103,104,67,152,175,148,173,157,155,119,118,101,74,73,40,107,9,108,49,48,131,32,194,211,184,74,185,191,80,183,185,40,186,119,230,118,210,202,214,84,83,17,77,76,146,161,160,30,190,56,173,182,106,194,138,135,192,129,203,98,54,21,68,5,51,4,145,144,23,90,77,91,207,205,187,83,201,18,181,91,182,180,90,181,16,85,17,205,206,36,176,148,140,165,92,39,245,193,244,27,159,28,30,247,161,174,236,196,103,54,104,55,193,8,111,117,31,221,189,55,240,98,99,142,126,100,219,166,218,112,155,26,198,209,131,169,135,150,114,47,217,224,223,53,220,45,134,32,211,140,109,67,108,146,43,91,231,230,120,113,226,247,105,63,52,241,238,242,124,46,156,95,78,96,70,46,63,116,143,227,116,123,111,1,44,19,3,236,51,207,216,205,26,154,22,165,39,167,199,200,208,101,36,100,43,57,202,242,20,99,56,28,157,124,35,113,29,160,27,211,204,210,124,113,46,106,43,204,96,62,77,227,137,116,73,41,72,36,203,142,235,64,240,48,49,64,42,41,74,214,212,207,183,42,184,210,169,211,140,170,176,104,105,69,193,122,168,50,123,187,89,96,90,66,65,107,179,89,180,119,101,120,68,63,104,234,93,227,16,15,85,209,129,49,15,14,86,107,55,9,120,100,121,153,145,22,178,88,179,197,6,196,89,88,96,135,138,136,138,215,172,218,115,219,41,42,81,5,195,51,57,43,61,208,171,199,41,81,38,224,53,225,24,144,110,105,52,66,118,229,117,227,34,234,66,107,69,10,109,151,219,48,235,183,62,191,142,129,126,116,111,143,7,163,246,118,117,50,223,222,52,94,19,141,222,221,65,196,3,197,45,220,44,156,70,139,188,122,245,139,71,162,145,153,159,149,170,150,122,188,196,206,216,92,163,144,161,164,2,167,242,141,241,0,164,37,11,72,12,144,145,160,12,38,13,70,63,71,31,226,111,157,158,154,36,101,205,203,206,165,126,209,217,98,165,97,237,220,218,237,239,241,210,214,169,140,171,32,241,125,237,179,86,178,180,85,179,181,84,180,182,83,181,194,201,182,177,137,132,184,76,183,185,61,184,186,57,185,216,212,186,192,214,187,139,34,156,218,79,237,147,123,177,45,44,4,208,201,32,98,64,129,192,213,138,235,59,219,141,242,97,97,2,141,240,75,235,229,24,228,31,25,226,230,23,229,231,22,230,232,26,231,233,112,232,244,189,243,189,221,190,222,28,221,223,27,222,224,29,223,225,30,224,113,247,225,99,60,240,213,147,215,60,20,166,192,187,213,243,112,244,244,233,245,245,128,188,188,114,174,134,131,220,174,217,236,236,198,134,215,177,58,156,143,124,25,110,7,31,228,25,264,356,368,0,11,267,451,452,349,267,302,269,350,357,277,350,452,357,299,333,297,396,175,377,381,384,382,280,347,330,269,303,270,151,9,337,344,278,360,424,418,431,270,304,409,272,310,407,322,270,410,449,450,347,432,422,434,18,313,17,291,306,375,259,387,260,424,335,418,434,364,416,391,423,327,301,251,298,275,281,4,254,373,253,375,307,321,280,425,411,200,421,18,335,321,406,321,320,405,314,315,17,423,426,266,396,377,369,270,322,269,413,417,464,385,386,258,248,456,419,298,284,333,168,417,8,448,346,261,417,413,285,326,327,328,277,355,329,309,392,438,381,382,256,279,429,360,365,364,379,355,277,437,282,443,283,281,275,363,395,431,369,299,297,337,335,273,321,348,450,349,359,446,467,283,293,282,250,458,462,300,276,383,292,308,325,283,276,293,264,372,447,346,352,340,354,274,19,363,456,281,426,436,425,380,381,252,267,269,393,421,200,428,371,266,329,432,287,422,290,250,328,385,258,384,446,265,342,386,387,257,422,424,430,445,342,276,422,273,424,306,292,307,352,366,345,268,271,302,358,423,371,327,294,460,331,279,294,303,271,304,436,432,427,304,272,408,395,394,431,378,395,400,296,334,299,6,351,168,376,352,411,307,325,320,285,295,336,320,319,404,329,330,349,334,293,333,366,323,447,316,15,315,331,358,279,317,14,316,8,285,9,277,329,350,253,374,252,319,318,403,351,6,419,324,318,325,397,367,365,288,435,397,278,344,439,310,272,311,248,195,281,375,273,291,175,396,199,312,311,268,276,283,445,390,373,339,295,282,296,448,449,346,356,264,454,337,336,299,337,338,151,294,278,455,308,292,415,429,358,355,265,340,372,388,390,466,352,346,280,295,442,282,354,19,370,285,441,295,195,248,197,457,440,274,301,300,368,417,351,465,251,301,389,385,380,386,394,395,379,399,412,419,410,436,322,387,373,388,326,2,393,354,370,461,393,164,267,268,302,12,386,374,387,312,268,13,298,293,301,265,446,340,380,385,381,280,330,425,322,426,391,420,429,437,393,391,326,344,440,438,458,459,461,364,434,394,428,396,262,274,354,457,317,316,402,316,315,403,315,314,404,314,313,405,313,421,406,323,366,361,292,306,407,306,291,408,291,287,409,287,432,410,427,434,411,372,264,383,459,309,457,366,352,401,1,274,4,418,421,262,331,294,358,435,433,367,392,289,439,328,462,326,94,2,370,289,305,455,339,254,448,359,255,446,254,253,449,253,252,450,252,256,451,256,341,452,414,413,463,286,441,414,286,258,441,258,257,442,257,259,443,259,260,444,260,467,445,309,459,250,305,289,290,305,290,460,401,376,435,309,250,392,376,411,433,453,341,464,357,453,465,343,357,412,437,343,399,344,360,440,420,437,456,360,420,363,361,401,288,265,372,353,390,339,249,339,448,255]});var ht=E(J=>{const Ee=require("@tensorflow/tfjs"),Q0=Ze(),dt=me(),Z0=it(),$0=at(),J0=ct().default;class lt{constructor(e,t,o,n){this.pipeline=new Z0.Pipeline(e,t,o,n),n&&(this.config=n)}async estimateFaces(e,t){t&&(this.config=t);const o=await this.pipeline.predict(e,t),n=[];for(const s of o||[]){if(s.isDisposedInternal)continue;const i=s.confidence.arraySync();if(i>=this.config.detector.minConfidence){const a=s.coords?s.coords.arraySync():null,c={};if(a&&a.length>0)for(const d in dt.MESH_ANNOTATIONS)(this.config.iris.enabled||d.includes("Iris")===!1)&&(c[d]=dt.MESH_ANNOTATIONS[d].map(l=>a[l]));n.push({confidence:i||0,box:s.box?[s.box.startPoint[0],s.box.startPoint[1],s.box.endPoint[0]-s.box.startPoint[0],s.box.endPoint[1]-s.box.startPoint[1]]:0,mesh:a,annotations:c,image:s.image?Ee.clone(s.image):null})}s.confidence&&s.confidence.dispose(),s.coords&&s.coords.dispose(),s.image&&s.image.dispose()}return n}}async function eo(e){const t=await Promise.all([Q0.load(e),Ee.loadGraphModel(e.mesh.modelPath,{fromTFHub:e.mesh.modelPath.includes("tfhub.dev")}),Ee.loadGraphModel(e.iris.modelPath,{fromTFHub:e.iris.modelPath.includes("tfhub.dev")})]),o=new lt(t[0],t[1],t[2],e);return o}J.load=eo;J.MediaPipeFaceMesh=lt;J.uv_coords=$0;J.triangulation=J0});var mt=E(ie=>{const j=require("@tensorflow/tfjs"),q={};let ut={age:0,gender:""},ve=0;async function to(e){return q.age||(q.age=await j.loadGraphModel(e.face.age.modelPath)),q.age}async function oo(e){return q.gender||(q.gender=await j.loadGraphModel(e.face.gender.modelPath)),q.gender}async function no(e,t){if(vet.face.gender.minConfidence&&(c.gender=d[0]<=.5?"female":"male",c.confidence=l),j.dispose(a)}return j.dispose(n),ut=c,c}ie.predict=no;ie.loadAge=to;ie.loadGender=oo});var gt=E(Pe=>{const L=require("@tensorflow/tfjs"),so=["angry","discust","fear","happy","sad","surpise","neutral"],re={};let ft=[],Te=0;const pt=1.5;async function io(e){return re.emotion||(re.emotion=await L.loadGraphModel(e.face.emotion.modelPath)),re.emotion}async function ro(e,t){if(Tet.face.emotion.minConfidence&&u.push({score:Math.min(.99,Math.trunc(100*pt*h[r])/100),emotion:so[r]});u.sort((r,g)=>g.score-r.score),L.dispose(f)}return L.dispose(l),ft=u,u}Pe.predict=ro;Pe.load=io});var yt=E(xt=>{const bt=require("@tensorflow/tfjs");class ao{constructor(e,t){this.model=e,this.outputStride=t;const o=this.model.inputs[0].shape;bt.util.assert(o[1]===-1&&o[2]===-1,()=>`Input shape [${o[1]}, ${o[2]}] must both be equal to or -1`)}predict(e){return bt.tidy(()=>{const t=this.preprocessInput(e.toFloat()),o=t.expandDims(0),n=this.model.predict(o),s=n.map(a=>a.squeeze([0])),i=this.nameOutputResults(s);return{heatmapScores:i.heatmap.sigmoid(),offsets:i.offsets,displacementFwd:i.displacementFwd,displacementBwd:i.displacementBwd}})}dispose(){this.model.dispose()}}xt.BaseModel=ao});var _e=E(wt=>{const Et=require("@tensorflow/tfjs"),co=yt();class lo extends co.BaseModel{preprocessInput(e){return Et.tidy(()=>Et.div(e,127.5).sub(1))}nameOutputResults(e){const[t,o,n,s]=e;return{offsets:t,heatmap:o,displacementFwd:n,displacementBwd:s}}}wt.MobileNet=lo});var Pt=E(vt=>{function Me(e){return Math.floor(e/2)}class ho{constructor(e,t){this.priorityQueue=new Array(e),this.numberOfElements=-1,this.getElementValue=t}enqueue(e){this.priorityQueue[++this.numberOfElements]=e,this.swim(this.numberOfElements)}dequeue(){const e=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,e}empty(){return this.numberOfElements===-1}size(){return this.numberOfElements+1}all(){return this.priorityQueue.slice(0,this.numberOfElements+1)}max(){return this.priorityQueue[0]}swim(e){for(;e>0&&this.less(Me(e),e);)this.exchange(e,Me(e)),e=Me(e)}sink(e){for(;2*e<=this.numberOfElements;){let t=2*e;if(t{const uo=Pt();function mo(e,t,o,n,s,i){const[a,c]=i.shape;let d=!0;const l=Math.max(o-s,0),u=Math.min(o+s+1,a);for(let f=l;ft){d=!1;break}if(!d)break}return d}function fo(e,t,o){const[n,s,i]=o.shape,a=new uo.MaxHeap(n*s*i,({score:c})=>c);for(let c=0;c{k.partNames=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"];k.NUM_KEYPOINTS=k.partNames.length;k.partIds=k.partNames.reduce((e,t,o)=>(e[t]=o,e),{});const po=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]];k.poseChain=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]];k.connectedPartIndices=po.map(([e,t])=>[k.partIds[e],k.partIds[t]]);k.partChannels=["left_face","right_face","right_upper_leg_front","right_lower_leg_back","right_upper_leg_back","left_lower_leg_front","left_upper_leg_front","left_upper_leg_back","left_lower_leg_back","right_feet","right_lower_leg_front","left_feet","torso_front","torso_back","right_upper_arm_front","right_upper_arm_back","right_lower_arm_back","left_lower_arm_front","left_upper_arm_front","left_upper_arm_back","left_lower_arm_back","right_hand","right_lower_arm_front","left_hand"]});var Se=E(X=>{const go=ee();function Mt(e,t,o,n){return{y:n.get(e,t,o),x:n.get(e,t,o+go.NUM_KEYPOINTS)}}X.getOffsetPoint=Mt;function xo(e,t,o){const{heatmapY:n,heatmapX:s,id:i}=e,{y:a,x:c}=Mt(n,s,i,o);return{x:e.heatmapX*t+c,y:e.heatmapY*t+a}}X.getImageCoords=xo;function bo(e,t){const o=new Array(t);for(let n=0;no?o:e}X.clamp=Ie;function yo(e,t,o,n){const s=o-e,i=n-t;return s*s+i*i}X.squaredDistance=yo;function wo(e,t){return{x:e.x+t.x,y:e.y+t.y}}X.addVectors=wo;function Eo(e,t,o){return{y:Ie(e.y,t,o),x:Ie(e.x,t,o)}}X.clampVector=Eo});var Bt=E(It=>{const te=ee(),Z=Se(),St=te.poseChain.map(([e,t])=>[te.partIds[e],te.partIds[t]]),Re=St.map(([,e])=>e),Rt=St.map(([e])=>e);function vo(e,t,o){const n=o.shape[2]/2;return{y:o.get(t.y,t.x,e),x:o.get(t.y,t.x,n+e)}}function Ae(e,t,o,n){return{y:Z.clamp(Math.round(e.y/t),0,o-1),x:Z.clamp(Math.round(e.x/t),0,n-1)}}function At(e,t,o,n,s,i,a,c=2){const[d,l]=n.shape,u=Ae(t.position,i,d,l),f=vo(e,u,a),h=Z.addVectors(t.position,f);let r=h;for(let _=0;_=0;--h){const r=Re[h],g=Rt[h];d[r]&&!d[g]&&(d[g]=At(h,d[r],g,t,o,n,i))}for(let h=0;h{const To=_t(),_o=Bt(),Dt=Se();function kt(e,t,{x:o,y:n},s){return e.some(({keypoints:i})=>{const a=i[s].position;return Dt.squaredDistance(n,o,a.y,a.x)<=t})}function Mo(e,t,o){const n=o.reduce((s,{position:i,score:a},c)=>(kt(e,t,i,c)||(s+=a),s),0);return n/o.length}const Io=1;function So(e,t,o,n,s,i,a=.5,c=20){const d=[],l=To.buildPartWithScoreQueue(a,Io,e),u=c*c;for(;d.length{const Ro=ee();function Ao(e,t,o){return e(Ao(e[n].score,e[s].score,t)||o.push([e[n],e[s]]),o),[])}W.getAdjacentKeyPoints=Bo;const{NEGATIVE_INFINITY:Nt,POSITIVE_INFINITY:Ct}=Number;function zt(e){return e.reduce(({maxX:t,maxY:o,minX:n,minY:s},{position:{x:i,y:a}})=>({maxX:Math.max(t,i),maxY:Math.max(o,a),minX:Math.min(n,i),minY:Math.min(s,a)}),{maxX:Nt,maxY:Nt,minX:Ct,minY:Ct})}W.getBoundingBox=zt;function Fo(e){const{minX:t,minY:o,maxX:n,maxY:s}=zt(e);return[{x:t,y:o},{x:n,y:o},{x:n,y:s},{x:t,y:s}]}W.getBoundingBoxPoints=Fo;async function Do(e){return Promise.all(e.map(t=>t.buffer()))}W.toTensorBuffers3D=Do;function Ot(e,t,o){return{score:e.score,keypoints:e.keypoints.map(({score:n,part:s,position:i})=>({score:n,part:s,position:{x:i.x*o,y:i.y*t}}))}}W.scalePose=Ot;function ko(e,[t,o]){const n=e.squeeze(0),s=n.resizeBilinear([t,o]);return n.dispose(),s}W.resizeTo=ko;function No(e,[t,o],[n,s]){const i=e.map(a=>Ot(a,t/n,o/s));return i}W.scaleAndFlipPoses=No});var Ht=E(De=>{const Co=require("@tensorflow/tfjs"),zo=_e(),Oo=Be(),ke=Fe();class Lt{constructor(e){this.baseModel=e}async estimatePoses(e,t){const o=t.outputStride,n=e.shape[1],s=e.shape[2],i=ke.resizeTo(e,[t.inputResolution,t.inputResolution]),{heatmapScores:a,offsets:c,displacementFwd:d,displacementBwd:l}=this.baseModel.predict(i),u=await ke.toTensorBuffers3D([a,c,d,l]),f=u[0],h=u[1],r=u[2],g=u[3],P=await Oo.decodeMultiplePoses(f,h,r,g,o,t.maxDetections,t.scoreThreshold,t.nmsRadius),_=ke.scaleAndFlipPoses(P,[n,s],[t.inputResolution,t.inputResolution]);return a.dispose(),c.dispose(),d.dispose(),l.dispose(),i.dispose(),_}dispose(){this.baseModel.dispose()}}De.PoseNet=Lt;async function Lo(e){const t=await Co.loadGraphModel(e.modelPath),o=new zo.MobileNet(t,e.outputStride);return new Lt(o)}async function Ho(e){return Lo(e)}De.load=Ho});var jt=E(A=>{const Uo=_e(),Ut=Ht(),jo=Be(),ae=ee(),oe=Fe();A.load=Ut.load;A.PoseNet=Ut.PoseNet;A.MobileNet=Uo.MobileNet;A.decodeMultiplePoses=jo.decodeMultiplePoses;A.partChannels=ae.partChannels;A.partIds=ae.partIds;A.partNames=ae.partNames;A.poseChain=ae.poseChain;A.getAdjacentKeyPoints=oe.getAdjacentKeyPoints;A.getBoundingBox=oe.getBoundingBox;A.getBoundingBoxPoints=oe.getBoundingBoxPoints;A.scaleAndFlipPoses=oe.scaleAndFlipPoses;A.scalePose=oe.scalePose});var ze=E(G=>{const qo=require("@tensorflow/tfjs");function Ne(e){return[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])]}G.getBoxSize=Ne;function Ce(e){return[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2]}G.getBoxCenter=Ce;function Xo(e,t,o){const n=t.shape[1],s=t.shape[2],i=[[e.startPoint[1]/n,e.startPoint[0]/s,e.endPoint[1]/n,e.endPoint[0]/s]];return qo.image.cropAndResize(t,i,[0],o)}G.cutBoxFromImageAndResize=Xo;function Wo(e,t){const o=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],n=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]],s=e.palmLandmarks.map(i=>{const a=[i[0]*t[0],i[1]*t[1]];return a});return{startPoint:o,endPoint:n,palmLandmarks:s}}G.scaleBoxCoordinates=Wo;function Go(e,t=1.5){const o=Ce(e),n=Ne(e),s=[t*n[0]/2,t*n[1]/2],i=[o[0]-s[0],o[1]-s[1]],a=[o[0]+s[0],o[1]+s[1]];return{startPoint:i,endPoint:a,palmLandmarks:e.palmLandmarks}}G.enlargeBox=Go;function Yo(e){const t=Ce(e),o=Ne(e),n=Math.max(...o),s=n/2,i=[t[0]-s,t[1]-s],a=[t[0]+s,t[1]+s];return{startPoint:i,endPoint:a,palmLandmarks:e.palmLandmarks}}G.squarifyBox=Yo;function Ko(e,t){const o=[e.endPoint[0]-e.startPoint[0],e.endPoint[1]-e.startPoint[1]],n=[o[0]*t[0],o[1]*t[1]],s=[e.startPoint[0]+n[0],e.startPoint[1]+n[1]],i=[e.endPoint[0]+n[0],e.endPoint[1]+n[1]];return{startPoint:s,endPoint:i,palmLandmarks:e.palmLandmarks}}G.shiftBox=Ko});var Xt=E(qt=>{const T=require("@tensorflow/tfjs"),Vo=ze();class Qo{constructor(e,t,o){this.model=e,this.width=o.inputSize,this.height=o.inputSize,this.anchors=t.map(n=>[n.x_center,n.y_center]),this.anchorsTensor=T.tensor2d(this.anchors),this.inputSizeTensor=T.tensor1d([o.inputSize,o.inputSize]),this.doubleInputSizeTensor=T.tensor1d([o.inputSize*2,o.inputSize*2])}normalizeBoxes(e){return T.tidy(()=>{const t=T.slice(e,[0,0],[-1,2]),o=T.slice(e,[0,2],[-1,2]),n=T.add(T.div(t,this.inputSizeTensor),this.anchorsTensor),s=T.div(o,this.doubleInputSizeTensor),i=T.mul(T.sub(n,s),this.inputSizeTensor),a=T.mul(T.add(n,s),this.inputSizeTensor);return T.concat2d([i,a],1)})}normalizeLandmarks(e,t){return T.tidy(()=>{const o=T.add(T.div(e.reshape([-1,7,2]),this.inputSizeTensor),this.anchors[t]);return T.mul(o,this.inputSizeTensor)})}async getBoundingBoxes(e){const t=this.model.predict(e),o=t.squeeze(),n=T.tidy(()=>T.sigmoid(T.slice(o,[0,0],[-1,1])).squeeze()),s=T.slice(o,[0,1],[-1,4]),i=this.normalizeBoxes(s),a=await T.image.nonMaxSuppressionAsync(i,n,this.maxHands,this.iouThreshold,this.scoreThreshold),c=await a.array(),d=[t,a,o,i,s,n],l=T.tidy(()=>{const u=[];for(const f in c){const h=c[f],r=T.slice(i,[h,0],[1,-1]),g=T.slice(o,[h,5],[1,14]),P=T.tidy(()=>this.normalizeLandmarks(g,h).reshape([-1,2]));u.push({boxes:r,palmLandmarks:P})}return u});return d.forEach(u=>u.dispose()),l}async estimateHandBounds(e,t){this.iouThreshold=t.iouThreshold,this.scoreThreshold=t.scoreThreshold,this.maxHands=t.maxHands;const o=e.resizeBilinear([this.width,this.height]),n=o.div(255),s=n.sub(.5),i=s.mul(2);o.dispose(),n.dispose(),s.dispose();const a=await this.getBoundingBoxes(i);if(i.dispose(),!a||a.length===0)return null;const c=[];for(const d in a){const l=a[d],u=await l.boxes.array(),f=u[0].slice(0,2),h=u[0].slice(2,4),r=await l.palmLandmarks.array();l.boxes.dispose(),l.palmLandmarks.dispose(),c.push(Vo.scaleBoxCoordinates({startPoint:f,endPoint:h,palmLandmarks:r},[e.shape[2]/this.width,e.shape[1]/this.height]))}return c}}qt.HandDetector=Qo});var Gt=E(Wt=>{Wt.MESH_ANNOTATIONS={thumb:[1,2,3,4],indexFinger:[5,6,7,8],middleFinger:[9,10,11,12],ringFinger:[13,14,15,16],pinky:[17,18,19,20],palmBase:[0]}});var Zt=E(Y=>{function Yt(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}Y.normalizeRadians=Yt;function Zo(e,t){const o=Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]);return Yt(o)}Y.computeRotation=Zo;const Kt=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]];function $(e,t){let o=0;for(let n=0;n{const Jt=require("@tensorflow/tfjs"),z=ze(),K=Zt(),tn=.8,on=[0,-.4],nn=[0,-.1],sn=1.65,e0=[0,5,9,13,17,1,2],rn=0,an=2;class cn{constructor(e,t,o){this.regionsOfInterest=[],this.runsWithoutHandDetector=0,this.boundingBoxDetector=e,this.meshDetector=t,this.meshWidth=o.inputSize,this.meshHeight=o.inputSize,this.enlargeFactor=o.enlargeFactor}getBoxForPalmLandmarks(e,t){const o=e.map(s=>{const i=[...s,1];return K.rotatePoint(i,t)}),n=this.calculateLandmarksBoundingBox(o);return z.enlargeBox(z.squarifyBox(z.shiftBox(n,on)),this.enlargeFactor)}getBoxForHandLandmarks(e){const t=this.calculateLandmarksBoundingBox(e),o=z.enlargeBox(z.squarifyBox(z.shiftBox(t,nn)),sn),n=[];for(let s=0;s[i[0]*(h[0]-this.meshWidth/2),i[1]*(h[1]-this.meshHeight/2),h[2]]),c=K.buildRotationMatrix(o,[0,0]),d=a.map(h=>{const r=K.rotatePoint(h,c);return[...r,h[2]]}),l=K.invertTransformMatrix(n),u=[...z.getBoxCenter(t),1],f=[K.dot(u,l[0]),K.dot(u,l[1])];return d.map(h=>[h[0]+f[0],h[1]+f[1],h[2]])}async estimateHands(e,t){this.skipFrames=t.skipFrames,this.detectionConfidence=t.minConfidence,this.maxHands=t.maxHands,this.runsWithoutHandDetector++;const o=this.shouldUpdateRegionsOfInterest();if(o===!0){const s=await this.boundingBoxDetector.estimateHandBounds(e,t);this.regionsOfInterest=[];for(const i in s)this.updateRegionsOfInterest(s[i],!0,i);this.runsWithoutHandDetector=0}const n=[];if(!this.regionsOfInterest)return n;for(const s in this.regionsOfInterest){const i=this.regionsOfInterest[s][0];if(!i)return n;const a=K.computeRotation(i.palmLandmarks[rn],i.palmLandmarks[an]),c=z.getBoxCenter(i),d=[c[0]/e.shape[2],c[1]/e.shape[1]],l=Jt.image.rotateWithOffset(e,a,0,d),u=K.buildRotationMatrix(-a,c),f=o?this.getBoxForPalmLandmarks(i.palmLandmarks,u):i,h=z.cutBoxFromImageAndResize(f,l,[this.meshWidth,this.meshHeight]),r=h.div(255);h.dispose(),l.dispose();const g=this.meshDetector.predict(r),[P,_]=g;r.dispose();const v=P.dataSync()[0];if(P.dispose(),vi[0]),o=e.map(i=>i[1]),n=[Math.min(...t),Math.min(...o)],s=[Math.max(...t),Math.max(...o)];return{startPoint:n,endPoint:s}}updateRegionsOfInterest(e,t,o){if(t)this.regionsOfInterest[o]=[e];else{const n=this.regionsOfInterest[o][0];let s=0;if(n!=null&&n.startPoint!=null){const[i,a]=e.startPoint,[c,d]=e.endPoint,[l,u]=n.startPoint,[f,h]=n.endPoint,r=Math.max(i,l),g=Math.max(a,u),P=Math.min(c,f),_=Math.min(d,h),v=(P-r)*(_-g),y=(c-i)*(d-a),B=(f-l)*(h-a);s=v/(y+B-v)}this.regionsOfInterest[o][0]=s>tn?n:e}}shouldUpdateRegionsOfInterest(){return!this.regionsOfInterest||this.regionsOfInterest.length===0||this.runsWithoutHandDetector>=this.skipFrames}}$t.HandPipeline=cn});var s0=E(Oe=>{const ce=require("@tensorflow/tfjs"),dn=Xt(),o0=Gt(),ln=t0();class n0{constructor(e){this.pipeline=e}async estimateHands(e,t){this.skipFrames=t.skipFrames,this.detectionConfidence=t.minConfidence,this.maxHands=t.maxHands;const o=await this.pipeline.estimateHands(e,t),n=[];if(!o)return n;for(const s of o){if(!s)return[];const i={};for(const a of Object.keys(o0.MESH_ANNOTATIONS))i[a]=o0.MESH_ANNOTATIONS[a].map(c=>s.landmarks[c]);n.push({confidence:s.confidence||0,box:s.box?[s.box.topLeft[0],s.box.topLeft[1],s.box.bottomRight[0]-s.box.topLeft[0],s.box.bottomRight[1]-s.box.topLeft[1]]:0,landmarks:s.landmarks,annotations:i})}return n}}Oe.HandPose=n0;async function hn(e){if(ce.env().features.IS_NODE){const t=require("fs"),o=await t.readFileSync(e.replace("file://",""));return JSON.parse(o)}return ce.util.fetch(e).then(t=>t.json())}async function un(e){const[t,o,n]=await Promise.all([hn(e.detector.anchors),ce.loadGraphModel(e.detector.modelPath,{fromTFHub:e.detector.modelPath.includes("tfhub.dev")}),ce.loadGraphModel(e.skeleton.modelPath,{fromTFHub:e.skeleton.modelPath.includes("tfhub.dev")})]),s=new dn.HandDetector(o,t,e),i=new ln.HandPipeline(s,n,e),a=new n0(i);return a}Oe.load=un});var r0=E(i0=>{const mn=function(e,t,o){const n=function(c,d,l){const u=new RegExp("\\b"+d+" \\w+ (\\w+)","ig");c.replace(u,(f,h)=>(l[h]=0,f))},s=function(c,d,l){const u=c.createShader(l);if(c.shaderSource(u,d),c.compileShader(u),!c.getShaderParameter(u,c.COMPILE_STATUS))throw new Error("Filter: GL compile failed",c.getShaderInfoLog(u));return u};this.uniform={},this.attribute={};const i=s(e,t,e.VERTEX_SHADER),a=s(e,o,e.FRAGMENT_SHADER);if(this.id=e.createProgram(),e.attachShader(this.id,i),e.attachShader(this.id,a),e.linkProgram(this.id),!e.getProgramParameter(this.id,e.LINK_STATUS))throw new Error("Filter: GL link failed",e.getProgramInfoLog(this.id));e.useProgram(this.id),n(t,"attribute",this.attribute);for(const c in this.attribute)this.attribute[c]=e.getAttribLocation(this.id,c);n(t,"uniform",this.uniform),n(o,"uniform",this.uniform);for(const c in this.uniform)this.uniform[c]=e.getUniformLocation(this.id,c)},fn=function(e){e||(e={});let t=0,o=null,n=!1,s=-1,i=[null,null],a=[],c=-1,d=-1,l=null,u=null;const f=e.canvas||document.createElement("canvas"),h={},r=f.getContext("webgl")||f.getContext("experimental-webgl");if(!r)throw new Error("Filter: getContext() failed");this.addFilter=function(x){const m=Array.prototype.slice.call(arguments,1),b=p[x];a.push({func:b,args:m})},this.reset=function(){a=[]},this.apply=function(x){if(g(x.width,x.height),t=0,o||(o=r.createTexture()),r.bindTexture(r.TEXTURE_2D,o),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,x),a.length===0){const m=y(F.FRAGMENT_IDENTITY);return v(),f}for(let m=0;m()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),E0=e=>We(e,"__esModule",{value:!0}),Ge=(e,t)=>{E0(e);for(var o in t)We(e,o,{get:t[o],enumerable:!0})};var Ze=E(ne=>{const w=require("@tensorflow/tfjs"),Ye=6;function v0(e){const t={strides:[e/16,e/8],anchors:[2,6]},o=[];for(let n=0;n{e.startEndTensor.dispose(),e.startPoint.dispose(),e.endPoint.dispose()},Ve=e=>({startEndTensor:e,startPoint:w.slice(e,[0,0],[-1,2]),endPoint:w.slice(e,[0,2],[-1,2])}),P0=(e,t)=>{const o=w.mul(e.startPoint,t),n=w.mul(e.endPoint,t),s=w.concat2d([o,n],1);return Ve(s)};function T0(e,t,o){const n=w.slice(e,[0,1],[-1,2]),s=w.add(n,t),i=w.slice(e,[0,3],[-1,2]),a=w.div(i,o),c=w.div(s,o),d=w.div(a,2),l=w.sub(c,d),u=w.add(c,d),f=w.mul(l,o),h=w.mul(u,o),r=1;return w.concat2d([f,h],r)}function _0(e,t){return w.tidy(()=>{const o=e.box?e.box:e;return P0(o,t).startEndTensor.squeeze()})}class Qe{constructor(e,t){this.blazeFaceModel=e,this.width=t.detector.inputSize,this.height=t.detector.inputSize,this.maxFaces=t.detector.maxFaces,this.anchorsData=v0(t.detector.inputSize),this.anchors=w.tensor2d(this.anchorsData),this.inputSize=w.tensor1d([this.width,this.height]),this.iouThreshold=t.detector.iouThreshold,this.scaleFaces=.8,this.scoreThreshold=t.detector.scoreThreshold}async getBoundingBoxes(e){if(!e||e.isDisposedInternal||e.shape.length!==4||e.shape[1]<1||e.shape[2]<1)return null;const[t,o,n]=w.tidy(()=>{const l=e.resizeBilinear([this.width,this.height]),u=w.mul(w.sub(l.div(255),.5),2),f=this.blazeFaceModel.predict(u);let h;if(Array.isArray(f)){const P=f.sort((F,p)=>F.size-p.size),T=w.concat([P[0],P[2]],2),y=w.concat([P[1],P[3]],2),B=w.concat([y,T],1);h=B.squeeze(0)}else h=f.squeeze();const r=T0(h,this.anchors,this.inputSize),b=w.slice(h,[0,0],[-1,1]),_=w.sigmoid(b).squeeze();return[h,r,_]}),s=await w.image.nonMaxSuppressionAsync(o,n,this.maxFaces,this.iouThreshold,this.scoreThreshold),i=await s.array();s.dispose();const a=i.map(l=>w.slice(o,[l,0],[1,-1])),c=await Promise.all(a.map(async l=>{const u=await l.array();return l.dispose(),u})),d=[];for(let l=0;l{const s=_0(n,o),[i,a,c]=await Promise.all([n.landmarks,s,n.probability].map(async r=>r.array())),d=n.anchor,[l,u]=o,f=i.map(r=>[(r[0]+d[0])*l,(r[1]+d[1])*u]),h={topLeft:a.slice(0,2),bottomRight:a.slice(2),landmarks:f,probability:c};return Ke(n.box),n.landmarks.dispose(),n.probability.dispose(),s.dispose(),h}))}}async function M0(e){const t=await w.loadGraphModel(e.detector.modelPath,{fromTFHub:e.detector.modelPath.includes("tfhub.dev")}),o=new Qe(t,e);return o}ne.load=M0;ne.BlazeFaceModel=Qe;ne.disposeBox=Ke});var me=E(ue=>{ue.MESH_ANNOTATIONS={silhouette:[10,338,297,332,284,251,389,356,454,323,361,288,397,365,379,378,400,377,152,148,176,149,150,136,172,58,132,93,234,127,162,21,54,103,67,109],lipsUpperOuter:[61,185,40,39,37,0,267,269,270,409,291],lipsLowerOuter:[146,91,181,84,17,314,405,321,375,291],lipsUpperInner:[78,191,80,81,82,13,312,311,310,415,308],lipsLowerInner:[78,95,88,178,87,14,317,402,318,324,308],rightEyeUpper0:[246,161,160,159,158,157,173],rightEyeLower0:[33,7,163,144,145,153,154,155,133],rightEyeUpper1:[247,30,29,27,28,56,190],rightEyeLower1:[130,25,110,24,23,22,26,112,243],rightEyeUpper2:[113,225,224,223,222,221,189],rightEyeLower2:[226,31,228,229,230,231,232,233,244],rightEyeLower3:[143,111,117,118,119,120,121,128,245],rightEyebrowUpper:[156,70,63,105,66,107,55,193],rightEyebrowLower:[35,124,46,53,52,65],rightEyeIris:[473,474,475,476,477],leftEyeUpper0:[466,388,387,386,385,384,398],leftEyeLower0:[263,249,390,373,374,380,381,382,362],leftEyeUpper1:[467,260,259,257,258,286,414],leftEyeLower1:[359,255,339,254,253,252,256,341,463],leftEyeUpper2:[342,445,444,443,442,441,413],leftEyeLower2:[446,261,448,449,450,451,452,453,464],leftEyeLower3:[372,340,346,347,348,349,350,357,465],leftEyebrowUpper:[383,300,293,334,296,336,285,417],leftEyebrowLower:[265,353,276,283,282,295],leftEyeIris:[468,469,470,471,472],midwayBetweenEyes:[168],noseTip:[1],noseBottom:[2],noseRightCorner:[98],noseLeftCorner:[327],rightCheek:[205],leftCheek:[425]};ue.MESH_TO_IRIS_INDICES_MAP=[{key:"EyeUpper0",indices:[9,10,11,12,13,14,15]},{key:"EyeUpper1",indices:[25,26,27,28,29,30,31]},{key:"EyeUpper2",indices:[41,42,43,44,45,46,47]},{key:"EyeLower0",indices:[0,1,2,3,4,5,6,7,8]},{key:"EyeLower1",indices:[16,17,18,19,20,21,22,23,24]},{key:"EyeLower2",indices:[32,33,34,35,36,37,38,39,40]},{key:"EyeLower3",indices:[54,55,56,57,58,59,60,61,62]},{key:"EyebrowUpper",indices:[63,64,65,66,67,68,69,70]},{key:"EyebrowLower",indices:[48,49,50,51,52,53]}]});var $e=E(V=>{const I0=require("@tensorflow/tfjs");function S0(e,t){const o=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],n=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]];return{startPoint:o,endPoint:n}}V.scaleBoxCoordinates=S0;function fe(e){return[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])]}V.getBoxSize=fe;function pe(e){return[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2]}V.getBoxCenter=pe;function R0(e,t,o){const n=t.shape[1],s=t.shape[2],i=[[e.startPoint[1]/n,e.startPoint[0]/s,e.endPoint[1]/n,e.endPoint[0]/s]];return I0.image.cropAndResize(t,i,[0],o)}V.cutBoxFromImageAndResize=R0;function A0(e,t=1.5){const o=pe(e),n=fe(e),s=[t*n[0]/2,t*n[1]/2],i=[o[0]-s[0],o[1]-s[1]],a=[o[0]+s[0],o[1]+s[1]];return{startPoint:i,endPoint:a,landmarks:e.landmarks}}V.enlargeBox=A0;function B0(e){const t=pe(e),o=fe(e),n=Math.max(...o),s=n/2,i=[t[0]-s,t[1]-s],a=[t[0]+s,t[1]+s];return{startPoint:i,endPoint:a,landmarks:e.landmarks}}V.squarifyBox=B0});var nt=E(D=>{D.IDENTITY_MATRIX=[[1,0,0],[0,1,0],[0,0,1]];function Je(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}D.normalizeRadians=Je;function F0(e,t){const o=Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]);return Je(o)}D.computeRotation=F0;function D0(e){return e*180/Math.PI}D.radToDegrees=D0;function et(e,t){return[[1,0,e],[0,1,t],[0,0,1]]}function Q(e,t){let o=0;for(let n=0;n{const O=require("@tensorflow/tfjs"),C=$e(),H=me(),U=nt(),O0=468,L0=.25,H0=13,U0=[H0,H.MESH_ANNOTATIONS.midwayBetweenEyes[0]],j0=3,q0=2,X0=[j0,q0],ge=H.MESH_ANNOTATIONS.leftEyeLower0,xe=[ge[0],ge[ge.length-1]],be=H.MESH_ANNOTATIONS.rightEyeLower0,ye=[be[0],be[be.length-1]],W0=3,G0=4,Y0=71,we=76;function se(e,t,o,n){for(let s=0;s[i[0]*(h[0]-this.meshWidth/2),i[1]*(h[1]-this.meshHeight/2),h[2]]),c=U.buildRotationMatrix(o,[0,0]),d=a.map(h=>[...U.rotatePoint(h,c),h[2]]),l=U.invertTransformMatrix(n),u=[...C.getBoxCenter({startPoint:t.startPoint,endPoint:t.endPoint}),1],f=[U.dot(u,l[0]),U.dot(u,l[1])];return d.map(h=>[h[0]+f[0],h[1]+f[1],h[2]])}getLeftToRightEyeDepthDifference(e){const t=e[xe[0]][2],o=e[ye[0]][2];return t-o}getEyeBox(e,t,o,n,s=!1){const i=C.squarifyBox(C.enlargeBox(this.calculateLandmarksBoundingBox([e[o],e[n]]),this.irisEnlarge)),a=C.getBoxSize(i);let c=O.image.cropAndResize(t,[[i.startPoint[1]/this.meshHeight,i.startPoint[0]/this.meshWidth,i.endPoint[1]/this.meshHeight,i.endPoint[0]/this.meshWidth]],[0],[this.irisSize,this.irisSize]);return s&&(c=O.image.flipLeftRight(c)),{box:i,boxSize:a,crop:c}}getEyeCoords(e,t,o,n=!1){const s=[];for(let i=0;i{let d=i;return c===2?d=n:c===4&&(d=s),[a[0],a[1],d]})}async predict(e,t){if(this.skipFrames=t.detector.skipFrames,this.maxFaces=t.detector.maxFaces,this.runsWithoutFaceDetector++,this.shouldUpdateRegionsOfInterest()){const n=await this.boundingBoxDetector.getBoundingBoxes(e);if(n.boxes.length===0)return this.regionsOfInterest=[],null;const s=n.boxes.map(i=>{const a=i.box.startPoint.squeeze(),c=i.box.endPoint.squeeze(),d={startPoint:a.arraySync(),endPoint:c.arraySync()};a.dispose(),c.dispose();const l=C.scaleBoxCoordinates(d,n.scaleFactor),u=C.enlargeBox(l),f=i.landmarks.arraySync();return i.box.startPoint.dispose(),i.box.endPoint.dispose(),i.landmarks.dispose(),i.probability.dispose(),{...u,landmarks:f}});this.updateRegionsOfInterest(s),this.runsWithoutFaceDetector=0}const o=O.tidy(()=>this.regionsOfInterest.map((n,s)=>{let i=0;const a=n.landmarks.length>=O0;let[c,d]=U0;a===!1&&([c,d]=X0),i=U.computeRotation(n.landmarks[c],n.landmarks[d]);const l=C.getBoxCenter({startPoint:n.startPoint,endPoint:n.endPoint}),u=[l[0]/e.shape[2],l[1]/e.shape[1]];let f=e,h=U.IDENTITY_MATRIX;i!==0&&(f=O.image.rotateWithOffset(e,i,0,u),h=U.buildRotationMatrix(-i,l));const r={startPoint:n.startPoint,endPoint:n.endPoint},b=C.cutBoxFromImageAndResize(r,f,[this.meshHeight,this.meshWidth]).div(255),[,_,P]=this.meshDetector.predict(b),T=O.reshape(P,[-1,3]);let y=T.arraySync();if(t.iris.enabled){const{box:m,boxSize:x,crop:M}=this.getEyeBox(y,b,xe[0],xe[1],!0),{box:S,boxSize:N,crop:f0}=this.getEyeBox(y,b,ye[0],ye[1]),He=this.irisModel.predict(O.concat([M,f0])),Ue=He.dataSync();He.dispose();const p0=Ue.slice(0,we*3),{rawCoords:je,iris:g0}=this.getEyeCoords(p0,m,x,!0),x0=Ue.slice(we*3),{rawCoords:qe,iris:b0}=this.getEyeCoords(x0,S,N),Xe=this.getLeftToRightEyeDepthDifference(y);Math.abs(Xe)<30?(se(y,je,"left"),se(y,qe,"right")):Xe<1?se(y,je,"left",["EyeUpper0","EyeLower0"]):se(y,qe,"right",["EyeUpper0","EyeLower0"]);const y0=this.getAdjustedIrisCoords(y,g0,"left"),w0=this.getAdjustedIrisCoords(y,b0,"right");y=y.concat(y0).concat(w0)}const B=this.transformRawCoords(y,n,i,h);O.dispose(y);const F=C.enlargeBox(this.calculateLandmarksBoundingBox(B)),p=_.squeeze();if(O.dispose(_),t.mesh.enabled){const m=O.tensor2d(B);this.regionsOfInterest[s]={...F,landmarks:m.arraySync()};const x={coords:m,box:F,confidence:p,image:b};return x}const g={coords:null,box:F,confidence:p,image:b};return g}));return o}updateRegionsOfInterest(e){for(let t=0;t=this.skipFrames}calculateLandmarksBoundingBox(e){const t=e.map(i=>i[0]),o=e.map(i=>i[1]),n=[Math.min(...t),Math.min(...o)],s=[Math.max(...t),Math.max(...o)];return{startPoint:n,endPoint:s,landmarks:e}}}st.Pipeline=K0});var at=E(rt=>{rt.UV_COORDS=[[.499976992607117,.652534008026123],[.500025987625122,.547487020492554],[.499974012374878,.602371990680695],[.482113003730774,.471979022026062],[.500150978565216,.527155995368958],[.499909996986389,.498252987861633],[.499523013830185,.40106201171875],[.289712011814117,.380764007568359],[.499954998493195,.312398016452789],[.499987006187439,.269918978214264],[.500023007392883,.107050001621246],[.500023007392883,.666234016418457],[.5000159740448,.679224014282227],[.500023007392883,.692348003387451],[.499976992607117,.695277988910675],[.499976992607117,.70593398809433],[.499976992607117,.719385027885437],[.499976992607117,.737019002437592],[.499967992305756,.781370997428894],[.499816000461578,.562981009483337],[.473773002624512,.573909997940063],[.104906998574734,.254140973091125],[.365929991006851,.409575998783112],[.338757991790771,.41302502155304],[.311120003461838,.409460008144379],[.274657994508743,.389131009578705],[.393361985683441,.403706014156342],[.345234006643295,.344011008739471],[.370094001293182,.346076011657715],[.319321990013123,.347265005111694],[.297903001308441,.353591024875641],[.24779200553894,.410809993743896],[.396889001131058,.842755019664764],[.280097991228104,.375599980354309],[.106310002505779,.399955987930298],[.2099249958992,.391353011131287],[.355807989835739,.534406006336212],[.471751004457474,.65040397644043],[.474155008792877,.680191993713379],[.439785003662109,.657229006290436],[.414617002010345,.66654098033905],[.450374007225037,.680860996246338],[.428770989179611,.682690978050232],[.374971002340317,.727805018424988],[.486716985702515,.547628998756409],[.485300987958908,.527395009994507],[.257764995098114,.314490020275116],[.401223003864288,.455172002315521],[.429818987846375,.548614978790283],[.421351999044418,.533740997314453],[.276895999908447,.532056987285614],[.483370006084442,.499586999416351],[.33721199631691,.282882988452911],[.296391993761063,.293242990970612],[.169294998049736,.193813979625702],[.447580009698868,.302609980106354],[.392390012741089,.353887975215912],[.354490011930466,.696784019470215],[.067304998636246,.730105042457581],[.442739009857178,.572826027870178],[.457098007202148,.584792017936707],[.381974011659622,.694710969924927],[.392388999462128,.694203019142151],[.277076005935669,.271932005882263],[.422551989555359,.563233017921448],[.385919004678726,.281364023685455],[.383103013038635,.255840003490448],[.331431001424789,.119714021682739],[.229923993349075,.232002973556519],[.364500999450684,.189113974571228],[.229622006416321,.299540996551514],[.173287004232407,.278747975826263],[.472878992557526,.666198015213013],[.446828007698059,.668527007102966],[.422762006521225,.673889994621277],[.445307999849319,.580065965652466],[.388103008270264,.693961024284363],[.403039008378983,.706539988517761],[.403629004955292,.693953037261963],[.460041999816895,.557139039039612],[.431158006191254,.692366003990173],[.452181994915009,.692366003990173],[.475387006998062,.692366003990173],[.465828001499176,.779190003871918],[.472328990697861,.736225962638855],[.473087012767792,.717857003211975],[.473122000694275,.704625964164734],[.473033010959625,.695277988910675],[.427942007780075,.695277988910675],[.426479011774063,.703539967536926],[.423162013292313,.711845993995667],[.4183090031147,.720062971115112],[.390094995498657,.639572978019714],[.013953999616206,.560034036636353],[.499913990497589,.58014702796936],[.413199990987778,.69539999961853],[.409626007080078,.701822996139526],[.468080013990402,.601534962654114],[.422728985548019,.585985004901886],[.463079988956451,.593783974647522],[.37211999297142,.47341400384903],[.334562003612518,.496073007583618],[.411671012639999,.546965003013611],[.242175996303558,.14767599105835],[.290776997804642,.201445996761322],[.327338010072708,.256527006626129],[.399509996175766,.748921036720276],[.441727995872498,.261676013469696],[.429764986038208,.187834024429321],[.412198007106781,.108901023864746],[.288955003023148,.398952007293701],[.218936994671822,.435410976409912],[.41278201341629,.398970007896423],[.257135003805161,.355440020561218],[.427684992551804,.437960982322693],[.448339998722076,.536936044692993],[.178560003638268,.45755398273468],[.247308000922203,.457193970680237],[.286267012357712,.467674970626831],[.332827985286713,.460712015628815],[.368755996227264,.447206974029541],[.398963987827301,.432654976844788],[.476410001516342,.405806005001068],[.189241006970406,.523923993110657],[.228962004184723,.348950982093811],[.490725994110107,.562400996685028],[.404670000076294,.485132992267609],[.019469000399113,.401564002037048],[.426243007183075,.420431017875671],[.396993011236191,.548797011375427],[.266469985246658,.376977026462555],[.439121007919312,.51895797252655],[.032313998788595,.644356966018677],[.419054001569748,.387154996395111],[.462783008813858,.505746960639954],[.238978996872902,.779744982719421],[.198220998048782,.831938028335571],[.107550002634525,.540755033493042],[.183610007166862,.740257024765015],[.134409993886948,.333683013916016],[.385764002799988,.883153975009918],[.490967005491257,.579378008842468],[.382384985685349,.508572995662689],[.174399003386497,.397670984268188],[.318785011768341,.39623498916626],[.343364000320435,.400596976280212],[.396100014448166,.710216999053955],[.187885001301765,.588537991046906],[.430987000465393,.944064974784851],[.318993002176285,.898285031318665],[.266247987747192,.869701027870178],[.500023007392883,.190576016902924],[.499976992607117,.954452991485596],[.366169989109039,.398822009563446],[.393207013607025,.39553701877594],[.410373002290726,.391080021858215],[.194993004202843,.342101991176605],[.388664990663528,.362284004688263],[.365961998701096,.355970978736877],[.343364000320435,.355356991291046],[.318785011768341,.35834002494812],[.301414996385574,.363156020641327],[.058132998645306,.319076001644135],[.301414996385574,.387449026107788],[.499987989664078,.618434011936188],[.415838003158569,.624195992946625],[.445681989192963,.566076993942261],[.465844005346298,.620640993118286],[.49992299079895,.351523995399475],[.288718998432159,.819945991039276],[.335278987884521,.852819979190826],[.440512001514435,.902418971061707],[.128294005990028,.791940987110138],[.408771991729736,.373893976211548],[.455606997013092,.451801002025604],[.499877005815506,.908990025520325],[.375436991453171,.924192011356354],[.11421000212431,.615022003650665],[.448662012815475,.695277988910675],[.4480200111866,.704632043838501],[.447111994028091,.715808033943176],[.444831997156143,.730794012546539],[.430011987686157,.766808986663818],[.406787008047104,.685672998428345],[.400738000869751,.681069016456604],[.392399996519089,.677703022956848],[.367855995893478,.663918972015381],[.247923001646996,.601333022117615],[.452769994735718,.420849978923798],[.43639200925827,.359887003898621],[.416164010763168,.368713974952698],[.413385987281799,.692366003990173],[.228018000721931,.683571994304657],[.468268007040024,.352671027183533],[.411361992359161,.804327011108398],[.499989002943039,.469825029373169],[.479153990745544,.442654013633728],[.499974012374878,.439637005329132],[.432112008333206,.493588984012604],[.499886006116867,.866917014122009],[.49991300702095,.821729004383087],[.456548988819122,.819200992584229],[.344549000263214,.745438992977142],[.37890899181366,.574010014533997],[.374292999505997,.780184984207153],[.319687992334366,.570737957954407],[.357154995203018,.604269981384277],[.295284003019333,.621580958366394],[.447750002145767,.862477004528046],[.410986006259918,.508723020553589],[.31395098567009,.775308012962341],[.354128003120422,.812552988529205],[.324548006057739,.703992962837219],[.189096003770828,.646299958229065],[.279776990413666,.71465802192688],[.1338230073452,.682700991630554],[.336768001317978,.644733011722565],[.429883986711502,.466521978378296],[.455527991056442,.548622965812683],[.437114000320435,.558896005153656],[.467287987470627,.529924988746643],[.414712011814117,.335219979286194],[.37704598903656,.322777986526489],[.344107985496521,.320150971412659],[.312875986099243,.32233202457428],[.283526003360748,.333190023899078],[.241245999932289,.382785975933075],[.102986000478268,.468762993812561],[.267612010240555,.424560010433197],[.297879010438919,.433175981044769],[.333433985710144,.433878004550934],[.366427004337311,.426115989685059],[.396012008190155,.416696012020111],[.420121014118195,.41022801399231],[.007561000064015,.480777025222778],[.432949006557465,.569517970085144],[.458638995885849,.479089021682739],[.473466008901596,.545744001865387],[.476087987422943,.563830018043518],[.468472003936768,.555056989192963],[.433990985155106,.582361996173859],[.483518004417419,.562983989715576],[.482482999563217,.57784903049469],[.42645001411438,.389798998832703],[.438998997211456,.39649498462677],[.450067013502121,.400434017181396],[.289712011814117,.368252992630005],[.276670008897781,.363372981548309],[.517862021923065,.471948027610779],[.710287988185883,.380764007568359],[.526226997375488,.573909997940063],[.895093023777008,.254140973091125],[.634069979190826,.409575998783112],[.661242008209229,.41302502155304],[.688880026340485,.409460008144379],[.725341975688934,.389131009578705],[.606630027294159,.40370500087738],[.654766023159027,.344011008739471],[.629905998706818,.346076011657715],[.680678009986877,.347265005111694],[.702096998691559,.353591024875641],[.75221198797226,.410804986953735],[.602918028831482,.842862963676453],[.719901978969574,.375599980354309],[.893692970275879,.399959981441498],[.790081977844238,.391354024410248],[.643998026847839,.534487962722778],[.528249025344849,.65040397644043],[.525849997997284,.680191040039062],[.560214996337891,.657229006290436],[.585384011268616,.66654098033905],[.549625992774963,.680860996246338],[.57122802734375,.682691991329193],[.624852001667023,.72809898853302],[.513050019741058,.547281980514526],[.51509702205658,.527251958847046],[.742246985435486,.314507007598877],[.598631024360657,.454979002475739],[.570338010787964,.548575043678284],[.578631997108459,.533622980117798],[.723087012767792,.532054007053375],[.516445994377136,.499638974666595],[.662801027297974,.282917976379395],[.70362401008606,.293271005153656],[.830704987049103,.193813979625702],[.552385985851288,.302568018436432],[.607609987258911,.353887975215912],[.645429015159607,.696707010269165],[.932694971561432,.730105042457581],[.557260990142822,.572826027870178],[.542901992797852,.584792017936707],[.6180260181427,.694710969924927],[.607590973377228,.694203019142151],[.722943007946014,.271963000297546],[.577413976192474,.563166975975037],[.614082992076874,.281386971473694],[.616907000541687,.255886018276215],[.668509006500244,.119913995265961],[.770092010498047,.232020974159241],[.635536015033722,.189248979091644],[.77039098739624,.299556016921997],[.826722025871277,.278755009174347],[.527121007442474,.666198015213013],[.553171992301941,.668527007102966],[.577238023281097,.673889994621277],[.554691970348358,.580065965652466],[.611896991729736,.693961024284363],[.59696102142334,.706539988517761],[.596370995044708,.693953037261963],[.539958000183105,.557139039039612],[.568841993808746,.692366003990173],[.547818005084991,.692366003990173],[.52461302280426,.692366003990173],[.534089982509613,.779141008853912],[.527670979499817,.736225962638855],[.526912987232208,.717857003211975],[.526877999305725,.704625964164734],[.526966989040375,.695277988910675],[.572058022022247,.695277988910675],[.573521018028259,.703539967536926],[.57683801651001,.711845993995667],[.581691026687622,.720062971115112],[.609944999217987,.639909982681274],[.986046016216278,.560034036636353],[.5867999792099,.69539999961853],[.590372025966644,.701822996139526],[.531915009021759,.601536989212036],[.577268004417419,.585934996604919],[.536915004253387,.593786001205444],[.627542972564697,.473352015018463],[.665585994720459,.495950996875763],[.588353991508484,.546862006187439],[.757824003696442,.14767599105835],[.709249973297119,.201507985591888],[.672684013843536,.256581008434296],[.600408971309662,.74900496006012],[.55826598405838,.261672019958496],[.570303976535797,.187870979309082],[.588165998458862,.109044015407562],[.711045026779175,.398952007293701],[.781069993972778,.435405015945435],[.587247014045715,.398931980133057],[.742869973182678,.355445981025696],[.572156012058258,.437651991844177],[.55186802148819,.536570012569427],[.821442008018494,.457556009292603],[.752701997756958,.457181990146637],[.71375697851181,.467626988887787],[.66711300611496,.460672974586487],[.631101012229919,.447153985500336],[.6008620262146,.432473003864288],[.523481011390686,.405627012252808],[.810747981071472,.523926019668579],[.771045982837677,.348959028720856],[.509127020835876,.562718033790588],[.595292985439301,.485023975372314],[.980530977249146,.401564002037048],[.573499977588654,.420000016689301],[.602994978427887,.548687994480133],[.733529984951019,.376977026462555],[.560611009597778,.519016981124878],[.967685997486115,.644356966018677],[.580985009670258,.387160003185272],[.537728011608124,.505385041236877],[.760966002941132,.779752969741821],[.801778972148895,.831938028335571],[.892440974712372,.54076099395752],[.816350996494293,.740260004997253],[.865594983100891,.333687007427216],[.614073991775513,.883246004581451],[.508952975273132,.579437971115112],[.617941975593567,.508316040039062],[.825608015060425,.397674977779388],[.681214988231659,.39623498916626],[.656635999679565,.400596976280212],[.603900015354156,.710216999053955],[.81208598613739,.588539004325867],[.56801301240921,.944564998149872],[.681007981300354,.898285031318665],[.733752012252808,.869701027870178],[.633830010890961,.398822009563446],[.606792986392975,.39553701877594],[.589659988880157,.391062021255493],[.805015981197357,.342108011245728],[.611334979534149,.362284004688263],[.634037971496582,.355970978736877],[.656635999679565,.355356991291046],[.681214988231659,.35834002494812],[.698584973812103,.363156020641327],[.941866993904114,.319076001644135],[.698584973812103,.387449026107788],[.584177017211914,.624107003211975],[.554318010807037,.566076993942261],[.534153997898102,.62064003944397],[.711217999458313,.819975018501282],[.664629995822906,.852871000766754],[.559099972248077,.902631998062134],[.871706008911133,.791940987110138],[.591234028339386,.373893976211548],[.544341027736664,.451583981513977],[.624562978744507,.924192011356354],[.88577002286911,.615028977394104],[.551338016986847,.695277988910675],[.551980018615723,.704632043838501],[.552887976169586,.715808033943176],[.555167973041534,.730794012546539],[.569944024085999,.767035007476807],[.593203008174896,.685675978660583],[.599261999130249,.681069016456604],[.607599973678589,.677703022956848],[.631937980651855,.663500010967255],[.752032995223999,.601315021514893],[.547226011753082,.420395016670227],[.563543975353241,.359827995300293],[.583841025829315,.368713974952698],[.586614012718201,.692366003990173],[.771915018558502,.683578014373779],[.531597018241882,.352482974529266],[.588370978832245,.804440975189209],[.52079701423645,.442565023899078],[.567984998226166,.493479013442993],[.543282985687256,.819254994392395],[.655317008495331,.745514988899231],[.621008992195129,.574018001556396],[.625559985637665,.78031200170517],[.680198013782501,.570719003677368],[.64276397228241,.604337990283966],[.704662978649139,.621529996395111],[.552012026309967,.862591981887817],[.589071989059448,.508637011051178],[.685944974422455,.775357007980347],[.645735025405884,.812640011310577],[.675342977046967,.703978002071381],[.810858011245728,.646304965019226],[.72012197971344,.714666962623596],[.866151988506317,.682704985141754],[.663187026977539,.644596993923187],[.570082008838654,.466325998306274],[.544561982154846,.548375964164734],[.562758982181549,.558784961700439],[.531987011432648,.530140042304993],[.585271000862122,.335177004337311],[.622952997684479,.32277899980545],[.655896008014679,.320163011550903],[.687132000923157,.322345972061157],[.716481983661652,.333200991153717],[.758756995201111,.382786989212036],[.897013008594513,.468769013881683],[.732392013072968,.424547016620636],[.70211398601532,.433162987232208],[.66652500629425,.433866024017334],[.633504986763,.426087975502014],[.603875994682312,.416586995124817],[.579657971858978,.409945011138916],[.992439985275269,.480777025222778],[.567192018032074,.569419980049133],[.54136598110199,.478899002075195],[.526564002037048,.546118021011353],[.523913025856018,.563830018043518],[.531529009342194,.555056989192963],[.566035985946655,.582329034805298],[.51631098985672,.563053965568542],[.5174720287323,.577877044677734],[.573594987392426,.389806985855103],[.560697972774506,.395331978797913],[.549755990505219,.399751007556915],[.710287988185883,.368252992630005],[.723330020904541,.363372981548309]]});var ct=E(V0=>{Ge(V0,{default:()=>Q0});var Q0=[127,34,139,11,0,37,232,231,120,72,37,39,128,121,47,232,121,128,104,69,67,175,171,148,157,154,155,118,50,101,73,39,40,9,151,108,48,115,131,194,204,211,74,40,185,80,42,183,40,92,186,230,229,118,202,212,214,83,18,17,76,61,146,160,29,30,56,157,173,106,204,194,135,214,192,203,165,98,21,71,68,51,45,4,144,24,23,77,146,91,205,50,187,201,200,18,91,106,182,90,91,181,85,84,17,206,203,36,148,171,140,92,40,39,193,189,244,159,158,28,247,246,161,236,3,196,54,68,104,193,168,8,117,228,31,189,193,55,98,97,99,126,47,100,166,79,218,155,154,26,209,49,131,135,136,150,47,126,217,223,52,53,45,51,134,211,170,140,67,69,108,43,106,91,230,119,120,226,130,247,63,53,52,238,20,242,46,70,156,78,62,96,46,53,63,143,34,227,173,155,133,123,117,111,44,125,19,236,134,51,216,206,205,154,153,22,39,37,167,200,201,208,36,142,100,57,212,202,20,60,99,28,158,157,35,226,113,160,159,27,204,202,210,113,225,46,43,202,204,62,76,77,137,123,116,41,38,72,203,129,142,64,98,240,49,102,64,41,73,74,212,216,207,42,74,184,169,170,211,170,149,176,105,66,69,122,6,168,123,147,187,96,77,90,65,55,107,89,90,180,101,100,120,63,105,104,93,137,227,15,86,85,129,102,49,14,87,86,55,8,9,100,47,121,145,23,22,88,89,179,6,122,196,88,95,96,138,172,136,215,58,172,115,48,219,42,80,81,195,3,51,43,146,61,171,175,199,81,82,38,53,46,225,144,163,110,246,33,7,52,65,66,229,228,117,34,127,234,107,108,69,109,108,151,48,64,235,62,78,191,129,209,126,111,35,143,163,161,246,117,123,50,222,65,52,19,125,141,221,55,65,3,195,197,25,7,33,220,237,44,70,71,139,122,193,245,247,130,33,71,21,162,153,158,159,170,169,150,188,174,196,216,186,92,144,160,161,2,97,167,141,125,241,164,167,37,72,38,12,145,159,160,38,82,13,63,68,71,226,35,111,158,153,154,101,50,205,206,92,165,209,198,217,165,167,97,220,115,218,133,112,243,239,238,241,214,135,169,190,173,133,171,208,32,125,44,237,86,87,178,85,86,179,84,85,180,83,84,181,201,83,182,137,93,132,76,62,183,61,76,184,57,61,185,212,57,186,214,207,187,34,143,156,79,239,237,123,137,177,44,1,4,201,194,32,64,102,129,213,215,138,59,166,219,242,99,97,2,94,141,75,59,235,24,110,228,25,130,226,23,24,229,22,23,230,26,22,231,112,26,232,189,190,243,221,56,190,28,56,221,27,28,222,29,27,223,30,29,224,247,30,225,238,79,20,166,59,75,60,75,240,147,177,215,20,79,166,187,147,213,112,233,244,233,128,245,128,114,188,114,217,174,131,115,220,217,198,236,198,131,134,177,132,58,143,35,124,110,163,7,228,110,25,356,389,368,11,302,267,452,350,349,302,303,269,357,343,277,452,453,357,333,332,297,175,152,377,384,398,382,347,348,330,303,304,270,9,336,337,278,279,360,418,262,431,304,408,409,310,415,407,270,409,410,450,348,347,422,430,434,313,314,17,306,307,375,387,388,260,286,414,398,335,406,418,364,367,416,423,358,327,251,284,298,281,5,4,373,374,253,307,320,321,425,427,411,421,313,18,321,405,406,320,404,405,315,16,17,426,425,266,377,400,369,322,391,269,417,465,464,386,257,258,466,260,388,456,399,419,284,332,333,417,285,8,346,340,261,413,441,285,327,460,328,355,371,329,392,439,438,382,341,256,429,420,360,364,394,379,277,343,437,443,444,283,275,440,363,431,262,369,297,338,337,273,375,321,450,451,349,446,342,467,293,334,282,458,461,462,276,353,383,308,324,325,276,300,293,372,345,447,382,398,362,352,345,340,274,1,19,456,248,281,436,427,425,381,256,252,269,391,393,200,199,428,266,330,329,287,273,422,250,462,328,258,286,384,265,353,342,387,259,257,424,431,430,342,353,276,273,335,424,292,325,307,366,447,345,271,303,302,423,266,371,294,455,460,279,278,294,271,272,304,432,434,427,272,407,408,394,430,431,395,369,400,334,333,299,351,417,168,352,280,411,325,319,320,295,296,336,319,403,404,330,348,349,293,298,333,323,454,447,15,16,315,358,429,279,14,15,316,285,336,9,329,349,350,374,380,252,318,402,403,6,197,419,318,319,325,367,364,365,435,367,397,344,438,439,272,271,311,195,5,281,273,287,291,396,428,199,311,271,268,283,444,445,373,254,339,263,466,249,282,334,296,449,347,346,264,447,454,336,296,299,338,10,151,278,439,455,292,407,415,358,371,355,340,345,372,390,249,466,346,347,280,442,443,282,19,94,370,441,442,295,248,419,197,263,255,359,440,275,274,300,383,368,351,412,465,263,467,466,301,368,389,380,374,386,395,378,379,412,351,419,436,426,322,373,390,388,2,164,393,370,462,461,164,0,267,302,11,12,374,373,387,268,12,13,293,300,301,446,261,340,385,384,381,330,266,425,426,423,391,429,355,437,391,327,326,440,457,438,341,382,362,459,457,461,434,430,394,414,463,362,396,369,262,354,461,457,316,403,402,315,404,403,314,405,404,313,406,405,421,418,406,366,401,361,306,408,407,291,409,408,287,410,409,432,436,410,434,416,411,264,368,383,309,438,457,352,376,401,274,275,4,421,428,262,294,327,358,433,416,367,289,455,439,462,370,326,2,326,370,305,460,455,254,449,448,255,261,446,253,450,449,252,451,450,256,452,451,341,453,452,413,464,463,441,413,414,258,442,441,257,443,442,259,444,443,260,445,444,467,342,445,459,458,250,289,392,290,290,328,460,376,433,435,250,290,392,411,416,433,341,463,464,453,464,465,357,465,412,343,412,399,360,363,440,437,399,456,420,456,363,401,435,288,372,383,353,339,255,249,448,261,255,133,243,190,133,155,112,33,246,247,33,130,25,398,384,286,362,398,414,362,463,341,263,359,467,263,249,255,466,467,260,75,60,166,238,239,79,162,127,139,72,11,37,121,232,120,73,72,39,114,128,47,233,232,128,103,104,67,152,175,148,173,157,155,119,118,101,74,73,40,107,9,108,49,48,131,32,194,211,184,74,185,191,80,183,185,40,186,119,230,118,210,202,214,84,83,17,77,76,146,161,160,30,190,56,173,182,106,194,138,135,192,129,203,98,54,21,68,5,51,4,145,144,23,90,77,91,207,205,187,83,201,18,181,91,182,180,90,181,16,85,17,205,206,36,176,148,140,165,92,39,245,193,244,27,159,28,30,247,161,174,236,196,103,54,104,55,193,8,111,117,31,221,189,55,240,98,99,142,126,100,219,166,218,112,155,26,198,209,131,169,135,150,114,47,217,224,223,53,220,45,134,32,211,140,109,67,108,146,43,91,231,230,120,113,226,247,105,63,52,241,238,242,124,46,156,95,78,96,70,46,63,116,143,227,116,123,111,1,44,19,3,236,51,207,216,205,26,154,22,165,39,167,199,200,208,101,36,100,43,57,202,242,20,99,56,28,157,124,35,113,29,160,27,211,204,210,124,113,46,106,43,204,96,62,77,227,137,116,73,41,72,36,203,142,235,64,240,48,49,64,42,41,74,214,212,207,183,42,184,210,169,211,140,170,176,104,105,69,193,122,168,50,123,187,89,96,90,66,65,107,179,89,180,119,101,120,68,63,104,234,93,227,16,15,85,209,129,49,15,14,86,107,55,9,120,100,121,153,145,22,178,88,179,197,6,196,89,88,96,135,138,136,138,215,172,218,115,219,41,42,81,5,195,51,57,43,61,208,171,199,41,81,38,224,53,225,24,144,110,105,52,66,118,229,117,227,34,234,66,107,69,10,109,151,219,48,235,183,62,191,142,129,126,116,111,143,7,163,246,118,117,50,223,222,52,94,19,141,222,221,65,196,3,197,45,220,44,156,70,139,188,122,245,139,71,162,145,153,159,149,170,150,122,188,196,206,216,92,163,144,161,164,2,167,242,141,241,0,164,37,11,72,12,144,145,160,12,38,13,70,63,71,31,226,111,157,158,154,36,101,205,203,206,165,126,209,217,98,165,97,237,220,218,237,239,241,210,214,169,140,171,32,241,125,237,179,86,178,180,85,179,181,84,180,182,83,181,194,201,182,177,137,132,184,76,183,185,61,184,186,57,185,216,212,186,192,214,187,139,34,156,218,79,237,147,123,177,45,44,4,208,201,32,98,64,129,192,213,138,235,59,219,141,242,97,97,2,141,240,75,235,229,24,228,31,25,226,230,23,229,231,22,230,232,26,231,233,112,232,244,189,243,189,221,190,222,28,221,223,27,222,224,29,223,225,30,224,113,247,225,99,60,240,213,147,215,60,20,166,192,187,213,243,112,244,244,233,245,245,128,188,188,114,174,134,131,220,174,217,236,236,198,134,215,177,58,156,143,124,25,110,7,31,228,25,264,356,368,0,11,267,451,452,349,267,302,269,350,357,277,350,452,357,299,333,297,396,175,377,381,384,382,280,347,330,269,303,270,151,9,337,344,278,360,424,418,431,270,304,409,272,310,407,322,270,410,449,450,347,432,422,434,18,313,17,291,306,375,259,387,260,424,335,418,434,364,416,391,423,327,301,251,298,275,281,4,254,373,253,375,307,321,280,425,411,200,421,18,335,321,406,321,320,405,314,315,17,423,426,266,396,377,369,270,322,269,413,417,464,385,386,258,248,456,419,298,284,333,168,417,8,448,346,261,417,413,285,326,327,328,277,355,329,309,392,438,381,382,256,279,429,360,365,364,379,355,277,437,282,443,283,281,275,363,395,431,369,299,297,337,335,273,321,348,450,349,359,446,467,283,293,282,250,458,462,300,276,383,292,308,325,283,276,293,264,372,447,346,352,340,354,274,19,363,456,281,426,436,425,380,381,252,267,269,393,421,200,428,371,266,329,432,287,422,290,250,328,385,258,384,446,265,342,386,387,257,422,424,430,445,342,276,422,273,424,306,292,307,352,366,345,268,271,302,358,423,371,327,294,460,331,279,294,303,271,304,436,432,427,304,272,408,395,394,431,378,395,400,296,334,299,6,351,168,376,352,411,307,325,320,285,295,336,320,319,404,329,330,349,334,293,333,366,323,447,316,15,315,331,358,279,317,14,316,8,285,9,277,329,350,253,374,252,319,318,403,351,6,419,324,318,325,397,367,365,288,435,397,278,344,439,310,272,311,248,195,281,375,273,291,175,396,199,312,311,268,276,283,445,390,373,339,295,282,296,448,449,346,356,264,454,337,336,299,337,338,151,294,278,455,308,292,415,429,358,355,265,340,372,388,390,466,352,346,280,295,442,282,354,19,370,285,441,295,195,248,197,457,440,274,301,300,368,417,351,465,251,301,389,385,380,386,394,395,379,399,412,419,410,436,322,387,373,388,326,2,393,354,370,461,393,164,267,268,302,12,386,374,387,312,268,13,298,293,301,265,446,340,380,385,381,280,330,425,322,426,391,420,429,437,393,391,326,344,440,438,458,459,461,364,434,394,428,396,262,274,354,457,317,316,402,316,315,403,315,314,404,314,313,405,313,421,406,323,366,361,292,306,407,306,291,408,291,287,409,287,432,410,427,434,411,372,264,383,459,309,457,366,352,401,1,274,4,418,421,262,331,294,358,435,433,367,392,289,439,328,462,326,94,2,370,289,305,455,339,254,448,359,255,446,254,253,449,253,252,450,252,256,451,256,341,452,414,413,463,286,441,414,286,258,441,258,257,442,257,259,443,259,260,444,260,467,445,309,459,250,305,289,290,305,290,460,401,376,435,309,250,392,376,411,433,453,341,464,357,453,465,343,357,412,437,343,399,344,360,440,420,437,456,360,420,363,361,401,288,265,372,353,390,339,249,339,448,255]});var ht=E(J=>{const Ee=require("@tensorflow/tfjs"),Z0=Ze(),dt=me(),$0=it(),J0=at(),eo=ct().default;class lt{constructor(e,t,o,n){this.pipeline=new $0.Pipeline(e,t,o,n),n&&(this.config=n)}async estimateFaces(e,t){t&&(this.config=t);const o=await this.pipeline.predict(e,t),n=[];for(const s of o||[]){if(s.isDisposedInternal)continue;const i=s.confidence.arraySync();if(i>=this.config.detector.minConfidence){const a=s.coords?s.coords.arraySync():null,c={};if(a&&a.length>0)for(const d in dt.MESH_ANNOTATIONS)(this.config.iris.enabled||d.includes("Iris")===!1)&&(c[d]=dt.MESH_ANNOTATIONS[d].map(l=>a[l]));n.push({confidence:i||0,box:s.box?[s.box.startPoint[0],s.box.startPoint[1],s.box.endPoint[0]-s.box.startPoint[0],s.box.endPoint[1]-s.box.startPoint[1]]:0,mesh:a,annotations:c,image:s.image?Ee.clone(s.image):null})}s.confidence&&s.confidence.dispose(),s.coords&&s.coords.dispose(),s.image&&s.image.dispose()}return n}}async function to(e){const t=await Promise.all([Z0.load(e),Ee.loadGraphModel(e.mesh.modelPath,{fromTFHub:e.mesh.modelPath.includes("tfhub.dev")}),Ee.loadGraphModel(e.iris.modelPath,{fromTFHub:e.iris.modelPath.includes("tfhub.dev")})]),o=new lt(t[0],t[1],t[2],e);return o}J.load=to;J.MediaPipeFaceMesh=lt;J.uv_coords=J0;J.triangulation=eo});var mt=E(ie=>{const j=require("@tensorflow/tfjs"),q={};let ut={age:0,gender:""},ve=0;async function oo(e){return q.age||(q.age=await j.loadGraphModel(e.face.age.modelPath)),q.age}async function no(e){return q.gender||(q.gender=await j.loadGraphModel(e.face.gender.modelPath)),q.gender}async function so(e,t){if(vet.face.gender.minConfidence&&(c.gender=d[0]<=.5?"female":"male",c.confidence=l),j.dispose(a)}return j.dispose(n),ut=c,c}ie.predict=so;ie.loadAge=oo;ie.loadGender=no});var gt=E(Pe=>{const L=require("@tensorflow/tfjs"),io=["angry","discust","fear","happy","sad","surpise","neutral"],re={};let ft=[],Te=0;const pt=1.5;async function ro(e){return re.emotion||(re.emotion=await L.loadGraphModel(e.face.emotion.modelPath)),re.emotion}async function ao(e,t){if(Tet.face.emotion.minConfidence&&u.push({score:Math.min(.99,Math.trunc(100*pt*h[r])/100),emotion:io[r]});u.sort((r,b)=>b.score-r.score),L.dispose(f)}return L.dispose(l),ft=u,u}Pe.predict=ao;Pe.load=ro});var yt=E(xt=>{const bt=require("@tensorflow/tfjs");class co{constructor(e,t){this.model=e,this.outputStride=t;const o=this.model.inputs[0].shape;bt.util.assert(o[1]===-1&&o[2]===-1,()=>`Input shape [${o[1]}, ${o[2]}] must both be equal to or -1`)}predict(e){return bt.tidy(()=>{const t=this.preprocessInput(e.toFloat()),o=t.expandDims(0),n=this.model.predict(o),s=n.map(a=>a.squeeze([0])),i=this.nameOutputResults(s);return{heatmapScores:i.heatmap.sigmoid(),offsets:i.offsets,displacementFwd:i.displacementFwd,displacementBwd:i.displacementBwd}})}dispose(){this.model.dispose()}}xt.BaseModel=co});var _e=E(wt=>{const Et=require("@tensorflow/tfjs"),lo=yt();class ho extends lo.BaseModel{preprocessInput(e){return Et.tidy(()=>Et.div(e,127.5).sub(1))}nameOutputResults(e){const[t,o,n,s]=e;return{offsets:t,heatmap:o,displacementFwd:n,displacementBwd:s}}}wt.MobileNet=ho});var Pt=E(vt=>{function Me(e){return Math.floor(e/2)}class uo{constructor(e,t){this.priorityQueue=new Array(e),this.numberOfElements=-1,this.getElementValue=t}enqueue(e){this.priorityQueue[++this.numberOfElements]=e,this.swim(this.numberOfElements)}dequeue(){const e=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,e}empty(){return this.numberOfElements===-1}size(){return this.numberOfElements+1}all(){return this.priorityQueue.slice(0,this.numberOfElements+1)}max(){return this.priorityQueue[0]}swim(e){for(;e>0&&this.less(Me(e),e);)this.exchange(e,Me(e)),e=Me(e)}sink(e){for(;2*e<=this.numberOfElements;){let t=2*e;if(t{const mo=Pt();function fo(e,t,o,n,s,i){const[a,c]=i.shape;let d=!0;const l=Math.max(o-s,0),u=Math.min(o+s+1,a);for(let f=l;ft){d=!1;break}if(!d)break}return d}function po(e,t,o){const[n,s,i]=o.shape,a=new mo.MaxHeap(n*s*i,({score:c})=>c);for(let c=0;c{k.partNames=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"];k.NUM_KEYPOINTS=k.partNames.length;k.partIds=k.partNames.reduce((e,t,o)=>(e[t]=o,e),{});const go=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]];k.poseChain=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]];k.connectedPartIndices=go.map(([e,t])=>[k.partIds[e],k.partIds[t]]);k.partChannels=["left_face","right_face","right_upper_leg_front","right_lower_leg_back","right_upper_leg_back","left_lower_leg_front","left_upper_leg_front","left_upper_leg_back","left_lower_leg_back","right_feet","right_lower_leg_front","left_feet","torso_front","torso_back","right_upper_arm_front","right_upper_arm_back","right_lower_arm_back","left_lower_arm_front","left_upper_arm_front","left_upper_arm_back","left_lower_arm_back","right_hand","right_lower_arm_front","left_hand"]});var Se=E(X=>{const xo=ee();function Mt(e,t,o,n){return{y:n.get(e,t,o),x:n.get(e,t,o+xo.NUM_KEYPOINTS)}}X.getOffsetPoint=Mt;function bo(e,t,o){const{heatmapY:n,heatmapX:s,id:i}=e,{y:a,x:c}=Mt(n,s,i,o);return{x:e.heatmapX*t+c,y:e.heatmapY*t+a}}X.getImageCoords=bo;function yo(e,t){const o=new Array(t);for(let n=0;no?o:e}X.clamp=Ie;function wo(e,t,o,n){const s=o-e,i=n-t;return s*s+i*i}X.squaredDistance=wo;function Eo(e,t){return{x:e.x+t.x,y:e.y+t.y}}X.addVectors=Eo;function vo(e,t,o){return{y:Ie(e.y,t,o),x:Ie(e.x,t,o)}}X.clampVector=vo});var Bt=E(It=>{const te=ee(),Z=Se(),St=te.poseChain.map(([e,t])=>[te.partIds[e],te.partIds[t]]),Re=St.map(([,e])=>e),Rt=St.map(([e])=>e);function Po(e,t,o){const n=o.shape[2]/2;return{y:o.get(t.y,t.x,e),x:o.get(t.y,t.x,n+e)}}function Ae(e,t,o,n){return{y:Z.clamp(Math.round(e.y/t),0,o-1),x:Z.clamp(Math.round(e.x/t),0,n-1)}}function At(e,t,o,n,s,i,a,c=2){const[d,l]=n.shape,u=Ae(t.position,i,d,l),f=Po(e,u,a),h=Z.addVectors(t.position,f);let r=h;for(let P=0;P=0;--h){const r=Re[h],b=Rt[h];d[r]&&!d[b]&&(d[b]=At(h,d[r],b,t,o,n,i))}for(let h=0;h{const _o=_t(),Mo=Bt(),Dt=Se();function kt(e,t,{x:o,y:n},s){return e.some(({keypoints:i})=>{const a=i[s].position;return Dt.squaredDistance(n,o,a.y,a.x)<=t})}function Io(e,t,o){const n=o.reduce((s,{position:i,score:a},c)=>(kt(e,t,i,c)||(s+=a),s),0);return n/o.length}const So=1;function Ro(e,t,o,n,s,i,a=.5,c=20){const d=[],l=_o.buildPartWithScoreQueue(a,So,e),u=c*c;for(;d.length{const Ao=ee();function Bo(e,t,o){return e(Bo(e[n].score,e[s].score,t)||o.push([e[n],e[s]]),o),[])}W.getAdjacentKeyPoints=Fo;const{NEGATIVE_INFINITY:Nt,POSITIVE_INFINITY:Ct}=Number;function zt(e){return e.reduce(({maxX:t,maxY:o,minX:n,minY:s},{position:{x:i,y:a}})=>({maxX:Math.max(t,i),maxY:Math.max(o,a),minX:Math.min(n,i),minY:Math.min(s,a)}),{maxX:Nt,maxY:Nt,minX:Ct,minY:Ct})}W.getBoundingBox=zt;function Do(e){const{minX:t,minY:o,maxX:n,maxY:s}=zt(e);return[{x:t,y:o},{x:n,y:o},{x:n,y:s},{x:t,y:s}]}W.getBoundingBoxPoints=Do;async function ko(e){return Promise.all(e.map(t=>t.buffer()))}W.toTensorBuffers3D=ko;function Ot(e,t,o){return{score:e.score,keypoints:e.keypoints.map(({score:n,part:s,position:i})=>({score:n,part:s,position:{x:i.x*o,y:i.y*t}}))}}W.scalePose=Ot;function No(e,[t,o]){const n=e.squeeze(0),s=n.resizeBilinear([t,o]);return n.dispose(),s}W.resizeTo=No;function Co(e,[t,o],[n,s]){const i=e.map(a=>Ot(a,t/n,o/s));return i}W.scaleAndFlipPoses=Co});var Ht=E(De=>{const zo=require("@tensorflow/tfjs"),Oo=_e(),Lo=Be(),ke=Fe();class Lt{constructor(e){this.baseModel=e}async estimatePoses(e,t){const o=t.outputStride,n=e.shape[1],s=e.shape[2],i=ke.resizeTo(e,[t.inputResolution,t.inputResolution]),{heatmapScores:a,offsets:c,displacementFwd:d,displacementBwd:l}=this.baseModel.predict(i),u=await ke.toTensorBuffers3D([a,c,d,l]),f=u[0],h=u[1],r=u[2],b=u[3],_=await Lo.decodeMultiplePoses(f,h,r,b,o,t.maxDetections,t.scoreThreshold,t.nmsRadius),P=ke.scaleAndFlipPoses(_,[n,s],[t.inputResolution,t.inputResolution]);return a.dispose(),c.dispose(),d.dispose(),l.dispose(),i.dispose(),P}dispose(){this.baseModel.dispose()}}De.PoseNet=Lt;async function Ho(e){const t=await zo.loadGraphModel(e.modelPath),o=new Oo.MobileNet(t,e.outputStride);return new Lt(o)}async function Uo(e){return Ho(e)}De.load=Uo});var jt=E(A=>{const jo=_e(),Ut=Ht(),qo=Be(),ae=ee(),oe=Fe();A.load=Ut.load;A.PoseNet=Ut.PoseNet;A.MobileNet=jo.MobileNet;A.decodeMultiplePoses=qo.decodeMultiplePoses;A.partChannels=ae.partChannels;A.partIds=ae.partIds;A.partNames=ae.partNames;A.poseChain=ae.poseChain;A.getAdjacentKeyPoints=oe.getAdjacentKeyPoints;A.getBoundingBox=oe.getBoundingBox;A.getBoundingBoxPoints=oe.getBoundingBoxPoints;A.scaleAndFlipPoses=oe.scaleAndFlipPoses;A.scalePose=oe.scalePose});var ze=E(G=>{const Xo=require("@tensorflow/tfjs");function Ne(e){return[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])]}G.getBoxSize=Ne;function Ce(e){return[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2]}G.getBoxCenter=Ce;function Wo(e,t,o){const n=t.shape[1],s=t.shape[2],i=[[e.startPoint[1]/n,e.startPoint[0]/s,e.endPoint[1]/n,e.endPoint[0]/s]];return Xo.image.cropAndResize(t,i,[0],o)}G.cutBoxFromImageAndResize=Wo;function Go(e,t){const o=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],n=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]],s=e.palmLandmarks.map(i=>{const a=[i[0]*t[0],i[1]*t[1]];return a});return{startPoint:o,endPoint:n,palmLandmarks:s}}G.scaleBoxCoordinates=Go;function Yo(e,t=1.5){const o=Ce(e),n=Ne(e),s=[t*n[0]/2,t*n[1]/2],i=[o[0]-s[0],o[1]-s[1]],a=[o[0]+s[0],o[1]+s[1]];return{startPoint:i,endPoint:a,palmLandmarks:e.palmLandmarks}}G.enlargeBox=Yo;function Ko(e){const t=Ce(e),o=Ne(e),n=Math.max(...o),s=n/2,i=[t[0]-s,t[1]-s],a=[t[0]+s,t[1]+s];return{startPoint:i,endPoint:a,palmLandmarks:e.palmLandmarks}}G.squarifyBox=Ko;function Vo(e,t){const o=[e.endPoint[0]-e.startPoint[0],e.endPoint[1]-e.startPoint[1]],n=[o[0]*t[0],o[1]*t[1]],s=[e.startPoint[0]+n[0],e.startPoint[1]+n[1]],i=[e.endPoint[0]+n[0],e.endPoint[1]+n[1]];return{startPoint:s,endPoint:i,palmLandmarks:e.palmLandmarks}}G.shiftBox=Vo});var Xt=E(qt=>{const v=require("@tensorflow/tfjs"),Qo=ze();class Zo{constructor(e,t,o){this.model=e,this.width=o.inputSize,this.height=o.inputSize,this.anchors=t.map(n=>[n.x_center,n.y_center]),this.anchorsTensor=v.tensor2d(this.anchors),this.inputSizeTensor=v.tensor1d([o.inputSize,o.inputSize]),this.doubleInputSizeTensor=v.tensor1d([o.inputSize*2,o.inputSize*2])}normalizeBoxes(e){return v.tidy(()=>{const t=v.slice(e,[0,0],[-1,2]),o=v.slice(e,[0,2],[-1,2]),n=v.add(v.div(t,this.inputSizeTensor),this.anchorsTensor),s=v.div(o,this.doubleInputSizeTensor),i=v.mul(v.sub(n,s),this.inputSizeTensor),a=v.mul(v.add(n,s),this.inputSizeTensor);return v.concat2d([i,a],1)})}normalizeLandmarks(e,t){return v.tidy(()=>{const o=v.add(v.div(e.reshape([-1,7,2]),this.inputSizeTensor),this.anchors[t]);return v.mul(o,this.inputSizeTensor)})}async getBoundingBoxes(e){const t=this.model.predict(e),o=t.squeeze(),n=v.tidy(()=>v.sigmoid(v.slice(o,[0,0],[-1,1])).squeeze()),s=v.slice(o,[0,1],[-1,4]),i=this.normalizeBoxes(s),a=await v.image.nonMaxSuppressionAsync(i,n,this.maxHands,this.iouThreshold,this.scoreThreshold),c=await a.array(),d=[t,a,o,i,s,n],l=v.tidy(()=>{const u=[];for(const f in c){const h=c[f],r=v.slice(i,[h,0],[1,-1]),b=v.slice(o,[h,5],[1,14]),_=v.tidy(()=>this.normalizeLandmarks(b,h).reshape([-1,2]));u.push({boxes:r,palmLandmarks:_})}return u});return d.forEach(u=>u.dispose()),l}async estimateHandBounds(e,t){this.iouThreshold=t.iouThreshold,this.scoreThreshold=t.scoreThreshold,this.maxHands=t.maxHands;const o=e.resizeBilinear([this.width,this.height]),n=o.div(255),s=n.sub(.5),i=s.mul(2);o.dispose(),n.dispose(),s.dispose();const a=await this.getBoundingBoxes(i);if(i.dispose(),!a||a.length===0)return null;const c=[];for(const d in a){const l=a[d],u=await l.boxes.array(),f=u[0].slice(0,2),h=u[0].slice(2,4),r=await l.palmLandmarks.array();l.boxes.dispose(),l.palmLandmarks.dispose(),c.push(Qo.scaleBoxCoordinates({startPoint:f,endPoint:h,palmLandmarks:r},[e.shape[2]/this.width,e.shape[1]/this.height]))}return c}}qt.HandDetector=Zo});var Gt=E(Wt=>{Wt.MESH_ANNOTATIONS={thumb:[1,2,3,4],indexFinger:[5,6,7,8],middleFinger:[9,10,11,12],ringFinger:[13,14,15,16],pinky:[17,18,19,20],palmBase:[0]}});var Zt=E(Y=>{function Yt(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}Y.normalizeRadians=Yt;function $o(e,t){const o=Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]);return Yt(o)}Y.computeRotation=$o;const Kt=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]];function $(e,t){let o=0;for(let n=0;n{const Jt=require("@tensorflow/tfjs"),z=ze(),K=Zt(),on=.8,nn=[0,-.4],sn=[0,-.1],rn=1.65,e0=[0,5,9,13,17,1,2],an=0,cn=2;class dn{constructor(e,t,o){this.regionsOfInterest=[],this.runsWithoutHandDetector=0,this.boundingBoxDetector=e,this.meshDetector=t,this.meshWidth=o.inputSize,this.meshHeight=o.inputSize,this.enlargeFactor=o.enlargeFactor}getBoxForPalmLandmarks(e,t){const o=e.map(s=>{const i=[...s,1];return K.rotatePoint(i,t)}),n=this.calculateLandmarksBoundingBox(o);return z.enlargeBox(z.squarifyBox(z.shiftBox(n,nn)),this.enlargeFactor)}getBoxForHandLandmarks(e){const t=this.calculateLandmarksBoundingBox(e),o=z.enlargeBox(z.squarifyBox(z.shiftBox(t,sn)),rn),n=[];for(let s=0;s[i[0]*(h[0]-this.meshWidth/2),i[1]*(h[1]-this.meshHeight/2),h[2]]),c=K.buildRotationMatrix(o,[0,0]),d=a.map(h=>{const r=K.rotatePoint(h,c);return[...r,h[2]]}),l=K.invertTransformMatrix(n),u=[...z.getBoxCenter(t),1],f=[K.dot(u,l[0]),K.dot(u,l[1])];return d.map(h=>[h[0]+f[0],h[1]+f[1],h[2]])}async estimateHands(e,t){this.skipFrames=t.skipFrames,this.detectionConfidence=t.minConfidence,this.maxHands=t.maxHands,this.runsWithoutHandDetector++;const o=this.shouldUpdateRegionsOfInterest();if(o===!0){const s=await this.boundingBoxDetector.estimateHandBounds(e,t);this.regionsOfInterest=[];for(const i in s)this.updateRegionsOfInterest(s[i],!0,i);this.runsWithoutHandDetector=0}const n=[];if(!this.regionsOfInterest)return n;for(const s in this.regionsOfInterest){const i=this.regionsOfInterest[s][0];if(!i)return n;const a=K.computeRotation(i.palmLandmarks[an],i.palmLandmarks[cn]),c=z.getBoxCenter(i),d=[c[0]/e.shape[2],c[1]/e.shape[1]],l=Jt.image.rotateWithOffset(e,a,0,d),u=K.buildRotationMatrix(-a,c),f=o?this.getBoxForPalmLandmarks(i.palmLandmarks,u):i,h=z.cutBoxFromImageAndResize(f,l,[this.meshWidth,this.meshHeight]),r=h.div(255);h.dispose(),l.dispose();const b=this.meshDetector.predict(r),[_,P]=b;r.dispose();const T=_.dataSync()[0];if(_.dispose(),Ti[0]),o=e.map(i=>i[1]),n=[Math.min(...t),Math.min(...o)],s=[Math.max(...t),Math.max(...o)];return{startPoint:n,endPoint:s}}updateRegionsOfInterest(e,t,o){if(t)this.regionsOfInterest[o]=[e];else{const n=this.regionsOfInterest[o][0];let s=0;if(n!=null&&n.startPoint!=null){const[i,a]=e.startPoint,[c,d]=e.endPoint,[l,u]=n.startPoint,[f,h]=n.endPoint,r=Math.max(i,l),b=Math.max(a,u),_=Math.min(c,f),P=Math.min(d,h),T=(_-r)*(P-b),y=(c-i)*(d-a),B=(f-l)*(h-a);s=T/(y+B-T)}this.regionsOfInterest[o][0]=s>on?n:e}}shouldUpdateRegionsOfInterest(){return!this.regionsOfInterest||this.regionsOfInterest.length===0||this.runsWithoutHandDetector>=this.skipFrames}}$t.HandPipeline=dn});var s0=E(Oe=>{const ce=require("@tensorflow/tfjs"),ln=Xt(),o0=Gt(),hn=t0();class n0{constructor(e){this.pipeline=e}async estimateHands(e,t){this.skipFrames=t.skipFrames,this.detectionConfidence=t.minConfidence,this.maxHands=t.maxHands;const o=await this.pipeline.estimateHands(e,t),n=[];if(!o)return n;for(const s of o){if(!s)return[];const i={};for(const a of Object.keys(o0.MESH_ANNOTATIONS))i[a]=o0.MESH_ANNOTATIONS[a].map(c=>s.landmarks[c]);n.push({confidence:s.confidence||0,box:s.box?[s.box.topLeft[0],s.box.topLeft[1],s.box.bottomRight[0]-s.box.topLeft[0],s.box.bottomRight[1]-s.box.topLeft[1]]:0,landmarks:s.landmarks,annotations:i})}return n}}Oe.HandPose=n0;async function un(e){if(ce.env().features.IS_NODE){const t=require("fs"),o=await t.readFileSync(e.replace("file://",""));return JSON.parse(o)}return ce.util.fetch(e).then(t=>t.json())}async function mn(e){const[t,o,n]=await Promise.all([un(e.detector.anchors),ce.loadGraphModel(e.detector.modelPath,{fromTFHub:e.detector.modelPath.includes("tfhub.dev")}),ce.loadGraphModel(e.skeleton.modelPath,{fromTFHub:e.skeleton.modelPath.includes("tfhub.dev")})]),s=new ln.HandDetector(o,t,e),i=new hn.HandPipeline(s,n,e),a=new n0(i);return a}Oe.load=mn});var r0=E(i0=>{const fn=function(e,t,o){const n=function(c,d,l){const u=new RegExp("\\b"+d+" \\w+ (\\w+)","ig");c.replace(u,(f,h)=>(l[h]=0,f))},s=function(c,d,l){const u=c.createShader(l);if(c.shaderSource(u,d),c.compileShader(u),!c.getShaderParameter(u,c.COMPILE_STATUS))throw new Error("Filter: GL compile failed",c.getShaderInfoLog(u));return u};this.uniform={},this.attribute={};const i=s(e,t,e.VERTEX_SHADER),a=s(e,o,e.FRAGMENT_SHADER);if(this.id=e.createProgram(),e.attachShader(this.id,i),e.attachShader(this.id,a),e.linkProgram(this.id),!e.getProgramParameter(this.id,e.LINK_STATUS))throw new Error("Filter: GL link failed",e.getProgramInfoLog(this.id));e.useProgram(this.id),n(t,"attribute",this.attribute);for(const c in this.attribute)this.attribute[c]=e.getAttribLocation(this.id,c);n(t,"uniform",this.uniform),n(o,"uniform",this.uniform);for(const c in this.uniform)this.uniform[c]=e.getUniformLocation(this.id,c)},pn=function(e){e||(e={});let t=0,o=null,n=!1,s=-1,i=[null,null],a=[],c=-1,d=-1,l=null,u=null;const f=e.canvas||document.createElement("canvas"),h={},r=f.getContext("webgl")||f.getContext("experimental-webgl");if(!r)throw new Error("Filter: getContext() failed");this.addFilter=function(g){const m=Array.prototype.slice.call(arguments,1),x=p[g];a.push({func:x,args:m})},this.reset=function(){a=[]},this.apply=function(g){if(b(g.width,g.height),t=0,o||(o=r.createTexture()),r.bindTexture(r.TEXTURE_2D,o),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,g),a.length===0){const m=y(F.FRAGMENT_IDENTITY);return T(),f}for(let m=0;m{Ge(pn,{default:()=>gn});var gn={backend:"webgl",console:!0,scoped:!1,videoOptimized:!0,filter:{enabled:!0,return:!0,brightness:0,contrast:0,sharpness:0,blur:0,saturation:0,hue:0,negative:!1,sepia:!1,vintage:!1,kodachrome:!1,technicolor:!1,polaroid:!1,pixelate:0},face:{enabled:!0,detector:{modelPath:"../models/blazeface/back/model.json",inputSize:256,maxFaces:10,skipFrames:10,minConfidence:.5,iouThreshold:.3,scoreThreshold:.7},mesh:{enabled:!0,modelPath:"../models/facemesh/model.json",inputSize:192},iris:{enabled:!0,modelPath:"../models/iris/model.json",enlargeFactor:2.3,inputSize:64},age:{enabled:!0,modelPath:"../models/ssrnet-age/imdb/model.json",inputSize:64,skipFrames:10},gender:{enabled:!0,minConfidence:.8,modelPath:"../models/ssrnet-gender/imdb/model.json"},emotion:{enabled:!0,inputSize:64,minConfidence:.5,skipFrames:10,modelPath:"../models/emotion/model.json"}},body:{enabled:!0,modelPath:"../models/posenet/model.json",inputResolution:257,outputStride:16,maxDetections:10,scoreThreshold:.7,nmsRadius:20},hand:{enabled:!0,inputSize:256,skipFrames:10,minConfidence:.5,iouThreshold:.3,scoreThreshold:.7,enlargeFactor:1.65,maxHands:10,detector:{anchors:"../models/handdetect/anchors.json",modelPath:"../models/handdetect/model.json"},skeleton:{modelPath:"../models/handskeleton/model.json"}}}});var d0=E(($n,c0)=>{c0.exports={name:"@vladmandic/human",version:"0.3.9",description:"human: 3D Face Detection, Iris Tracking and Age & Gender Prediction",sideEffects:!1,main:"dist/human.cjs",module:"dist/human.esm.js",browser:"dist/human.esm.js",author:"Vladimir Mandic ",bugs:{url:"https://github.com/vladmandic/human/issues"},homepage:"https://github.com/vladmandic/human#readme",license:"MIT",engines:{node:">=14.0.0"},repository:{type:"git",url:"git+https://github.com/vladmandic/human.git"},dependencies:{},peerDependencies:{},devDependencies:{"@vladmandic/pilogger":"^0.2.6",dayjs:"^1.9.3","simple-git":"^2.21.0","@tensorflow/tfjs":"^2.6.0","@tensorflow/tfjs-node":"^2.6.0",esbuild:"^0.7.15",eslint:"^7.10.0","eslint-config-airbnb-base":"^14.2.0","eslint-plugin-import":"^2.22.1","eslint-plugin-json":"^2.1.2","eslint-plugin-node":"^11.1.0","eslint-plugin-promise":"^4.2.1",rimraf:"^3.0.2"},scripts:{start:"node --trace-warnings --unhandled-rejections=strict --trace-uncaught --no-deprecation src/node.js",lint:"eslint src/*.js demo/*.js","build-iife":"esbuild --bundle --platform=browser --sourcemap --target=esnext --format=iife --minify --external:fs --global-name=human --metafile=dist/human.json --outfile=dist/human.js src/human.js","build-esm-bundle":"esbuild --bundle --platform=browser --sourcemap --target=esnext --format=esm --minify --external:fs --metafile=dist/human.esm.json --outfile=dist/human.esm.js src/human.js","build-esm-nobundle":"esbuild --bundle --platform=browser --sourcemap --target=esnext --format=esm --minify --external:@tensorflow --external:fs --metafile=dist/human.esm-nobundle.json --outfile=dist/human.esm-nobundle.js src/human.js","build-node":"esbuild --bundle --platform=node --sourcemap --target=esnext --format=cjs --external:@tensorflow --metafile=dist/human.cjs.json --outfile=dist/human.cjs src/human.js",build:"rimraf dist/* && npm run build-iife && npm run build-esm-bundle && npm run build-esm-nobundle && npm run build-node && ls -l dist/",update:"npm update --depth 20 && npm dedupe && npm prune && npm audit",changelog:"node changelog.js"},keywords:["tensorflowjs","face-detection","face-geometry","body-tracking","hand-tracking","iris-tracking","age-estimation","emotion-detection","gender-prediction","gesture-recognition"]}});const R=require("@tensorflow/tfjs"),l0=ht(),de=mt(),Le=gt(),h0=jt(),u0=s0(),xn=r0(),le=a0().default,bn=d0(),yn={face:{detector:{skipFrames:0},age:{skipFrames:0},emotion:{skipFrames:0}},hand:{skipFrames:0}},I=()=>typeof performance!="undefined"?performance.now():parseInt(Number(process.hrtime.bigint())/1e3/1e3);function he(...e){const t=o=>o&&typeof o=="object";return e.reduce((o,n)=>(Object.keys(n||{}).forEach(s=>{const i=o[s],a=n[s];Array.isArray(i)&&Array.isArray(a)?o[s]=i.concat(...a):t(i)&&t(a)?o[s]=he(i,a):o[s]=a}),o),{})}function wn(e){if(!e)return"input is not defined";if(R.ENV.flags.IS_NODE&&!(e instanceof R.Tensor))return"input must be a tensor";try{R.getBackend()}catch{return"backend not loaded"}return null}class En{constructor(){this.tf=R,this.version=bn.version,this.defaults=le,this.config=le,this.fx=R.ENV.flags.IS_BROWSER&&typeof document!="undefined"?new xn.Canvas:null,this.state="idle",this.numTensors=0,this.analyzeMemoryLeaks=!1,this.models={facemesh:null,posenet:null,handpose:null,iris:null,age:null,gender:null,emotion:null},this.facemesh=l0,this.ssrnet=de,this.emotion=Le,this.posenet=h0,this.handpose=u0}log(...e){e&&this.config.console&&console.log(...e)}analyze(...e){if(!this.analyzeMemoryLeaks)return;const t=R.engine().state.numTensors,o=this.numTensors;this.numTensors=t;const n=t-o;n!==0&&this.log(...e,n)}async load(e){e&&(this.config=he(le,e)),this.config.face.enabled&&!this.models.facemesh&&(this.log("Load model: Face"),this.models.facemesh=await l0.load(this.config.face)),this.config.body.enabled&&!this.models.posenet&&(this.log("Load model: Body"),this.models.posenet=await h0.load(this.config.body)),this.config.hand.enabled&&!this.models.handpose&&(this.log("Load model: Hand"),this.models.handpose=await u0.load(this.config.hand)),this.config.face.enabled&&this.config.face.age.enabled&&!this.models.age&&(this.log("Load model: Age"),this.models.age=await de.loadAge(this.config)),this.config.face.enabled&&this.config.face.gender.enabled&&!this.models.gender&&(this.log("Load model: Gender"),this.models.gender=await de.loadGender(this.config)),this.config.face.enabled&&this.config.face.emotion.enabled&&!this.models.emotion&&(this.log("Load model: Emotion"),this.models.emotion=await Le.load(this.config))}tfImage(e){let t;if(this.fx&&this.config.filter.enabled&&!(e instanceof R.Tensor)){const n=e.naturalWidth||e.videoWidth||e.width||e.shape&&e.shape[1]>0,s=e.naturalHeight||e.videoHeight||e.height||e.shape&&e.shape[2]>0,i=new OffscreenCanvas(n,s),a=i.getContext("2d");e instanceof ImageData?a.putImageData(e,0,0):a.drawImage(e,0,0,n,s,0,0,i.width,i.height),this.fx.reset(),this.fx.addFilter("brightness",this.config.filter.brightness),this.config.filter.contrast!==0&&this.fx.addFilter("contrast",this.config.filter.contrast),this.config.filter.sharpness!==0&&this.fx.addFilter("sharpen",this.config.filter.sharpness),this.config.filter.blur!==0&&this.fx.addFilter("blur",this.config.filter.blur),this.config.filter.saturation!==0&&this.fx.addFilter("saturation",this.config.filter.saturation),this.config.filter.hue!==0&&this.fx.addFilter("hue",this.config.filter.hue),this.config.filter.negative&&this.fx.addFilter("negative"),this.config.filter.sepia&&this.fx.addFilter("sepia"),this.config.filter.vintage&&this.fx.addFilter("brownie"),this.config.filter.sepia&&this.fx.addFilter("sepia"),this.config.filter.kodachrome&&this.fx.addFilter("kodachrome"),this.config.filter.technicolor&&this.fx.addFilter("technicolor"),this.config.filter.polaroid&&this.fx.addFilter("polaroid"),this.config.filter.pixelate!==0&&this.fx.addFilter("pixelate",this.config.filter.pixelate),t=this.fx.apply(i)}let o;if(e instanceof R.Tensor)o=R.clone(e);else{const n=R.browser.fromPixels(t||e),s=n.toFloat();o=s.expandDims(0),n.dispose(),s.dispose()}return{tensor:o,canvas:this.config.filter.return?t:null}}async detect(e,t={}){this.state="config";const o={};let n;n=I(),this.config=he(le,t),this.config.videoOptimized||(this.config=he(this.config,yn)),o.config=Math.trunc(I()-n),n=I(),this.state="check";const s=wn(e);return s?(this.log(s,e),{error:s}):(o.sanity=Math.trunc(I()-n),new Promise(async i=>{const a=I();n=I(),R.getBackend()!==this.config.backend&&(this.state="backend",this.log("Human library setting backend:",this.config.backend),await R.setBackend(this.config.backend),await R.ready()),o.backend=Math.trunc(I()-n);const c=Object.values(this.models).filter(r=>r).length;c===0&&(this.log("Human library starting"),this.log("Configuration:",this.config),this.log("Flags:",R.ENV.flags)),n=I(),this.state="load",await this.load(),o.load=Math.trunc(I()-n),this.config.scoped&&R.engine().startScope(),this.analyze("Start Detect:"),n=I();const d=this.tfImage(e);o.image=Math.trunc(I()-n);const l=d.tensor;this.state="run:body",n=I(),this.analyze("Start PoseNet");const u=this.config.body.enabled?await this.models.posenet.estimatePoses(l,this.config.body):[];this.analyze("End PoseNet:"),o.body=Math.trunc(I()-n),this.state="run:hand",n=I(),this.analyze("Start HandPose:");const f=this.config.hand.enabled?await this.models.handpose.estimateHands(l,this.config.hand):[];this.analyze("End HandPose:"),o.hand=Math.trunc(I()-n);const h=[];if(this.config.face.enabled){this.state="run:face",n=I(),this.analyze("Start FaceMesh:");const r=await this.models.facemesh.estimateFaces(l,this.config.face);o.face=Math.trunc(I()-n);for(const g of r){if(!g.image||g.image.isDisposedInternal){this.log("face object is disposed:",g.image);continue}this.state="run:agegender",n=I();const P=this.config.face.age.enabled||this.config.face.gender.enabled?await de.predict(g.image,this.config):{};o.agegender=Math.trunc(I()-n),this.state="run:emotion",n=I();const _=this.config.face.emotion.enabled?await Le.predict(g.image,this.config):{};o.emotion=Math.trunc(I()-n),g.image.dispose();const v=g.annotations.leftEyeIris&&g.annotations.rightEyeIris?Math.max(g.annotations.leftEyeIris[3][0]-g.annotations.leftEyeIris[1][0],g.annotations.rightEyeIris[3][0]-g.annotations.rightEyeIris[1][0]):0;h.push({confidence:g.confidence,box:g.box,mesh:g.mesh,annotations:g.annotations,age:P.age,gender:P.gender,agConfidence:P.confidence,emotion:_,iris:v!==0?Math.trunc(100*11.7/v)/100:0}),this.analyze("End FaceMesh:")}}l.dispose(),this.state="idle",this.config.scoped&&R.engine().endScope(),this.analyze("End Scope:"),o.total=Math.trunc(I()-a),i({face:h,body:u,hand:f,performance:o,canvas:d.canvas})}))}}export{En as default}; +`),p.brightness=function(g){const m=(g||0)+1;p.colorMatrix([m,0,0,0,0,0,m,0,0,0,0,0,m,0,0,0,0,0,1,0])},p.saturation=function(g){const m=(g||0)*2/3+1,x=(m-1)*-.5;p.colorMatrix([m,x,x,0,0,x,m,x,0,0,x,x,m,0,0,0,0,0,1,0])},p.desaturate=function(){p.saturation(-1)},p.contrast=function(g){const m=(g||0)+1,x=-128*(m-1);p.colorMatrix([m,0,0,0,x,0,m,0,0,x,0,0,m,0,x,0,0,0,1,0])},p.negative=function(){p.contrast(-2)},p.hue=function(g){g=(g||0)/180*Math.PI;const m=Math.cos(g),x=Math.sin(g),M=.213,S=.715,N=.072;p.colorMatrix([M+m*(1-M)+x*-M,S+m*-S+x*-S,N+m*-N+x*(1-N),0,0,M+m*-M+x*.143,S+m*(1-S)+x*.14,N+m*-N+x*-.283,0,0,M+m*-M+x*-(1-M),S+m*-S+x*S,N+m*(1-N)+x*N,0,0,0,0,0,1,0])},p.desaturateLuminance=function(){p.colorMatrix([.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,0,0,0,1,0])},p.sepia=function(){p.colorMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0])},p.brownie=function(){p.colorMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0])},p.vintagePinhole=function(){p.colorMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0])},p.kodachrome=function(){p.colorMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0])},p.technicolor=function(){p.colorMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0])},p.polaroid=function(){p.colorMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0])},p.shiftToBGR=function(){p.colorMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0])},p.convolution=function(g){const m=new Float32Array(g),x=1/c,M=1/d,S=y(p.convolution.SHADER);r.uniform1fv(S.uniform.m,m),r.uniform2f(S.uniform.px,x,M),T()},p.convolution.SHADER=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","uniform vec2 px;","uniform float m[9];","void main(void) {","vec4 c11 = texture2D(texture, vUv - px);","vec4 c12 = texture2D(texture, vec2(vUv.x, vUv.y - px.y));","vec4 c13 = texture2D(texture, vec2(vUv.x + px.x, vUv.y - px.y));","vec4 c21 = texture2D(texture, vec2(vUv.x - px.x, vUv.y) );","vec4 c22 = texture2D(texture, vUv);","vec4 c23 = texture2D(texture, vec2(vUv.x + px.x, vUv.y) );","vec4 c31 = texture2D(texture, vec2(vUv.x - px.x, vUv.y + px.y) );","vec4 c32 = texture2D(texture, vec2(vUv.x, vUv.y + px.y) );","vec4 c33 = texture2D(texture, vUv + px );","gl_FragColor = ","c11 * m[0] + c12 * m[1] + c22 * m[2] +","c21 * m[3] + c22 * m[4] + c23 * m[5] +","c31 * m[6] + c32 * m[7] + c33 * m[8];","gl_FragColor.a = c22.a;","}"].join(` +`),p.detectEdges=function(){p.convolution.call(this,[0,1,0,1,-4,1,0,1,0])},p.sobelX=function(){p.convolution.call(this,[-1,0,1,-2,0,2,-1,0,1])},p.sobelY=function(){p.convolution.call(this,[-1,-2,-1,0,0,0,1,2,1])},p.sharpen=function(g){const m=g||1;p.convolution.call(this,[0,-1*m,0,-1*m,1+4*m,-1*m,0,-1*m,0])},p.emboss=function(g){const m=g||1;p.convolution.call(this,[-2*m,-1*m,0,-1*m,1,1*m,0,1*m,2*m])},p.blur=function(g){const m=g/7/c,x=g/7/d,M=y(p.blur.SHADER);r.uniform2f(M.uniform.px,0,x),T(B.INTERMEDIATE),r.uniform2f(M.uniform.px,m,0),T()},p.blur.SHADER=["precision highp float;","varying vec2 vUv;","uniform sampler2D texture;","uniform vec2 px;","void main(void) {","gl_FragColor = vec4(0.0);","gl_FragColor += texture2D(texture, vUv + vec2(-7.0*px.x, -7.0*px.y))*0.0044299121055113265;","gl_FragColor += texture2D(texture, vUv + vec2(-6.0*px.x, -6.0*px.y))*0.00895781211794;","gl_FragColor += texture2D(texture, vUv + vec2(-5.0*px.x, -5.0*px.y))*0.0215963866053;","gl_FragColor += texture2D(texture, vUv + vec2(-4.0*px.x, -4.0*px.y))*0.0443683338718;","gl_FragColor += texture2D(texture, vUv + vec2(-3.0*px.x, -3.0*px.y))*0.0776744219933;","gl_FragColor += texture2D(texture, vUv + vec2(-2.0*px.x, -2.0*px.y))*0.115876621105;","gl_FragColor += texture2D(texture, vUv + vec2(-1.0*px.x, -1.0*px.y))*0.147308056121;","gl_FragColor += texture2D(texture, vUv )*0.159576912161;","gl_FragColor += texture2D(texture, vUv + vec2( 1.0*px.x, 1.0*px.y))*0.147308056121;","gl_FragColor += texture2D(texture, vUv + vec2( 2.0*px.x, 2.0*px.y))*0.115876621105;","gl_FragColor += texture2D(texture, vUv + vec2( 3.0*px.x, 3.0*px.y))*0.0776744219933;","gl_FragColor += texture2D(texture, vUv + vec2( 4.0*px.x, 4.0*px.y))*0.0443683338718;","gl_FragColor += texture2D(texture, vUv + vec2( 5.0*px.x, 5.0*px.y))*0.0215963866053;","gl_FragColor += texture2D(texture, vUv + vec2( 6.0*px.x, 6.0*px.y))*0.00895781211794;","gl_FragColor += texture2D(texture, vUv + vec2( 7.0*px.x, 7.0*px.y))*0.0044299121055113265;","}"].join(` +`),p.pixelate=function(g){const m=g/c,x=g/d,M=y(p.pixelate.SHADER);r.uniform2f(M.uniform.size,m,x),T()},p.pixelate.SHADER=["precision highp float;","varying vec2 vUv;","uniform vec2 size;","uniform sampler2D texture;","vec2 pixelate(vec2 coord, vec2 size) {","return floor( coord / size ) * size;","}","void main(void) {","gl_FragColor = vec4(0.0);","vec2 coord = pixelate(vUv, size);","gl_FragColor += texture2D(texture, coord);","}"].join(` +`)};i0.Canvas=pn});var a0=E(gn=>{Ge(gn,{default:()=>xn});var xn={backend:"webgl",console:!0,scoped:!1,videoOptimized:!0,filter:{enabled:!0,return:!0,brightness:0,contrast:0,sharpness:0,blur:0,saturation:0,hue:0,negative:!1,sepia:!1,vintage:!1,kodachrome:!1,technicolor:!1,polaroid:!1,pixelate:0},face:{enabled:!0,detector:{modelPath:"../models/blazeface/back/model.json",inputSize:256,maxFaces:10,skipFrames:10,minConfidence:.5,iouThreshold:.3,scoreThreshold:.7},mesh:{enabled:!0,modelPath:"../models/facemesh/model.json",inputSize:192},iris:{enabled:!0,modelPath:"../models/iris/model.json",enlargeFactor:2.3,inputSize:64},age:{enabled:!0,modelPath:"../models/ssrnet-age/imdb/model.json",inputSize:64,skipFrames:10},gender:{enabled:!0,minConfidence:.8,modelPath:"../models/ssrnet-gender/imdb/model.json"},emotion:{enabled:!0,inputSize:64,minConfidence:.5,skipFrames:10,modelPath:"../models/emotion/model.json"}},body:{enabled:!0,modelPath:"../models/posenet/model.json",inputResolution:257,outputStride:16,maxDetections:10,scoreThreshold:.7,nmsRadius:20},hand:{enabled:!0,inputSize:256,skipFrames:10,minConfidence:.5,iouThreshold:.3,scoreThreshold:.7,enlargeFactor:1.65,maxHands:10,detector:{anchors:"../models/handdetect/anchors.json",modelPath:"../models/handdetect/model.json"},skeleton:{modelPath:"../models/handskeleton/model.json"}}}});var d0=E((Jn,c0)=>{c0.exports={name:"@vladmandic/human",version:"0.4.1",description:"human: 3D Face Detection, Iris Tracking and Age & Gender Prediction",sideEffects:!1,main:"dist/human.cjs",module:"dist/human.esm.js",browser:"dist/human.esm.js",author:"Vladimir Mandic ",bugs:{url:"https://github.com/vladmandic/human/issues"},homepage:"https://github.com/vladmandic/human#readme",license:"MIT",engines:{node:">=14.0.0"},repository:{type:"git",url:"git+https://github.com/vladmandic/human.git"},dependencies:{},peerDependencies:{},devDependencies:{"@vladmandic/pilogger":"^0.2.6",dayjs:"^1.9.3","simple-git":"^2.21.0","@tensorflow/tfjs":"^2.6.0","@tensorflow/tfjs-node":"^2.6.0",esbuild:"^0.7.15",eslint:"^7.10.0","eslint-config-airbnb-base":"^14.2.0","eslint-plugin-import":"^2.22.1","eslint-plugin-json":"^2.1.2","eslint-plugin-node":"^11.1.0","eslint-plugin-promise":"^4.2.1",rimraf:"^3.0.2"},scripts:{start:"node --trace-warnings --unhandled-rejections=strict --trace-uncaught --no-deprecation src/node.js",lint:"eslint src/*.js demo/*.js","build-iife":"esbuild --bundle --platform=browser --sourcemap --target=esnext --format=iife --minify --external:fs --global-name=Human --metafile=dist/human.json --outfile=dist/human.js src/human.js","build-esm-bundle":"esbuild --bundle --platform=browser --sourcemap --target=esnext --format=esm --minify --external:fs --metafile=dist/human.esm.json --outfile=dist/human.esm.js src/human.js","build-esm-nobundle":"esbuild --bundle --platform=browser --sourcemap --target=esnext --format=esm --minify --external:@tensorflow --external:fs --metafile=dist/human.esm-nobundle.json --outfile=dist/human.esm-nobundle.js src/human.js","build-node":"esbuild --bundle --platform=node --sourcemap --target=esnext --format=cjs --external:@tensorflow --metafile=dist/human.cjs.json --outfile=dist/human.cjs src/human.js",build:"rimraf dist/* && npm run build-iife && npm run build-esm-bundle && npm run build-esm-nobundle && npm run build-node && ls -l dist/",update:"npm update --depth 20 && npm dedupe && npm prune && npm audit",changelog:"node changelog.js"},keywords:["tensorflowjs","face-detection","face-geometry","body-tracking","hand-tracking","iris-tracking","age-estimation","emotion-detection","gender-prediction","gesture-recognition"]}});const R=require("@tensorflow/tfjs"),l0=ht(),de=mt(),Le=gt(),h0=jt(),u0=s0(),bn=r0(),le=a0().default,yn=d0();let m0=!0;const wn={face:{detector:{skipFrames:0},age:{skipFrames:0},emotion:{skipFrames:0}},hand:{skipFrames:0}},I=()=>typeof performance!="undefined"?performance.now():parseInt(Number(process.hrtime.bigint())/1e3/1e3);function he(...e){const t=o=>o&&typeof o=="object";return e.reduce((o,n)=>(Object.keys(n||{}).forEach(s=>{const i=o[s],a=n[s];Array.isArray(i)&&Array.isArray(a)?o[s]=i.concat(...a):t(i)&&t(a)?o[s]=he(i,a):o[s]=a}),o),{})}function En(e){if(!e)return"input is not defined";if(R.ENV.flags.IS_NODE&&!(e instanceof R.Tensor))return"input must be a tensor";try{R.getBackend()}catch{return"backend not loaded"}return null}class vn{constructor(){this.tf=R,this.version=yn.version,this.defaults=le,this.config=le,this.fx=R.ENV.flags.IS_BROWSER&&typeof document!="undefined"?new bn.Canvas:null,this.state="idle",this.numTensors=0,this.analyzeMemoryLeaks=!1,this.models={facemesh:null,posenet:null,handpose:null,iris:null,age:null,gender:null,emotion:null},this.facemesh=l0,this.ssrnet=de,this.emotion=Le,this.posenet=h0,this.handpose=u0}log(...e){e&&this.config.console&&console.log(...e)}analyze(...e){if(!this.analyzeMemoryLeaks)return;const t=R.engine().state.numTensors,o=this.numTensors;this.numTensors=t;const n=t-o;n!==0&&this.log(...e,n)}async load(e){e&&(this.config=he(le,e)),this.config.face.enabled&&!this.models.facemesh&&(this.log("Load model: Face"),this.models.facemesh=await l0.load(this.config.face)),this.config.body.enabled&&!this.models.posenet&&(this.log("Load model: Body"),this.models.posenet=await h0.load(this.config.body)),this.config.hand.enabled&&!this.models.handpose&&(this.log("Load model: Hand"),this.models.handpose=await u0.load(this.config.hand)),this.config.face.enabled&&this.config.face.age.enabled&&!this.models.age&&(this.log("Load model: Age"),this.models.age=await de.loadAge(this.config)),this.config.face.enabled&&this.config.face.gender.enabled&&!this.models.gender&&(this.log("Load model: Gender"),this.models.gender=await de.loadGender(this.config)),this.config.face.enabled&&this.config.face.emotion.enabled&&!this.models.emotion&&(this.log("Load model: Emotion"),this.models.emotion=await Le.load(this.config))}tfImage(e){let t;if(this.fx&&this.config.filter.enabled&&!(e instanceof R.Tensor)){const n=e.naturalWidth||e.videoWidth||e.width||e.shape&&e.shape[1]>0,s=e.naturalHeight||e.videoHeight||e.height||e.shape&&e.shape[2]>0,i=new OffscreenCanvas(n,s),a=i.getContext("2d");e instanceof ImageData?a.putImageData(e,0,0):a.drawImage(e,0,0,n,s,0,0,i.width,i.height),this.fx.reset(),this.fx.addFilter("brightness",this.config.filter.brightness),this.config.filter.contrast!==0&&this.fx.addFilter("contrast",this.config.filter.contrast),this.config.filter.sharpness!==0&&this.fx.addFilter("sharpen",this.config.filter.sharpness),this.config.filter.blur!==0&&this.fx.addFilter("blur",this.config.filter.blur),this.config.filter.saturation!==0&&this.fx.addFilter("saturation",this.config.filter.saturation),this.config.filter.hue!==0&&this.fx.addFilter("hue",this.config.filter.hue),this.config.filter.negative&&this.fx.addFilter("negative"),this.config.filter.sepia&&this.fx.addFilter("sepia"),this.config.filter.vintage&&this.fx.addFilter("brownie"),this.config.filter.sepia&&this.fx.addFilter("sepia"),this.config.filter.kodachrome&&this.fx.addFilter("kodachrome"),this.config.filter.technicolor&&this.fx.addFilter("technicolor"),this.config.filter.polaroid&&this.fx.addFilter("polaroid"),this.config.filter.pixelate!==0&&this.fx.addFilter("pixelate",this.config.filter.pixelate),t=this.fx.apply(i)}let o;if(e instanceof R.Tensor)o=R.clone(e);else{const n=R.browser.fromPixels(t||e),s=n.toFloat();o=s.expandDims(0),n.dispose(),s.dispose()}return{tensor:o,canvas:this.config.filter.return?t:null}}async detect(e,t={}){this.state="config";const o={};let n;n=I(),this.config=he(le,t),this.config.videoOptimized||(this.config=he(this.config,wn)),o.config=Math.trunc(I()-n),n=I(),this.state="check";const s=En(e);return s?(this.log(s,e),{error:s}):(o.sanity=Math.trunc(I()-n),new Promise(async i=>{const a=I();n=I(),R.getBackend()!==this.config.backend&&(this.state="backend",this.log("Human library setting backend:",this.config.backend),await R.setBackend(this.config.backend),await R.ready()),o.backend=Math.trunc(I()-n),m0&&(this.log("Human library starting"),this.log("Configuration:",this.config),this.log("Flags:",R.ENV.flags),m0=!1),n=I(),this.state="load",await this.load(),o.load=Math.trunc(I()-n),this.config.scoped&&R.engine().startScope(),this.analyze("Start Detect:"),n=I();const c=this.tfImage(e);o.image=Math.trunc(I()-n);const d=c.tensor;this.state="run:body",n=I(),this.analyze("Start PoseNet");const l=this.config.body.enabled?await this.models.posenet.estimatePoses(d,this.config.body):[];this.analyze("End PoseNet:"),o.body=Math.trunc(I()-n),this.state="run:hand",n=I(),this.analyze("Start HandPose:");const u=this.config.hand.enabled?await this.models.handpose.estimateHands(d,this.config.hand):[];this.analyze("End HandPose:"),o.hand=Math.trunc(I()-n);const f=[];if(this.config.face.enabled){this.state="run:face",n=I(),this.analyze("Start FaceMesh:");const h=await this.models.facemesh.estimateFaces(d,this.config.face);o.face=Math.trunc(I()-n);for(const r of h){if(!r.image||r.image.isDisposedInternal){this.log("face object is disposed:",r.image);continue}this.state="run:agegender",n=I();const b=this.config.face.age.enabled||this.config.face.gender.enabled?await de.predict(r.image,this.config):{};o.agegender=Math.trunc(I()-n),this.state="run:emotion",n=I();const _=this.config.face.emotion.enabled?await Le.predict(r.image,this.config):{};o.emotion=Math.trunc(I()-n),r.image.dispose();const P=r.annotations.leftEyeIris&&r.annotations.rightEyeIris?Math.max(r.annotations.leftEyeIris[3][0]-r.annotations.leftEyeIris[1][0],r.annotations.rightEyeIris[3][0]-r.annotations.rightEyeIris[1][0]):0;f.push({confidence:r.confidence,box:r.box,mesh:r.mesh,annotations:r.annotations,age:b.age,gender:b.gender,agConfidence:b.confidence,emotion:_,iris:P!==0?Math.trunc(100*11.7/P)/100:0}),this.analyze("End FaceMesh:")}}d.dispose(),this.state="idle",this.config.scoped&&R.engine().endScope(),this.analyze("End Scope:"),o.total=Math.trunc(I()-a),i({face:f,body:l,hand:u,performance:o,canvas:c.canvas})}))}}export{vn as default}; //# sourceMappingURL=human.esm-nobundle.js.map diff --git a/dist/human.esm-nobundle.js.map b/dist/human.esm-nobundle.js.map index 7fc765c2..cca246bf 100644 --- a/dist/human.esm-nobundle.js.map +++ b/dist/human.esm-nobundle.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["../src/facemesh/blazeface.js", "../src/facemesh/keypoints.js", "../src/facemesh/box.js", "../src/facemesh/util.js", "../src/facemesh/pipeline.js", "../src/facemesh/uvcoords.js", "../src/facemesh/triangulation.js", "../src/facemesh/facemesh.js", "../src/ssrnet/ssrnet.js", "../src/emotion/emotion.js", "../src/posenet/modelBase.js", "../src/posenet/modelMobileNet.js", "../src/posenet/heapSort.js", "../src/posenet/buildParts.js", "../src/posenet/keypoints.js", "../src/posenet/vectors.js", "../src/posenet/decodePose.js", "../src/posenet/decodeMultiple.js", "../src/posenet/util.js", "../src/posenet/modelPoseNet.js", "../src/posenet/posenet.js", "../src/handpose/box.js", "../src/handpose/handdetector.js", "../src/handpose/keypoints.js", "../src/handpose/util.js", "../src/handpose/pipeline.js", "../src/handpose/handpose.js", "../src/imagefx.js", "../config.js", "../src/human.js"], - "sourcesContent": ["const tf = require('@tensorflow/tfjs');\n\nconst NUM_LANDMARKS = 6;\n\nfunction generateAnchors(inputSize) {\n const spec = { strides: [inputSize / 16, inputSize / 8], anchors: [2, 6] };\n const anchors = [];\n for (let i = 0; i < spec.strides.length; i++) {\n const stride = spec.strides[i];\n const gridRows = Math.floor((inputSize + stride - 1) / stride);\n const gridCols = Math.floor((inputSize + stride - 1) / stride);\n const anchorsNum = spec.anchors[i];\n for (let gridY = 0; gridY < gridRows; gridY++) {\n const anchorY = stride * (gridY + 0.5);\n for (let gridX = 0; gridX < gridCols; gridX++) {\n const anchorX = stride * (gridX + 0.5);\n for (let n = 0; n < anchorsNum; n++) {\n anchors.push([anchorX, anchorY]);\n }\n }\n }\n }\n return anchors;\n}\n\nconst disposeBox = (box) => {\n box.startEndTensor.dispose();\n box.startPoint.dispose();\n box.endPoint.dispose();\n};\n\nconst createBox = (startEndTensor) => ({\n startEndTensor,\n startPoint: tf.slice(startEndTensor, [0, 0], [-1, 2]),\n endPoint: tf.slice(startEndTensor, [0, 2], [-1, 2]),\n});\n\nconst scaleBox = (box, factors) => {\n const starts = tf.mul(box.startPoint, factors);\n const ends = tf.mul(box.endPoint, factors);\n const newCoordinates = tf.concat2d([starts, ends], 1);\n return createBox(newCoordinates);\n};\n\nfunction decodeBounds(boxOutputs, anchors, inputSize) {\n const boxStarts = tf.slice(boxOutputs, [0, 1], [-1, 2]);\n const centers = tf.add(boxStarts, anchors);\n const boxSizes = tf.slice(boxOutputs, [0, 3], [-1, 2]);\n const boxSizesNormalized = tf.div(boxSizes, inputSize);\n const centersNormalized = tf.div(centers, inputSize);\n const halfBoxSize = tf.div(boxSizesNormalized, 2);\n const starts = tf.sub(centersNormalized, halfBoxSize);\n const ends = tf.add(centersNormalized, halfBoxSize);\n const startNormalized = tf.mul(starts, inputSize);\n const endNormalized = tf.mul(ends, inputSize);\n const concatAxis = 1;\n return tf.concat2d([startNormalized, endNormalized], concatAxis);\n}\n\nfunction scaleBoxFromPrediction(face, scaleFactor) {\n return tf.tidy(() => {\n const box = face['box'] ? face['box'] : face;\n return scaleBox(box, scaleFactor).startEndTensor.squeeze();\n });\n}\n\nclass BlazeFaceModel {\n constructor(model, config) {\n this.blazeFaceModel = model;\n this.width = config.detector.inputSize;\n this.height = config.detector.inputSize;\n this.maxFaces = config.detector.maxFaces;\n this.anchorsData = generateAnchors(config.detector.inputSize);\n this.anchors = tf.tensor2d(this.anchorsData);\n this.inputSize = tf.tensor1d([this.width, this.height]);\n this.iouThreshold = config.detector.iouThreshold;\n this.scaleFaces = 0.8;\n this.scoreThreshold = config.detector.scoreThreshold;\n }\n\n // toto blazeface leaks two tensors per run\n async getBoundingBoxes(inputImage) {\n // sanity check on input\n if ((!inputImage) || (inputImage.isDisposedInternal) || (inputImage.shape.length !== 4) || (inputImage.shape[1] < 1) || (inputImage.shape[2] < 1)) return null;\n const [detectedOutputs, boxes, scores] = tf.tidy(() => {\n const resizedImage = inputImage.resizeBilinear([this.width, this.height]);\n const normalizedImage = tf.mul(tf.sub(resizedImage.div(255), 0.5), 2);\n const batchedPrediction = this.blazeFaceModel.predict(normalizedImage);\n let prediction;\n // are we using tfhub or pinto converted model?\n if (Array.isArray(batchedPrediction)) {\n const sorted = batchedPrediction.sort((a, b) => a.size - b.size);\n const concat384 = tf.concat([sorted[0], sorted[2]], 2); // dim: 384, 1 + 16\n const concat512 = tf.concat([sorted[1], sorted[3]], 2); // dim: 512, 1 + 16\n const concat = tf.concat([concat512, concat384], 1);\n prediction = concat.squeeze(0);\n } else {\n prediction = batchedPrediction.squeeze(); // when using tfhub model\n }\n const decodedBounds = decodeBounds(prediction, this.anchors, this.inputSize);\n const logits = tf.slice(prediction, [0, 0], [-1, 1]);\n const scoresOut = tf.sigmoid(logits).squeeze();\n return [prediction, decodedBounds, scoresOut];\n });\n const boxIndicesTensor = await tf.image.nonMaxSuppressionAsync(boxes, scores, this.maxFaces, this.iouThreshold, this.scoreThreshold);\n const boxIndices = await boxIndicesTensor.array();\n boxIndicesTensor.dispose();\n const boundingBoxesMap = boxIndices.map((boxIndex) => tf.slice(boxes, [boxIndex, 0], [1, -1]));\n const boundingBoxes = await Promise.all(boundingBoxesMap.map(async (boundingBox) => {\n const vals = await boundingBox.array();\n boundingBox.dispose();\n return vals;\n }));\n const annotatedBoxes = [];\n for (let i = 0; i < boundingBoxes.length; i++) {\n const boundingBox = boundingBoxes[i];\n const box = createBox(boundingBox);\n const boxIndex = boxIndices[i];\n const anchor = this.anchorsData[boxIndex];\n const sliced = tf.slice(detectedOutputs, [boxIndex, NUM_LANDMARKS - 1], [1, -1]);\n const squeezed = sliced.squeeze();\n const landmarks = squeezed.reshape([NUM_LANDMARKS, -1]);\n /*\n const landmarks = tf\n .slice(detectedOutputs, [boxIndex, NUM_LANDMARKS - 1], [1, -1])\n .squeeze()\n .reshape([NUM_LANDMARKS, -1]);\n */\n const probability = tf.slice(scores, [boxIndex], [1]);\n const annotatedBox = { box, landmarks, probability, anchor };\n annotatedBoxes.push(annotatedBox);\n sliced.dispose();\n squeezed.dispose();\n // landmarks.dispose();\n }\n detectedOutputs.dispose();\n boxes.dispose();\n scores.dispose();\n detectedOutputs.dispose();\n return {\n boxes: annotatedBoxes,\n scaleFactor: [inputImage.shape[2] / this.width, inputImage.shape[1] / this.height],\n };\n }\n\n async estimateFaces(input) {\n const { boxes, scaleFactor } = await this.getBoundingBoxes(input);\n return Promise.all(boxes.map(async (face) => {\n const scaledBox = scaleBoxFromPrediction(face, scaleFactor);\n const [landmarkData, boxData, probabilityData] = await Promise.all([face.landmarks, scaledBox, face.probability].map(async (d) => d.array()));\n const anchor = face.anchor;\n const [scaleFactorX, scaleFactorY] = scaleFactor;\n const scaledLandmarks = landmarkData\n .map((landmark) => ([\n (landmark[0] + anchor[0]) * scaleFactorX,\n (landmark[1] + anchor[1]) * scaleFactorY,\n ]));\n const normalizedFace = {\n topLeft: boxData.slice(0, 2),\n bottomRight: boxData.slice(2),\n landmarks: scaledLandmarks,\n probability: probabilityData,\n };\n disposeBox(face.box);\n face.landmarks.dispose();\n face.probability.dispose();\n scaledBox.dispose();\n return normalizedFace;\n }));\n }\n}\n\nasync function load(config) {\n const blazeface = await tf.loadGraphModel(config.detector.modelPath, { fromTFHub: config.detector.modelPath.includes('tfhub.dev') });\n const model = new BlazeFaceModel(blazeface, config);\n return model;\n}\n\nexports.load = load;\nexports.BlazeFaceModel = BlazeFaceModel;\nexports.disposeBox = disposeBox;\n", "exports.MESH_ANNOTATIONS = {\n silhouette: [\n 10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288,\n 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136,\n 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109,\n ],\n lipsUpperOuter: [61, 185, 40, 39, 37, 0, 267, 269, 270, 409, 291],\n lipsLowerOuter: [146, 91, 181, 84, 17, 314, 405, 321, 375, 291],\n lipsUpperInner: [78, 191, 80, 81, 82, 13, 312, 311, 310, 415, 308],\n lipsLowerInner: [78, 95, 88, 178, 87, 14, 317, 402, 318, 324, 308],\n rightEyeUpper0: [246, 161, 160, 159, 158, 157, 173],\n rightEyeLower0: [33, 7, 163, 144, 145, 153, 154, 155, 133],\n rightEyeUpper1: [247, 30, 29, 27, 28, 56, 190],\n rightEyeLower1: [130, 25, 110, 24, 23, 22, 26, 112, 243],\n rightEyeUpper2: [113, 225, 224, 223, 222, 221, 189],\n rightEyeLower2: [226, 31, 228, 229, 230, 231, 232, 233, 244],\n rightEyeLower3: [143, 111, 117, 118, 119, 120, 121, 128, 245],\n rightEyebrowUpper: [156, 70, 63, 105, 66, 107, 55, 193],\n rightEyebrowLower: [35, 124, 46, 53, 52, 65],\n rightEyeIris: [473, 474, 475, 476, 477],\n leftEyeUpper0: [466, 388, 387, 386, 385, 384, 398],\n leftEyeLower0: [263, 249, 390, 373, 374, 380, 381, 382, 362],\n leftEyeUpper1: [467, 260, 259, 257, 258, 286, 414],\n leftEyeLower1: [359, 255, 339, 254, 253, 252, 256, 341, 463],\n leftEyeUpper2: [342, 445, 444, 443, 442, 441, 413],\n leftEyeLower2: [446, 261, 448, 449, 450, 451, 452, 453, 464],\n leftEyeLower3: [372, 340, 346, 347, 348, 349, 350, 357, 465],\n leftEyebrowUpper: [383, 300, 293, 334, 296, 336, 285, 417],\n leftEyebrowLower: [265, 353, 276, 283, 282, 295],\n leftEyeIris: [468, 469, 470, 471, 472],\n midwayBetweenEyes: [168],\n noseTip: [1],\n noseBottom: [2],\n noseRightCorner: [98],\n noseLeftCorner: [327],\n rightCheek: [205],\n leftCheek: [425],\n};\nexports.MESH_TO_IRIS_INDICES_MAP = [ // A mapping from facemesh model keypoints to iris model keypoints.\n { key: 'EyeUpper0', indices: [9, 10, 11, 12, 13, 14, 15] },\n { key: 'EyeUpper1', indices: [25, 26, 27, 28, 29, 30, 31] },\n { key: 'EyeUpper2', indices: [41, 42, 43, 44, 45, 46, 47] },\n { key: 'EyeLower0', indices: [0, 1, 2, 3, 4, 5, 6, 7, 8] },\n { key: 'EyeLower1', indices: [16, 17, 18, 19, 20, 21, 22, 23, 24] },\n { key: 'EyeLower2', indices: [32, 33, 34, 35, 36, 37, 38, 39, 40] },\n { key: 'EyeLower3', indices: [54, 55, 56, 57, 58, 59, 60, 61, 62] },\n { key: 'EyebrowUpper', indices: [63, 64, 65, 66, 67, 68, 69, 70] },\n { key: 'EyebrowLower', indices: [48, 49, 50, 51, 52, 53] },\n];\n", "const tf = require('@tensorflow/tfjs');\n\nfunction scaleBoxCoordinates(box, factor) {\n const startPoint = [box.startPoint[0] * factor[0], box.startPoint[1] * factor[1]];\n const endPoint = [box.endPoint[0] * factor[0], box.endPoint[1] * factor[1]];\n return { startPoint, endPoint };\n}\nexports.scaleBoxCoordinates = scaleBoxCoordinates;\nfunction getBoxSize(box) {\n return [\n Math.abs(box.endPoint[0] - box.startPoint[0]),\n Math.abs(box.endPoint[1] - box.startPoint[1]),\n ];\n}\nexports.getBoxSize = getBoxSize;\nfunction getBoxCenter(box) {\n return [\n box.startPoint[0] + (box.endPoint[0] - box.startPoint[0]) / 2,\n box.startPoint[1] + (box.endPoint[1] - box.startPoint[1]) / 2,\n ];\n}\nexports.getBoxCenter = getBoxCenter;\nfunction cutBoxFromImageAndResize(box, image, cropSize) {\n const h = image.shape[1];\n const w = image.shape[2];\n const boxes = [[\n box.startPoint[1] / h, box.startPoint[0] / w, box.endPoint[1] / h,\n box.endPoint[0] / w,\n ]];\n return tf.image.cropAndResize(image, boxes, [0], cropSize);\n}\nexports.cutBoxFromImageAndResize = cutBoxFromImageAndResize;\nfunction enlargeBox(box, factor = 1.5) {\n const center = getBoxCenter(box);\n const size = getBoxSize(box);\n const newHalfSize = [factor * size[0] / 2, factor * size[1] / 2];\n const startPoint = [center[0] - newHalfSize[0], center[1] - newHalfSize[1]];\n const endPoint = [center[0] + newHalfSize[0], center[1] + newHalfSize[1]];\n return { startPoint, endPoint, landmarks: box.landmarks };\n}\nexports.enlargeBox = enlargeBox;\nfunction squarifyBox(box) {\n const centers = getBoxCenter(box);\n const size = getBoxSize(box);\n const maxEdge = Math.max(...size);\n const halfSize = maxEdge / 2;\n const startPoint = [centers[0] - halfSize, centers[1] - halfSize];\n const endPoint = [centers[0] + halfSize, centers[1] + halfSize];\n return { startPoint, endPoint, landmarks: box.landmarks };\n}\nexports.squarifyBox = squarifyBox;\n", "exports.IDENTITY_MATRIX = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];\n/**\n * Normalizes the provided angle to the range -pi to pi.\n * @param angle The angle in radians to be normalized.\n */\nfunction normalizeRadians(angle) {\n return angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));\n}\nexports.normalizeRadians = normalizeRadians;\n/**\n * Computes the angle of rotation between two anchor points.\n * @param point1 First anchor point\n * @param point2 Second anchor point\n */\nfunction computeRotation(point1, point2) {\n const radians = Math.PI / 2 - Math.atan2(-(point2[1] - point1[1]), point2[0] - point1[0]);\n return normalizeRadians(radians);\n}\nexports.computeRotation = computeRotation;\nfunction radToDegrees(rad) {\n return rad * 180 / Math.PI;\n}\nexports.radToDegrees = radToDegrees;\nfunction buildTranslationMatrix(x, y) {\n return [[1, 0, x], [0, 1, y], [0, 0, 1]];\n}\nfunction dot(v1, v2) {\n let product = 0;\n for (let i = 0; i < v1.length; i++) {\n product += v1[i] * v2[i];\n }\n return product;\n}\nexports.dot = dot;\nfunction getColumnFrom2DArr(arr, columnIndex) {\n const column = [];\n for (let i = 0; i < arr.length; i++) {\n column.push(arr[i][columnIndex]);\n }\n return column;\n}\nexports.getColumnFrom2DArr = getColumnFrom2DArr;\nfunction multiplyTransformMatrices(mat1, mat2) {\n const product = [];\n const size = mat1.length;\n for (let row = 0; row < size; row++) {\n product.push([]);\n for (let col = 0; col < size; col++) {\n product[row].push(dot(mat1[row], getColumnFrom2DArr(mat2, col)));\n }\n }\n return product;\n}\nfunction buildRotationMatrix(rotation, center) {\n const cosA = Math.cos(rotation);\n const sinA = Math.sin(rotation);\n const rotationMatrix = [[cosA, -sinA, 0], [sinA, cosA, 0], [0, 0, 1]];\n const translationMatrix = buildTranslationMatrix(center[0], center[1]);\n const translationTimesRotation = multiplyTransformMatrices(translationMatrix, rotationMatrix);\n const negativeTranslationMatrix = buildTranslationMatrix(-center[0], -center[1]);\n return multiplyTransformMatrices(translationTimesRotation, negativeTranslationMatrix);\n}\nexports.buildRotationMatrix = buildRotationMatrix;\nfunction invertTransformMatrix(matrix) {\n const rotationComponent = [[matrix[0][0], matrix[1][0]], [matrix[0][1], matrix[1][1]]];\n const translationComponent = [matrix[0][2], matrix[1][2]];\n const invertedTranslation = [\n -dot(rotationComponent[0], translationComponent),\n -dot(rotationComponent[1], translationComponent),\n ];\n return [\n rotationComponent[0].concat(invertedTranslation[0]),\n rotationComponent[1].concat(invertedTranslation[1]),\n [0, 0, 1],\n ];\n}\nexports.invertTransformMatrix = invertTransformMatrix;\nfunction rotatePoint(homogeneousCoordinate, rotationMatrix) {\n return [\n dot(homogeneousCoordinate, rotationMatrix[0]),\n dot(homogeneousCoordinate, rotationMatrix[1]),\n ];\n}\nexports.rotatePoint = rotatePoint;\nfunction xyDistanceBetweenPoints(a, b) {\n return Math.sqrt(((a[0] - b[0]) ** 2) + ((a[1] - b[1]) ** 2));\n}\nexports.xyDistanceBetweenPoints = xyDistanceBetweenPoints;\n", "/* eslint-disable class-methods-use-this */\nconst tf = require('@tensorflow/tfjs');\nconst bounding = require('./box');\nconst keypoints = require('./keypoints');\nconst util = require('./util');\n\nconst LANDMARKS_COUNT = 468;\nconst UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD = 0.25;\nconst MESH_MOUTH_INDEX = 13;\nconst MESH_KEYPOINTS_LINE_OF_SYMMETRY_INDICES = [MESH_MOUTH_INDEX, keypoints.MESH_ANNOTATIONS['midwayBetweenEyes'][0]];\nconst BLAZEFACE_MOUTH_INDEX = 3;\nconst BLAZEFACE_NOSE_INDEX = 2;\nconst BLAZEFACE_KEYPOINTS_LINE_OF_SYMMETRY_INDICES = [BLAZEFACE_MOUTH_INDEX, BLAZEFACE_NOSE_INDEX];\nconst LEFT_EYE_OUTLINE = keypoints.MESH_ANNOTATIONS['leftEyeLower0'];\nconst LEFT_EYE_BOUNDS = [LEFT_EYE_OUTLINE[0], LEFT_EYE_OUTLINE[LEFT_EYE_OUTLINE.length - 1]];\nconst RIGHT_EYE_OUTLINE = keypoints.MESH_ANNOTATIONS['rightEyeLower0'];\nconst RIGHT_EYE_BOUNDS = [RIGHT_EYE_OUTLINE[0], RIGHT_EYE_OUTLINE[RIGHT_EYE_OUTLINE.length - 1]];\nconst IRIS_UPPER_CENTER_INDEX = 3;\nconst IRIS_LOWER_CENTER_INDEX = 4;\nconst IRIS_IRIS_INDEX = 71;\nconst IRIS_NUM_COORDINATES = 76;\n\n// Replace the raw coordinates returned by facemesh with refined iris model coordinates. Update the z coordinate to be an average of the original and the new. This produces the best visual effect.\nfunction replaceRawCoordinates(rawCoords, newCoords, prefix, keys) {\n for (let i = 0; i < keypoints.MESH_TO_IRIS_INDICES_MAP.length; i++) {\n const { key, indices } = keypoints.MESH_TO_IRIS_INDICES_MAP[i];\n const originalIndices = keypoints.MESH_ANNOTATIONS[`${prefix}${key}`];\n const shouldReplaceAllKeys = keys == null;\n if (shouldReplaceAllKeys || keys.includes(key)) {\n for (let j = 0; j < indices.length; j++) {\n const index = indices[j];\n rawCoords[originalIndices[j]] = [\n newCoords[index][0], newCoords[index][1],\n (newCoords[index][2] + rawCoords[originalIndices[j]][2]) / 2,\n ];\n }\n }\n }\n}\n// The Pipeline coordinates between the bounding box and skeleton models.\nclass Pipeline {\n constructor(boundingBoxDetector, meshDetector, irisModel, config) {\n // An array of facial bounding boxes.\n this.regionsOfInterest = [];\n this.runsWithoutFaceDetector = 0;\n this.boundingBoxDetector = boundingBoxDetector;\n this.meshDetector = meshDetector;\n this.irisModel = irisModel;\n this.meshWidth = config.mesh.inputSize;\n this.meshHeight = config.mesh.inputSize;\n this.irisSize = config.iris.inputSize;\n this.irisEnlarge = config.iris.enlargeFactor;\n }\n\n transformRawCoords(rawCoords, box, angle, rotationMatrix) {\n const boxSize = bounding.getBoxSize({ startPoint: box.startPoint, endPoint: box.endPoint });\n const scaleFactor = [boxSize[0] / this.meshWidth, boxSize[1] / this.meshHeight];\n const coordsScaled = rawCoords.map((coord) => ([\n scaleFactor[0] * (coord[0] - this.meshWidth / 2),\n scaleFactor[1] * (coord[1] - this.meshHeight / 2), coord[2],\n ]));\n const coordsRotationMatrix = util.buildRotationMatrix(angle, [0, 0]);\n const coordsRotated = coordsScaled.map((coord) => ([...util.rotatePoint(coord, coordsRotationMatrix), coord[2]]));\n const inverseRotationMatrix = util.invertTransformMatrix(rotationMatrix);\n const boxCenter = [...bounding.getBoxCenter({ startPoint: box.startPoint, endPoint: box.endPoint }), 1];\n const originalBoxCenter = [\n util.dot(boxCenter, inverseRotationMatrix[0]),\n util.dot(boxCenter, inverseRotationMatrix[1]),\n ];\n return coordsRotated.map((coord) => ([\n coord[0] + originalBoxCenter[0],\n coord[1] + originalBoxCenter[1], coord[2],\n ]));\n }\n\n getLeftToRightEyeDepthDifference(rawCoords) {\n const leftEyeZ = rawCoords[LEFT_EYE_BOUNDS[0]][2];\n const rightEyeZ = rawCoords[RIGHT_EYE_BOUNDS[0]][2];\n return leftEyeZ - rightEyeZ;\n }\n\n // Returns a box describing a cropped region around the eye fit for passing to the iris model.\n getEyeBox(rawCoords, face, eyeInnerCornerIndex, eyeOuterCornerIndex, flip = false) {\n const box = bounding.squarifyBox(bounding.enlargeBox(this.calculateLandmarksBoundingBox([rawCoords[eyeInnerCornerIndex], rawCoords[eyeOuterCornerIndex]]), this.irisEnlarge));\n const boxSize = bounding.getBoxSize(box);\n let crop = tf.image.cropAndResize(face, [[\n box.startPoint[1] / this.meshHeight,\n box.startPoint[0] / this.meshWidth, box.endPoint[1] / this.meshHeight,\n box.endPoint[0] / this.meshWidth,\n ]], [0], [this.irisSize, this.irisSize]);\n if (flip) {\n crop = tf.image.flipLeftRight(crop);\n }\n return { box, boxSize, crop };\n }\n\n // Given a cropped image of an eye, returns the coordinates of the contours surrounding the eye and the iris.\n getEyeCoords(eyeData, eyeBox, eyeBoxSize, flip = false) {\n const eyeRawCoords = [];\n for (let i = 0; i < IRIS_NUM_COORDINATES; i++) {\n const x = eyeData[i * 3];\n const y = eyeData[i * 3 + 1];\n const z = eyeData[i * 3 + 2];\n eyeRawCoords.push([\n (flip\n ? (1 - (x / this.irisSize))\n : (x / this.irisSize)) * eyeBoxSize[0] + eyeBox.startPoint[0],\n (y / this.irisSize) * eyeBoxSize[1] + eyeBox.startPoint[1], z,\n ]);\n }\n return { rawCoords: eyeRawCoords, iris: eyeRawCoords.slice(IRIS_IRIS_INDEX) };\n }\n\n // The z-coordinates returned for the iris are unreliable, so we take the z values from the surrounding keypoints.\n getAdjustedIrisCoords(rawCoords, irisCoords, direction) {\n const upperCenterZ = rawCoords[keypoints.MESH_ANNOTATIONS[`${direction}EyeUpper0`][IRIS_UPPER_CENTER_INDEX]][2];\n const lowerCenterZ = rawCoords[keypoints.MESH_ANNOTATIONS[`${direction}EyeLower0`][IRIS_LOWER_CENTER_INDEX]][2];\n const averageZ = (upperCenterZ + lowerCenterZ) / 2;\n // Iris indices: 0: center | 1: right | 2: above | 3: left | 4: below\n return irisCoords.map((coord, i) => {\n let z = averageZ;\n if (i === 2) {\n z = upperCenterZ;\n } else if (i === 4) {\n z = lowerCenterZ;\n }\n return [coord[0], coord[1], z];\n });\n }\n\n async predict(input, config) {\n this.skipFrames = config.detector.skipFrames;\n this.maxFaces = config.detector.maxFaces;\n this.runsWithoutFaceDetector++;\n if (this.shouldUpdateRegionsOfInterest()) {\n const detector = await this.boundingBoxDetector.getBoundingBoxes(input);\n if (detector.boxes.length === 0) {\n this.regionsOfInterest = [];\n return null;\n }\n const scaledBoxes = detector.boxes.map((prediction) => {\n const startPoint = prediction.box.startPoint.squeeze();\n const endPoint = prediction.box.endPoint.squeeze();\n const predictionBox = {\n startPoint: startPoint.arraySync(),\n endPoint: endPoint.arraySync(),\n };\n startPoint.dispose();\n endPoint.dispose();\n const scaledBox = bounding.scaleBoxCoordinates(predictionBox, detector.scaleFactor);\n const enlargedBox = bounding.enlargeBox(scaledBox);\n const landmarks = prediction.landmarks.arraySync();\n prediction.box.startPoint.dispose();\n prediction.box.endPoint.dispose();\n prediction.landmarks.dispose();\n prediction.probability.dispose();\n return { ...enlargedBox, landmarks };\n });\n this.updateRegionsOfInterest(scaledBoxes);\n this.runsWithoutFaceDetector = 0;\n }\n const results = tf.tidy(() => this.regionsOfInterest.map((box, i) => {\n let angle = 0;\n // The facial bounding box landmarks could come either from blazeface (if we are using a fresh box), or from the mesh model (if we are reusing an old box).\n const boxLandmarksFromMeshModel = box.landmarks.length >= LANDMARKS_COUNT;\n let [indexOfMouth, indexOfForehead] = MESH_KEYPOINTS_LINE_OF_SYMMETRY_INDICES;\n if (boxLandmarksFromMeshModel === false) {\n [indexOfMouth, indexOfForehead] = BLAZEFACE_KEYPOINTS_LINE_OF_SYMMETRY_INDICES;\n }\n angle = util.computeRotation(box.landmarks[indexOfMouth], box.landmarks[indexOfForehead]);\n const faceCenter = bounding.getBoxCenter({ startPoint: box.startPoint, endPoint: box.endPoint });\n const faceCenterNormalized = [faceCenter[0] / input.shape[2], faceCenter[1] / input.shape[1]];\n let rotatedImage = input;\n let rotationMatrix = util.IDENTITY_MATRIX;\n if (angle !== 0) {\n rotatedImage = tf.image.rotateWithOffset(input, angle, 0, faceCenterNormalized);\n rotationMatrix = util.buildRotationMatrix(-angle, faceCenter);\n }\n const boxCPU = { startPoint: box.startPoint, endPoint: box.endPoint };\n const face = bounding.cutBoxFromImageAndResize(boxCPU, rotatedImage, [this.meshHeight, this.meshWidth]).div(255);\n // The first returned tensor represents facial contours, which are included in the coordinates.\n const [, flag, coords] = this.meshDetector.predict(face);\n const coordsReshaped = tf.reshape(coords, [-1, 3]);\n let rawCoords = coordsReshaped.arraySync();\n if (config.iris.enabled) {\n const { box: leftEyeBox, boxSize: leftEyeBoxSize, crop: leftEyeCrop } = this.getEyeBox(rawCoords, face, LEFT_EYE_BOUNDS[0], LEFT_EYE_BOUNDS[1], true);\n const { box: rightEyeBox, boxSize: rightEyeBoxSize, crop: rightEyeCrop } = this.getEyeBox(rawCoords, face, RIGHT_EYE_BOUNDS[0], RIGHT_EYE_BOUNDS[1]);\n const eyePredictions = (this.irisModel.predict(tf.concat([leftEyeCrop, rightEyeCrop])));\n const eyePredictionsData = eyePredictions.dataSync();\n eyePredictions.dispose();\n const leftEyeData = eyePredictionsData.slice(0, IRIS_NUM_COORDINATES * 3);\n const { rawCoords: leftEyeRawCoords, iris: leftIrisRawCoords } = this.getEyeCoords(leftEyeData, leftEyeBox, leftEyeBoxSize, true);\n const rightEyeData = eyePredictionsData.slice(IRIS_NUM_COORDINATES * 3);\n const { rawCoords: rightEyeRawCoords, iris: rightIrisRawCoords } = this.getEyeCoords(rightEyeData, rightEyeBox, rightEyeBoxSize);\n const leftToRightEyeDepthDifference = this.getLeftToRightEyeDepthDifference(rawCoords);\n if (Math.abs(leftToRightEyeDepthDifference) < 30) { // User is looking straight ahead.\n replaceRawCoordinates(rawCoords, leftEyeRawCoords, 'left');\n replaceRawCoordinates(rawCoords, rightEyeRawCoords, 'right');\n // If the user is looking to the left or to the right, the iris coordinates tend to diverge too much from the mesh coordinates for them to be merged. So we only update a single contour line above and below the eye.\n } else if (leftToRightEyeDepthDifference < 1) { // User is looking towards the right.\n replaceRawCoordinates(rawCoords, leftEyeRawCoords, 'left', ['EyeUpper0', 'EyeLower0']);\n } else { // User is looking towards the left.\n replaceRawCoordinates(rawCoords, rightEyeRawCoords, 'right', ['EyeUpper0', 'EyeLower0']);\n }\n const adjustedLeftIrisCoords = this.getAdjustedIrisCoords(rawCoords, leftIrisRawCoords, 'left');\n const adjustedRightIrisCoords = this.getAdjustedIrisCoords(rawCoords, rightIrisRawCoords, 'right');\n rawCoords = rawCoords.concat(adjustedLeftIrisCoords).concat(adjustedRightIrisCoords);\n }\n const transformedCoordsData = this.transformRawCoords(rawCoords, box, angle, rotationMatrix);\n tf.dispose(rawCoords);\n const landmarksBox = bounding.enlargeBox(this.calculateLandmarksBoundingBox(transformedCoordsData));\n const confidence = flag.squeeze();\n tf.dispose(flag);\n if (config.mesh.enabled) {\n const transformedCoords = tf.tensor2d(transformedCoordsData);\n this.regionsOfInterest[i] = { ...landmarksBox, landmarks: transformedCoords.arraySync() };\n const prediction = {\n coords: transformedCoords,\n box: landmarksBox,\n confidence,\n image: face,\n };\n return prediction;\n }\n const prediction = {\n coords: null,\n box: landmarksBox,\n confidence,\n image: face,\n };\n return prediction;\n }));\n return results;\n }\n\n // Updates regions of interest if the intersection over union between the incoming and previous regions falls below a threshold.\n updateRegionsOfInterest(boxes) {\n for (let i = 0; i < boxes.length; i++) {\n const box = boxes[i];\n const previousBox = this.regionsOfInterest[i];\n let iou = 0;\n if (previousBox && previousBox.startPoint) {\n const [boxStartX, boxStartY] = box.startPoint;\n const [boxEndX, boxEndY] = box.endPoint;\n const [previousBoxStartX, previousBoxStartY] = previousBox.startPoint;\n const [previousBoxEndX, previousBoxEndY] = previousBox.endPoint;\n const xStartMax = Math.max(boxStartX, previousBoxStartX);\n const yStartMax = Math.max(boxStartY, previousBoxStartY);\n const xEndMin = Math.min(boxEndX, previousBoxEndX);\n const yEndMin = Math.min(boxEndY, previousBoxEndY);\n const intersection = (xEndMin - xStartMax) * (yEndMin - yStartMax);\n const boxArea = (boxEndX - boxStartX) * (boxEndY - boxStartY);\n const previousBoxArea = (previousBoxEndX - previousBoxStartX) * (previousBoxEndY - boxStartY);\n iou = intersection / (boxArea + previousBoxArea - intersection);\n }\n if (iou < UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD) {\n this.regionsOfInterest[i] = box;\n }\n }\n this.regionsOfInterest = this.regionsOfInterest.slice(0, boxes.length);\n }\n\n clearRegionOfInterest(index) {\n if (this.regionsOfInterest[index] != null) {\n this.regionsOfInterest = [\n ...this.regionsOfInterest.slice(0, index),\n ...this.regionsOfInterest.slice(index + 1),\n ];\n }\n }\n\n shouldUpdateRegionsOfInterest() {\n if (this.regionsOfInterest.length === 0) return true; // nothing detected, so run detector on the next frame\n return (this.regionsOfInterest.length !== this.maxFaces) && (this.runsWithoutFaceDetector >= this.skipFrames);\n }\n\n calculateLandmarksBoundingBox(landmarks) {\n const xs = landmarks.map((d) => d[0]);\n const ys = landmarks.map((d) => d[1]);\n const startPoint = [Math.min(...xs), Math.min(...ys)];\n const endPoint = [Math.max(...xs), Math.max(...ys)];\n return { startPoint, endPoint, landmarks };\n }\n}\nexports.Pipeline = Pipeline;\n", "exports.UV_COORDS = [\n [0.499976992607117, 0.652534008026123],\n [0.500025987625122, 0.547487020492554],\n [0.499974012374878, 0.602371990680695],\n [0.482113003730774, 0.471979022026062],\n [0.500150978565216, 0.527155995368958],\n [0.499909996986389, 0.498252987861633],\n [0.499523013830185, 0.40106201171875],\n [0.289712011814117, 0.380764007568359],\n [0.499954998493195, 0.312398016452789],\n [0.499987006187439, 0.269918978214264],\n [0.500023007392883, 0.107050001621246],\n [0.500023007392883, 0.666234016418457],\n [0.5000159740448, 0.679224014282227],\n [0.500023007392883, 0.692348003387451],\n [0.499976992607117, 0.695277988910675],\n [0.499976992607117, 0.70593398809433],\n [0.499976992607117, 0.719385027885437],\n [0.499976992607117, 0.737019002437592],\n [0.499967992305756, 0.781370997428894],\n [0.499816000461578, 0.562981009483337],\n [0.473773002624512, 0.573909997940063],\n [0.104906998574734, 0.254140973091125],\n [0.365929991006851, 0.409575998783112],\n [0.338757991790771, 0.41302502155304],\n [0.311120003461838, 0.409460008144379],\n [0.274657994508743, 0.389131009578705],\n [0.393361985683441, 0.403706014156342],\n [0.345234006643295, 0.344011008739471],\n [0.370094001293182, 0.346076011657715],\n [0.319321990013123, 0.347265005111694],\n [0.297903001308441, 0.353591024875641],\n [0.24779200553894, 0.410809993743896],\n [0.396889001131058, 0.842755019664764],\n [0.280097991228104, 0.375599980354309],\n [0.106310002505779, 0.399955987930298],\n [0.2099249958992, 0.391353011131287],\n [0.355807989835739, 0.534406006336212],\n [0.471751004457474, 0.65040397644043],\n [0.474155008792877, 0.680191993713379],\n [0.439785003662109, 0.657229006290436],\n [0.414617002010345, 0.66654098033905],\n [0.450374007225037, 0.680860996246338],\n [0.428770989179611, 0.682690978050232],\n [0.374971002340317, 0.727805018424988],\n [0.486716985702515, 0.547628998756409],\n [0.485300987958908, 0.527395009994507],\n [0.257764995098114, 0.314490020275116],\n [0.401223003864288, 0.455172002315521],\n [0.429818987846375, 0.548614978790283],\n [0.421351999044418, 0.533740997314453],\n [0.276895999908447, 0.532056987285614],\n [0.483370006084442, 0.499586999416351],\n [0.33721199631691, 0.282882988452911],\n [0.296391993761063, 0.293242990970612],\n [0.169294998049736, 0.193813979625702],\n [0.447580009698868, 0.302609980106354],\n [0.392390012741089, 0.353887975215912],\n [0.354490011930466, 0.696784019470215],\n [0.067304998636246, 0.730105042457581],\n [0.442739009857178, 0.572826027870178],\n [0.457098007202148, 0.584792017936707],\n [0.381974011659622, 0.694710969924927],\n [0.392388999462128, 0.694203019142151],\n [0.277076005935669, 0.271932005882263],\n [0.422551989555359, 0.563233017921448],\n [0.385919004678726, 0.281364023685455],\n [0.383103013038635, 0.255840003490448],\n [0.331431001424789, 0.119714021682739],\n [0.229923993349075, 0.232002973556519],\n [0.364500999450684, 0.189113974571228],\n [0.229622006416321, 0.299540996551514],\n [0.173287004232407, 0.278747975826263],\n [0.472878992557526, 0.666198015213013],\n [0.446828007698059, 0.668527007102966],\n [0.422762006521225, 0.673889994621277],\n [0.445307999849319, 0.580065965652466],\n [0.388103008270264, 0.693961024284363],\n [0.403039008378983, 0.706539988517761],\n [0.403629004955292, 0.693953037261963],\n [0.460041999816895, 0.557139039039612],\n [0.431158006191254, 0.692366003990173],\n [0.452181994915009, 0.692366003990173],\n [0.475387006998062, 0.692366003990173],\n [0.465828001499176, 0.779190003871918],\n [0.472328990697861, 0.736225962638855],\n [0.473087012767792, 0.717857003211975],\n [0.473122000694275, 0.704625964164734],\n [0.473033010959625, 0.695277988910675],\n [0.427942007780075, 0.695277988910675],\n [0.426479011774063, 0.703539967536926],\n [0.423162013292313, 0.711845993995667],\n [0.4183090031147, 0.720062971115112],\n [0.390094995498657, 0.639572978019714],\n [0.013953999616206, 0.560034036636353],\n [0.499913990497589, 0.58014702796936],\n [0.413199990987778, 0.69539999961853],\n [0.409626007080078, 0.701822996139526],\n [0.468080013990402, 0.601534962654114],\n [0.422728985548019, 0.585985004901886],\n [0.463079988956451, 0.593783974647522],\n [0.37211999297142, 0.47341400384903],\n [0.334562003612518, 0.496073007583618],\n [0.411671012639999, 0.546965003013611],\n [0.242175996303558, 0.14767599105835],\n [0.290776997804642, 0.201445996761322],\n [0.327338010072708, 0.256527006626129],\n [0.399509996175766, 0.748921036720276],\n [0.441727995872498, 0.261676013469696],\n [0.429764986038208, 0.187834024429321],\n [0.412198007106781, 0.108901023864746],\n [0.288955003023148, 0.398952007293701],\n [0.218936994671822, 0.435410976409912],\n [0.41278201341629, 0.398970007896423],\n [0.257135003805161, 0.355440020561218],\n [0.427684992551804, 0.437960982322693],\n [0.448339998722076, 0.536936044692993],\n [0.178560003638268, 0.45755398273468],\n [0.247308000922203, 0.457193970680237],\n [0.286267012357712, 0.467674970626831],\n [0.332827985286713, 0.460712015628815],\n [0.368755996227264, 0.447206974029541],\n [0.398963987827301, 0.432654976844788],\n [0.476410001516342, 0.405806005001068],\n [0.189241006970406, 0.523923993110657],\n [0.228962004184723, 0.348950982093811],\n [0.490725994110107, 0.562400996685028],\n [0.404670000076294, 0.485132992267609],\n [0.019469000399113, 0.401564002037048],\n [0.426243007183075, 0.420431017875671],\n [0.396993011236191, 0.548797011375427],\n [0.266469985246658, 0.376977026462555],\n [0.439121007919312, 0.51895797252655],\n [0.032313998788595, 0.644356966018677],\n [0.419054001569748, 0.387154996395111],\n [0.462783008813858, 0.505746960639954],\n [0.238978996872902, 0.779744982719421],\n [0.198220998048782, 0.831938028335571],\n [0.107550002634525, 0.540755033493042],\n [0.183610007166862, 0.740257024765015],\n [0.134409993886948, 0.333683013916016],\n [0.385764002799988, 0.883153975009918],\n [0.490967005491257, 0.579378008842468],\n [0.382384985685349, 0.508572995662689],\n [0.174399003386497, 0.397670984268188],\n [0.318785011768341, 0.39623498916626],\n [0.343364000320435, 0.400596976280212],\n [0.396100014448166, 0.710216999053955],\n [0.187885001301765, 0.588537991046906],\n [0.430987000465393, 0.944064974784851],\n [0.318993002176285, 0.898285031318665],\n [0.266247987747192, 0.869701027870178],\n [0.500023007392883, 0.190576016902924],\n [0.499976992607117, 0.954452991485596],\n [0.366169989109039, 0.398822009563446],\n [0.393207013607025, 0.39553701877594],\n [0.410373002290726, 0.391080021858215],\n [0.194993004202843, 0.342101991176605],\n [0.388664990663528, 0.362284004688263],\n [0.365961998701096, 0.355970978736877],\n [0.343364000320435, 0.355356991291046],\n [0.318785011768341, 0.35834002494812],\n [0.301414996385574, 0.363156020641327],\n [0.058132998645306, 0.319076001644135],\n [0.301414996385574, 0.387449026107788],\n [0.499987989664078, 0.618434011936188],\n [0.415838003158569, 0.624195992946625],\n [0.445681989192963, 0.566076993942261],\n [0.465844005346298, 0.620640993118286],\n [0.49992299079895, 0.351523995399475],\n [0.288718998432159, 0.819945991039276],\n [0.335278987884521, 0.852819979190826],\n [0.440512001514435, 0.902418971061707],\n [0.128294005990028, 0.791940987110138],\n [0.408771991729736, 0.373893976211548],\n [0.455606997013092, 0.451801002025604],\n [0.499877005815506, 0.908990025520325],\n [0.375436991453171, 0.924192011356354],\n [0.11421000212431, 0.615022003650665],\n [0.448662012815475, 0.695277988910675],\n [0.4480200111866, 0.704632043838501],\n [0.447111994028091, 0.715808033943176],\n [0.444831997156143, 0.730794012546539],\n [0.430011987686157, 0.766808986663818],\n [0.406787008047104, 0.685672998428345],\n [0.400738000869751, 0.681069016456604],\n [0.392399996519089, 0.677703022956848],\n [0.367855995893478, 0.663918972015381],\n [0.247923001646996, 0.601333022117615],\n [0.452769994735718, 0.420849978923798],\n [0.43639200925827, 0.359887003898621],\n [0.416164010763168, 0.368713974952698],\n [0.413385987281799, 0.692366003990173],\n [0.228018000721931, 0.683571994304657],\n [0.468268007040024, 0.352671027183533],\n [0.411361992359161, 0.804327011108398],\n [0.499989002943039, 0.469825029373169],\n [0.479153990745544, 0.442654013633728],\n [0.499974012374878, 0.439637005329132],\n [0.432112008333206, 0.493588984012604],\n [0.499886006116867, 0.866917014122009],\n [0.49991300702095, 0.821729004383087],\n [0.456548988819122, 0.819200992584229],\n [0.344549000263214, 0.745438992977142],\n [0.37890899181366, 0.574010014533997],\n [0.374292999505997, 0.780184984207153],\n [0.319687992334366, 0.570737957954407],\n [0.357154995203018, 0.604269981384277],\n [0.295284003019333, 0.621580958366394],\n [0.447750002145767, 0.862477004528046],\n [0.410986006259918, 0.508723020553589],\n [0.31395098567009, 0.775308012962341],\n [0.354128003120422, 0.812552988529205],\n [0.324548006057739, 0.703992962837219],\n [0.189096003770828, 0.646299958229065],\n [0.279776990413666, 0.71465802192688],\n [0.1338230073452, 0.682700991630554],\n [0.336768001317978, 0.644733011722565],\n [0.429883986711502, 0.466521978378296],\n [0.455527991056442, 0.548622965812683],\n [0.437114000320435, 0.558896005153656],\n [0.467287987470627, 0.529924988746643],\n [0.414712011814117, 0.335219979286194],\n [0.37704598903656, 0.322777986526489],\n [0.344107985496521, 0.320150971412659],\n [0.312875986099243, 0.32233202457428],\n [0.283526003360748, 0.333190023899078],\n [0.241245999932289, 0.382785975933075],\n [0.102986000478268, 0.468762993812561],\n [0.267612010240555, 0.424560010433197],\n [0.297879010438919, 0.433175981044769],\n [0.333433985710144, 0.433878004550934],\n [0.366427004337311, 0.426115989685059],\n [0.396012008190155, 0.416696012020111],\n [0.420121014118195, 0.41022801399231],\n [0.007561000064015, 0.480777025222778],\n [0.432949006557465, 0.569517970085144],\n [0.458638995885849, 0.479089021682739],\n [0.473466008901596, 0.545744001865387],\n [0.476087987422943, 0.563830018043518],\n [0.468472003936768, 0.555056989192963],\n [0.433990985155106, 0.582361996173859],\n [0.483518004417419, 0.562983989715576],\n [0.482482999563217, 0.57784903049469],\n [0.42645001411438, 0.389798998832703],\n [0.438998997211456, 0.39649498462677],\n [0.450067013502121, 0.400434017181396],\n [0.289712011814117, 0.368252992630005],\n [0.276670008897781, 0.363372981548309],\n [0.517862021923065, 0.471948027610779],\n [0.710287988185883, 0.380764007568359],\n [0.526226997375488, 0.573909997940063],\n [0.895093023777008, 0.254140973091125],\n [0.634069979190826, 0.409575998783112],\n [0.661242008209229, 0.41302502155304],\n [0.688880026340485, 0.409460008144379],\n [0.725341975688934, 0.389131009578705],\n [0.606630027294159, 0.40370500087738],\n [0.654766023159027, 0.344011008739471],\n [0.629905998706818, 0.346076011657715],\n [0.680678009986877, 0.347265005111694],\n [0.702096998691559, 0.353591024875641],\n [0.75221198797226, 0.410804986953735],\n [0.602918028831482, 0.842862963676453],\n [0.719901978969574, 0.375599980354309],\n [0.893692970275879, 0.399959981441498],\n [0.790081977844238, 0.391354024410248],\n [0.643998026847839, 0.534487962722778],\n [0.528249025344849, 0.65040397644043],\n [0.525849997997284, 0.680191040039062],\n [0.560214996337891, 0.657229006290436],\n [0.585384011268616, 0.66654098033905],\n [0.549625992774963, 0.680860996246338],\n [0.57122802734375, 0.682691991329193],\n [0.624852001667023, 0.72809898853302],\n [0.513050019741058, 0.547281980514526],\n [0.51509702205658, 0.527251958847046],\n [0.742246985435486, 0.314507007598877],\n [0.598631024360657, 0.454979002475739],\n [0.570338010787964, 0.548575043678284],\n [0.578631997108459, 0.533622980117798],\n [0.723087012767792, 0.532054007053375],\n [0.516445994377136, 0.499638974666595],\n [0.662801027297974, 0.282917976379395],\n [0.70362401008606, 0.293271005153656],\n [0.830704987049103, 0.193813979625702],\n [0.552385985851288, 0.302568018436432],\n [0.607609987258911, 0.353887975215912],\n [0.645429015159607, 0.696707010269165],\n [0.932694971561432, 0.730105042457581],\n [0.557260990142822, 0.572826027870178],\n [0.542901992797852, 0.584792017936707],\n [0.6180260181427, 0.694710969924927],\n [0.607590973377228, 0.694203019142151],\n [0.722943007946014, 0.271963000297546],\n [0.577413976192474, 0.563166975975037],\n [0.614082992076874, 0.281386971473694],\n [0.616907000541687, 0.255886018276215],\n [0.668509006500244, 0.119913995265961],\n [0.770092010498047, 0.232020974159241],\n [0.635536015033722, 0.189248979091644],\n [0.77039098739624, 0.299556016921997],\n [0.826722025871277, 0.278755009174347],\n [0.527121007442474, 0.666198015213013],\n [0.553171992301941, 0.668527007102966],\n [0.577238023281097, 0.673889994621277],\n [0.554691970348358, 0.580065965652466],\n [0.611896991729736, 0.693961024284363],\n [0.59696102142334, 0.706539988517761],\n [0.596370995044708, 0.693953037261963],\n [0.539958000183105, 0.557139039039612],\n [0.568841993808746, 0.692366003990173],\n [0.547818005084991, 0.692366003990173],\n [0.52461302280426, 0.692366003990173],\n [0.534089982509613, 0.779141008853912],\n [0.527670979499817, 0.736225962638855],\n [0.526912987232208, 0.717857003211975],\n [0.526877999305725, 0.704625964164734],\n [0.526966989040375, 0.695277988910675],\n [0.572058022022247, 0.695277988910675],\n [0.573521018028259, 0.703539967536926],\n [0.57683801651001, 0.711845993995667],\n [0.581691026687622, 0.720062971115112],\n [0.609944999217987, 0.639909982681274],\n [0.986046016216278, 0.560034036636353],\n [0.5867999792099, 0.69539999961853],\n [0.590372025966644, 0.701822996139526],\n [0.531915009021759, 0.601536989212036],\n [0.577268004417419, 0.585934996604919],\n [0.536915004253387, 0.593786001205444],\n [0.627542972564697, 0.473352015018463],\n [0.665585994720459, 0.495950996875763],\n [0.588353991508484, 0.546862006187439],\n [0.757824003696442, 0.14767599105835],\n [0.709249973297119, 0.201507985591888],\n [0.672684013843536, 0.256581008434296],\n [0.600408971309662, 0.74900496006012],\n [0.55826598405838, 0.261672019958496],\n [0.570303976535797, 0.187870979309082],\n [0.588165998458862, 0.109044015407562],\n [0.711045026779175, 0.398952007293701],\n [0.781069993972778, 0.435405015945435],\n [0.587247014045715, 0.398931980133057],\n [0.742869973182678, 0.355445981025696],\n [0.572156012058258, 0.437651991844177],\n [0.55186802148819, 0.536570012569427],\n [0.821442008018494, 0.457556009292603],\n [0.752701997756958, 0.457181990146637],\n [0.71375697851181, 0.467626988887787],\n [0.66711300611496, 0.460672974586487],\n [0.631101012229919, 0.447153985500336],\n [0.6008620262146, 0.432473003864288],\n [0.523481011390686, 0.405627012252808],\n [0.810747981071472, 0.523926019668579],\n [0.771045982837677, 0.348959028720856],\n [0.509127020835876, 0.562718033790588],\n [0.595292985439301, 0.485023975372314],\n [0.980530977249146, 0.401564002037048],\n [0.573499977588654, 0.420000016689301],\n [0.602994978427887, 0.548687994480133],\n [0.733529984951019, 0.376977026462555],\n [0.560611009597778, 0.519016981124878],\n [0.967685997486115, 0.644356966018677],\n [0.580985009670258, 0.387160003185272],\n [0.537728011608124, 0.505385041236877],\n [0.760966002941132, 0.779752969741821],\n [0.801778972148895, 0.831938028335571],\n [0.892440974712372, 0.54076099395752],\n [0.816350996494293, 0.740260004997253],\n [0.865594983100891, 0.333687007427216],\n [0.614073991775513, 0.883246004581451],\n [0.508952975273132, 0.579437971115112],\n [0.617941975593567, 0.508316040039062],\n [0.825608015060425, 0.397674977779388],\n [0.681214988231659, 0.39623498916626],\n [0.656635999679565, 0.400596976280212],\n [0.603900015354156, 0.710216999053955],\n [0.81208598613739, 0.588539004325867],\n [0.56801301240921, 0.944564998149872],\n [0.681007981300354, 0.898285031318665],\n [0.733752012252808, 0.869701027870178],\n [0.633830010890961, 0.398822009563446],\n [0.606792986392975, 0.39553701877594],\n [0.589659988880157, 0.391062021255493],\n [0.805015981197357, 0.342108011245728],\n [0.611334979534149, 0.362284004688263],\n [0.634037971496582, 0.355970978736877],\n [0.656635999679565, 0.355356991291046],\n [0.681214988231659, 0.35834002494812],\n [0.698584973812103, 0.363156020641327],\n [0.941866993904114, 0.319076001644135],\n [0.698584973812103, 0.387449026107788],\n [0.584177017211914, 0.624107003211975],\n [0.554318010807037, 0.566076993942261],\n [0.534153997898102, 0.62064003944397],\n [0.711217999458313, 0.819975018501282],\n [0.664629995822906, 0.852871000766754],\n [0.559099972248077, 0.902631998062134],\n [0.871706008911133, 0.791940987110138],\n [0.591234028339386, 0.373893976211548],\n [0.544341027736664, 0.451583981513977],\n [0.624562978744507, 0.924192011356354],\n [0.88577002286911, 0.615028977394104],\n [0.551338016986847, 0.695277988910675],\n [0.551980018615723, 0.704632043838501],\n [0.552887976169586, 0.715808033943176],\n [0.555167973041534, 0.730794012546539],\n [0.569944024085999, 0.767035007476807],\n [0.593203008174896, 0.685675978660583],\n [0.599261999130249, 0.681069016456604],\n [0.607599973678589, 0.677703022956848],\n [0.631937980651855, 0.663500010967255],\n [0.752032995223999, 0.601315021514893],\n [0.547226011753082, 0.420395016670227],\n [0.563543975353241, 0.359827995300293],\n [0.583841025829315, 0.368713974952698],\n [0.586614012718201, 0.692366003990173],\n [0.771915018558502, 0.683578014373779],\n [0.531597018241882, 0.352482974529266],\n [0.588370978832245, 0.804440975189209],\n [0.52079701423645, 0.442565023899078],\n [0.567984998226166, 0.493479013442993],\n [0.543282985687256, 0.819254994392395],\n [0.655317008495331, 0.745514988899231],\n [0.621008992195129, 0.574018001556396],\n [0.625559985637665, 0.78031200170517],\n [0.680198013782501, 0.570719003677368],\n [0.64276397228241, 0.604337990283966],\n [0.704662978649139, 0.621529996395111],\n [0.552012026309967, 0.862591981887817],\n [0.589071989059448, 0.508637011051178],\n [0.685944974422455, 0.775357007980347],\n [0.645735025405884, 0.812640011310577],\n [0.675342977046967, 0.703978002071381],\n [0.810858011245728, 0.646304965019226],\n [0.72012197971344, 0.714666962623596],\n [0.866151988506317, 0.682704985141754],\n [0.663187026977539, 0.644596993923187],\n [0.570082008838654, 0.466325998306274],\n [0.544561982154846, 0.548375964164734],\n [0.562758982181549, 0.558784961700439],\n [0.531987011432648, 0.530140042304993],\n [0.585271000862122, 0.335177004337311],\n [0.622952997684479, 0.32277899980545],\n [0.655896008014679, 0.320163011550903],\n [0.687132000923157, 0.322345972061157],\n [0.716481983661652, 0.333200991153717],\n [0.758756995201111, 0.382786989212036],\n [0.897013008594513, 0.468769013881683],\n [0.732392013072968, 0.424547016620636],\n [0.70211398601532, 0.433162987232208],\n [0.66652500629425, 0.433866024017334],\n [0.633504986763, 0.426087975502014],\n [0.603875994682312, 0.416586995124817],\n [0.579657971858978, 0.409945011138916],\n [0.992439985275269, 0.480777025222778],\n [0.567192018032074, 0.569419980049133],\n [0.54136598110199, 0.478899002075195],\n [0.526564002037048, 0.546118021011353],\n [0.523913025856018, 0.563830018043518],\n [0.531529009342194, 0.555056989192963],\n [0.566035985946655, 0.582329034805298],\n [0.51631098985672, 0.563053965568542],\n [0.5174720287323, 0.577877044677734],\n [0.573594987392426, 0.389806985855103],\n [0.560697972774506, 0.395331978797913],\n [0.549755990505219, 0.399751007556915],\n [0.710287988185883, 0.368252992630005],\n [0.723330020904541, 0.363372981548309],\n];\n", "export default [\n 127, 34, 139, 11, 0, 37, 232, 231, 120, 72, 37, 39, 128, 121, 47, 232, 121,\n 128, 104, 69, 67, 175, 171, 148, 157, 154, 155, 118, 50, 101, 73, 39, 40, 9,\n 151, 108, 48, 115, 131, 194, 204, 211, 74, 40, 185, 80, 42, 183, 40, 92,\n 186, 230, 229, 118, 202, 212, 214, 83, 18, 17, 76, 61, 146, 160, 29, 30, 56,\n 157, 173, 106, 204, 194, 135, 214, 192, 203, 165, 98, 21, 71, 68, 51, 45, 4,\n 144, 24, 23, 77, 146, 91, 205, 50, 187, 201, 200, 18, 91, 106, 182, 90, 91,\n 181, 85, 84, 17, 206, 203, 36, 148, 171, 140, 92, 40, 39, 193, 189, 244,\n 159, 158, 28, 247, 246, 161, 236, 3, 196, 54, 68, 104, 193, 168, 8, 117,\n 228, 31, 189, 193, 55, 98, 97, 99, 126, 47, 100, 166, 79, 218, 155, 154, 26,\n 209, 49, 131, 135, 136, 150, 47, 126, 217, 223, 52, 53, 45, 51, 134, 211,\n 170, 140, 67, 69, 108, 43, 106, 91, 230, 119, 120, 226, 130, 247, 63, 53,\n 52, 238, 20, 242, 46, 70, 156, 78, 62, 96, 46, 53, 63, 143, 34, 227, 173,\n 155, 133, 123, 117, 111, 44, 125, 19, 236, 134, 51, 216, 206, 205, 154, 153,\n 22, 39, 37, 167, 200, 201, 208, 36, 142, 100, 57, 212, 202, 20, 60, 99, 28,\n 158, 157, 35, 226, 113, 160, 159, 27, 204, 202, 210, 113, 225, 46, 43, 202,\n 204, 62, 76, 77, 137, 123, 116, 41, 38, 72, 203, 129, 142, 64, 98, 240, 49,\n 102, 64, 41, 73, 74, 212, 216, 207, 42, 74, 184, 169, 170, 211, 170, 149,\n 176, 105, 66, 69, 122, 6, 168, 123, 147, 187, 96, 77, 90, 65, 55, 107, 89,\n 90, 180, 101, 100, 120, 63, 105, 104, 93, 137, 227, 15, 86, 85, 129, 102,\n 49, 14, 87, 86, 55, 8, 9, 100, 47, 121, 145, 23, 22, 88, 89, 179, 6, 122,\n 196, 88, 95, 96, 138, 172, 136, 215, 58, 172, 115, 48, 219, 42, 80, 81, 195,\n 3, 51, 43, 146, 61, 171, 175, 199, 81, 82, 38, 53, 46, 225, 144, 163, 110,\n 246, 33, 7, 52, 65, 66, 229, 228, 117, 34, 127, 234, 107, 108, 69, 109, 108,\n 151, 48, 64, 235, 62, 78, 191, 129, 209, 126, 111, 35, 143, 163, 161, 246,\n 117, 123, 50, 222, 65, 52, 19, 125, 141, 221, 55, 65, 3, 195, 197, 25, 7,\n 33, 220, 237, 44, 70, 71, 139, 122, 193, 245, 247, 130, 33, 71, 21, 162,\n 153, 158, 159, 170, 169, 150, 188, 174, 196, 216, 186, 92, 144, 160, 161, 2,\n 97, 167, 141, 125, 241, 164, 167, 37, 72, 38, 12, 145, 159, 160, 38, 82, 13,\n 63, 68, 71, 226, 35, 111, 158, 153, 154, 101, 50, 205, 206, 92, 165, 209,\n 198, 217, 165, 167, 97, 220, 115, 218, 133, 112, 243, 239, 238, 241, 214,\n 135, 169, 190, 173, 133, 171, 208, 32, 125, 44, 237, 86, 87, 178, 85, 86,\n 179, 84, 85, 180, 83, 84, 181, 201, 83, 182, 137, 93, 132, 76, 62, 183, 61,\n 76, 184, 57, 61, 185, 212, 57, 186, 214, 207, 187, 34, 143, 156, 79, 239,\n 237, 123, 137, 177, 44, 1, 4, 201, 194, 32, 64, 102, 129, 213, 215, 138, 59,\n 166, 219, 242, 99, 97, 2, 94, 141, 75, 59, 235, 24, 110, 228, 25, 130, 226,\n 23, 24, 229, 22, 23, 230, 26, 22, 231, 112, 26, 232, 189, 190, 243, 221, 56,\n 190, 28, 56, 221, 27, 28, 222, 29, 27, 223, 30, 29, 224, 247, 30, 225, 238,\n 79, 20, 166, 59, 75, 60, 75, 240, 147, 177, 215, 20, 79, 166, 187, 147, 213,\n 112, 233, 244, 233, 128, 245, 128, 114, 188, 114, 217, 174, 131, 115, 220,\n 217, 198, 236, 198, 131, 134, 177, 132, 58, 143, 35, 124, 110, 163, 7, 228,\n 110, 25, 356, 389, 368, 11, 302, 267, 452, 350, 349, 302, 303, 269, 357,\n 343, 277, 452, 453, 357, 333, 332, 297, 175, 152, 377, 384, 398, 382, 347,\n 348, 330, 303, 304, 270, 9, 336, 337, 278, 279, 360, 418, 262, 431, 304,\n 408, 409, 310, 415, 407, 270, 409, 410, 450, 348, 347, 422, 430, 434, 313,\n 314, 17, 306, 307, 375, 387, 388, 260, 286, 414, 398, 335, 406, 418, 364,\n 367, 416, 423, 358, 327, 251, 284, 298, 281, 5, 4, 373, 374, 253, 307, 320,\n 321, 425, 427, 411, 421, 313, 18, 321, 405, 406, 320, 404, 405, 315, 16, 17,\n 426, 425, 266, 377, 400, 369, 322, 391, 269, 417, 465, 464, 386, 257, 258,\n 466, 260, 388, 456, 399, 419, 284, 332, 333, 417, 285, 8, 346, 340, 261,\n 413, 441, 285, 327, 460, 328, 355, 371, 329, 392, 439, 438, 382, 341, 256,\n 429, 420, 360, 364, 394, 379, 277, 343, 437, 443, 444, 283, 275, 440, 363,\n 431, 262, 369, 297, 338, 337, 273, 375, 321, 450, 451, 349, 446, 342, 467,\n 293, 334, 282, 458, 461, 462, 276, 353, 383, 308, 324, 325, 276, 300, 293,\n 372, 345, 447, 382, 398, 362, 352, 345, 340, 274, 1, 19, 456, 248, 281, 436,\n 427, 425, 381, 256, 252, 269, 391, 393, 200, 199, 428, 266, 330, 329, 287,\n 273, 422, 250, 462, 328, 258, 286, 384, 265, 353, 342, 387, 259, 257, 424,\n 431, 430, 342, 353, 276, 273, 335, 424, 292, 325, 307, 366, 447, 345, 271,\n 303, 302, 423, 266, 371, 294, 455, 460, 279, 278, 294, 271, 272, 304, 432,\n 434, 427, 272, 407, 408, 394, 430, 431, 395, 369, 400, 334, 333, 299, 351,\n 417, 168, 352, 280, 411, 325, 319, 320, 295, 296, 336, 319, 403, 404, 330,\n 348, 349, 293, 298, 333, 323, 454, 447, 15, 16, 315, 358, 429, 279, 14, 15,\n 316, 285, 336, 9, 329, 349, 350, 374, 380, 252, 318, 402, 403, 6, 197, 419,\n 318, 319, 325, 367, 364, 365, 435, 367, 397, 344, 438, 439, 272, 271, 311,\n 195, 5, 281, 273, 287, 291, 396, 428, 199, 311, 271, 268, 283, 444, 445,\n 373, 254, 339, 263, 466, 249, 282, 334, 296, 449, 347, 346, 264, 447, 454,\n 336, 296, 299, 338, 10, 151, 278, 439, 455, 292, 407, 415, 358, 371, 355,\n 340, 345, 372, 390, 249, 466, 346, 347, 280, 442, 443, 282, 19, 94, 370,\n 441, 442, 295, 248, 419, 197, 263, 255, 359, 440, 275, 274, 300, 383, 368,\n 351, 412, 465, 263, 467, 466, 301, 368, 389, 380, 374, 386, 395, 378, 379,\n 412, 351, 419, 436, 426, 322, 373, 390, 388, 2, 164, 393, 370, 462, 461,\n 164, 0, 267, 302, 11, 12, 374, 373, 387, 268, 12, 13, 293, 300, 301, 446,\n 261, 340, 385, 384, 381, 330, 266, 425, 426, 423, 391, 429, 355, 437, 391,\n 327, 326, 440, 457, 438, 341, 382, 362, 459, 457, 461, 434, 430, 394, 414,\n 463, 362, 396, 369, 262, 354, 461, 457, 316, 403, 402, 315, 404, 403, 314,\n 405, 404, 313, 406, 405, 421, 418, 406, 366, 401, 361, 306, 408, 407, 291,\n 409, 408, 287, 410, 409, 432, 436, 410, 434, 416, 411, 264, 368, 383, 309,\n 438, 457, 352, 376, 401, 274, 275, 4, 421, 428, 262, 294, 327, 358, 433,\n 416, 367, 289, 455, 439, 462, 370, 326, 2, 326, 370, 305, 460, 455, 254,\n 449, 448, 255, 261, 446, 253, 450, 449, 252, 451, 450, 256, 452, 451, 341,\n 453, 452, 413, 464, 463, 441, 413, 414, 258, 442, 441, 257, 443, 442, 259,\n 444, 443, 260, 445, 444, 467, 342, 445, 459, 458, 250, 289, 392, 290, 290,\n 328, 460, 376, 433, 435, 250, 290, 392, 411, 416, 433, 341, 463, 464, 453,\n 464, 465, 357, 465, 412, 343, 412, 399, 360, 363, 440, 437, 399, 456, 420,\n 456, 363, 401, 435, 288, 372, 383, 353, 339, 255, 249, 448, 261, 255, 133,\n 243, 190, 133, 155, 112, 33, 246, 247, 33, 130, 25, 398, 384, 286, 362, 398,\n 414, 362, 463, 341, 263, 359, 467, 263, 249, 255, 466, 467, 260, 75, 60,\n 166, 238, 239, 79, 162, 127, 139, 72, 11, 37, 121, 232, 120, 73, 72, 39,\n 114, 128, 47, 233, 232, 128, 103, 104, 67, 152, 175, 148, 173, 157, 155,\n 119, 118, 101, 74, 73, 40, 107, 9, 108, 49, 48, 131, 32, 194, 211, 184, 74,\n 185, 191, 80, 183, 185, 40, 186, 119, 230, 118, 210, 202, 214, 84, 83, 17,\n 77, 76, 146, 161, 160, 30, 190, 56, 173, 182, 106, 194, 138, 135, 192, 129,\n 203, 98, 54, 21, 68, 5, 51, 4, 145, 144, 23, 90, 77, 91, 207, 205, 187, 83,\n 201, 18, 181, 91, 182, 180, 90, 181, 16, 85, 17, 205, 206, 36, 176, 148,\n 140, 165, 92, 39, 245, 193, 244, 27, 159, 28, 30, 247, 161, 174, 236, 196,\n 103, 54, 104, 55, 193, 8, 111, 117, 31, 221, 189, 55, 240, 98, 99, 142, 126,\n 100, 219, 166, 218, 112, 155, 26, 198, 209, 131, 169, 135, 150, 114, 47,\n 217, 224, 223, 53, 220, 45, 134, 32, 211, 140, 109, 67, 108, 146, 43, 91,\n 231, 230, 120, 113, 226, 247, 105, 63, 52, 241, 238, 242, 124, 46, 156, 95,\n 78, 96, 70, 46, 63, 116, 143, 227, 116, 123, 111, 1, 44, 19, 3, 236, 51,\n 207, 216, 205, 26, 154, 22, 165, 39, 167, 199, 200, 208, 101, 36, 100, 43,\n 57, 202, 242, 20, 99, 56, 28, 157, 124, 35, 113, 29, 160, 27, 211, 204, 210,\n 124, 113, 46, 106, 43, 204, 96, 62, 77, 227, 137, 116, 73, 41, 72, 36, 203,\n 142, 235, 64, 240, 48, 49, 64, 42, 41, 74, 214, 212, 207, 183, 42, 184, 210,\n 169, 211, 140, 170, 176, 104, 105, 69, 193, 122, 168, 50, 123, 187, 89, 96,\n 90, 66, 65, 107, 179, 89, 180, 119, 101, 120, 68, 63, 104, 234, 93, 227, 16,\n 15, 85, 209, 129, 49, 15, 14, 86, 107, 55, 9, 120, 100, 121, 153, 145, 22,\n 178, 88, 179, 197, 6, 196, 89, 88, 96, 135, 138, 136, 138, 215, 172, 218,\n 115, 219, 41, 42, 81, 5, 195, 51, 57, 43, 61, 208, 171, 199, 41, 81, 38,\n 224, 53, 225, 24, 144, 110, 105, 52, 66, 118, 229, 117, 227, 34, 234, 66,\n 107, 69, 10, 109, 151, 219, 48, 235, 183, 62, 191, 142, 129, 126, 116, 111,\n 143, 7, 163, 246, 118, 117, 50, 223, 222, 52, 94, 19, 141, 222, 221, 65,\n 196, 3, 197, 45, 220, 44, 156, 70, 139, 188, 122, 245, 139, 71, 162, 145,\n 153, 159, 149, 170, 150, 122, 188, 196, 206, 216, 92, 163, 144, 161, 164, 2,\n 167, 242, 141, 241, 0, 164, 37, 11, 72, 12, 144, 145, 160, 12, 38, 13, 70,\n 63, 71, 31, 226, 111, 157, 158, 154, 36, 101, 205, 203, 206, 165, 126, 209,\n 217, 98, 165, 97, 237, 220, 218, 237, 239, 241, 210, 214, 169, 140, 171, 32,\n 241, 125, 237, 179, 86, 178, 180, 85, 179, 181, 84, 180, 182, 83, 181, 194,\n 201, 182, 177, 137, 132, 184, 76, 183, 185, 61, 184, 186, 57, 185, 216, 212,\n 186, 192, 214, 187, 139, 34, 156, 218, 79, 237, 147, 123, 177, 45, 44, 4,\n 208, 201, 32, 98, 64, 129, 192, 213, 138, 235, 59, 219, 141, 242, 97, 97, 2,\n 141, 240, 75, 235, 229, 24, 228, 31, 25, 226, 230, 23, 229, 231, 22, 230,\n 232, 26, 231, 233, 112, 232, 244, 189, 243, 189, 221, 190, 222, 28, 221,\n 223, 27, 222, 224, 29, 223, 225, 30, 224, 113, 247, 225, 99, 60, 240, 213,\n 147, 215, 60, 20, 166, 192, 187, 213, 243, 112, 244, 244, 233, 245, 245,\n 128, 188, 188, 114, 174, 134, 131, 220, 174, 217, 236, 236, 198, 134, 215,\n 177, 58, 156, 143, 124, 25, 110, 7, 31, 228, 25, 264, 356, 368, 0, 11, 267,\n 451, 452, 349, 267, 302, 269, 350, 357, 277, 350, 452, 357, 299, 333, 297,\n 396, 175, 377, 381, 384, 382, 280, 347, 330, 269, 303, 270, 151, 9, 337,\n 344, 278, 360, 424, 418, 431, 270, 304, 409, 272, 310, 407, 322, 270, 410,\n 449, 450, 347, 432, 422, 434, 18, 313, 17, 291, 306, 375, 259, 387, 260,\n 424, 335, 418, 434, 364, 416, 391, 423, 327, 301, 251, 298, 275, 281, 4,\n 254, 373, 253, 375, 307, 321, 280, 425, 411, 200, 421, 18, 335, 321, 406,\n 321, 320, 405, 314, 315, 17, 423, 426, 266, 396, 377, 369, 270, 322, 269,\n 413, 417, 464, 385, 386, 258, 248, 456, 419, 298, 284, 333, 168, 417, 8,\n 448, 346, 261, 417, 413, 285, 326, 327, 328, 277, 355, 329, 309, 392, 438,\n 381, 382, 256, 279, 429, 360, 365, 364, 379, 355, 277, 437, 282, 443, 283,\n 281, 275, 363, 395, 431, 369, 299, 297, 337, 335, 273, 321, 348, 450, 349,\n 359, 446, 467, 283, 293, 282, 250, 458, 462, 300, 276, 383, 292, 308, 325,\n 283, 276, 293, 264, 372, 447, 346, 352, 340, 354, 274, 19, 363, 456, 281,\n 426, 436, 425, 380, 381, 252, 267, 269, 393, 421, 200, 428, 371, 266, 329,\n 432, 287, 422, 290, 250, 328, 385, 258, 384, 446, 265, 342, 386, 387, 257,\n 422, 424, 430, 445, 342, 276, 422, 273, 424, 306, 292, 307, 352, 366, 345,\n 268, 271, 302, 358, 423, 371, 327, 294, 460, 331, 279, 294, 303, 271, 304,\n 436, 432, 427, 304, 272, 408, 395, 394, 431, 378, 395, 400, 296, 334, 299,\n 6, 351, 168, 376, 352, 411, 307, 325, 320, 285, 295, 336, 320, 319, 404,\n 329, 330, 349, 334, 293, 333, 366, 323, 447, 316, 15, 315, 331, 358, 279,\n 317, 14, 316, 8, 285, 9, 277, 329, 350, 253, 374, 252, 319, 318, 403, 351,\n 6, 419, 324, 318, 325, 397, 367, 365, 288, 435, 397, 278, 344, 439, 310,\n 272, 311, 248, 195, 281, 375, 273, 291, 175, 396, 199, 312, 311, 268, 276,\n 283, 445, 390, 373, 339, 295, 282, 296, 448, 449, 346, 356, 264, 454, 337,\n 336, 299, 337, 338, 151, 294, 278, 455, 308, 292, 415, 429, 358, 355, 265,\n 340, 372, 388, 390, 466, 352, 346, 280, 295, 442, 282, 354, 19, 370, 285,\n 441, 295, 195, 248, 197, 457, 440, 274, 301, 300, 368, 417, 351, 465, 251,\n 301, 389, 385, 380, 386, 394, 395, 379, 399, 412, 419, 410, 436, 322, 387,\n 373, 388, 326, 2, 393, 354, 370, 461, 393, 164, 267, 268, 302, 12, 386, 374,\n 387, 312, 268, 13, 298, 293, 301, 265, 446, 340, 380, 385, 381, 280, 330,\n 425, 322, 426, 391, 420, 429, 437, 393, 391, 326, 344, 440, 438, 458, 459,\n 461, 364, 434, 394, 428, 396, 262, 274, 354, 457, 317, 316, 402, 316, 315,\n 403, 315, 314, 404, 314, 313, 405, 313, 421, 406, 323, 366, 361, 292, 306,\n 407, 306, 291, 408, 291, 287, 409, 287, 432, 410, 427, 434, 411, 372, 264,\n 383, 459, 309, 457, 366, 352, 401, 1, 274, 4, 418, 421, 262, 331, 294, 358,\n 435, 433, 367, 392, 289, 439, 328, 462, 326, 94, 2, 370, 289, 305, 455, 339,\n 254, 448, 359, 255, 446, 254, 253, 449, 253, 252, 450, 252, 256, 451, 256,\n 341, 452, 414, 413, 463, 286, 441, 414, 286, 258, 441, 258, 257, 442, 257,\n 259, 443, 259, 260, 444, 260, 467, 445, 309, 459, 250, 305, 289, 290, 305,\n 290, 460, 401, 376, 435, 309, 250, 392, 376, 411, 433, 453, 341, 464, 357,\n 453, 465, 343, 357, 412, 437, 343, 399, 344, 360, 440, 420, 437, 456, 360,\n 420, 363, 361, 401, 288, 265, 372, 353, 390, 339, 249, 339, 448, 255];\n", "const tf = require('@tensorflow/tfjs');\nconst blazeface = require('./blazeface');\nconst keypoints = require('./keypoints');\nconst pipe = require('./pipeline');\nconst uv_coords = require('./uvcoords');\nconst triangulation = require('./triangulation').default;\n\nclass MediaPipeFaceMesh {\n constructor(blazeFace, blazeMeshModel, irisModel, config) {\n this.pipeline = new pipe.Pipeline(blazeFace, blazeMeshModel, irisModel, config);\n if (config) this.config = config;\n }\n\n async estimateFaces(input, config) {\n if (config) this.config = config;\n const predictions = await this.pipeline.predict(input, config);\n const results = [];\n for (const prediction of (predictions || [])) {\n // guard against disposed tensors on long running operations such as pause in middle of processing\n if (prediction.isDisposedInternal) continue;\n const confidence = prediction.confidence.arraySync();\n if (confidence >= this.config.detector.minConfidence) {\n const mesh = prediction.coords ? prediction.coords.arraySync() : null;\n const annotations = {};\n if (mesh && mesh.length > 0) {\n for (const key in keypoints.MESH_ANNOTATIONS) {\n if (this.config.iris.enabled || key.includes('Iris') === false) {\n annotations[key] = keypoints.MESH_ANNOTATIONS[key].map((index) => mesh[index]);\n }\n }\n }\n results.push({\n confidence: confidence || 0,\n box: prediction.box ? [prediction.box.startPoint[0], prediction.box.startPoint[1], prediction.box.endPoint[0] - prediction.box.startPoint[0], prediction.box.endPoint[1] - prediction.box.startPoint[1]] : 0,\n mesh,\n annotations,\n image: prediction.image ? tf.clone(prediction.image) : null,\n });\n }\n if (prediction.confidence) prediction.confidence.dispose();\n if (prediction.coords) prediction.coords.dispose();\n if (prediction.image) prediction.image.dispose();\n }\n return results;\n }\n}\n\nasync function load(config) {\n const models = await Promise.all([\n blazeface.load(config),\n tf.loadGraphModel(config.mesh.modelPath, { fromTFHub: config.mesh.modelPath.includes('tfhub.dev') }),\n tf.loadGraphModel(config.iris.modelPath, { fromTFHub: config.iris.modelPath.includes('tfhub.dev') }),\n ]);\n const faceMesh = new MediaPipeFaceMesh(models[0], models[1], models[2], config);\n return faceMesh;\n}\n\nexports.load = load;\nexports.MediaPipeFaceMesh = MediaPipeFaceMesh;\nexports.uv_coords = uv_coords;\nexports.triangulation = triangulation;\n", "const tf = require('@tensorflow/tfjs');\n\nconst models = {};\nlet last = { age: 0, gender: '' };\nlet frame = 0;\n\nasync function loadAge(config) {\n if (!models.age) models.age = await tf.loadGraphModel(config.face.age.modelPath);\n return models.age;\n}\n\nasync function loadGender(config) {\n if (!models.gender) models.gender = await tf.loadGraphModel(config.face.gender.modelPath);\n return models.gender;\n}\n\nasync function predict(image, config) {\n if (frame < config.face.age.skipFrames) {\n frame += 1;\n return last;\n }\n frame = 0;\n const resize = tf.image.resizeBilinear(image, [config.face.age.inputSize, config.face.age.inputSize], false);\n const enhance = tf.mul(resize, [255.0]);\n tf.dispose(resize);\n\n const promises = [];\n let ageT;\n let genderT;\n if (config.face.age.enabled) promises.push(ageT = models.age.predict(enhance));\n if (config.face.gender.enabled) promises.push(genderT = models.gender.predict(enhance));\n await Promise.all(promises);\n\n const obj = {};\n if (ageT) {\n const data = await ageT.data();\n obj.age = Math.trunc(10 * data[0]) / 10;\n tf.dispose(ageT);\n }\n if (genderT) {\n const data = await genderT.data();\n const confidence = Math.trunc(Math.abs(1.9 * 100 * (data[0] - 0.5))) / 100;\n if (confidence > config.face.gender.minConfidence) {\n obj.gender = data[0] <= 0.5 ? 'female' : 'male';\n obj.confidence = confidence;\n }\n tf.dispose(genderT);\n }\n\n tf.dispose(enhance);\n last = obj;\n return obj;\n}\n\nexports.predict = predict;\nexports.loadAge = loadAge;\nexports.loadGender = loadGender;\n", "const tf = require('@tensorflow/tfjs');\n\nconst annotations = ['angry', 'discust', 'fear', 'happy', 'sad', 'surpise', 'neutral'];\nconst models = {};\nlet last = [];\nlet frame = 0;\nconst multiplier = 1.5;\n\nasync function load(config) {\n if (!models.emotion) models.emotion = await tf.loadGraphModel(config.face.emotion.modelPath);\n return models.emotion;\n}\n\nasync function predict(image, config) {\n if (frame < config.face.emotion.skipFrames) {\n frame += 1;\n return last;\n }\n frame = 0;\n const resize = tf.image.resizeBilinear(image, [config.face.emotion.inputSize, config.face.emotion.inputSize], false);\n const [red, green, blue] = tf.split(resize, 3, 3);\n resize.dispose();\n // weighted rgb to grayscale: https://www.mathworks.com/help/matlab/ref/rgb2gray.html\n const redNorm = tf.mul(red, [0.2989]);\n const greenNorm = tf.mul(green, [0.5870]);\n const blueNorm = tf.mul(blue, [0.1140]);\n red.dispose();\n green.dispose();\n blue.dispose();\n const grayscale = tf.addN([redNorm, greenNorm, blueNorm]);\n redNorm.dispose();\n greenNorm.dispose();\n blueNorm.dispose();\n const obj = [];\n if (config.face.emotion.enabled) {\n const emotionT = await models.emotion.predict(grayscale);\n const data = await emotionT.data();\n for (let i = 0; i < data.length; i++) {\n if (multiplier * data[i] > config.face.emotion.minConfidence) obj.push({ score: Math.min(0.99, Math.trunc(100 * multiplier * data[i]) / 100), emotion: annotations[i] });\n }\n obj.sort((a, b) => b.score - a.score);\n tf.dispose(emotionT);\n }\n tf.dispose(grayscale);\n last = obj;\n return obj;\n}\n\nexports.predict = predict;\nexports.load = load;\n", "const tf = require('@tensorflow/tfjs');\n\nclass BaseModel {\n constructor(model, outputStride) {\n this.model = model;\n this.outputStride = outputStride;\n const inputShape = this.model.inputs[0].shape;\n tf.util.assert((inputShape[1] === -1) && (inputShape[2] === -1), () => `Input shape [${inputShape[1]}, ${inputShape[2]}] must both be equal to or -1`);\n }\n\n /**\n * Predicts intermediate Tensor representations.\n *\n * @param input The input RGB image of the base model.\n * A Tensor of shape: [`inputResolution`, `inputResolution`, 3].\n *\n * @return A dictionary of base model's intermediate predictions.\n * The returned dictionary should contains the following elements:\n * heatmapScores: A Tensor3D that represents the heatmapScores.\n * offsets: A Tensor3D that represents the offsets.\n * displacementFwd: A Tensor3D that represents the forward displacement.\n * displacementBwd: A Tensor3D that represents the backward displacement.\n */\n predict(input) {\n return tf.tidy(() => {\n const asFloat = this.preprocessInput(input.toFloat());\n const asBatch = asFloat.expandDims(0);\n const results = this.model.predict(asBatch);\n const results3d = results.map((y) => y.squeeze([0]));\n const namedResults = this.nameOutputResults(results3d);\n return {\n heatmapScores: namedResults.heatmap.sigmoid(),\n offsets: namedResults.offsets,\n displacementFwd: namedResults.displacementFwd,\n displacementBwd: namedResults.displacementBwd,\n };\n });\n }\n\n /**\n * Releases the CPU and GPU memory allocated by the model.\n */\n dispose() {\n this.model.dispose();\n }\n}\nexports.BaseModel = BaseModel;\n", "const tf = require('@tensorflow/tfjs');\nconst modelBase = require('./modelBase');\n\nclass MobileNet extends modelBase.BaseModel {\n // eslint-disable-next-line class-methods-use-this\n preprocessInput(input) {\n // Normalize the pixels [0, 255] to be between [-1, 1].\n return tf.tidy(() => tf.div(input, 127.5).sub(1.0));\n }\n\n // eslint-disable-next-line class-methods-use-this\n nameOutputResults(results) {\n const [offsets, heatmap, displacementFwd, displacementBwd] = results;\n return { offsets, heatmap, displacementFwd, displacementBwd };\n }\n}\nexports.MobileNet = MobileNet;\n", "// algorithm based on Coursera Lecture from Algorithms, Part 1: https://www.coursera.org/learn/algorithms-part1/lecture/ZjoSM/heapsort\nfunction half(k) {\n return Math.floor(k / 2);\n}\nclass MaxHeap {\n constructor(maxSize, getElementValue) {\n this.priorityQueue = new Array(maxSize);\n this.numberOfElements = -1;\n this.getElementValue = getElementValue;\n }\n\n enqueue(x) {\n this.priorityQueue[++this.numberOfElements] = x;\n this.swim(this.numberOfElements);\n }\n\n dequeue() {\n const max = this.priorityQueue[0];\n this.exchange(0, this.numberOfElements--);\n this.sink(0);\n this.priorityQueue[this.numberOfElements + 1] = null;\n return max;\n }\n\n empty() {\n return this.numberOfElements === -1;\n }\n\n size() {\n return this.numberOfElements + 1;\n }\n\n all() {\n return this.priorityQueue.slice(0, this.numberOfElements + 1);\n }\n\n max() {\n return this.priorityQueue[0];\n }\n\n swim(k) {\n while (k > 0 && this.less(half(k), k)) {\n this.exchange(k, half(k));\n k = half(k);\n }\n }\n\n sink(k) {\n while (2 * k <= this.numberOfElements) {\n let j = 2 * k;\n if (j < this.numberOfElements && this.less(j, j + 1)) j++;\n if (!this.less(k, j)) break;\n this.exchange(k, j);\n k = j;\n }\n }\n\n getValueAt(i) {\n return this.getElementValue(this.priorityQueue[i]);\n }\n\n less(i, j) {\n return this.getValueAt(i) < this.getValueAt(j);\n }\n\n exchange(i, j) {\n const t = this.priorityQueue[i];\n this.priorityQueue[i] = this.priorityQueue[j];\n this.priorityQueue[j] = t;\n }\n}\nexports.MaxHeap = MaxHeap;\n", "const heapSort = require('./heapSort');\n\nfunction scoreIsMaximumInLocalWindow(keypointId, score, heatmapY, heatmapX, localMaximumRadius, scores) {\n const [height, width] = scores.shape;\n let localMaximum = true;\n const yStart = Math.max(heatmapY - localMaximumRadius, 0);\n const yEnd = Math.min(heatmapY + localMaximumRadius + 1, height);\n for (let yCurrent = yStart; yCurrent < yEnd; ++yCurrent) {\n const xStart = Math.max(heatmapX - localMaximumRadius, 0);\n const xEnd = Math.min(heatmapX + localMaximumRadius + 1, width);\n for (let xCurrent = xStart; xCurrent < xEnd; ++xCurrent) {\n if (scores.get(yCurrent, xCurrent, keypointId) > score) {\n localMaximum = false;\n break;\n }\n }\n if (!localMaximum) {\n break;\n }\n }\n return localMaximum;\n}\n/**\n * Builds a priority queue with part candidate positions for a specific image in\n * the batch. For this we find all local maxima in the score maps with score\n * values above a threshold. We create a single priority queue across all parts.\n */\nfunction buildPartWithScoreQueue(scoreThreshold, localMaximumRadius, scores) {\n const [height, width, numKeypoints] = scores.shape;\n const queue = new heapSort.MaxHeap(height * width * numKeypoints, ({ score }) => score);\n for (let heatmapY = 0; heatmapY < height; ++heatmapY) {\n for (let heatmapX = 0; heatmapX < width; ++heatmapX) {\n for (let keypointId = 0; keypointId < numKeypoints; ++keypointId) {\n const score = scores.get(heatmapY, heatmapX, keypointId);\n // Only consider parts with score greater or equal to threshold as root candidates.\n if (score < scoreThreshold) continue;\n // Only consider keypoints whose score is maximum in a local window.\n if (scoreIsMaximumInLocalWindow(keypointId, score, heatmapY, heatmapX, localMaximumRadius, scores)) {\n queue.enqueue({ score, part: { heatmapY, heatmapX, id: keypointId } });\n }\n }\n }\n }\n return queue;\n}\nexports.buildPartWithScoreQueue = buildPartWithScoreQueue;\n", "exports.partNames = [\n 'nose', 'leftEye', 'rightEye', 'leftEar', 'rightEar', 'leftShoulder',\n 'rightShoulder', 'leftElbow', 'rightElbow', 'leftWrist', 'rightWrist',\n 'leftHip', 'rightHip', 'leftKnee', 'rightKnee', 'leftAnkle', 'rightAnkle',\n];\nexports.NUM_KEYPOINTS = exports.partNames.length;\nexports.partIds = exports.partNames.reduce((result, jointName, i) => {\n result[jointName] = i;\n return result;\n}, {});\nconst connectedPartNames = [\n ['leftHip', 'leftShoulder'], ['leftElbow', 'leftShoulder'],\n ['leftElbow', 'leftWrist'], ['leftHip', 'leftKnee'],\n ['leftKnee', 'leftAnkle'], ['rightHip', 'rightShoulder'],\n ['rightElbow', 'rightShoulder'], ['rightElbow', 'rightWrist'],\n ['rightHip', 'rightKnee'], ['rightKnee', 'rightAnkle'],\n ['leftShoulder', 'rightShoulder'], ['leftHip', 'rightHip'],\n];\n/*\n * Define the skeleton. This defines the parent->child relationships of our\n * tree. Arbitrarily this defines the nose as the root of the tree, however\n * since we will infer the displacement for both parent->child and\n * child->parent, we can define the tree root as any node.\n */\nexports.poseChain = [\n ['nose', 'leftEye'], ['leftEye', 'leftEar'], ['nose', 'rightEye'],\n ['rightEye', 'rightEar'], ['nose', 'leftShoulder'],\n ['leftShoulder', 'leftElbow'], ['leftElbow', 'leftWrist'],\n ['leftShoulder', 'leftHip'], ['leftHip', 'leftKnee'],\n ['leftKnee', 'leftAnkle'], ['nose', 'rightShoulder'],\n ['rightShoulder', 'rightElbow'], ['rightElbow', 'rightWrist'],\n ['rightShoulder', 'rightHip'], ['rightHip', 'rightKnee'],\n ['rightKnee', 'rightAnkle'],\n];\nexports.connectedPartIndices = connectedPartNames.map(([jointNameA, jointNameB]) => ([exports.partIds[jointNameA], exports.partIds[jointNameB]]));\nexports.partChannels = [\n 'left_face',\n 'right_face',\n 'right_upper_leg_front',\n 'right_lower_leg_back',\n 'right_upper_leg_back',\n 'left_lower_leg_front',\n 'left_upper_leg_front',\n 'left_upper_leg_back',\n 'left_lower_leg_back',\n 'right_feet',\n 'right_lower_leg_front',\n 'left_feet',\n 'torso_front',\n 'torso_back',\n 'right_upper_arm_front',\n 'right_upper_arm_back',\n 'right_lower_arm_back',\n 'left_lower_arm_front',\n 'left_upper_arm_front',\n 'left_upper_arm_back',\n 'left_lower_arm_back',\n 'right_hand',\n 'right_lower_arm_front',\n 'left_hand',\n];\n", "const kpt = require('./keypoints');\n\nfunction getOffsetPoint(y, x, keypoint, offsets) {\n return {\n y: offsets.get(y, x, keypoint),\n x: offsets.get(y, x, keypoint + kpt.NUM_KEYPOINTS),\n };\n}\nexports.getOffsetPoint = getOffsetPoint;\n\nfunction getImageCoords(part, outputStride, offsets) {\n const { heatmapY, heatmapX, id: keypoint } = part;\n const { y, x } = getOffsetPoint(heatmapY, heatmapX, keypoint, offsets);\n return {\n x: part.heatmapX * outputStride + x,\n y: part.heatmapY * outputStride + y,\n };\n}\nexports.getImageCoords = getImageCoords;\n\nfunction fillArray(element, size) {\n const result = new Array(size);\n for (let i = 0; i < size; i++) {\n result[i] = element;\n }\n return result;\n}\nexports.fillArray = fillArray;\n\nfunction clamp(a, min, max) {\n if (a < min) return min;\n if (a > max) return max;\n return a;\n}\nexports.clamp = clamp;\n\nfunction squaredDistance(y1, x1, y2, x2) {\n const dy = y2 - y1;\n const dx = x2 - x1;\n return dy * dy + dx * dx;\n}\nexports.squaredDistance = squaredDistance;\n\nfunction addVectors(a, b) {\n return { x: a.x + b.x, y: a.y + b.y };\n}\nexports.addVectors = addVectors;\n\nfunction clampVector(a, min, max) {\n return { y: clamp(a.y, min, max), x: clamp(a.x, min, max) };\n}\nexports.clampVector = clampVector;\n", "const keypoints = require('./keypoints');\nconst vectors = require('./vectors');\n\nconst parentChildrenTuples = keypoints.poseChain.map(([parentJoinName, childJoinName]) => ([keypoints.partIds[parentJoinName], keypoints.partIds[childJoinName]]));\nconst parentToChildEdges = parentChildrenTuples.map(([, childJointId]) => childJointId);\nconst childToParentEdges = parentChildrenTuples.map(([parentJointId]) => parentJointId);\nfunction getDisplacement(edgeId, point, displacements) {\n const numEdges = displacements.shape[2] / 2;\n return {\n y: displacements.get(point.y, point.x, edgeId),\n x: displacements.get(point.y, point.x, numEdges + edgeId),\n };\n}\nfunction getStridedIndexNearPoint(point, outputStride, height, width) {\n return {\n y: vectors.clamp(Math.round(point.y / outputStride), 0, height - 1),\n x: vectors.clamp(Math.round(point.x / outputStride), 0, width - 1),\n };\n}\n/**\n * We get a new keypoint along the `edgeId` for the pose instance, assuming\n * that the position of the `idSource` part is already known. For this, we\n * follow the displacement vector from the source to target part (stored in\n * the `i`-t channel of the displacement tensor). The displaced keypoint\n * vector is refined using the offset vector by `offsetRefineStep` times.\n */\nfunction traverseToTargetKeypoint(edgeId, sourceKeypoint, targetKeypointId, scoresBuffer, offsets, outputStride, displacements, offsetRefineStep = 2) {\n const [height, width] = scoresBuffer.shape;\n // Nearest neighbor interpolation for the source->target displacements.\n const sourceKeypointIndices = getStridedIndexNearPoint(sourceKeypoint.position, outputStride, height, width);\n const displacement = getDisplacement(edgeId, sourceKeypointIndices, displacements);\n const displacedPoint = vectors.addVectors(sourceKeypoint.position, displacement);\n let targetKeypoint = displacedPoint;\n for (let i = 0; i < offsetRefineStep; i++) {\n const targetKeypointIndices = getStridedIndexNearPoint(targetKeypoint, outputStride, height, width);\n const offsetPoint = vectors.getOffsetPoint(targetKeypointIndices.y, targetKeypointIndices.x, targetKeypointId, offsets);\n targetKeypoint = vectors.addVectors({\n x: targetKeypointIndices.x * outputStride,\n y: targetKeypointIndices.y * outputStride,\n }, { x: offsetPoint.x, y: offsetPoint.y });\n }\n const targetKeyPointIndices = getStridedIndexNearPoint(targetKeypoint, outputStride, height, width);\n const score = scoresBuffer.get(targetKeyPointIndices.y, targetKeyPointIndices.x, targetKeypointId);\n return { position: targetKeypoint, part: keypoints.partNames[targetKeypointId], score };\n}\n/**\n * Follows the displacement fields to decode the full pose of the object\n * instance given the position of a part that acts as root.\n *\n * @return An array of decoded keypoints and their scores for a single pose\n */\nfunction decodePose(root, scores, offsets, outputStride, displacementsFwd, displacementsBwd) {\n const numParts = scores.shape[2];\n const numEdges = parentToChildEdges.length;\n const instanceKeypoints = new Array(numParts);\n // Start a new detection instance at the position of the root.\n const { part: rootPart, score: rootScore } = root;\n const rootPoint = vectors.getImageCoords(rootPart, outputStride, offsets);\n instanceKeypoints[rootPart.id] = {\n score: rootScore,\n part: keypoints.partNames[rootPart.id],\n position: rootPoint,\n };\n // Decode the part positions upwards in the tree, following the backward\n // displacements.\n for (let edge = numEdges - 1; edge >= 0; --edge) {\n const sourceKeypointId = parentToChildEdges[edge];\n const targetKeypointId = childToParentEdges[edge];\n if (instanceKeypoints[sourceKeypointId] && !instanceKeypoints[targetKeypointId]) {\n instanceKeypoints[targetKeypointId] = traverseToTargetKeypoint(edge, instanceKeypoints[sourceKeypointId], targetKeypointId, scores, offsets, outputStride, displacementsBwd);\n }\n }\n // Decode the part positions downwards in the tree, following the forward\n // displacements.\n for (let edge = 0; edge < numEdges; ++edge) {\n const sourceKeypointId = childToParentEdges[edge];\n const targetKeypointId = parentToChildEdges[edge];\n if (instanceKeypoints[sourceKeypointId] && !instanceKeypoints[targetKeypointId]) {\n instanceKeypoints[targetKeypointId] = traverseToTargetKeypoint(edge, instanceKeypoints[sourceKeypointId], targetKeypointId, scores, offsets, outputStride, displacementsFwd);\n }\n }\n return instanceKeypoints;\n}\nexports.decodePose = decodePose;\n", "const buildParts = require('./buildParts');\nconst decodePose = require('./decodePose');\nconst vectors = require('./vectors');\n\nfunction withinNmsRadiusOfCorrespondingPoint(poses, squaredNmsRadius, { x, y }, keypointId) {\n return poses.some(({ keypoints }) => {\n const correspondingKeypoint = keypoints[keypointId].position;\n return vectors.squaredDistance(y, x, correspondingKeypoint.y, correspondingKeypoint.x) <= squaredNmsRadius;\n });\n}\n/* Score the newly proposed object instance without taking into account\n * the scores of the parts that overlap with any previously detected\n * instance.\n */\nfunction getInstanceScore(existingPoses, squaredNmsRadius, instanceKeypoints) {\n const notOverlappedKeypointScores = instanceKeypoints.reduce((result, { position, score }, keypointId) => {\n if (!withinNmsRadiusOfCorrespondingPoint(existingPoses, squaredNmsRadius, position, keypointId)) {\n result += score;\n }\n return result;\n }, 0.0);\n return notOverlappedKeypointScores / instanceKeypoints.length;\n}\n// A point (y, x) is considered as root part candidate if its score is a\n// maximum in a window |y - y'| <= kLocalMaximumRadius, |x - x'| <=\n// kLocalMaximumRadius.\nconst kLocalMaximumRadius = 1;\n/**\n * Detects multiple poses and finds their parts from part scores and\n * displacement vectors. It returns up to `maxDetections` object instance\n * detections in decreasing root score order. It works as follows: We first\n * create a priority queue with local part score maxima above\n * `scoreThreshold`, considering all parts at the same time. Then we\n * iteratively pull the top element of the queue (in decreasing score order)\n * and treat it as a root candidate for a new object instance. To avoid\n * duplicate detections, we reject the root candidate if it is within a disk\n * of `nmsRadius` pixels from the corresponding part of a previously detected\n * instance, which is a form of part-based non-maximum suppression (NMS). If\n * the root candidate passes the NMS check, we start a new object instance\n * detection, treating the corresponding part as root and finding the\n * positions of the remaining parts by following the displacement vectors\n * along the tree-structured part graph. We assign to the newly detected\n * instance a score equal to the sum of scores of its parts which have not\n * been claimed by a previous instance (i.e., those at least `nmsRadius`\n * pixels away from the corresponding part of all previously detected\n * instances), divided by the total number of parts `numParts`.\n *\n * @param heatmapScores 3-D tensor with shape `[height, width, numParts]`.\n * The value of heatmapScores[y, x, k]` is the score of placing the `k`-th\n * object part at position `(y, x)`.\n *\n * @param offsets 3-D tensor with shape `[height, width, numParts * 2]`.\n * The value of [offsets[y, x, k], offsets[y, x, k + numParts]]` is the\n * short range offset vector of the `k`-th object part at heatmap\n * position `(y, x)`.\n *\n * @param displacementsFwd 3-D tensor of shape\n * `[height, width, 2 * num_edges]`, where `num_edges = num_parts - 1` is the\n * number of edges (parent-child pairs) in the tree. It contains the forward\n * displacements between consecutive part from the root towards the leaves.\n *\n * @param displacementsBwd 3-D tensor of shape\n * `[height, width, 2 * num_edges]`, where `num_edges = num_parts - 1` is the\n * number of edges (parent-child pairs) in the tree. It contains the backward\n * displacements between consecutive part from the root towards the leaves.\n *\n * @param outputStride The output stride that was used when feed-forwarding\n * through the PoseNet model. Must be 32, 16, or 8.\n *\n * @param maxPoseDetections Maximum number of returned instance detections per\n * image.\n *\n * @param scoreThreshold Only return instance detections that have root part\n * score greater or equal to this value. Defaults to 0.5.\n *\n * @param nmsRadius Non-maximum suppression part distance. It needs to be\n * strictly positive. Two parts suppress each other if they are less than\n * `nmsRadius` pixels away. Defaults to 20.\n *\n * @return An array of poses and their scores, each containing keypoints and\n * the corresponding keypoint scores.\n */\nfunction decodeMultiplePoses(scoresBuffer, offsetsBuffer, displacementsFwdBuffer, displacementsBwdBuffer, outputStride, maxPoseDetections, scoreThreshold = 0.5, nmsRadius = 20) {\n const poses = [];\n const queue = buildParts.buildPartWithScoreQueue(scoreThreshold, kLocalMaximumRadius, scoresBuffer);\n const squaredNmsRadius = nmsRadius * nmsRadius;\n // Generate at most maxDetections object instances per image in\n // decreasing root part score order.\n while (poses.length < maxPoseDetections && !queue.empty()) {\n // The top element in the queue is the next root candidate.\n const root = queue.dequeue();\n // Part-based non-maximum suppression: We reject a root candidate if it\n // is within a disk of `nmsRadius` pixels from the corresponding part of\n // a previously detected instance.\n const rootImageCoords = vectors.getImageCoords(root.part, outputStride, offsetsBuffer);\n if (withinNmsRadiusOfCorrespondingPoint(poses, squaredNmsRadius, rootImageCoords, root.part.id)) continue;\n // Start a new detection instance at the position of the root.\n const keypoints = decodePose.decodePose(root, scoresBuffer, offsetsBuffer, outputStride, displacementsFwdBuffer, displacementsBwdBuffer);\n const score = getInstanceScore(poses, squaredNmsRadius, keypoints);\n poses.push({ keypoints, score });\n }\n return poses;\n}\nexports.decodeMultiplePoses = decodeMultiplePoses;\n", "const kpt = require('./keypoints');\n\nfunction eitherPointDoesntMeetConfidence(a, b, minConfidence) {\n return (a < minConfidence || b < minConfidence);\n}\n\nfunction getAdjacentKeyPoints(keypoints, minConfidence) {\n return kpt.connectedPartIndices.reduce((result, [leftJoint, rightJoint]) => {\n if (eitherPointDoesntMeetConfidence(keypoints[leftJoint].score, keypoints[rightJoint].score, minConfidence)) {\n return result;\n }\n result.push([keypoints[leftJoint], keypoints[rightJoint]]);\n return result;\n }, []);\n}\nexports.getAdjacentKeyPoints = getAdjacentKeyPoints;\n\nconst { NEGATIVE_INFINITY, POSITIVE_INFINITY } = Number;\nfunction getBoundingBox(keypoints) {\n return keypoints.reduce(({ maxX, maxY, minX, minY }, { position: { x, y } }) => ({\n maxX: Math.max(maxX, x),\n maxY: Math.max(maxY, y),\n minX: Math.min(minX, x),\n minY: Math.min(minY, y),\n }), {\n maxX: NEGATIVE_INFINITY,\n maxY: NEGATIVE_INFINITY,\n minX: POSITIVE_INFINITY,\n minY: POSITIVE_INFINITY,\n });\n}\nexports.getBoundingBox = getBoundingBox;\nfunction getBoundingBoxPoints(keypoints) {\n const { minX, minY, maxX, maxY } = getBoundingBox(keypoints);\n return [{ x: minX, y: minY }, { x: maxX, y: minY }, { x: maxX, y: maxY }, { x: minX, y: maxY }];\n}\nexports.getBoundingBoxPoints = getBoundingBoxPoints;\nasync function toTensorBuffers3D(tensors) {\n return Promise.all(tensors.map((tensor) => tensor.buffer()));\n}\nexports.toTensorBuffers3D = toTensorBuffers3D;\n\nfunction scalePose(pose, scaleY, scaleX) {\n return {\n score: pose.score,\n keypoints: pose.keypoints.map(({ score, part, position }) => ({\n score,\n part,\n position: { x: position.x * scaleX, y: position.y * scaleY },\n })),\n };\n}\nexports.scalePose = scalePose;\n\nfunction resizeTo(image, [targetH, targetW]) {\n const input = image.squeeze(0);\n const resized = input.resizeBilinear([targetH, targetW]);\n input.dispose();\n return resized;\n}\nexports.resizeTo = resizeTo;\n\nfunction scaleAndFlipPoses(poses, [height, width], [inputResolutionHeight, inputResolutionWidth]) {\n const scaledPoses = poses.map((pose) => scalePose(pose, height / inputResolutionHeight, width / inputResolutionWidth));\n return scaledPoses;\n}\nexports.scaleAndFlipPoses = scaleAndFlipPoses;\n", "const tf = require('@tensorflow/tfjs');\nconst modelMobileNet = require('./modelMobileNet');\nconst decodeMultiple = require('./decodeMultiple');\nconst util = require('./util');\n\nclass PoseNet {\n constructor(net) {\n this.baseModel = net;\n }\n\n /**\n * Infer through PoseNet, and estimates multiple poses using the outputs.\n * This does standard ImageNet pre-processing before inferring through the\n * model. The image should pixels should have values [0-255]. It detects\n * multiple poses and finds their parts from part scores and displacement\n * vectors using a fast greedy decoding algorithm. It returns up to\n * `config.maxDetections` object instance detections in decreasing root\n * score order.\n *\n * @param input\n * ImageData|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement) The input\n * image to feed through the network.\n *\n * @param config MultiPoseEstimationConfig object that contains parameters\n * for the PoseNet inference using multiple pose estimation.\n *\n * @return An array of poses and their scores, each containing keypoints and\n * the corresponding keypoint scores. The positions of the keypoints are\n * in the same scale as the original image\n */\n async estimatePoses(input, config) {\n const outputStride = config.outputStride;\n // const inputResolution = config.inputResolution;\n const height = input.shape[1];\n const width = input.shape[2];\n const resized = util.resizeTo(input, [config.inputResolution, config.inputResolution]);\n const { heatmapScores, offsets, displacementFwd, displacementBwd } = this.baseModel.predict(resized);\n const allTensorBuffers = await util.toTensorBuffers3D([heatmapScores, offsets, displacementFwd, displacementBwd]);\n const scoresBuffer = allTensorBuffers[0];\n const offsetsBuffer = allTensorBuffers[1];\n const displacementsFwdBuffer = allTensorBuffers[2];\n const displacementsBwdBuffer = allTensorBuffers[3];\n const poses = await decodeMultiple.decodeMultiplePoses(scoresBuffer, offsetsBuffer, displacementsFwdBuffer, displacementsBwdBuffer, outputStride, config.maxDetections, config.scoreThreshold, config.nmsRadius);\n const resultPoses = util.scaleAndFlipPoses(poses, [height, width], [config.inputResolution, config.inputResolution]);\n heatmapScores.dispose();\n offsets.dispose();\n displacementFwd.dispose();\n displacementBwd.dispose();\n resized.dispose();\n return resultPoses;\n }\n\n dispose() {\n this.baseModel.dispose();\n }\n}\nexports.PoseNet = PoseNet;\nasync function loadMobileNet(config) {\n const graphModel = await tf.loadGraphModel(config.modelPath);\n const mobilenet = new modelMobileNet.MobileNet(graphModel, config.outputStride);\n return new PoseNet(mobilenet);\n}\n/**\n * Loads the PoseNet model instance from a checkpoint, with the MobileNet architecture. The model to be loaded is configurable using the\n * config dictionary ModelConfig. Please find more details in the documentation of the ModelConfig.\n *\n * @param config ModelConfig dictionary that contains parameters for\n * the PoseNet loading process. Please find more details of each parameters\n * in the documentation of the ModelConfig interface. The predefined\n * `MOBILENET_V1_CONFIG` and `RESNET_CONFIG` can also be used as references\n * for defining your customized config.\n */\nasync function load(config) {\n return loadMobileNet(config);\n}\nexports.load = load;\n", "const modelMobileNet = require('./modelMobileNet');\nconst modelPoseNet = require('./modelPoseNet');\nconst decodeMultiple = require('./decodeMultiple');\nconst keypoints = require('./keypoints');\nconst util = require('./util');\n\nexports.load = modelPoseNet.load;\nexports.PoseNet = modelPoseNet.PoseNet;\n\nexports.MobileNet = modelMobileNet.MobileNet;\nexports.decodeMultiplePoses = decodeMultiple.decodeMultiplePoses;\nexports.partChannels = keypoints.partChannels;\nexports.partIds = keypoints.partIds;\nexports.partNames = keypoints.partNames;\nexports.poseChain = keypoints.poseChain;\nexports.getAdjacentKeyPoints = util.getAdjacentKeyPoints;\nexports.getBoundingBox = util.getBoundingBox;\nexports.getBoundingBoxPoints = util.getBoundingBoxPoints;\nexports.scaleAndFlipPoses = util.scaleAndFlipPoses;\nexports.scalePose = util.scalePose;\n", "const tf = require('@tensorflow/tfjs');\n\nfunction getBoxSize(box) {\n return [\n Math.abs(box.endPoint[0] - box.startPoint[0]),\n Math.abs(box.endPoint[1] - box.startPoint[1]),\n ];\n}\nexports.getBoxSize = getBoxSize;\n\nfunction getBoxCenter(box) {\n return [\n box.startPoint[0] + (box.endPoint[0] - box.startPoint[0]) / 2,\n box.startPoint[1] + (box.endPoint[1] - box.startPoint[1]) / 2,\n ];\n}\nexports.getBoxCenter = getBoxCenter;\n\nfunction cutBoxFromImageAndResize(box, image, cropSize) {\n const h = image.shape[1];\n const w = image.shape[2];\n const boxes = [[\n box.startPoint[1] / h, box.startPoint[0] / w, box.endPoint[1] / h,\n box.endPoint[0] / w,\n ]];\n return tf.image.cropAndResize(image, boxes, [0], cropSize);\n}\nexports.cutBoxFromImageAndResize = cutBoxFromImageAndResize;\n\nfunction scaleBoxCoordinates(box, factor) {\n const startPoint = [box.startPoint[0] * factor[0], box.startPoint[1] * factor[1]];\n const endPoint = [box.endPoint[0] * factor[0], box.endPoint[1] * factor[1]];\n const palmLandmarks = box.palmLandmarks.map((coord) => {\n const scaledCoord = [coord[0] * factor[0], coord[1] * factor[1]];\n return scaledCoord;\n });\n return { startPoint, endPoint, palmLandmarks };\n}\nexports.scaleBoxCoordinates = scaleBoxCoordinates;\n\nfunction enlargeBox(box, factor = 1.5) {\n const center = getBoxCenter(box);\n const size = getBoxSize(box);\n const newHalfSize = [factor * size[0] / 2, factor * size[1] / 2];\n const startPoint = [center[0] - newHalfSize[0], center[1] - newHalfSize[1]];\n const endPoint = [center[0] + newHalfSize[0], center[1] + newHalfSize[1]];\n return { startPoint, endPoint, palmLandmarks: box.palmLandmarks };\n}\nexports.enlargeBox = enlargeBox;\n\nfunction squarifyBox(box) {\n const centers = getBoxCenter(box);\n const size = getBoxSize(box);\n const maxEdge = Math.max(...size);\n const halfSize = maxEdge / 2;\n const startPoint = [centers[0] - halfSize, centers[1] - halfSize];\n const endPoint = [centers[0] + halfSize, centers[1] + halfSize];\n return { startPoint, endPoint, palmLandmarks: box.palmLandmarks };\n}\nexports.squarifyBox = squarifyBox;\n\nfunction shiftBox(box, shiftFactor) {\n const boxSize = [\n box.endPoint[0] - box.startPoint[0], box.endPoint[1] - box.startPoint[1],\n ];\n const shiftVector = [boxSize[0] * shiftFactor[0], boxSize[1] * shiftFactor[1]];\n const startPoint = [box.startPoint[0] + shiftVector[0], box.startPoint[1] + shiftVector[1]];\n const endPoint = [box.endPoint[0] + shiftVector[0], box.endPoint[1] + shiftVector[1]];\n return { startPoint, endPoint, palmLandmarks: box.palmLandmarks };\n}\nexports.shiftBox = shiftBox;\n", "const tf = require('@tensorflow/tfjs');\nconst bounding = require('./box');\n\nclass HandDetector {\n constructor(model, anchors, config) {\n this.model = model;\n this.width = config.inputSize;\n this.height = config.inputSize;\n this.anchors = anchors.map((anchor) => [anchor.x_center, anchor.y_center]);\n this.anchorsTensor = tf.tensor2d(this.anchors);\n this.inputSizeTensor = tf.tensor1d([config.inputSize, config.inputSize]);\n this.doubleInputSizeTensor = tf.tensor1d([config.inputSize * 2, config.inputSize * 2]);\n }\n\n normalizeBoxes(boxes) {\n return tf.tidy(() => {\n const boxOffsets = tf.slice(boxes, [0, 0], [-1, 2]);\n const boxSizes = tf.slice(boxes, [0, 2], [-1, 2]);\n const boxCenterPoints = tf.add(tf.div(boxOffsets, this.inputSizeTensor), this.anchorsTensor);\n const halfBoxSizes = tf.div(boxSizes, this.doubleInputSizeTensor);\n const startPoints = tf.mul(tf.sub(boxCenterPoints, halfBoxSizes), this.inputSizeTensor);\n const endPoints = tf.mul(tf.add(boxCenterPoints, halfBoxSizes), this.inputSizeTensor);\n return tf.concat2d([startPoints, endPoints], 1);\n });\n }\n\n normalizeLandmarks(rawPalmLandmarks, index) {\n return tf.tidy(() => {\n const landmarks = tf.add(tf.div(rawPalmLandmarks.reshape([-1, 7, 2]), this.inputSizeTensor), this.anchors[index]);\n return tf.mul(landmarks, this.inputSizeTensor);\n });\n }\n\n async getBoundingBoxes(input) {\n const batchedPrediction = this.model.predict(input);\n const prediction = batchedPrediction.squeeze();\n // Regression score for each anchor point.\n const scores = tf.tidy(() => tf.sigmoid(tf.slice(prediction, [0, 0], [-1, 1])).squeeze());\n // Bounding box for each anchor point.\n const rawBoxes = tf.slice(prediction, [0, 1], [-1, 4]);\n const boxes = this.normalizeBoxes(rawBoxes);\n const boxesWithHandsTensor = await tf.image.nonMaxSuppressionAsync(boxes, scores, this.maxHands, this.iouThreshold, this.scoreThreshold);\n const boxesWithHands = await boxesWithHandsTensor.array();\n const toDispose = [batchedPrediction, boxesWithHandsTensor, prediction, boxes, rawBoxes, scores];\n const detectedHands = tf.tidy(() => {\n const detectedBoxes = [];\n for (const i in boxesWithHands) {\n const boxIndex = boxesWithHands[i];\n const matchingBox = tf.slice(boxes, [boxIndex, 0], [1, -1]);\n const rawPalmLandmarks = tf.slice(prediction, [boxIndex, 5], [1, 14]);\n const palmLandmarks = tf.tidy(() => this.normalizeLandmarks(rawPalmLandmarks, boxIndex).reshape([-1, 2]));\n detectedBoxes.push({ boxes: matchingBox, palmLandmarks });\n }\n return detectedBoxes;\n });\n toDispose.forEach((tensor) => tensor.dispose());\n return detectedHands;\n }\n\n /**\n * Returns a Box identifying the bounding box of a hand within the image.\n * Returns null if there is no hand in the image.\n *\n * @param input The image to classify.\n */\n async estimateHandBounds(input, config) {\n // const inputHeight = input.shape[2];\n // const inputWidth = input.shape[1];\n this.iouThreshold = config.iouThreshold;\n this.scoreThreshold = config.scoreThreshold;\n this.maxHands = config.maxHands;\n const resized = input.resizeBilinear([this.width, this.height]);\n const divided = resized.div(255);\n const normalized = divided.sub(0.5);\n const image = normalized.mul(2.0);\n resized.dispose();\n divided.dispose();\n normalized.dispose();\n const predictions = await this.getBoundingBoxes(image);\n image.dispose();\n if (!predictions || (predictions.length === 0)) return null;\n const hands = [];\n for (const i in predictions) {\n const prediction = predictions[i];\n const boundingBoxes = await prediction.boxes.array();\n const startPoint = boundingBoxes[0].slice(0, 2);\n const endPoint = boundingBoxes[0].slice(2, 4);\n const palmLandmarks = await prediction.palmLandmarks.array();\n prediction.boxes.dispose();\n prediction.palmLandmarks.dispose();\n hands.push(bounding.scaleBoxCoordinates({ startPoint, endPoint, palmLandmarks }, [input.shape[2] / this.width, input.shape[1] / this.height]));\n }\n return hands;\n }\n}\nexports.HandDetector = HandDetector;\n", "exports.MESH_ANNOTATIONS = {\n thumb: [1, 2, 3, 4],\n indexFinger: [5, 6, 7, 8],\n middleFinger: [9, 10, 11, 12],\n ringFinger: [13, 14, 15, 16],\n pinky: [17, 18, 19, 20],\n palmBase: [0],\n};\n", "function normalizeRadians(angle) {\n return angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));\n}\nexports.normalizeRadians = normalizeRadians;\n\nfunction computeRotation(point1, point2) {\n const radians = Math.PI / 2 - Math.atan2(-(point2[1] - point1[1]), point2[0] - point1[0]);\n return normalizeRadians(radians);\n}\nexports.computeRotation = computeRotation;\n\nconst buildTranslationMatrix = (x, y) => ([[1, 0, x], [0, 1, y], [0, 0, 1]]);\nfunction dot(v1, v2) {\n let product = 0;\n for (let i = 0; i < v1.length; i++) {\n product += v1[i] * v2[i];\n }\n return product;\n}\nexports.dot = dot;\n\nfunction getColumnFrom2DArr(arr, columnIndex) {\n const column = [];\n for (let i = 0; i < arr.length; i++) {\n column.push(arr[i][columnIndex]);\n }\n return column;\n}\nexports.getColumnFrom2DArr = getColumnFrom2DArr;\n\nfunction multiplyTransformMatrices(mat1, mat2) {\n const product = [];\n const size = mat1.length;\n for (let row = 0; row < size; row++) {\n product.push([]);\n for (let col = 0; col < size; col++) {\n product[row].push(dot(mat1[row], getColumnFrom2DArr(mat2, col)));\n }\n }\n return product;\n}\nfunction buildRotationMatrix(rotation, center) {\n const cosA = Math.cos(rotation);\n const sinA = Math.sin(rotation);\n const rotationMatrix = [[cosA, -sinA, 0], [sinA, cosA, 0], [0, 0, 1]];\n const translationMatrix = buildTranslationMatrix(center[0], center[1]);\n const translationTimesRotation = multiplyTransformMatrices(translationMatrix, rotationMatrix);\n const negativeTranslationMatrix = buildTranslationMatrix(-center[0], -center[1]);\n return multiplyTransformMatrices(translationTimesRotation, negativeTranslationMatrix);\n}\nexports.buildRotationMatrix = buildRotationMatrix;\n\nfunction invertTransformMatrix(matrix) {\n const rotationComponent = [[matrix[0][0], matrix[1][0]], [matrix[0][1], matrix[1][1]]];\n const translationComponent = [matrix[0][2], matrix[1][2]];\n const invertedTranslation = [\n -dot(rotationComponent[0], translationComponent),\n -dot(rotationComponent[1], translationComponent),\n ];\n return [\n rotationComponent[0].concat(invertedTranslation[0]),\n rotationComponent[1].concat(invertedTranslation[1]),\n [0, 0, 1],\n ];\n}\nexports.invertTransformMatrix = invertTransformMatrix;\n\nfunction rotatePoint(homogeneousCoordinate, rotationMatrix) {\n return [\n dot(homogeneousCoordinate, rotationMatrix[0]),\n dot(homogeneousCoordinate, rotationMatrix[1]),\n ];\n}\nexports.rotatePoint = rotatePoint;\n", "const tf = require('@tensorflow/tfjs');\nconst bounding = require('./box');\nconst util = require('./util');\n\nconst UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD = 0.8;\nconst PALM_BOX_SHIFT_VECTOR = [0, -0.4];\nconst HAND_BOX_SHIFT_VECTOR = [0, -0.1];\nconst HAND_BOX_ENLARGE_FACTOR = 1.65;\nconst PALM_LANDMARK_IDS = [0, 5, 9, 13, 17, 1, 2];\nconst PALM_LANDMARKS_INDEX_OF_PALM_BASE = 0;\nconst PALM_LANDMARKS_INDEX_OF_MIDDLE_FINGER_BASE = 2;\n\n// The Pipeline coordinates between the bounding box and skeleton models.\nclass HandPipeline {\n constructor(boundingBoxDetector, meshDetector, config) {\n this.regionsOfInterest = [];\n this.runsWithoutHandDetector = 0;\n this.boundingBoxDetector = boundingBoxDetector;\n this.meshDetector = meshDetector;\n this.meshWidth = config.inputSize;\n this.meshHeight = config.inputSize;\n this.enlargeFactor = config.enlargeFactor;\n }\n\n // Get the bounding box surrounding the hand, given palm landmarks.\n getBoxForPalmLandmarks(palmLandmarks, rotationMatrix) {\n const rotatedPalmLandmarks = palmLandmarks.map((coord) => {\n const homogeneousCoordinate = [...coord, 1];\n return util.rotatePoint(homogeneousCoordinate, rotationMatrix);\n });\n const boxAroundPalm = this.calculateLandmarksBoundingBox(rotatedPalmLandmarks);\n // boxAroundPalm only surrounds the palm - therefore we shift it\n // upwards so it will capture fingers once enlarged + squarified.\n return bounding.enlargeBox(bounding.squarifyBox(bounding.shiftBox(boxAroundPalm, PALM_BOX_SHIFT_VECTOR)), this.enlargeFactor);\n }\n\n // Get the bounding box surrounding the hand, given all hand landmarks.\n getBoxForHandLandmarks(landmarks) {\n // The MediaPipe hand mesh model is trained on hands with empty space\n // around them, so we still need to shift / enlarge boxAroundHand even\n // though it surrounds the entire hand.\n const boundingBox = this.calculateLandmarksBoundingBox(landmarks);\n const boxAroundHand = bounding.enlargeBox(bounding.squarifyBox(bounding.shiftBox(boundingBox, HAND_BOX_SHIFT_VECTOR)), HAND_BOX_ENLARGE_FACTOR);\n const palmLandmarks = [];\n for (let i = 0; i < PALM_LANDMARK_IDS.length; i++) {\n palmLandmarks.push(landmarks[PALM_LANDMARK_IDS[i]].slice(0, 2));\n }\n boxAroundHand.palmLandmarks = palmLandmarks;\n return boxAroundHand;\n }\n\n // Scale, rotate, and translate raw keypoints from the model so they map to\n // the input coordinates.\n transformRawCoords(rawCoords, box, angle, rotationMatrix) {\n const boxSize = bounding.getBoxSize(box);\n const scaleFactor = [boxSize[0] / this.meshWidth, boxSize[1] / this.meshHeight];\n const coordsScaled = rawCoords.map((coord) => [\n scaleFactor[0] * (coord[0] - this.meshWidth / 2),\n scaleFactor[1] * (coord[1] - this.meshHeight / 2), coord[2],\n ]);\n const coordsRotationMatrix = util.buildRotationMatrix(angle, [0, 0]);\n const coordsRotated = coordsScaled.map((coord) => {\n const rotated = util.rotatePoint(coord, coordsRotationMatrix);\n return [...rotated, coord[2]];\n });\n const inverseRotationMatrix = util.invertTransformMatrix(rotationMatrix);\n const boxCenter = [...bounding.getBoxCenter(box), 1];\n const originalBoxCenter = [\n util.dot(boxCenter, inverseRotationMatrix[0]),\n util.dot(boxCenter, inverseRotationMatrix[1]),\n ];\n return coordsRotated.map((coord) => [\n coord[0] + originalBoxCenter[0], coord[1] + originalBoxCenter[1],\n coord[2],\n ]);\n }\n\n async estimateHands(image, config) {\n this.skipFrames = config.skipFrames;\n this.detectionConfidence = config.minConfidence;\n this.maxHands = config.maxHands;\n this.runsWithoutHandDetector++;\n const useFreshBox = this.shouldUpdateRegionsOfInterest();\n if (useFreshBox === true) {\n const boundingBoxPredictions = await this.boundingBoxDetector.estimateHandBounds(image, config);\n this.regionsOfInterest = [];\n for (const i in boundingBoxPredictions) {\n this.updateRegionsOfInterest(boundingBoxPredictions[i], true /* force update */, i);\n }\n this.runsWithoutHandDetector = 0;\n }\n // Rotate input so the hand is vertically oriented.\n const hands = [];\n if (!this.regionsOfInterest) return hands;\n for (const i in this.regionsOfInterest) {\n const currentBox = this.regionsOfInterest[i][0];\n if (!currentBox) return hands;\n const angle = util.computeRotation(currentBox.palmLandmarks[PALM_LANDMARKS_INDEX_OF_PALM_BASE], currentBox.palmLandmarks[PALM_LANDMARKS_INDEX_OF_MIDDLE_FINGER_BASE]);\n const palmCenter = bounding.getBoxCenter(currentBox);\n const palmCenterNormalized = [palmCenter[0] / image.shape[2], palmCenter[1] / image.shape[1]];\n const rotatedImage = tf.image.rotateWithOffset(image, angle, 0, palmCenterNormalized);\n const rotationMatrix = util.buildRotationMatrix(-angle, palmCenter);\n const box = useFreshBox ? this.getBoxForPalmLandmarks(currentBox.palmLandmarks, rotationMatrix) : currentBox;\n const croppedInput = bounding.cutBoxFromImageAndResize(box, rotatedImage, [this.meshWidth, this.meshHeight]);\n const handImage = croppedInput.div(255);\n croppedInput.dispose();\n rotatedImage.dispose();\n const prediction = this.meshDetector.predict(handImage);\n const [flag, keypoints] = prediction;\n handImage.dispose();\n const flagValue = flag.dataSync()[0];\n flag.dispose();\n if (flagValue < config.minConfidence) {\n keypoints.dispose();\n this.regionsOfInterest[i] = [];\n return hands;\n }\n const keypointsReshaped = tf.reshape(keypoints, [-1, 3]);\n const rawCoords = await keypointsReshaped.array();\n keypoints.dispose();\n keypointsReshaped.dispose();\n const coords = this.transformRawCoords(rawCoords, box, angle, rotationMatrix);\n const nextBoundingBox = this.getBoxForHandLandmarks(coords);\n this.updateRegionsOfInterest(nextBoundingBox, false /* force replace */, i);\n const result = {\n landmarks: coords,\n confidence: flagValue,\n box: {\n topLeft: nextBoundingBox.startPoint,\n bottomRight: nextBoundingBox.endPoint,\n },\n };\n hands.push(result);\n }\n return hands;\n }\n\n // eslint-disable-next-line class-methods-use-this\n calculateLandmarksBoundingBox(landmarks) {\n const xs = landmarks.map((d) => d[0]);\n const ys = landmarks.map((d) => d[1]);\n const startPoint = [Math.min(...xs), Math.min(...ys)];\n const endPoint = [Math.max(...xs), Math.max(...ys)];\n return { startPoint, endPoint };\n }\n\n // Updates regions of interest if the intersection over union between\n // the incoming and previous regions falls below a threshold.\n updateRegionsOfInterest(box, forceUpdate, index) {\n if (forceUpdate) {\n this.regionsOfInterest[index] = [box];\n } else {\n const previousBox = this.regionsOfInterest[index][0];\n let iou = 0;\n if (previousBox != null && previousBox.startPoint != null) {\n const [boxStartX, boxStartY] = box.startPoint;\n const [boxEndX, boxEndY] = box.endPoint;\n const [previousBoxStartX, previousBoxStartY] = previousBox.startPoint;\n const [previousBoxEndX, previousBoxEndY] = previousBox.endPoint;\n const xStartMax = Math.max(boxStartX, previousBoxStartX);\n const yStartMax = Math.max(boxStartY, previousBoxStartY);\n const xEndMin = Math.min(boxEndX, previousBoxEndX);\n const yEndMin = Math.min(boxEndY, previousBoxEndY);\n const intersection = (xEndMin - xStartMax) * (yEndMin - yStartMax);\n const boxArea = (boxEndX - boxStartX) * (boxEndY - boxStartY);\n const previousBoxArea = (previousBoxEndX - previousBoxStartX) * (previousBoxEndY - boxStartY);\n iou = intersection / (boxArea + previousBoxArea - intersection);\n }\n this.regionsOfInterest[index][0] = iou > UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD ? previousBox : box;\n }\n }\n\n shouldUpdateRegionsOfInterest() {\n return !this.regionsOfInterest || (this.regionsOfInterest.length === 0) || (this.runsWithoutHandDetector >= this.skipFrames);\n }\n}\nexports.HandPipeline = HandPipeline;\n", "const tf = require('@tensorflow/tfjs');\nconst hand = require('./handdetector');\nconst keypoints = require('./keypoints');\nconst pipe = require('./pipeline');\n\nclass HandPose {\n constructor(pipeline) {\n this.pipeline = pipeline;\n }\n\n async estimateHands(input, config) {\n this.skipFrames = config.skipFrames;\n this.detectionConfidence = config.minConfidence;\n this.maxHands = config.maxHands;\n const predictions = await this.pipeline.estimateHands(input, config);\n const hands = [];\n if (!predictions) return hands;\n for (const prediction of predictions) {\n if (!prediction) return [];\n const annotations = {};\n for (const key of Object.keys(keypoints.MESH_ANNOTATIONS)) {\n annotations[key] = keypoints.MESH_ANNOTATIONS[key].map((index) => prediction.landmarks[index]);\n }\n hands.push({\n confidence: prediction.confidence || 0,\n box: prediction.box ? [prediction.box.topLeft[0], prediction.box.topLeft[1], prediction.box.bottomRight[0] - prediction.box.topLeft[0], prediction.box.bottomRight[1] - prediction.box.topLeft[1]] : 0,\n landmarks: prediction.landmarks,\n annotations,\n });\n }\n return hands;\n }\n}\nexports.HandPose = HandPose;\n\nasync function loadAnchors(url) {\n if (tf.env().features.IS_NODE) {\n // eslint-disable-next-line global-require\n const fs = require('fs');\n const data = await fs.readFileSync(url.replace('file://', ''));\n return JSON.parse(data);\n }\n return tf.util.fetch(url).then((d) => d.json());\n}\n\nasync function load(config) {\n const [anchors, handDetectorModel, handPoseModel] = await Promise.all([\n loadAnchors(config.detector.anchors),\n tf.loadGraphModel(config.detector.modelPath, { fromTFHub: config.detector.modelPath.includes('tfhub.dev') }),\n tf.loadGraphModel(config.skeleton.modelPath, { fromTFHub: config.skeleton.modelPath.includes('tfhub.dev') }),\n ]);\n const detector = new hand.HandDetector(handDetectorModel, anchors, config);\n const pipeline = new pipe.HandPipeline(detector, handPoseModel, config);\n const handpose = new HandPose(pipeline);\n return handpose;\n}\nexports.load = load;\n", "/* eslint-disable no-shadow */\n/* eslint-disable prefer-rest-params */\n/* eslint-disable no-sequences */\n/* eslint-disable no-unused-vars */\n/* eslint-disable no-unused-expressions */\n/* eslint-disable no-multi-assign */\n/* eslint-disable no-use-before-define */\n/*\nWebGLImageFilter - MIT Licensed\n2013, Dominic Szablewski - phoboslab.org\n*/\n\nconst WebGLProgram = function (gl, vertexSource, fragmentSource) {\n const _collect = function (source, prefix, collection) {\n const r = new RegExp('\\\\b' + prefix + ' \\\\w+ (\\\\w+)', 'ig');\n source.replace(r, (match, name) => {\n collection[name] = 0;\n return match;\n });\n };\n\n const _compile = function (gl, source, type) {\n const shader = gl.createShader(type);\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n throw new Error('Filter: GL compile failed', gl.getShaderInfoLog(shader));\n }\n return shader;\n };\n\n this.uniform = {};\n this.attribute = {};\n\n const _vsh = _compile(gl, vertexSource, gl.VERTEX_SHADER);\n const _fsh = _compile(gl, fragmentSource, gl.FRAGMENT_SHADER);\n\n this.id = gl.createProgram();\n gl.attachShader(this.id, _vsh);\n gl.attachShader(this.id, _fsh);\n gl.linkProgram(this.id);\n\n if (!gl.getProgramParameter(this.id, gl.LINK_STATUS)) {\n throw new Error('Filter: GL link failed', gl.getProgramInfoLog(this.id));\n }\n\n gl.useProgram(this.id);\n\n // Collect attributes\n _collect(vertexSource, 'attribute', this.attribute);\n for (const a in this.attribute) {\n this.attribute[a] = gl.getAttribLocation(this.id, a);\n }\n\n // Collect uniforms\n _collect(vertexSource, 'uniform', this.uniform);\n _collect(fragmentSource, 'uniform', this.uniform);\n for (const u in this.uniform) {\n this.uniform[u] = gl.getUniformLocation(this.id, u);\n }\n};\n\nconst WebGLImageFilter = function (params) {\n if (!params) params = { };\n let _drawCount = 0;\n let _sourceTexture = null;\n let _lastInChain = false;\n let _currentFramebufferIndex = -1;\n let _tempFramebuffers = [null, null];\n let _filterChain = [];\n let _width = -1;\n let _height = -1;\n let _vertexBuffer = null;\n let _currentProgram = null;\n const _canvas = params.canvas || document.createElement('canvas');\n\n // key is the shader program source, value is the compiled program\n const _shaderProgramCache = { };\n\n const gl = _canvas.getContext('webgl') || _canvas.getContext('experimental-webgl');\n if (!gl) throw new Error('Filter: getContext() failed');\n\n this.addFilter = function (name) {\n const args = Array.prototype.slice.call(arguments, 1);\n const filter = _filter[name];\n\n _filterChain.push({ func: filter, args });\n };\n\n this.reset = function () {\n _filterChain = [];\n };\n\n this.apply = function (image) {\n _resize(image.width, image.height);\n _drawCount = 0;\n\n // Create the texture for the input image if we haven't yet\n if (!_sourceTexture) _sourceTexture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, _sourceTexture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);\n\n // No filters? Just draw\n if (_filterChain.length === 0) {\n const program = _compileShader(SHADER.FRAGMENT_IDENTITY);\n _draw();\n return _canvas;\n }\n\n for (let i = 0; i < _filterChain.length; i++) {\n _lastInChain = (i === _filterChain.length - 1);\n const f = _filterChain[i];\n f.func.apply(this, f.args || []);\n }\n\n return _canvas;\n };\n\n const _resize = function (width, height) {\n // Same width/height? Nothing to do here\n if (width === _width && height === _height) { return; }\n\n _canvas.width = _width = width;\n _canvas.height = _height = height;\n\n // Create the context if we don't have it yet\n if (!_vertexBuffer) {\n // Create the vertex buffer for the two triangles [x, y, u, v] * 6\n const vertices = new Float32Array([\n -1, -1, 0, 1, 1, -1, 1, 1, -1, 1, 0, 0,\n -1, 1, 0, 0, 1, -1, 1, 1, 1, 1, 1, 0,\n ]);\n _vertexBuffer = gl.createBuffer(),\n gl.bindBuffer(gl.ARRAY_BUFFER, _vertexBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);\n\n // Note sure if this is a good idea; at least it makes texture loading\n // in Ejecta instant.\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);\n }\n\n gl.viewport(0, 0, _width, _height);\n\n // Delete old temp framebuffers\n _tempFramebuffers = [null, null];\n };\n\n const _getTempFramebuffer = function (index) {\n _tempFramebuffers[index] = _tempFramebuffers[index]\n || _createFramebufferTexture(_width, _height);\n\n return _tempFramebuffers[index];\n };\n\n const _createFramebufferTexture = function (width, height) {\n const fbo = gl.createFramebuffer();\n gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);\n\n const renderbuffer = gl.createRenderbuffer();\n gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer);\n\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);\n\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n\n return { fbo, texture };\n };\n\n const _draw = function (flags) {\n let source = null;\n let target = null;\n let flipY = false;\n\n // Set up the source\n if (_drawCount === 0) {\n // First draw call - use the source texture\n source = _sourceTexture;\n } else {\n // All following draw calls use the temp buffer last drawn to\n source = _getTempFramebuffer(_currentFramebufferIndex).texture;\n }\n _drawCount++;\n\n // Set up the target\n if (_lastInChain && !(flags & DRAW.INTERMEDIATE)) {\n // Last filter in our chain - draw directly to the WebGL Canvas. We may\n // also have to flip the image vertically now\n target = null;\n flipY = _drawCount % 2 === 0;\n } else {\n // Intermediate draw call - get a temp buffer to draw to\n _currentFramebufferIndex = (_currentFramebufferIndex + 1) % 2;\n target = _getTempFramebuffer(_currentFramebufferIndex).fbo;\n }\n\n // Bind the source and target and draw the two triangles\n gl.bindTexture(gl.TEXTURE_2D, source);\n gl.bindFramebuffer(gl.FRAMEBUFFER, target);\n\n gl.uniform1f(_currentProgram.uniform.flipY, (flipY ? -1 : 1));\n gl.drawArrays(gl.TRIANGLES, 0, 6);\n };\n\n const _compileShader = function (fragmentSource) {\n if (_shaderProgramCache[fragmentSource]) {\n _currentProgram = _shaderProgramCache[fragmentSource];\n gl.useProgram(_currentProgram.id);\n return _currentProgram;\n }\n\n // Compile shaders\n _currentProgram = new WebGLProgram(gl, SHADER.VERTEX_IDENTITY, fragmentSource);\n\n const floatSize = Float32Array.BYTES_PER_ELEMENT;\n const vertSize = 4 * floatSize;\n gl.enableVertexAttribArray(_currentProgram.attribute.pos);\n gl.vertexAttribPointer(_currentProgram.attribute.pos, 2, gl.FLOAT, false, vertSize, 0 * floatSize);\n gl.enableVertexAttribArray(_currentProgram.attribute.uv);\n gl.vertexAttribPointer(_currentProgram.attribute.uv, 2, gl.FLOAT, false, vertSize, 2 * floatSize);\n\n _shaderProgramCache[fragmentSource] = _currentProgram;\n return _currentProgram;\n };\n\n let DRAW = { INTERMEDIATE: 1 };\n\n let SHADER = {};\n SHADER.VERTEX_IDENTITY = [\n 'precision highp float;',\n 'attribute vec2 pos;',\n 'attribute vec2 uv;',\n 'varying vec2 vUv;',\n 'uniform float flipY;',\n\n 'void main(void) {',\n 'vUv = uv;',\n 'gl_Position = vec4(pos.x, pos.y*flipY, 0.0, 1.);',\n '}',\n ].join('\\n');\n\n SHADER.FRAGMENT_IDENTITY = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n\n 'void main(void) {',\n 'gl_FragColor = texture2D(texture, vUv);',\n '}',\n ].join('\\n');\n\n let _filter = {};\n\n // -------------------------------------------------------------------------\n // Color Matrix Filter\n\n _filter.colorMatrix = function (matrix) {\n // Create a Float32 Array and normalize the offset component to 0-1\n const m = new Float32Array(matrix);\n m[4] /= 255;\n m[9] /= 255;\n m[14] /= 255;\n m[19] /= 255;\n\n // Can we ignore the alpha value? Makes things a bit faster.\n const shader = (m[18] === 1 && m[3] === 0 && m[8] === 0 && m[13] === 0 && m[15] === 0 && m[16] === 0 && m[17] === 0 && m[19] === 0)\n ? _filter.colorMatrix.SHADER.WITHOUT_ALPHA\n : _filter.colorMatrix.SHADER.WITH_ALPHA;\n\n const program = _compileShader(shader);\n gl.uniform1fv(program.uniform.m, m);\n _draw();\n };\n\n _filter.colorMatrix.SHADER = {};\n _filter.colorMatrix.SHADER.WITH_ALPHA = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform float m[20];',\n\n 'void main(void) {',\n 'vec4 c = texture2D(texture, vUv);',\n 'gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[3] * c.a + m[4];',\n 'gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[8] * c.a + m[9];',\n 'gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[13] * c.a + m[14];',\n 'gl_FragColor.a = m[15] * c.r + m[16] * c.g + m[17] * c.b + m[18] * c.a + m[19];',\n '}',\n ].join('\\n');\n _filter.colorMatrix.SHADER.WITHOUT_ALPHA = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform float m[20];',\n\n 'void main(void) {',\n 'vec4 c = texture2D(texture, vUv);',\n 'gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[4];',\n 'gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[9];',\n 'gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[14];',\n 'gl_FragColor.a = c.a;',\n '}',\n ].join('\\n');\n\n _filter.brightness = function (brightness) {\n const b = (brightness || 0) + 1;\n _filter.colorMatrix([\n b, 0, 0, 0, 0,\n 0, b, 0, 0, 0,\n 0, 0, b, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.saturation = function (amount) {\n const x = (amount || 0) * 2 / 3 + 1;\n const y = ((x - 1) * -0.5);\n _filter.colorMatrix([\n x, y, y, 0, 0,\n y, x, y, 0, 0,\n y, y, x, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.desaturate = function () {\n _filter.saturation(-1);\n };\n\n _filter.contrast = function (amount) {\n const v = (amount || 0) + 1;\n const o = -128 * (v - 1);\n\n _filter.colorMatrix([\n v, 0, 0, 0, o,\n 0, v, 0, 0, o,\n 0, 0, v, 0, o,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.negative = function () {\n _filter.contrast(-2);\n };\n\n _filter.hue = function (rotation) {\n rotation = (rotation || 0) / 180 * Math.PI;\n const cos = Math.cos(rotation);\n const sin = Math.sin(rotation);\n const lumR = 0.213;\n const lumG = 0.715;\n const lumB = 0.072;\n\n _filter.colorMatrix([\n lumR + cos * (1 - lumR) + sin * (-lumR), lumG + cos * (-lumG) + sin * (-lumG), lumB + cos * (-lumB) + sin * (1 - lumB), 0, 0,\n lumR + cos * (-lumR) + sin * (0.143), lumG + cos * (1 - lumG) + sin * (0.140), lumB + cos * (-lumB) + sin * (-0.283), 0, 0,\n lumR + cos * (-lumR) + sin * (-(1 - lumR)), lumG + cos * (-lumG) + sin * (lumG), lumB + cos * (1 - lumB) + sin * (lumB), 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.desaturateLuminance = function () {\n _filter.colorMatrix([\n 0.2764723, 0.9297080, 0.0938197, 0, -37.1,\n 0.2764723, 0.9297080, 0.0938197, 0, -37.1,\n 0.2764723, 0.9297080, 0.0938197, 0, -37.1,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.sepia = function () {\n _filter.colorMatrix([\n 0.393, 0.7689999, 0.18899999, 0, 0,\n 0.349, 0.6859999, 0.16799999, 0, 0,\n 0.272, 0.5339999, 0.13099999, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.brownie = function () {\n _filter.colorMatrix([\n 0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873,\n -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127,\n 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.vintagePinhole = function () {\n _filter.colorMatrix([\n 0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123,\n 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591,\n 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.kodachrome = function () {\n _filter.colorMatrix([\n 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502,\n -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203,\n -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.technicolor = function () {\n _filter.colorMatrix([\n 1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337,\n -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398,\n -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.polaroid = function () {\n _filter.colorMatrix([\n 1.438, -0.062, -0.062, 0, 0,\n -0.122, 1.378, -0.122, 0, 0,\n -0.016, -0.016, 1.483, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.shiftToBGR = function () {\n _filter.colorMatrix([\n 0, 0, 1, 0, 0,\n 0, 1, 0, 0, 0,\n 1, 0, 0, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n // -------------------------------------------------------------------------\n // Convolution Filter\n\n _filter.convolution = function (matrix) {\n const m = new Float32Array(matrix);\n const pixelSizeX = 1 / _width;\n const pixelSizeY = 1 / _height;\n\n const program = _compileShader(_filter.convolution.SHADER);\n gl.uniform1fv(program.uniform.m, m);\n gl.uniform2f(program.uniform.px, pixelSizeX, pixelSizeY);\n _draw();\n };\n\n _filter.convolution.SHADER = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform vec2 px;',\n 'uniform float m[9];',\n\n 'void main(void) {',\n 'vec4 c11 = texture2D(texture, vUv - px);', // top left\n 'vec4 c12 = texture2D(texture, vec2(vUv.x, vUv.y - px.y));', // top center\n 'vec4 c13 = texture2D(texture, vec2(vUv.x + px.x, vUv.y - px.y));', // top right\n\n 'vec4 c21 = texture2D(texture, vec2(vUv.x - px.x, vUv.y) );', // mid left\n 'vec4 c22 = texture2D(texture, vUv);', // mid center\n 'vec4 c23 = texture2D(texture, vec2(vUv.x + px.x, vUv.y) );', // mid right\n\n 'vec4 c31 = texture2D(texture, vec2(vUv.x - px.x, vUv.y + px.y) );', // bottom left\n 'vec4 c32 = texture2D(texture, vec2(vUv.x, vUv.y + px.y) );', // bottom center\n 'vec4 c33 = texture2D(texture, vUv + px );', // bottom right\n\n 'gl_FragColor = ',\n 'c11 * m[0] + c12 * m[1] + c22 * m[2] +',\n 'c21 * m[3] + c22 * m[4] + c23 * m[5] +',\n 'c31 * m[6] + c32 * m[7] + c33 * m[8];',\n 'gl_FragColor.a = c22.a;',\n '}',\n ].join('\\n');\n\n _filter.detectEdges = function () {\n _filter.convolution.call(this, [\n 0, 1, 0,\n 1, -4, 1,\n 0, 1, 0,\n ]);\n };\n\n _filter.sobelX = function () {\n _filter.convolution.call(this, [\n -1, 0, 1,\n -2, 0, 2,\n -1, 0, 1,\n ]);\n };\n\n _filter.sobelY = function () {\n _filter.convolution.call(this, [\n -1, -2, -1,\n 0, 0, 0,\n 1, 2, 1,\n ]);\n };\n\n _filter.sharpen = function (amount) {\n const a = amount || 1;\n _filter.convolution.call(this, [\n 0, -1 * a, 0,\n -1 * a, 1 + 4 * a, -1 * a,\n 0, -1 * a, 0,\n ]);\n };\n\n _filter.emboss = function (size) {\n const s = size || 1;\n _filter.convolution.call(this, [\n -2 * s, -1 * s, 0,\n -1 * s, 1, 1 * s,\n 0, 1 * s, 2 * s,\n ]);\n };\n\n // -------------------------------------------------------------------------\n // Blur Filter\n\n _filter.blur = function (size) {\n const blurSizeX = (size / 7) / _width;\n const blurSizeY = (size / 7) / _height;\n\n const program = _compileShader(_filter.blur.SHADER);\n\n // Vertical\n gl.uniform2f(program.uniform.px, 0, blurSizeY);\n _draw(DRAW.INTERMEDIATE);\n\n // Horizontal\n gl.uniform2f(program.uniform.px, blurSizeX, 0);\n _draw();\n };\n\n _filter.blur.SHADER = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform vec2 px;',\n\n 'void main(void) {',\n 'gl_FragColor = vec4(0.0);',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-7.0*px.x, -7.0*px.y))*0.0044299121055113265;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-6.0*px.x, -6.0*px.y))*0.00895781211794;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-5.0*px.x, -5.0*px.y))*0.0215963866053;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-4.0*px.x, -4.0*px.y))*0.0443683338718;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-3.0*px.x, -3.0*px.y))*0.0776744219933;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-2.0*px.x, -2.0*px.y))*0.115876621105;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-1.0*px.x, -1.0*px.y))*0.147308056121;',\n 'gl_FragColor += texture2D(texture, vUv )*0.159576912161;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 1.0*px.x, 1.0*px.y))*0.147308056121;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 2.0*px.x, 2.0*px.y))*0.115876621105;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 3.0*px.x, 3.0*px.y))*0.0776744219933;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 4.0*px.x, 4.0*px.y))*0.0443683338718;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 5.0*px.x, 5.0*px.y))*0.0215963866053;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 6.0*px.x, 6.0*px.y))*0.00895781211794;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 7.0*px.x, 7.0*px.y))*0.0044299121055113265;',\n '}',\n ].join('\\n');\n\n // -------------------------------------------------------------------------\n // Pixelate Filter\n\n _filter.pixelate = function (size) {\n const blurSizeX = (size) / _width;\n const blurSizeY = (size) / _height;\n\n const program = _compileShader(_filter.pixelate.SHADER);\n\n // Horizontal\n gl.uniform2f(program.uniform.size, blurSizeX, blurSizeY);\n _draw();\n };\n\n _filter.pixelate.SHADER = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform vec2 size;',\n 'uniform sampler2D texture;',\n\n 'vec2 pixelate(vec2 coord, vec2 size) {',\n 'return floor( coord / size ) * size;',\n '}',\n\n 'void main(void) {',\n 'gl_FragColor = vec4(0.0);',\n 'vec2 coord = pixelate(vUv, size);',\n 'gl_FragColor += texture2D(texture, coord);',\n '}',\n ].join('\\n');\n};\n\nexports.Canvas = WebGLImageFilter;\n", "/* eslint-disable indent */\n/* eslint-disable no-multi-spaces */\n\nexport default {\n backend: 'webgl', // select tfjs backend to use\n console: true, // enable debugging output to console\n scoped: false, // enable scoped runs\n // some models *may* have memory leaks, this wrapps everything in a local scope at a cost of performance\n // typically not needed\n videoOptimized: true, // perform additional optimizations when input is video, must be disabled for images\n filter: {\n enabled: true, // enable image pre-processing filters\n return: true, // return processed canvas imagedata in result\n brightness: 0, // range: -1 (darken) to 1 (lighten)\n contrast: 0, // range: -1 (reduce contrast) to 1 (increase contrast)\n sharpness: 0, // range: 0 (no sharpening) to 1 (maximum sharpening)\n blur: 0, // range: 0 (no blur) to N (blur radius in pixels)\n saturation: 0, // range: -1 (reduce saturation) to 1 (increase saturation)\n hue: 0, // range: 0 (no change) to 360 (hue rotation in degrees)\n negative: false, // image negative\n sepia: false, // image sepia colors\n vintage: false, // image vintage colors\n kodachrome: false, // image kodachrome colors\n technicolor: false, // image technicolor colors\n polaroid: false, // image polaroid camera effect\n pixelate: 0, // range: 0 (no pixelate) to N (number of pixels to pixelate)\n },\n face: {\n enabled: true, // controls if specified modul is enabled\n // face.enabled is required for all face models: detector, mesh, iris, age, gender, emotion\n // (note: module is not loaded until it is required)\n detector: {\n modelPath: '../models/blazeface/back/model.json', // can be 'front' or 'back'.\n // 'front' is optimized for large faces such as front-facing camera and 'back' is optimized for distanct faces.\n inputSize: 256, // fixed value: 128 for front and 256 for 'back'\n maxFaces: 10, // maximum number of faces detected in the input, should be set to the minimum number for performance\n skipFrames: 10, // how many frames to go without re-running the face bounding box detector, only used for video inputs\n // if model is running st 25 FPS, we can re-use existing bounding box for updated face mesh analysis\n // as face probably hasn't moved much in short time (10 * 1/25 = 0.25 sec)\n minConfidence: 0.5, // threshold for discarding a prediction\n iouThreshold: 0.3, // threshold for deciding whether boxes overlap too much in non-maximum suppression\n scoreThreshold: 0.7, // threshold for deciding when to remove boxes based on score in non-maximum suppression\n },\n mesh: {\n enabled: true,\n modelPath: '../models/facemesh/model.json',\n inputSize: 192, // fixed value\n },\n iris: {\n enabled: true,\n modelPath: '../models/iris/model.json',\n enlargeFactor: 2.3, // empiric tuning\n inputSize: 64, // fixed value\n },\n age: {\n enabled: true,\n modelPath: '../models/ssrnet-age/imdb/model.json', // can be 'imdb' or 'wiki'\n // which determines training set for model\n inputSize: 64, // fixed value\n skipFrames: 10, // how many frames to go without re-running the detector, only used for video inputs\n },\n gender: {\n enabled: true,\n minConfidence: 0.8, // threshold for discarding a prediction\n modelPath: '../models/ssrnet-gender/imdb/model.json',\n },\n emotion: {\n enabled: true,\n inputSize: 64, // fixed value\n minConfidence: 0.5, // threshold for discarding a prediction\n skipFrames: 10, // how many frames to go without re-running the detector\n modelPath: '../models/emotion/model.json',\n },\n },\n body: {\n enabled: true,\n modelPath: '../models/posenet/model.json',\n inputResolution: 257, // fixed value\n outputStride: 16, // fixed value\n maxDetections: 10, // maximum number of people detected in the input, should be set to the minimum number for performance\n scoreThreshold: 0.7, // threshold for deciding when to remove boxes based on score in non-maximum suppression\n nmsRadius: 20, // radius for deciding points are too close in non-maximum suppression\n },\n hand: {\n enabled: true,\n inputSize: 256, // fixed value\n skipFrames: 10, // how many frames to go without re-running the hand bounding box detector, only used for video inputs\n // if model is running st 25 FPS, we can re-use existing bounding box for updated hand skeleton analysis\n // as the hand probably hasn't moved much in short time (10 * 1/25 = 0.25 sec)\n minConfidence: 0.5, // threshold for discarding a prediction\n iouThreshold: 0.3, // threshold for deciding whether boxes overlap too much in non-maximum suppression\n scoreThreshold: 0.7, // threshold for deciding when to remove boxes based on score in non-maximum suppression\n enlargeFactor: 1.65, // empiric tuning as skeleton prediction prefers hand box with some whitespace\n maxHands: 10, // maximum number of hands detected in the input, should be set to the minimum number for performance\n detector: {\n anchors: '../models/handdetect/anchors.json',\n modelPath: '../models/handdetect/model.json',\n },\n skeleton: {\n modelPath: '../models/handskeleton/model.json',\n },\n },\n};\n", "const tf = require('@tensorflow/tfjs');\nconst facemesh = require('./facemesh/facemesh.js');\nconst ssrnet = require('./ssrnet/ssrnet.js');\nconst emotion = require('./emotion/emotion.js');\nconst posenet = require('./posenet/posenet.js');\nconst handpose = require('./handpose/handpose.js');\nconst fxImage = require('./imagefx.js');\nconst defaults = require('../config.js').default;\nconst app = require('../package.json');\n\n// static config override for non-video detection\nconst override = {\n face: { detector: { skipFrames: 0 }, age: { skipFrames: 0 }, emotion: { skipFrames: 0 } },\n hand: { skipFrames: 0 },\n};\n\n// helper function: gets elapsed time on both browser and nodejs\nconst now = () => {\n if (typeof performance !== 'undefined') return performance.now();\n return parseInt(Number(process.hrtime.bigint()) / 1000 / 1000);\n};\n\n// helper function: perform deep merge of multiple objects so it allows full inheriance with overrides\nfunction mergeDeep(...objects) {\n const isObject = (obj) => obj && typeof obj === 'object';\n return objects.reduce((prev, obj) => {\n Object.keys(obj || {}).forEach((key) => {\n const pVal = prev[key];\n const oVal = obj[key];\n if (Array.isArray(pVal) && Array.isArray(oVal)) {\n prev[key] = pVal.concat(...oVal);\n } else if (isObject(pVal) && isObject(oVal)) {\n prev[key] = mergeDeep(pVal, oVal);\n } else {\n prev[key] = oVal;\n }\n });\n return prev;\n }, {});\n}\n\nfunction sanity(input) {\n if (!input) return 'input is not defined';\n if (tf.ENV.flags.IS_NODE && !(input instanceof tf.Tensor)) {\n return 'input must be a tensor';\n }\n try {\n tf.getBackend();\n } catch {\n return 'backend not loaded';\n }\n return null;\n}\n\nclass Human {\n constructor() {\n this.tf = tf;\n this.version = app.version;\n this.defaults = defaults;\n this.config = defaults;\n this.fx = (tf.ENV.flags.IS_BROWSER && (typeof document !== 'undefined')) ? new fxImage.Canvas() : null;\n this.state = 'idle';\n this.numTensors = 0;\n this.analyzeMemoryLeaks = false;\n // object that contains all initialized models\n this.models = {\n facemesh: null,\n posenet: null,\n handpose: null,\n iris: null,\n age: null,\n gender: null,\n emotion: null,\n };\n // export raw access to underlying models\n this.facemesh = facemesh;\n this.ssrnet = ssrnet;\n this.emotion = emotion;\n this.posenet = posenet;\n this.handpose = handpose;\n }\n\n // helper function: wrapper around console output\n log(...msg) {\n // eslint-disable-next-line no-console\n if (msg && this.config.console) console.log(...msg);\n }\n\n // helper function: measure tensor leak\n analyze(...msg) {\n if (!this.analyzeMemoryLeaks) return;\n const current = tf.engine().state.numTensors;\n const previous = this.numTensors;\n this.numTensors = current;\n const leaked = current - previous;\n if (leaked !== 0) this.log(...msg, leaked);\n }\n\n async load(userConfig) {\n if (userConfig) this.config = mergeDeep(defaults, userConfig);\n if (this.config.face.enabled && !this.models.facemesh) {\n this.log('Load model: Face');\n this.models.facemesh = await facemesh.load(this.config.face);\n }\n if (this.config.body.enabled && !this.models.posenet) {\n this.log('Load model: Body');\n this.models.posenet = await posenet.load(this.config.body);\n }\n if (this.config.hand.enabled && !this.models.handpose) {\n this.log('Load model: Hand');\n this.models.handpose = await handpose.load(this.config.hand);\n }\n if (this.config.face.enabled && this.config.face.age.enabled && !this.models.age) {\n this.log('Load model: Age');\n this.models.age = await ssrnet.loadAge(this.config);\n }\n if (this.config.face.enabled && this.config.face.gender.enabled && !this.models.gender) {\n this.log('Load model: Gender');\n this.models.gender = await ssrnet.loadGender(this.config);\n }\n if (this.config.face.enabled && this.config.face.emotion.enabled && !this.models.emotion) {\n this.log('Load model: Emotion');\n this.models.emotion = await emotion.load(this.config);\n }\n }\n\n tfImage(input) {\n // let imageData;\n let filtered;\n if (this.fx && this.config.filter.enabled && !(input instanceof tf.Tensor)) {\n const width = input.naturalWidth || input.videoWidth || input.width || (input.shape && (input.shape[1] > 0));\n const height = input.naturalHeight || input.videoHeight || input.height || (input.shape && (input.shape[2] > 0));\n const offscreenCanvas = new OffscreenCanvas(width, height);\n const ctx = offscreenCanvas.getContext('2d');\n if (input instanceof ImageData) ctx.putImageData(input, 0, 0);\n else ctx.drawImage(input, 0, 0, width, height, 0, 0, offscreenCanvas.width, offscreenCanvas.height);\n this.fx.reset();\n this.fx.addFilter('brightness', this.config.filter.brightness); // must have at least one filter enabled\n if (this.config.filter.contrast !== 0) this.fx.addFilter('contrast', this.config.filter.contrast);\n if (this.config.filter.sharpness !== 0) this.fx.addFilter('sharpen', this.config.filter.sharpness);\n if (this.config.filter.blur !== 0) this.fx.addFilter('blur', this.config.filter.blur);\n if (this.config.filter.saturation !== 0) this.fx.addFilter('saturation', this.config.filter.saturation);\n if (this.config.filter.hue !== 0) this.fx.addFilter('hue', this.config.filter.hue);\n if (this.config.filter.negative) this.fx.addFilter('negative');\n if (this.config.filter.sepia) this.fx.addFilter('sepia');\n if (this.config.filter.vintage) this.fx.addFilter('brownie');\n if (this.config.filter.sepia) this.fx.addFilter('sepia');\n if (this.config.filter.kodachrome) this.fx.addFilter('kodachrome');\n if (this.config.filter.technicolor) this.fx.addFilter('technicolor');\n if (this.config.filter.polaroid) this.fx.addFilter('polaroid');\n if (this.config.filter.pixelate !== 0) this.fx.addFilter('pixelate', this.config.filter.pixelate);\n filtered = this.fx.apply(offscreenCanvas);\n }\n let tensor;\n if (input instanceof tf.Tensor) {\n tensor = tf.clone(input);\n } else {\n const pixels = tf.browser.fromPixels(filtered || input);\n const casted = pixels.toFloat();\n tensor = casted.expandDims(0);\n pixels.dispose();\n casted.dispose();\n }\n return { tensor, canvas: this.config.filter.return ? filtered : null };\n }\n\n async detect(input, userConfig = {}) {\n this.state = 'config';\n const perf = {};\n let timeStamp;\n\n timeStamp = now();\n this.config = mergeDeep(defaults, userConfig);\n if (!this.config.videoOptimized) this.config = mergeDeep(this.config, override);\n perf.config = Math.trunc(now() - timeStamp);\n\n // sanity checks\n timeStamp = now();\n this.state = 'check';\n const error = sanity(input);\n if (error) {\n this.log(error, input);\n return { error };\n }\n perf.sanity = Math.trunc(now() - timeStamp);\n\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve) => {\n const timeStart = now();\n\n // configure backend\n timeStamp = now();\n if (tf.getBackend() !== this.config.backend) {\n this.state = 'backend';\n this.log('Human library setting backend:', this.config.backend);\n await tf.setBackend(this.config.backend);\n await tf.ready();\n }\n perf.backend = Math.trunc(now() - timeStamp);\n\n // check number of loaded models\n const loadedModels = Object.values(this.models).filter((a) => a).length;\n if (loadedModels === 0) {\n this.log('Human library starting');\n this.log('Configuration:', this.config);\n this.log('Flags:', tf.ENV.flags);\n }\n\n // load models if enabled\n timeStamp = now();\n this.state = 'load';\n await this.load();\n perf.load = Math.trunc(now() - timeStamp);\n\n if (this.config.scoped) tf.engine().startScope();\n\n this.analyze('Start Detect:');\n\n timeStamp = now();\n const image = this.tfImage(input);\n perf.image = Math.trunc(now() - timeStamp);\n const imageTensor = image.tensor;\n\n // run posenet\n this.state = 'run:body';\n timeStamp = now();\n this.analyze('Start PoseNet');\n const poseRes = this.config.body.enabled ? await this.models.posenet.estimatePoses(imageTensor, this.config.body) : [];\n this.analyze('End PoseNet:');\n perf.body = Math.trunc(now() - timeStamp);\n\n // run handpose\n this.state = 'run:hand';\n timeStamp = now();\n this.analyze('Start HandPose:');\n const handRes = this.config.hand.enabled ? await this.models.handpose.estimateHands(imageTensor, this.config.hand) : [];\n this.analyze('End HandPose:');\n perf.hand = Math.trunc(now() - timeStamp);\n\n // run facemesh, includes blazeface and iris\n const faceRes = [];\n if (this.config.face.enabled) {\n this.state = 'run:face';\n timeStamp = now();\n this.analyze('Start FaceMesh:');\n const faces = await this.models.facemesh.estimateFaces(imageTensor, this.config.face);\n perf.face = Math.trunc(now() - timeStamp);\n for (const face of faces) {\n // is something went wrong, skip the face\n if (!face.image || face.image.isDisposedInternal) {\n this.log('face object is disposed:', face.image);\n continue;\n }\n // run ssr-net age & gender, inherits face from blazeface\n this.state = 'run:agegender';\n timeStamp = now();\n const ssrData = (this.config.face.age.enabled || this.config.face.gender.enabled) ? await ssrnet.predict(face.image, this.config) : {};\n perf.agegender = Math.trunc(now() - timeStamp);\n // run emotion, inherits face from blazeface\n this.state = 'run:emotion';\n timeStamp = now();\n const emotionData = this.config.face.emotion.enabled ? await emotion.predict(face.image, this.config) : {};\n perf.emotion = Math.trunc(now() - timeStamp);\n\n // dont need face anymore\n face.image.dispose();\n // calculate iris distance\n // iris: array[ bottom, left, top, right, center ]\n const iris = (face.annotations.leftEyeIris && face.annotations.rightEyeIris)\n ? Math.max(face.annotations.leftEyeIris[3][0] - face.annotations.leftEyeIris[1][0], face.annotations.rightEyeIris[3][0] - face.annotations.rightEyeIris[1][0])\n : 0;\n faceRes.push({\n confidence: face.confidence,\n box: face.box,\n mesh: face.mesh,\n annotations: face.annotations,\n age: ssrData.age,\n gender: ssrData.gender,\n agConfidence: ssrData.confidence,\n emotion: emotionData,\n iris: (iris !== 0) ? Math.trunc(100 * 11.7 /* human iris size in mm */ / iris) / 100 : 0,\n });\n this.analyze('End FaceMesh:');\n }\n }\n\n imageTensor.dispose();\n this.state = 'idle';\n\n if (this.config.scoped) tf.engine().endScope();\n this.analyze('End Scope:');\n\n perf.total = Math.trunc(now() - timeStart);\n resolve({ face: faceRes, body: poseRes, hand: handRes, performance: perf, canvas: image.canvas });\n });\n }\n}\n\nexport { Human as default };\n"], - "mappings": "mMAAA,mBAAM,GAAK,4BAEL,GAAgB,EAEtB,YAAyB,GACvB,KAAM,GAAO,CAAE,QAAS,CAAC,EAAY,GAAI,EAAY,GAAI,QAAS,CAAC,EAAG,IAChE,EAAU,GAChB,OAAS,GAAI,EAAG,EAAI,EAAK,QAAQ,OAAQ,KACvC,KAAM,GAAS,EAAK,QAAQ,GACtB,EAAW,KAAK,MAAO,GAAY,EAAS,GAAK,GACjD,EAAW,KAAK,MAAO,GAAY,EAAS,GAAK,GACjD,EAAa,EAAK,QAAQ,GAChC,OAAS,GAAQ,EAAG,EAAQ,EAAU,KACpC,KAAM,GAAU,EAAU,GAAQ,IAClC,OAAS,GAAQ,EAAG,EAAQ,EAAU,KACpC,KAAM,GAAU,EAAU,GAAQ,IAClC,OAAS,GAAI,EAAG,EAAI,EAAY,IAC9B,EAAQ,KAAK,CAAC,EAAS,MAK/B,MAAO,GAGT,KAAM,IAAa,AAAC,IAClB,EAAI,eAAe,UACnB,EAAI,WAAW,UACf,EAAI,SAA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AAQ,gBACb,EAAY,IACZ,KAAM,GAAW,KAAK,OAAO,KAAK,IAAI,SAAW,KAAK,OAAO,KAAK,OAAO,QAAW,KAAM,IAAO,QAAQ,EAAK,MAAO,KAAK,QAAU,GACpI,EAAK,UAAY,KAAK,MAAM,IAAQ,GAEpC,KAAK,MAAQ,cACb,EAAY,IACZ,KAAM,GAAc,KAAK,OAAO,KAAK,QAAQ,QAAU,KAAM,IAAQ,QAAQ,EAAK,MAAO,KAAK,QAAU,GACxG,EAAK,QAAU,KAAK,MAAM,IAAQ,GAGlC,EAAK,MAAM,UAGX,KAAM,GAAQ,EAAK,YAAY,aAAe,EAAK,YAAY,aAC3D,KAAK,IAAI,EAAK,YAAY,YAAY,GAAG,GAAK,EAAK,YAAY,YAAY,GAAG,GAAI,EAAK,YAAY,aAAa,GAAG,GAAK,EAAK,YAAY,aAAa,GAAG,IACzJ,EACJ,EAAQ,KAAK,CACX,WAAY,EAAK,WACjB,IAAK,EAAK,IACV,KAAM,EAAK,KACX,YAAa,EAAK,YAClB,IAAK,EAAQ,IACb,OAAQ,EAAQ,OAChB,aAAc,EAAQ,WACtB,QAAS,EACT,KAAO,IAAS,EAAK,KAAK,MAAM,IAAM,KAAmC,GAAQ,IAAM,IAEzF,KAAK,QAAQ,kBAIjB,EAAY,UACZ,KAAK,MAAQ,OAEb,AAAI,KAAK,OAAO,QAAQ,EAAG,SAAS,WACpC,KAAK,QAAQ,cAEb,EAAK,MAAQ,KAAK,MAAM,IAAQ,GAChC,EAAQ,CAAE,KAAM,EAAS,KAAM,EAAS,KAAM,EAAS,YAAa,EAAM,OAAQ,EAAM", + "sourcesContent": ["const tf = require('@tensorflow/tfjs');\n\nconst NUM_LANDMARKS = 6;\n\nfunction generateAnchors(inputSize) {\n const spec = { strides: [inputSize / 16, inputSize / 8], anchors: [2, 6] };\n const anchors = [];\n for (let i = 0; i < spec.strides.length; i++) {\n const stride = spec.strides[i];\n const gridRows = Math.floor((inputSize + stride - 1) / stride);\n const gridCols = Math.floor((inputSize + stride - 1) / stride);\n const anchorsNum = spec.anchors[i];\n for (let gridY = 0; gridY < gridRows; gridY++) {\n const anchorY = stride * (gridY + 0.5);\n for (let gridX = 0; gridX < gridCols; gridX++) {\n const anchorX = stride * (gridX + 0.5);\n for (let n = 0; n < anchorsNum; n++) {\n anchors.push([anchorX, anchorY]);\n }\n }\n }\n }\n return anchors;\n}\n\nconst disposeBox = (box) => {\n box.startEndTensor.dispose();\n box.startPoint.dispose();\n box.endPoint.dispose();\n};\n\nconst createBox = (startEndTensor) => ({\n startEndTensor,\n startPoint: tf.slice(startEndTensor, [0, 0], [-1, 2]),\n endPoint: tf.slice(startEndTensor, [0, 2], [-1, 2]),\n});\n\nconst scaleBox = (box, factors) => {\n const starts = tf.mul(box.startPoint, factors);\n const ends = tf.mul(box.endPoint, factors);\n const newCoordinates = tf.concat2d([starts, ends], 1);\n return createBox(newCoordinates);\n};\n\nfunction decodeBounds(boxOutputs, anchors, inputSize) {\n const boxStarts = tf.slice(boxOutputs, [0, 1], [-1, 2]);\n const centers = tf.add(boxStarts, anchors);\n const boxSizes = tf.slice(boxOutputs, [0, 3], [-1, 2]);\n const boxSizesNormalized = tf.div(boxSizes, inputSize);\n const centersNormalized = tf.div(centers, inputSize);\n const halfBoxSize = tf.div(boxSizesNormalized, 2);\n const starts = tf.sub(centersNormalized, halfBoxSize);\n const ends = tf.add(centersNormalized, halfBoxSize);\n const startNormalized = tf.mul(starts, inputSize);\n const endNormalized = tf.mul(ends, inputSize);\n const concatAxis = 1;\n return tf.concat2d([startNormalized, endNormalized], concatAxis);\n}\n\nfunction scaleBoxFromPrediction(face, scaleFactor) {\n return tf.tidy(() => {\n const box = face['box'] ? face['box'] : face;\n return scaleBox(box, scaleFactor).startEndTensor.squeeze();\n });\n}\n\nclass BlazeFaceModel {\n constructor(model, config) {\n this.blazeFaceModel = model;\n this.width = config.detector.inputSize;\n this.height = config.detector.inputSize;\n this.maxFaces = config.detector.maxFaces;\n this.anchorsData = generateAnchors(config.detector.inputSize);\n this.anchors = tf.tensor2d(this.anchorsData);\n this.inputSize = tf.tensor1d([this.width, this.height]);\n this.iouThreshold = config.detector.iouThreshold;\n this.scaleFaces = 0.8;\n this.scoreThreshold = config.detector.scoreThreshold;\n }\n\n // toto blazeface leaks two tensors per run\n async getBoundingBoxes(inputImage) {\n // sanity check on input\n if ((!inputImage) || (inputImage.isDisposedInternal) || (inputImage.shape.length !== 4) || (inputImage.shape[1] < 1) || (inputImage.shape[2] < 1)) return null;\n const [detectedOutputs, boxes, scores] = tf.tidy(() => {\n const resizedImage = inputImage.resizeBilinear([this.width, this.height]);\n const normalizedImage = tf.mul(tf.sub(resizedImage.div(255), 0.5), 2);\n const batchedPrediction = this.blazeFaceModel.predict(normalizedImage);\n let prediction;\n // are we using tfhub or pinto converted model?\n if (Array.isArray(batchedPrediction)) {\n const sorted = batchedPrediction.sort((a, b) => a.size - b.size);\n const concat384 = tf.concat([sorted[0], sorted[2]], 2); // dim: 384, 1 + 16\n const concat512 = tf.concat([sorted[1], sorted[3]], 2); // dim: 512, 1 + 16\n const concat = tf.concat([concat512, concat384], 1);\n prediction = concat.squeeze(0);\n } else {\n prediction = batchedPrediction.squeeze(); // when using tfhub model\n }\n const decodedBounds = decodeBounds(prediction, this.anchors, this.inputSize);\n const logits = tf.slice(prediction, [0, 0], [-1, 1]);\n const scoresOut = tf.sigmoid(logits).squeeze();\n return [prediction, decodedBounds, scoresOut];\n });\n const boxIndicesTensor = await tf.image.nonMaxSuppressionAsync(boxes, scores, this.maxFaces, this.iouThreshold, this.scoreThreshold);\n const boxIndices = await boxIndicesTensor.array();\n boxIndicesTensor.dispose();\n const boundingBoxesMap = boxIndices.map((boxIndex) => tf.slice(boxes, [boxIndex, 0], [1, -1]));\n const boundingBoxes = await Promise.all(boundingBoxesMap.map(async (boundingBox) => {\n const vals = await boundingBox.array();\n boundingBox.dispose();\n return vals;\n }));\n const annotatedBoxes = [];\n for (let i = 0; i < boundingBoxes.length; i++) {\n const boundingBox = boundingBoxes[i];\n const box = createBox(boundingBox);\n const boxIndex = boxIndices[i];\n const anchor = this.anchorsData[boxIndex];\n const sliced = tf.slice(detectedOutputs, [boxIndex, NUM_LANDMARKS - 1], [1, -1]);\n const squeezed = sliced.squeeze();\n const landmarks = squeezed.reshape([NUM_LANDMARKS, -1]);\n /*\n const landmarks = tf\n .slice(detectedOutputs, [boxIndex, NUM_LANDMARKS - 1], [1, -1])\n .squeeze()\n .reshape([NUM_LANDMARKS, -1]);\n */\n const probability = tf.slice(scores, [boxIndex], [1]);\n const annotatedBox = { box, landmarks, probability, anchor };\n annotatedBoxes.push(annotatedBox);\n sliced.dispose();\n squeezed.dispose();\n // landmarks.dispose();\n }\n detectedOutputs.dispose();\n boxes.dispose();\n scores.dispose();\n detectedOutputs.dispose();\n return {\n boxes: annotatedBoxes,\n scaleFactor: [inputImage.shape[2] / this.width, inputImage.shape[1] / this.height],\n };\n }\n\n async estimateFaces(input) {\n const { boxes, scaleFactor } = await this.getBoundingBoxes(input);\n return Promise.all(boxes.map(async (face) => {\n const scaledBox = scaleBoxFromPrediction(face, scaleFactor);\n const [landmarkData, boxData, probabilityData] = await Promise.all([face.landmarks, scaledBox, face.probability].map(async (d) => d.array()));\n const anchor = face.anchor;\n const [scaleFactorX, scaleFactorY] = scaleFactor;\n const scaledLandmarks = landmarkData\n .map((landmark) => ([\n (landmark[0] + anchor[0]) * scaleFactorX,\n (landmark[1] + anchor[1]) * scaleFactorY,\n ]));\n const normalizedFace = {\n topLeft: boxData.slice(0, 2),\n bottomRight: boxData.slice(2),\n landmarks: scaledLandmarks,\n probability: probabilityData,\n };\n disposeBox(face.box);\n face.landmarks.dispose();\n face.probability.dispose();\n scaledBox.dispose();\n return normalizedFace;\n }));\n }\n}\n\nasync function load(config) {\n const blazeface = await tf.loadGraphModel(config.detector.modelPath, { fromTFHub: config.detector.modelPath.includes('tfhub.dev') });\n const model = new BlazeFaceModel(blazeface, config);\n return model;\n}\n\nexports.load = load;\nexports.BlazeFaceModel = BlazeFaceModel;\nexports.disposeBox = disposeBox;\n", "exports.MESH_ANNOTATIONS = {\n silhouette: [\n 10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288,\n 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136,\n 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109,\n ],\n lipsUpperOuter: [61, 185, 40, 39, 37, 0, 267, 269, 270, 409, 291],\n lipsLowerOuter: [146, 91, 181, 84, 17, 314, 405, 321, 375, 291],\n lipsUpperInner: [78, 191, 80, 81, 82, 13, 312, 311, 310, 415, 308],\n lipsLowerInner: [78, 95, 88, 178, 87, 14, 317, 402, 318, 324, 308],\n rightEyeUpper0: [246, 161, 160, 159, 158, 157, 173],\n rightEyeLower0: [33, 7, 163, 144, 145, 153, 154, 155, 133],\n rightEyeUpper1: [247, 30, 29, 27, 28, 56, 190],\n rightEyeLower1: [130, 25, 110, 24, 23, 22, 26, 112, 243],\n rightEyeUpper2: [113, 225, 224, 223, 222, 221, 189],\n rightEyeLower2: [226, 31, 228, 229, 230, 231, 232, 233, 244],\n rightEyeLower3: [143, 111, 117, 118, 119, 120, 121, 128, 245],\n rightEyebrowUpper: [156, 70, 63, 105, 66, 107, 55, 193],\n rightEyebrowLower: [35, 124, 46, 53, 52, 65],\n rightEyeIris: [473, 474, 475, 476, 477],\n leftEyeUpper0: [466, 388, 387, 386, 385, 384, 398],\n leftEyeLower0: [263, 249, 390, 373, 374, 380, 381, 382, 362],\n leftEyeUpper1: [467, 260, 259, 257, 258, 286, 414],\n leftEyeLower1: [359, 255, 339, 254, 253, 252, 256, 341, 463],\n leftEyeUpper2: [342, 445, 444, 443, 442, 441, 413],\n leftEyeLower2: [446, 261, 448, 449, 450, 451, 452, 453, 464],\n leftEyeLower3: [372, 340, 346, 347, 348, 349, 350, 357, 465],\n leftEyebrowUpper: [383, 300, 293, 334, 296, 336, 285, 417],\n leftEyebrowLower: [265, 353, 276, 283, 282, 295],\n leftEyeIris: [468, 469, 470, 471, 472],\n midwayBetweenEyes: [168],\n noseTip: [1],\n noseBottom: [2],\n noseRightCorner: [98],\n noseLeftCorner: [327],\n rightCheek: [205],\n leftCheek: [425],\n};\nexports.MESH_TO_IRIS_INDICES_MAP = [ // A mapping from facemesh model keypoints to iris model keypoints.\n { key: 'EyeUpper0', indices: [9, 10, 11, 12, 13, 14, 15] },\n { key: 'EyeUpper1', indices: [25, 26, 27, 28, 29, 30, 31] },\n { key: 'EyeUpper2', indices: [41, 42, 43, 44, 45, 46, 47] },\n { key: 'EyeLower0', indices: [0, 1, 2, 3, 4, 5, 6, 7, 8] },\n { key: 'EyeLower1', indices: [16, 17, 18, 19, 20, 21, 22, 23, 24] },\n { key: 'EyeLower2', indices: [32, 33, 34, 35, 36, 37, 38, 39, 40] },\n { key: 'EyeLower3', indices: [54, 55, 56, 57, 58, 59, 60, 61, 62] },\n { key: 'EyebrowUpper', indices: [63, 64, 65, 66, 67, 68, 69, 70] },\n { key: 'EyebrowLower', indices: [48, 49, 50, 51, 52, 53] },\n];\n", "const tf = require('@tensorflow/tfjs');\n\nfunction scaleBoxCoordinates(box, factor) {\n const startPoint = [box.startPoint[0] * factor[0], box.startPoint[1] * factor[1]];\n const endPoint = [box.endPoint[0] * factor[0], box.endPoint[1] * factor[1]];\n return { startPoint, endPoint };\n}\nexports.scaleBoxCoordinates = scaleBoxCoordinates;\nfunction getBoxSize(box) {\n return [\n Math.abs(box.endPoint[0] - box.startPoint[0]),\n Math.abs(box.endPoint[1] - box.startPoint[1]),\n ];\n}\nexports.getBoxSize = getBoxSize;\nfunction getBoxCenter(box) {\n return [\n box.startPoint[0] + (box.endPoint[0] - box.startPoint[0]) / 2,\n box.startPoint[1] + (box.endPoint[1] - box.startPoint[1]) / 2,\n ];\n}\nexports.getBoxCenter = getBoxCenter;\nfunction cutBoxFromImageAndResize(box, image, cropSize) {\n const h = image.shape[1];\n const w = image.shape[2];\n const boxes = [[\n box.startPoint[1] / h, box.startPoint[0] / w, box.endPoint[1] / h,\n box.endPoint[0] / w,\n ]];\n return tf.image.cropAndResize(image, boxes, [0], cropSize);\n}\nexports.cutBoxFromImageAndResize = cutBoxFromImageAndResize;\nfunction enlargeBox(box, factor = 1.5) {\n const center = getBoxCenter(box);\n const size = getBoxSize(box);\n const newHalfSize = [factor * size[0] / 2, factor * size[1] / 2];\n const startPoint = [center[0] - newHalfSize[0], center[1] - newHalfSize[1]];\n const endPoint = [center[0] + newHalfSize[0], center[1] + newHalfSize[1]];\n return { startPoint, endPoint, landmarks: box.landmarks };\n}\nexports.enlargeBox = enlargeBox;\nfunction squarifyBox(box) {\n const centers = getBoxCenter(box);\n const size = getBoxSize(box);\n const maxEdge = Math.max(...size);\n const halfSize = maxEdge / 2;\n const startPoint = [centers[0] - halfSize, centers[1] - halfSize];\n const endPoint = [centers[0] + halfSize, centers[1] + halfSize];\n return { startPoint, endPoint, landmarks: box.landmarks };\n}\nexports.squarifyBox = squarifyBox;\n", "exports.IDENTITY_MATRIX = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];\n/**\n * Normalizes the provided angle to the range -pi to pi.\n * @param angle The angle in radians to be normalized.\n */\nfunction normalizeRadians(angle) {\n return angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));\n}\nexports.normalizeRadians = normalizeRadians;\n/**\n * Computes the angle of rotation between two anchor points.\n * @param point1 First anchor point\n * @param point2 Second anchor point\n */\nfunction computeRotation(point1, point2) {\n const radians = Math.PI / 2 - Math.atan2(-(point2[1] - point1[1]), point2[0] - point1[0]);\n return normalizeRadians(radians);\n}\nexports.computeRotation = computeRotation;\nfunction radToDegrees(rad) {\n return rad * 180 / Math.PI;\n}\nexports.radToDegrees = radToDegrees;\nfunction buildTranslationMatrix(x, y) {\n return [[1, 0, x], [0, 1, y], [0, 0, 1]];\n}\nfunction dot(v1, v2) {\n let product = 0;\n for (let i = 0; i < v1.length; i++) {\n product += v1[i] * v2[i];\n }\n return product;\n}\nexports.dot = dot;\nfunction getColumnFrom2DArr(arr, columnIndex) {\n const column = [];\n for (let i = 0; i < arr.length; i++) {\n column.push(arr[i][columnIndex]);\n }\n return column;\n}\nexports.getColumnFrom2DArr = getColumnFrom2DArr;\nfunction multiplyTransformMatrices(mat1, mat2) {\n const product = [];\n const size = mat1.length;\n for (let row = 0; row < size; row++) {\n product.push([]);\n for (let col = 0; col < size; col++) {\n product[row].push(dot(mat1[row], getColumnFrom2DArr(mat2, col)));\n }\n }\n return product;\n}\nfunction buildRotationMatrix(rotation, center) {\n const cosA = Math.cos(rotation);\n const sinA = Math.sin(rotation);\n const rotationMatrix = [[cosA, -sinA, 0], [sinA, cosA, 0], [0, 0, 1]];\n const translationMatrix = buildTranslationMatrix(center[0], center[1]);\n const translationTimesRotation = multiplyTransformMatrices(translationMatrix, rotationMatrix);\n const negativeTranslationMatrix = buildTranslationMatrix(-center[0], -center[1]);\n return multiplyTransformMatrices(translationTimesRotation, negativeTranslationMatrix);\n}\nexports.buildRotationMatrix = buildRotationMatrix;\nfunction invertTransformMatrix(matrix) {\n const rotationComponent = [[matrix[0][0], matrix[1][0]], [matrix[0][1], matrix[1][1]]];\n const translationComponent = [matrix[0][2], matrix[1][2]];\n const invertedTranslation = [\n -dot(rotationComponent[0], translationComponent),\n -dot(rotationComponent[1], translationComponent),\n ];\n return [\n rotationComponent[0].concat(invertedTranslation[0]),\n rotationComponent[1].concat(invertedTranslation[1]),\n [0, 0, 1],\n ];\n}\nexports.invertTransformMatrix = invertTransformMatrix;\nfunction rotatePoint(homogeneousCoordinate, rotationMatrix) {\n return [\n dot(homogeneousCoordinate, rotationMatrix[0]),\n dot(homogeneousCoordinate, rotationMatrix[1]),\n ];\n}\nexports.rotatePoint = rotatePoint;\nfunction xyDistanceBetweenPoints(a, b) {\n return Math.sqrt(((a[0] - b[0]) ** 2) + ((a[1] - b[1]) ** 2));\n}\nexports.xyDistanceBetweenPoints = xyDistanceBetweenPoints;\n", "/* eslint-disable class-methods-use-this */\nconst tf = require('@tensorflow/tfjs');\nconst bounding = require('./box');\nconst keypoints = require('./keypoints');\nconst util = require('./util');\n\nconst LANDMARKS_COUNT = 468;\nconst UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD = 0.25;\nconst MESH_MOUTH_INDEX = 13;\nconst MESH_KEYPOINTS_LINE_OF_SYMMETRY_INDICES = [MESH_MOUTH_INDEX, keypoints.MESH_ANNOTATIONS['midwayBetweenEyes'][0]];\nconst BLAZEFACE_MOUTH_INDEX = 3;\nconst BLAZEFACE_NOSE_INDEX = 2;\nconst BLAZEFACE_KEYPOINTS_LINE_OF_SYMMETRY_INDICES = [BLAZEFACE_MOUTH_INDEX, BLAZEFACE_NOSE_INDEX];\nconst LEFT_EYE_OUTLINE = keypoints.MESH_ANNOTATIONS['leftEyeLower0'];\nconst LEFT_EYE_BOUNDS = [LEFT_EYE_OUTLINE[0], LEFT_EYE_OUTLINE[LEFT_EYE_OUTLINE.length - 1]];\nconst RIGHT_EYE_OUTLINE = keypoints.MESH_ANNOTATIONS['rightEyeLower0'];\nconst RIGHT_EYE_BOUNDS = [RIGHT_EYE_OUTLINE[0], RIGHT_EYE_OUTLINE[RIGHT_EYE_OUTLINE.length - 1]];\nconst IRIS_UPPER_CENTER_INDEX = 3;\nconst IRIS_LOWER_CENTER_INDEX = 4;\nconst IRIS_IRIS_INDEX = 71;\nconst IRIS_NUM_COORDINATES = 76;\n\n// Replace the raw coordinates returned by facemesh with refined iris model coordinates. Update the z coordinate to be an average of the original and the new. This produces the best visual effect.\nfunction replaceRawCoordinates(rawCoords, newCoords, prefix, keys) {\n for (let i = 0; i < keypoints.MESH_TO_IRIS_INDICES_MAP.length; i++) {\n const { key, indices } = keypoints.MESH_TO_IRIS_INDICES_MAP[i];\n const originalIndices = keypoints.MESH_ANNOTATIONS[`${prefix}${key}`];\n const shouldReplaceAllKeys = keys == null;\n if (shouldReplaceAllKeys || keys.includes(key)) {\n for (let j = 0; j < indices.length; j++) {\n const index = indices[j];\n rawCoords[originalIndices[j]] = [\n newCoords[index][0], newCoords[index][1],\n (newCoords[index][2] + rawCoords[originalIndices[j]][2]) / 2,\n ];\n }\n }\n }\n}\n// The Pipeline coordinates between the bounding box and skeleton models.\nclass Pipeline {\n constructor(boundingBoxDetector, meshDetector, irisModel, config) {\n // An array of facial bounding boxes.\n this.regionsOfInterest = [];\n this.runsWithoutFaceDetector = 0;\n this.boundingBoxDetector = boundingBoxDetector;\n this.meshDetector = meshDetector;\n this.irisModel = irisModel;\n this.meshWidth = config.mesh.inputSize;\n this.meshHeight = config.mesh.inputSize;\n this.irisSize = config.iris.inputSize;\n this.irisEnlarge = config.iris.enlargeFactor;\n }\n\n transformRawCoords(rawCoords, box, angle, rotationMatrix) {\n const boxSize = bounding.getBoxSize({ startPoint: box.startPoint, endPoint: box.endPoint });\n const scaleFactor = [boxSize[0] / this.meshWidth, boxSize[1] / this.meshHeight];\n const coordsScaled = rawCoords.map((coord) => ([\n scaleFactor[0] * (coord[0] - this.meshWidth / 2),\n scaleFactor[1] * (coord[1] - this.meshHeight / 2), coord[2],\n ]));\n const coordsRotationMatrix = util.buildRotationMatrix(angle, [0, 0]);\n const coordsRotated = coordsScaled.map((coord) => ([...util.rotatePoint(coord, coordsRotationMatrix), coord[2]]));\n const inverseRotationMatrix = util.invertTransformMatrix(rotationMatrix);\n const boxCenter = [...bounding.getBoxCenter({ startPoint: box.startPoint, endPoint: box.endPoint }), 1];\n const originalBoxCenter = [\n util.dot(boxCenter, inverseRotationMatrix[0]),\n util.dot(boxCenter, inverseRotationMatrix[1]),\n ];\n return coordsRotated.map((coord) => ([\n coord[0] + originalBoxCenter[0],\n coord[1] + originalBoxCenter[1], coord[2],\n ]));\n }\n\n getLeftToRightEyeDepthDifference(rawCoords) {\n const leftEyeZ = rawCoords[LEFT_EYE_BOUNDS[0]][2];\n const rightEyeZ = rawCoords[RIGHT_EYE_BOUNDS[0]][2];\n return leftEyeZ - rightEyeZ;\n }\n\n // Returns a box describing a cropped region around the eye fit for passing to the iris model.\n getEyeBox(rawCoords, face, eyeInnerCornerIndex, eyeOuterCornerIndex, flip = false) {\n const box = bounding.squarifyBox(bounding.enlargeBox(this.calculateLandmarksBoundingBox([rawCoords[eyeInnerCornerIndex], rawCoords[eyeOuterCornerIndex]]), this.irisEnlarge));\n const boxSize = bounding.getBoxSize(box);\n let crop = tf.image.cropAndResize(face, [[\n box.startPoint[1] / this.meshHeight,\n box.startPoint[0] / this.meshWidth, box.endPoint[1] / this.meshHeight,\n box.endPoint[0] / this.meshWidth,\n ]], [0], [this.irisSize, this.irisSize]);\n if (flip) {\n crop = tf.image.flipLeftRight(crop);\n }\n return { box, boxSize, crop };\n }\n\n // Given a cropped image of an eye, returns the coordinates of the contours surrounding the eye and the iris.\n getEyeCoords(eyeData, eyeBox, eyeBoxSize, flip = false) {\n const eyeRawCoords = [];\n for (let i = 0; i < IRIS_NUM_COORDINATES; i++) {\n const x = eyeData[i * 3];\n const y = eyeData[i * 3 + 1];\n const z = eyeData[i * 3 + 2];\n eyeRawCoords.push([\n (flip\n ? (1 - (x / this.irisSize))\n : (x / this.irisSize)) * eyeBoxSize[0] + eyeBox.startPoint[0],\n (y / this.irisSize) * eyeBoxSize[1] + eyeBox.startPoint[1], z,\n ]);\n }\n return { rawCoords: eyeRawCoords, iris: eyeRawCoords.slice(IRIS_IRIS_INDEX) };\n }\n\n // The z-coordinates returned for the iris are unreliable, so we take the z values from the surrounding keypoints.\n getAdjustedIrisCoords(rawCoords, irisCoords, direction) {\n const upperCenterZ = rawCoords[keypoints.MESH_ANNOTATIONS[`${direction}EyeUpper0`][IRIS_UPPER_CENTER_INDEX]][2];\n const lowerCenterZ = rawCoords[keypoints.MESH_ANNOTATIONS[`${direction}EyeLower0`][IRIS_LOWER_CENTER_INDEX]][2];\n const averageZ = (upperCenterZ + lowerCenterZ) / 2;\n // Iris indices: 0: center | 1: right | 2: above | 3: left | 4: below\n return irisCoords.map((coord, i) => {\n let z = averageZ;\n if (i === 2) {\n z = upperCenterZ;\n } else if (i === 4) {\n z = lowerCenterZ;\n }\n return [coord[0], coord[1], z];\n });\n }\n\n async predict(input, config) {\n this.skipFrames = config.detector.skipFrames;\n this.maxFaces = config.detector.maxFaces;\n this.runsWithoutFaceDetector++;\n if (this.shouldUpdateRegionsOfInterest()) {\n const detector = await this.boundingBoxDetector.getBoundingBoxes(input);\n if (detector.boxes.length === 0) {\n this.regionsOfInterest = [];\n return null;\n }\n const scaledBoxes = detector.boxes.map((prediction) => {\n const startPoint = prediction.box.startPoint.squeeze();\n const endPoint = prediction.box.endPoint.squeeze();\n const predictionBox = {\n startPoint: startPoint.arraySync(),\n endPoint: endPoint.arraySync(),\n };\n startPoint.dispose();\n endPoint.dispose();\n const scaledBox = bounding.scaleBoxCoordinates(predictionBox, detector.scaleFactor);\n const enlargedBox = bounding.enlargeBox(scaledBox);\n const landmarks = prediction.landmarks.arraySync();\n prediction.box.startPoint.dispose();\n prediction.box.endPoint.dispose();\n prediction.landmarks.dispose();\n prediction.probability.dispose();\n return { ...enlargedBox, landmarks };\n });\n this.updateRegionsOfInterest(scaledBoxes);\n this.runsWithoutFaceDetector = 0;\n }\n const results = tf.tidy(() => this.regionsOfInterest.map((box, i) => {\n let angle = 0;\n // The facial bounding box landmarks could come either from blazeface (if we are using a fresh box), or from the mesh model (if we are reusing an old box).\n const boxLandmarksFromMeshModel = box.landmarks.length >= LANDMARKS_COUNT;\n let [indexOfMouth, indexOfForehead] = MESH_KEYPOINTS_LINE_OF_SYMMETRY_INDICES;\n if (boxLandmarksFromMeshModel === false) {\n [indexOfMouth, indexOfForehead] = BLAZEFACE_KEYPOINTS_LINE_OF_SYMMETRY_INDICES;\n }\n angle = util.computeRotation(box.landmarks[indexOfMouth], box.landmarks[indexOfForehead]);\n const faceCenter = bounding.getBoxCenter({ startPoint: box.startPoint, endPoint: box.endPoint });\n const faceCenterNormalized = [faceCenter[0] / input.shape[2], faceCenter[1] / input.shape[1]];\n let rotatedImage = input;\n let rotationMatrix = util.IDENTITY_MATRIX;\n if (angle !== 0) {\n rotatedImage = tf.image.rotateWithOffset(input, angle, 0, faceCenterNormalized);\n rotationMatrix = util.buildRotationMatrix(-angle, faceCenter);\n }\n const boxCPU = { startPoint: box.startPoint, endPoint: box.endPoint };\n const face = bounding.cutBoxFromImageAndResize(boxCPU, rotatedImage, [this.meshHeight, this.meshWidth]).div(255);\n // The first returned tensor represents facial contours, which are included in the coordinates.\n const [, flag, coords] = this.meshDetector.predict(face);\n const coordsReshaped = tf.reshape(coords, [-1, 3]);\n let rawCoords = coordsReshaped.arraySync();\n if (config.iris.enabled) {\n const { box: leftEyeBox, boxSize: leftEyeBoxSize, crop: leftEyeCrop } = this.getEyeBox(rawCoords, face, LEFT_EYE_BOUNDS[0], LEFT_EYE_BOUNDS[1], true);\n const { box: rightEyeBox, boxSize: rightEyeBoxSize, crop: rightEyeCrop } = this.getEyeBox(rawCoords, face, RIGHT_EYE_BOUNDS[0], RIGHT_EYE_BOUNDS[1]);\n const eyePredictions = (this.irisModel.predict(tf.concat([leftEyeCrop, rightEyeCrop])));\n const eyePredictionsData = eyePredictions.dataSync();\n eyePredictions.dispose();\n const leftEyeData = eyePredictionsData.slice(0, IRIS_NUM_COORDINATES * 3);\n const { rawCoords: leftEyeRawCoords, iris: leftIrisRawCoords } = this.getEyeCoords(leftEyeData, leftEyeBox, leftEyeBoxSize, true);\n const rightEyeData = eyePredictionsData.slice(IRIS_NUM_COORDINATES * 3);\n const { rawCoords: rightEyeRawCoords, iris: rightIrisRawCoords } = this.getEyeCoords(rightEyeData, rightEyeBox, rightEyeBoxSize);\n const leftToRightEyeDepthDifference = this.getLeftToRightEyeDepthDifference(rawCoords);\n if (Math.abs(leftToRightEyeDepthDifference) < 30) { // User is looking straight ahead.\n replaceRawCoordinates(rawCoords, leftEyeRawCoords, 'left');\n replaceRawCoordinates(rawCoords, rightEyeRawCoords, 'right');\n // If the user is looking to the left or to the right, the iris coordinates tend to diverge too much from the mesh coordinates for them to be merged. So we only update a single contour line above and below the eye.\n } else if (leftToRightEyeDepthDifference < 1) { // User is looking towards the right.\n replaceRawCoordinates(rawCoords, leftEyeRawCoords, 'left', ['EyeUpper0', 'EyeLower0']);\n } else { // User is looking towards the left.\n replaceRawCoordinates(rawCoords, rightEyeRawCoords, 'right', ['EyeUpper0', 'EyeLower0']);\n }\n const adjustedLeftIrisCoords = this.getAdjustedIrisCoords(rawCoords, leftIrisRawCoords, 'left');\n const adjustedRightIrisCoords = this.getAdjustedIrisCoords(rawCoords, rightIrisRawCoords, 'right');\n rawCoords = rawCoords.concat(adjustedLeftIrisCoords).concat(adjustedRightIrisCoords);\n }\n const transformedCoordsData = this.transformRawCoords(rawCoords, box, angle, rotationMatrix);\n tf.dispose(rawCoords);\n const landmarksBox = bounding.enlargeBox(this.calculateLandmarksBoundingBox(transformedCoordsData));\n const confidence = flag.squeeze();\n tf.dispose(flag);\n if (config.mesh.enabled) {\n const transformedCoords = tf.tensor2d(transformedCoordsData);\n this.regionsOfInterest[i] = { ...landmarksBox, landmarks: transformedCoords.arraySync() };\n const prediction = {\n coords: transformedCoords,\n box: landmarksBox,\n confidence,\n image: face,\n };\n return prediction;\n }\n const prediction = {\n coords: null,\n box: landmarksBox,\n confidence,\n image: face,\n };\n return prediction;\n }));\n return results;\n }\n\n // Updates regions of interest if the intersection over union between the incoming and previous regions falls below a threshold.\n updateRegionsOfInterest(boxes) {\n for (let i = 0; i < boxes.length; i++) {\n const box = boxes[i];\n const previousBox = this.regionsOfInterest[i];\n let iou = 0;\n if (previousBox && previousBox.startPoint) {\n const [boxStartX, boxStartY] = box.startPoint;\n const [boxEndX, boxEndY] = box.endPoint;\n const [previousBoxStartX, previousBoxStartY] = previousBox.startPoint;\n const [previousBoxEndX, previousBoxEndY] = previousBox.endPoint;\n const xStartMax = Math.max(boxStartX, previousBoxStartX);\n const yStartMax = Math.max(boxStartY, previousBoxStartY);\n const xEndMin = Math.min(boxEndX, previousBoxEndX);\n const yEndMin = Math.min(boxEndY, previousBoxEndY);\n const intersection = (xEndMin - xStartMax) * (yEndMin - yStartMax);\n const boxArea = (boxEndX - boxStartX) * (boxEndY - boxStartY);\n const previousBoxArea = (previousBoxEndX - previousBoxStartX) * (previousBoxEndY - boxStartY);\n iou = intersection / (boxArea + previousBoxArea - intersection);\n }\n if (iou < UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD) {\n this.regionsOfInterest[i] = box;\n }\n }\n this.regionsOfInterest = this.regionsOfInterest.slice(0, boxes.length);\n }\n\n clearRegionOfInterest(index) {\n if (this.regionsOfInterest[index] != null) {\n this.regionsOfInterest = [\n ...this.regionsOfInterest.slice(0, index),\n ...this.regionsOfInterest.slice(index + 1),\n ];\n }\n }\n\n shouldUpdateRegionsOfInterest() {\n if (this.regionsOfInterest.length === 0) return true; // nothing detected, so run detector on the next frame\n return (this.regionsOfInterest.length !== this.maxFaces) && (this.runsWithoutFaceDetector >= this.skipFrames);\n }\n\n calculateLandmarksBoundingBox(landmarks) {\n const xs = landmarks.map((d) => d[0]);\n const ys = landmarks.map((d) => d[1]);\n const startPoint = [Math.min(...xs), Math.min(...ys)];\n const endPoint = [Math.max(...xs), Math.max(...ys)];\n return { startPoint, endPoint, landmarks };\n }\n}\nexports.Pipeline = Pipeline;\n", "exports.UV_COORDS = [\n [0.499976992607117, 0.652534008026123],\n [0.500025987625122, 0.547487020492554],\n [0.499974012374878, 0.602371990680695],\n [0.482113003730774, 0.471979022026062],\n [0.500150978565216, 0.527155995368958],\n [0.499909996986389, 0.498252987861633],\n [0.499523013830185, 0.40106201171875],\n [0.289712011814117, 0.380764007568359],\n [0.499954998493195, 0.312398016452789],\n [0.499987006187439, 0.269918978214264],\n [0.500023007392883, 0.107050001621246],\n [0.500023007392883, 0.666234016418457],\n [0.5000159740448, 0.679224014282227],\n [0.500023007392883, 0.692348003387451],\n [0.499976992607117, 0.695277988910675],\n [0.499976992607117, 0.70593398809433],\n [0.499976992607117, 0.719385027885437],\n [0.499976992607117, 0.737019002437592],\n [0.499967992305756, 0.781370997428894],\n [0.499816000461578, 0.562981009483337],\n [0.473773002624512, 0.573909997940063],\n [0.104906998574734, 0.254140973091125],\n [0.365929991006851, 0.409575998783112],\n [0.338757991790771, 0.41302502155304],\n [0.311120003461838, 0.409460008144379],\n [0.274657994508743, 0.389131009578705],\n [0.393361985683441, 0.403706014156342],\n [0.345234006643295, 0.344011008739471],\n [0.370094001293182, 0.346076011657715],\n [0.319321990013123, 0.347265005111694],\n [0.297903001308441, 0.353591024875641],\n [0.24779200553894, 0.410809993743896],\n [0.396889001131058, 0.842755019664764],\n [0.280097991228104, 0.375599980354309],\n [0.106310002505779, 0.399955987930298],\n [0.2099249958992, 0.391353011131287],\n [0.355807989835739, 0.534406006336212],\n [0.471751004457474, 0.65040397644043],\n [0.474155008792877, 0.680191993713379],\n [0.439785003662109, 0.657229006290436],\n [0.414617002010345, 0.66654098033905],\n [0.450374007225037, 0.680860996246338],\n [0.428770989179611, 0.682690978050232],\n [0.374971002340317, 0.727805018424988],\n [0.486716985702515, 0.547628998756409],\n [0.485300987958908, 0.527395009994507],\n [0.257764995098114, 0.314490020275116],\n [0.401223003864288, 0.455172002315521],\n [0.429818987846375, 0.548614978790283],\n [0.421351999044418, 0.533740997314453],\n [0.276895999908447, 0.532056987285614],\n [0.483370006084442, 0.499586999416351],\n [0.33721199631691, 0.282882988452911],\n [0.296391993761063, 0.293242990970612],\n [0.169294998049736, 0.193813979625702],\n [0.447580009698868, 0.302609980106354],\n [0.392390012741089, 0.353887975215912],\n [0.354490011930466, 0.696784019470215],\n [0.067304998636246, 0.730105042457581],\n [0.442739009857178, 0.572826027870178],\n [0.457098007202148, 0.584792017936707],\n [0.381974011659622, 0.694710969924927],\n [0.392388999462128, 0.694203019142151],\n [0.277076005935669, 0.271932005882263],\n [0.422551989555359, 0.563233017921448],\n [0.385919004678726, 0.281364023685455],\n [0.383103013038635, 0.255840003490448],\n [0.331431001424789, 0.119714021682739],\n [0.229923993349075, 0.232002973556519],\n [0.364500999450684, 0.189113974571228],\n [0.229622006416321, 0.299540996551514],\n [0.173287004232407, 0.278747975826263],\n [0.472878992557526, 0.666198015213013],\n [0.446828007698059, 0.668527007102966],\n [0.422762006521225, 0.673889994621277],\n [0.445307999849319, 0.580065965652466],\n [0.388103008270264, 0.693961024284363],\n [0.403039008378983, 0.706539988517761],\n [0.403629004955292, 0.693953037261963],\n [0.460041999816895, 0.557139039039612],\n [0.431158006191254, 0.692366003990173],\n [0.452181994915009, 0.692366003990173],\n [0.475387006998062, 0.692366003990173],\n [0.465828001499176, 0.779190003871918],\n [0.472328990697861, 0.736225962638855],\n [0.473087012767792, 0.717857003211975],\n [0.473122000694275, 0.704625964164734],\n [0.473033010959625, 0.695277988910675],\n [0.427942007780075, 0.695277988910675],\n [0.426479011774063, 0.703539967536926],\n [0.423162013292313, 0.711845993995667],\n [0.4183090031147, 0.720062971115112],\n [0.390094995498657, 0.639572978019714],\n [0.013953999616206, 0.560034036636353],\n [0.499913990497589, 0.58014702796936],\n [0.413199990987778, 0.69539999961853],\n [0.409626007080078, 0.701822996139526],\n [0.468080013990402, 0.601534962654114],\n [0.422728985548019, 0.585985004901886],\n [0.463079988956451, 0.593783974647522],\n [0.37211999297142, 0.47341400384903],\n [0.334562003612518, 0.496073007583618],\n [0.411671012639999, 0.546965003013611],\n [0.242175996303558, 0.14767599105835],\n [0.290776997804642, 0.201445996761322],\n [0.327338010072708, 0.256527006626129],\n [0.399509996175766, 0.748921036720276],\n [0.441727995872498, 0.261676013469696],\n [0.429764986038208, 0.187834024429321],\n [0.412198007106781, 0.108901023864746],\n [0.288955003023148, 0.398952007293701],\n [0.218936994671822, 0.435410976409912],\n [0.41278201341629, 0.398970007896423],\n [0.257135003805161, 0.355440020561218],\n [0.427684992551804, 0.437960982322693],\n [0.448339998722076, 0.536936044692993],\n [0.178560003638268, 0.45755398273468],\n [0.247308000922203, 0.457193970680237],\n [0.286267012357712, 0.467674970626831],\n [0.332827985286713, 0.460712015628815],\n [0.368755996227264, 0.447206974029541],\n [0.398963987827301, 0.432654976844788],\n [0.476410001516342, 0.405806005001068],\n [0.189241006970406, 0.523923993110657],\n [0.228962004184723, 0.348950982093811],\n [0.490725994110107, 0.562400996685028],\n [0.404670000076294, 0.485132992267609],\n [0.019469000399113, 0.401564002037048],\n [0.426243007183075, 0.420431017875671],\n [0.396993011236191, 0.548797011375427],\n [0.266469985246658, 0.376977026462555],\n [0.439121007919312, 0.51895797252655],\n [0.032313998788595, 0.644356966018677],\n [0.419054001569748, 0.387154996395111],\n [0.462783008813858, 0.505746960639954],\n [0.238978996872902, 0.779744982719421],\n [0.198220998048782, 0.831938028335571],\n [0.107550002634525, 0.540755033493042],\n [0.183610007166862, 0.740257024765015],\n [0.134409993886948, 0.333683013916016],\n [0.385764002799988, 0.883153975009918],\n [0.490967005491257, 0.579378008842468],\n [0.382384985685349, 0.508572995662689],\n [0.174399003386497, 0.397670984268188],\n [0.318785011768341, 0.39623498916626],\n [0.343364000320435, 0.400596976280212],\n [0.396100014448166, 0.710216999053955],\n [0.187885001301765, 0.588537991046906],\n [0.430987000465393, 0.944064974784851],\n [0.318993002176285, 0.898285031318665],\n [0.266247987747192, 0.869701027870178],\n [0.500023007392883, 0.190576016902924],\n [0.499976992607117, 0.954452991485596],\n [0.366169989109039, 0.398822009563446],\n [0.393207013607025, 0.39553701877594],\n [0.410373002290726, 0.391080021858215],\n [0.194993004202843, 0.342101991176605],\n [0.388664990663528, 0.362284004688263],\n [0.365961998701096, 0.355970978736877],\n [0.343364000320435, 0.355356991291046],\n [0.318785011768341, 0.35834002494812],\n [0.301414996385574, 0.363156020641327],\n [0.058132998645306, 0.319076001644135],\n [0.301414996385574, 0.387449026107788],\n [0.499987989664078, 0.618434011936188],\n [0.415838003158569, 0.624195992946625],\n [0.445681989192963, 0.566076993942261],\n [0.465844005346298, 0.620640993118286],\n [0.49992299079895, 0.351523995399475],\n [0.288718998432159, 0.819945991039276],\n [0.335278987884521, 0.852819979190826],\n [0.440512001514435, 0.902418971061707],\n [0.128294005990028, 0.791940987110138],\n [0.408771991729736, 0.373893976211548],\n [0.455606997013092, 0.451801002025604],\n [0.499877005815506, 0.908990025520325],\n [0.375436991453171, 0.924192011356354],\n [0.11421000212431, 0.615022003650665],\n [0.448662012815475, 0.695277988910675],\n [0.4480200111866, 0.704632043838501],\n [0.447111994028091, 0.715808033943176],\n [0.444831997156143, 0.730794012546539],\n [0.430011987686157, 0.766808986663818],\n [0.406787008047104, 0.685672998428345],\n [0.400738000869751, 0.681069016456604],\n [0.392399996519089, 0.677703022956848],\n [0.367855995893478, 0.663918972015381],\n [0.247923001646996, 0.601333022117615],\n [0.452769994735718, 0.420849978923798],\n [0.43639200925827, 0.359887003898621],\n [0.416164010763168, 0.368713974952698],\n [0.413385987281799, 0.692366003990173],\n [0.228018000721931, 0.683571994304657],\n [0.468268007040024, 0.352671027183533],\n [0.411361992359161, 0.804327011108398],\n [0.499989002943039, 0.469825029373169],\n [0.479153990745544, 0.442654013633728],\n [0.499974012374878, 0.439637005329132],\n [0.432112008333206, 0.493588984012604],\n [0.499886006116867, 0.866917014122009],\n [0.49991300702095, 0.821729004383087],\n [0.456548988819122, 0.819200992584229],\n [0.344549000263214, 0.745438992977142],\n [0.37890899181366, 0.574010014533997],\n [0.374292999505997, 0.780184984207153],\n [0.319687992334366, 0.570737957954407],\n [0.357154995203018, 0.604269981384277],\n [0.295284003019333, 0.621580958366394],\n [0.447750002145767, 0.862477004528046],\n [0.410986006259918, 0.508723020553589],\n [0.31395098567009, 0.775308012962341],\n [0.354128003120422, 0.812552988529205],\n [0.324548006057739, 0.703992962837219],\n [0.189096003770828, 0.646299958229065],\n [0.279776990413666, 0.71465802192688],\n [0.1338230073452, 0.682700991630554],\n [0.336768001317978, 0.644733011722565],\n [0.429883986711502, 0.466521978378296],\n [0.455527991056442, 0.548622965812683],\n [0.437114000320435, 0.558896005153656],\n [0.467287987470627, 0.529924988746643],\n [0.414712011814117, 0.335219979286194],\n [0.37704598903656, 0.322777986526489],\n [0.344107985496521, 0.320150971412659],\n [0.312875986099243, 0.32233202457428],\n [0.283526003360748, 0.333190023899078],\n [0.241245999932289, 0.382785975933075],\n [0.102986000478268, 0.468762993812561],\n [0.267612010240555, 0.424560010433197],\n [0.297879010438919, 0.433175981044769],\n [0.333433985710144, 0.433878004550934],\n [0.366427004337311, 0.426115989685059],\n [0.396012008190155, 0.416696012020111],\n [0.420121014118195, 0.41022801399231],\n [0.007561000064015, 0.480777025222778],\n [0.432949006557465, 0.569517970085144],\n [0.458638995885849, 0.479089021682739],\n [0.473466008901596, 0.545744001865387],\n [0.476087987422943, 0.563830018043518],\n [0.468472003936768, 0.555056989192963],\n [0.433990985155106, 0.582361996173859],\n [0.483518004417419, 0.562983989715576],\n [0.482482999563217, 0.57784903049469],\n [0.42645001411438, 0.389798998832703],\n [0.438998997211456, 0.39649498462677],\n [0.450067013502121, 0.400434017181396],\n [0.289712011814117, 0.368252992630005],\n [0.276670008897781, 0.363372981548309],\n [0.517862021923065, 0.471948027610779],\n [0.710287988185883, 0.380764007568359],\n [0.526226997375488, 0.573909997940063],\n [0.895093023777008, 0.254140973091125],\n [0.634069979190826, 0.409575998783112],\n [0.661242008209229, 0.41302502155304],\n [0.688880026340485, 0.409460008144379],\n [0.725341975688934, 0.389131009578705],\n [0.606630027294159, 0.40370500087738],\n [0.654766023159027, 0.344011008739471],\n [0.629905998706818, 0.346076011657715],\n [0.680678009986877, 0.347265005111694],\n [0.702096998691559, 0.353591024875641],\n [0.75221198797226, 0.410804986953735],\n [0.602918028831482, 0.842862963676453],\n [0.719901978969574, 0.375599980354309],\n [0.893692970275879, 0.399959981441498],\n [0.790081977844238, 0.391354024410248],\n [0.643998026847839, 0.534487962722778],\n [0.528249025344849, 0.65040397644043],\n [0.525849997997284, 0.680191040039062],\n [0.560214996337891, 0.657229006290436],\n [0.585384011268616, 0.66654098033905],\n [0.549625992774963, 0.680860996246338],\n [0.57122802734375, 0.682691991329193],\n [0.624852001667023, 0.72809898853302],\n [0.513050019741058, 0.547281980514526],\n [0.51509702205658, 0.527251958847046],\n [0.742246985435486, 0.314507007598877],\n [0.598631024360657, 0.454979002475739],\n [0.570338010787964, 0.548575043678284],\n [0.578631997108459, 0.533622980117798],\n [0.723087012767792, 0.532054007053375],\n [0.516445994377136, 0.499638974666595],\n [0.662801027297974, 0.282917976379395],\n [0.70362401008606, 0.293271005153656],\n [0.830704987049103, 0.193813979625702],\n [0.552385985851288, 0.302568018436432],\n [0.607609987258911, 0.353887975215912],\n [0.645429015159607, 0.696707010269165],\n [0.932694971561432, 0.730105042457581],\n [0.557260990142822, 0.572826027870178],\n [0.542901992797852, 0.584792017936707],\n [0.6180260181427, 0.694710969924927],\n [0.607590973377228, 0.694203019142151],\n [0.722943007946014, 0.271963000297546],\n [0.577413976192474, 0.563166975975037],\n [0.614082992076874, 0.281386971473694],\n [0.616907000541687, 0.255886018276215],\n [0.668509006500244, 0.119913995265961],\n [0.770092010498047, 0.232020974159241],\n [0.635536015033722, 0.189248979091644],\n [0.77039098739624, 0.299556016921997],\n [0.826722025871277, 0.278755009174347],\n [0.527121007442474, 0.666198015213013],\n [0.553171992301941, 0.668527007102966],\n [0.577238023281097, 0.673889994621277],\n [0.554691970348358, 0.580065965652466],\n [0.611896991729736, 0.693961024284363],\n [0.59696102142334, 0.706539988517761],\n [0.596370995044708, 0.693953037261963],\n [0.539958000183105, 0.557139039039612],\n [0.568841993808746, 0.692366003990173],\n [0.547818005084991, 0.692366003990173],\n [0.52461302280426, 0.692366003990173],\n [0.534089982509613, 0.779141008853912],\n [0.527670979499817, 0.736225962638855],\n [0.526912987232208, 0.717857003211975],\n [0.526877999305725, 0.704625964164734],\n [0.526966989040375, 0.695277988910675],\n [0.572058022022247, 0.695277988910675],\n [0.573521018028259, 0.703539967536926],\n [0.57683801651001, 0.711845993995667],\n [0.581691026687622, 0.720062971115112],\n [0.609944999217987, 0.639909982681274],\n [0.986046016216278, 0.560034036636353],\n [0.5867999792099, 0.69539999961853],\n [0.590372025966644, 0.701822996139526],\n [0.531915009021759, 0.601536989212036],\n [0.577268004417419, 0.585934996604919],\n [0.536915004253387, 0.593786001205444],\n [0.627542972564697, 0.473352015018463],\n [0.665585994720459, 0.495950996875763],\n [0.588353991508484, 0.546862006187439],\n [0.757824003696442, 0.14767599105835],\n [0.709249973297119, 0.201507985591888],\n [0.672684013843536, 0.256581008434296],\n [0.600408971309662, 0.74900496006012],\n [0.55826598405838, 0.261672019958496],\n [0.570303976535797, 0.187870979309082],\n [0.588165998458862, 0.109044015407562],\n [0.711045026779175, 0.398952007293701],\n [0.781069993972778, 0.435405015945435],\n [0.587247014045715, 0.398931980133057],\n [0.742869973182678, 0.355445981025696],\n [0.572156012058258, 0.437651991844177],\n [0.55186802148819, 0.536570012569427],\n [0.821442008018494, 0.457556009292603],\n [0.752701997756958, 0.457181990146637],\n [0.71375697851181, 0.467626988887787],\n [0.66711300611496, 0.460672974586487],\n [0.631101012229919, 0.447153985500336],\n [0.6008620262146, 0.432473003864288],\n [0.523481011390686, 0.405627012252808],\n [0.810747981071472, 0.523926019668579],\n [0.771045982837677, 0.348959028720856],\n [0.509127020835876, 0.562718033790588],\n [0.595292985439301, 0.485023975372314],\n [0.980530977249146, 0.401564002037048],\n [0.573499977588654, 0.420000016689301],\n [0.602994978427887, 0.548687994480133],\n [0.733529984951019, 0.376977026462555],\n [0.560611009597778, 0.519016981124878],\n [0.967685997486115, 0.644356966018677],\n [0.580985009670258, 0.387160003185272],\n [0.537728011608124, 0.505385041236877],\n [0.760966002941132, 0.779752969741821],\n [0.801778972148895, 0.831938028335571],\n [0.892440974712372, 0.54076099395752],\n [0.816350996494293, 0.740260004997253],\n [0.865594983100891, 0.333687007427216],\n [0.614073991775513, 0.883246004581451],\n [0.508952975273132, 0.579437971115112],\n [0.617941975593567, 0.508316040039062],\n [0.825608015060425, 0.397674977779388],\n [0.681214988231659, 0.39623498916626],\n [0.656635999679565, 0.400596976280212],\n [0.603900015354156, 0.710216999053955],\n [0.81208598613739, 0.588539004325867],\n [0.56801301240921, 0.944564998149872],\n [0.681007981300354, 0.898285031318665],\n [0.733752012252808, 0.869701027870178],\n [0.633830010890961, 0.398822009563446],\n [0.606792986392975, 0.39553701877594],\n [0.589659988880157, 0.391062021255493],\n [0.805015981197357, 0.342108011245728],\n [0.611334979534149, 0.362284004688263],\n [0.634037971496582, 0.355970978736877],\n [0.656635999679565, 0.355356991291046],\n [0.681214988231659, 0.35834002494812],\n [0.698584973812103, 0.363156020641327],\n [0.941866993904114, 0.319076001644135],\n [0.698584973812103, 0.387449026107788],\n [0.584177017211914, 0.624107003211975],\n [0.554318010807037, 0.566076993942261],\n [0.534153997898102, 0.62064003944397],\n [0.711217999458313, 0.819975018501282],\n [0.664629995822906, 0.852871000766754],\n [0.559099972248077, 0.902631998062134],\n [0.871706008911133, 0.791940987110138],\n [0.591234028339386, 0.373893976211548],\n [0.544341027736664, 0.451583981513977],\n [0.624562978744507, 0.924192011356354],\n [0.88577002286911, 0.615028977394104],\n [0.551338016986847, 0.695277988910675],\n [0.551980018615723, 0.704632043838501],\n [0.552887976169586, 0.715808033943176],\n [0.555167973041534, 0.730794012546539],\n [0.569944024085999, 0.767035007476807],\n [0.593203008174896, 0.685675978660583],\n [0.599261999130249, 0.681069016456604],\n [0.607599973678589, 0.677703022956848],\n [0.631937980651855, 0.663500010967255],\n [0.752032995223999, 0.601315021514893],\n [0.547226011753082, 0.420395016670227],\n [0.563543975353241, 0.359827995300293],\n [0.583841025829315, 0.368713974952698],\n [0.586614012718201, 0.692366003990173],\n [0.771915018558502, 0.683578014373779],\n [0.531597018241882, 0.352482974529266],\n [0.588370978832245, 0.804440975189209],\n [0.52079701423645, 0.442565023899078],\n [0.567984998226166, 0.493479013442993],\n [0.543282985687256, 0.819254994392395],\n [0.655317008495331, 0.745514988899231],\n [0.621008992195129, 0.574018001556396],\n [0.625559985637665, 0.78031200170517],\n [0.680198013782501, 0.570719003677368],\n [0.64276397228241, 0.604337990283966],\n [0.704662978649139, 0.621529996395111],\n [0.552012026309967, 0.862591981887817],\n [0.589071989059448, 0.508637011051178],\n [0.685944974422455, 0.775357007980347],\n [0.645735025405884, 0.812640011310577],\n [0.675342977046967, 0.703978002071381],\n [0.810858011245728, 0.646304965019226],\n [0.72012197971344, 0.714666962623596],\n [0.866151988506317, 0.682704985141754],\n [0.663187026977539, 0.644596993923187],\n [0.570082008838654, 0.466325998306274],\n [0.544561982154846, 0.548375964164734],\n [0.562758982181549, 0.558784961700439],\n [0.531987011432648, 0.530140042304993],\n [0.585271000862122, 0.335177004337311],\n [0.622952997684479, 0.32277899980545],\n [0.655896008014679, 0.320163011550903],\n [0.687132000923157, 0.322345972061157],\n [0.716481983661652, 0.333200991153717],\n [0.758756995201111, 0.382786989212036],\n [0.897013008594513, 0.468769013881683],\n [0.732392013072968, 0.424547016620636],\n [0.70211398601532, 0.433162987232208],\n [0.66652500629425, 0.433866024017334],\n [0.633504986763, 0.426087975502014],\n [0.603875994682312, 0.416586995124817],\n [0.579657971858978, 0.409945011138916],\n [0.992439985275269, 0.480777025222778],\n [0.567192018032074, 0.569419980049133],\n [0.54136598110199, 0.478899002075195],\n [0.526564002037048, 0.546118021011353],\n [0.523913025856018, 0.563830018043518],\n [0.531529009342194, 0.555056989192963],\n [0.566035985946655, 0.582329034805298],\n [0.51631098985672, 0.563053965568542],\n [0.5174720287323, 0.577877044677734],\n [0.573594987392426, 0.389806985855103],\n [0.560697972774506, 0.395331978797913],\n [0.549755990505219, 0.399751007556915],\n [0.710287988185883, 0.368252992630005],\n [0.723330020904541, 0.363372981548309],\n];\n", "export default [\n 127, 34, 139, 11, 0, 37, 232, 231, 120, 72, 37, 39, 128, 121, 47, 232, 121,\n 128, 104, 69, 67, 175, 171, 148, 157, 154, 155, 118, 50, 101, 73, 39, 40, 9,\n 151, 108, 48, 115, 131, 194, 204, 211, 74, 40, 185, 80, 42, 183, 40, 92,\n 186, 230, 229, 118, 202, 212, 214, 83, 18, 17, 76, 61, 146, 160, 29, 30, 56,\n 157, 173, 106, 204, 194, 135, 214, 192, 203, 165, 98, 21, 71, 68, 51, 45, 4,\n 144, 24, 23, 77, 146, 91, 205, 50, 187, 201, 200, 18, 91, 106, 182, 90, 91,\n 181, 85, 84, 17, 206, 203, 36, 148, 171, 140, 92, 40, 39, 193, 189, 244,\n 159, 158, 28, 247, 246, 161, 236, 3, 196, 54, 68, 104, 193, 168, 8, 117,\n 228, 31, 189, 193, 55, 98, 97, 99, 126, 47, 100, 166, 79, 218, 155, 154, 26,\n 209, 49, 131, 135, 136, 150, 47, 126, 217, 223, 52, 53, 45, 51, 134, 211,\n 170, 140, 67, 69, 108, 43, 106, 91, 230, 119, 120, 226, 130, 247, 63, 53,\n 52, 238, 20, 242, 46, 70, 156, 78, 62, 96, 46, 53, 63, 143, 34, 227, 173,\n 155, 133, 123, 117, 111, 44, 125, 19, 236, 134, 51, 216, 206, 205, 154, 153,\n 22, 39, 37, 167, 200, 201, 208, 36, 142, 100, 57, 212, 202, 20, 60, 99, 28,\n 158, 157, 35, 226, 113, 160, 159, 27, 204, 202, 210, 113, 225, 46, 43, 202,\n 204, 62, 76, 77, 137, 123, 116, 41, 38, 72, 203, 129, 142, 64, 98, 240, 49,\n 102, 64, 41, 73, 74, 212, 216, 207, 42, 74, 184, 169, 170, 211, 170, 149,\n 176, 105, 66, 69, 122, 6, 168, 123, 147, 187, 96, 77, 90, 65, 55, 107, 89,\n 90, 180, 101, 100, 120, 63, 105, 104, 93, 137, 227, 15, 86, 85, 129, 102,\n 49, 14, 87, 86, 55, 8, 9, 100, 47, 121, 145, 23, 22, 88, 89, 179, 6, 122,\n 196, 88, 95, 96, 138, 172, 136, 215, 58, 172, 115, 48, 219, 42, 80, 81, 195,\n 3, 51, 43, 146, 61, 171, 175, 199, 81, 82, 38, 53, 46, 225, 144, 163, 110,\n 246, 33, 7, 52, 65, 66, 229, 228, 117, 34, 127, 234, 107, 108, 69, 109, 108,\n 151, 48, 64, 235, 62, 78, 191, 129, 209, 126, 111, 35, 143, 163, 161, 246,\n 117, 123, 50, 222, 65, 52, 19, 125, 141, 221, 55, 65, 3, 195, 197, 25, 7,\n 33, 220, 237, 44, 70, 71, 139, 122, 193, 245, 247, 130, 33, 71, 21, 162,\n 153, 158, 159, 170, 169, 150, 188, 174, 196, 216, 186, 92, 144, 160, 161, 2,\n 97, 167, 141, 125, 241, 164, 167, 37, 72, 38, 12, 145, 159, 160, 38, 82, 13,\n 63, 68, 71, 226, 35, 111, 158, 153, 154, 101, 50, 205, 206, 92, 165, 209,\n 198, 217, 165, 167, 97, 220, 115, 218, 133, 112, 243, 239, 238, 241, 214,\n 135, 169, 190, 173, 133, 171, 208, 32, 125, 44, 237, 86, 87, 178, 85, 86,\n 179, 84, 85, 180, 83, 84, 181, 201, 83, 182, 137, 93, 132, 76, 62, 183, 61,\n 76, 184, 57, 61, 185, 212, 57, 186, 214, 207, 187, 34, 143, 156, 79, 239,\n 237, 123, 137, 177, 44, 1, 4, 201, 194, 32, 64, 102, 129, 213, 215, 138, 59,\n 166, 219, 242, 99, 97, 2, 94, 141, 75, 59, 235, 24, 110, 228, 25, 130, 226,\n 23, 24, 229, 22, 23, 230, 26, 22, 231, 112, 26, 232, 189, 190, 243, 221, 56,\n 190, 28, 56, 221, 27, 28, 222, 29, 27, 223, 30, 29, 224, 247, 30, 225, 238,\n 79, 20, 166, 59, 75, 60, 75, 240, 147, 177, 215, 20, 79, 166, 187, 147, 213,\n 112, 233, 244, 233, 128, 245, 128, 114, 188, 114, 217, 174, 131, 115, 220,\n 217, 198, 236, 198, 131, 134, 177, 132, 58, 143, 35, 124, 110, 163, 7, 228,\n 110, 25, 356, 389, 368, 11, 302, 267, 452, 350, 349, 302, 303, 269, 357,\n 343, 277, 452, 453, 357, 333, 332, 297, 175, 152, 377, 384, 398, 382, 347,\n 348, 330, 303, 304, 270, 9, 336, 337, 278, 279, 360, 418, 262, 431, 304,\n 408, 409, 310, 415, 407, 270, 409, 410, 450, 348, 347, 422, 430, 434, 313,\n 314, 17, 306, 307, 375, 387, 388, 260, 286, 414, 398, 335, 406, 418, 364,\n 367, 416, 423, 358, 327, 251, 284, 298, 281, 5, 4, 373, 374, 253, 307, 320,\n 321, 425, 427, 411, 421, 313, 18, 321, 405, 406, 320, 404, 405, 315, 16, 17,\n 426, 425, 266, 377, 400, 369, 322, 391, 269, 417, 465, 464, 386, 257, 258,\n 466, 260, 388, 456, 399, 419, 284, 332, 333, 417, 285, 8, 346, 340, 261,\n 413, 441, 285, 327, 460, 328, 355, 371, 329, 392, 439, 438, 382, 341, 256,\n 429, 420, 360, 364, 394, 379, 277, 343, 437, 443, 444, 283, 275, 440, 363,\n 431, 262, 369, 297, 338, 337, 273, 375, 321, 450, 451, 349, 446, 342, 467,\n 293, 334, 282, 458, 461, 462, 276, 353, 383, 308, 324, 325, 276, 300, 293,\n 372, 345, 447, 382, 398, 362, 352, 345, 340, 274, 1, 19, 456, 248, 281, 436,\n 427, 425, 381, 256, 252, 269, 391, 393, 200, 199, 428, 266, 330, 329, 287,\n 273, 422, 250, 462, 328, 258, 286, 384, 265, 353, 342, 387, 259, 257, 424,\n 431, 430, 342, 353, 276, 273, 335, 424, 292, 325, 307, 366, 447, 345, 271,\n 303, 302, 423, 266, 371, 294, 455, 460, 279, 278, 294, 271, 272, 304, 432,\n 434, 427, 272, 407, 408, 394, 430, 431, 395, 369, 400, 334, 333, 299, 351,\n 417, 168, 352, 280, 411, 325, 319, 320, 295, 296, 336, 319, 403, 404, 330,\n 348, 349, 293, 298, 333, 323, 454, 447, 15, 16, 315, 358, 429, 279, 14, 15,\n 316, 285, 336, 9, 329, 349, 350, 374, 380, 252, 318, 402, 403, 6, 197, 419,\n 318, 319, 325, 367, 364, 365, 435, 367, 397, 344, 438, 439, 272, 271, 311,\n 195, 5, 281, 273, 287, 291, 396, 428, 199, 311, 271, 268, 283, 444, 445,\n 373, 254, 339, 263, 466, 249, 282, 334, 296, 449, 347, 346, 264, 447, 454,\n 336, 296, 299, 338, 10, 151, 278, 439, 455, 292, 407, 415, 358, 371, 355,\n 340, 345, 372, 390, 249, 466, 346, 347, 280, 442, 443, 282, 19, 94, 370,\n 441, 442, 295, 248, 419, 197, 263, 255, 359, 440, 275, 274, 300, 383, 368,\n 351, 412, 465, 263, 467, 466, 301, 368, 389, 380, 374, 386, 395, 378, 379,\n 412, 351, 419, 436, 426, 322, 373, 390, 388, 2, 164, 393, 370, 462, 461,\n 164, 0, 267, 302, 11, 12, 374, 373, 387, 268, 12, 13, 293, 300, 301, 446,\n 261, 340, 385, 384, 381, 330, 266, 425, 426, 423, 391, 429, 355, 437, 391,\n 327, 326, 440, 457, 438, 341, 382, 362, 459, 457, 461, 434, 430, 394, 414,\n 463, 362, 396, 369, 262, 354, 461, 457, 316, 403, 402, 315, 404, 403, 314,\n 405, 404, 313, 406, 405, 421, 418, 406, 366, 401, 361, 306, 408, 407, 291,\n 409, 408, 287, 410, 409, 432, 436, 410, 434, 416, 411, 264, 368, 383, 309,\n 438, 457, 352, 376, 401, 274, 275, 4, 421, 428, 262, 294, 327, 358, 433,\n 416, 367, 289, 455, 439, 462, 370, 326, 2, 326, 370, 305, 460, 455, 254,\n 449, 448, 255, 261, 446, 253, 450, 449, 252, 451, 450, 256, 452, 451, 341,\n 453, 452, 413, 464, 463, 441, 413, 414, 258, 442, 441, 257, 443, 442, 259,\n 444, 443, 260, 445, 444, 467, 342, 445, 459, 458, 250, 289, 392, 290, 290,\n 328, 460, 376, 433, 435, 250, 290, 392, 411, 416, 433, 341, 463, 464, 453,\n 464, 465, 357, 465, 412, 343, 412, 399, 360, 363, 440, 437, 399, 456, 420,\n 456, 363, 401, 435, 288, 372, 383, 353, 339, 255, 249, 448, 261, 255, 133,\n 243, 190, 133, 155, 112, 33, 246, 247, 33, 130, 25, 398, 384, 286, 362, 398,\n 414, 362, 463, 341, 263, 359, 467, 263, 249, 255, 466, 467, 260, 75, 60,\n 166, 238, 239, 79, 162, 127, 139, 72, 11, 37, 121, 232, 120, 73, 72, 39,\n 114, 128, 47, 233, 232, 128, 103, 104, 67, 152, 175, 148, 173, 157, 155,\n 119, 118, 101, 74, 73, 40, 107, 9, 108, 49, 48, 131, 32, 194, 211, 184, 74,\n 185, 191, 80, 183, 185, 40, 186, 119, 230, 118, 210, 202, 214, 84, 83, 17,\n 77, 76, 146, 161, 160, 30, 190, 56, 173, 182, 106, 194, 138, 135, 192, 129,\n 203, 98, 54, 21, 68, 5, 51, 4, 145, 144, 23, 90, 77, 91, 207, 205, 187, 83,\n 201, 18, 181, 91, 182, 180, 90, 181, 16, 85, 17, 205, 206, 36, 176, 148,\n 140, 165, 92, 39, 245, 193, 244, 27, 159, 28, 30, 247, 161, 174, 236, 196,\n 103, 54, 104, 55, 193, 8, 111, 117, 31, 221, 189, 55, 240, 98, 99, 142, 126,\n 100, 219, 166, 218, 112, 155, 26, 198, 209, 131, 169, 135, 150, 114, 47,\n 217, 224, 223, 53, 220, 45, 134, 32, 211, 140, 109, 67, 108, 146, 43, 91,\n 231, 230, 120, 113, 226, 247, 105, 63, 52, 241, 238, 242, 124, 46, 156, 95,\n 78, 96, 70, 46, 63, 116, 143, 227, 116, 123, 111, 1, 44, 19, 3, 236, 51,\n 207, 216, 205, 26, 154, 22, 165, 39, 167, 199, 200, 208, 101, 36, 100, 43,\n 57, 202, 242, 20, 99, 56, 28, 157, 124, 35, 113, 29, 160, 27, 211, 204, 210,\n 124, 113, 46, 106, 43, 204, 96, 62, 77, 227, 137, 116, 73, 41, 72, 36, 203,\n 142, 235, 64, 240, 48, 49, 64, 42, 41, 74, 214, 212, 207, 183, 42, 184, 210,\n 169, 211, 140, 170, 176, 104, 105, 69, 193, 122, 168, 50, 123, 187, 89, 96,\n 90, 66, 65, 107, 179, 89, 180, 119, 101, 120, 68, 63, 104, 234, 93, 227, 16,\n 15, 85, 209, 129, 49, 15, 14, 86, 107, 55, 9, 120, 100, 121, 153, 145, 22,\n 178, 88, 179, 197, 6, 196, 89, 88, 96, 135, 138, 136, 138, 215, 172, 218,\n 115, 219, 41, 42, 81, 5, 195, 51, 57, 43, 61, 208, 171, 199, 41, 81, 38,\n 224, 53, 225, 24, 144, 110, 105, 52, 66, 118, 229, 117, 227, 34, 234, 66,\n 107, 69, 10, 109, 151, 219, 48, 235, 183, 62, 191, 142, 129, 126, 116, 111,\n 143, 7, 163, 246, 118, 117, 50, 223, 222, 52, 94, 19, 141, 222, 221, 65,\n 196, 3, 197, 45, 220, 44, 156, 70, 139, 188, 122, 245, 139, 71, 162, 145,\n 153, 159, 149, 170, 150, 122, 188, 196, 206, 216, 92, 163, 144, 161, 164, 2,\n 167, 242, 141, 241, 0, 164, 37, 11, 72, 12, 144, 145, 160, 12, 38, 13, 70,\n 63, 71, 31, 226, 111, 157, 158, 154, 36, 101, 205, 203, 206, 165, 126, 209,\n 217, 98, 165, 97, 237, 220, 218, 237, 239, 241, 210, 214, 169, 140, 171, 32,\n 241, 125, 237, 179, 86, 178, 180, 85, 179, 181, 84, 180, 182, 83, 181, 194,\n 201, 182, 177, 137, 132, 184, 76, 183, 185, 61, 184, 186, 57, 185, 216, 212,\n 186, 192, 214, 187, 139, 34, 156, 218, 79, 237, 147, 123, 177, 45, 44, 4,\n 208, 201, 32, 98, 64, 129, 192, 213, 138, 235, 59, 219, 141, 242, 97, 97, 2,\n 141, 240, 75, 235, 229, 24, 228, 31, 25, 226, 230, 23, 229, 231, 22, 230,\n 232, 26, 231, 233, 112, 232, 244, 189, 243, 189, 221, 190, 222, 28, 221,\n 223, 27, 222, 224, 29, 223, 225, 30, 224, 113, 247, 225, 99, 60, 240, 213,\n 147, 215, 60, 20, 166, 192, 187, 213, 243, 112, 244, 244, 233, 245, 245,\n 128, 188, 188, 114, 174, 134, 131, 220, 174, 217, 236, 236, 198, 134, 215,\n 177, 58, 156, 143, 124, 25, 110, 7, 31, 228, 25, 264, 356, 368, 0, 11, 267,\n 451, 452, 349, 267, 302, 269, 350, 357, 277, 350, 452, 357, 299, 333, 297,\n 396, 175, 377, 381, 384, 382, 280, 347, 330, 269, 303, 270, 151, 9, 337,\n 344, 278, 360, 424, 418, 431, 270, 304, 409, 272, 310, 407, 322, 270, 410,\n 449, 450, 347, 432, 422, 434, 18, 313, 17, 291, 306, 375, 259, 387, 260,\n 424, 335, 418, 434, 364, 416, 391, 423, 327, 301, 251, 298, 275, 281, 4,\n 254, 373, 253, 375, 307, 321, 280, 425, 411, 200, 421, 18, 335, 321, 406,\n 321, 320, 405, 314, 315, 17, 423, 426, 266, 396, 377, 369, 270, 322, 269,\n 413, 417, 464, 385, 386, 258, 248, 456, 419, 298, 284, 333, 168, 417, 8,\n 448, 346, 261, 417, 413, 285, 326, 327, 328, 277, 355, 329, 309, 392, 438,\n 381, 382, 256, 279, 429, 360, 365, 364, 379, 355, 277, 437, 282, 443, 283,\n 281, 275, 363, 395, 431, 369, 299, 297, 337, 335, 273, 321, 348, 450, 349,\n 359, 446, 467, 283, 293, 282, 250, 458, 462, 300, 276, 383, 292, 308, 325,\n 283, 276, 293, 264, 372, 447, 346, 352, 340, 354, 274, 19, 363, 456, 281,\n 426, 436, 425, 380, 381, 252, 267, 269, 393, 421, 200, 428, 371, 266, 329,\n 432, 287, 422, 290, 250, 328, 385, 258, 384, 446, 265, 342, 386, 387, 257,\n 422, 424, 430, 445, 342, 276, 422, 273, 424, 306, 292, 307, 352, 366, 345,\n 268, 271, 302, 358, 423, 371, 327, 294, 460, 331, 279, 294, 303, 271, 304,\n 436, 432, 427, 304, 272, 408, 395, 394, 431, 378, 395, 400, 296, 334, 299,\n 6, 351, 168, 376, 352, 411, 307, 325, 320, 285, 295, 336, 320, 319, 404,\n 329, 330, 349, 334, 293, 333, 366, 323, 447, 316, 15, 315, 331, 358, 279,\n 317, 14, 316, 8, 285, 9, 277, 329, 350, 253, 374, 252, 319, 318, 403, 351,\n 6, 419, 324, 318, 325, 397, 367, 365, 288, 435, 397, 278, 344, 439, 310,\n 272, 311, 248, 195, 281, 375, 273, 291, 175, 396, 199, 312, 311, 268, 276,\n 283, 445, 390, 373, 339, 295, 282, 296, 448, 449, 346, 356, 264, 454, 337,\n 336, 299, 337, 338, 151, 294, 278, 455, 308, 292, 415, 429, 358, 355, 265,\n 340, 372, 388, 390, 466, 352, 346, 280, 295, 442, 282, 354, 19, 370, 285,\n 441, 295, 195, 248, 197, 457, 440, 274, 301, 300, 368, 417, 351, 465, 251,\n 301, 389, 385, 380, 386, 394, 395, 379, 399, 412, 419, 410, 436, 322, 387,\n 373, 388, 326, 2, 393, 354, 370, 461, 393, 164, 267, 268, 302, 12, 386, 374,\n 387, 312, 268, 13, 298, 293, 301, 265, 446, 340, 380, 385, 381, 280, 330,\n 425, 322, 426, 391, 420, 429, 437, 393, 391, 326, 344, 440, 438, 458, 459,\n 461, 364, 434, 394, 428, 396, 262, 274, 354, 457, 317, 316, 402, 316, 315,\n 403, 315, 314, 404, 314, 313, 405, 313, 421, 406, 323, 366, 361, 292, 306,\n 407, 306, 291, 408, 291, 287, 409, 287, 432, 410, 427, 434, 411, 372, 264,\n 383, 459, 309, 457, 366, 352, 401, 1, 274, 4, 418, 421, 262, 331, 294, 358,\n 435, 433, 367, 392, 289, 439, 328, 462, 326, 94, 2, 370, 289, 305, 455, 339,\n 254, 448, 359, 255, 446, 254, 253, 449, 253, 252, 450, 252, 256, 451, 256,\n 341, 452, 414, 413, 463, 286, 441, 414, 286, 258, 441, 258, 257, 442, 257,\n 259, 443, 259, 260, 444, 260, 467, 445, 309, 459, 250, 305, 289, 290, 305,\n 290, 460, 401, 376, 435, 309, 250, 392, 376, 411, 433, 453, 341, 464, 357,\n 453, 465, 343, 357, 412, 437, 343, 399, 344, 360, 440, 420, 437, 456, 360,\n 420, 363, 361, 401, 288, 265, 372, 353, 390, 339, 249, 339, 448, 255];\n", "const tf = require('@tensorflow/tfjs');\nconst blazeface = require('./blazeface');\nconst keypoints = require('./keypoints');\nconst pipe = require('./pipeline');\nconst uv_coords = require('./uvcoords');\nconst triangulation = require('./triangulation').default;\n\nclass MediaPipeFaceMesh {\n constructor(blazeFace, blazeMeshModel, irisModel, config) {\n this.pipeline = new pipe.Pipeline(blazeFace, blazeMeshModel, irisModel, config);\n if (config) this.config = config;\n }\n\n async estimateFaces(input, config) {\n if (config) this.config = config;\n const predictions = await this.pipeline.predict(input, config);\n const results = [];\n for (const prediction of (predictions || [])) {\n // guard against disposed tensors on long running operations such as pause in middle of processing\n if (prediction.isDisposedInternal) continue;\n const confidence = prediction.confidence.arraySync();\n if (confidence >= this.config.detector.minConfidence) {\n const mesh = prediction.coords ? prediction.coords.arraySync() : null;\n const annotations = {};\n if (mesh && mesh.length > 0) {\n for (const key in keypoints.MESH_ANNOTATIONS) {\n if (this.config.iris.enabled || key.includes('Iris') === false) {\n annotations[key] = keypoints.MESH_ANNOTATIONS[key].map((index) => mesh[index]);\n }\n }\n }\n results.push({\n confidence: confidence || 0,\n box: prediction.box ? [prediction.box.startPoint[0], prediction.box.startPoint[1], prediction.box.endPoint[0] - prediction.box.startPoint[0], prediction.box.endPoint[1] - prediction.box.startPoint[1]] : 0,\n mesh,\n annotations,\n image: prediction.image ? tf.clone(prediction.image) : null,\n });\n }\n if (prediction.confidence) prediction.confidence.dispose();\n if (prediction.coords) prediction.coords.dispose();\n if (prediction.image) prediction.image.dispose();\n }\n return results;\n }\n}\n\nasync function load(config) {\n const models = await Promise.all([\n blazeface.load(config),\n tf.loadGraphModel(config.mesh.modelPath, { fromTFHub: config.mesh.modelPath.includes('tfhub.dev') }),\n tf.loadGraphModel(config.iris.modelPath, { fromTFHub: config.iris.modelPath.includes('tfhub.dev') }),\n ]);\n const faceMesh = new MediaPipeFaceMesh(models[0], models[1], models[2], config);\n return faceMesh;\n}\n\nexports.load = load;\nexports.MediaPipeFaceMesh = MediaPipeFaceMesh;\nexports.uv_coords = uv_coords;\nexports.triangulation = triangulation;\n", "const tf = require('@tensorflow/tfjs');\n\nconst models = {};\nlet last = { age: 0, gender: '' };\nlet frame = 0;\n\nasync function loadAge(config) {\n if (!models.age) models.age = await tf.loadGraphModel(config.face.age.modelPath);\n return models.age;\n}\n\nasync function loadGender(config) {\n if (!models.gender) models.gender = await tf.loadGraphModel(config.face.gender.modelPath);\n return models.gender;\n}\n\nasync function predict(image, config) {\n if (frame < config.face.age.skipFrames) {\n frame += 1;\n return last;\n }\n frame = 0;\n const resize = tf.image.resizeBilinear(image, [config.face.age.inputSize, config.face.age.inputSize], false);\n const enhance = tf.mul(resize, [255.0]);\n tf.dispose(resize);\n\n const promises = [];\n let ageT;\n let genderT;\n if (config.face.age.enabled) promises.push(ageT = models.age.predict(enhance));\n if (config.face.gender.enabled) promises.push(genderT = models.gender.predict(enhance));\n await Promise.all(promises);\n\n const obj = {};\n if (ageT) {\n const data = await ageT.data();\n obj.age = Math.trunc(10 * data[0]) / 10;\n tf.dispose(ageT);\n }\n if (genderT) {\n const data = await genderT.data();\n const confidence = Math.trunc(Math.abs(1.9 * 100 * (data[0] - 0.5))) / 100;\n if (confidence > config.face.gender.minConfidence) {\n obj.gender = data[0] <= 0.5 ? 'female' : 'male';\n obj.confidence = confidence;\n }\n tf.dispose(genderT);\n }\n\n tf.dispose(enhance);\n last = obj;\n return obj;\n}\n\nexports.predict = predict;\nexports.loadAge = loadAge;\nexports.loadGender = loadGender;\n", "const tf = require('@tensorflow/tfjs');\n\nconst annotations = ['angry', 'discust', 'fear', 'happy', 'sad', 'surpise', 'neutral'];\nconst models = {};\nlet last = [];\nlet frame = 0;\nconst multiplier = 1.5;\n\nasync function load(config) {\n if (!models.emotion) models.emotion = await tf.loadGraphModel(config.face.emotion.modelPath);\n return models.emotion;\n}\n\nasync function predict(image, config) {\n if (frame < config.face.emotion.skipFrames) {\n frame += 1;\n return last;\n }\n frame = 0;\n const resize = tf.image.resizeBilinear(image, [config.face.emotion.inputSize, config.face.emotion.inputSize], false);\n const [red, green, blue] = tf.split(resize, 3, 3);\n resize.dispose();\n // weighted rgb to grayscale: https://www.mathworks.com/help/matlab/ref/rgb2gray.html\n const redNorm = tf.mul(red, [0.2989]);\n const greenNorm = tf.mul(green, [0.5870]);\n const blueNorm = tf.mul(blue, [0.1140]);\n red.dispose();\n green.dispose();\n blue.dispose();\n const grayscale = tf.addN([redNorm, greenNorm, blueNorm]);\n redNorm.dispose();\n greenNorm.dispose();\n blueNorm.dispose();\n const obj = [];\n if (config.face.emotion.enabled) {\n const emotionT = await models.emotion.predict(grayscale);\n const data = await emotionT.data();\n for (let i = 0; i < data.length; i++) {\n if (multiplier * data[i] > config.face.emotion.minConfidence) obj.push({ score: Math.min(0.99, Math.trunc(100 * multiplier * data[i]) / 100), emotion: annotations[i] });\n }\n obj.sort((a, b) => b.score - a.score);\n tf.dispose(emotionT);\n }\n tf.dispose(grayscale);\n last = obj;\n return obj;\n}\n\nexports.predict = predict;\nexports.load = load;\n", "const tf = require('@tensorflow/tfjs');\n\nclass BaseModel {\n constructor(model, outputStride) {\n this.model = model;\n this.outputStride = outputStride;\n const inputShape = this.model.inputs[0].shape;\n tf.util.assert((inputShape[1] === -1) && (inputShape[2] === -1), () => `Input shape [${inputShape[1]}, ${inputShape[2]}] must both be equal to or -1`);\n }\n\n /**\n * Predicts intermediate Tensor representations.\n *\n * @param input The input RGB image of the base model.\n * A Tensor of shape: [`inputResolution`, `inputResolution`, 3].\n *\n * @return A dictionary of base model's intermediate predictions.\n * The returned dictionary should contains the following elements:\n * heatmapScores: A Tensor3D that represents the heatmapScores.\n * offsets: A Tensor3D that represents the offsets.\n * displacementFwd: A Tensor3D that represents the forward displacement.\n * displacementBwd: A Tensor3D that represents the backward displacement.\n */\n predict(input) {\n return tf.tidy(() => {\n const asFloat = this.preprocessInput(input.toFloat());\n const asBatch = asFloat.expandDims(0);\n const results = this.model.predict(asBatch);\n const results3d = results.map((y) => y.squeeze([0]));\n const namedResults = this.nameOutputResults(results3d);\n return {\n heatmapScores: namedResults.heatmap.sigmoid(),\n offsets: namedResults.offsets,\n displacementFwd: namedResults.displacementFwd,\n displacementBwd: namedResults.displacementBwd,\n };\n });\n }\n\n /**\n * Releases the CPU and GPU memory allocated by the model.\n */\n dispose() {\n this.model.dispose();\n }\n}\nexports.BaseModel = BaseModel;\n", "const tf = require('@tensorflow/tfjs');\nconst modelBase = require('./modelBase');\n\nclass MobileNet extends modelBase.BaseModel {\n // eslint-disable-next-line class-methods-use-this\n preprocessInput(input) {\n // Normalize the pixels [0, 255] to be between [-1, 1].\n return tf.tidy(() => tf.div(input, 127.5).sub(1.0));\n }\n\n // eslint-disable-next-line class-methods-use-this\n nameOutputResults(results) {\n const [offsets, heatmap, displacementFwd, displacementBwd] = results;\n return { offsets, heatmap, displacementFwd, displacementBwd };\n }\n}\nexports.MobileNet = MobileNet;\n", "// algorithm based on Coursera Lecture from Algorithms, Part 1: https://www.coursera.org/learn/algorithms-part1/lecture/ZjoSM/heapsort\nfunction half(k) {\n return Math.floor(k / 2);\n}\nclass MaxHeap {\n constructor(maxSize, getElementValue) {\n this.priorityQueue = new Array(maxSize);\n this.numberOfElements = -1;\n this.getElementValue = getElementValue;\n }\n\n enqueue(x) {\n this.priorityQueue[++this.numberOfElements] = x;\n this.swim(this.numberOfElements);\n }\n\n dequeue() {\n const max = this.priorityQueue[0];\n this.exchange(0, this.numberOfElements--);\n this.sink(0);\n this.priorityQueue[this.numberOfElements + 1] = null;\n return max;\n }\n\n empty() {\n return this.numberOfElements === -1;\n }\n\n size() {\n return this.numberOfElements + 1;\n }\n\n all() {\n return this.priorityQueue.slice(0, this.numberOfElements + 1);\n }\n\n max() {\n return this.priorityQueue[0];\n }\n\n swim(k) {\n while (k > 0 && this.less(half(k), k)) {\n this.exchange(k, half(k));\n k = half(k);\n }\n }\n\n sink(k) {\n while (2 * k <= this.numberOfElements) {\n let j = 2 * k;\n if (j < this.numberOfElements && this.less(j, j + 1)) j++;\n if (!this.less(k, j)) break;\n this.exchange(k, j);\n k = j;\n }\n }\n\n getValueAt(i) {\n return this.getElementValue(this.priorityQueue[i]);\n }\n\n less(i, j) {\n return this.getValueAt(i) < this.getValueAt(j);\n }\n\n exchange(i, j) {\n const t = this.priorityQueue[i];\n this.priorityQueue[i] = this.priorityQueue[j];\n this.priorityQueue[j] = t;\n }\n}\nexports.MaxHeap = MaxHeap;\n", "const heapSort = require('./heapSort');\n\nfunction scoreIsMaximumInLocalWindow(keypointId, score, heatmapY, heatmapX, localMaximumRadius, scores) {\n const [height, width] = scores.shape;\n let localMaximum = true;\n const yStart = Math.max(heatmapY - localMaximumRadius, 0);\n const yEnd = Math.min(heatmapY + localMaximumRadius + 1, height);\n for (let yCurrent = yStart; yCurrent < yEnd; ++yCurrent) {\n const xStart = Math.max(heatmapX - localMaximumRadius, 0);\n const xEnd = Math.min(heatmapX + localMaximumRadius + 1, width);\n for (let xCurrent = xStart; xCurrent < xEnd; ++xCurrent) {\n if (scores.get(yCurrent, xCurrent, keypointId) > score) {\n localMaximum = false;\n break;\n }\n }\n if (!localMaximum) {\n break;\n }\n }\n return localMaximum;\n}\n/**\n * Builds a priority queue with part candidate positions for a specific image in\n * the batch. For this we find all local maxima in the score maps with score\n * values above a threshold. We create a single priority queue across all parts.\n */\nfunction buildPartWithScoreQueue(scoreThreshold, localMaximumRadius, scores) {\n const [height, width, numKeypoints] = scores.shape;\n const queue = new heapSort.MaxHeap(height * width * numKeypoints, ({ score }) => score);\n for (let heatmapY = 0; heatmapY < height; ++heatmapY) {\n for (let heatmapX = 0; heatmapX < width; ++heatmapX) {\n for (let keypointId = 0; keypointId < numKeypoints; ++keypointId) {\n const score = scores.get(heatmapY, heatmapX, keypointId);\n // Only consider parts with score greater or equal to threshold as root candidates.\n if (score < scoreThreshold) continue;\n // Only consider keypoints whose score is maximum in a local window.\n if (scoreIsMaximumInLocalWindow(keypointId, score, heatmapY, heatmapX, localMaximumRadius, scores)) {\n queue.enqueue({ score, part: { heatmapY, heatmapX, id: keypointId } });\n }\n }\n }\n }\n return queue;\n}\nexports.buildPartWithScoreQueue = buildPartWithScoreQueue;\n", "exports.partNames = [\n 'nose', 'leftEye', 'rightEye', 'leftEar', 'rightEar', 'leftShoulder',\n 'rightShoulder', 'leftElbow', 'rightElbow', 'leftWrist', 'rightWrist',\n 'leftHip', 'rightHip', 'leftKnee', 'rightKnee', 'leftAnkle', 'rightAnkle',\n];\nexports.NUM_KEYPOINTS = exports.partNames.length;\nexports.partIds = exports.partNames.reduce((result, jointName, i) => {\n result[jointName] = i;\n return result;\n}, {});\nconst connectedPartNames = [\n ['leftHip', 'leftShoulder'], ['leftElbow', 'leftShoulder'],\n ['leftElbow', 'leftWrist'], ['leftHip', 'leftKnee'],\n ['leftKnee', 'leftAnkle'], ['rightHip', 'rightShoulder'],\n ['rightElbow', 'rightShoulder'], ['rightElbow', 'rightWrist'],\n ['rightHip', 'rightKnee'], ['rightKnee', 'rightAnkle'],\n ['leftShoulder', 'rightShoulder'], ['leftHip', 'rightHip'],\n];\n/*\n * Define the skeleton. This defines the parent->child relationships of our\n * tree. Arbitrarily this defines the nose as the root of the tree, however\n * since we will infer the displacement for both parent->child and\n * child->parent, we can define the tree root as any node.\n */\nexports.poseChain = [\n ['nose', 'leftEye'], ['leftEye', 'leftEar'], ['nose', 'rightEye'],\n ['rightEye', 'rightEar'], ['nose', 'leftShoulder'],\n ['leftShoulder', 'leftElbow'], ['leftElbow', 'leftWrist'],\n ['leftShoulder', 'leftHip'], ['leftHip', 'leftKnee'],\n ['leftKnee', 'leftAnkle'], ['nose', 'rightShoulder'],\n ['rightShoulder', 'rightElbow'], ['rightElbow', 'rightWrist'],\n ['rightShoulder', 'rightHip'], ['rightHip', 'rightKnee'],\n ['rightKnee', 'rightAnkle'],\n];\nexports.connectedPartIndices = connectedPartNames.map(([jointNameA, jointNameB]) => ([exports.partIds[jointNameA], exports.partIds[jointNameB]]));\nexports.partChannels = [\n 'left_face',\n 'right_face',\n 'right_upper_leg_front',\n 'right_lower_leg_back',\n 'right_upper_leg_back',\n 'left_lower_leg_front',\n 'left_upper_leg_front',\n 'left_upper_leg_back',\n 'left_lower_leg_back',\n 'right_feet',\n 'right_lower_leg_front',\n 'left_feet',\n 'torso_front',\n 'torso_back',\n 'right_upper_arm_front',\n 'right_upper_arm_back',\n 'right_lower_arm_back',\n 'left_lower_arm_front',\n 'left_upper_arm_front',\n 'left_upper_arm_back',\n 'left_lower_arm_back',\n 'right_hand',\n 'right_lower_arm_front',\n 'left_hand',\n];\n", "const kpt = require('./keypoints');\n\nfunction getOffsetPoint(y, x, keypoint, offsets) {\n return {\n y: offsets.get(y, x, keypoint),\n x: offsets.get(y, x, keypoint + kpt.NUM_KEYPOINTS),\n };\n}\nexports.getOffsetPoint = getOffsetPoint;\n\nfunction getImageCoords(part, outputStride, offsets) {\n const { heatmapY, heatmapX, id: keypoint } = part;\n const { y, x } = getOffsetPoint(heatmapY, heatmapX, keypoint, offsets);\n return {\n x: part.heatmapX * outputStride + x,\n y: part.heatmapY * outputStride + y,\n };\n}\nexports.getImageCoords = getImageCoords;\n\nfunction fillArray(element, size) {\n const result = new Array(size);\n for (let i = 0; i < size; i++) {\n result[i] = element;\n }\n return result;\n}\nexports.fillArray = fillArray;\n\nfunction clamp(a, min, max) {\n if (a < min) return min;\n if (a > max) return max;\n return a;\n}\nexports.clamp = clamp;\n\nfunction squaredDistance(y1, x1, y2, x2) {\n const dy = y2 - y1;\n const dx = x2 - x1;\n return dy * dy + dx * dx;\n}\nexports.squaredDistance = squaredDistance;\n\nfunction addVectors(a, b) {\n return { x: a.x + b.x, y: a.y + b.y };\n}\nexports.addVectors = addVectors;\n\nfunction clampVector(a, min, max) {\n return { y: clamp(a.y, min, max), x: clamp(a.x, min, max) };\n}\nexports.clampVector = clampVector;\n", "const keypoints = require('./keypoints');\nconst vectors = require('./vectors');\n\nconst parentChildrenTuples = keypoints.poseChain.map(([parentJoinName, childJoinName]) => ([keypoints.partIds[parentJoinName], keypoints.partIds[childJoinName]]));\nconst parentToChildEdges = parentChildrenTuples.map(([, childJointId]) => childJointId);\nconst childToParentEdges = parentChildrenTuples.map(([parentJointId]) => parentJointId);\nfunction getDisplacement(edgeId, point, displacements) {\n const numEdges = displacements.shape[2] / 2;\n return {\n y: displacements.get(point.y, point.x, edgeId),\n x: displacements.get(point.y, point.x, numEdges + edgeId),\n };\n}\nfunction getStridedIndexNearPoint(point, outputStride, height, width) {\n return {\n y: vectors.clamp(Math.round(point.y / outputStride), 0, height - 1),\n x: vectors.clamp(Math.round(point.x / outputStride), 0, width - 1),\n };\n}\n/**\n * We get a new keypoint along the `edgeId` for the pose instance, assuming\n * that the position of the `idSource` part is already known. For this, we\n * follow the displacement vector from the source to target part (stored in\n * the `i`-t channel of the displacement tensor). The displaced keypoint\n * vector is refined using the offset vector by `offsetRefineStep` times.\n */\nfunction traverseToTargetKeypoint(edgeId, sourceKeypoint, targetKeypointId, scoresBuffer, offsets, outputStride, displacements, offsetRefineStep = 2) {\n const [height, width] = scoresBuffer.shape;\n // Nearest neighbor interpolation for the source->target displacements.\n const sourceKeypointIndices = getStridedIndexNearPoint(sourceKeypoint.position, outputStride, height, width);\n const displacement = getDisplacement(edgeId, sourceKeypointIndices, displacements);\n const displacedPoint = vectors.addVectors(sourceKeypoint.position, displacement);\n let targetKeypoint = displacedPoint;\n for (let i = 0; i < offsetRefineStep; i++) {\n const targetKeypointIndices = getStridedIndexNearPoint(targetKeypoint, outputStride, height, width);\n const offsetPoint = vectors.getOffsetPoint(targetKeypointIndices.y, targetKeypointIndices.x, targetKeypointId, offsets);\n targetKeypoint = vectors.addVectors({\n x: targetKeypointIndices.x * outputStride,\n y: targetKeypointIndices.y * outputStride,\n }, { x: offsetPoint.x, y: offsetPoint.y });\n }\n const targetKeyPointIndices = getStridedIndexNearPoint(targetKeypoint, outputStride, height, width);\n const score = scoresBuffer.get(targetKeyPointIndices.y, targetKeyPointIndices.x, targetKeypointId);\n return { position: targetKeypoint, part: keypoints.partNames[targetKeypointId], score };\n}\n/**\n * Follows the displacement fields to decode the full pose of the object\n * instance given the position of a part that acts as root.\n *\n * @return An array of decoded keypoints and their scores for a single pose\n */\nfunction decodePose(root, scores, offsets, outputStride, displacementsFwd, displacementsBwd) {\n const numParts = scores.shape[2];\n const numEdges = parentToChildEdges.length;\n const instanceKeypoints = new Array(numParts);\n // Start a new detection instance at the position of the root.\n const { part: rootPart, score: rootScore } = root;\n const rootPoint = vectors.getImageCoords(rootPart, outputStride, offsets);\n instanceKeypoints[rootPart.id] = {\n score: rootScore,\n part: keypoints.partNames[rootPart.id],\n position: rootPoint,\n };\n // Decode the part positions upwards in the tree, following the backward\n // displacements.\n for (let edge = numEdges - 1; edge >= 0; --edge) {\n const sourceKeypointId = parentToChildEdges[edge];\n const targetKeypointId = childToParentEdges[edge];\n if (instanceKeypoints[sourceKeypointId] && !instanceKeypoints[targetKeypointId]) {\n instanceKeypoints[targetKeypointId] = traverseToTargetKeypoint(edge, instanceKeypoints[sourceKeypointId], targetKeypointId, scores, offsets, outputStride, displacementsBwd);\n }\n }\n // Decode the part positions downwards in the tree, following the forward\n // displacements.\n for (let edge = 0; edge < numEdges; ++edge) {\n const sourceKeypointId = childToParentEdges[edge];\n const targetKeypointId = parentToChildEdges[edge];\n if (instanceKeypoints[sourceKeypointId] && !instanceKeypoints[targetKeypointId]) {\n instanceKeypoints[targetKeypointId] = traverseToTargetKeypoint(edge, instanceKeypoints[sourceKeypointId], targetKeypointId, scores, offsets, outputStride, displacementsFwd);\n }\n }\n return instanceKeypoints;\n}\nexports.decodePose = decodePose;\n", "const buildParts = require('./buildParts');\nconst decodePose = require('./decodePose');\nconst vectors = require('./vectors');\n\nfunction withinNmsRadiusOfCorrespondingPoint(poses, squaredNmsRadius, { x, y }, keypointId) {\n return poses.some(({ keypoints }) => {\n const correspondingKeypoint = keypoints[keypointId].position;\n return vectors.squaredDistance(y, x, correspondingKeypoint.y, correspondingKeypoint.x) <= squaredNmsRadius;\n });\n}\n/* Score the newly proposed object instance without taking into account\n * the scores of the parts that overlap with any previously detected\n * instance.\n */\nfunction getInstanceScore(existingPoses, squaredNmsRadius, instanceKeypoints) {\n const notOverlappedKeypointScores = instanceKeypoints.reduce((result, { position, score }, keypointId) => {\n if (!withinNmsRadiusOfCorrespondingPoint(existingPoses, squaredNmsRadius, position, keypointId)) {\n result += score;\n }\n return result;\n }, 0.0);\n return notOverlappedKeypointScores / instanceKeypoints.length;\n}\n// A point (y, x) is considered as root part candidate if its score is a\n// maximum in a window |y - y'| <= kLocalMaximumRadius, |x - x'| <=\n// kLocalMaximumRadius.\nconst kLocalMaximumRadius = 1;\n/**\n * Detects multiple poses and finds their parts from part scores and\n * displacement vectors. It returns up to `maxDetections` object instance\n * detections in decreasing root score order. It works as follows: We first\n * create a priority queue with local part score maxima above\n * `scoreThreshold`, considering all parts at the same time. Then we\n * iteratively pull the top element of the queue (in decreasing score order)\n * and treat it as a root candidate for a new object instance. To avoid\n * duplicate detections, we reject the root candidate if it is within a disk\n * of `nmsRadius` pixels from the corresponding part of a previously detected\n * instance, which is a form of part-based non-maximum suppression (NMS). If\n * the root candidate passes the NMS check, we start a new object instance\n * detection, treating the corresponding part as root and finding the\n * positions of the remaining parts by following the displacement vectors\n * along the tree-structured part graph. We assign to the newly detected\n * instance a score equal to the sum of scores of its parts which have not\n * been claimed by a previous instance (i.e., those at least `nmsRadius`\n * pixels away from the corresponding part of all previously detected\n * instances), divided by the total number of parts `numParts`.\n *\n * @param heatmapScores 3-D tensor with shape `[height, width, numParts]`.\n * The value of heatmapScores[y, x, k]` is the score of placing the `k`-th\n * object part at position `(y, x)`.\n *\n * @param offsets 3-D tensor with shape `[height, width, numParts * 2]`.\n * The value of [offsets[y, x, k], offsets[y, x, k + numParts]]` is the\n * short range offset vector of the `k`-th object part at heatmap\n * position `(y, x)`.\n *\n * @param displacementsFwd 3-D tensor of shape\n * `[height, width, 2 * num_edges]`, where `num_edges = num_parts - 1` is the\n * number of edges (parent-child pairs) in the tree. It contains the forward\n * displacements between consecutive part from the root towards the leaves.\n *\n * @param displacementsBwd 3-D tensor of shape\n * `[height, width, 2 * num_edges]`, where `num_edges = num_parts - 1` is the\n * number of edges (parent-child pairs) in the tree. It contains the backward\n * displacements between consecutive part from the root towards the leaves.\n *\n * @param outputStride The output stride that was used when feed-forwarding\n * through the PoseNet model. Must be 32, 16, or 8.\n *\n * @param maxPoseDetections Maximum number of returned instance detections per\n * image.\n *\n * @param scoreThreshold Only return instance detections that have root part\n * score greater or equal to this value. Defaults to 0.5.\n *\n * @param nmsRadius Non-maximum suppression part distance. It needs to be\n * strictly positive. Two parts suppress each other if they are less than\n * `nmsRadius` pixels away. Defaults to 20.\n *\n * @return An array of poses and their scores, each containing keypoints and\n * the corresponding keypoint scores.\n */\nfunction decodeMultiplePoses(scoresBuffer, offsetsBuffer, displacementsFwdBuffer, displacementsBwdBuffer, outputStride, maxPoseDetections, scoreThreshold = 0.5, nmsRadius = 20) {\n const poses = [];\n const queue = buildParts.buildPartWithScoreQueue(scoreThreshold, kLocalMaximumRadius, scoresBuffer);\n const squaredNmsRadius = nmsRadius * nmsRadius;\n // Generate at most maxDetections object instances per image in\n // decreasing root part score order.\n while (poses.length < maxPoseDetections && !queue.empty()) {\n // The top element in the queue is the next root candidate.\n const root = queue.dequeue();\n // Part-based non-maximum suppression: We reject a root candidate if it\n // is within a disk of `nmsRadius` pixels from the corresponding part of\n // a previously detected instance.\n const rootImageCoords = vectors.getImageCoords(root.part, outputStride, offsetsBuffer);\n if (withinNmsRadiusOfCorrespondingPoint(poses, squaredNmsRadius, rootImageCoords, root.part.id)) continue;\n // Start a new detection instance at the position of the root.\n const keypoints = decodePose.decodePose(root, scoresBuffer, offsetsBuffer, outputStride, displacementsFwdBuffer, displacementsBwdBuffer);\n const score = getInstanceScore(poses, squaredNmsRadius, keypoints);\n poses.push({ keypoints, score });\n }\n return poses;\n}\nexports.decodeMultiplePoses = decodeMultiplePoses;\n", "const kpt = require('./keypoints');\n\nfunction eitherPointDoesntMeetConfidence(a, b, minConfidence) {\n return (a < minConfidence || b < minConfidence);\n}\n\nfunction getAdjacentKeyPoints(keypoints, minConfidence) {\n return kpt.connectedPartIndices.reduce((result, [leftJoint, rightJoint]) => {\n if (eitherPointDoesntMeetConfidence(keypoints[leftJoint].score, keypoints[rightJoint].score, minConfidence)) {\n return result;\n }\n result.push([keypoints[leftJoint], keypoints[rightJoint]]);\n return result;\n }, []);\n}\nexports.getAdjacentKeyPoints = getAdjacentKeyPoints;\n\nconst { NEGATIVE_INFINITY, POSITIVE_INFINITY } = Number;\nfunction getBoundingBox(keypoints) {\n return keypoints.reduce(({ maxX, maxY, minX, minY }, { position: { x, y } }) => ({\n maxX: Math.max(maxX, x),\n maxY: Math.max(maxY, y),\n minX: Math.min(minX, x),\n minY: Math.min(minY, y),\n }), {\n maxX: NEGATIVE_INFINITY,\n maxY: NEGATIVE_INFINITY,\n minX: POSITIVE_INFINITY,\n minY: POSITIVE_INFINITY,\n });\n}\nexports.getBoundingBox = getBoundingBox;\nfunction getBoundingBoxPoints(keypoints) {\n const { minX, minY, maxX, maxY } = getBoundingBox(keypoints);\n return [{ x: minX, y: minY }, { x: maxX, y: minY }, { x: maxX, y: maxY }, { x: minX, y: maxY }];\n}\nexports.getBoundingBoxPoints = getBoundingBoxPoints;\nasync function toTensorBuffers3D(tensors) {\n return Promise.all(tensors.map((tensor) => tensor.buffer()));\n}\nexports.toTensorBuffers3D = toTensorBuffers3D;\n\nfunction scalePose(pose, scaleY, scaleX) {\n return {\n score: pose.score,\n keypoints: pose.keypoints.map(({ score, part, position }) => ({\n score,\n part,\n position: { x: position.x * scaleX, y: position.y * scaleY },\n })),\n };\n}\nexports.scalePose = scalePose;\n\nfunction resizeTo(image, [targetH, targetW]) {\n const input = image.squeeze(0);\n const resized = input.resizeBilinear([targetH, targetW]);\n input.dispose();\n return resized;\n}\nexports.resizeTo = resizeTo;\n\nfunction scaleAndFlipPoses(poses, [height, width], [inputResolutionHeight, inputResolutionWidth]) {\n const scaledPoses = poses.map((pose) => scalePose(pose, height / inputResolutionHeight, width / inputResolutionWidth));\n return scaledPoses;\n}\nexports.scaleAndFlipPoses = scaleAndFlipPoses;\n", "const tf = require('@tensorflow/tfjs');\nconst modelMobileNet = require('./modelMobileNet');\nconst decodeMultiple = require('./decodeMultiple');\nconst util = require('./util');\n\nclass PoseNet {\n constructor(net) {\n this.baseModel = net;\n }\n\n /**\n * Infer through PoseNet, and estimates multiple poses using the outputs.\n * This does standard ImageNet pre-processing before inferring through the\n * model. The image should pixels should have values [0-255]. It detects\n * multiple poses and finds their parts from part scores and displacement\n * vectors using a fast greedy decoding algorithm. It returns up to\n * `config.maxDetections` object instance detections in decreasing root\n * score order.\n *\n * @param input\n * ImageData|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement) The input\n * image to feed through the network.\n *\n * @param config MultiPoseEstimationConfig object that contains parameters\n * for the PoseNet inference using multiple pose estimation.\n *\n * @return An array of poses and their scores, each containing keypoints and\n * the corresponding keypoint scores. The positions of the keypoints are\n * in the same scale as the original image\n */\n async estimatePoses(input, config) {\n const outputStride = config.outputStride;\n // const inputResolution = config.inputResolution;\n const height = input.shape[1];\n const width = input.shape[2];\n const resized = util.resizeTo(input, [config.inputResolution, config.inputResolution]);\n const { heatmapScores, offsets, displacementFwd, displacementBwd } = this.baseModel.predict(resized);\n const allTensorBuffers = await util.toTensorBuffers3D([heatmapScores, offsets, displacementFwd, displacementBwd]);\n const scoresBuffer = allTensorBuffers[0];\n const offsetsBuffer = allTensorBuffers[1];\n const displacementsFwdBuffer = allTensorBuffers[2];\n const displacementsBwdBuffer = allTensorBuffers[3];\n const poses = await decodeMultiple.decodeMultiplePoses(scoresBuffer, offsetsBuffer, displacementsFwdBuffer, displacementsBwdBuffer, outputStride, config.maxDetections, config.scoreThreshold, config.nmsRadius);\n const resultPoses = util.scaleAndFlipPoses(poses, [height, width], [config.inputResolution, config.inputResolution]);\n heatmapScores.dispose();\n offsets.dispose();\n displacementFwd.dispose();\n displacementBwd.dispose();\n resized.dispose();\n return resultPoses;\n }\n\n dispose() {\n this.baseModel.dispose();\n }\n}\nexports.PoseNet = PoseNet;\nasync function loadMobileNet(config) {\n const graphModel = await tf.loadGraphModel(config.modelPath);\n const mobilenet = new modelMobileNet.MobileNet(graphModel, config.outputStride);\n return new PoseNet(mobilenet);\n}\n/**\n * Loads the PoseNet model instance from a checkpoint, with the MobileNet architecture. The model to be loaded is configurable using the\n * config dictionary ModelConfig. Please find more details in the documentation of the ModelConfig.\n *\n * @param config ModelConfig dictionary that contains parameters for\n * the PoseNet loading process. Please find more details of each parameters\n * in the documentation of the ModelConfig interface. The predefined\n * `MOBILENET_V1_CONFIG` and `RESNET_CONFIG` can also be used as references\n * for defining your customized config.\n */\nasync function load(config) {\n return loadMobileNet(config);\n}\nexports.load = load;\n", "const modelMobileNet = require('./modelMobileNet');\nconst modelPoseNet = require('./modelPoseNet');\nconst decodeMultiple = require('./decodeMultiple');\nconst keypoints = require('./keypoints');\nconst util = require('./util');\n\nexports.load = modelPoseNet.load;\nexports.PoseNet = modelPoseNet.PoseNet;\n\nexports.MobileNet = modelMobileNet.MobileNet;\nexports.decodeMultiplePoses = decodeMultiple.decodeMultiplePoses;\nexports.partChannels = keypoints.partChannels;\nexports.partIds = keypoints.partIds;\nexports.partNames = keypoints.partNames;\nexports.poseChain = keypoints.poseChain;\nexports.getAdjacentKeyPoints = util.getAdjacentKeyPoints;\nexports.getBoundingBox = util.getBoundingBox;\nexports.getBoundingBoxPoints = util.getBoundingBoxPoints;\nexports.scaleAndFlipPoses = util.scaleAndFlipPoses;\nexports.scalePose = util.scalePose;\n", "const tf = require('@tensorflow/tfjs');\n\nfunction getBoxSize(box) {\n return [\n Math.abs(box.endPoint[0] - box.startPoint[0]),\n Math.abs(box.endPoint[1] - box.startPoint[1]),\n ];\n}\nexports.getBoxSize = getBoxSize;\n\nfunction getBoxCenter(box) {\n return [\n box.startPoint[0] + (box.endPoint[0] - box.startPoint[0]) / 2,\n box.startPoint[1] + (box.endPoint[1] - box.startPoint[1]) / 2,\n ];\n}\nexports.getBoxCenter = getBoxCenter;\n\nfunction cutBoxFromImageAndResize(box, image, cropSize) {\n const h = image.shape[1];\n const w = image.shape[2];\n const boxes = [[\n box.startPoint[1] / h, box.startPoint[0] / w, box.endPoint[1] / h,\n box.endPoint[0] / w,\n ]];\n return tf.image.cropAndResize(image, boxes, [0], cropSize);\n}\nexports.cutBoxFromImageAndResize = cutBoxFromImageAndResize;\n\nfunction scaleBoxCoordinates(box, factor) {\n const startPoint = [box.startPoint[0] * factor[0], box.startPoint[1] * factor[1]];\n const endPoint = [box.endPoint[0] * factor[0], box.endPoint[1] * factor[1]];\n const palmLandmarks = box.palmLandmarks.map((coord) => {\n const scaledCoord = [coord[0] * factor[0], coord[1] * factor[1]];\n return scaledCoord;\n });\n return { startPoint, endPoint, palmLandmarks };\n}\nexports.scaleBoxCoordinates = scaleBoxCoordinates;\n\nfunction enlargeBox(box, factor = 1.5) {\n const center = getBoxCenter(box);\n const size = getBoxSize(box);\n const newHalfSize = [factor * size[0] / 2, factor * size[1] / 2];\n const startPoint = [center[0] - newHalfSize[0], center[1] - newHalfSize[1]];\n const endPoint = [center[0] + newHalfSize[0], center[1] + newHalfSize[1]];\n return { startPoint, endPoint, palmLandmarks: box.palmLandmarks };\n}\nexports.enlargeBox = enlargeBox;\n\nfunction squarifyBox(box) {\n const centers = getBoxCenter(box);\n const size = getBoxSize(box);\n const maxEdge = Math.max(...size);\n const halfSize = maxEdge / 2;\n const startPoint = [centers[0] - halfSize, centers[1] - halfSize];\n const endPoint = [centers[0] + halfSize, centers[1] + halfSize];\n return { startPoint, endPoint, palmLandmarks: box.palmLandmarks };\n}\nexports.squarifyBox = squarifyBox;\n\nfunction shiftBox(box, shiftFactor) {\n const boxSize = [\n box.endPoint[0] - box.startPoint[0], box.endPoint[1] - box.startPoint[1],\n ];\n const shiftVector = [boxSize[0] * shiftFactor[0], boxSize[1] * shiftFactor[1]];\n const startPoint = [box.startPoint[0] + shiftVector[0], box.startPoint[1] + shiftVector[1]];\n const endPoint = [box.endPoint[0] + shiftVector[0], box.endPoint[1] + shiftVector[1]];\n return { startPoint, endPoint, palmLandmarks: box.palmLandmarks };\n}\nexports.shiftBox = shiftBox;\n", "const tf = require('@tensorflow/tfjs');\nconst bounding = require('./box');\n\nclass HandDetector {\n constructor(model, anchors, config) {\n this.model = model;\n this.width = config.inputSize;\n this.height = config.inputSize;\n this.anchors = anchors.map((anchor) => [anchor.x_center, anchor.y_center]);\n this.anchorsTensor = tf.tensor2d(this.anchors);\n this.inputSizeTensor = tf.tensor1d([config.inputSize, config.inputSize]);\n this.doubleInputSizeTensor = tf.tensor1d([config.inputSize * 2, config.inputSize * 2]);\n }\n\n normalizeBoxes(boxes) {\n return tf.tidy(() => {\n const boxOffsets = tf.slice(boxes, [0, 0], [-1, 2]);\n const boxSizes = tf.slice(boxes, [0, 2], [-1, 2]);\n const boxCenterPoints = tf.add(tf.div(boxOffsets, this.inputSizeTensor), this.anchorsTensor);\n const halfBoxSizes = tf.div(boxSizes, this.doubleInputSizeTensor);\n const startPoints = tf.mul(tf.sub(boxCenterPoints, halfBoxSizes), this.inputSizeTensor);\n const endPoints = tf.mul(tf.add(boxCenterPoints, halfBoxSizes), this.inputSizeTensor);\n return tf.concat2d([startPoints, endPoints], 1);\n });\n }\n\n normalizeLandmarks(rawPalmLandmarks, index) {\n return tf.tidy(() => {\n const landmarks = tf.add(tf.div(rawPalmLandmarks.reshape([-1, 7, 2]), this.inputSizeTensor), this.anchors[index]);\n return tf.mul(landmarks, this.inputSizeTensor);\n });\n }\n\n async getBoundingBoxes(input) {\n const batchedPrediction = this.model.predict(input);\n const prediction = batchedPrediction.squeeze();\n // Regression score for each anchor point.\n const scores = tf.tidy(() => tf.sigmoid(tf.slice(prediction, [0, 0], [-1, 1])).squeeze());\n // Bounding box for each anchor point.\n const rawBoxes = tf.slice(prediction, [0, 1], [-1, 4]);\n const boxes = this.normalizeBoxes(rawBoxes);\n const boxesWithHandsTensor = await tf.image.nonMaxSuppressionAsync(boxes, scores, this.maxHands, this.iouThreshold, this.scoreThreshold);\n const boxesWithHands = await boxesWithHandsTensor.array();\n const toDispose = [batchedPrediction, boxesWithHandsTensor, prediction, boxes, rawBoxes, scores];\n const detectedHands = tf.tidy(() => {\n const detectedBoxes = [];\n for (const i in boxesWithHands) {\n const boxIndex = boxesWithHands[i];\n const matchingBox = tf.slice(boxes, [boxIndex, 0], [1, -1]);\n const rawPalmLandmarks = tf.slice(prediction, [boxIndex, 5], [1, 14]);\n const palmLandmarks = tf.tidy(() => this.normalizeLandmarks(rawPalmLandmarks, boxIndex).reshape([-1, 2]));\n detectedBoxes.push({ boxes: matchingBox, palmLandmarks });\n }\n return detectedBoxes;\n });\n toDispose.forEach((tensor) => tensor.dispose());\n return detectedHands;\n }\n\n /**\n * Returns a Box identifying the bounding box of a hand within the image.\n * Returns null if there is no hand in the image.\n *\n * @param input The image to classify.\n */\n async estimateHandBounds(input, config) {\n // const inputHeight = input.shape[2];\n // const inputWidth = input.shape[1];\n this.iouThreshold = config.iouThreshold;\n this.scoreThreshold = config.scoreThreshold;\n this.maxHands = config.maxHands;\n const resized = input.resizeBilinear([this.width, this.height]);\n const divided = resized.div(255);\n const normalized = divided.sub(0.5);\n const image = normalized.mul(2.0);\n resized.dispose();\n divided.dispose();\n normalized.dispose();\n const predictions = await this.getBoundingBoxes(image);\n image.dispose();\n if (!predictions || (predictions.length === 0)) return null;\n const hands = [];\n for (const i in predictions) {\n const prediction = predictions[i];\n const boundingBoxes = await prediction.boxes.array();\n const startPoint = boundingBoxes[0].slice(0, 2);\n const endPoint = boundingBoxes[0].slice(2, 4);\n const palmLandmarks = await prediction.palmLandmarks.array();\n prediction.boxes.dispose();\n prediction.palmLandmarks.dispose();\n hands.push(bounding.scaleBoxCoordinates({ startPoint, endPoint, palmLandmarks }, [input.shape[2] / this.width, input.shape[1] / this.height]));\n }\n return hands;\n }\n}\nexports.HandDetector = HandDetector;\n", "exports.MESH_ANNOTATIONS = {\n thumb: [1, 2, 3, 4],\n indexFinger: [5, 6, 7, 8],\n middleFinger: [9, 10, 11, 12],\n ringFinger: [13, 14, 15, 16],\n pinky: [17, 18, 19, 20],\n palmBase: [0],\n};\n", "function normalizeRadians(angle) {\n return angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));\n}\nexports.normalizeRadians = normalizeRadians;\n\nfunction computeRotation(point1, point2) {\n const radians = Math.PI / 2 - Math.atan2(-(point2[1] - point1[1]), point2[0] - point1[0]);\n return normalizeRadians(radians);\n}\nexports.computeRotation = computeRotation;\n\nconst buildTranslationMatrix = (x, y) => ([[1, 0, x], [0, 1, y], [0, 0, 1]]);\nfunction dot(v1, v2) {\n let product = 0;\n for (let i = 0; i < v1.length; i++) {\n product += v1[i] * v2[i];\n }\n return product;\n}\nexports.dot = dot;\n\nfunction getColumnFrom2DArr(arr, columnIndex) {\n const column = [];\n for (let i = 0; i < arr.length; i++) {\n column.push(arr[i][columnIndex]);\n }\n return column;\n}\nexports.getColumnFrom2DArr = getColumnFrom2DArr;\n\nfunction multiplyTransformMatrices(mat1, mat2) {\n const product = [];\n const size = mat1.length;\n for (let row = 0; row < size; row++) {\n product.push([]);\n for (let col = 0; col < size; col++) {\n product[row].push(dot(mat1[row], getColumnFrom2DArr(mat2, col)));\n }\n }\n return product;\n}\nfunction buildRotationMatrix(rotation, center) {\n const cosA = Math.cos(rotation);\n const sinA = Math.sin(rotation);\n const rotationMatrix = [[cosA, -sinA, 0], [sinA, cosA, 0], [0, 0, 1]];\n const translationMatrix = buildTranslationMatrix(center[0], center[1]);\n const translationTimesRotation = multiplyTransformMatrices(translationMatrix, rotationMatrix);\n const negativeTranslationMatrix = buildTranslationMatrix(-center[0], -center[1]);\n return multiplyTransformMatrices(translationTimesRotation, negativeTranslationMatrix);\n}\nexports.buildRotationMatrix = buildRotationMatrix;\n\nfunction invertTransformMatrix(matrix) {\n const rotationComponent = [[matrix[0][0], matrix[1][0]], [matrix[0][1], matrix[1][1]]];\n const translationComponent = [matrix[0][2], matrix[1][2]];\n const invertedTranslation = [\n -dot(rotationComponent[0], translationComponent),\n -dot(rotationComponent[1], translationComponent),\n ];\n return [\n rotationComponent[0].concat(invertedTranslation[0]),\n rotationComponent[1].concat(invertedTranslation[1]),\n [0, 0, 1],\n ];\n}\nexports.invertTransformMatrix = invertTransformMatrix;\n\nfunction rotatePoint(homogeneousCoordinate, rotationMatrix) {\n return [\n dot(homogeneousCoordinate, rotationMatrix[0]),\n dot(homogeneousCoordinate, rotationMatrix[1]),\n ];\n}\nexports.rotatePoint = rotatePoint;\n", "const tf = require('@tensorflow/tfjs');\nconst bounding = require('./box');\nconst util = require('./util');\n\nconst UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD = 0.8;\nconst PALM_BOX_SHIFT_VECTOR = [0, -0.4];\nconst HAND_BOX_SHIFT_VECTOR = [0, -0.1];\nconst HAND_BOX_ENLARGE_FACTOR = 1.65;\nconst PALM_LANDMARK_IDS = [0, 5, 9, 13, 17, 1, 2];\nconst PALM_LANDMARKS_INDEX_OF_PALM_BASE = 0;\nconst PALM_LANDMARKS_INDEX_OF_MIDDLE_FINGER_BASE = 2;\n\n// The Pipeline coordinates between the bounding box and skeleton models.\nclass HandPipeline {\n constructor(boundingBoxDetector, meshDetector, config) {\n this.regionsOfInterest = [];\n this.runsWithoutHandDetector = 0;\n this.boundingBoxDetector = boundingBoxDetector;\n this.meshDetector = meshDetector;\n this.meshWidth = config.inputSize;\n this.meshHeight = config.inputSize;\n this.enlargeFactor = config.enlargeFactor;\n }\n\n // Get the bounding box surrounding the hand, given palm landmarks.\n getBoxForPalmLandmarks(palmLandmarks, rotationMatrix) {\n const rotatedPalmLandmarks = palmLandmarks.map((coord) => {\n const homogeneousCoordinate = [...coord, 1];\n return util.rotatePoint(homogeneousCoordinate, rotationMatrix);\n });\n const boxAroundPalm = this.calculateLandmarksBoundingBox(rotatedPalmLandmarks);\n // boxAroundPalm only surrounds the palm - therefore we shift it\n // upwards so it will capture fingers once enlarged + squarified.\n return bounding.enlargeBox(bounding.squarifyBox(bounding.shiftBox(boxAroundPalm, PALM_BOX_SHIFT_VECTOR)), this.enlargeFactor);\n }\n\n // Get the bounding box surrounding the hand, given all hand landmarks.\n getBoxForHandLandmarks(landmarks) {\n // The MediaPipe hand mesh model is trained on hands with empty space\n // around them, so we still need to shift / enlarge boxAroundHand even\n // though it surrounds the entire hand.\n const boundingBox = this.calculateLandmarksBoundingBox(landmarks);\n const boxAroundHand = bounding.enlargeBox(bounding.squarifyBox(bounding.shiftBox(boundingBox, HAND_BOX_SHIFT_VECTOR)), HAND_BOX_ENLARGE_FACTOR);\n const palmLandmarks = [];\n for (let i = 0; i < PALM_LANDMARK_IDS.length; i++) {\n palmLandmarks.push(landmarks[PALM_LANDMARK_IDS[i]].slice(0, 2));\n }\n boxAroundHand.palmLandmarks = palmLandmarks;\n return boxAroundHand;\n }\n\n // Scale, rotate, and translate raw keypoints from the model so they map to\n // the input coordinates.\n transformRawCoords(rawCoords, box, angle, rotationMatrix) {\n const boxSize = bounding.getBoxSize(box);\n const scaleFactor = [boxSize[0] / this.meshWidth, boxSize[1] / this.meshHeight];\n const coordsScaled = rawCoords.map((coord) => [\n scaleFactor[0] * (coord[0] - this.meshWidth / 2),\n scaleFactor[1] * (coord[1] - this.meshHeight / 2), coord[2],\n ]);\n const coordsRotationMatrix = util.buildRotationMatrix(angle, [0, 0]);\n const coordsRotated = coordsScaled.map((coord) => {\n const rotated = util.rotatePoint(coord, coordsRotationMatrix);\n return [...rotated, coord[2]];\n });\n const inverseRotationMatrix = util.invertTransformMatrix(rotationMatrix);\n const boxCenter = [...bounding.getBoxCenter(box), 1];\n const originalBoxCenter = [\n util.dot(boxCenter, inverseRotationMatrix[0]),\n util.dot(boxCenter, inverseRotationMatrix[1]),\n ];\n return coordsRotated.map((coord) => [\n coord[0] + originalBoxCenter[0], coord[1] + originalBoxCenter[1],\n coord[2],\n ]);\n }\n\n async estimateHands(image, config) {\n this.skipFrames = config.skipFrames;\n this.detectionConfidence = config.minConfidence;\n this.maxHands = config.maxHands;\n this.runsWithoutHandDetector++;\n const useFreshBox = this.shouldUpdateRegionsOfInterest();\n if (useFreshBox === true) {\n const boundingBoxPredictions = await this.boundingBoxDetector.estimateHandBounds(image, config);\n this.regionsOfInterest = [];\n for (const i in boundingBoxPredictions) {\n this.updateRegionsOfInterest(boundingBoxPredictions[i], true /* force update */, i);\n }\n this.runsWithoutHandDetector = 0;\n }\n // Rotate input so the hand is vertically oriented.\n const hands = [];\n if (!this.regionsOfInterest) return hands;\n for (const i in this.regionsOfInterest) {\n const currentBox = this.regionsOfInterest[i][0];\n if (!currentBox) return hands;\n const angle = util.computeRotation(currentBox.palmLandmarks[PALM_LANDMARKS_INDEX_OF_PALM_BASE], currentBox.palmLandmarks[PALM_LANDMARKS_INDEX_OF_MIDDLE_FINGER_BASE]);\n const palmCenter = bounding.getBoxCenter(currentBox);\n const palmCenterNormalized = [palmCenter[0] / image.shape[2], palmCenter[1] / image.shape[1]];\n const rotatedImage = tf.image.rotateWithOffset(image, angle, 0, palmCenterNormalized);\n const rotationMatrix = util.buildRotationMatrix(-angle, palmCenter);\n const box = useFreshBox ? this.getBoxForPalmLandmarks(currentBox.palmLandmarks, rotationMatrix) : currentBox;\n const croppedInput = bounding.cutBoxFromImageAndResize(box, rotatedImage, [this.meshWidth, this.meshHeight]);\n const handImage = croppedInput.div(255);\n croppedInput.dispose();\n rotatedImage.dispose();\n const prediction = this.meshDetector.predict(handImage);\n const [flag, keypoints] = prediction;\n handImage.dispose();\n const flagValue = flag.dataSync()[0];\n flag.dispose();\n if (flagValue < config.minConfidence) {\n keypoints.dispose();\n this.regionsOfInterest[i] = [];\n return hands;\n }\n const keypointsReshaped = tf.reshape(keypoints, [-1, 3]);\n const rawCoords = await keypointsReshaped.array();\n keypoints.dispose();\n keypointsReshaped.dispose();\n const coords = this.transformRawCoords(rawCoords, box, angle, rotationMatrix);\n const nextBoundingBox = this.getBoxForHandLandmarks(coords);\n this.updateRegionsOfInterest(nextBoundingBox, false /* force replace */, i);\n const result = {\n landmarks: coords,\n confidence: flagValue,\n box: {\n topLeft: nextBoundingBox.startPoint,\n bottomRight: nextBoundingBox.endPoint,\n },\n };\n hands.push(result);\n }\n return hands;\n }\n\n // eslint-disable-next-line class-methods-use-this\n calculateLandmarksBoundingBox(landmarks) {\n const xs = landmarks.map((d) => d[0]);\n const ys = landmarks.map((d) => d[1]);\n const startPoint = [Math.min(...xs), Math.min(...ys)];\n const endPoint = [Math.max(...xs), Math.max(...ys)];\n return { startPoint, endPoint };\n }\n\n // Updates regions of interest if the intersection over union between\n // the incoming and previous regions falls below a threshold.\n updateRegionsOfInterest(box, forceUpdate, index) {\n if (forceUpdate) {\n this.regionsOfInterest[index] = [box];\n } else {\n const previousBox = this.regionsOfInterest[index][0];\n let iou = 0;\n if (previousBox != null && previousBox.startPoint != null) {\n const [boxStartX, boxStartY] = box.startPoint;\n const [boxEndX, boxEndY] = box.endPoint;\n const [previousBoxStartX, previousBoxStartY] = previousBox.startPoint;\n const [previousBoxEndX, previousBoxEndY] = previousBox.endPoint;\n const xStartMax = Math.max(boxStartX, previousBoxStartX);\n const yStartMax = Math.max(boxStartY, previousBoxStartY);\n const xEndMin = Math.min(boxEndX, previousBoxEndX);\n const yEndMin = Math.min(boxEndY, previousBoxEndY);\n const intersection = (xEndMin - xStartMax) * (yEndMin - yStartMax);\n const boxArea = (boxEndX - boxStartX) * (boxEndY - boxStartY);\n const previousBoxArea = (previousBoxEndX - previousBoxStartX) * (previousBoxEndY - boxStartY);\n iou = intersection / (boxArea + previousBoxArea - intersection);\n }\n this.regionsOfInterest[index][0] = iou > UPDATE_REGION_OF_INTEREST_IOU_THRESHOLD ? previousBox : box;\n }\n }\n\n shouldUpdateRegionsOfInterest() {\n return !this.regionsOfInterest || (this.regionsOfInterest.length === 0) || (this.runsWithoutHandDetector >= this.skipFrames);\n }\n}\nexports.HandPipeline = HandPipeline;\n", "const tf = require('@tensorflow/tfjs');\nconst hand = require('./handdetector');\nconst keypoints = require('./keypoints');\nconst pipe = require('./pipeline');\n\nclass HandPose {\n constructor(pipeline) {\n this.pipeline = pipeline;\n }\n\n async estimateHands(input, config) {\n this.skipFrames = config.skipFrames;\n this.detectionConfidence = config.minConfidence;\n this.maxHands = config.maxHands;\n const predictions = await this.pipeline.estimateHands(input, config);\n const hands = [];\n if (!predictions) return hands;\n for (const prediction of predictions) {\n if (!prediction) return [];\n const annotations = {};\n for (const key of Object.keys(keypoints.MESH_ANNOTATIONS)) {\n annotations[key] = keypoints.MESH_ANNOTATIONS[key].map((index) => prediction.landmarks[index]);\n }\n hands.push({\n confidence: prediction.confidence || 0,\n box: prediction.box ? [prediction.box.topLeft[0], prediction.box.topLeft[1], prediction.box.bottomRight[0] - prediction.box.topLeft[0], prediction.box.bottomRight[1] - prediction.box.topLeft[1]] : 0,\n landmarks: prediction.landmarks,\n annotations,\n });\n }\n return hands;\n }\n}\nexports.HandPose = HandPose;\n\nasync function loadAnchors(url) {\n if (tf.env().features.IS_NODE) {\n // eslint-disable-next-line global-require\n const fs = require('fs');\n const data = await fs.readFileSync(url.replace('file://', ''));\n return JSON.parse(data);\n }\n return tf.util.fetch(url).then((d) => d.json());\n}\n\nasync function load(config) {\n const [anchors, handDetectorModel, handPoseModel] = await Promise.all([\n loadAnchors(config.detector.anchors),\n tf.loadGraphModel(config.detector.modelPath, { fromTFHub: config.detector.modelPath.includes('tfhub.dev') }),\n tf.loadGraphModel(config.skeleton.modelPath, { fromTFHub: config.skeleton.modelPath.includes('tfhub.dev') }),\n ]);\n const detector = new hand.HandDetector(handDetectorModel, anchors, config);\n const pipeline = new pipe.HandPipeline(detector, handPoseModel, config);\n const handpose = new HandPose(pipeline);\n return handpose;\n}\nexports.load = load;\n", "/* eslint-disable no-shadow */\n/* eslint-disable prefer-rest-params */\n/* eslint-disable no-sequences */\n/* eslint-disable no-unused-vars */\n/* eslint-disable no-unused-expressions */\n/* eslint-disable no-multi-assign */\n/* eslint-disable no-use-before-define */\n/*\nWebGLImageFilter - MIT Licensed\n2013, Dominic Szablewski - phoboslab.org\n*/\n\nconst WebGLProgram = function (gl, vertexSource, fragmentSource) {\n const _collect = function (source, prefix, collection) {\n const r = new RegExp('\\\\b' + prefix + ' \\\\w+ (\\\\w+)', 'ig');\n source.replace(r, (match, name) => {\n collection[name] = 0;\n return match;\n });\n };\n\n const _compile = function (gl, source, type) {\n const shader = gl.createShader(type);\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n throw new Error('Filter: GL compile failed', gl.getShaderInfoLog(shader));\n }\n return shader;\n };\n\n this.uniform = {};\n this.attribute = {};\n\n const _vsh = _compile(gl, vertexSource, gl.VERTEX_SHADER);\n const _fsh = _compile(gl, fragmentSource, gl.FRAGMENT_SHADER);\n\n this.id = gl.createProgram();\n gl.attachShader(this.id, _vsh);\n gl.attachShader(this.id, _fsh);\n gl.linkProgram(this.id);\n\n if (!gl.getProgramParameter(this.id, gl.LINK_STATUS)) {\n throw new Error('Filter: GL link failed', gl.getProgramInfoLog(this.id));\n }\n\n gl.useProgram(this.id);\n\n // Collect attributes\n _collect(vertexSource, 'attribute', this.attribute);\n for (const a in this.attribute) {\n this.attribute[a] = gl.getAttribLocation(this.id, a);\n }\n\n // Collect uniforms\n _collect(vertexSource, 'uniform', this.uniform);\n _collect(fragmentSource, 'uniform', this.uniform);\n for (const u in this.uniform) {\n this.uniform[u] = gl.getUniformLocation(this.id, u);\n }\n};\n\nconst WebGLImageFilter = function (params) {\n if (!params) params = { };\n let _drawCount = 0;\n let _sourceTexture = null;\n let _lastInChain = false;\n let _currentFramebufferIndex = -1;\n let _tempFramebuffers = [null, null];\n let _filterChain = [];\n let _width = -1;\n let _height = -1;\n let _vertexBuffer = null;\n let _currentProgram = null;\n const _canvas = params.canvas || document.createElement('canvas');\n\n // key is the shader program source, value is the compiled program\n const _shaderProgramCache = { };\n\n const gl = _canvas.getContext('webgl') || _canvas.getContext('experimental-webgl');\n if (!gl) throw new Error('Filter: getContext() failed');\n\n this.addFilter = function (name) {\n const args = Array.prototype.slice.call(arguments, 1);\n const filter = _filter[name];\n\n _filterChain.push({ func: filter, args });\n };\n\n this.reset = function () {\n _filterChain = [];\n };\n\n this.apply = function (image) {\n _resize(image.width, image.height);\n _drawCount = 0;\n\n // Create the texture for the input image if we haven't yet\n if (!_sourceTexture) _sourceTexture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, _sourceTexture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);\n\n // No filters? Just draw\n if (_filterChain.length === 0) {\n const program = _compileShader(SHADER.FRAGMENT_IDENTITY);\n _draw();\n return _canvas;\n }\n\n for (let i = 0; i < _filterChain.length; i++) {\n _lastInChain = (i === _filterChain.length - 1);\n const f = _filterChain[i];\n f.func.apply(this, f.args || []);\n }\n\n return _canvas;\n };\n\n const _resize = function (width, height) {\n // Same width/height? Nothing to do here\n if (width === _width && height === _height) { return; }\n\n _canvas.width = _width = width;\n _canvas.height = _height = height;\n\n // Create the context if we don't have it yet\n if (!_vertexBuffer) {\n // Create the vertex buffer for the two triangles [x, y, u, v] * 6\n const vertices = new Float32Array([\n -1, -1, 0, 1, 1, -1, 1, 1, -1, 1, 0, 0,\n -1, 1, 0, 0, 1, -1, 1, 1, 1, 1, 1, 0,\n ]);\n _vertexBuffer = gl.createBuffer(),\n gl.bindBuffer(gl.ARRAY_BUFFER, _vertexBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);\n\n // Note sure if this is a good idea; at least it makes texture loading\n // in Ejecta instant.\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);\n }\n\n gl.viewport(0, 0, _width, _height);\n\n // Delete old temp framebuffers\n _tempFramebuffers = [null, null];\n };\n\n const _getTempFramebuffer = function (index) {\n _tempFramebuffers[index] = _tempFramebuffers[index]\n || _createFramebufferTexture(_width, _height);\n\n return _tempFramebuffers[index];\n };\n\n const _createFramebufferTexture = function (width, height) {\n const fbo = gl.createFramebuffer();\n gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);\n\n const renderbuffer = gl.createRenderbuffer();\n gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer);\n\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);\n\n gl.bindTexture(gl.TEXTURE_2D, null);\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n\n return { fbo, texture };\n };\n\n const _draw = function (flags) {\n let source = null;\n let target = null;\n let flipY = false;\n\n // Set up the source\n if (_drawCount === 0) {\n // First draw call - use the source texture\n source = _sourceTexture;\n } else {\n // All following draw calls use the temp buffer last drawn to\n source = _getTempFramebuffer(_currentFramebufferIndex).texture;\n }\n _drawCount++;\n\n // Set up the target\n if (_lastInChain && !(flags & DRAW.INTERMEDIATE)) {\n // Last filter in our chain - draw directly to the WebGL Canvas. We may\n // also have to flip the image vertically now\n target = null;\n flipY = _drawCount % 2 === 0;\n } else {\n // Intermediate draw call - get a temp buffer to draw to\n _currentFramebufferIndex = (_currentFramebufferIndex + 1) % 2;\n target = _getTempFramebuffer(_currentFramebufferIndex).fbo;\n }\n\n // Bind the source and target and draw the two triangles\n gl.bindTexture(gl.TEXTURE_2D, source);\n gl.bindFramebuffer(gl.FRAMEBUFFER, target);\n\n gl.uniform1f(_currentProgram.uniform.flipY, (flipY ? -1 : 1));\n gl.drawArrays(gl.TRIANGLES, 0, 6);\n };\n\n const _compileShader = function (fragmentSource) {\n if (_shaderProgramCache[fragmentSource]) {\n _currentProgram = _shaderProgramCache[fragmentSource];\n gl.useProgram(_currentProgram.id);\n return _currentProgram;\n }\n\n // Compile shaders\n _currentProgram = new WebGLProgram(gl, SHADER.VERTEX_IDENTITY, fragmentSource);\n\n const floatSize = Float32Array.BYTES_PER_ELEMENT;\n const vertSize = 4 * floatSize;\n gl.enableVertexAttribArray(_currentProgram.attribute.pos);\n gl.vertexAttribPointer(_currentProgram.attribute.pos, 2, gl.FLOAT, false, vertSize, 0 * floatSize);\n gl.enableVertexAttribArray(_currentProgram.attribute.uv);\n gl.vertexAttribPointer(_currentProgram.attribute.uv, 2, gl.FLOAT, false, vertSize, 2 * floatSize);\n\n _shaderProgramCache[fragmentSource] = _currentProgram;\n return _currentProgram;\n };\n\n let DRAW = { INTERMEDIATE: 1 };\n\n let SHADER = {};\n SHADER.VERTEX_IDENTITY = [\n 'precision highp float;',\n 'attribute vec2 pos;',\n 'attribute vec2 uv;',\n 'varying vec2 vUv;',\n 'uniform float flipY;',\n\n 'void main(void) {',\n 'vUv = uv;',\n 'gl_Position = vec4(pos.x, pos.y*flipY, 0.0, 1.);',\n '}',\n ].join('\\n');\n\n SHADER.FRAGMENT_IDENTITY = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n\n 'void main(void) {',\n 'gl_FragColor = texture2D(texture, vUv);',\n '}',\n ].join('\\n');\n\n let _filter = {};\n\n // -------------------------------------------------------------------------\n // Color Matrix Filter\n\n _filter.colorMatrix = function (matrix) {\n // Create a Float32 Array and normalize the offset component to 0-1\n const m = new Float32Array(matrix);\n m[4] /= 255;\n m[9] /= 255;\n m[14] /= 255;\n m[19] /= 255;\n\n // Can we ignore the alpha value? Makes things a bit faster.\n const shader = (m[18] === 1 && m[3] === 0 && m[8] === 0 && m[13] === 0 && m[15] === 0 && m[16] === 0 && m[17] === 0 && m[19] === 0)\n ? _filter.colorMatrix.SHADER.WITHOUT_ALPHA\n : _filter.colorMatrix.SHADER.WITH_ALPHA;\n\n const program = _compileShader(shader);\n gl.uniform1fv(program.uniform.m, m);\n _draw();\n };\n\n _filter.colorMatrix.SHADER = {};\n _filter.colorMatrix.SHADER.WITH_ALPHA = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform float m[20];',\n\n 'void main(void) {',\n 'vec4 c = texture2D(texture, vUv);',\n 'gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[3] * c.a + m[4];',\n 'gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[8] * c.a + m[9];',\n 'gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[13] * c.a + m[14];',\n 'gl_FragColor.a = m[15] * c.r + m[16] * c.g + m[17] * c.b + m[18] * c.a + m[19];',\n '}',\n ].join('\\n');\n _filter.colorMatrix.SHADER.WITHOUT_ALPHA = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform float m[20];',\n\n 'void main(void) {',\n 'vec4 c = texture2D(texture, vUv);',\n 'gl_FragColor.r = m[0] * c.r + m[1] * c.g + m[2] * c.b + m[4];',\n 'gl_FragColor.g = m[5] * c.r + m[6] * c.g + m[7] * c.b + m[9];',\n 'gl_FragColor.b = m[10] * c.r + m[11] * c.g + m[12] * c.b + m[14];',\n 'gl_FragColor.a = c.a;',\n '}',\n ].join('\\n');\n\n _filter.brightness = function (brightness) {\n const b = (brightness || 0) + 1;\n _filter.colorMatrix([\n b, 0, 0, 0, 0,\n 0, b, 0, 0, 0,\n 0, 0, b, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.saturation = function (amount) {\n const x = (amount || 0) * 2 / 3 + 1;\n const y = ((x - 1) * -0.5);\n _filter.colorMatrix([\n x, y, y, 0, 0,\n y, x, y, 0, 0,\n y, y, x, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.desaturate = function () {\n _filter.saturation(-1);\n };\n\n _filter.contrast = function (amount) {\n const v = (amount || 0) + 1;\n const o = -128 * (v - 1);\n\n _filter.colorMatrix([\n v, 0, 0, 0, o,\n 0, v, 0, 0, o,\n 0, 0, v, 0, o,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.negative = function () {\n _filter.contrast(-2);\n };\n\n _filter.hue = function (rotation) {\n rotation = (rotation || 0) / 180 * Math.PI;\n const cos = Math.cos(rotation);\n const sin = Math.sin(rotation);\n const lumR = 0.213;\n const lumG = 0.715;\n const lumB = 0.072;\n\n _filter.colorMatrix([\n lumR + cos * (1 - lumR) + sin * (-lumR), lumG + cos * (-lumG) + sin * (-lumG), lumB + cos * (-lumB) + sin * (1 - lumB), 0, 0,\n lumR + cos * (-lumR) + sin * (0.143), lumG + cos * (1 - lumG) + sin * (0.140), lumB + cos * (-lumB) + sin * (-0.283), 0, 0,\n lumR + cos * (-lumR) + sin * (-(1 - lumR)), lumG + cos * (-lumG) + sin * (lumG), lumB + cos * (1 - lumB) + sin * (lumB), 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.desaturateLuminance = function () {\n _filter.colorMatrix([\n 0.2764723, 0.9297080, 0.0938197, 0, -37.1,\n 0.2764723, 0.9297080, 0.0938197, 0, -37.1,\n 0.2764723, 0.9297080, 0.0938197, 0, -37.1,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.sepia = function () {\n _filter.colorMatrix([\n 0.393, 0.7689999, 0.18899999, 0, 0,\n 0.349, 0.6859999, 0.16799999, 0, 0,\n 0.272, 0.5339999, 0.13099999, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.brownie = function () {\n _filter.colorMatrix([\n 0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873,\n -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127,\n 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.vintagePinhole = function () {\n _filter.colorMatrix([\n 0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123,\n 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591,\n 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.kodachrome = function () {\n _filter.colorMatrix([\n 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502,\n -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203,\n -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.technicolor = function () {\n _filter.colorMatrix([\n 1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337,\n -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398,\n -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.polaroid = function () {\n _filter.colorMatrix([\n 1.438, -0.062, -0.062, 0, 0,\n -0.122, 1.378, -0.122, 0, 0,\n -0.016, -0.016, 1.483, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n _filter.shiftToBGR = function () {\n _filter.colorMatrix([\n 0, 0, 1, 0, 0,\n 0, 1, 0, 0, 0,\n 1, 0, 0, 0, 0,\n 0, 0, 0, 1, 0,\n ]);\n };\n\n // -------------------------------------------------------------------------\n // Convolution Filter\n\n _filter.convolution = function (matrix) {\n const m = new Float32Array(matrix);\n const pixelSizeX = 1 / _width;\n const pixelSizeY = 1 / _height;\n\n const program = _compileShader(_filter.convolution.SHADER);\n gl.uniform1fv(program.uniform.m, m);\n gl.uniform2f(program.uniform.px, pixelSizeX, pixelSizeY);\n _draw();\n };\n\n _filter.convolution.SHADER = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform vec2 px;',\n 'uniform float m[9];',\n\n 'void main(void) {',\n 'vec4 c11 = texture2D(texture, vUv - px);', // top left\n 'vec4 c12 = texture2D(texture, vec2(vUv.x, vUv.y - px.y));', // top center\n 'vec4 c13 = texture2D(texture, vec2(vUv.x + px.x, vUv.y - px.y));', // top right\n\n 'vec4 c21 = texture2D(texture, vec2(vUv.x - px.x, vUv.y) );', // mid left\n 'vec4 c22 = texture2D(texture, vUv);', // mid center\n 'vec4 c23 = texture2D(texture, vec2(vUv.x + px.x, vUv.y) );', // mid right\n\n 'vec4 c31 = texture2D(texture, vec2(vUv.x - px.x, vUv.y + px.y) );', // bottom left\n 'vec4 c32 = texture2D(texture, vec2(vUv.x, vUv.y + px.y) );', // bottom center\n 'vec4 c33 = texture2D(texture, vUv + px );', // bottom right\n\n 'gl_FragColor = ',\n 'c11 * m[0] + c12 * m[1] + c22 * m[2] +',\n 'c21 * m[3] + c22 * m[4] + c23 * m[5] +',\n 'c31 * m[6] + c32 * m[7] + c33 * m[8];',\n 'gl_FragColor.a = c22.a;',\n '}',\n ].join('\\n');\n\n _filter.detectEdges = function () {\n _filter.convolution.call(this, [\n 0, 1, 0,\n 1, -4, 1,\n 0, 1, 0,\n ]);\n };\n\n _filter.sobelX = function () {\n _filter.convolution.call(this, [\n -1, 0, 1,\n -2, 0, 2,\n -1, 0, 1,\n ]);\n };\n\n _filter.sobelY = function () {\n _filter.convolution.call(this, [\n -1, -2, -1,\n 0, 0, 0,\n 1, 2, 1,\n ]);\n };\n\n _filter.sharpen = function (amount) {\n const a = amount || 1;\n _filter.convolution.call(this, [\n 0, -1 * a, 0,\n -1 * a, 1 + 4 * a, -1 * a,\n 0, -1 * a, 0,\n ]);\n };\n\n _filter.emboss = function (size) {\n const s = size || 1;\n _filter.convolution.call(this, [\n -2 * s, -1 * s, 0,\n -1 * s, 1, 1 * s,\n 0, 1 * s, 2 * s,\n ]);\n };\n\n // -------------------------------------------------------------------------\n // Blur Filter\n\n _filter.blur = function (size) {\n const blurSizeX = (size / 7) / _width;\n const blurSizeY = (size / 7) / _height;\n\n const program = _compileShader(_filter.blur.SHADER);\n\n // Vertical\n gl.uniform2f(program.uniform.px, 0, blurSizeY);\n _draw(DRAW.INTERMEDIATE);\n\n // Horizontal\n gl.uniform2f(program.uniform.px, blurSizeX, 0);\n _draw();\n };\n\n _filter.blur.SHADER = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform sampler2D texture;',\n 'uniform vec2 px;',\n\n 'void main(void) {',\n 'gl_FragColor = vec4(0.0);',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-7.0*px.x, -7.0*px.y))*0.0044299121055113265;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-6.0*px.x, -6.0*px.y))*0.00895781211794;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-5.0*px.x, -5.0*px.y))*0.0215963866053;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-4.0*px.x, -4.0*px.y))*0.0443683338718;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-3.0*px.x, -3.0*px.y))*0.0776744219933;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-2.0*px.x, -2.0*px.y))*0.115876621105;',\n 'gl_FragColor += texture2D(texture, vUv + vec2(-1.0*px.x, -1.0*px.y))*0.147308056121;',\n 'gl_FragColor += texture2D(texture, vUv )*0.159576912161;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 1.0*px.x, 1.0*px.y))*0.147308056121;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 2.0*px.x, 2.0*px.y))*0.115876621105;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 3.0*px.x, 3.0*px.y))*0.0776744219933;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 4.0*px.x, 4.0*px.y))*0.0443683338718;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 5.0*px.x, 5.0*px.y))*0.0215963866053;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 6.0*px.x, 6.0*px.y))*0.00895781211794;',\n 'gl_FragColor += texture2D(texture, vUv + vec2( 7.0*px.x, 7.0*px.y))*0.0044299121055113265;',\n '}',\n ].join('\\n');\n\n // -------------------------------------------------------------------------\n // Pixelate Filter\n\n _filter.pixelate = function (size) {\n const blurSizeX = (size) / _width;\n const blurSizeY = (size) / _height;\n\n const program = _compileShader(_filter.pixelate.SHADER);\n\n // Horizontal\n gl.uniform2f(program.uniform.size, blurSizeX, blurSizeY);\n _draw();\n };\n\n _filter.pixelate.SHADER = [\n 'precision highp float;',\n 'varying vec2 vUv;',\n 'uniform vec2 size;',\n 'uniform sampler2D texture;',\n\n 'vec2 pixelate(vec2 coord, vec2 size) {',\n 'return floor( coord / size ) * size;',\n '}',\n\n 'void main(void) {',\n 'gl_FragColor = vec4(0.0);',\n 'vec2 coord = pixelate(vUv, size);',\n 'gl_FragColor += texture2D(texture, coord);',\n '}',\n ].join('\\n');\n};\n\nexports.Canvas = WebGLImageFilter;\n", "/* eslint-disable indent */\n/* eslint-disable no-multi-spaces */\n\nexport default {\n backend: 'webgl', // select tfjs backend to use\n console: true, // enable debugging output to console\n scoped: false, // enable scoped runs\n // some models *may* have memory leaks, this wrapps everything in a local scope at a cost of performance\n // typically not needed\n videoOptimized: true, // perform additional optimizations when input is video, must be disabled for images\n filter: {\n enabled: true, // enable image pre-processing filters\n return: true, // return processed canvas imagedata in result\n brightness: 0, // range: -1 (darken) to 1 (lighten)\n contrast: 0, // range: -1 (reduce contrast) to 1 (increase contrast)\n sharpness: 0, // range: 0 (no sharpening) to 1 (maximum sharpening)\n blur: 0, // range: 0 (no blur) to N (blur radius in pixels)\n saturation: 0, // range: -1 (reduce saturation) to 1 (increase saturation)\n hue: 0, // range: 0 (no change) to 360 (hue rotation in degrees)\n negative: false, // image negative\n sepia: false, // image sepia colors\n vintage: false, // image vintage colors\n kodachrome: false, // image kodachrome colors\n technicolor: false, // image technicolor colors\n polaroid: false, // image polaroid camera effect\n pixelate: 0, // range: 0 (no pixelate) to N (number of pixels to pixelate)\n },\n face: {\n enabled: true, // controls if specified modul is enabled\n // face.enabled is required for all face models: detector, mesh, iris, age, gender, emotion\n // (note: module is not loaded until it is required)\n detector: {\n modelPath: '../models/blazeface/back/model.json', // can be 'front' or 'back'.\n // 'front' is optimized for large faces such as front-facing camera and 'back' is optimized for distanct faces.\n inputSize: 256, // fixed value: 128 for front and 256 for 'back'\n maxFaces: 10, // maximum number of faces detected in the input, should be set to the minimum number for performance\n skipFrames: 10, // how many frames to go without re-running the face bounding box detector, only used for video inputs\n // if model is running st 25 FPS, we can re-use existing bounding box for updated face mesh analysis\n // as face probably hasn't moved much in short time (10 * 1/25 = 0.25 sec)\n minConfidence: 0.5, // threshold for discarding a prediction\n iouThreshold: 0.3, // threshold for deciding whether boxes overlap too much in non-maximum suppression\n scoreThreshold: 0.7, // threshold for deciding when to remove boxes based on score in non-maximum suppression\n },\n mesh: {\n enabled: true,\n modelPath: '../models/facemesh/model.json',\n inputSize: 192, // fixed value\n },\n iris: {\n enabled: true,\n modelPath: '../models/iris/model.json',\n enlargeFactor: 2.3, // empiric tuning\n inputSize: 64, // fixed value\n },\n age: {\n enabled: true,\n modelPath: '../models/ssrnet-age/imdb/model.json', // can be 'imdb' or 'wiki'\n // which determines training set for model\n inputSize: 64, // fixed value\n skipFrames: 10, // how many frames to go without re-running the detector, only used for video inputs\n },\n gender: {\n enabled: true,\n minConfidence: 0.8, // threshold for discarding a prediction\n modelPath: '../models/ssrnet-gender/imdb/model.json',\n },\n emotion: {\n enabled: true,\n inputSize: 64, // fixed value\n minConfidence: 0.5, // threshold for discarding a prediction\n skipFrames: 10, // how many frames to go without re-running the detector\n modelPath: '../models/emotion/model.json',\n },\n },\n body: {\n enabled: true,\n modelPath: '../models/posenet/model.json',\n inputResolution: 257, // fixed value\n outputStride: 16, // fixed value\n maxDetections: 10, // maximum number of people detected in the input, should be set to the minimum number for performance\n scoreThreshold: 0.7, // threshold for deciding when to remove boxes based on score in non-maximum suppression\n nmsRadius: 20, // radius for deciding points are too close in non-maximum suppression\n },\n hand: {\n enabled: true,\n inputSize: 256, // fixed value\n skipFrames: 10, // how many frames to go without re-running the hand bounding box detector, only used for video inputs\n // if model is running st 25 FPS, we can re-use existing bounding box for updated hand skeleton analysis\n // as the hand probably hasn't moved much in short time (10 * 1/25 = 0.25 sec)\n minConfidence: 0.5, // threshold for discarding a prediction\n iouThreshold: 0.3, // threshold for deciding whether boxes overlap too much in non-maximum suppression\n scoreThreshold: 0.7, // threshold for deciding when to remove boxes based on score in non-maximum suppression\n enlargeFactor: 1.65, // empiric tuning as skeleton prediction prefers hand box with some whitespace\n maxHands: 10, // maximum number of hands detected in the input, should be set to the minimum number for performance\n detector: {\n anchors: '../models/handdetect/anchors.json',\n modelPath: '../models/handdetect/model.json',\n },\n skeleton: {\n modelPath: '../models/handskeleton/model.json',\n },\n },\n};\n", "const tf = require('@tensorflow/tfjs');\nconst facemesh = require('./facemesh/facemesh.js');\nconst ssrnet = require('./ssrnet/ssrnet.js');\nconst emotion = require('./emotion/emotion.js');\nconst posenet = require('./posenet/posenet.js');\nconst handpose = require('./handpose/handpose.js');\nconst fxImage = require('./imagefx.js');\nconst defaults = require('../config.js').default;\nconst app = require('../package.json');\n\nlet first = true;\n\n// static config override for non-video detection\nconst override = {\n face: { detector: { skipFrames: 0 }, age: { skipFrames: 0 }, emotion: { skipFrames: 0 } },\n hand: { skipFrames: 0 },\n};\n\n// helper function: gets elapsed time on both browser and nodejs\nconst now = () => {\n if (typeof performance !== 'undefined') return performance.now();\n return parseInt(Number(process.hrtime.bigint()) / 1000 / 1000);\n};\n\n// helper function: perform deep merge of multiple objects so it allows full inheriance with overrides\nfunction mergeDeep(...objects) {\n const isObject = (obj) => obj && typeof obj === 'object';\n return objects.reduce((prev, obj) => {\n Object.keys(obj || {}).forEach((key) => {\n const pVal = prev[key];\n const oVal = obj[key];\n if (Array.isArray(pVal) && Array.isArray(oVal)) {\n prev[key] = pVal.concat(...oVal);\n } else if (isObject(pVal) && isObject(oVal)) {\n prev[key] = mergeDeep(pVal, oVal);\n } else {\n prev[key] = oVal;\n }\n });\n return prev;\n }, {});\n}\n\nfunction sanity(input) {\n if (!input) return 'input is not defined';\n if (tf.ENV.flags.IS_NODE && !(input instanceof tf.Tensor)) {\n return 'input must be a tensor';\n }\n try {\n tf.getBackend();\n } catch {\n return 'backend not loaded';\n }\n return null;\n}\n\nclass Human {\n constructor() {\n this.tf = tf;\n this.version = app.version;\n this.defaults = defaults;\n this.config = defaults;\n this.fx = (tf.ENV.flags.IS_BROWSER && (typeof document !== 'undefined')) ? new fxImage.Canvas() : null;\n this.state = 'idle';\n this.numTensors = 0;\n this.analyzeMemoryLeaks = false;\n // object that contains all initialized models\n this.models = {\n facemesh: null,\n posenet: null,\n handpose: null,\n iris: null,\n age: null,\n gender: null,\n emotion: null,\n };\n // export raw access to underlying models\n this.facemesh = facemesh;\n this.ssrnet = ssrnet;\n this.emotion = emotion;\n this.posenet = posenet;\n this.handpose = handpose;\n }\n\n // helper function: wrapper around console output\n log(...msg) {\n // eslint-disable-next-line no-console\n if (msg && this.config.console) console.log(...msg);\n }\n\n // helper function: measure tensor leak\n analyze(...msg) {\n if (!this.analyzeMemoryLeaks) return;\n const current = tf.engine().state.numTensors;\n const previous = this.numTensors;\n this.numTensors = current;\n const leaked = current - previous;\n if (leaked !== 0) this.log(...msg, leaked);\n }\n\n async load(userConfig) {\n if (userConfig) this.config = mergeDeep(defaults, userConfig);\n if (this.config.face.enabled && !this.models.facemesh) {\n this.log('Load model: Face');\n this.models.facemesh = await facemesh.load(this.config.face);\n }\n if (this.config.body.enabled && !this.models.posenet) {\n this.log('Load model: Body');\n this.models.posenet = await posenet.load(this.config.body);\n }\n if (this.config.hand.enabled && !this.models.handpose) {\n this.log('Load model: Hand');\n this.models.handpose = await handpose.load(this.config.hand);\n }\n if (this.config.face.enabled && this.config.face.age.enabled && !this.models.age) {\n this.log('Load model: Age');\n this.models.age = await ssrnet.loadAge(this.config);\n }\n if (this.config.face.enabled && this.config.face.gender.enabled && !this.models.gender) {\n this.log('Load model: Gender');\n this.models.gender = await ssrnet.loadGender(this.config);\n }\n if (this.config.face.enabled && this.config.face.emotion.enabled && !this.models.emotion) {\n this.log('Load model: Emotion');\n this.models.emotion = await emotion.load(this.config);\n }\n }\n\n tfImage(input) {\n // let imageData;\n let filtered;\n if (this.fx && this.config.filter.enabled && !(input instanceof tf.Tensor)) {\n const width = input.naturalWidth || input.videoWidth || input.width || (input.shape && (input.shape[1] > 0));\n const height = input.naturalHeight || input.videoHeight || input.height || (input.shape && (input.shape[2] > 0));\n const offscreenCanvas = new OffscreenCanvas(width, height);\n const ctx = offscreenCanvas.getContext('2d');\n if (input instanceof ImageData) ctx.putImageData(input, 0, 0);\n else ctx.drawImage(input, 0, 0, width, height, 0, 0, offscreenCanvas.width, offscreenCanvas.height);\n this.fx.reset();\n this.fx.addFilter('brightness', this.config.filter.brightness); // must have at least one filter enabled\n if (this.config.filter.contrast !== 0) this.fx.addFilter('contrast', this.config.filter.contrast);\n if (this.config.filter.sharpness !== 0) this.fx.addFilter('sharpen', this.config.filter.sharpness);\n if (this.config.filter.blur !== 0) this.fx.addFilter('blur', this.config.filter.blur);\n if (this.config.filter.saturation !== 0) this.fx.addFilter('saturation', this.config.filter.saturation);\n if (this.config.filter.hue !== 0) this.fx.addFilter('hue', this.config.filter.hue);\n if (this.config.filter.negative) this.fx.addFilter('negative');\n if (this.config.filter.sepia) this.fx.addFilter('sepia');\n if (this.config.filter.vintage) this.fx.addFilter('brownie');\n if (this.config.filter.sepia) this.fx.addFilter('sepia');\n if (this.config.filter.kodachrome) this.fx.addFilter('kodachrome');\n if (this.config.filter.technicolor) this.fx.addFilter('technicolor');\n if (this.config.filter.polaroid) this.fx.addFilter('polaroid');\n if (this.config.filter.pixelate !== 0) this.fx.addFilter('pixelate', this.config.filter.pixelate);\n filtered = this.fx.apply(offscreenCanvas);\n }\n let tensor;\n if (input instanceof tf.Tensor) {\n tensor = tf.clone(input);\n } else {\n const pixels = tf.browser.fromPixels(filtered || input);\n const casted = pixels.toFloat();\n tensor = casted.expandDims(0);\n pixels.dispose();\n casted.dispose();\n }\n return { tensor, canvas: this.config.filter.return ? filtered : null };\n }\n\n async detect(input, userConfig = {}) {\n this.state = 'config';\n const perf = {};\n let timeStamp;\n\n timeStamp = now();\n this.config = mergeDeep(defaults, userConfig);\n if (!this.config.videoOptimized) this.config = mergeDeep(this.config, override);\n perf.config = Math.trunc(now() - timeStamp);\n\n // sanity checks\n timeStamp = now();\n this.state = 'check';\n const error = sanity(input);\n if (error) {\n this.log(error, input);\n return { error };\n }\n perf.sanity = Math.trunc(now() - timeStamp);\n\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve) => {\n const timeStart = now();\n\n // configure backend\n timeStamp = now();\n if (tf.getBackend() !== this.config.backend) {\n this.state = 'backend';\n this.log('Human library setting backend:', this.config.backend);\n await tf.setBackend(this.config.backend);\n await tf.ready();\n }\n perf.backend = Math.trunc(now() - timeStamp);\n\n // check number of loaded models\n if (first) {\n this.log('Human library starting');\n this.log('Configuration:', this.config);\n this.log('Flags:', tf.ENV.flags);\n first = false;\n }\n\n // load models if enabled\n timeStamp = now();\n this.state = 'load';\n await this.load();\n perf.load = Math.trunc(now() - timeStamp);\n\n if (this.config.scoped) tf.engine().startScope();\n\n this.analyze('Start Detect:');\n\n timeStamp = now();\n const image = this.tfImage(input);\n perf.image = Math.trunc(now() - timeStamp);\n const imageTensor = image.tensor;\n\n // run posenet\n this.state = 'run:body';\n timeStamp = now();\n this.analyze('Start PoseNet');\n const poseRes = this.config.body.enabled ? await this.models.posenet.estimatePoses(imageTensor, this.config.body) : [];\n this.analyze('End PoseNet:');\n perf.body = Math.trunc(now() - timeStamp);\n\n // run handpose\n this.state = 'run:hand';\n timeStamp = now();\n this.analyze('Start HandPose:');\n const handRes = this.config.hand.enabled ? await this.models.handpose.estimateHands(imageTensor, this.config.hand) : [];\n this.analyze('End HandPose:');\n perf.hand = Math.trunc(now() - timeStamp);\n\n // run facemesh, includes blazeface and iris\n const faceRes = [];\n if (this.config.face.enabled) {\n this.state = 'run:face';\n timeStamp = now();\n this.analyze('Start FaceMesh:');\n const faces = await this.models.facemesh.estimateFaces(imageTensor, this.config.face);\n perf.face = Math.trunc(now() - timeStamp);\n for (const face of faces) {\n // is something went wrong, skip the face\n if (!face.image || face.image.isDisposedInternal) {\n this.log('face object is disposed:', face.image);\n continue;\n }\n // run ssr-net age & gender, inherits face from blazeface\n this.state = 'run:agegender';\n timeStamp = now();\n const ssrData = (this.config.face.age.enabled || this.config.face.gender.enabled) ? await ssrnet.predict(face.image, this.config) : {};\n perf.agegender = Math.trunc(now() - timeStamp);\n // run emotion, inherits face from blazeface\n this.state = 'run:emotion';\n timeStamp = now();\n const emotionData = this.config.face.emotion.enabled ? await emotion.predict(face.image, this.config) : {};\n perf.emotion = Math.trunc(now() - timeStamp);\n\n // dont need face anymore\n face.image.dispose();\n // calculate iris distance\n // iris: array[ bottom, left, top, right, center ]\n const iris = (face.annotations.leftEyeIris && face.annotations.rightEyeIris)\n ? Math.max(face.annotations.leftEyeIris[3][0] - face.annotations.leftEyeIris[1][0], face.annotations.rightEyeIris[3][0] - face.annotations.rightEyeIris[1][0])\n : 0;\n faceRes.push({\n confidence: face.confidence,\n box: face.box,\n mesh: face.mesh,\n annotations: face.annotations,\n age: ssrData.age,\n gender: ssrData.gender,\n agConfidence: ssrData.confidence,\n emotion: emotionData,\n iris: (iris !== 0) ? Math.trunc(100 * 11.7 /* human iris size in mm */ / iris) / 100 : 0,\n });\n this.analyze('End FaceMesh:');\n }\n }\n\n imageTensor.dispose();\n this.state = 'idle';\n\n if (this.config.scoped) tf.engine().endScope();\n this.analyze('End Scope:');\n\n perf.total = Math.trunc(now() - timeStart);\n resolve({ face: faceRes, body: poseRes, hand: handRes, performance: perf, canvas: image.canvas });\n });\n }\n}\n\nexport { Human as default };\n"], + "mappings": "mMAAA,mBAAM,GAAK,4BAEL,GAAgB,EAEtB,YAAyB,GACvB,KAAM,GAAO,CAAE,QAAS,CAAC,EAAY,GAAI,EAAY,GAAI,QAAS,CAAC,EAAG,IAChE,EAAU,GAChB,OAAS,GAAI,EAAG,EAAI,EAAK,QAAQ,OAAQ,KACvC,KAAM,GAAS,EAAK,QAAQ,GACtB,EAAW,KAAK,MAAO,GAAY,EAAS,GAAK,GACjD,EAAW,KAAK,MAAO,GAAY,EAAS,GAAK,GACjD,EAAa,EAAK,QAAQ,GAChC,OAAS,GAAQ,EAAG,EAAQ,EAAU,KACpC,KAAM,GAAU,EAAU,GAAQ,IAClC,OAAS,GAAQ,EAAG,EAAQ,EAAU,KACpC,KAAM,GAAU,EAAU,GAAQ,IAClC,OAAS,GAAI,EAAG,EAAI,EAAY,IAC9B,EAAQ,KAAK,CAAC,EAAS,MAK/B,MAAO,GAGT,KAAM,IAAa,AAAC,IAClB,EAAI,eAAe,UACnB,EAAI,WAAW,UACf,EAAI,SAAS,WAGT,GAAY,AAAC,GAAoB,EACrC,iBACA,WAAY,EAAG,MAAM,EAAgB,CAAC,EAAG,GAAI,CAAC,GAAI,IAClD,SAAU,EAAG,MAAM,EAAgB,CAAC,EAAG,GAAI,CAAC,GAAI,MAG5C,GAAW,CAAC,EAAK,KACrB,KAAM,GAAS,EAAG,IAAI,EAAI,WAAY,GAChC,EAAO,EAAG,IAAI,EAAI,SAAU,GAC5B,EAAiB,EAAG,SA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U,KAAK,MAAM,IAAQ,GAGlC,EAAK,MAAM,UAGX,KAAM,GAAQ,EAAK,YAAY,aAAe,EAAK,YAAY,aAC3D,KAAK,IAAI,EAAK,YAAY,YAAY,GAAG,GAAK,EAAK,YAAY,YAAY,GAAG,GAAI,EAAK,YAAY,aAAa,GAAG,GAAK,EAAK,YAAY,aAAa,GAAG,IACzJ,EACJ,EAAQ,KAAK,CACX,WAAY,EAAK,WACjB,IAAK,EAAK,IACV,KAAM,EAAK,KACX,YAAa,EAAK,YAClB,IAAK,EAAQ,IACb,OAAQ,EAAQ,OAChB,aAAc,EAAQ,WACtB,QAAS,EACT,KAAO,IAAS,EAAK,KAAK,MAAM,IAAM,KAAmC,GAAQ,IAAM,IAEzF,KAAK,QAAQ,kBAIjB,EAAY,UACZ,KAAK,MAAQ,OAEb,AAAI,KAAK,OAAO,QAAQ,EAAG,SAAS,WACpC,KAAK,QAAQ,cAEb,EAAK,MAAQ,KAAK,MAAM,IAAQ,GAChC,EAAQ,CAAE,KAAM,EAAS,KAAM,EAAS,KAAM,EAAS,YAAa,EAAM,OAAQ,EAAM", "names": [] } diff --git a/dist/human.esm-nobundle.json b/dist/human.esm-nobundle.json index 744c5320..6c75142a 100644 --- a/dist/human.esm-nobundle.json +++ b/dist/human.esm-nobundle.json @@ -116,7 +116,7 @@ "imports": [] }, "src/human.js": { - "bytes": 11405, + "bytes": 11355, "imports": [ { "path": "src/facemesh/facemesh.js" @@ -260,7 +260,7 @@ "dist/human.esm-nobundle.js.map": { "imports": [], "inputs": {}, - "bytes": 228083 + "bytes": 228002 }, "dist/human.esm-nobundle.js": { "imports": [], @@ -356,13 +356,13 @@ "bytesInOutput": 2304 }, "src/human.js": { - "bytesInOutput": 6417 + "bytesInOutput": 6381 }, "src/human.js": { "bytesInOutput": 0 } }, - "bytes": 81881 + "bytes": 81845 } } } diff --git a/dist/human.esm.js b/dist/human.esm.js index b93a8d40..1e1f8afe 100644 --- a/dist/human.esm.js +++ b/dist/human.esm.js @@ -1,39 +1,39 @@ -var Ip=Object.defineProperty;var be=(n,t)=>()=>(t||(t={exports:{}},n(t.exports,t)),t.exports),SI=n=>Ip(n,"__esModule",{value:!0}),Ap=(n,t)=>{SI(n);for(var e in t)Ip(n,e,{get:t[e],enumerable:!0})};var Tp=be(()=>{});var Np=be(()=>{});var ss=be(()=>{});var Ki=be(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});var $o=function(n,t){return $o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,i){e.__proto__=i}||function(e,i){for(var r in i)i.hasOwnProperty(r)&&(e[r]=i[r])},$o(n,t)};function zn(n,t){$o(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function de(n,t,e,i){return new(e||(e=Promise))(function(r,a){function s(u){try{l(i.next(u))}catch(c){a(c)}}function o(u){try{l(i.throw(u))}catch(c){a(c)}}function l(u){u.done?r(u.value):new e(function(c){c(u.value)}).then(s,o)}l((i=i.apply(n,t||[])).next())})}function pe(n,t){var e={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,r,a,s;return s={next:o(0),throw:o(1),return:o(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function o(u){return function(c){return l([u,c])}}function l(u){if(i)throw new TypeError("Generator is already executing.");for(;e;)try{if(i=1,r&&(a=u[0]&2?r.return:u[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,u[1])).done)return a;(r=0,a)&&(u=[u[0]&2,a.value]);switch(u[0]){case 0:case 1:a=u;break;case 4:return e.label++,{value:u[1],done:!1};case 5:e.label++,r=u[1],u=[0];continue;case 7:u=e.ops.pop(),e.trys.pop();continue;default:if(!(a=e.trys,a=a.length>0&&a[a.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!a||u[1]>a[0]&&u[1]0;)i=Math.random()*t|0,t--,e=n[t],n[t]=n[i],n[i]=e}function oa(n,t,e){return Math.max(n,Math.min(t,e))}function WI(n){return n%2===0?n:n+1}function UI(n){for(var t=0,e=0;e=e){r();return}setTimeout(s,o)};s()})}function Df(n,t){for(var e=1,i=-1,r=0;r=0)e*=n[r];else if(n[r]===-1){if(i!==-1)throw Error("Shapes can only have 1 implicit size. "+("Found -1 at dim "+i+" and dim "+r));i=r}else if(n[r]<0)throw Error("Shapes can not be < 0. Found "+n[r]+" at dim "+r);if(i===-1){if(t>0&&t!==e)throw Error("Size("+t+") must match the product of shape "+n);return n}if(e===0)throw Error("Cannot infer the missing size in ["+n+"] when there are 0 elements");if(t%e!==0)throw Error("The implicit shape can't be a fractional number. "+("Got "+t+" / "+e));var a=n.slice();return a[i]=t/e,a}function Ze(n,t){var e=t.length;return n=n==null?t.map(function(i,r){return r}):[].concat(n),D(n.every(function(i){return i>=-e&&io)&&n[o]===1&&(e.push(n[o]),i.push(o)),a[s]<=o&&s++}n[o]!==1&&(e.push(n[o]),i.push(o))}return{newShape:e,keptDims:i}}function cs(n,t){var e=null;if(n==null||n==="float32")e=new Float32Array(t);else if(n==="int32")e=new Int32Array(t);else if(n==="bool")e=new Uint8Array(t);else throw new Error("Unknown data type "+n);return e}function Ff(n,t){var e=null;if(n==null||n==="float32")e=new Float32Array(t);else if(n==="int32")e=new Int32Array(t);else if(n==="bool")e=new Uint8Array(t);else if(n==="string")e=new Array(t);else throw new Error("Unknown data type "+n);return e}function Wf(n,t){for(var e=0;e=0;--i)e[i]=e[i+1]*n[i+1];return e}function qI(n,t){return t==="string"?Mu(n):ps([n],t)}function ps(n,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(n)&&(n=Di(n)),Me().getBool("DEBUG")&&Wf(n,t),GI(n,t))return n;if(t==null||t==="float32"||t==="complex64")return new Float32Array(n);if(t==="int32")return new Int32Array(n);if(t==="bool"){for(var e=new Uint8Array(n.length),i=0;i=0,function(){return"Tensor must have a shape comprised of positive integers but got "+("shape ["+n+"].")})})}function KI(n,t){return Me().platform.fetch(n,t)}function Mu(n,t){return t===void 0&&(t="utf-8"),t=t||"utf-8",Me().platform.encode(n,t)}function Gu(n,t){return t===void 0&&(t="utf-8"),t=t||"utf-8",Me().platform.decode(n,t)}function jI(n,t,e){if(t===0)return 0;if(t===1)return n[0];for(var i=n[n.length-1],r=0;r0?m:"")+" "}}console.log("%c"+l+" %c"+o+" %c"+u+"D "+h+" %c"+c+" %c"+d+" %c"+s,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},n}();function e2(n,t,e){for(var i={},r={},a=0;a=0;a--)for(var s=n[a],o=s.inputs,h=0;h=0;a--)r(a)}var Vf=20,ua=3,Yu=7;function i2(n,t,e,i){var r=mr(t),a=n2(n,t,e,r),s=t.length,o=fs(n,t,e,r,a),l=["Tensor"];return i&&(l.push(" dtype: "+e),l.push(" rank: "+s),l.push(" shape: ["+t+"]"),l.push(" values:")),l.push(o.map(function(u){return" "+u}).join(` +var Ip=Object.defineProperty;var be=(n,t)=>()=>(t||(t={exports:{}},n(t.exports,t)),t.exports),LI=n=>Ip(n,"__esModule",{value:!0}),Ap=(n,t)=>{LI(n);for(var e in t)Ip(n,e,{get:t[e],enumerable:!0})};var Tp=be(()=>{});var Np=be(()=>{});var ss=be(()=>{});var Ki=be(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});var $o=function(n,t){return $o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,i){e.__proto__=i}||function(e,i){for(var r in i)i.hasOwnProperty(r)&&(e[r]=i[r])},$o(n,t)};function zn(n,t){$o(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function de(n,t,e,i){return new(e||(e=Promise))(function(r,a){function s(u){try{l(i.next(u))}catch(c){a(c)}}function o(u){try{l(i.throw(u))}catch(c){a(c)}}function l(u){u.done?r(u.value):new e(function(c){c(u.value)}).then(s,o)}l((i=i.apply(n,t||[])).next())})}function pe(n,t){var e={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,r,a,s;return s={next:o(0),throw:o(1),return:o(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function o(u){return function(c){return l([u,c])}}function l(u){if(i)throw new TypeError("Generator is already executing.");for(;e;)try{if(i=1,r&&(a=u[0]&2?r.return:u[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,u[1])).done)return a;(r=0,a)&&(u=[u[0]&2,a.value]);switch(u[0]){case 0:case 1:a=u;break;case 4:return e.label++,{value:u[1],done:!1};case 5:e.label++,r=u[1],u=[0];continue;case 7:u=e.ops.pop(),e.trys.pop();continue;default:if(!(a=e.trys,a=a.length>0&&a[a.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!a||u[1]>a[0]&&u[1]0;)i=Math.random()*t|0,t--,e=n[t],n[t]=n[i],n[i]=e}function oa(n,t,e){return Math.max(n,Math.min(t,e))}function UI(n){return n%2===0?n:n+1}function BI(n){for(var t=0,e=0;e=e){r();return}setTimeout(s,o)};s()})}function Df(n,t){for(var e=1,i=-1,r=0;r=0)e*=n[r];else if(n[r]===-1){if(i!==-1)throw Error("Shapes can only have 1 implicit size. "+("Found -1 at dim "+i+" and dim "+r));i=r}else if(n[r]<0)throw Error("Shapes can not be < 0. Found "+n[r]+" at dim "+r);if(i===-1){if(t>0&&t!==e)throw Error("Size("+t+") must match the product of shape "+n);return n}if(e===0)throw Error("Cannot infer the missing size in ["+n+"] when there are 0 elements");if(t%e!==0)throw Error("The implicit shape can't be a fractional number. "+("Got "+t+" / "+e));var a=n.slice();return a[i]=t/e,a}function Ze(n,t){var e=t.length;return n=n==null?t.map(function(i,r){return r}):[].concat(n),D(n.every(function(i){return i>=-e&&io)&&n[o]===1&&(e.push(n[o]),i.push(o)),a[s]<=o&&s++}n[o]!==1&&(e.push(n[o]),i.push(o))}return{newShape:e,keptDims:i}}function cs(n,t){var e=null;if(n==null||n==="float32")e=new Float32Array(t);else if(n==="int32")e=new Int32Array(t);else if(n==="bool")e=new Uint8Array(t);else throw new Error("Unknown data type "+n);return e}function Ff(n,t){var e=null;if(n==null||n==="float32")e=new Float32Array(t);else if(n==="int32")e=new Int32Array(t);else if(n==="bool")e=new Uint8Array(t);else if(n==="string")e=new Array(t);else throw new Error("Unknown data type "+n);return e}function Wf(n,t){for(var e=0;e=0;--i)e[i]=e[i+1]*n[i+1];return e}function GI(n,t){return t==="string"?Mu(n):ps([n],t)}function ps(n,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(n)&&(n=Di(n)),Me().getBool("DEBUG")&&Wf(n,t),YI(n,t))return n;if(t==null||t==="float32"||t==="complex64")return new Float32Array(n);if(t==="int32")return new Int32Array(n);if(t==="bool"){for(var e=new Uint8Array(n.length),i=0;i=0,function(){return"Tensor must have a shape comprised of positive integers but got "+("shape ["+n+"].")})})}function jI(n,t){return Me().platform.fetch(n,t)}function Mu(n,t){return t===void 0&&(t="utf-8"),t=t||"utf-8",Me().platform.encode(n,t)}function Gu(n,t){return t===void 0&&(t="utf-8"),t=t||"utf-8",Me().platform.decode(n,t)}function $I(n,t,e){if(t===0)return 0;if(t===1)return n[0];for(var i=n[n.length-1],r=0;r0?m:"")+" "}}console.log("%c"+l+" %c"+o+" %c"+u+"D "+h+" %c"+c+" %c"+d+" %c"+s,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},n}();function t2(n,t,e){for(var i={},r={},a=0;a=0;a--)for(var s=n[a],o=s.inputs,h=0;h=0;a--)r(a)}var Vf=20,ua=3,Yu=7;function r2(n,t,e,i){var r=mr(t),a=i2(n,t,e,r),s=t.length,o=fs(n,t,e,r,a),l=["Tensor"];return i&&(l.push(" dtype: "+e),l.push(" rank: "+s),l.push(" shape: ["+t+"]"),l.push(" values:")),l.push(o.map(function(u){return" "+u}).join(` `)),l.join(` -`)}function n2(n,t,e,i){var r=st(t),a=i[i.length-1],s=new Array(a).fill(0),o=t.length,l=e==="complex64"?ha(n):n;if(o>1)for(var u=0;uVf){var c=ua*s,h=Array.from(n.slice(0,c)),d=Array.from(n.slice((o-ua)*s,o*s));return e==="complex64"&&(h=ha(h),d=ha(d)),["["+h.map(function(I,C){return ca(I,r[C],e)}).join(", ")+", ..., "+d.map(function(I,C){return ca(I,r[o-ua+C],e)}).join(", ")+"]"]}var p=e==="complex64"?ha(n):Array.from(n);return["["+p.map(function(I,C){return ca(I,r[C],e)}).join(", ")+"]"]}var f=t.slice(1),m=i.slice(1),g=i[0]*s,v=[];if(o>Vf){for(var b=0;b1)for(var u=0;uVf){var c=ua*s,h=Array.from(n.slice(0,c)),d=Array.from(n.slice((o-ua)*s,o*s));return e==="complex64"&&(h=ha(h),d=ha(d)),["["+h.map(function(I,C){return ca(I,r[C],e)}).join(", ")+", ..., "+d.map(function(I,C){return ca(I,r[o-ua+C],e)}).join(", ")+"]"]}var p=e==="complex64"?ha(n):Array.from(n);return["["+p.map(function(I,C){return ca(I,r[C],e)}).join(", ")+"]"]}var f=t.slice(1),m=i.slice(1),g=i[0]*s,v=[];if(o>Vf){for(var b=0;b=this.shape[i]){var o="Requested out of range element at "+t+". "+(" Buffer shape="+this.shape);throw new Error(o)}i++}for(var l=t[t.length-1],u=0;u0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak "+("("+o+" data ids) after running '"+t+"'"))},n.prototype.runKernelFunc=function(t,e,i,r,a,s,o){var l=this,u,c=[],h=this.isTapeOn();r==null&&(r=this.state.activeScope!=null?this.state.activeScope.name:"");var d=this.state.numBytes,p=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var f,m=_u(r,this.backendName),g;if(m!=null)f=function(){var S=l.backend.numDataIds();g=m.kernelFunc({inputs:e,attrs:a,backend:l.backend});var L=Array.isArray(g)?g:[g];l.shouldCheckForMemLeaks()&&l.checkKernelForMemLeak(r,S,L);var w=L.map(function(C){var E=C.dataId,k=C.shape,W=C.dtype;return l.makeTensorFromDataId(E,k,W)});if(h){var N=l.getTensorsForGradient(r,e,w);if(N==null){o==null&&(o=[]);var I=w.filter(function(C,E){return o[E]});N=(s||[]).slice().concat(I)}c=l.saveTensorsForBackwardMode(N)}return w};else{var v=function(S){if(!h)return;c=S.map(function(L){return l.keep(l.clone(L))})};f=function(){var S=l.backend.numDataIds();g=l.tidy(function(){return t(l.backend,v)});var L=Array.isArray(g)?g:[g];return l.shouldCheckForMemLeaks()&&l.checkKernelForMemLeak(r,S,L),L}}var b;return this.scopedRun(function(){return l.state.kernelDepth++},function(){return l.state.kernelDepth--},function(){!l.ENV.getBool("DEBUG")&&!l.state.profiling?u=f():(b=l.profiler.profileKernel(r,e,function(){return f()}),l.ENV.getBool("DEBUG")&&l.profiler.logKernelProfile(b),u=b.outputs)}),h&&this.addTapeNode(r,e,u,i,c,a),this.state.profiling&&this.state.activeProfile.kernels.push({name:r,bytesAdded:this.state.numBytes-d,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-p,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(e).map(function(S){return e[S]!=null?e[S].shape:null}),outputShapes:u.map(function(S){return S.shape}),kernelTimeMs:b.timeMs,extraInfo:b.extraInfo}),Array.isArray(g)?u:u[0]},n.prototype.saveTensorsForBackwardMode=function(t){var e=this,i=t.map(function(r){return e.keep(e.clone(r))});return i},n.prototype.getTensorsForGradient=function(t,e,i){var r=Pu(t);if(r!=null){var a=r.inputsToSave||[],s=r.outputsToSave||[],o=void 0;r.saveAllInputs?(D(Array.isArray(e),function(){return"saveAllInputs is true, expected inputs to be an array."}),o=Object.keys(e).map(function(u){return e[u]})):o=a.map(function(u){return e[u]});var l=i.filter(function(u,c){return s[c]});return o.concat(l)}return null},n.prototype.makeTensor=function(t,e,i,r){if(t==null)throw new Error("Values passed to engine.makeTensor() are null");i=i||"float32",r=r||this.backend;var a=t;i==="string"&&Zn(t[0])&&(a=t.map(function(c){return Mu(c)}));var s=r.write(a,e,i),o=new Y(e,i,s,this.nextTensorId());if(this.incRef(o,r),i==="string"){var l=this.state.tensorInfo.get(s),u=_f(a);this.state.numBytes+=u-l.bytes,l.bytes=u}return o},n.prototype.makeTensorFromDataId=function(t,e,i,r){i=i||"float32";var a=new Y(e,i,t,this.nextTensorId());return this.incRef(a,r),a},n.prototype.makeVariable=function(t,e,i,r){e===void 0&&(e=!0),i=i||this.nextVariableId().toString(),r!=null&&r!==t.dtype&&(t=t.cast(r));var a=new da(t,e,i,this.nextTensorId());if(this.state.registeredVariables[a.name]!=null)throw new Error("Variable with name "+a.name+" was already registered");return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a},n.prototype.incRef=function(t,e){var i=this.state.tensorInfo.has(t.dataId)?this.state.tensorInfo.get(t.dataId).refCount:0;if(this.state.numTensors++,t.dtype==="string"&&this.state.numStringTensors++,i===0){this.state.numDataBuffers++;var r=0;t.dtype!=="complex64"&&t.dtype!=="string"&&(r=t.size*zf(t.dtype)),this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:r,refCount:0}),this.state.numBytes+=r}this.state.tensorInfo.get(t.dataId).refCount++,t instanceof da||this.track(t)},n.prototype.disposeTensor=function(t){if(!this.state.tensorInfo.has(t.dataId))return;this.state.numTensors--,t.dtype==="string"&&this.state.numStringTensors--;var e=this.state.tensorInfo.get(t.dataId),i=e.refCount;i<=1?(t.dtype!=="complex64"&&(this.state.numBytes-=e.bytes),this.state.numDataBuffers--,e.backend.disposeData(t.dataId),this.state.tensorInfo.delete(t.dataId)):this.state.tensorInfo.get(t.dataId).refCount--},n.prototype.disposeVariables=function(){for(var t in this.state.registeredVariables){var e=this.state.registeredVariables[t];this.disposeVariable(e)}},n.prototype.disposeVariable=function(t){this.disposeTensor(t),this.state.registeredVariables[t.name]!=null&&delete this.state.registeredVariables[t.name]},n.prototype.memory=function(){var t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,t.reasons==null&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t},n.prototype.profile=function(t){return de(this,void 0,void 0,function(){var e,i,r,a,s,o,l,u;return pe(this,function(c){switch(c.label){case 0:return this.state.profiling=!0,e=this.state.numBytes,i=this.state.numTensors,this.state.activeProfile.kernels=[],r=this.state.activeProfile,[4,t()];case 1:r.result=c.sent(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map(function(h){return h.totalBytesSnapshot})),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-i,a=0,s=this.state.activeProfile.kernels,c.label=2;case 2:return a0&&this.state.kernelDepth===0},n.prototype.addTapeNode=function(t,e,i,r,a,s){var o=this,l={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:i,saved:a},u=Pu(t);u!=null&&(r=u.gradFunc),r!=null&&(l.gradient=function(c){return c=c.map(function(h,d){if(h==null){var p=i[d],f=vr(p.size,p.dtype);return o.makeTensor(f,p.shape,p.dtype)}return h}),r(c.length>1?c:c[0],a,s)}),this.state.activeTape.push(l)},n.prototype.keep=function(t){return t.kept=!0,t},n.prototype.startTape=function(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++},n.prototype.endTape=function(){this.state.gradientDepth--},n.prototype.startScope=function(t){var e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(e.name=t),this.state.scopeStack.push(e),this.state.activeScope=e},n.prototype.endScope=function(t){for(var e=this,i=Ju(t),r=new Set(i.map(function(l){return l.id})),a=0;a0,function(){return"gradients() received an empty list of xs."}),i!=null&&i.dtype!=="float32")throw new Error("dy must have 'float32' dtype, but has '"+i.dtype+"'");var s=this.scopedRun(function(){return a.startTape()},function(){return a.endTape()},function(){return a.tidy("forward",t)});D(s instanceof Y,function(){return"The result y returned by f() must be a tensor."});var o=e2(this.state.activeTape,e,s);if(!r&&o.length===0&&e.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",function(){var l={};l[s.id]=i??h2(s.shape),t2(l,o,function(c){return a.tidy(c)},d2);var u=e.map(function(c){return l[c.id]});return a.state.gradientDepth===0&&(a.state.activeTape.forEach(function(c){for(var h=0,d=c.saved;h0,function(){return"Element arr["+e.join("][")+"] should be a primitive, "+("but is an array of "+n.length+" elements")}),D(n.length===t[0],function(){return"Element arr["+e.join("][")+"] should have "+t[0]+" "+("elements, but has "+n.length+" elements")});for(var i=t.slice(1),r=0;r=0&&(r=i),Jf(i,r,t,e),n==null||!Ot(n)&&!Array.isArray(n)&&typeof n!="number"&&typeof n!="boolean"&&typeof n!="string"){var a=n==null?"null":n.constructor.name;throw new Error("Argument '"+t+"' passed to '"+e+"' must be a "+("Tensor or TensorLike, but got '"+a+"'"))}var s=An(n,r);!Ot(n)&&!Array.isArray(n)&&(n=[n]);var o=!0,l=r!=="string"?ps(n,r):Di(n,[],o);return z.makeTensor(l,s,r)}function pa(n,t,e,i){if(i===void 0&&(i="numeric"),!Array.isArray(n))throw new Error("Argument "+t+" passed to "+e+" must be a `Tensor[]` or `TensorLike[]`");var r=n;return r.map(function(a,s){return O(a,t+"["+s+"]",e)},i)}var Zf="__op";function U(n){var t=Object.keys(n);if(t.length!==1)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+(t.length+" keys."));var e=t[0],i=n[e];e.endsWith("_")&&(e=e.substring(0,e.length-1)),e=e+Zf;var r=function(){for(var a=[],s=0;s>10]+(o&1023)]+t[o>>10];a[s]=l}return new Float32Array(r)}}var Jt=function(){function n(){this.saveRouters=[],this.loadRouters=[]}return n.getInstance=function(){return n.instance==null&&(n.instance=new n),n.instance},n.registerSaveRouter=function(t){n.getInstance().saveRouters.push(t)},n.registerLoadRouter=function(t){n.getInstance().loadRouters.push(t)},n.getSaveHandlers=function(t){return n.getHandlers(t,"save")},n.getLoadHandlers=function(t,e){return n.getHandlers(t,"load",e)},n.getHandlers=function(t,e,i){var r=[],a=e==="load"?n.getInstance().loadRouters:n.getInstance().saveRouters;return a.forEach(function(s){var o=s(t,i);o!==null&&r.push(o)}),r},n}(),N2=function(n){return Jt.registerSaveRouter(n)},x2=function(n){return Jt.registerLoadRouter(n)},C2=function(n){return Jt.getSaveHandlers(n)},R2=function(n,t){return Jt.getLoadHandlers(n,t)};var tc="tensorflowjs",nc=1,ki="models_store",ii="model_info_store";function nm(){if(!Me().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var n=typeof window=="undefined"?self:window,t=n.indexedDB||n.mozIndexedDB||n.webkitIndexedDB||n.msIndexedDB||n.shimIndexedDB;if(t==null)throw new Error("The current browser does not appear to support IndexedDB.");return t}function ic(n){var t=n.result;t.createObjectStore(ki,{keyPath:"modelPath"}),t.createObjectStore(ii,{keyPath:"modelPath"})}var br=function(){function n(t){if(this.indexedDB=nm(),t==null||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}return n.prototype.save=function(t){return de(this,void 0,void 0,function(){return pe(this,function(e){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,t)]})})},n.prototype.load=function(){return de(this,void 0,void 0,function(){return pe(this,function(t){return[2,this.databaseAction(this.modelPath)]})})},n.prototype.databaseAction=function(t,e){var i=this;return new Promise(function(r,a){var s=i.indexedDB.open(tc,nc);s.onupgradeneeded=function(){return ic(s)},s.onsuccess=function(){var o=s.result;if(e==null){var l=o.transaction(ki,"readonly"),u=l.objectStore(ki),c=u.get(i.modelPath);c.onsuccess=function(){if(c.result==null)return o.close(),a(new Error("Cannot find model with path '"+i.modelPath+"' in IndexedDB."));r(c.result.modelArtifacts)},c.onerror=function(g){return o.close(),a(c.error)},l.oncomplete=function(){return o.close()}}else{var h=fa(e),d=o.transaction(ii,"readwrite"),p=d.objectStore(ii),f=p.put({modelPath:i.modelPath,modelArtifactsInfo:h}),m;f.onsuccess=function(){m=o.transaction(ki,"readwrite");var g=m.objectStore(ki),v=g.put({modelPath:i.modelPath,modelArtifacts:e,modelArtifactsInfo:h});v.onsuccess=function(){return r({modelArtifactsInfo:h})},v.onerror=function(b){p=d.objectStore(ii);var S=p.delete(i.modelPath);S.onsuccess=function(){return o.close(),a(v.error)},S.onerror=function(L){return o.close(),a(v.error)}}},f.onerror=function(g){return o.close(),a(f.error)},d.oncomplete=function(){m==null?o.close():m.oncomplete=function(){return o.close()}}}},s.onerror=function(o){return a(s.error)}})},n.URL_SCHEME="indexeddb://",n}(),im=function(n){return Me().getBool("IS_BROWSER")&&(!Array.isArray(n)&&n.startsWith(br.URL_SCHEME))?O2(n.slice(br.URL_SCHEME.length)):null};Jt.registerSaveRouter(im);Jt.registerLoadRouter(im);function O2(n){return new br(n)}function E2(n){return n.startsWith(br.URL_SCHEME)?n.slice(br.URL_SCHEME.length):n}var D2=function(){function n(){this.indexedDB=nm()}return n.prototype.listModels=function(){return de(this,void 0,void 0,function(){var t=this;return pe(this,function(e){return[2,new Promise(function(i,r){var a=t.indexedDB.open(tc,nc);a.onupgradeneeded=function(){return ic(a)},a.onsuccess=function(){var s=a.result,o=s.transaction(ii,"readonly"),l=o.objectStore(ii),u=l.getAll();u.onsuccess=function(){for(var c={},h=0,d=u.result;h0,function(){return"scheme must not be an empty string."});var i=n.getInstance();D(i.managers[t]==null,function(){return"A model store manager is already registered for scheme '"+t+"'."}),i.managers[t]=e},n.getManager=function(t){var e=this.getInstance().managers[t];if(e==null)throw new Error("Cannot find model manager for scheme '"+t+"'");return e},n.getSchemes=function(){return Object.keys(this.getInstance().managers)},n}();function ys(n){if(n.indexOf(Lr)===-1)throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+(""+ri.getSchemes().join(",")));return{scheme:n.split(Lr)[0],path:n.split(Lr)[1]}}function om(n,t,e){return e===void 0&&(e=!1),de(this,void 0,void 0,function(){var i,r,a,s,o,l,u,c,h;return pe(this,function(d){switch(d.label){case 0:return D(n!==t,function(){return"Old path and new path are the same: '"+n+"'"}),i=Jt.getLoadHandlers(n),D(i.length>0,function(){return"Copying failed because no load handler is found for source URL "+n+"."}),D(i.length<2,function(){return"Copying failed because more than one ("+i.length+") "+("load handlers for source URL "+n+".")}),r=i[0],a=Jt.getSaveHandlers(t),D(a.length>0,function(){return"Copying failed because no save handler is found for destination "+("URL "+t+".")}),D(a.length<2,function(){return"Copying failed because more than one ("+i.length+") "+("save handlers for destination URL "+t+".")}),s=a[0],o=ys(n).scheme,l=ys(n).path,u=o===ys(n).scheme,[4,r.load()];case 1:return c=d.sent(),e&&u?[4,ri.getManager(o).removeModel(l)]:[3,3];case 2:d.sent(),d.label=3;case 3:return[4,s.save(c)];case 4:return h=d.sent(),e&&!u?[4,ri.getManager(o).removeModel(l)]:[3,6];case 5:d.sent(),d.label=6;case 6:return[2,h.modelArtifactsInfo]}})})}function M2(){return de(this,void 0,void 0,function(){var n,t,e,i,r,a,s,o;return pe(this,function(l){switch(l.label){case 0:n=ri.getSchemes(),t={},e=0,i=n,l.label=1;case 1:return e0,function(){return"promises must be a none empty array"})}function o(l,u){D(l>=0&&l<=1,function(){return"Progress fraction must be in range [0, 1], but "+("got startFraction "+l)}),D(u>=0&&u<=1,function(){return"Progress fraction must be in range [0, 1], but "+("got endFraction "+u)}),D(u>=l,function(){return"startFraction must be no more than endFraction, but "+("got startFraction "+l+" and endFraction ")+(""+u)})}return Promise.all(n.map(a))}function hm(n,t){return de(this,void 0,void 0,function(){var e,i,r,a,s,o,l,u,c,h,d;return pe(this,function(p){switch(p.label){case 0:return t==null&&(t={}),e=t.fetchFunc==null?Me().platform.fetch:t.fetchFunc,i=n.map(function(f){return e(f,t.requestInit,{isBinary:!0})}),r=0,a=.5,t.onProgress==null?[4,Promise.all(i)]:[3,2];case 1:return o=p.sent(),[3,4];case 2:return[4,cm(i,t.onProgress,r,a)];case 3:o=p.sent(),p.label=4;case 4:return s=o,l=s.map(function(f){return f.arrayBuffer()}),u=.5,c=1,t.onProgress==null?[4,Promise.all(l)]:[3,6];case 5:return d=p.sent(),[3,8];case 6:return[4,cm(l,t.onProgress,u,c)];case 7:d=p.sent(),p.label=8;case 8:return h=d,[2,h]}})})}function rA(n,t,e,i){return t===void 0&&(t=""),de(this,void 0,void 0,function(){var r,a;return pe(this,function(s){return r=function(o){return hm(o,{requestInit:i})},a=dm(r),[2,a(n,t,e)]})})}function dm(n){var t=this;return function(e,i,r){return i===void 0&&(i=""),de(t,void 0,void 0,function(){var a,s,o,l,u,c,h,d,p,f;return pe(this,function(m){switch(m.label){case 0:if(a=e.map(function(){return!1}),s={},o=r!=null?r.map(function(){return!1}):[],l=[],e.forEach(function(g,v){var b=0;g.weights.forEach(function(S){var L="quantization"in S?S.quantization.dtype:S.dtype,w=Zu[L]*st(S.shape),N=function(){a[v]=!0,s[v]==null&&(s[v]=[]),s[v].push({manifestEntry:S,groupOffset:b,sizeBytes:w})};r!=null?r.forEach(function(I,C){I===S.name&&(N(),o[C]=!0)}):N(),l.push(S.name),b+=w})}),!o.every(function(g){return g}))throw u=r.filter(function(g,v){return!o[v]}),new Error("Could not find weights in manifest with names: "+(u.join(", ")+`. -`)+"Manifest JSON has weights with names: "+(l.join(", ")+"."));return c=a.reduce(function(g,v,b){return v&&g.push(b),g},[]),h=[],c.forEach(function(g){e[g].paths.forEach(function(v){var b=i+(i.endsWith("/")?"":"/")+v;h.push(b)})}),[4,n(h)];case 1:return d=m.sent(),p={},f=0,c.forEach(function(g){for(var v=e[g].paths.length,b=0,S=0;S0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(t)&&D(t.length===2,function(){return"URL paths for http must have a length of 2, "+("(actual length is "+t.length+").")}),this.path=t,e.requestInit!=null&&e.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}return n.prototype.save=function(t){return de(this,void 0,void 0,function(){var e,i,r,a;return pe(this,function(s){switch(s.label){case 0:if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit),e.body=new FormData,i=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata,weightsManifest:i},e.body.append("model.json",new Blob([JSON.stringify(r)],{type:sA}),"model.json"),t.weightData!=null&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:aA}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if(a=s.sent(),a.ok)return[2,{modelArtifactsInfo:fa(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+(a.status+"."))}})})},n.prototype.load=function(){return de(this,void 0,void 0,function(){var t,e,i,r,a,s,o,l,u,c,h,d,p,f,m;return pe(this,function(g){switch(g.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(t=g.sent(),!t.ok)throw new Error("Request to "+this.path+" failed with status code "+(t.status+". Please verify this URL points to ")+"the model JSON of the model to load.");g.label=2;case 2:return g.trys.push([2,4,,5]),[4,t.json()];case 3:return e=g.sent(),[3,5];case 4:throw i=g.sent(),r="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?r+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":r+=" Please make sure the server is serving valid JSON for this request.",new Error(r);case 5:if(a=e.modelTopology,s=e.weightsManifest,o=e.generatedBy,l=e.convertedBy,u=e.format,c=e.userDefinedMetadata,a==null&&s==null)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return s!=null?[4,this.loadWeights(s)]:[3,7];case 6:p=g.sent(),h=p[0],d=p[1],g.label=7;case 7:return f={modelTopology:a,weightSpecs:h,weightData:d,userDefinedMetadata:c,generatedBy:o,convertedBy:l,format:u},m=e.modelInitializer,m&&(f.modelInitializer=m),[2,f]}})})},n.prototype.loadWeights=function(t){return de(this,void 0,void 0,function(){var e,i,r,a,s,o,l,u,c,h,d,p,f,m,g,v,b,S,L,w,N;return pe(this,function(I){switch(I.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,i=oA(e),r=i[0],a=i[1],s=this.weightPathPrefix||r,o=[],l=0,u=t;lt?n.substring(e):"";return[i+"/",r]}function sc(n){return n.match(pm.URL_SCHEME_REGEX)!=null}var fm=function(n,t){if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;var e=!0;return Array.isArray(n)?e=n.every(function(i){return sc(i)}):e=sc(n),e?oc(n,t):null};Jt.registerSaveRouter(fm);Jt.registerLoadRouter(fm);function oc(n,t){return new pm(n,t)}function lA(n,t){return oc(n,t)}var lc=function(){function n(t){this.modelArtifacts=t}return n.prototype.load=function(){return de(this,void 0,void 0,function(){return pe(this,function(t){return[2,this.modelArtifacts]})})},n}(),uA=function(){function n(t){this.saveHandler=t}return n.prototype.save=function(t){return de(this,void 0,void 0,function(){return pe(this,function(e){return[2,this.saveHandler(t)]})})},n}();function cA(n,t,e,i){if(arguments.length===1){var r=n.modelTopology!=null||n.weightSpecs!=null;return r?new lc(n):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new lc({modelTopology:n}))}else return console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new lc({modelTopology:n,weightSpecs:t,weightData:e,trainingConfig:i})}function hA(n){return new uA(n)}var dA={__proto__:null,browserFiles:iA,browserHTTPRequest:lA,concatenateArrayBuffers:ec,decodeWeights:Qf,encodeWeights:b2,fromMemory:cA,getLoadHandlers:R2,getModelArtifactsInfoForJSON:fa,getSaveHandlers:C2,http:oc,isHTTPScheme:sc,loadWeights:rA,registerLoadRouter:x2,registerSaveRouter:N2,weightsLoaderFactory:dm,withSaveHandler:hA,copyModel:V2,listModels:M2,moveModel:q2,removeModel:H2};function pA(n,t){var e=O(n,"x","reshape",null),i={x:e},r={shape:t},a=function(s,o){return t=Df(t,e.size),D(e.size===st(t),function(){return"new shape and old shape must have the same number of elements."}),o([e]),s.reshape(e,t)};return z.runKernelFunc(a,i,null,ru,r)}var V=U({reshape_:pA});function fA(n,t,e,i){var r;e===void 0&&(e=!1),i===void 0&&(i=!1);var a=O(n,"a","matMul"),s=O(t,"b","matMul");r=rt(a,s),a=r[0],s=r[1],D(a.rank>=2&&s.rank>=2&&a.rank===s.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, "+("got ranks "+a.rank+" and "+s.rank+".")});var o=e?a.shape[a.rank-2]:a.shape[a.rank-1],l=i?s.shape[s.rank-1]:s.shape[s.rank-2],u=e?a.shape[a.rank-1]:a.shape[a.rank-2],c=i?s.shape[s.rank-2]:s.shape[s.rank-1],h=a.shape.slice(0,-2),d=s.shape.slice(0,-2),p=st(h),f=st(d);D(an(h,d),function(){return"Error in matMul: outer dimensions ("+h+") and ("+(d+") of Tensors with shapes "+a.shape+" and ")+(s.shape+" must match.")}),D(o===l,function(){return"Error in matMul: inner shapes ("+o+") and ("+(l+") of Tensors with shapes "+a.shape+" and ")+(s.shape+" and transposeA="+e)+(" and transposeB="+i+" must match.")});var m=a.shape.slice(0,-2).concat([u,c]),g=e?V(a,[p,o,u]):V(a,[p,u,o]),v=i?V(s,[f,c,l]):V(s,[f,l,c]),b=function(N,I){return I([g,v]),N.batchMatMul(g,v,e,i)},S={a:g,b:v},L={transposeA:e,transposeB:i},w=z.runKernelFunc(b,S,null,cl,L);return V(w,m)}var Fe=U({matMul_:fA});function mA(n,t,e,i){if(e===void 0&&(e=1),i===void 0&&(i=0),t<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+t);var r=O(n,"indices","oneHot","int32"),a=r.shape.concat([t]),s=function(u,c){return c([r]),V(u.oneHot(V(r,[r.size]),t,e,i),a)},o={indices:r},l={depth:t,onValue:e,offValue:i};return z.runKernelFunc(s,o,null,Zl,l)}var bs=U({oneHot_:mA});function gA(n,t){var e=O(n,"x","transpose");if(t==null&&(t=e.shape.map(function(a,s){return s}).reverse()),D(e.rank===t.length,function(){return"Error in transpose: rank of input "+e.rank+" "+("must match length of perm "+t+".")}),t.forEach(function(a){D(a>=0&&a0&&Number.isInteger(e),function(){return"If provided, numClasses must be a positive integer, "+("but got "+e)}),D(i.rank===1,function(){return"Expected the rank of labels to be 1, but got "+i.rank}),D(r.rank===1,function(){return"Expected the rank of predictions to be 1, "+("but got "+r.rank)}),D(i.shape[0]===r.shape[0],function(){return"Mismatch in the number of examples: "+(i.shape[0]+" vs. "+r.shape[0]+". ")+"Labels and predictions should have the same number of elements."}),D(e>0&&Number.isInteger(e),function(){return"numClasses is required to be a positive integer, but got "+(""+e)});var a=bs(ue(i,"int32"),e),s=bs(ue(r,"int32"),e),o=lt(a);return ue(Fe(o,s),"int32")}var yA=U({confusionMatrix_:vA});var bA={__proto__:null,confusionMatrix:yA};function mm(n,t,e){if(Ei(n),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");var i=An(n,e);if(i.length!==3&&i.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(i.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return ti(n,t,i,e)}var Ir;function wA(n,t){if(t===void 0&&(t=3),t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(n==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var e=!1,i=!1,r=!1,a=!1,s=!1;if(n.data instanceof Uint8Array)e=!0;else if(typeof ImageData!="undefined"&&n instanceof ImageData)i=!0;else if(typeof HTMLVideoElement!="undefined"&&n instanceof HTMLVideoElement)r=!0;else if(typeof HTMLImageElement!="undefined"&&n instanceof HTMLImageElement)a=!0;else if(n.getContext!=null)s=!0;else throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, "+("but was "+n.constructor.name));if(r){var o=2;if(r&&n.readyState element.")}var l=_u(Fu,z.backendName);if(l!=null){var u={pixels:n},c={numChannels:t};return z.runKernel(Fu,u,c)}var h=r?[n.videoWidth,n.videoHeight]:[n.width,n.height],d=h[0],p=h[1],f;s?f=n.getContext("2d").getImageData(0,0,d,p).data:i||e?f=n.data:(a||r)&&(Ir==null&&(Ir=document.createElement("canvas").getContext("2d")),Ir.canvas.width=d,Ir.canvas.height=p,Ir.drawImage(n,0,0,d,p),f=Ir.getImageData(0,0,d,p).data);var m;if(t===4)m=new Int32Array(f);else{var g=d*p;m=new Int32Array(g*t);for(var v=0;v4||o===2)throw new Error("toPixels only supports depth of size "+("1, 3 or 4 but got "+o));if(e.dtype!=="float32"&&e.dtype!=="int32")throw new Error("Unsupported type for toPixels: "+e.dtype+". Please use float32 or int32 tensors.");return[4,e.data()];case 1:for(l=b.sent(),u=e.dtype==="float32"?255:1,c=new Uint8ClampedArray(s*a*4),h=0;h1)throw new Error("Tensor values for a float32 Tensor must be in the "+("range [0 - 1] but encountered "+f+"."))}else if(e.dtype==="int32"&&(f<0||f>255))throw new Error("Tensor values for a int32 Tensor must be in the "+("range [0 - 255] but encountered "+f+"."));o===1?(d[0]=f*u,d[1]=f*u,d[2]=f*u):d[p]=f*u}m=h*4,c[m+0]=Math.round(d[0]),c[m+1]=Math.round(d[1]),c[m+2]=Math.round(d[2]),c[m+3]=Math.round(d[3])}return t!=null&&(t.width=s,t.height=a,g=t.getContext("2d"),v=new ImageData(c,s,a),g.putImageData(v,0,0)),e!==n&&e.dispose(),[2,c]}})})}var LA=U({fromPixels_:wA}),IA={__proto__:null,toPixels:SA,fromPixels:LA};function gm(n,t){if(n.rank<1)throw new Error("tf.gatherND() expects the input to be rank 1 or higher,"+(" but the rank was "+n.rank+"."));if(t.rank<1)throw new Error("tf.gatherND() expects the indices to be rank 1 or higher,"+(" but the rank was "+t.rank+"."));if(t.dtype!=="int32")throw new Error("tf.gatherND() expects the indices to be int32 type,"+(" but the dtype was "+t.dtype+"."));if(t.shape[t.rank-1]>n.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+(t.shape[t.rank-1]+" vs. "+n.rank));if(n.size===0)throw new Error("Requested more than 0 entries, but input is empty."+(" Input shape: "+n.shape+"."));for(var e=t.shape,i=e[e.length-1],r=1,a=0;a1?t.shape[t.rank-1]:1,r=t.rank>1?t.rank-1:1,a="Must have updates.shape = indices.shape[:batchDim] + "+("shape[sliceDim:], got updates.shape: "+e.shape)+(", indices.shape: "+t.shape+", shape: "+n)+(", sliceDim: "+i+", and batchDim: "+r+".");if(e.rank1?t.shape[i-1]:1,a=e.length,s=1,o=r;o0;)n&1&&t.push(e),n/=2,e++;return t}function bm(n,t,e){for(var i=[],r=0;r0){var p=t[0],f=e+1;c=Im(s,p,f,i,n),h=Am(o,p,f,r,n),d=wm(a,p,f,n)}else for(var m=0;m-1)a[o]=0;else{var l=Sm(t,e,o),u=i[l];n&1<-1)a[o]=Number.MAX_SAFE_INTEGER;else{var l=Sm(t,e,o),u=i[l];n&1<0?s=Number.MIN_SAFE_INTEGER:s=Number.MAX_SAFE_INTEGER);var l=i[r];return s<0&&(s+=l),s=oa(0,s,l-1),s}function xm(n,t,e,i,r,a){var s=t[r],o=e[r]||1;(n&1<0?s=Number.MAX_SAFE_INTEGER:s=Number.MIN_SAFE_INTEGER);var l=i[r];return s<0&&(s+=l),o>0?s=oa(0,s,l):s=oa(-1,s,l-1),s}function NA(n,t,e){for(var i=e.length,r=0;r1){i=r;break}for(var r=i+1;r0||e[r]!==n[r])return!1;return!0}function xA(n,t){for(var e=n.length>0?n[n.length-1]:1,i=0;i=0?s:(D(s===-1,function(){return"Negative size values should be exactly -1 but got "+(s+" for the slice() size at index "+o+".")}),n.shape[o]-i[o])}),[i,a]}var Rm={__proto__:null,assertParamsValid:ym,maskToAxes:ws,computeOutShape:bm,stridesWithElidedDims:wm,getNormalizedAxes:Cm,startIndicesWithElidedDims:Im,stopIndicesWithElidedDims:Am,stridesForAxis:Tm,startForAxis:Nm,stopForAxis:xm,isSliceContinous:NA,computeFlatOffset:xA,parseSliceParams:hc};var Om=function(){function n(){}return n.prototype.getClassName=function(){return this.constructor.className},n.fromConfig=function(t,e){return new t(e)},n}(),Em=function(){function n(){this.classNameMap={}}return n.getMap=function(){return n.instance==null&&(n.instance=new n),n.instance},n.register=function(t){n.getMap().classNameMap[t.className]=[t,t.fromConfig]},n}();function ai(n){D(n.className!=null,function(){return"Class being registered does not have the static className property defined."}),D(typeof n.className=="string",function(){return"className is required to be a string, but got type "+typeof n.className}),D(n.className.length>0,function(){return"Class being registered has an empty-string as its className, which is disallowed."}),Em.register(n)}var CA={__proto__:null,Serializable:Om,SerializationMap:Em,registerClass:ai};var RA=.001,Dm=.1;function OA(n,t,e){return e==null&&(e=dc()),pc(n,t,function(i,r){return fc(i,r,e)})}function dc(){return z.backend.floatPrecision()===32?RA:Dm}function pc(n,t,e){var i=!0;if((Ot(n)||Ot(t))&&(i=!1),Ot(n)&&Ot(t)&&(i=!0),i){var r=n.constructor.name,a=t.constructor.name;if(r!==a)throw new Error("Arrays are of different type. Actual: "+r+". "+("Expected: "+a))}if(Array.isArray(n)&&Array.isArray(t)){var s=An(n),o=An(t);if(!an(s,o))throw new Error("Arrays have different shapes. "+("Actual: ["+s+"]. Expected: ["+o+"]"))}var l=Ot(n)?n:Di(n),u=Ot(t)?t:Di(t);if(l.length!==u.length)throw new Error("Arrays have different lengths actual: "+l.length+" vs "+("expected: "+u.length+`. +`;return v[v.length-1]=" "+v[v.length-1]+"]"+(a?"":N),v}function ha(n){for(var t=[],e=0;e=this.shape[i]){var o="Requested out of range element at "+t+". "+(" Buffer shape="+this.shape);throw new Error(o)}i++}for(var l=t[t.length-1],u=0;u0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak "+("("+o+" data ids) after running '"+t+"'"))},n.prototype.runKernelFunc=function(t,e,i,r,a,s,o){var l=this,u,c=[],h=this.isTapeOn();r==null&&(r=this.state.activeScope!=null?this.state.activeScope.name:"");var d=this.state.numBytes,p=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var f,m=_u(r,this.backendName),g;if(m!=null)f=function(){var S=l.backend.numDataIds();g=m.kernelFunc({inputs:e,attrs:a,backend:l.backend});var L=Array.isArray(g)?g:[g];l.shouldCheckForMemLeaks()&&l.checkKernelForMemLeak(r,S,L);var w=L.map(function(C){var E=C.dataId,k=C.shape,W=C.dtype;return l.makeTensorFromDataId(E,k,W)});if(h){var N=l.getTensorsForGradient(r,e,w);if(N==null){o==null&&(o=[]);var I=w.filter(function(C,E){return o[E]});N=(s||[]).slice().concat(I)}c=l.saveTensorsForBackwardMode(N)}return w};else{var v=function(S){if(!h)return;c=S.map(function(L){return l.keep(l.clone(L))})};f=function(){var S=l.backend.numDataIds();g=l.tidy(function(){return t(l.backend,v)});var L=Array.isArray(g)?g:[g];return l.shouldCheckForMemLeaks()&&l.checkKernelForMemLeak(r,S,L),L}}var b;return this.scopedRun(function(){return l.state.kernelDepth++},function(){return l.state.kernelDepth--},function(){!l.ENV.getBool("DEBUG")&&!l.state.profiling?u=f():(b=l.profiler.profileKernel(r,e,function(){return f()}),l.ENV.getBool("DEBUG")&&l.profiler.logKernelProfile(b),u=b.outputs)}),h&&this.addTapeNode(r,e,u,i,c,a),this.state.profiling&&this.state.activeProfile.kernels.push({name:r,bytesAdded:this.state.numBytes-d,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-p,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(e).map(function(S){return e[S]!=null?e[S].shape:null}),outputShapes:u.map(function(S){return S.shape}),kernelTimeMs:b.timeMs,extraInfo:b.extraInfo}),Array.isArray(g)?u:u[0]},n.prototype.saveTensorsForBackwardMode=function(t){var e=this,i=t.map(function(r){return e.keep(e.clone(r))});return i},n.prototype.getTensorsForGradient=function(t,e,i){var r=Pu(t);if(r!=null){var a=r.inputsToSave||[],s=r.outputsToSave||[],o=void 0;r.saveAllInputs?(D(Array.isArray(e),function(){return"saveAllInputs is true, expected inputs to be an array."}),o=Object.keys(e).map(function(u){return e[u]})):o=a.map(function(u){return e[u]});var l=i.filter(function(u,c){return s[c]});return o.concat(l)}return null},n.prototype.makeTensor=function(t,e,i,r){if(t==null)throw new Error("Values passed to engine.makeTensor() are null");i=i||"float32",r=r||this.backend;var a=t;i==="string"&&Zn(t[0])&&(a=t.map(function(c){return Mu(c)}));var s=r.write(a,e,i),o=new Y(e,i,s,this.nextTensorId());if(this.incRef(o,r),i==="string"){var l=this.state.tensorInfo.get(s),u=_f(a);this.state.numBytes+=u-l.bytes,l.bytes=u}return o},n.prototype.makeTensorFromDataId=function(t,e,i,r){i=i||"float32";var a=new Y(e,i,t,this.nextTensorId());return this.incRef(a,r),a},n.prototype.makeVariable=function(t,e,i,r){e===void 0&&(e=!0),i=i||this.nextVariableId().toString(),r!=null&&r!==t.dtype&&(t=t.cast(r));var a=new da(t,e,i,this.nextTensorId());if(this.state.registeredVariables[a.name]!=null)throw new Error("Variable with name "+a.name+" was already registered");return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a},n.prototype.incRef=function(t,e){var i=this.state.tensorInfo.has(t.dataId)?this.state.tensorInfo.get(t.dataId).refCount:0;if(this.state.numTensors++,t.dtype==="string"&&this.state.numStringTensors++,i===0){this.state.numDataBuffers++;var r=0;t.dtype!=="complex64"&&t.dtype!=="string"&&(r=t.size*zf(t.dtype)),this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:r,refCount:0}),this.state.numBytes+=r}this.state.tensorInfo.get(t.dataId).refCount++,t instanceof da||this.track(t)},n.prototype.disposeTensor=function(t){if(!this.state.tensorInfo.has(t.dataId))return;this.state.numTensors--,t.dtype==="string"&&this.state.numStringTensors--;var e=this.state.tensorInfo.get(t.dataId),i=e.refCount;i<=1?(t.dtype!=="complex64"&&(this.state.numBytes-=e.bytes),this.state.numDataBuffers--,e.backend.disposeData(t.dataId),this.state.tensorInfo.delete(t.dataId)):this.state.tensorInfo.get(t.dataId).refCount--},n.prototype.disposeVariables=function(){for(var t in this.state.registeredVariables){var e=this.state.registeredVariables[t];this.disposeVariable(e)}},n.prototype.disposeVariable=function(t){this.disposeTensor(t),this.state.registeredVariables[t.name]!=null&&delete this.state.registeredVariables[t.name]},n.prototype.memory=function(){var t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,t.reasons==null&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t},n.prototype.profile=function(t){return de(this,void 0,void 0,function(){var e,i,r,a,s,o,l,u;return pe(this,function(c){switch(c.label){case 0:return this.state.profiling=!0,e=this.state.numBytes,i=this.state.numTensors,this.state.activeProfile.kernels=[],r=this.state.activeProfile,[4,t()];case 1:r.result=c.sent(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map(function(h){return h.totalBytesSnapshot})),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-i,a=0,s=this.state.activeProfile.kernels,c.label=2;case 2:return a0&&this.state.kernelDepth===0},n.prototype.addTapeNode=function(t,e,i,r,a,s){var o=this,l={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:i,saved:a},u=Pu(t);u!=null&&(r=u.gradFunc),r!=null&&(l.gradient=function(c){return c=c.map(function(h,d){if(h==null){var p=i[d],f=vr(p.size,p.dtype);return o.makeTensor(f,p.shape,p.dtype)}return h}),r(c.length>1?c:c[0],a,s)}),this.state.activeTape.push(l)},n.prototype.keep=function(t){return t.kept=!0,t},n.prototype.startTape=function(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++},n.prototype.endTape=function(){this.state.gradientDepth--},n.prototype.startScope=function(t){var e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(e.name=t),this.state.scopeStack.push(e),this.state.activeScope=e},n.prototype.endScope=function(t){for(var e=this,i=Ju(t),r=new Set(i.map(function(l){return l.id})),a=0;a0,function(){return"gradients() received an empty list of xs."}),i!=null&&i.dtype!=="float32")throw new Error("dy must have 'float32' dtype, but has '"+i.dtype+"'");var s=this.scopedRun(function(){return a.startTape()},function(){return a.endTape()},function(){return a.tidy("forward",t)});D(s instanceof Y,function(){return"The result y returned by f() must be a tensor."});var o=t2(this.state.activeTape,e,s);if(!r&&o.length===0&&e.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",function(){var l={};l[s.id]=i??d2(s.shape),n2(l,o,function(c){return a.tidy(c)},p2);var u=e.map(function(c){return l[c.id]});return a.state.gradientDepth===0&&(a.state.activeTape.forEach(function(c){for(var h=0,d=c.saved;h0,function(){return"Element arr["+e.join("][")+"] should be a primitive, "+("but is an array of "+n.length+" elements")}),D(n.length===t[0],function(){return"Element arr["+e.join("][")+"] should have "+t[0]+" "+("elements, but has "+n.length+" elements")});for(var i=t.slice(1),r=0;r=0&&(r=i),Jf(i,r,t,e),n==null||!Ot(n)&&!Array.isArray(n)&&typeof n!="number"&&typeof n!="boolean"&&typeof n!="string"){var a=n==null?"null":n.constructor.name;throw new Error("Argument '"+t+"' passed to '"+e+"' must be a "+("Tensor or TensorLike, but got '"+a+"'"))}var s=An(n,r);!Ot(n)&&!Array.isArray(n)&&(n=[n]);var o=!0,l=r!=="string"?ps(n,r):Di(n,[],o);return z.makeTensor(l,s,r)}function pa(n,t,e,i){if(i===void 0&&(i="numeric"),!Array.isArray(n))throw new Error("Argument "+t+" passed to "+e+" must be a `Tensor[]` or `TensorLike[]`");var r=n;return r.map(function(a,s){return O(a,t+"["+s+"]",e)},i)}var Zf="__op";function U(n){var t=Object.keys(n);if(t.length!==1)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+(t.length+" keys."));var e=t[0],i=n[e];e.endsWith("_")&&(e=e.substring(0,e.length-1)),e=e+Zf;var r=function(){for(var a=[],s=0;s>10]+(o&1023)]+t[o>>10];a[s]=l}return new Float32Array(r)}}var Jt=function(){function n(){this.saveRouters=[],this.loadRouters=[]}return n.getInstance=function(){return n.instance==null&&(n.instance=new n),n.instance},n.registerSaveRouter=function(t){n.getInstance().saveRouters.push(t)},n.registerLoadRouter=function(t){n.getInstance().loadRouters.push(t)},n.getSaveHandlers=function(t){return n.getHandlers(t,"save")},n.getLoadHandlers=function(t,e){return n.getHandlers(t,"load",e)},n.getHandlers=function(t,e,i){var r=[],a=e==="load"?n.getInstance().loadRouters:n.getInstance().saveRouters;return a.forEach(function(s){var o=s(t,i);o!==null&&r.push(o)}),r},n}(),x2=function(n){return Jt.registerSaveRouter(n)},C2=function(n){return Jt.registerLoadRouter(n)},R2=function(n){return Jt.getSaveHandlers(n)},O2=function(n,t){return Jt.getLoadHandlers(n,t)};var tc="tensorflowjs",nc=1,ki="models_store",ii="model_info_store";function nm(){if(!Me().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var n=typeof window=="undefined"?self:window,t=n.indexedDB||n.mozIndexedDB||n.webkitIndexedDB||n.msIndexedDB||n.shimIndexedDB;if(t==null)throw new Error("The current browser does not appear to support IndexedDB.");return t}function ic(n){var t=n.result;t.createObjectStore(ki,{keyPath:"modelPath"}),t.createObjectStore(ii,{keyPath:"modelPath"})}var br=function(){function n(t){if(this.indexedDB=nm(),t==null||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}return n.prototype.save=function(t){return de(this,void 0,void 0,function(){return pe(this,function(e){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,t)]})})},n.prototype.load=function(){return de(this,void 0,void 0,function(){return pe(this,function(t){return[2,this.databaseAction(this.modelPath)]})})},n.prototype.databaseAction=function(t,e){var i=this;return new Promise(function(r,a){var s=i.indexedDB.open(tc,nc);s.onupgradeneeded=function(){return ic(s)},s.onsuccess=function(){var o=s.result;if(e==null){var l=o.transaction(ki,"readonly"),u=l.objectStore(ki),c=u.get(i.modelPath);c.onsuccess=function(){if(c.result==null)return o.close(),a(new Error("Cannot find model with path '"+i.modelPath+"' in IndexedDB."));r(c.result.modelArtifacts)},c.onerror=function(g){return o.close(),a(c.error)},l.oncomplete=function(){return o.close()}}else{var h=fa(e),d=o.transaction(ii,"readwrite"),p=d.objectStore(ii),f=p.put({modelPath:i.modelPath,modelArtifactsInfo:h}),m;f.onsuccess=function(){m=o.transaction(ki,"readwrite");var g=m.objectStore(ki),v=g.put({modelPath:i.modelPath,modelArtifacts:e,modelArtifactsInfo:h});v.onsuccess=function(){return r({modelArtifactsInfo:h})},v.onerror=function(b){p=d.objectStore(ii);var S=p.delete(i.modelPath);S.onsuccess=function(){return o.close(),a(v.error)},S.onerror=function(L){return o.close(),a(v.error)}}},f.onerror=function(g){return o.close(),a(f.error)},d.oncomplete=function(){m==null?o.close():m.oncomplete=function(){return o.close()}}}},s.onerror=function(o){return a(s.error)}})},n.URL_SCHEME="indexeddb://",n}(),im=function(n){return Me().getBool("IS_BROWSER")&&(!Array.isArray(n)&&n.startsWith(br.URL_SCHEME))?E2(n.slice(br.URL_SCHEME.length)):null};Jt.registerSaveRouter(im);Jt.registerLoadRouter(im);function E2(n){return new br(n)}function D2(n){return n.startsWith(br.URL_SCHEME)?n.slice(br.URL_SCHEME.length):n}var k2=function(){function n(){this.indexedDB=nm()}return n.prototype.listModels=function(){return de(this,void 0,void 0,function(){var t=this;return pe(this,function(e){return[2,new Promise(function(i,r){var a=t.indexedDB.open(tc,nc);a.onupgradeneeded=function(){return ic(a)},a.onsuccess=function(){var s=a.result,o=s.transaction(ii,"readonly"),l=o.objectStore(ii),u=l.getAll();u.onsuccess=function(){for(var c={},h=0,d=u.result;h0,function(){return"scheme must not be an empty string."});var i=n.getInstance();D(i.managers[t]==null,function(){return"A model store manager is already registered for scheme '"+t+"'."}),i.managers[t]=e},n.getManager=function(t){var e=this.getInstance().managers[t];if(e==null)throw new Error("Cannot find model manager for scheme '"+t+"'");return e},n.getSchemes=function(){return Object.keys(this.getInstance().managers)},n}();function ys(n){if(n.indexOf(Lr)===-1)throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+(""+ri.getSchemes().join(",")));return{scheme:n.split(Lr)[0],path:n.split(Lr)[1]}}function om(n,t,e){return e===void 0&&(e=!1),de(this,void 0,void 0,function(){var i,r,a,s,o,l,u,c,h;return pe(this,function(d){switch(d.label){case 0:return D(n!==t,function(){return"Old path and new path are the same: '"+n+"'"}),i=Jt.getLoadHandlers(n),D(i.length>0,function(){return"Copying failed because no load handler is found for source URL "+n+"."}),D(i.length<2,function(){return"Copying failed because more than one ("+i.length+") "+("load handlers for source URL "+n+".")}),r=i[0],a=Jt.getSaveHandlers(t),D(a.length>0,function(){return"Copying failed because no save handler is found for destination "+("URL "+t+".")}),D(a.length<2,function(){return"Copying failed because more than one ("+i.length+") "+("save handlers for destination URL "+t+".")}),s=a[0],o=ys(n).scheme,l=ys(n).path,u=o===ys(n).scheme,[4,r.load()];case 1:return c=d.sent(),e&&u?[4,ri.getManager(o).removeModel(l)]:[3,3];case 2:d.sent(),d.label=3;case 3:return[4,s.save(c)];case 4:return h=d.sent(),e&&!u?[4,ri.getManager(o).removeModel(l)]:[3,6];case 5:d.sent(),d.label=6;case 6:return[2,h.modelArtifactsInfo]}})})}function H2(){return de(this,void 0,void 0,function(){var n,t,e,i,r,a,s,o;return pe(this,function(l){switch(l.label){case 0:n=ri.getSchemes(),t={},e=0,i=n,l.label=1;case 1:return e0,function(){return"promises must be a none empty array"})}function o(l,u){D(l>=0&&l<=1,function(){return"Progress fraction must be in range [0, 1], but "+("got startFraction "+l)}),D(u>=0&&u<=1,function(){return"Progress fraction must be in range [0, 1], but "+("got endFraction "+u)}),D(u>=l,function(){return"startFraction must be no more than endFraction, but "+("got startFraction "+l+" and endFraction ")+(""+u)})}return Promise.all(n.map(a))}function hm(n,t){return de(this,void 0,void 0,function(){var e,i,r,a,s,o,l,u,c,h,d;return pe(this,function(p){switch(p.label){case 0:return t==null&&(t={}),e=t.fetchFunc==null?Me().platform.fetch:t.fetchFunc,i=n.map(function(f){return e(f,t.requestInit,{isBinary:!0})}),r=0,a=.5,t.onProgress==null?[4,Promise.all(i)]:[3,2];case 1:return o=p.sent(),[3,4];case 2:return[4,cm(i,t.onProgress,r,a)];case 3:o=p.sent(),p.label=4;case 4:return s=o,l=s.map(function(f){return f.arrayBuffer()}),u=.5,c=1,t.onProgress==null?[4,Promise.all(l)]:[3,6];case 5:return d=p.sent(),[3,8];case 6:return[4,cm(l,t.onProgress,u,c)];case 7:d=p.sent(),p.label=8;case 8:return h=d,[2,h]}})})}function aA(n,t,e,i){return t===void 0&&(t=""),de(this,void 0,void 0,function(){var r,a;return pe(this,function(s){return r=function(o){return hm(o,{requestInit:i})},a=dm(r),[2,a(n,t,e)]})})}function dm(n){var t=this;return function(e,i,r){return i===void 0&&(i=""),de(t,void 0,void 0,function(){var a,s,o,l,u,c,h,d,p,f;return pe(this,function(m){switch(m.label){case 0:if(a=e.map(function(){return!1}),s={},o=r!=null?r.map(function(){return!1}):[],l=[],e.forEach(function(g,v){var b=0;g.weights.forEach(function(S){var L="quantization"in S?S.quantization.dtype:S.dtype,w=Zu[L]*st(S.shape),N=function(){a[v]=!0,s[v]==null&&(s[v]=[]),s[v].push({manifestEntry:S,groupOffset:b,sizeBytes:w})};r!=null?r.forEach(function(I,C){I===S.name&&(N(),o[C]=!0)}):N(),l.push(S.name),b+=w})}),!o.every(function(g){return g}))throw u=r.filter(function(g,v){return!o[v]}),new Error("Could not find weights in manifest with names: "+(u.join(", ")+`. +`)+"Manifest JSON has weights with names: "+(l.join(", ")+"."));return c=a.reduce(function(g,v,b){return v&&g.push(b),g},[]),h=[],c.forEach(function(g){e[g].paths.forEach(function(v){var b=i+(i.endsWith("/")?"":"/")+v;h.push(b)})}),[4,n(h)];case 1:return d=m.sent(),p={},f=0,c.forEach(function(g){for(var v=e[g].paths.length,b=0,S=0;S0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(t)&&D(t.length===2,function(){return"URL paths for http must have a length of 2, "+("(actual length is "+t.length+").")}),this.path=t,e.requestInit!=null&&e.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{}}return n.prototype.save=function(t){return de(this,void 0,void 0,function(){var e,i,r,a;return pe(this,function(s){switch(s.label){case 0:if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit),e.body=new FormData,i=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata,weightsManifest:i},e.body.append("model.json",new Blob([JSON.stringify(r)],{type:oA}),"model.json"),t.weightData!=null&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:sA}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if(a=s.sent(),a.ok)return[2,{modelArtifactsInfo:fa(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+(a.status+"."))}})})},n.prototype.load=function(){return de(this,void 0,void 0,function(){var t,e,i,r,a,s,o,l,u,c,h,d,p,f,m;return pe(this,function(g){switch(g.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(t=g.sent(),!t.ok)throw new Error("Request to "+this.path+" failed with status code "+(t.status+". Please verify this URL points to ")+"the model JSON of the model to load.");g.label=2;case 2:return g.trys.push([2,4,,5]),[4,t.json()];case 3:return e=g.sent(),[3,5];case 4:throw i=g.sent(),r="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?r+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":r+=" Please make sure the server is serving valid JSON for this request.",new Error(r);case 5:if(a=e.modelTopology,s=e.weightsManifest,o=e.generatedBy,l=e.convertedBy,u=e.format,c=e.userDefinedMetadata,a==null&&s==null)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return s!=null?[4,this.loadWeights(s)]:[3,7];case 6:p=g.sent(),h=p[0],d=p[1],g.label=7;case 7:return f={modelTopology:a,weightSpecs:h,weightData:d,userDefinedMetadata:c,generatedBy:o,convertedBy:l,format:u},m=e.modelInitializer,m&&(f.modelInitializer=m),[2,f]}})})},n.prototype.loadWeights=function(t){return de(this,void 0,void 0,function(){var e,i,r,a,s,o,l,u,c,h,d,p,f,m,g,v,b,S,L,w,N;return pe(this,function(I){switch(I.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,i=lA(e),r=i[0],a=i[1],s=this.weightPathPrefix||r,o=[],l=0,u=t;lt?n.substring(e):"";return[i+"/",r]}function sc(n){return n.match(pm.URL_SCHEME_REGEX)!=null}var fm=function(n,t){if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;var e=!0;return Array.isArray(n)?e=n.every(function(i){return sc(i)}):e=sc(n),e?oc(n,t):null};Jt.registerSaveRouter(fm);Jt.registerLoadRouter(fm);function oc(n,t){return new pm(n,t)}function uA(n,t){return oc(n,t)}var lc=function(){function n(t){this.modelArtifacts=t}return n.prototype.load=function(){return de(this,void 0,void 0,function(){return pe(this,function(t){return[2,this.modelArtifacts]})})},n}(),cA=function(){function n(t){this.saveHandler=t}return n.prototype.save=function(t){return de(this,void 0,void 0,function(){return pe(this,function(e){return[2,this.saveHandler(t)]})})},n}();function hA(n,t,e,i){if(arguments.length===1){var r=n.modelTopology!=null||n.weightSpecs!=null;return r?new lc(n):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new lc({modelTopology:n}))}else return console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new lc({modelTopology:n,weightSpecs:t,weightData:e,trainingConfig:i})}function dA(n){return new cA(n)}var pA={__proto__:null,browserFiles:rA,browserHTTPRequest:uA,concatenateArrayBuffers:ec,decodeWeights:Qf,encodeWeights:w2,fromMemory:hA,getLoadHandlers:O2,getModelArtifactsInfoForJSON:fa,getSaveHandlers:R2,http:oc,isHTTPScheme:sc,loadWeights:aA,registerLoadRouter:C2,registerSaveRouter:x2,weightsLoaderFactory:dm,withSaveHandler:dA,copyModel:q2,listModels:H2,moveModel:G2,removeModel:V2};function fA(n,t){var e=O(n,"x","reshape",null),i={x:e},r={shape:t},a=function(s,o){return t=Df(t,e.size),D(e.size===st(t),function(){return"new shape and old shape must have the same number of elements."}),o([e]),s.reshape(e,t)};return z.runKernelFunc(a,i,null,ru,r)}var V=U({reshape_:fA});function mA(n,t,e,i){var r;e===void 0&&(e=!1),i===void 0&&(i=!1);var a=O(n,"a","matMul"),s=O(t,"b","matMul");r=rt(a,s),a=r[0],s=r[1],D(a.rank>=2&&s.rank>=2&&a.rank===s.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, "+("got ranks "+a.rank+" and "+s.rank+".")});var o=e?a.shape[a.rank-2]:a.shape[a.rank-1],l=i?s.shape[s.rank-1]:s.shape[s.rank-2],u=e?a.shape[a.rank-1]:a.shape[a.rank-2],c=i?s.shape[s.rank-2]:s.shape[s.rank-1],h=a.shape.slice(0,-2),d=s.shape.slice(0,-2),p=st(h),f=st(d);D(an(h,d),function(){return"Error in matMul: outer dimensions ("+h+") and ("+(d+") of Tensors with shapes "+a.shape+" and ")+(s.shape+" must match.")}),D(o===l,function(){return"Error in matMul: inner shapes ("+o+") and ("+(l+") of Tensors with shapes "+a.shape+" and ")+(s.shape+" and transposeA="+e)+(" and transposeB="+i+" must match.")});var m=a.shape.slice(0,-2).concat([u,c]),g=e?V(a,[p,o,u]):V(a,[p,u,o]),v=i?V(s,[f,c,l]):V(s,[f,l,c]),b=function(N,I){return I([g,v]),N.batchMatMul(g,v,e,i)},S={a:g,b:v},L={transposeA:e,transposeB:i},w=z.runKernelFunc(b,S,null,cl,L);return V(w,m)}var Fe=U({matMul_:mA});function gA(n,t,e,i){if(e===void 0&&(e=1),i===void 0&&(i=0),t<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+t);var r=O(n,"indices","oneHot","int32"),a=r.shape.concat([t]),s=function(u,c){return c([r]),V(u.oneHot(V(r,[r.size]),t,e,i),a)},o={indices:r},l={depth:t,onValue:e,offValue:i};return z.runKernelFunc(s,o,null,Zl,l)}var bs=U({oneHot_:gA});function vA(n,t){var e=O(n,"x","transpose");if(t==null&&(t=e.shape.map(function(a,s){return s}).reverse()),D(e.rank===t.length,function(){return"Error in transpose: rank of input "+e.rank+" "+("must match length of perm "+t+".")}),t.forEach(function(a){D(a>=0&&a0&&Number.isInteger(e),function(){return"If provided, numClasses must be a positive integer, "+("but got "+e)}),D(i.rank===1,function(){return"Expected the rank of labels to be 1, but got "+i.rank}),D(r.rank===1,function(){return"Expected the rank of predictions to be 1, "+("but got "+r.rank)}),D(i.shape[0]===r.shape[0],function(){return"Mismatch in the number of examples: "+(i.shape[0]+" vs. "+r.shape[0]+". ")+"Labels and predictions should have the same number of elements."}),D(e>0&&Number.isInteger(e),function(){return"numClasses is required to be a positive integer, but got "+(""+e)});var a=bs(ue(i,"int32"),e),s=bs(ue(r,"int32"),e),o=lt(a);return ue(Fe(o,s),"int32")}var bA=U({confusionMatrix_:yA});var wA={__proto__:null,confusionMatrix:bA};function mm(n,t,e){if(Ei(n),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");var i=An(n,e);if(i.length!==3&&i.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(i.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return ti(n,t,i,e)}var Ir;function SA(n,t){if(t===void 0&&(t=3),t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(n==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var e=!1,i=!1,r=!1,a=!1,s=!1;if(n.data instanceof Uint8Array)e=!0;else if(typeof ImageData!="undefined"&&n instanceof ImageData)i=!0;else if(typeof HTMLVideoElement!="undefined"&&n instanceof HTMLVideoElement)r=!0;else if(typeof HTMLImageElement!="undefined"&&n instanceof HTMLImageElement)a=!0;else if(n.getContext!=null)s=!0;else throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, "+("but was "+n.constructor.name));if(r){var o=2;if(r&&n.readyState element.")}var l=_u(Fu,z.backendName);if(l!=null){var u={pixels:n},c={numChannels:t};return z.runKernel(Fu,u,c)}var h=r?[n.videoWidth,n.videoHeight]:[n.width,n.height],d=h[0],p=h[1],f;s?f=n.getContext("2d").getImageData(0,0,d,p).data:i||e?f=n.data:(a||r)&&(Ir==null&&(Ir=document.createElement("canvas").getContext("2d")),Ir.canvas.width=d,Ir.canvas.height=p,Ir.drawImage(n,0,0,d,p),f=Ir.getImageData(0,0,d,p).data);var m;if(t===4)m=new Int32Array(f);else{var g=d*p;m=new Int32Array(g*t);for(var v=0;v4||o===2)throw new Error("toPixels only supports depth of size "+("1, 3 or 4 but got "+o));if(e.dtype!=="float32"&&e.dtype!=="int32")throw new Error("Unsupported type for toPixels: "+e.dtype+". Please use float32 or int32 tensors.");return[4,e.data()];case 1:for(l=b.sent(),u=e.dtype==="float32"?255:1,c=new Uint8ClampedArray(s*a*4),h=0;h1)throw new Error("Tensor values for a float32 Tensor must be in the "+("range [0 - 1] but encountered "+f+"."))}else if(e.dtype==="int32"&&(f<0||f>255))throw new Error("Tensor values for a int32 Tensor must be in the "+("range [0 - 255] but encountered "+f+"."));o===1?(d[0]=f*u,d[1]=f*u,d[2]=f*u):d[p]=f*u}m=h*4,c[m+0]=Math.round(d[0]),c[m+1]=Math.round(d[1]),c[m+2]=Math.round(d[2]),c[m+3]=Math.round(d[3])}return t!=null&&(t.width=s,t.height=a,g=t.getContext("2d"),v=new ImageData(c,s,a),g.putImageData(v,0,0)),e!==n&&e.dispose(),[2,c]}})})}var IA=U({fromPixels_:SA}),AA={__proto__:null,toPixels:LA,fromPixels:IA};function gm(n,t){if(n.rank<1)throw new Error("tf.gatherND() expects the input to be rank 1 or higher,"+(" but the rank was "+n.rank+"."));if(t.rank<1)throw new Error("tf.gatherND() expects the indices to be rank 1 or higher,"+(" but the rank was "+t.rank+"."));if(t.dtype!=="int32")throw new Error("tf.gatherND() expects the indices to be int32 type,"+(" but the dtype was "+t.dtype+"."));if(t.shape[t.rank-1]>n.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+(t.shape[t.rank-1]+" vs. "+n.rank));if(n.size===0)throw new Error("Requested more than 0 entries, but input is empty."+(" Input shape: "+n.shape+"."));for(var e=t.shape,i=e[e.length-1],r=1,a=0;a1?t.shape[t.rank-1]:1,r=t.rank>1?t.rank-1:1,a="Must have updates.shape = indices.shape[:batchDim] + "+("shape[sliceDim:], got updates.shape: "+e.shape)+(", indices.shape: "+t.shape+", shape: "+n)+(", sliceDim: "+i+", and batchDim: "+r+".");if(e.rank1?t.shape[i-1]:1,a=e.length,s=1,o=r;o0;)n&1&&t.push(e),n/=2,e++;return t}function bm(n,t,e){for(var i=[],r=0;r0){var p=t[0],f=e+1;c=Im(s,p,f,i,n),h=Am(o,p,f,r,n),d=wm(a,p,f,n)}else for(var m=0;m-1)a[o]=0;else{var l=Sm(t,e,o),u=i[l];n&1<-1)a[o]=Number.MAX_SAFE_INTEGER;else{var l=Sm(t,e,o),u=i[l];n&1<0?s=Number.MIN_SAFE_INTEGER:s=Number.MAX_SAFE_INTEGER);var l=i[r];return s<0&&(s+=l),s=oa(0,s,l-1),s}function xm(n,t,e,i,r,a){var s=t[r],o=e[r]||1;(n&1<0?s=Number.MAX_SAFE_INTEGER:s=Number.MIN_SAFE_INTEGER);var l=i[r];return s<0&&(s+=l),o>0?s=oa(0,s,l):s=oa(-1,s,l-1),s}function xA(n,t,e){for(var i=e.length,r=0;r1){i=r;break}for(var r=i+1;r0||e[r]!==n[r])return!1;return!0}function CA(n,t){for(var e=n.length>0?n[n.length-1]:1,i=0;i=0?s:(D(s===-1,function(){return"Negative size values should be exactly -1 but got "+(s+" for the slice() size at index "+o+".")}),n.shape[o]-i[o])}),[i,a]}var Rm={__proto__:null,assertParamsValid:ym,maskToAxes:ws,computeOutShape:bm,stridesWithElidedDims:wm,getNormalizedAxes:Cm,startIndicesWithElidedDims:Im,stopIndicesWithElidedDims:Am,stridesForAxis:Tm,startForAxis:Nm,stopForAxis:xm,isSliceContinous:xA,computeFlatOffset:CA,parseSliceParams:hc};var Om=function(){function n(){}return n.prototype.getClassName=function(){return this.constructor.className},n.fromConfig=function(t,e){return new t(e)},n}(),Em=function(){function n(){this.classNameMap={}}return n.getMap=function(){return n.instance==null&&(n.instance=new n),n.instance},n.register=function(t){n.getMap().classNameMap[t.className]=[t,t.fromConfig]},n}();function ai(n){D(n.className!=null,function(){return"Class being registered does not have the static className property defined."}),D(typeof n.className=="string",function(){return"className is required to be a string, but got type "+typeof n.className}),D(n.className.length>0,function(){return"Class being registered has an empty-string as its className, which is disallowed."}),Em.register(n)}var RA={__proto__:null,Serializable:Om,SerializationMap:Em,registerClass:ai};var OA=.001,Dm=.1;function EA(n,t,e){return e==null&&(e=dc()),pc(n,t,function(i,r){return fc(i,r,e)})}function dc(){return z.backend.floatPrecision()===32?OA:Dm}function pc(n,t,e){var i=!0;if((Ot(n)||Ot(t))&&(i=!1),Ot(n)&&Ot(t)&&(i=!0),i){var r=n.constructor.name,a=t.constructor.name;if(r!==a)throw new Error("Arrays are of different type. Actual: "+r+". "+("Expected: "+a))}if(Array.isArray(n)&&Array.isArray(t)){var s=An(n),o=An(t);if(!an(s,o))throw new Error("Arrays have different shapes. "+("Actual: ["+s+"]. Expected: ["+o+"]"))}var l=Ot(n)?n:Di(n),u=Ot(t)?t:Di(t);if(l.length!==u.length)throw new Error("Arrays have different lengths actual: "+l.length+" vs "+("expected: "+u.length+`. `)+("Actual: "+l+`. `)+("Expected: "+u+"."));for(var c=0;ce)}function FA(n,t,e){for(var i=0;ie)throw new Error("Value out of range:"+n[i]+" low: "+t+", high: "+e)}function WA(n,t){expect(new Float32Array(n)).toEqual(new Float32Array(t))}var UA={__proto__:null,TEST_EPSILON_FLOAT16:Dm,expectArraysClose:OA,testEpsilon:dc,expectPromiseToFail:EA,expectArraysEqual:DA,expectNumbersClose:kA,expectValuesInRange:FA,expectArrayBuffersEqual:WA};var BA="2.6.0";function zA(){Me().set("PROD",!0)}function _A(){Me().set("DEBUG",!0)}function PA(){Me().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function It(n){Me().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(n+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function MA(){z.disposeVariables()}function HA(){return z}function VA(){return z.memory()}function qA(n){return z.profile(n)}function ft(n,t){return z.tidy(n,t)}function Ut(n){var t=Ju(n);t.forEach(function(e){return e.dispose()})}function km(n){return z.keep(n)}function GA(n){return z.time(n)}function YA(n){return z.setBackend(n)}function KA(){return z.ready()}function jA(){return z.backendName}function $A(n){z.removeBackend(n)}function XA(n){return z.findBackend(n)}function JA(n){return z.findBackendFactory(n)}function ZA(n,t,e){return e===void 0&&(e=1),z.registerBackend(n,t,e)}function QA(){return z.backend}function e1(n,t){Me().setPlatform(n,t)}function t1(n,t){var e,i=O(n,"a","add"),r=O(t,"b","add");e=rt(i,r),i=e[0],r=e[1];var a=function(o,l){var u=o.add(i,r);return l([i,r]),u},s={a:i,b:r};return z.runKernelFunc(a,s,null,os)}var fe=U({add_:t1});function n1(n,t){var e,i=O(n,"a","floorDiv"),r=O(t,"b","floorDiv");e=rt(i,r),i=e[0],r=e[1];var a=function(o,l){var u=o.floorDiv(i,r);return l([i,r]),u},s={a:i,b:r};return z.runKernelFunc(a,s,null,Ol)}var mc=U({floorDiv_:n1});function i1(n,t){var e,i=O(n,"a","div"),r=O(t,"b","div");if(e=rt(i,r),i=e[0],r=e[1],i.dtype==="int32"&&r.dtype==="int32")return mc(i,r);var a=function(l,u){var c=l.realDivide(i,r);return u([i,r]),c},s={a:i,b:r},o={};return z.runKernelFunc(a,s,null,Al,o)}var Ie=U({div_:i1});function r1(n,t){var e,i=O(n,"a","mul"),r=O(t,"b","mul");e=rt(i,r),i=e[0],r=e[1];var a=function(o,l){var u=o.multiply(i,r);return l([i,r]),u},s={a:i,b:r};return z.runKernelFunc(a,s,null,$l)}var J=U({mul_:r1});function a1(n){var t=O(n,"x","abs"),e={x:t};return z.runKernelFunc(function(i,r){return r([t]),t.dtype==="complex64"?i.complexAbs(t):i.abs(t)},e,null,Jo)}var Vt=U({abs_:a1});function s1(n){var t=O(n,"x","acos"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.acos(t);return r([t]),a},e,null,Zo)}var Fm=U({acos_:s1});function o1(n){var t=O(n,"x","acosh"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.acosh(t);return r([t]),a},e,null,Qo)}var Wm=U({acosh_:o1});function l1(n){D(Array.isArray(n),function(){return"The argument passed to tf.addN() must be a list of tensors"}),D(n.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+(""+n.length)});var t=n.map(function(a,s){return O(a,"tensors"+s,"addN")}),e=t[0];t.forEach(function(a){if(a.dtype!==e.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(function(a){if(!an(a.shape,e.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var i=function(a,s){var o=a.addN(t);return s(t),o},r=t;return z.runKernelFunc(i,r,null,el)}var u1=U({addN_:l1});function gc(n,t){for(var e=0;e=0&&t=1,function(){return"Pass at least one tensor to concat"});var e=pa(n,"tensors","concat");e[0].dtype==="complex64"&&e.forEach(function(s){if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor - with dtype `+s.dtype+". ")});var i=function(s,o){var l=Ze(t,e[0].shape)[0],u=jm(e.map(function(d){return d.shape}),l);if(st(u)===0)return ni([],u);if(e=e.filter(function(d){return d.size>0}),e.length===1)return e[0];var c=e.map(function(d){return d.shape});Km(c,l);var h=s.concat(e,l);return o(e),h},r=e,a={axis:t};return z.runKernelFunc(i,r,null,ml,a)}var xt=U({concat_:C1});function R1(n){var t=O(n,"x","sigmoid"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.sigmoid(t);return r([a]),a},e,null,vu)}var Ui=U({sigmoid_:R1});function O1(n,t,e){var i=O(n,"x","slice");if(i.rank===0)throw new Error("Slicing scalar is not possible");var r=function(o,l){var u=hc(i,t,e),c=u[0],h=u[1];return ym(i,c,h),l([i]),o.slice(i,c,h)},a={x:i},s={begin:t,size:e};return z.runKernelFunc(r,a,null,pu,s)}var Be=U({slice_:O1});function E1(n){var t=O(n,"x","tanh"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.tanh(t);return r([a]),a},e,null,xu)}var Is=U({tanh_:E1});function D1(n,t,e,i,r,a){var s=O(n,"forgetBias","basicLSTMCell"),o=O(t,"lstmKernel","basicLSTMCell"),l=O(e,"lstmBias","basicLSTMCell"),u=O(i,"data","basicLSTMCell"),c=O(r,"c","basicLSTMCell"),h=O(a,"h","basicLSTMCell"),d=xt([u,h],1),p=Fe(d,o),f=fe(p,l),m=f.shape[0],g=f.shape[1]/4,v=[m,g],b=Be(f,[0,0],v),S=Be(f,[0,g],v),L=Be(f,[0,g*2],v),w=Be(f,[0,g*3],v),N=fe(J(Ui(b),Is(S)),J(c,Ui(fe(s,L)))),I=J(Is(N),Ui(w));return[N,I]}var k1=U({basicLSTMCell_:D1});function F1(n,t,e){var i=O(n,"x","batchToSpaceND"),r=t.reduce(function(l,u){return l*u});D(i.rank>=1+t.length,function(){return"input rank is "+i.rank+" but should be > than blockShape.length "+t.length}),D(e.length===t.length,function(){return"crops.length is "+e.length+" but should be equal to blockShape.length "+t.length}),D(i.shape[0]%r===0,function(){return"input tensor batch is "+i.shape[0]+" but is not divisible by the product of "+("the elements of blockShape "+t.join(" * ")+" === "+r)});var a=function(l){return l.batchToSpaceND(i,t,e)},s={x:i},o={blockShape:t,crops:e};return z.runKernelFunc(a,s,null,hl,o)}var As=U({batchToSpaceND_:F1});function W1(n){var t;return n.rank===0||n.rank===1?t=V(n,[1,1,1,n.size]):n.rank===2?t=V(n,[1,1,n.shape[0],n.shape[1]]):n.rank===3?t=V(n,[1,n.shape[0],n.shape[1],n.shape[2]]):t=n,t}function U1(n,t,e,i,r,a){a==null&&(a=.001);var s=O(n,"x","batchNorm"),o=O(t,"mean","batchNorm"),l=O(e,"variance","batchNorm"),u;r!=null&&(u=O(r,"scale","batchNorm"));var c;i!=null&&(c=O(i,"offset","batchNorm")),D(o.rank===l.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),D(c==null||o.rank===c.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),D(u==null||o.rank===u.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."});var h=W1(s),d=function(g,v){return v([h,o,l,u]),g.batchNorm(h,Ts(o),Ts(l),Ts(c),Ts(u),a)},p={x:h,scale:u,offset:c,mean:o,variance:l},f={varianceEpsilon:a},m=z.runKernelFunc(d,p,null,El,f);return V(m,s.shape)}function Ts(n){return n==null?null:n.rank===0?V(n,[n.size]):n.rank===1?n:n.rank===2?V(n,[1,1,n.shape[0],n.shape[1]]):n.rank===3?V(n,[1,n.shape[0],n.shape[1],n.shape[2]]):n}var ya=U({batchNorm_:U1});function B1(n,t,e,i,r,a){var s=O(n,"x","batchNorm"),o=O(t,"mean","batchNorm"),l=O(e,"variance","batchNorm"),u;r!=null&&(u=O(r,"scale","batchNorm"));var c;return i!=null&&(c=O(i,"offset","batchNorm")),D(s.rank===2,function(){return"Error in batchNorm2D: x must be rank 2 but got rank "+(s.rank+".")}),D(o.rank===2||o.rank===1,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but "+("got rank "+o.rank+".")}),D(l.rank===2||l.rank===1,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 "+("but got rank "+l.rank+".")}),u!=null&&D(u.rank===2||u.rank===1,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 "+("but got rank "+u.rank+".")}),c!=null&&D(c.rank===2||c.rank===1,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 "+("but got rank "+c.rank+".")}),ya(s,o,l,c,u,a)}var z1=U({batchNorm2d_:B1});function _1(n,t,e,i,r,a){var s=O(n,"x","batchNorm"),o=O(t,"mean","batchNorm"),l=O(e,"variance","batchNorm"),u;r!=null&&(u=O(r,"scale","batchNorm"));var c;return i!=null&&(c=O(i,"offset","batchNorm")),D(s.rank===3,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+(s.rank+".")}),D(o.rank===3||o.rank===1,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but "+("got rank "+o.rank+".")}),D(l.rank===3||l.rank===1,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 "+("but got rank "+l.rank+".")}),u!=null&&D(u.rank===3||u.rank===1,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 "+("but got rank "+u.rank+".")}),c!=null&&D(c.rank===3||c.rank===1,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 "+("but got rank "+c.rank+".")}),ya(s,o,l,c,u,a)}var P1=U({batchNorm3d_:_1});function M1(n,t,e,i,r,a){var s=O(n,"x","batchNorm"),o=O(t,"mean","batchNorm"),l=O(e,"variance","batchNorm"),u;r!=null&&(u=O(r,"scale","batchNorm"));var c;return i!=null&&(c=O(i,"offset","batchNorm")),D(s.rank===4,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+(s.rank+".")}),D(o.rank===4||o.rank===1,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but "+("got rank "+o.rank+".")}),D(l.rank===4||l.rank===1,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 "+("but got rank "+l.rank+".")}),u!=null&&D(u.rank===4||u.rank===1,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 "+("but got rank "+u.rank+".")}),c!=null&&D(c.rank===4||c.rank===1,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 "+("but got rank "+c.rank+".")}),ya(s,o,l,c,u,a)}var H1=U({batchNorm4d_:M1});function V1(n,t){var e=O(n,"broadcastTo","x"),i=e.shape;if(t.some(function(d){return!(d>0)||d%1!==0}))throw new Error("broadcastTo(): Invalid broadcast shape ["+t+"].");if(t.lengthe.rank){for(var r=e.shape.slice();r.length=0;o--)if(a[o]===t[o])s[o]=1;else if(e.shape[o]!==1)throw new Error("broadcastTo(): ["+i+"] cannot be broadcast to ["+t+"].");var l=s.map(function(d,p){return d>1?p:-1}).filter(function(d){return d>=0});if(l.length===0)return Fi(e);var u=function(d){return d.tile(e,s)},c={x:e},h={shape:t,inputShape:a};return z.runKernelFunc(u,c,null,dl,h)}var Ns=U({broadcastTo_:V1});function q1(n){var t=O(n,"x","ceil"),e={x:t};return z.runKernelFunc(function(i){return i.ceil(t)},e,null,pl)}var $m=U({ceil_:q1});function G1(n,t,e){var i=O(n,"x","clipByValue");D(t<=e,function(){return"Error in clip: min ("+t+") must be "+("less than or equal to max ("+e+").")});var r={x:i},a={clipValueMin:t,clipValueMax:e};return z.runKernelFunc(function(s,o){var l=s.clip(i,t,e);return o([i]),l},r,null,fl,a)}var Xm=U({clipByValue_:G1});function Y1(n){return xt(n,0)}var K1=U({concat1d_:Y1});function j1(n,t){return xt(n,t)}var $1=U({concat2d_:j1});function X1(n,t){return xt(n,t)}var J1=U({concat3d_:X1});function Z1(n,t){return xt(n,t)}var Q1=U({concat4d_:Z1});function eT(n,t,e,i,r,a,s){r===void 0&&(r="NHWC"),a===void 0&&(a=[1,1]);var o=O(n,"x","conv2d"),l=O(t,"filter","conv2d"),u=o,c=!1;o.rank===3&&(c=!0,u=V(o,[1,o.shape[0],o.shape[1],o.shape[2]])),D(u.rank===4,function(){return"Error in conv2d: input must be rank 4, but got rank "+u.rank+"."}),D(l.rank===4,function(){return"Error in conv2d: filter must be rank 4, but got rank "+(l.rank+".")}),s!=null&&D(it(i),function(){return"Error in conv2d: pad must be an integer when using, "+("dimRoundingMode "+s+" but got pad "+i+".")});var h=r==="NHWC"?u.shape[3]:u.shape[1];D(h===l.shape[2],function(){return"Error in conv2d: depth of input ("+h+") must match "+("input depth for filter "+l.shape[2]+".")}),D(Bt(e,a),function(){return"Error in conv2D: Either strides or dilations must be 1. "+("Got strides "+e+" and dilations '"+a+"'")});var d=function(g,v){var b=ma(r),S=xn(u.shape,l.shape,e,a,i,s,!1,b),L=g.conv2d(u,l,S);return v([u,l]),L},p={x:u,filter:l},f={strides:e,pad:i,dataFormat:r,dilations:a,dimRoundingMode:s},m=z.runKernelFunc(d,p,null,gl,f);return c?V(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Nr=U({conv2d_:eT});function tT(n,t,e,i,r,a,s){r===void 0&&(r="NWC"),a===void 0&&(a=1);var o=O(n,"x","conv1d"),l=O(t,"filter","conv1d"),u=o,c=!1;o.rank===2&&(c=!0,u=V(o,[1,o.shape[0],o.shape[1]])),D(u.rank===3,function(){return"Error in conv1d: input must be rank 3, but got rank "+u.rank+"."}),D(l.rank===3,function(){return"Error in conv1d: filter must be rank 3, but got rank "+(l.rank+".")}),s!=null&&D(it(i),function(){return"Error in conv1d: pad must be an integer when using, "+("dimRoundingMode "+s+" but got pad "+i+".")}),D(u.shape[2]===l.shape[1],function(){return"Error in conv1d: depth of input ("+u.shape[2]+") must match "+("input depth for filter "+l.shape[1]+".")}),D(Bt(e,a),function(){return"Error in conv1D: Either stride or dilation must be 1. "+("Got stride "+e+" and dilation '"+a+"'")}),D(r==="NWC",function(){return"Error in conv1d: got dataFormat of "+r+" but only NWC is currently supported."});var h=V(l,[1,l.shape[0],l.shape[1],l.shape[2]]),d=V(u,[u.shape[0],1,u.shape[1],u.shape[2]]),p=[1,e],f=[1,a],m="NHWC",g=Nr(d,h,p,i,m,f,s);return c?V(g,[g.shape[2],g.shape[3]]):V(g,[g.shape[0],g.shape[2],g.shape[3]])}var Jm=U({conv1d_:tT});function nT(n,t,e,i,r,a,s){a===void 0&&(a="NHWC"),D(n.length===t.rank,function(){return"Length of inShape "+("("+n.length+") and rank of dy ("+t.rank+") must match")});var o=n,l=t,u=!1;t.rank===3&&(u=!0,l=V(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,n[0],n[1],n[2]]),D(o.length===4,function(){return"Error in conv2dDerInput: inShape must be length 4, but got length "+(o.length+".")}),D(l.rank===4,function(){return"Error in conv2dDerInput: dy must be rank 4, but got "+("rank "+l.rank)}),D(e.rank===4,function(){return"Error in conv2dDerInput: filter must be rank 4, but got "+("rank "+e.rank)});var c=a==="NHWC"?o[3]:o[1],h=a==="NHWC"?l.shape[3]:l.shape[1];D(c===e.shape[2],function(){return"Error in conv2dDerInput: depth of input ("+c+") must "+("match input depth for filter "+e.shape[2]+".")}),D(h===e.shape[3],function(){return"Error in conv2dDerInput: depth of output ("+h+") must "+("match output depth for filter "+e.shape[3]+".")}),s!=null&&D(it(r),function(){return"Error in conv2dDerInput: pad must be an integer when using, "+("dimRoundingMode "+s+" but got pad "+r+".")});var d=function(g,v){var b=1,S=ma(a),L=xn(o,e.shape,i,b,r,s,!1,S),w=g.conv2dDerInput(l,e,L);return v([l,e]),w},p={dy:l,filter:e},f={strides:i,pad:r,dataFormat:a,dimRoundingMode:s,inputShape:o},m=z.runKernelFunc(d,p,null,vl,f);return u?V(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var wc=U({conv2DBackpropInput_:nT});function iT(n,t,e,i,r,a){var s=O(n,"x","conv2dTranspose"),o=O(t,"filter","conv2dTranspose");return wc(e,s,o,i,r,"NHWC",a)}var Zm=U({conv2dTranspose_:iT});function rT(n,t,e,i,r,a){r===void 0&&(r="NDHWC"),a===void 0&&(a=[1,1,1]);var s=O(n,"x","conv3d"),o=O(t,"filter","conv3d"),l=s,u=!1;s.rank===4&&(u=!0,l=V(s,[1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]])),D(l.rank===5,function(){return"Error in conv3d: input must be rank 5, but got rank "+l.rank+"."}),D(o.rank===5,function(){return"Error in conv3d: filter must be rank 5, but got rank "+(o.rank+".")}),D(l.shape[4]===o.shape[3],function(){return"Error in conv3d: depth of input ("+l.shape[4]+") must match "+("input depth for filter "+o.shape[3]+".")}),D(Bt(e,a),function(){return"Error in conv3D: Either strides or dilations must be 1. "+("Got strides "+e+" and dilations '"+a+"'")}),D(r==="NDHWC",function(){return"Error in conv3d: got dataFormat of "+r+" but only NDHWC is currently supported."});var c=function(f,m){var g=ga(l.shape,o.shape,e,a,i),v=f.conv3d(l,o,g);return m([l,o]),v},h={x:l,filter:o},d={strides:e,pad:i,dataFormat:r,dilations:a},p=z.runKernelFunc(c,h,null,yl,d);return u?V(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var aT=U({conv3d_:rT});function sT(n,t,e,i,r){D(n.length===t.rank,function(){return"Length of inShape "+("("+n.length+") and rank of dy ("+t.rank+") must match")});var a=n,s=t,o=!1;t.rank===4&&(o=!0,s=V(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),a=[1,n[0],n[1],n[2],n[3]]);var l=a[4],u=s.shape[4];D(a.length===5,function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+(a.length+".")}),D(s.rank===5,function(){return"Error in conv3dDerInput: dy must be rank 5, but got "+("rank "+s.rank)}),D(e.rank===5,function(){return"Error in conv3dDerInput: filter must be rank 5, but got "+("rank "+e.rank)}),D(l===e.shape[3],function(){return"Error in conv3dDerInput: depth of input ("+l+") must "+("match input depth for filter "+e.shape[3]+".")}),D(u===e.shape[4],function(){return"Error in conv3dDerInput: depth of output ("+u+") must "+("match output depth for filter "+e.shape[4]+".")});var c=function(f){var m=1,g=ga(a,e.shape,i,m,r);return f.conv3dDerInput(s,e,g)},h={dy:s},d={pad:r},p=z.runKernelFunc(c,h,null,_p,d);return o?V(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var Qm=U({conv3DBackpropInput_:sT});function oT(n,t,e,i,r){var a=O(n,"x","conv3dTranspose"),s=O(t,"filter","conv3dTranspose");return Qm(e,a,s,i,r)}var lT=U({conv3dTranspose_:oT});function uT(n){var t=O(n,"x","cos"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.cos(t);return r([t]),a},e,null,bl)}var xs=U({cos_:uT});function cT(n){var t=O(n,"x","cosh"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.cosh(t);return r([t]),a},e,null,wl)}var Sc=U({cosh_:cT});function hT(n,t,e,i){t===void 0&&(t=0),e===void 0&&(e=!1),i===void 0&&(i=!1);var r=O(n,"x","cumsum"),a=function(l,u){var c=Qt([t],r.rank),h=r;c!=null&&(h=lt(r,c));var d=Nn(1,r.rank)[0],p=l.cumsum(h,d,e,i);if(u([r]),c!=null){var f=Ss(c);p=lt(p,f)}return p},s={x:r},o={axis:t,exclusive:e,reverse:i};return z.runKernelFunc(a,s,null,Sl,o)}var Lc=U({cumsum_:hT});function dT(n,t,e){e===void 0&&(e="NHWC");var i=O(n,"x","depthToSpace"),r=e==="NHWC"?i.shape[1]:i.shape[2],a=e==="NHWC"?i.shape[2]:i.shape[3],s=e==="NHWC"?i.shape[3]:i.shape[1];D(r*t>=0,function(){return`Negative dimension size caused by overflow when multiplying +`)+("Expected: "+u+"."))}}function DA(n,t){n().then(function(){return t.fail()},function(){return t()})}function kA(n,t){var e=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Zn(n)||Zn(n[0])||Zn(t)||Zn(t[0])?pc(n,e,function(i,r){return i==r}):pc(n,t,function(i,r){return fc(i,r,0)})}function FA(n,t,e){if(e==null&&(e=dc()),!fc(n,t,e))throw new Error("Numbers differ: actual === "+n+", expected === "+t)}function fc(n,t,e){return!isFinite(n)&&!isFinite(t)?!0:!(isNaN(n)||isNaN(t)||Math.abs(n-t)>e)}function WA(n,t,e){for(var i=0;ie)throw new Error("Value out of range:"+n[i]+" low: "+t+", high: "+e)}function UA(n,t){expect(new Float32Array(n)).toEqual(new Float32Array(t))}var BA={__proto__:null,TEST_EPSILON_FLOAT16:Dm,expectArraysClose:EA,testEpsilon:dc,expectPromiseToFail:DA,expectArraysEqual:kA,expectNumbersClose:FA,expectValuesInRange:WA,expectArrayBuffersEqual:UA};var zA="2.6.0";function _A(){Me().set("PROD",!0)}function PA(){Me().set("DEBUG",!0)}function MA(){Me().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function It(n){Me().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(n+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function HA(){z.disposeVariables()}function VA(){return z}function qA(){return z.memory()}function GA(n){return z.profile(n)}function ft(n,t){return z.tidy(n,t)}function Ut(n){var t=Ju(n);t.forEach(function(e){return e.dispose()})}function km(n){return z.keep(n)}function YA(n){return z.time(n)}function KA(n){return z.setBackend(n)}function jA(){return z.ready()}function $A(){return z.backendName}function XA(n){z.removeBackend(n)}function JA(n){return z.findBackend(n)}function ZA(n){return z.findBackendFactory(n)}function QA(n,t,e){return e===void 0&&(e=1),z.registerBackend(n,t,e)}function e1(){return z.backend}function t1(n,t){Me().setPlatform(n,t)}function n1(n,t){var e,i=O(n,"a","add"),r=O(t,"b","add");e=rt(i,r),i=e[0],r=e[1];var a=function(o,l){var u=o.add(i,r);return l([i,r]),u},s={a:i,b:r};return z.runKernelFunc(a,s,null,os)}var fe=U({add_:n1});function i1(n,t){var e,i=O(n,"a","floorDiv"),r=O(t,"b","floorDiv");e=rt(i,r),i=e[0],r=e[1];var a=function(o,l){var u=o.floorDiv(i,r);return l([i,r]),u},s={a:i,b:r};return z.runKernelFunc(a,s,null,Ol)}var mc=U({floorDiv_:i1});function r1(n,t){var e,i=O(n,"a","div"),r=O(t,"b","div");if(e=rt(i,r),i=e[0],r=e[1],i.dtype==="int32"&&r.dtype==="int32")return mc(i,r);var a=function(l,u){var c=l.realDivide(i,r);return u([i,r]),c},s={a:i,b:r},o={};return z.runKernelFunc(a,s,null,Al,o)}var Ie=U({div_:r1});function a1(n,t){var e,i=O(n,"a","mul"),r=O(t,"b","mul");e=rt(i,r),i=e[0],r=e[1];var a=function(o,l){var u=o.multiply(i,r);return l([i,r]),u},s={a:i,b:r};return z.runKernelFunc(a,s,null,$l)}var J=U({mul_:a1});function s1(n){var t=O(n,"x","abs"),e={x:t};return z.runKernelFunc(function(i,r){return r([t]),t.dtype==="complex64"?i.complexAbs(t):i.abs(t)},e,null,Jo)}var Vt=U({abs_:s1});function o1(n){var t=O(n,"x","acos"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.acos(t);return r([t]),a},e,null,Zo)}var Fm=U({acos_:o1});function l1(n){var t=O(n,"x","acosh"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.acosh(t);return r([t]),a},e,null,Qo)}var Wm=U({acosh_:l1});function u1(n){D(Array.isArray(n),function(){return"The argument passed to tf.addN() must be a list of tensors"}),D(n.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+(""+n.length)});var t=n.map(function(a,s){return O(a,"tensors"+s,"addN")}),e=t[0];t.forEach(function(a){if(a.dtype!==e.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(function(a){if(!an(a.shape,e.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var i=function(a,s){var o=a.addN(t);return s(t),o},r=t;return z.runKernelFunc(i,r,null,el)}var c1=U({addN_:u1});function gc(n,t){for(var e=0;e=0&&t=1,function(){return"Pass at least one tensor to concat"});var e=pa(n,"tensors","concat");e[0].dtype==="complex64"&&e.forEach(function(s){if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor + with dtype `+s.dtype+". ")});var i=function(s,o){var l=Ze(t,e[0].shape)[0],u=jm(e.map(function(d){return d.shape}),l);if(st(u)===0)return ni([],u);if(e=e.filter(function(d){return d.size>0}),e.length===1)return e[0];var c=e.map(function(d){return d.shape});Km(c,l);var h=s.concat(e,l);return o(e),h},r=e,a={axis:t};return z.runKernelFunc(i,r,null,ml,a)}var xt=U({concat_:R1});function O1(n){var t=O(n,"x","sigmoid"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.sigmoid(t);return r([a]),a},e,null,vu)}var Ui=U({sigmoid_:O1});function E1(n,t,e){var i=O(n,"x","slice");if(i.rank===0)throw new Error("Slicing scalar is not possible");var r=function(o,l){var u=hc(i,t,e),c=u[0],h=u[1];return ym(i,c,h),l([i]),o.slice(i,c,h)},a={x:i},s={begin:t,size:e};return z.runKernelFunc(r,a,null,pu,s)}var Be=U({slice_:E1});function D1(n){var t=O(n,"x","tanh"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.tanh(t);return r([a]),a},e,null,xu)}var Is=U({tanh_:D1});function k1(n,t,e,i,r,a){var s=O(n,"forgetBias","basicLSTMCell"),o=O(t,"lstmKernel","basicLSTMCell"),l=O(e,"lstmBias","basicLSTMCell"),u=O(i,"data","basicLSTMCell"),c=O(r,"c","basicLSTMCell"),h=O(a,"h","basicLSTMCell"),d=xt([u,h],1),p=Fe(d,o),f=fe(p,l),m=f.shape[0],g=f.shape[1]/4,v=[m,g],b=Be(f,[0,0],v),S=Be(f,[0,g],v),L=Be(f,[0,g*2],v),w=Be(f,[0,g*3],v),N=fe(J(Ui(b),Is(S)),J(c,Ui(fe(s,L)))),I=J(Is(N),Ui(w));return[N,I]}var F1=U({basicLSTMCell_:k1});function W1(n,t,e){var i=O(n,"x","batchToSpaceND"),r=t.reduce(function(l,u){return l*u});D(i.rank>=1+t.length,function(){return"input rank is "+i.rank+" but should be > than blockShape.length "+t.length}),D(e.length===t.length,function(){return"crops.length is "+e.length+" but should be equal to blockShape.length "+t.length}),D(i.shape[0]%r===0,function(){return"input tensor batch is "+i.shape[0]+" but is not divisible by the product of "+("the elements of blockShape "+t.join(" * ")+" === "+r)});var a=function(l){return l.batchToSpaceND(i,t,e)},s={x:i},o={blockShape:t,crops:e};return z.runKernelFunc(a,s,null,hl,o)}var As=U({batchToSpaceND_:W1});function U1(n){var t;return n.rank===0||n.rank===1?t=V(n,[1,1,1,n.size]):n.rank===2?t=V(n,[1,1,n.shape[0],n.shape[1]]):n.rank===3?t=V(n,[1,n.shape[0],n.shape[1],n.shape[2]]):t=n,t}function B1(n,t,e,i,r,a){a==null&&(a=.001);var s=O(n,"x","batchNorm"),o=O(t,"mean","batchNorm"),l=O(e,"variance","batchNorm"),u;r!=null&&(u=O(r,"scale","batchNorm"));var c;i!=null&&(c=O(i,"offset","batchNorm")),D(o.rank===l.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),D(c==null||o.rank===c.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),D(u==null||o.rank===u.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."});var h=U1(s),d=function(g,v){return v([h,o,l,u]),g.batchNorm(h,Ts(o),Ts(l),Ts(c),Ts(u),a)},p={x:h,scale:u,offset:c,mean:o,variance:l},f={varianceEpsilon:a},m=z.runKernelFunc(d,p,null,El,f);return V(m,s.shape)}function Ts(n){return n==null?null:n.rank===0?V(n,[n.size]):n.rank===1?n:n.rank===2?V(n,[1,1,n.shape[0],n.shape[1]]):n.rank===3?V(n,[1,n.shape[0],n.shape[1],n.shape[2]]):n}var ya=U({batchNorm_:B1});function z1(n,t,e,i,r,a){var s=O(n,"x","batchNorm"),o=O(t,"mean","batchNorm"),l=O(e,"variance","batchNorm"),u;r!=null&&(u=O(r,"scale","batchNorm"));var c;return i!=null&&(c=O(i,"offset","batchNorm")),D(s.rank===2,function(){return"Error in batchNorm2D: x must be rank 2 but got rank "+(s.rank+".")}),D(o.rank===2||o.rank===1,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but "+("got rank "+o.rank+".")}),D(l.rank===2||l.rank===1,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 "+("but got rank "+l.rank+".")}),u!=null&&D(u.rank===2||u.rank===1,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 "+("but got rank "+u.rank+".")}),c!=null&&D(c.rank===2||c.rank===1,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 "+("but got rank "+c.rank+".")}),ya(s,o,l,c,u,a)}var _1=U({batchNorm2d_:z1});function P1(n,t,e,i,r,a){var s=O(n,"x","batchNorm"),o=O(t,"mean","batchNorm"),l=O(e,"variance","batchNorm"),u;r!=null&&(u=O(r,"scale","batchNorm"));var c;return i!=null&&(c=O(i,"offset","batchNorm")),D(s.rank===3,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+(s.rank+".")}),D(o.rank===3||o.rank===1,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but "+("got rank "+o.rank+".")}),D(l.rank===3||l.rank===1,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 "+("but got rank "+l.rank+".")}),u!=null&&D(u.rank===3||u.rank===1,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 "+("but got rank "+u.rank+".")}),c!=null&&D(c.rank===3||c.rank===1,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 "+("but got rank "+c.rank+".")}),ya(s,o,l,c,u,a)}var M1=U({batchNorm3d_:P1});function H1(n,t,e,i,r,a){var s=O(n,"x","batchNorm"),o=O(t,"mean","batchNorm"),l=O(e,"variance","batchNorm"),u;r!=null&&(u=O(r,"scale","batchNorm"));var c;return i!=null&&(c=O(i,"offset","batchNorm")),D(s.rank===4,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+(s.rank+".")}),D(o.rank===4||o.rank===1,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but "+("got rank "+o.rank+".")}),D(l.rank===4||l.rank===1,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 "+("but got rank "+l.rank+".")}),u!=null&&D(u.rank===4||u.rank===1,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 "+("but got rank "+u.rank+".")}),c!=null&&D(c.rank===4||c.rank===1,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 "+("but got rank "+c.rank+".")}),ya(s,o,l,c,u,a)}var V1=U({batchNorm4d_:H1});function q1(n,t){var e=O(n,"broadcastTo","x"),i=e.shape;if(t.some(function(d){return!(d>0)||d%1!==0}))throw new Error("broadcastTo(): Invalid broadcast shape ["+t+"].");if(t.lengthe.rank){for(var r=e.shape.slice();r.length=0;o--)if(a[o]===t[o])s[o]=1;else if(e.shape[o]!==1)throw new Error("broadcastTo(): ["+i+"] cannot be broadcast to ["+t+"].");var l=s.map(function(d,p){return d>1?p:-1}).filter(function(d){return d>=0});if(l.length===0)return Fi(e);var u=function(d){return d.tile(e,s)},c={x:e},h={shape:t,inputShape:a};return z.runKernelFunc(u,c,null,dl,h)}var Ns=U({broadcastTo_:q1});function G1(n){var t=O(n,"x","ceil"),e={x:t};return z.runKernelFunc(function(i){return i.ceil(t)},e,null,pl)}var $m=U({ceil_:G1});function Y1(n,t,e){var i=O(n,"x","clipByValue");D(t<=e,function(){return"Error in clip: min ("+t+") must be "+("less than or equal to max ("+e+").")});var r={x:i},a={clipValueMin:t,clipValueMax:e};return z.runKernelFunc(function(s,o){var l=s.clip(i,t,e);return o([i]),l},r,null,fl,a)}var Xm=U({clipByValue_:Y1});function K1(n){return xt(n,0)}var j1=U({concat1d_:K1});function $1(n,t){return xt(n,t)}var X1=U({concat2d_:$1});function J1(n,t){return xt(n,t)}var Z1=U({concat3d_:J1});function Q1(n,t){return xt(n,t)}var eT=U({concat4d_:Q1});function tT(n,t,e,i,r,a,s){r===void 0&&(r="NHWC"),a===void 0&&(a=[1,1]);var o=O(n,"x","conv2d"),l=O(t,"filter","conv2d"),u=o,c=!1;o.rank===3&&(c=!0,u=V(o,[1,o.shape[0],o.shape[1],o.shape[2]])),D(u.rank===4,function(){return"Error in conv2d: input must be rank 4, but got rank "+u.rank+"."}),D(l.rank===4,function(){return"Error in conv2d: filter must be rank 4, but got rank "+(l.rank+".")}),s!=null&&D(it(i),function(){return"Error in conv2d: pad must be an integer when using, "+("dimRoundingMode "+s+" but got pad "+i+".")});var h=r==="NHWC"?u.shape[3]:u.shape[1];D(h===l.shape[2],function(){return"Error in conv2d: depth of input ("+h+") must match "+("input depth for filter "+l.shape[2]+".")}),D(Bt(e,a),function(){return"Error in conv2D: Either strides or dilations must be 1. "+("Got strides "+e+" and dilations '"+a+"'")});var d=function(g,v){var b=ma(r),S=xn(u.shape,l.shape,e,a,i,s,!1,b),L=g.conv2d(u,l,S);return v([u,l]),L},p={x:u,filter:l},f={strides:e,pad:i,dataFormat:r,dilations:a,dimRoundingMode:s},m=z.runKernelFunc(d,p,null,gl,f);return c?V(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Nr=U({conv2d_:tT});function nT(n,t,e,i,r,a,s){r===void 0&&(r="NWC"),a===void 0&&(a=1);var o=O(n,"x","conv1d"),l=O(t,"filter","conv1d"),u=o,c=!1;o.rank===2&&(c=!0,u=V(o,[1,o.shape[0],o.shape[1]])),D(u.rank===3,function(){return"Error in conv1d: input must be rank 3, but got rank "+u.rank+"."}),D(l.rank===3,function(){return"Error in conv1d: filter must be rank 3, but got rank "+(l.rank+".")}),s!=null&&D(it(i),function(){return"Error in conv1d: pad must be an integer when using, "+("dimRoundingMode "+s+" but got pad "+i+".")}),D(u.shape[2]===l.shape[1],function(){return"Error in conv1d: depth of input ("+u.shape[2]+") must match "+("input depth for filter "+l.shape[1]+".")}),D(Bt(e,a),function(){return"Error in conv1D: Either stride or dilation must be 1. "+("Got stride "+e+" and dilation '"+a+"'")}),D(r==="NWC",function(){return"Error in conv1d: got dataFormat of "+r+" but only NWC is currently supported."});var h=V(l,[1,l.shape[0],l.shape[1],l.shape[2]]),d=V(u,[u.shape[0],1,u.shape[1],u.shape[2]]),p=[1,e],f=[1,a],m="NHWC",g=Nr(d,h,p,i,m,f,s);return c?V(g,[g.shape[2],g.shape[3]]):V(g,[g.shape[0],g.shape[2],g.shape[3]])}var Jm=U({conv1d_:nT});function iT(n,t,e,i,r,a,s){a===void 0&&(a="NHWC"),D(n.length===t.rank,function(){return"Length of inShape "+("("+n.length+") and rank of dy ("+t.rank+") must match")});var o=n,l=t,u=!1;t.rank===3&&(u=!0,l=V(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,n[0],n[1],n[2]]),D(o.length===4,function(){return"Error in conv2dDerInput: inShape must be length 4, but got length "+(o.length+".")}),D(l.rank===4,function(){return"Error in conv2dDerInput: dy must be rank 4, but got "+("rank "+l.rank)}),D(e.rank===4,function(){return"Error in conv2dDerInput: filter must be rank 4, but got "+("rank "+e.rank)});var c=a==="NHWC"?o[3]:o[1],h=a==="NHWC"?l.shape[3]:l.shape[1];D(c===e.shape[2],function(){return"Error in conv2dDerInput: depth of input ("+c+") must "+("match input depth for filter "+e.shape[2]+".")}),D(h===e.shape[3],function(){return"Error in conv2dDerInput: depth of output ("+h+") must "+("match output depth for filter "+e.shape[3]+".")}),s!=null&&D(it(r),function(){return"Error in conv2dDerInput: pad must be an integer when using, "+("dimRoundingMode "+s+" but got pad "+r+".")});var d=function(g,v){var b=1,S=ma(a),L=xn(o,e.shape,i,b,r,s,!1,S),w=g.conv2dDerInput(l,e,L);return v([l,e]),w},p={dy:l,filter:e},f={strides:i,pad:r,dataFormat:a,dimRoundingMode:s,inputShape:o},m=z.runKernelFunc(d,p,null,vl,f);return u?V(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var wc=U({conv2DBackpropInput_:iT});function rT(n,t,e,i,r,a){var s=O(n,"x","conv2dTranspose"),o=O(t,"filter","conv2dTranspose");return wc(e,s,o,i,r,"NHWC",a)}var Zm=U({conv2dTranspose_:rT});function aT(n,t,e,i,r,a){r===void 0&&(r="NDHWC"),a===void 0&&(a=[1,1,1]);var s=O(n,"x","conv3d"),o=O(t,"filter","conv3d"),l=s,u=!1;s.rank===4&&(u=!0,l=V(s,[1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]])),D(l.rank===5,function(){return"Error in conv3d: input must be rank 5, but got rank "+l.rank+"."}),D(o.rank===5,function(){return"Error in conv3d: filter must be rank 5, but got rank "+(o.rank+".")}),D(l.shape[4]===o.shape[3],function(){return"Error in conv3d: depth of input ("+l.shape[4]+") must match "+("input depth for filter "+o.shape[3]+".")}),D(Bt(e,a),function(){return"Error in conv3D: Either strides or dilations must be 1. "+("Got strides "+e+" and dilations '"+a+"'")}),D(r==="NDHWC",function(){return"Error in conv3d: got dataFormat of "+r+" but only NDHWC is currently supported."});var c=function(f,m){var g=ga(l.shape,o.shape,e,a,i),v=f.conv3d(l,o,g);return m([l,o]),v},h={x:l,filter:o},d={strides:e,pad:i,dataFormat:r,dilations:a},p=z.runKernelFunc(c,h,null,yl,d);return u?V(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var sT=U({conv3d_:aT});function oT(n,t,e,i,r){D(n.length===t.rank,function(){return"Length of inShape "+("("+n.length+") and rank of dy ("+t.rank+") must match")});var a=n,s=t,o=!1;t.rank===4&&(o=!0,s=V(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),a=[1,n[0],n[1],n[2],n[3]]);var l=a[4],u=s.shape[4];D(a.length===5,function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+(a.length+".")}),D(s.rank===5,function(){return"Error in conv3dDerInput: dy must be rank 5, but got "+("rank "+s.rank)}),D(e.rank===5,function(){return"Error in conv3dDerInput: filter must be rank 5, but got "+("rank "+e.rank)}),D(l===e.shape[3],function(){return"Error in conv3dDerInput: depth of input ("+l+") must "+("match input depth for filter "+e.shape[3]+".")}),D(u===e.shape[4],function(){return"Error in conv3dDerInput: depth of output ("+u+") must "+("match output depth for filter "+e.shape[4]+".")});var c=function(f){var m=1,g=ga(a,e.shape,i,m,r);return f.conv3dDerInput(s,e,g)},h={dy:s},d={pad:r},p=z.runKernelFunc(c,h,null,_p,d);return o?V(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var Qm=U({conv3DBackpropInput_:oT});function lT(n,t,e,i,r){var a=O(n,"x","conv3dTranspose"),s=O(t,"filter","conv3dTranspose");return Qm(e,a,s,i,r)}var uT=U({conv3dTranspose_:lT});function cT(n){var t=O(n,"x","cos"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.cos(t);return r([t]),a},e,null,bl)}var xs=U({cos_:cT});function hT(n){var t=O(n,"x","cosh"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.cosh(t);return r([t]),a},e,null,wl)}var Sc=U({cosh_:hT});function dT(n,t,e,i){t===void 0&&(t=0),e===void 0&&(e=!1),i===void 0&&(i=!1);var r=O(n,"x","cumsum"),a=function(l,u){var c=Qt([t],r.rank),h=r;c!=null&&(h=lt(r,c));var d=Nn(1,r.rank)[0],p=l.cumsum(h,d,e,i);if(u([r]),c!=null){var f=Ss(c);p=lt(p,f)}return p},s={x:r},o={axis:t,exclusive:e,reverse:i};return z.runKernelFunc(a,s,null,Sl,o)}var Lc=U({cumsum_:dT});function pT(n,t,e){e===void 0&&(e="NHWC");var i=O(n,"x","depthToSpace"),r=e==="NHWC"?i.shape[1]:i.shape[2],a=e==="NHWC"?i.shape[2]:i.shape[3],s=e==="NHWC"?i.shape[3]:i.shape[1];D(r*t>=0,function(){return`Negative dimension size caused by overflow when multiplying `+r+" and "+t+` for depthToSpace with input shape `+i.shape}),D(a*t>=0,function(){return`Negative dimension size caused by overflow when multiplying `+a+" and "+t+` for depthToSpace with input shape - `+i.shape}),D(s%(t*t)===0,function(){return"Dimension size must be evenly divisible by "+t*t+" but is "+s+" for depthToSpace with input shape "+i.shape});var o=function(c){return c.depthToSpace(i,t,e)},l={x:i},u={blockSize:t,dataFormat:e};return z.runKernelFunc(o,l,null,Mp,u)}var eg=U({depthToSpace_:dT});function pT(n,t,e,i,r,a,s){r===void 0&&(r="NHWC"),a===void 0&&(a=[1,1]);var o=O(n,"x","depthwiseConv2d"),l=O(t,"filter","depthwiseConv2d"),u=o,c=!1;o.rank===3&&(c=!0,u=V(o,[1,o.shape[0],o.shape[1],o.shape[2]])),D(u.rank===4,function(){return"Error in depthwiseConv2d: input must be rank 4, but got "+("rank "+u.rank+".")}),D(l.rank===4,function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+(l.rank+".")}),D(u.shape[3]===l.shape[2],function(){return"Error in depthwiseConv2d: number of input channels "+("("+u.shape[3]+") must match the inChannels dimension in ")+("filter "+l.shape[2]+".")}),s!=null&&D(it(i),function(){return"Error in depthwiseConv2d: pad must be an integer when using, "+("dimRoundingMode "+s+" but got pad "+i+".")});var h=function(m,g){a==null&&(a=[1,1]),D(Bt(e,a),function(){return"Error in depthwiseConv2d: Either strides or dilations must be "+("1. Got strides "+e+" and dilations '"+a+"'")});var v=xn(u.shape,l.shape,e,a,i,s,!0),b=m.depthwiseConv2D(u,l,v);return g([u,l]),b},d={x:u,filter:l},p={strides:e,pad:i,dataFormat:r,dilations:a,dimRoundingMode:s},f=z.runKernelFunc(h,d,null,Ll,p);return c?V(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var ba=U({depthwiseConv2d_:pT});function fT(n){var t=O(n,"x","diag"),e=function(r){var a=V(t,[t.size]),s=r.diag(a),o=n.shape.concat(n.shape);return V(s,o)},i={x:t};return z.runKernelFunc(e,i,null,qp)}var mT=U({diag_:fT});function gT(n,t,e,i,r,a){r===void 0&&(r=[1,1]),a===void 0&&(a="NHWC");var s=O(n,"x","dilation2d"),o=O(t,"filter","dilation2d");D(s.rank===3||s.rank===4,function(){return"Error in dilation2d: input must be rank 3 or 4, but got rank "+(s.rank+".")}),D(o.rank===3,function(){return"Error in dilation2d: filter must be rank 3, but got rank "+(o.rank+".")}),D(a==="NHWC",function(){return"Error in dilation2d: Only NHWC is currently supported, "+("but got dataFormat of "+a)});var l=s,u=!1;s.rank===3&&(l=V(s,[1,s.shape[0],s.shape[1],s.shape[2]]),u=!0);var c={x:l,filter:o},h={strides:e,pad:i,dilations:r},d=z.runKernel(Il,c,h);return u?V(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var tg=U({dilation2d_:gT});function vT(n,t){for(var e=n.length,i=[],r=0;r1&&s===1&&i.unshift(a)}return i}function mt(n,t){for(var e=[],i=0;i1)&&e.unshift(a)}return e}function Qe(n,t){for(var e=[],i=Math.max(n.length,t.length),r=0;rt||i===n?e=!0:i=ds(n,i+1);return i}function kT(n,t,e){for(var i=[],r=n.length,a=0;a0,function(){return"variableGrads() expects at least one of the input variables to "+("be trainable, but none of the "+a+" variables is ")+"trainable."});var s=!0,o=z.gradients(n,t,null,s),l=o.value,u=o.grads;D(u.some(function(h){return h!=null}),function(){return"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."}),D(l.rank===0,function(){return"The f passed in variableGrads(f) must return a scalar, but it "+("returned a rank-"+l.rank+" tensor")});var c={};return t.forEach(function(h,d){u[d]!=null&&(c[h.name]=u[d])}),r!=null&&r.forEach(function(h){return c[h.name]=null}),{value:l,grads:c}}function Cn(n){return z.customGrad(n)}function Ds(n){var t=n.filter(function(e){return e==null}).length;if(t>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that - the f you passed encloses all operations that lead from x to y.`)}function eN(n){var t=O(n,"x","neg"),e={x:t};return z.runKernelFunc(function(i){return i.neg(t)},e,null,Xl)}var gt=U({neg_:eN});function tN(n){var t=O(n,"x","softplus"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.softplus(t);return r([t]),a},e,null,yu)}var xc=U({softplus_:tN});function nN(n){var t=O(n,"x","logSigmoid"),e=Cn(function(i){var r=gt(xc(gt(i))),a=function(s){var o=J(s,Ui(gt(i)));return o};return{value:r,gradFunc:a}});return e(t)}var fg=U({logSigmoid_:nN});function iN(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var i=O(n,"x","max"),r=function(o,l){var u=Ze(t,i.shape),c=u,h=Qt(c,i.rank),d=i;h!=null&&(d=lt(i,h),c=Nn(c.length,d.rank));var p=o.max(d,c);h!=null&&d.dispose();var f=p;if(e){var m=Zt(f.shape,Ze(t,i.shape));f=V(f,m),p.dispose()}return l([i,f]),f},a={x:i},s={reductionIndices:t,keepDims:e};return z.runKernelFunc(r,a,null,Hl,s)}var Pi=U({max_:iN});function rN(n,t){var e,i=O(n,"a","sub"),r=O(t,"b","sub");e=rt(i,r),i=e[0],r=e[1];var a=function(o,l){var u=o.subtract(i,r);return l([i,r]),u},s={a:i,b:r};return z.runKernelFunc(a,s,null,Tu)}var ge=U({sub_:rN});function aN(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var i=O(n,"x","sum");i.dtype==="bool"&&(i=ue(i,"int32"));var r=function(o,l){l([i]);var u=Ze(t,i.shape),c=Qt(u,i.rank),h=u,d=i;c!=null&&(d=lt(i,c),h=Nn(h.length,i.rank));var p=o.sum(d,h);if(e){var f=Zt(p.shape,u);p=V(p,f)}return p},a={x:i},s={axis:t,keepDims:e};return z.runKernelFunc(r,a,null,wu,s)}var Ae=U({sum_:aN});function sN(n,t){t===void 0&&(t=-1);var e=O(n,"logits","logSoftmax");if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. "+("Logits was rank "+e.rank+" and axis was "+t));var i=function(s,o){var l=!0,u=Pi(n,t,!0),c=ge(n,u),h=ge(ue(c,"float32"),_i(Ae(cn(c),t,l)));return o([h]),h},r={logits:e},a={axis:t};return z.runKernelFunc(i,r,null,Pl,a)}var mg=U({logSoftmax_:sN});function oN(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var i=O(n,"x","logSumExp"),r=Ze(t,i.shape),a=Pi(i,r,!0),s=ge(i,a),o=cn(s),l=Ae(o,r),u=_i(l),c=fe(V(a,u.shape),u);if(e){var h=Zt(c.shape,r);return V(c,h)}return c}var Cc=U({logSumExp_:oN});function lN(n,t){var e=O(n,"a","logicalAnd","bool"),i=O(t,"b","logicalAnd","bool");Qe(e.shape,i.shape);var r={a:e,b:i};return z.runKernelFunc(function(a){return a.logicalAnd(e,i)},r,null,sf)}var Mi=U({logicalAnd_:lN});function uN(n){var t=O(n,"x","logicalNot","bool"),e={x:t};return z.runKernelFunc(function(i){return i.logicalNot(t)},e,null,of)}var ks=U({logicalNot_:uN});function cN(n,t){var e=O(n,"a","logicalOr","bool"),i=O(t,"b","logicalOr","bool");Qe(e.shape,i.shape);var r={a:e,b:i};return z.runKernelFunc(function(a){return a.logicalOr(e,i)},r,null,lf)}var Rc=U({logicalOr_:cN});function hN(n,t){var e=O(n,"a","logicalXor","bool"),i=O(t,"b","logicalXor","bool");return Qe(e.shape,i.shape),Mi(Rc(n,t),ks(Mi(n,t)))}var gg=U({logicalXor_:hN});function dN(n,t,e,i,r){var a=O(n,"x","maxPool"),s=1,o=a,l=!1;a.rank===3&&(l=!0,o=V(a,[1,a.shape[0],a.shape[1],a.shape[2]])),D(o.rank===4,function(){return"Error in maxPool: input must be rank 4 but got rank "+o.rank+"."}),D(Bt(e,s),function(){return"Error in maxPool: Either strides or dilations must be 1. "+("Got strides "+e+" and dilations '"+s+"'")}),r!=null&&D(it(i),function(){return"Error in maxPool: pad must be an integer when using, "+("dimRoundingMode "+r+" but got pad "+i+".")});var u=function(p,f){var m=Ar(o.shape,t,e,1,i,r),g;return m.filterWidth===1&&m.filterHeight===1&&an(m.inShape,m.outShape)?g=o.clone():g=p.maxPool(o,m),f([o,g]),g},c={x:o},h={filterSize:t,strides:e,pad:i,dimRoundingMode:r},d=z.runKernelFunc(u,c,null,ql,h);return l?V(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Oc=U({maxPool_:dN});function pN(n,t,e,i,r,a,s){t===void 0&&(t=[1,1,1]),a===void 0&&(a="NDHWC"),s==null?s=[1,1,1]:It("dilations is deprecated, this field will be gone in v3.0.0.");var o=O(n,"x","maxPool3d"),l=o,u=!1;o.rank===4&&(u=!0,l=V(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),D(l.rank===5,function(){return"Error in maxPool3d: x must be rank 5 but got rank "+l.rank+"."}),D(a==="NDHWC",function(){return"Error in maxPool3d: Only NDHWC is currently supported, "+("but got dataFormat of "+a)}),D(Bt(e,s),function(){return"Error in maxPool3d: Either strides or dilations must be 1. "+("Got strides "+e+" and dilations '"+s+"'")}),r!=null&&D(it(i),function(){return"Error in maxPool3d: pad must be an integer when using, "+("dimRoundingMode "+r+" but got pad "+i+".")});var c=function(f,m){s==null&&(s=[1,1,1]);var g=va(l.shape,t,e,s,i,r,a),v=f.maxPool3d(l,g);return m([l,v]),v},h={x:l},d={filterSize:t,strides:e,pad:i,dimRoundingMode:r,dataFormat:a,dilations:s},p=z.runKernelFunc(c,h,null,Gl,d);return u?V(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var fN=U({maxPool3d_:pN});function mN(n,t,e,i,r){r===void 0&&(r=!1);var a=O(n,"x","maxPoolWithArgmax"),s={x:a},o={filterSize:t,strides:e,pad:i,includeBatchInIndex:r},l=z.runKernel(df,s,o);return{result:l[0],indexes:l[1]}}var gN=U({maxPoolWithArgmax_:mN});function Mn(n,t){if(t===void 0&&(t="float32"),t==="complex64"){var e=Mn(n,"float32"),i=Mn(n,"float32");return ei(e,i)}var r=vr(st(n),t);return z.makeTensor(r,n,t)}function Rr(n,t){if(t===void 0&&(t="float32"),t==="complex64"){var e=Rr(n,"float32"),i=Mn(n,"float32");return ei(e,i)}var r=Hu(st(n),t);return z.makeTensor(r,n,t)}function vN(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var i=O(n,"x","mean"),r=Ze(t,i.shape),a=Bm(i.shape,r),s=a[1],o=st(s),l=Cn(function(u){var c=we(o),h=c.dtype===u.dtype?u:ue(u,c.dtype),d=Ie(h,c),p=Ae(d,t,e),f=function(m){var g=u.shape.slice();r.forEach(function(S){g[S]=1});var v=V(m,g),b=Ie(J(v,Rr(u.shape,"float32")),o);return b};return{value:p,gradFunc:f}});return l(i)}var Sa=U({mean_:vN});function yN(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var i=O(n,"x","min"),r=function(o,l){var u=Ze(t,i.shape),c=u,h=Qt(c,i.rank),d=i;h!=null&&(d=lt(i,h),c=Nn(c.length,i.rank));var p=o.min(d,c);h!=null&&d.dispose();var f=p;if(e){var m=Zt(f.shape,u);f=V(p,m),p.dispose()}return l([i,f]),f},a={x:i},s={axis:t,keepDims:e};return z.runKernelFunc(r,a,null,Yl,s)}var Fs=U({min_:yN});function bN(n,t){var e,i=O(n,"a","minimum"),r=O(t,"b","minimum");e=rt(i,r),i=e[0],r=e[1],i.dtype==="bool"&&(i=ue(i,"int32"),r=ue(r,"int32")),Qe(i.shape,r.shape);var a=function(o,l){var u=o.minimum(i,r);return l([i,r]),u},s={a:i,b:r};return z.runKernelFunc(a,s,null,Kl)}var Ws=U({minimum_:bN});function wN(n,t){var e,i=O(n,"a","mod"),r=O(t,"b","mod");e=rt(i,r),i=e[0],r=e[1];var a=function(o,l){var u=o.mod(i,r);return l([i,r]),u},s={a:i,b:r};return z.runKernelFunc(a,s,null,jl)}var Ec=U({mod_:wN});function SN(n){var t=O(n,"x","square"),e={},i=[t],r=[];return z.runKernelFunc(function(a,s){return s([t]),a.square(t)},{x:t},null,"Square",e,i,r)}var qe=U({square_:SN});function LN(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1),n=O(n,"x","moments");var i=Ze(t,n.shape),r=Sa(n,i,e),a=r.shape;e||(a=Zt(r.shape,i));var s=qe(ge(ue(n,"float32"),V(r,a))),o=Sa(s,i,e);return{mean:r,variance:o}}var IN=U({moments_:LN});function AN(n,t,e,i){for(var r=O(t,"data","multiRNNCell"),a=pa(e,"c","multiRNNCell"),s=pa(i,"h","multiRNNCell"),o=r,l=[],u=0;u2)throw new Error("Rank of probabilities must be 1 or 2, but is "+s);e=e||Math.random();var o=s===1?V(r,[1,-1]):r,l=z.runKernelFunc(function(u){return u.multinomial(o,i,t,e)},{logits2D:o});return s===1?V(l,[l.size]):l}var xN=U({multinomial_:NN});function CN(n,t){var e,i=O(n,"a","notEqual"),r=O(t,"b","notEqual");e=rt(i,r),i=e[0],r=e[1],Qe(i.shape,r.shape);var a=function(o){return o.notEqual(i,r)},s={a:i,b:r};return z.runKernelFunc(a,s,null,pf)}var Us=U({notEqual_:CN});function RN(n){var t=O(n,"input","real"),e=function(r){return r.real(t)},i={input:t};return z.runKernelFunc(e,i,null,bf)}var La=U({real_:RN});function ON(n){var t=O(n,"x","onesLike"),e=function(r,a){if(t.dtype==="complex64"){var s=Dc(La(t)),o=Ee(Os(t));return ei(s,o)}return r.onesLike(t)},i={x:t};return z.runKernelFunc(e,i,null,Jl)}var Dc=U({onesLike_:ON});function EN(n,t){var e=O(n,"v1","outerProduct"),i=O(t,"v2","outerProduct");D(e.rank===1&&i.rank===1,function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+(e.rank+" and "+i.rank+".")});var r=V(e,[-1,1]),a=V(i,[1,-1]);return Fe(r,a)}var DN=U({outerProduct_:EN});function kN(n,t,e){e===void 0&&(e=0);var i=O(n,"x","pad");if(i.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var r=function(o,l){return l([i]),o.pad(i,t,e)},a={paddings:t,constantValue:e},s={x:i};return z.runKernelFunc(r,s,null,Ql,a)}var Hi=U({pad_:kN});function FN(n,t,e){return e===void 0&&(e=0),D(t.length===2,function(){return"Invalid number of paddings. Must be length of 2."}),Hi(n,[t],e)}var WN=U({pad1d_:FN});function UN(n,t,e){return e===void 0&&(e=0),D(t.length===2&&t[0].length===2&&t[1].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),Hi(n,t,e)}var BN=U({pad2d_:UN});function zN(n,t,e){return e===void 0&&(e=0),D(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),Hi(n,t,e)}var _N=U({pad3d_:zN});function PN(n,t,e){return e===void 0&&(e=0),D(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),Hi(n,t,e)}var MN=U({pad4d_:PN});function HN(n,t,e){var i=O(n,"x","spaceToBatchND");D(i.rank>=1+t.length,function(){return"input rank "+i.rank+" should be > than [blockShape] "+t.length}),D(e.length===t.length,function(){return"paddings.shape[0] "+e.length+" must be equal to [blockShape] "+t.length}),D(i.shape.reduce(function(o,l,u){return u>0&&u<=t.length?o&&(l+e[u-1][0]+e[u-1][1])%t[u-1]===0:o},!0),function(){return"input spatial dimensions "+i.shape.slice(1)+" with paddings "+e.toString()+" must be divisible by blockShapes "+t.toString()});var r=function(o){return o.spaceToBatchND(i,t,e)},a={x:i},s={blockShape:t,paddings:e};return z.runKernelFunc(r,a,null,Su,s)}var Bs=U({spaceToBatchND_:HN});function GN(n,t,e,i,r,a){r==null&&(r=[1,1]),a==null&&(a=1),i===0&&(i="valid");var s=O(n,"x","maxPool"),o=s,l=!1;s.rank===3&&(l=!0,o=V(s,[1,s.shape[0],s.shape[1],s.shape[2]])),D(Bt(a,r),function(){return"Error in pool: Either strides or dilations must be 1. "+("Got strides "+a+" and dilations '"+r+"'")});var u=Ar(o.shape,t,a,r,i),c=[u.dilationHeight,u.dilationWidth],h;i==="same"?h=qN([u.filterHeight,u.filterWidth],c):h=[[0,0],[0,0]];var d=c[0]===1&&c[1]===1,p=VN([u.inHeight,u.inWidth],c,h),f=p[0],m=p[1],g=d?i:"valid",v=d?o:Bs(o,c,f),b=e==="avg"?function(){return bc(v,t,a,g)}:function(){return Oc(v,t,a,g)},S=b(),L=d?S:As(S,c,m);return l?V(L,[L.shape[1],L.shape[2],L.shape[3]]):L}function VN(n,t,e){var i=e.map(function(c){return c[0]}),r=e.map(function(c){return c[1]}),a=n.concat(i,r),s=t.map(function(c,h){return(c-a[h]%c)%c}),o=r.map(function(c,h){return c+s[h]}),l=t.map(function(c,h){return[i[h],o[h]]}),u=t.map(function(c,h){return[0,s[h]]});return[l,u]}function qN(n,t){var e=n.map(function(s,o){return s+(s-1)*(t[o]-1)}),i=e.map(function(s){return s-1}),r=i.map(function(s){return Math.floor(s/2)}),a=i.map(function(s,o){return s-r[o]});return i.map(function(s,o){return[r[o],a[o]]})}var vg=U({pool_:GN});function YN(n,t){var e,i=O(n,"base","pow"),r=O(t,"exp","pow");e=rt(i,r),i=e[0],r=e[1];var a={a:i,b:r},s=function(o,l){var u=o.pow(i,r);return l([i,r,u]),u};return z.runKernelFunc(s,a,null,eu)}var Hn=U({pow_:YN});function KN(n,t){var e=O(n,"x","prelu"),i=O(t,"alpha","prelu"),r=function(s,o){var l=s.prelu(e,i);return o([e,i]),l},a={x:e,alpha:i};return z.runKernelFunc(r,a,null,tu)}var kc=U({prelu_:KN});function jN(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var i=O(n,"x","prod"),r=function(o){i.dtype==="bool"&&(i=ue(i,"int32"));var l=Ze(t,i.shape),u=Qt(l,i.rank),c=l,h=i;u!=null&&(h=lt(i,u),c=Nn(c.length,i.rank));var d=o.prod(h,c);if(e){var p=Zt(d.shape,l);d=V(d,p)}return d},a={x:i},s={axis:t,keepDims:e};return z.runKernelFunc(r,a,null,vf,s)}var yg=U({prod_:jN});function $N(n,t,e){var i=st(n),r=null;if(e==null||e==="float32")r=new Float32Array(i);else if(e==="int32")r=new Int32Array(i);else if(e==="bool")r=new Uint8Array(i);else throw new Error("Unknown data type "+e);for(var a=0;a>>0,d-=l,d*=l,l=d>>>0,d-=l,l+=d*4294967296}return(l>>>0)*23283064365386963e-26};return u}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.alea=s})(Or,n,!1)}),ZN=Vi(function(n){(function(t,e,i){function r(o){var l=this,u="";l.x=0,l.y=0,l.z=0,l.w=0,l.next=function(){var h=l.x^l.x<<11;return l.x=l.y,l.y=l.z,l.z=l.w,l.w^=l.w>>>19^h^h>>>8},o===(o|0)?l.x=o:u+=o;for(var c=0;c>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.xor128=s})(Or,n,!1)}),QN=Vi(function(n){(function(t,e,i){function r(o){var l=this,u="";l.next=function(){var h=l.x^l.x>>>2;return l.x=l.y,l.y=l.z,l.z=l.w,l.w=l.v,(l.d=l.d+362437|0)+(l.v=l.v^l.v<<4^(h^h<<1))|0},l.x=0,l.y=0,l.z=0,l.w=0,l.v=0,o===(o|0)?l.x=o:u+=o;for(var c=0;c>>4),l.next()}function a(o,l){return l.x=o.x,l.y=o.y,l.z=o.z,l.w=o.w,l.v=o.v,l.d=o.d,l}function s(o,l){var u=new r(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.xorwow=s})(Or,n,!1)}),ex=Vi(function(n){(function(t,e,i){function r(o){var l=this;l.next=function(){var c=l.x,h=l.i,d,p;return d=c[h],d^=d>>>7,p=d^d<<24,d=c[h+1&7],p^=d^d>>>10,d=c[h+3&7],p^=d^d>>>3,d=c[h+4&7],p^=d^d<<7,d=c[h+7&7],d=d^d<<13,p^=d^d<<9,c[h]=p,l.i=h+1&7,p};function u(c,h){var d,p,f=[];if(h===(h|0))p=f[0]=h;else for(h=""+h,d=0;d0;--d)c.next()}u(l,o)}function a(o,l){return l.x=o.x.slice(),l.i=o.i,l}function s(o,l){o==null&&(o=+new Date);var u=new r(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(c.x&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.xorshift7=s})(Or,n,!1)}),tx=Vi(function(n){(function(t,e,i){function r(o){var l=this;l.next=function(){var c=l.w,h=l.X,d=l.i,p,f;return l.w=c=c+1640531527|0,f=h[d+34&127],p=h[d=d+1&127],f^=f<<13,p^=p<<17,f^=f>>>15,p^=p>>>12,f=h[d]=f^p,l.i=d,f+(c^c>>>16)|0};function u(c,h){var d,p,f,m,g,v=[],b=128;for(h===(h|0)?(p=h,h=null):(h=h+"\0",p=0,b=Math.max(b,h.length)),f=0,m=-32;m>>15,p^=p<<4,p^=p>>>13,m>=0&&(g=g+1640531527|0,d=v[m&127]^=p+g,f=d==0?f+1:0);for(f>=128&&(v[(h&&h.length||0)&127]=-1),f=127,m=4*128;m>0;--m)p=v[f+34&127],d=v[f=f+1&127],p^=p<<13,d^=d<<17,p^=p>>>15,d^=d>>>12,v[f]=p^d;c.w=g,c.X=v,c.i=f}u(l,o)}function a(o,l){return l.i=o.i,l.w=o.w,l.X=o.X.slice(),l}function s(o,l){o==null&&(o=+new Date);var u=new r(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(c.X&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.xor4096=s})(Or,n,!1)}),nx=Vi(function(n){(function(t,e,i){function r(o){var l=this,u="";l.next=function(){var h=l.b,d=l.c,p=l.d,f=l.a;return h=h<<25^h>>>7^d,d=d-p|0,p=p<<24^p>>>8^f,f=f-h|0,l.b=h=h<<20^h>>>12^d,l.c=d=d-p|0,l.d=p<<16^d>>>16^f,l.a=f-h|0},l.a=0,l.b=0,l.c=2654435769|0,l.d=1367130551,o===Math.floor(o)?(l.a=o/4294967296|0,l.b=o|0):u+=o;for(var c=0;c>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.tychei=s})(Or,n,!1)}),qi=Vi(function(n){(function(t,e){var i=this,r=256,a=6,s=52,o="random",l=e.pow(r,a),u=e.pow(2,s),c=u*2,h=r-1,d;function p(L,w,N){var I=[];w=w==!0?{entropy:!0}:w||{};var C=v(g(w.entropy?[L,S(t)]:L??b(),3),I),E=new f(I),k=function(){for(var W=E.g(a),F=l,_=0;W=c;)W/=2,F/=2,_>>>=1;return(W+_)/F};return k.int32=function(){return E.g(4)|0},k.quick=function(){return E.g(4)/4294967296},k.double=k,v(S(E.S),t),(w.pass||N||function(W,F,_,H){return H&&(H.S&&m(H,E),W.state=function(){return m(E,{})}),_?(e[o]=W,F):W})(k,C,"global"in w?w.global:this==e,w.state)}e["seed"+o]=p;function f(L){var w,N=L.length,I=this,C=0,E=I.i=I.j=0,k=I.S=[];for(N||(L=[N++]);C=1||o===0);var l=Math.sqrt(-2*Math.log(o)/o);e=this.mean+this.stdDev*a*l,i=this.mean+this.stdDev*s*l,(!this.truncated||this.isValidTruncated(e))&&(r=!0)}return(!this.truncated||this.isValidTruncated(i))&&(this.nextVal=this.convertValue(i)),this.convertValue(e)},n.prototype.convertValue=function(t){return this.dtype==null||this.dtype==="float32"?t:Math.round(t)},n.prototype.isValidTruncated=function(t){return t<=this.upper&&t>=this.lower},n}(),rx=function(){function n(t,e,i,r){this.alpha=t,this.beta=1/e,this.dtype=i;var a=r||Math.random();this.randu=Fc(a.toString()),this.randn=new Wc(0,1,i,!1,this.randu()),t<1?this.d=t+2/3:this.d=t-1/3,this.c=1/Math.sqrt(9*this.d)}return n.prototype.nextValue=function(){for(var t,e,i,r,a,s;;){do r=this.randn.nextValue(),s=1+this.c*r;while(s<=0);if(s*=s*s,t=r*r,e=1-.331*t*t,i=.5*t+this.d*(1-s+Math.log(s)),a=this.randu(),a1;if(s||o||l)return Mn([0],i);var u=Math.abs(Math.ceil((t-n)/e)),c=vr(u,i);t0?o+l:o});t[a]=n.shape[e]-s}D(n.shape[e]===t.reduce(function(o,l){return o+l}),function(){return"The sum of sizes must match the size of the axis dimension."}),i=t}return i}function qx(n,t,e){e===void 0&&(e=0);var i=O(n,"x","split"),r=function(o,l){var u=Ze(e,i.shape)[0],c=Ng(i,t,u);return o.split(i,c,u)},a={x:i},s={numOrSizeSplits:t,axis:e};return z.runKernelFunc(r,a,null,Lu,s)}var Dr=U({split_:qx});function Gx(n,t){D(n.dtype==="float32",function(){return"The dtype for rfft() must be real value but got "+n.dtype});var e=n.shape[n.shape.length-1],i=n.size/e,r;if(t!=null&&te){var o=n.shape.map(function(v){return v});o[n.shape.length-1]=t-e,r=xt([n,Mn(o)],n.shape.length-1),e=t}else r=n;var l=Ee(r),u=V(ei(r,l),[i,e]),c=zs(u),h=Math.floor(e/2)+1,d=La(c),p=Os(c),f=Dr(d,[h,e-h],d.shape.length-1),m=Dr(p,[h,e-h],p.shape.length-1),g=r.shape.slice();return g[r.shape.length-1]=h,V(ei(f[0],m[0]),g)}var _s=U({rfft_:Gx});function Yx(n){var t=O(n,"x","sqrt"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.sqrt(t);return r([t]),a},e,null,bu)}var zt=U({sqrt_:Yx});function Kx(n,t){var e,i=O(n,"a","squaredDifference"),r=O(t,"b","squaredDifference");e=rt(i,r),i=e[0],r=e[1],Qe(i.shape,r.shape);var a=function(l,u){var c=l.squaredDifference(i,r);return u([i,r]),c},s={a:i,b:r},o={};return z.runKernelFunc(a,s,null,Au,o)}var Ps=U({squaredDifference_:Kx});function jx(n,t){var e=O(n,"x","squeeze");return V(e,kf(e.shape,t).newShape)}var Ms=U({squeeze_:jx});function $x(n,t){t===void 0&&(t=0);var e=pa(n,"tensors","stack");if(D(e.length>=1,function(){return"Pass at least one tensor to tf.stack"}),e.length===1)return hn(e[0],t);var i=e[0].rank,r=e[0].shape,a=e[0].dtype;D(t<=i,function(){return"Axis must be <= rank of the tensor"}),e.forEach(function(o){Ue(r,o.shape,"All tensors passed to stack must have matching shapes"),D(a===o.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var s=e.map(function(o){return hn(o,t)});return xt(s,t)}var Gi=U({stack_:$x});function Xx(n,t){t===void 0&&(t=0);var e=O(n,"x","step"),i={x:e},r={alpha:t};return z.runKernelFunc(function(a){return a.step(e,t)},i,null,ku,r)}var kr=U({step_:Xx});function Jx(n,t,e,i,r,a,s,o,l){r===void 0&&(r=0),a===void 0&&(a=0),s===void 0&&(s=0),o===void 0&&(o=0),l===void 0&&(l=0);var u=O(n,"x","stridedSlice"),c=function(p){i==null&&(i=new Array(t.length));var f=ws(s);if(f.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(s!==0&&o!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(s!==0&&l!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");var m=u.rank-t.length,g=ws(o),v=u.shape.slice();g.forEach(function(W){t[W]=0,e[W]=1,v.splice(W,0,1)}),u=V(u,v);var b=Cm(u.shape,f,m,t,e,i,r,a,s),S=b.begin,L=b.end,w=b.strides;t=S,e=L,i=w;var N=ws(l);N.forEach(function(W){e[W]=t[W]+1,i[W]=1});var I=bm(t,e,i),C=I.filter(function(W,F){return N.indexOf(F)===-1}),E=i.every(function(W){return W===1});if(E)return V(Be(u,t,I),C);var k=p.stridedSlice(u,t,e,i);return V(k,C)},h={x:u},d={begin:t,end:e,strides:i,beginMask:r,endMask:a,ellipsisMask:s,newAxisMask:o,shrinkAxisMask:l};return z.runKernelFunc(c,h,null,Tf,d)}var xg=U({stridedSlice_:Jx});function Zx(n){var t=O(n,"x","tan"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.tan(t);return r([t]),a},e,null,Nu)}var Cg=U({tan_:Zx});function Ta(n,t,e){if(Ei(n),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");var i=An(n,e);if(i.length!==2&&i.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(i.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return ti(n,t,i,e)}function Qx(n,t,e){if(Ei(n),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");var i=An(n,e);if(i.length!==4&&i.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(i.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return ti(n,t,i,e)}function eC(n,t,e){if(Ei(n),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");var i=An(n,e);if(i.length!==5&&i.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(i.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return ti(n,t,i,e)}function tC(n,t,e){if(Ei(n),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");var i=An(n,e);if(i.length!==6&&i.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(i.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||i,ti(n,t,i,e)}function nC(n,t,e){t===void 0&&(t=1),e===void 0&&(e=!0);var i=O(n,"x","topk");if(i.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");var r=i.shape[i.shape.length-1];if(t>r)throw new Error("'k' passed to topk() must be <= the last dimension ("+r+") "+("but got "+t));var a={x:i},s={k:t,sorted:e},o=z.runKernelFunc(function(c){return c.topk(i,t,e)},a,null,Nf,s),l=o[0],u=o[1];return{values:l,indices:u}}var Rg=U({topk_:nC});function iC(n,t,e,i,r){if(t===void 0&&(t=0),e===void 0&&(e=1),i!=null&&i==="bool")throw new Error("Unsupported data type $ { dtype }");for(var a=new Wc(t,e,i,!0,r),s=Tn(n,i),o=0;o0,function(){return"The input tensor must be at least 1D"});var i={x:e},r={axis:t},a=z.runKernel(xf,i,r),s=a[0],o=a[1];return{values:s,indices:o}}var Og=U({unique_:aC});function sC(n,t,e){var i=O(n,"x","unsortedSegmentSum"),r=O(t,"segmentIds","unsortedSegmentSum","int32");D(it(e),function(){return"numSegments must be of dtype int"});var a={x:i,segmentIds:r},s={numSegments:e},o=function(l,u){var c=l.unsortedSegmentSum(i,r,e);return u([r]),c};return z.runKernelFunc(o,a,null,Eu,s)}var Hc=U({unsortedSegmentSum_:sC});function oC(n,t){t===void 0&&(t=0);var e=O(n,"x","unstack");D(t>=-e.shape.length&&t0,function(){return"mask cannot be scalar"}),Ue(o.slice(a,a+s),r.shape,"mask's shape must match the first K dimensions of tensor's shape,"),l=1,u=a;u2)throw new Error("sparseIndices should be a scalar, vector, or matrix,"+(" but got shape "+n.shape+"."));var r=n.rank>0?n.shape[0]:1,a=n.rank>1?n.shape[1]:1;if(e.length!==a)throw new Error("outputShape has incorrect number of elements:,"+(" "+e.length+", should be: "+a+"."));var s=t.size;if(!(t.rank===0||t.rank===1&&s===r))throw new Error("sparseValues has incorrect shape "+(t.shape+", should be [] or ["+r+"]"));if(t.dtype!==i.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function kC(n,t,e,i){i===void 0&&(i=0);var r=O(n,"sparseIndices","sparseToDense","int32"),a=O(t,"sparseValues","sparseToDense"),s=O(i,"defaultValue","sparseToDense",a.dtype);DC(r,a,e,s);var o={sparseIndices:r,sparseValues:a,defaultValue:s},l={outputShape:e};return z.runKernelFunc(function(u){return u.sparseToDense(r,a,e,s)},o,null,Af,l)}var FC=U({sparseToDense_:kC});function WC(n,t){var e=O(t,"indices","gatherND","int32"),i=O(n,"x","gatherND"),r=function(s){return s.gatherND(i,e)},a={params:i,indices:e};return z.runKernelFunc(r,a,null,Zp)}var UC=U({gatherND_:WC});function BC(n,t){if(t==null)return n.shape.slice();if(an(n.shape,t))return t;if(n.shape.length===t.length){for(var e=[],i=0;i=0&&t<1,function(){return"rate must be a float in the range [0, 1), but got "+t+"."}),t===0)return n instanceof Y?r.clone():r;var a=BC(r,e),s=1-t,o=Ie(Cs(fe(bg(a,0,1,"float32",i),s)),s);return J(r,o)}var _C=U({dropout_:zC});function $g(n){return Math.floor(Math.pow(2,Math.ceil(Math.log(n)/Math.log(2))))}function Vc(n,t,e){for(var i=1-n%2,r=new Float32Array(n),a=0;a1,function(){return"inTopK() expects the predictions to be of rank 2 or higher, "+("but got "+i.rank)}),D(i.rank-1===r.rank,function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+(i.rank+" and targets rank "+r.rank)}),Ue(i.shape.slice(0,i.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),a=i.shape[i.shape.length-1],D(e>0&&e<=a,function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last "+("dimension ("+a+"), but got "+e)}),[4,i.data()];case 1:return s=v.sent(),[4,r.data()];case 2:for(o=v.sent(),l=[s.length/a,a],u=l[0],c=l[1],h=cs("bool",u),d=0;d0&&(e=Ae(e,i)),V(e,n.shape)}function Ys(n,t,e){if(t==="linear")return n;if(t==="relu")return Ia(n);if(t==="elu")return Ic(n);if(t==="relu6")return Bc(n);if(t==="prelu")return kc(n,e);throw new Error("Unknown fused activation "+t+".")}var Ks=function(n,t){var e=n>0;return!e||t==="linear"};function VC(n){var t=n.x,e=n.filter,i=n.strides,r=n.pad,a=n.dataFormat,s=a===void 0?"NHWC":a,o=n.dilations,l=o===void 0?[1,1]:o,u=n.dimRoundingMode,c=n.bias,h=n.activation,d=h===void 0?"linear":h,p=n.preluActivationWeights;if(d=d||"linear",Ks(z.state.gradientDepth,d)===!1){var f=Nr(t,e,i,r,s,l,u);return c!=null&&(f=fe(f,c)),Ys(f,d,p)}var m=O(t,"x","conv2d"),g=O(e,"filter","conv2d"),v=m,b=!1;m.rank===3&&(b=!0,v=V(m,[1,m.shape[0],m.shape[1],m.shape[2]])),D(v.rank===4,function(){return"Error in fused conv2d: input must be rank 4, but got rank "+(v.rank+".")}),D(g.rank===4,function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+(g.rank+".")}),u!=null&&D(it(r),function(){return"Error in fused conv2d: pad must be an integer when using, "+("dimRoundingMode "+u+" but got pad "+r+".")}),D(v.shape[3]===g.shape[2],function(){return"Error in conv2d: depth of input ("+v.shape[3]+") must match "+("input depth for filter "+g.shape[2]+".")}),D(Bt(i,l),function(){return"Error in conv2D: Either strides or dilations must be 1. "+("Got strides "+i+" and dilations '"+l+"'")}),D(s==="NHWC",function(){return"Error in conv2d: got dataFormat of "+s+" but only NHWC is currently supported."});var S=xn(v.shape,g.shape,i,l,r,u),L;c!=null&&(L=O(c,"bias","fused conv2d"),L=rt(L,m)[0],Qe(S.outShape,L.shape));var w;p!=null&&(w=O(p,"prelu weights","fused conv2d"));var N=function(F,_){var H=_,P=H[0],K=H[1],j=H[2],q=H[3],G=qs(F,j,d);D(si(l),function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 "+("are not yet supported in gradients. Got dilations '"+l+"'")});var Z=wc(K.shape,G,P,i,r),X=qc(K,G,P.shape,i,r),ee=[Z,X];if(q!=null){var ne=Gs(q,G);ee.push(ne)}return ee},I=function(F){var _=F.fusedConv2d({input:v,filter:g,convInfo:S,bias:L,activation:d,preluActivationWeights:w});return _},C={x:v,filter:g,bias:L,preluActivationWeights:w},E={strides:i,pad:r,dataFormat:s,dilations:l,dimRoundingMode:u,activation:d};if(c==null){var k=Cn(function(F,_,H){var P=z.runKernelFunc(I,C,null,Uu,E);return H([_,F,P]),b&&(P=V(P,[P.shape[1],P.shape[2],P.shape[3]])),{value:P,gradFunc:N}});return k(v,g)}else{var W=Cn(function(F,_,H,P){var K=z.runKernelFunc(I,C,null,Uu,E);return P([_,F,K,H]),b&&(K=V(K,[K.shape[1],K.shape[2],K.shape[3]])),{value:K,gradFunc:N}});return W(v,g,L)}}var qC=U({fusedConv2d_:VC});function GC(n,t,e,i){var r=n;n.rank===3&&(r=V(n,[1,n.shape[0],n.shape[1],n.shape[2]]));var a=t;a.rank===3&&(a=V(t,[1,t.shape[0],t.shape[1],t.shape[2]]));var s=function(l){return l.depthwiseConv2DDerFilter(r,a,i)},o={x:r,dy:a};return z.runKernelFunc(s,o,null,Hp)}var Xg=U({depthwiseConv2dNativeBackpropFilter_:GC});function YC(n,t,e,i){var r=t,a=!1;t.rank===3&&(a=!0,r=V(t,[1,t.shape[0],t.shape[1],t.shape[2]]));var s=function(u){return u.depthwiseConv2DDerInput(r,e,i)},o={dy:r},l=z.runKernelFunc(s,o,null,Vp);return a?V(l,[l.shape[1],l.shape[2],l.shape[3]]):l}var Jg=U({depthwiseConv2dNativeBackpropInput_:YC});function KC(n){var t=n.x,e=n.filter,i=n.strides,r=n.pad,a=n.dataFormat,s=a===void 0?"NHWC":a,o=n.dilations,l=o===void 0?[1,1]:o,u=n.dimRoundingMode,c=n.bias,h=n.activation,d=h===void 0?"linear":h,p=n.preluActivationWeights;if(Ks(z.state.gradientDepth,d)===!1){var f=ba(t,e,i,r,s,l,u);return c!=null&&(f=fe(f,c)),Ys(f,d,p)}var m=O(t,"x","depthwiseConv2d"),g=O(e,"filter","depthwiseConv2d"),v=m,b=!1;m.rank===3&&(b=!0,v=V(m,[1,m.shape[0],m.shape[1],m.shape[2]])),D(v.rank===4,function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got "+("rank "+v.rank+".")}),D(g.rank===4,function(){return"Error in fused depthwiseConv2d: filter must be rank 4, "+("but got rank "+g.rank+".")}),D(v.shape[3]===g.shape[2],function(){return"Error in fused depthwiseConv2d: number of input channels "+("("+v.shape[3]+") must match the inChannels dimension in ")+("filter "+g.shape[2]+".")}),l==null&&(l=[1,1]),D(Bt(i,l),function(){return"Error in fused depthwiseConv2d: Either strides or dilations must "+("be 1. Got strides "+i+" and dilations '"+l+"'")}),u!=null&&D(it(r),function(){return"Error in fused depthwiseConv2d: pad must be an integer when "+("using dimRoundingMode "+u+" but got pad "+r+".")});var S=xn(v.shape,g.shape,i,l,r,u,!0),L;c!=null&&(L=O(c,"bias","fused conv2d"),L=rt(L,m)[0],Qe(S.outShape,L.shape));var w;p!=null&&(w=O(p,"prelu weights","fused depthwiseConv2d"));var N=function(F,_){D(si(l),function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations "+("'"+l+"'")});var H=_[0],P=_[1],K=_[2],j=_[3],q=qs(F,K,d),G=Jg(P.shape,q,H,S),Z=Xg(P,q,H.shape,S);if(j!=null){var X=Gs(L,q);return[G,Z,X]}return[G,Z]},I=function(F){var _=F.fusedDepthwiseConv2D({input:v,filter:g,convInfo:S,bias:L,activation:d,preluActivationWeights:w});return _},C={x:v,filter:g,bias:L,preluActivationWeights:w},E={strides:i,pad:r,dataFormat:s,dilations:l,dimRoundingMode:u,activation:d};if(c==null){var k=Cn(function(F,_,H){var P=z.runKernelFunc(I,C,null,Bu,E);return H([_,F,P]),b&&(P=V(P,[P.shape[1],P.shape[2],P.shape[3]])),{value:P,gradFunc:N}});return k(v,g)}else{var W=Cn(function(F,_,H,P){var K=z.runKernelFunc(I,C,null,Bu,E);return P([_,F,K,H]),b&&(K=V(K,[K.shape[1],K.shape[2],K.shape[3]])),{value:K,gradFunc:N}});return W(v,g,L)}}var jC=U({fusedDepthwiseConv2d_:KC});function $C(n){var t,e=n.a,i=n.b,r=n.transposeA,a=r===void 0?!1:r,s=n.transposeB,o=s===void 0?!1:s,l=n.bias,u=n.activation,c=u===void 0?"linear":u,h=n.preluActivationWeights;if(Ks(z.state.gradientDepth,c)===!1){var d=Fe(e,i,a,o);return l!=null&&(d=fe(d,l)),Ys(d,c,h)}var p=O(e,"a","fused matMul"),f=O(i,"b","fused matMul");t=rt(p,f),p=t[0],f=t[1];var m=a?p.shape[p.rank-2]:p.shape[p.rank-1],g=o?f.shape[f.rank-1]:f.shape[f.rank-2],v=a?p.shape[p.rank-1]:p.shape[p.rank-2],b=o?f.shape[f.rank-2]:f.shape[f.rank-1],S=p.shape.slice(0,-2),L=f.shape.slice(0,-2),w=st(S),N=st(L);D(p.rank>=2&&f.rank>=2&&p.rank===f.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least "+("2, got ranks "+p.rank+" and "+f.rank+".")}),D(an(S,L),function(){return"Error in fused matMul: outer dimensions ("+S+") and ("+(L+") of Tensors with shapes "+p.shape+" and ")+(f.shape+" must match.")}),D(m===g,function(){return"Error in fused matMul: inner shapes ("+m+") and ("+(g+") of Tensors with shapes "+p.shape+" and ")+(f.shape+" and transposeA="+a)+(" and transposeB="+o+" must match.")});var I=p.shape.slice(0,-2).concat([v,b]),C=a?V(p,[w,m,v]):V(p,[w,v,m]),E=o?V(f,[N,b,g]):V(f,[N,g,b]),k;l!=null&&(k=O(l,"bias","fused matMul"),k=rt(k,p)[0],Qe(I,k.shape));var W;h!=null&&(W=O(h,"prelu weights","fused matMul"));var F=function(q,G){var Z=G[0],X=G[1],ee=G[2],ne=G[3],ie=qs(V(q,ee.shape),ee,c),te,re;if(!a&&!o?(te=Fe(ie,X,!1,!0),re=Fe(Z,ie,!0,!1)):!a&&o?(te=Fe(ie,X,!1,!1),re=Fe(ie,Z,!0,!1)):a&&!o?(te=Fe(X,ie,!1,!0),re=Fe(Z,ie,!1,!1)):(te=Fe(X,ie,!0,!0),re=Fe(ie,Z,!0,!0)),l!=null){var le=Gs(ne,ie);return[te,re,le]}else return[te,re]},_=function(q){var G=q.fusedBatchMatMul({a:C,b:E,transposeA:a,transposeB:o,bias:k,activation:c,preluActivationWeights:W});return G},H={a:C,b:E,bias:k,preluActivationWeights:W},P={transposeA:a,transposeB:o,activation:c};if(l==null){var K=Cn(function(q,G,Z){var X=z.runKernelFunc(_,H,null,Wu,P);return Z([q,G,X]),{value:V(X,I),gradFunc:F}});return K(C,E)}else{var j=Cn(function(q,G,Z,X){var ee=z.runKernelFunc(_,H,null,Wu,P);return X([q,G,ee,Z]),{value:V(ee,I),gradFunc:F}});return j(C,E,k)}}var XC=U({fusedMatMul_:$C});var JC={__proto__:null,conv2d:qC,depthwiseConv2d:jC,matMul:XC};function ZC(n){return Vc(n,.54,.46)}var QC=U({hammingWindow_:ZC});function eR(n){return Vc(n,.5,.5)}var Zg=U({hannWindow_:eR});function tR(n,t,e,i,r){i===void 0&&(i=!1),r===void 0&&(r=0);for(var a=0,s=[];a+t<=n.size;)s.push(Be(n,a,t)),a+=e;if(i)for(;a=1&&i[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+i}),D(r==="bilinear"||r==="nearest",function(){return"method must be bilinear or nearest, but was "+r});var c=function(f){return f.cropAndResize(s,o,l,i,r,a)},h={image:s,boxes:o,boxInd:l},d={method:r,extrapolationValue:a,cropSize:i},p=z.runKernelFunc(c,h,null,Pp,d);return p}var aR=U({cropAndResize_:rR});function sR(n){var t=O(n,"image","flipLeftRight","float32");D(t.rank===4,function(){return"Error in flipLeftRight: image must be rank 4,"+("but got rank "+t.rank+".")});var e={image:t},i=z.runKernel(Jp,e,{});return i}var oR=U({flipLeftRight_:sR});function lR(n,t,e,i){e===void 0&&(e=0),i===void 0&&(i=.5);var r=O(n,"image","rotateWithOffset","float32");D(r.rank===4,function(){return"Error in rotateWithOffset: image must be rank 4,"+("but got rank "+r.rank+".")});var a={image:r},s={radians:t,fillValue:e,center:i},o=z.runKernel(Cf,a,s);return o}var uR=U({rotateWithOffset_:lR});function Fr(n,t,e,i,r,a){i==null&&(i=.5),r==null&&(r=Number.NEGATIVE_INFINITY),a==null&&(a=0);var s=n.shape[0];return e=Math.min(e,s),D(0<=i&&i<=1,function(){return"iouThreshold must be in [0, 1], but was '"+i+"'"}),D(n.rank===2,function(){return"boxes must be a 2D tensor, but was of rank '"+n.rank+"'"}),D(n.shape[1]===4,function(){return"boxes must have 4 columns, but 2nd dimension was "+n.shape[1]}),D(t.rank===1,function(){return"scores must be a 1D tensor"}),D(t.shape[0]===s,function(){return"scores has incompatible shape with boxes. Expected "+s+", "+("but was "+t.shape[0])}),D(0<=a&&a<=1,function(){return"softNmsSigma must be in [0, 1], but was '"+a+"'"}),{maxOutputSize:e,iouThreshold:i,scoreThreshold:r,softNmsSigma:a}}function cR(n,t,e,i,r){i===void 0&&(i=.5),r===void 0&&(r=Number.NEGATIVE_INFINITY);var a=O(n,"boxes","nonMaxSuppression"),s=O(t,"scores","nonMaxSuppression"),o=Fr(a,s,e,i,r);e=o.maxOutputSize,i=o.iouThreshold,r=o.scoreThreshold;var l={maxOutputSize:e,iouThreshold:i,scoreThreshold:r};return z.runKernelFunc(function(u){return u.nonMaxSuppression(a,s,e,i,r)},{boxes:a,scores:s},null,ff,l)}var hR=U({nonMaxSuppression_:cR});function pR(n,t,e){var i=dR(n,t,e),r=i<0?-(i+1):i;n.splice(r,0,t)}function dR(n,t,e){return mR(n,t,e||fR)}function fR(n,t){return n>t?1:n>>1);var o=e(t,n[a]);o>0?i=a+1:(r=a,s=!o)}return s?i:-i-1}function ev(n,t,e,i,r){return Gc(n,t,e,i,r,0).selectedIndices}function tv(n,t,e,i,r,a){return Gc(n,t,e,i,r,0,!1,a,!0)}function nv(n,t,e,i,r,a){return Gc(n,t,e,i,r,a,!0)}function Gc(n,t,e,i,r,a,s,o,l){s===void 0&&(s=!1),o===void 0&&(o=!1),l===void 0&&(l=!1);for(var u=[],c=0;cr&&u.push({score:t[c],boxIndex:c,suppressBeginIndex:0});u.sort(iv);for(var h=a>0?-.5/a:0,d=[],p=[];d.length0;){var f=u.pop(),m=f.score,g=f.boxIndex,v=f.suppressBeginIndex;if(m=v;--S){var L=gR(n,g,d[S]);if(L>=i){b=!0;break}if(f.score=f.score*vR(i,h,L),f.score<=r)break}f.suppressBeginIndex=d.length,b||(f.score===m?(d.push(g),p.push(f.score)):f.score>r&&pR(u,f,iv))}var w=d.length,N=e-w;o&&N>0&&(d.push.apply(d,new Array(N).fill(0)),p.push.apply(p,new Array(N).fill(0)));var I={selectedIndices:Er(d,"int32")};return s&&(I.selectedScores=Er(p,"float32")),l&&(I.validOutputs=we(w,"int32")),I}function gR(n,t,e){var i=n.subarray(t*4,t*4+4),r=n.subarray(e*4,e*4+4),a=Math.min(i[0],i[2]),s=Math.min(i[1],i[3]),o=Math.max(i[0],i[2]),l=Math.max(i[1],i[3]),u=Math.min(r[0],r[2]),c=Math.min(r[1],r[3]),h=Math.max(r[0],r[2]),d=Math.max(r[1],r[3]),p=(o-a)*(l-s),f=(h-u)*(d-c);if(p<=0||f<=0)return 0;var m=Math.max(a,u),g=Math.max(s,c),v=Math.min(o,h),b=Math.min(l,d),S=Math.max(v-m,0)*Math.max(b-g,0);return S/(p+f-S)}function vR(n,t,e){var i=Math.exp(t*e*e);return e<=n?i:0}function iv(n,t){return n.score-t.score||n.score===t.score&&t.boxIndex-n.boxIndex}function yR(n,t,e,i,r){return i===void 0&&(i=.5),r===void 0&&(r=Number.NEGATIVE_INFINITY),de(this,void 0,void 0,function(){var a,s,o,l,u,c,h;return pe(this,function(d){switch(d.label){case 0:return a=O(n,"boxes","nonMaxSuppressionAsync"),s=O(t,"scores","nonMaxSuppressionAsync"),o=Fr(a,s,e,i,r),e=o.maxOutputSize,i=o.iouThreshold,r=o.scoreThreshold,[4,Promise.all([a.data(),s.data()])];case 1:return l=d.sent(),u=l[0],c=l[1],h=ev(u,c,e,i,r),a!==n&&a.dispose(),s!==t&&s.dispose(),[2,h]}})})}var bR=yR;function wR(n,t,e,i,r,a){i===void 0&&(i=.5),r===void 0&&(r=Number.NEGATIVE_INFINITY),a===void 0&&(a=0);var s=O(n,"boxes","nonMaxSuppression"),o=O(t,"scores","nonMaxSuppression"),l=Fr(s,o,e,i,r,a);e=l.maxOutputSize,i=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;var u={boxes:s,scores:o},c={maxOutputSize:e,iouThreshold:i,scoreThreshold:r,softNmsSigma:a},h=z.runKernel(gf,u,c);return{selectedIndices:h[0],selectedScores:h[1]}}var SR=U({nonMaxSuppressionWithScore_:wR});function LR(n,t,e,i,r,a){return i===void 0&&(i=.5),r===void 0&&(r=Number.NEGATIVE_INFINITY),a===void 0&&(a=0),de(this,void 0,void 0,function(){var s,o,l,u,c,h,d;return pe(this,function(p){switch(p.label){case 0:return s=O(n,"boxes","nonMaxSuppressionAsync"),o=O(t,"scores","nonMaxSuppressionAsync"),l=Fr(s,o,e,i,r,a),e=l.maxOutputSize,i=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma,[4,Promise.all([s.data(),o.data()])];case 1:return u=p.sent(),c=u[0],h=u[1],d=nv(c,h,e,i,r,a),s!==n&&s.dispose(),o!==t&&o.dispose(),[2,d]}})})}var IR=LR;function AR(n,t,e,i,r,a){i===void 0&&(i=.5),r===void 0&&(r=Number.NEGATIVE_INFINITY),a===void 0&&(a=!1);var s=O(n,"boxes","nonMaxSuppression"),o=O(t,"scores","nonMaxSuppression"),l=Fr(s,o,e,i,r,null),u=l.maxOutputSize,c=l.iouThreshold,h=l.scoreThreshold,d={boxes:s,scores:o},p={maxOutputSize:u,iouThreshold:c,scoreThreshold:h,padToMaxOutputSize:a},f=z.runKernel(mf,d,p);return{selectedIndices:f[0],validOutputs:f[1]}}var TR=U({nonMaxSuppressionPadded_:AR});function NR(n,t,e,i,r,a){return i===void 0&&(i=.5),r===void 0&&(r=Number.NEGATIVE_INFINITY),a===void 0&&(a=!1),de(this,void 0,void 0,function(){var s,o,l,u,c,h,d,p,f,m;return pe(this,function(g){switch(g.label){case 0:return s=O(n,"boxes","nonMaxSuppressionAsync"),o=O(t,"scores","nonMaxSuppressionAsync"),l=Fr(s,o,e,i,r,null),u=l.maxOutputSize,c=l.iouThreshold,h=l.scoreThreshold,[4,Promise.all([s.data(),o.data()])];case 1:return d=g.sent(),p=d[0],f=d[1],m=tv(p,f,u,c,h,a),s!==n&&s.dispose(),o!==t&&o.dispose(),[2,m]}})})}var xR=NR;function CR(n,t,e){e===void 0&&(e=!1);var i=O(n,"images","resizeBilinear");D(i.rank===3||i.rank===4,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got "+("rank "+i.rank+".")}),D(t.length===2,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+(t+".")});var r=i,a=!1;i.rank===3&&(a=!0,r=V(i,[1,i.shape[0],i.shape[1],i.shape[2]]));var s=t[0],o=t[1],l=function(d,p){return p([r]),d.resizeBilinear(r,s,o,e)},u={images:r},c={alignCorners:e,size:t},h=z.runKernelFunc(l,u,null,su,c);return a?V(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var rv=U({resizeBilinear_:CR});function RR(n,t,e){e===void 0&&(e=!1);var i=O(n,"images","resizeNearestNeighbor");D(i.rank===3||i.rank===4,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got "+("rank "+i.rank+".")}),D(t.length===2,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+(t+".")}),D(i.dtype==="float32"||i.dtype==="int32",function(){return"`images` must have `int32` or `float32` as dtype"});var r=i,a=!1;i.rank===3&&(a=!0,r=V(i,[1,i.shape[0],i.shape[1],i.shape[2]]));var s=t[0],o=t[1],l={images:r},u={alignCorners:e,size:t},c=function(d,p){return p([r]),d.resizeNearestNeighbor(r,s,o,e)},h=z.runKernelFunc(c,l,null,au,u);return a?V(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var av=U({resizeNearestNeighbor_:RR});function OR(n,t,e){D(t%1===0,function(){return"bandPart(): numLower must be an integer, got "+t+"."}),D(e%1===0,function(){return"bandPart(): numUpper must be an integer, got "+e+"."});var i=O(n,"a","bandPart");D(i.rank>=2,function(){return"bandPart(): Rank must be at least 2, got "+i.rank+"."});var r=i.shape,a=i.shape.slice(-2),s=a[0],o=a[1];if(!(t<=s))throw new Error("bandPart(): numLower ("+t+")"+(" must not be greater than the number of rows ("+s+")."));if(!(e<=o))throw new Error("bandPart(): numUpper ("+e+")"+(" must not be greater than the number of columns ("+o+")."));t<0&&(t=s),e<0&&(e=o);var l=V(Uc(0,s,1,"int32"),[-1,1]),u=Uc(0,o,1,"int32"),c=ge(l,u),h=Mi(zi(c,we(+t,"int32")),Bi(c,we(-e,"int32"))),d=Mn([s,o],i.dtype);return V(Gi(Hs(V(i,[-1,s,o])).map(function(p){return un(h,p,d)})),r)}var ER=U({bandPart_:OR});function DR(n){var t;if(Array.isArray(n)){t=!1,D(n!=null&&n.length>0,function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"});for(var e=n[0].shape[0],i=function(l){D(n[l].shape[0]===e,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: "+("("+n[l].shape[0]+" vs. "+e+")")})},r=1;r0)for(var c=0;c=2,function(){return"qr() requires input tensor to have a rank >= 2, but got rank "+n.rank}),n.rank===2)return sv(n,t);var e=n.shape.slice(0,n.shape.length-2).reduce(function(l,u){return l*u}),i=Hs(V(n,[e,n.shape[n.shape.length-2],n.shape[n.shape.length-1]]),0),r=[],a=[];i.forEach(function(l){var u=sv(l,t),c=u[0],h=u[1];r.push(c),a.push(h)});var s=V(Gi(r,0),n.shape),o=V(Gi(a,0),n.shape);return[s,o]}function sv(n,t){return t===void 0&&(t=!1),z.tidy(function(){D(n.shape.length===2,function(){return"qr2d() requires a 2D Tensor, but got a "+n.shape.length+"D Tensor."});for(var e=n.shape[0],i=n.shape[1],r=sg(e),a=Fi(n),s=Ta([[1]],[1,1]),o=Fi(s),l=e>=i?i:e,u=function(h){var d,p=a,f=o,m=r;d=z.tidy(function(){var g=Be(a,[h,h],[e-h,1]),v=Vs(g),b=Be(a,[h,h],[1,1]),S=un(oi(b,0),Ta([[-1]]),Ta([[1]])),L=ge(b,J(S,v)),w=Ie(g,L);w.shape[0]===1?o=Fi(s):o=xt([s,Be(w,[1,0],[w.shape[0]-1,w.shape[1]])],0);var N=gt(Ie(Fe(S,L),v)),I=Be(a,[h,0],[e-h,i]),C=J(N,o),E=lt(o);if(h===0)a=ge(I,Fe(C,Fe(E,I)));else{var k=ge(I,Fe(C,Fe(E,I)));a=xt([Be(a,[0,0],[h,i]),k],0)}var W=lt(C),F=Be(r,[0,h],[e,r.shape[1]-h]);if(h===0)r=ge(F,Fe(Fe(F,o),W));else{var _=ge(F,Fe(Fe(F,o),W));r=xt([Be(r,[0,0],[e,h]),_],1)}return[o,a,r]}),o=d[0],a=d[1],r=d[2],Ut([p,f,m])},c=0;ci&&(r=Be(r,[0,0],[e,i]),a=Be(a,[0,0],[i,i])),[r,a]})}var WR=U({qr_:FR});(function(n){n[n.NONE=0]="NONE",n[n.MEAN=1]="MEAN",n[n.SUM=2]="SUM",n[n.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(A.Reduction||(A.Reduction={}));function UR(n,t,e){e===void 0&&(e=A.Reduction.SUM_BY_NONZERO_WEIGHTS);var i=O(n,"losses","computeWeightedLoss"),r=null;t!=null&&(r=O(t,"weights","computeWeightedLoss"));var a=r==null?i:J(i,r);if(e===A.Reduction.NONE)return a;if(e===A.Reduction.SUM)return Ae(a);if(e===A.Reduction.MEAN){if(r==null)return Sa(a);var s=i.size/r.size,o=Ie(Ae(a),Ae(r));return s>1?Ie(o,we(s)):o}if(e===A.Reduction.SUM_BY_NONZERO_WEIGHTS){if(r==null)return Ie(Ae(a),we(i.size));var l=J(r,Rr(i.shape)),u=ue(Ae(Us(l,we(0))),"float32");return Ie(Ae(a),u)}throw Error("Unknown reduction: "+e)}var qn=U({computeWeightedLoss_:UR});function BR(n,t,e,i){i===void 0&&(i=A.Reduction.SUM_BY_NONZERO_WEIGHTS);var r=O(n,"labels","absoluteDifference"),a=O(t,"predictions","absoluteDifference"),s=null;e!=null&&(s=O(e,"weights","absoluteDifference")),Ue(r.shape,a.shape,"Error in absoluteDifference: ");var o=Vt(ge(r,a));return qn(o,s,i)}var zR=U({absoluteDifference_:BR});function _R(n,t,e,i,r){r===void 0&&(r=A.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=O(n,"labels","cosineDistance"),s=O(t,"predictions","cosineDistance"),o=null;i!=null&&(o=O(i,"weights","cosineDistance")),Ue(a.shape,s.shape,"Error in cosineDistance: ");var l=we(1),u=ge(l,Ae(J(a,s),e,!0));return qn(u,o,r)}var PR=U({cosineDistance_:_R});function MR(n,t,e,i){i===void 0&&(i=A.Reduction.SUM_BY_NONZERO_WEIGHTS);var r=O(n,"labels","hingeLoss"),a=O(t,"predictions","hingeLoss"),s=null;e!=null&&(s=O(e,"weights","hingeLoss")),Ue(r.shape,a.shape,"Error in hingeLoss: ");var o=we(1);r=ge(J(we(2),r),o);var l=Ia(ge(o,J(r,a)));return qn(l,s,i)}var HR=U({hingeLoss_:MR});function VR(n,t,e,i,r){i===void 0&&(i=1),r===void 0&&(r=A.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=O(n,"labels","huberLoss"),s=O(t,"predictions","huberLoss"),o=null;e!=null&&(o=O(e,"weights","huberLoss")),Ue(a.shape,s.shape,"Error in huberLoss: ");var l=we(i),u=Vt(ge(s,a)),c=Ws(u,l),h=ge(u,c),d=fe(J(we(.5),qe(c)),J(l,h));return qn(d,o,r)}var qR=U({huberLoss_:VR});function GR(n,t,e,i,r){i===void 0&&(i=1e-7),r===void 0&&(r=A.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=O(n,"labels","logLoss"),s=O(t,"predictions","logLoss"),o=null;e!=null&&(o=O(e,"weights","logLoss")),Ue(a.shape,s.shape,"Error in logLoss: ");var l=we(1),u=we(i),c=gt(J(a,_i(fe(s,u)))),h=J(ge(l,a),_i(fe(ge(l,s),u))),d=ge(c,h);return qn(d,o,r)}var YR=U({logLoss_:GR});function KR(n,t,e,i){i===void 0&&(i=A.Reduction.SUM_BY_NONZERO_WEIGHTS);var r=O(n,"labels","meanSquaredError"),a=O(t,"predictions","meanSquaredError"),s=null;e!=null&&(s=O(e,"weights","meanSquaredError")),Ue(r.shape,a.shape,"Error in meanSquaredError: ");var o=Ps(r,a);return qn(o,s,i)}var jR=U({meanSquaredError_:KR});function $R(n,t){var e=O(n,"labels","sigmoidCrossEntropyWithLogits"),i=O(t,"logits","sigmoidCrossEntropyWithLogits");Ue(e.shape,i.shape,"Error in sigmoidCrossEntropyWithLogits: ");var r=Ia(i),a=J(i,e),s=Nc(cn(gt(Vt(i))));return fe(ge(r,a),s)}function XR(n,t,e,i,r){i===void 0&&(i=0),r===void 0&&(r=A.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=O(n,"multiClassLabels","sigmoidCrossEntropy"),s=O(t,"logits","sigmoidCrossEntropy"),o=null;if(e!=null&&(o=O(e,"weights","sigmoidCrossEntropy")),Ue(a.shape,s.shape,"Error in sigmoidCrossEntropy: "),i>0){var l=we(i),u=we(1),c=we(.5);a=fe(J(a,ge(u,l)),J(c,l))}var h=$R(a,s);return qn(h,o,r)}var JR=U({sigmoidCrossEntropy_:XR});function ZR(n,t,e){if(e===void 0&&(e=-1),e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet "+("supported. Labels / logits was rank "+t.rank+" ")+("and dim was "+e));var i=Cn(function(r,a,s){var o=!0,l=Cc(a,[e],o),u=ge(ue(a,"float32"),l);s([r,u]);var c=gt(J(u,r)),h=Ae(c,[e]),d=function(p,f){var m=f[0],g=f[1],v=Zt(p.shape,[e]);return[J(V(p,v),ge(ue(m,"float32"),cn(g))),J(V(p,v),ge(cn(g),ue(m,"float32")))]};return{value:h,gradFunc:d}});return i(n,t)}function QR(n,t,e,i,r){i===void 0&&(i=0),r===void 0&&(r=A.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=O(n,"onehotLabels","softmaxCrossEntropy"),s=O(t,"logits","softmaxCrossEntropy"),o=null;if(e!=null&&(o=O(e,"weights","softmaxCrossEntropy")),Ue(a.shape,s.shape,"Error in softmaxCrossEntropy: "),i>0){var l=we(i),u=we(1),c=we(a.shape[1]);a=fe(J(a,ge(u,l)),Ie(l,c))}var h=ZR(a,s);return qn(h,o,r)}var eO=U({softmaxCrossEntropy_:QR});var tO={fft:zs,ifft:Aa,rfft:_s,irfft:Mc},nO={hammingWindow:QC,hannWindow:Zg,frame:Qg,stft:iR},iO={flipLeftRight:oR,resizeNearestNeighbor:av,resizeBilinear:rv,rotateWithOffset:uR,cropAndResize:aR,nonMaxSuppression:hR,nonMaxSuppressionAsync:bR,nonMaxSuppressionWithScore:SR,nonMaxSuppressionWithScoreAsync:IR,nonMaxSuppressionPadded:TR,nonMaxSuppressionPaddedAsync:xR},rO={bandPart:ER,gramSchmidt:kR,qr:WR},aO={absoluteDifference:zR,computeWeightedLoss:qn,cosineDistance:PR,hingeLoss:HR,huberLoss:qR,logLoss:YR,meanSquaredError:jR,sigmoidCrossEntropy:JR,softmaxCrossEntropy:eO};var li=function(n){zn(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.minimize=function(e,i,r){i===void 0&&(i=!1);var a=this.computeGradients(e,r),s=a.value,o=a.grads;if(r!=null){var l=r.map(function(u){return{name:u.name,tensor:o[u.name]}});this.applyGradients(l)}else this.applyGradients(o);return Ut(o),i?s:(s.dispose(),null)},Object.defineProperty(t.prototype,"iterations",{get:function(){return this.iterations_==null&&(this.iterations_=0),this.iterations_},enumerable:!0,configurable:!0}),t.prototype.incrementIterations=function(){this.iterations_=this.iterations+1},t.prototype.computeGradients=function(e,i){return pg(e,i)},t.prototype.dispose=function(){this.iterations_!=null&&Ut(this.iterations_)},t.prototype.saveIterations=function(){return de(this,void 0,void 0,function(){return pe(this,function(e){return this.iterations_==null&&(this.iterations_=0),[2,{name:"iter",tensor:we(this.iterations_,"int32")}]})})},t.prototype.getWeights=function(){return de(this,void 0,void 0,function(){return pe(this,function(e){throw new Error("getWeights() is not implemented for this optimizer yet.")})})},t.prototype.setWeights=function(e){return de(this,void 0,void 0,function(){return pe(this,function(i){throw new Error("setWeights() is not implemented for this optimizer class "+(""+this.getClassName()))})})},t.prototype.extractIterations=function(e){return de(this,void 0,void 0,function(){var i;return pe(this,function(r){switch(r.label){case 0:return i=this,[4,e[0].tensor.data()];case 1:return i.iterations_=r.sent()[0],[2,e.slice(1)]}})})},t}(Om);Object.defineProperty(li,Symbol.hasInstance,{value:function(n){return n.minimize!=null&&n.computeGradients!=null&&n.applyGradients!=null}});var Yc=function(n){zn(t,n);function t(e,i,r){r===void 0&&(r=null);var a=n.call(this)||this;return a.learningRate=e,a.rho=i,a.epsilon=r,a.accumulatedGrads=[],a.accumulatedUpdates=[],r==null&&(a.epsilon=z.backend.epsilon()),a}return t.prototype.applyGradients=function(e){var i=this,r=Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e);r.forEach(function(a,s){var o=z.registeredVariables[a],l=!1;i.accumulatedGrads[s]==null&&(i.accumulatedGrads[s]={originalName:a+"/accum_grad",variable:ft(function(){return Ee(o).variable(l)})}),i.accumulatedUpdates[s]==null&&(i.accumulatedUpdates[s]={originalName:a+"/accum_var",variable:ft(function(){return Ee(o).variable(l)})});var u=Array.isArray(e)?e[s].tensor:e[a];if(u==null)return;var c=i.accumulatedGrads[s].variable,h=i.accumulatedUpdates[s].variable;ft(function(){var d=fe(J(c,i.rho),J(qe(u),1-i.rho)),p=J(Ie(zt(fe(h,i.epsilon)),zt(fe(c,i.epsilon))),u),f=fe(J(h,i.rho),J(qe(p),1-i.rho));c.assign(d),h.assign(f);var m=fe(J(p,-i.learningRate),o);o.assign(m)})}),this.incrementIterations()},t.prototype.dispose=function(){this.accumulatedUpdates!=null&&(Ut(this.accumulatedGrads.map(function(e){return e.variable})),Ut(this.accumulatedUpdates.map(function(e){return e.variable})))},t.prototype.getWeights=function(){return de(this,void 0,void 0,function(){var e;return pe(this,function(i){switch(i.label){case 0:return e=this.accumulatedGrads.concat(this.accumulatedUpdates),[4,this.saveIterations()];case 1:return[2,[i.sent()].concat(e.map(function(r){return{name:r.originalName,tensor:r.variable}}))]}})})},t.prototype.setWeights=function(e){return de(this,void 0,void 0,function(){var i,r;return pe(this,function(a){switch(a.label){case 0:return[4,this.extractIterations(e)];case 1:return e=a.sent(),i=e.length/2,r=!1,this.accumulatedGrads=e.slice(0,i).map(function(s){return{originalName:s.name,variable:s.tensor.variable(r)}}),this.accumulatedUpdates=e.slice(i,i*2).map(function(s){return{originalName:s.name,variable:s.tensor.variable(r)}}),[2]}})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},t.fromConfig=function(e,i){return new e(i.learningRate,i.rho,i.epsilon)},t.className="Adadelta",t}(li);ai(Yc);var Kc=function(n){zn(t,n);function t(e,i){i===void 0&&(i=.1);var r=n.call(this)||this;return r.learningRate=e,r.initialAccumulatorValue=i,r.accumulatedGrads=[],r}return t.prototype.applyGradients=function(e){var i=this,r=Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e);r.forEach(function(a,s){var o=z.registeredVariables[a];if(i.accumulatedGrads[s]==null){var l=!1;i.accumulatedGrads[s]={originalName:a+"/accumulator",variable:ft(function(){return Ac(o.shape,i.initialAccumulatorValue).variable(l)})}}var u=Array.isArray(e)?e[s].tensor:e[a];if(u==null)return;var c=i.accumulatedGrads[s].variable;ft(function(){var h=fe(c,qe(u));c.assign(h);var d=fe(J(Ie(u,zt(fe(h,z.backend.epsilon()))),-i.learningRate),o);o.assign(d)})}),this.incrementIterations()},t.prototype.dispose=function(){this.accumulatedGrads!=null&&Ut(this.accumulatedGrads.map(function(e){return e.variable}))},t.prototype.getWeights=function(){return de(this,void 0,void 0,function(){return pe(this,function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(this.accumulatedGrads.map(function(i){return{name:i.originalName,tensor:i.variable}}))]}})})},t.prototype.setWeights=function(e){return de(this,void 0,void 0,function(){var i;return pe(this,function(r){switch(r.label){case 0:return[4,this.extractIterations(e)];case 1:return e=r.sent(),i=!1,this.accumulatedGrads=e.map(function(a){return{originalName:a.name,variable:a.tensor.variable(i)}}),[2]}})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},t.fromConfig=function(e,i){return new e(i.learningRate,i.initialAccumulatorValue)},t.className="Adagrad",t}(li);ai(Kc);var jc=function(n){zn(t,n);function t(e,i,r,a){a===void 0&&(a=null);var s=n.call(this)||this;return s.learningRate=e,s.beta1=i,s.beta2=r,s.epsilon=a,s.accumulatedFirstMoment=[],s.accumulatedSecondMoment=[],ft(function(){s.accBeta1=we(i).variable(),s.accBeta2=we(r).variable()}),a==null&&(s.epsilon=z.backend.epsilon()),s}return t.prototype.applyGradients=function(e){var i=this,r=Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e);ft(function(){var a=ge(1,i.accBeta1),s=ge(1,i.accBeta2);r.forEach(function(o,l){var u=z.registeredVariables[o],c=!1;i.accumulatedFirstMoment[l]==null&&(i.accumulatedFirstMoment[l]={originalName:o+"/m",variable:ft(function(){return Ee(u).variable(c)})}),i.accumulatedSecondMoment[l]==null&&(i.accumulatedSecondMoment[l]={originalName:o+"/v",variable:ft(function(){return Ee(u).variable(c)})});var h=Array.isArray(e)?e[l].tensor:e[o];if(h==null)return;var d=i.accumulatedFirstMoment[l].variable,p=i.accumulatedSecondMoment[l].variable,f=fe(J(d,i.beta1),J(h,1-i.beta1)),m=fe(J(p,i.beta2),J(qe(h),1-i.beta2)),g=Ie(f,a),v=Ie(m,s);d.assign(f),p.assign(m);var b=fe(J(Ie(g,fe(zt(v),i.epsilon)),-i.learningRate),u);u.assign(b)}),i.accBeta1.assign(J(i.accBeta1,i.beta1)),i.accBeta2.assign(J(i.accBeta2,i.beta2))}),this.incrementIterations()},t.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Ut(this.accumulatedFirstMoment.map(function(e){return e.variable})),this.accumulatedSecondMoment!=null&&Ut(this.accumulatedSecondMoment.map(function(e){return e.variable}))},t.prototype.getWeights=function(){return de(this,void 0,void 0,function(){var e;return pe(this,function(i){switch(i.label){case 0:return e=this.accumulatedFirstMoment.concat(this.accumulatedSecondMoment),[4,this.saveIterations()];case 1:return[2,[i.sent()].concat(e.map(function(r){return{name:r.originalName,tensor:r.variable}}))]}})})},t.prototype.setWeights=function(e){return de(this,void 0,void 0,function(){var i,r,a=this;return pe(this,function(s){switch(s.label){case 0:return[4,this.extractIterations(e)];case 1:return e=s.sent(),ft(function(){a.accBeta1.assign(Hn(a.beta1,a.iterations_+1)),a.accBeta2.assign(Hn(a.beta2,a.iterations_+1))}),i=e.length/2,r=!1,this.accumulatedFirstMoment=e.slice(0,i).map(function(o){return{originalName:o.name,variable:o.tensor.variable(r)}}),this.accumulatedSecondMoment=e.slice(i,i*2).map(function(o){return{originalName:o.name,variable:o.tensor.variable(r)}}),[2]}})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},t.fromConfig=function(e,i){return new e(i.learningRate,i.beta1,i.beta2,i.epsilon)},t.className="Adam",t}(li);ai(jc);var $c=function(n){zn(t,n);function t(e,i,r,a,s){a===void 0&&(a=null),s===void 0&&(s=0);var o=n.call(this)||this;return o.learningRate=e,o.beta1=i,o.beta2=r,o.epsilon=a,o.decay=s,o.accumulatedFirstMoment=[],o.accumulatedWeightedInfNorm=[],ft(function(){o.iteration=we(0).variable(),o.accBeta1=we(i).variable()}),a==null&&(o.epsilon=z.backend.epsilon()),o}return t.prototype.applyGradients=function(e){var i=this,r=Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e);ft(function(){var a=ge(1,i.accBeta1),s=Ie(-i.learningRate,fe(J(i.iteration,i.decay),1));r.forEach(function(o,l){var u=z.registeredVariables[o],c=!1;i.accumulatedFirstMoment[l]==null&&(i.accumulatedFirstMoment[l]={originalName:o+"/m",variable:Ee(u).variable(c)}),i.accumulatedWeightedInfNorm[l]==null&&(i.accumulatedWeightedInfNorm[l]={originalName:o+"/v",variable:Ee(u).variable(c)});var h=Array.isArray(e)?e[l].tensor:e[o];if(h==null)return;var d=i.accumulatedFirstMoment[l].variable,p=i.accumulatedWeightedInfNorm[l].variable,f=fe(J(d,i.beta1),J(h,1-i.beta1)),m=J(p,i.beta2),g=Vt(h),v=Cr(m,g);d.assign(f),p.assign(v);var b=fe(J(Ie(s,a),Ie(f,fe(v,i.epsilon))),u);u.assign(b)}),i.iteration.assign(fe(i.iteration,1)),i.accBeta1.assign(J(i.accBeta1,i.beta1))}),this.incrementIterations()},t.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Ut(this.accumulatedFirstMoment.map(function(e){return e.variable})),this.accumulatedWeightedInfNorm!=null&&Ut(this.accumulatedWeightedInfNorm.map(function(e){return e.variable}))},t.prototype.getWeights=function(){return de(this,void 0,void 0,function(){return pe(this,function(e){throw new Error("getWeights() is not implemented for Adamax yet.")})})},t.prototype.setWeights=function(e){return de(this,void 0,void 0,function(){return pe(this,function(i){throw new Error("setWeights() is not implemented for Adamax yet.")})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},t.fromConfig=function(e,i){return new e(i.learningRate,i.beta1,i.beta2,i.epsilon,i.decay)},t.className="Adamax",t}(li);ai($c);var js=function(n){zn(t,n);function t(e){var i=n.call(this)||this;return i.learningRate=e,i.setLearningRate(e),i}return t.prototype.applyGradients=function(e){var i=this,r=Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e);r.forEach(function(a,s){var o=Array.isArray(e)?e[s].tensor:e[a];if(o==null)return;var l=z.registeredVariables[a];ft(function(){var u=fe(J(i.c,o),l);l.assign(u)})}),this.incrementIterations()},t.prototype.setLearningRate=function(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=km(we(-e))},t.prototype.dispose=function(){this.c.dispose()},t.prototype.getWeights=function(){return de(this,void 0,void 0,function(){return pe(this,function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()]]}})})},t.prototype.setWeights=function(e){return de(this,void 0,void 0,function(){return pe(this,function(i){switch(i.label){case 0:return[4,this.extractIterations(e)];case 1:if(e=i.sent(),e.length!==0)throw new Error("SGD optimizer does not have settable weights.");return[2]}})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate}},t.fromConfig=function(e,i){return new e(i.learningRate)},t.className="SGD",t}(li);ai(js);var Xc=function(n){zn(t,n);function t(e,i,r){r===void 0&&(r=!1);var a=n.call(this,e)||this;return a.learningRate=e,a.momentum=i,a.useNesterov=r,a.accumulations=[],a.m=we(a.momentum),a}return t.prototype.applyGradients=function(e){var i=this,r=Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e);r.forEach(function(a,s){var o=z.registeredVariables[a];if(i.accumulations[s]==null){var l=!1;i.accumulations[s]={originalName:a+"/momentum",variable:ft(function(){return Ee(o).variable(l)})}}var u=i.accumulations[s].variable,c=Array.isArray(e)?e[s].tensor:e[a];if(c==null)return;ft(function(){var h,d=fe(J(i.m,u),c);i.useNesterov?h=fe(J(i.c,fe(c,J(d,i.m))),o):h=fe(J(i.c,d),o),u.assign(d),o.assign(h)})}),this.incrementIterations()},t.prototype.dispose=function(){this.m.dispose(),this.accumulations!=null&&Ut(this.accumulations.map(function(e){return e.variable}))},t.prototype.setMomentum=function(e){this.momentum=e},t.prototype.getWeights=function(){return de(this,void 0,void 0,function(){return pe(this,function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(this.accumulations.map(function(i){return{name:i.originalName,tensor:i.variable}}))]}})})},t.prototype.setWeights=function(e){return de(this,void 0,void 0,function(){var i;return pe(this,function(r){switch(r.label){case 0:return[4,this.extractIterations(e)];case 1:return e=r.sent(),i=!1,this.accumulations=e.map(function(a){return{originalName:a.name,variable:a.tensor.variable(i)}}),[2]}})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},t.fromConfig=function(e,i){return new e(i.learningRate,i.momentum,i.useNesterov)},t.className="Momentum",t}(js);ai(Xc);var Jc=function(n){zn(t,n);function t(e,i,r,a,s){i===void 0&&(i=.9),r===void 0&&(r=0),a===void 0&&(a=null),s===void 0&&(s=!1);var o=n.call(this)||this;if(o.learningRate=e,o.decay=i,o.momentum=r,o.epsilon=a,o.accumulatedMeanSquares=[],o.accumulatedMoments=[],o.accumulatedMeanGrads=[],o.centered=s,a==null&&(o.epsilon=z.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.");return o}return t.prototype.applyGradients=function(e){var i=this,r=Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e);r.forEach(function(a,s){var o=z.registeredVariables[a],l=!1;i.accumulatedMeanSquares[s]==null&&(i.accumulatedMeanSquares[s]={originalName:a+"/rms",variable:ft(function(){return Ee(o).variable(l)})}),i.accumulatedMoments[s]==null&&(i.accumulatedMoments[s]={originalName:a+"/momentum",variable:ft(function(){return Ee(o).variable(l)})}),i.accumulatedMeanGrads[s]==null&&i.centered&&(i.accumulatedMeanGrads[s]={originalName:a+"/mg",variable:ft(function(){return Ee(o).variable(l)})});var u=Array.isArray(e)?e[s].tensor:e[a];if(u==null)return;var c=i.accumulatedMeanSquares[s].variable,h=i.accumulatedMoments[s].variable;ft(function(){var d=fe(J(c,i.decay),J(qe(u),1-i.decay));if(i.centered){var p=i.accumulatedMeanGrads[s].variable,f=fe(J(p,i.decay),J(u,1-i.decay)),m=Ie(J(u,i.learningRate),zt(ge(d,fe(qe(f),i.epsilon)))),g=fe(J(h,i.momentum),m);c.assign(d),p.assign(f),h.assign(g);var v=ge(o,g);o.assign(v)}else{var b=fe(J(c,i.decay),J(qe(u),1-i.decay)),g=fe(J(h,i.momentum),Ie(J(u,i.learningRate),zt(fe(b,i.epsilon))));c.assign(b),h.assign(g);var v=ge(o,g);o.assign(v)}})}),this.incrementIterations()},t.prototype.dispose=function(){this.accumulatedMeanSquares!=null&&Ut(this.accumulatedMeanSquares.map(function(e){return e.variable})),this.accumulatedMeanGrads!=null&&this.centered&&Ut(this.accumulatedMeanGrads.map(function(e){return e.variable})),this.accumulatedMoments!=null&&Ut(this.accumulatedMoments.map(function(e){return e.variable}))},t.prototype.getWeights=function(){return de(this,void 0,void 0,function(){var e;return pe(this,function(i){switch(i.label){case 0:return e=this.accumulatedMeanSquares.concat(this.accumulatedMoments),this.centered&&e.push.apply(e,this.accumulatedMeanGrads),[4,this.saveIterations()];case 1:return[2,[i.sent()].concat(e.map(function(r){return{name:r.originalName,tensor:r.variable}}))]}})})},t.prototype.setWeights=function(e){return de(this,void 0,void 0,function(){var i,r;return pe(this,function(a){switch(a.label){case 0:return[4,this.extractIterations(e)];case 1:return e=a.sent(),i=this.centered?e.length/3:e.length/2,r=!1,this.accumulatedMeanSquares=e.slice(0,i).map(function(s){return{originalName:s.name,variable:s.tensor.variable(r)}}),this.accumulatedMoments=e.slice(i,i*2).map(function(s){return{originalName:s.name,variable:s.tensor.variable(r)}}),this.centered&&(this.accumulatedMeanGrads=e.slice(i*2,i*3).map(function(s){return{originalName:s.name,variable:s.tensor.variable(r)}})),[2]}})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},t.fromConfig=function(e,i){return new e(i.learningRate,i.decay,i.momentum,i.epsilon,i.centered)},t.className="RMSProp",t}(li);ai(Jc);var Yi=function(){function n(){}return n.sgd=function(t){return new js(t)},n.momentum=function(t,e,i){return i===void 0&&(i=!1),new Xc(t,e,i)},n.rmsprop=function(t,e,i,r,a){return e===void 0&&(e=.9),i===void 0&&(i=0),r===void 0&&(r=null),a===void 0&&(a=!1),new Jc(t,e,i,r,a)},n.adam=function(t,e,i,r){return t===void 0&&(t=.001),e===void 0&&(e=.9),i===void 0&&(i=.999),r===void 0&&(r=null),new jc(t,e,i,r)},n.adadelta=function(t,e,i){return t===void 0&&(t=.001),e===void 0&&(e=.95),i===void 0&&(i=null),new Yc(t,e,i)},n.adamax=function(t,e,i,r,a){return t===void 0&&(t=.002),e===void 0&&(e=.9),i===void 0&&(i=.999),r===void 0&&(r=null),a===void 0&&(a=0),new $c(t,e,i,r,a)},n.adagrad=function(t,e){return e===void 0&&(e=.1),new Kc(t,e)},n}();var sO={sgd:Yi.sgd,momentum:Yi.momentum,adadelta:Yi.adadelta,adagrad:Yi.adagrad,rmsprop:Yi.rmsprop,adamax:Yi.adamax,adam:Yi.adam};var oO=function(){return typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:function(n){return n()}}();function lO(){return new Promise(function(n){return oO(function(){return n()})})}function uO(n,t,e){var i=e*(typeof n=="number"?n:n[0]),r=t*(typeof n=="number"?n:n[1]);return[i,r]}function cO(n,t,e,i){i===void 0&&(i=!0);var r=[];if(i)r=r.concat(t.slice(0)),r.push(n[0]/e),r=r.concat(n.slice(1));else{r=r.concat(n[0]);for(var a=t.length,s=0;s=t*2+1||r%2===1?s.push(r):a.push(r);i.push.apply(i,a),i.push(0),i.push.apply(i,s)}return i}function dO(n,t,e,i){i===void 0&&(i=!0);var r=[];i?r.push(n[0]/e):r.push(n[0]*e);for(var a=1;a0&&(o=Ae(o,l)),V(o,e.shape)},s=function(){var o=n,l=mt(i.shape,r);return l.length>0&&(o=Ae(o,l)),V(o,i.shape)};return{a,b:s}}};var VO={kernelName:el,saveAllInputs:!0,gradFunc:function(n,t){var e={};return t.forEach(function(i,r){e[r]=function(){return n.clone()}}),e}};var qO={kernelName:tl,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return Ee(e)}}}};var GO={kernelName:nl,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return Ee(e)}}}};var YO={kernelName:il,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return Ie(n,zt(ge(we(1),qe(ue(e,"float32")))))}}}};var KO={kernelName:rl,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){var i=zt(fe(we(1),qe(ue(e,"float32"))));return Ie(n,i)}}}};var jO={kernelName:ol,inputsToSave:["a","b"],gradFunc:function(n,t){var e=t[0],i=t[1],r=Qe(e.shape,i.shape),a=function(){var o=fe(qe(e),qe(i)),l=J(n,Ie(i,o)),u=mt(e.shape,r);return u.length>0&&(l=Ae(l,u)),V(l,e.shape)},s=function(){var o=fe(qe(e),qe(i)),l=gt(J(n,Ie(e,o))),u=mt(i.shape,r);return u.length>0&&(l=Ae(l,u)),V(l,i.shape)};return{a,b:s}}};var $O={kernelName:al,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return Ie(n,fe(qe(ue(e,"float32")),1))}}}};var XO={kernelName:sl,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return Ie(n,ge(we(1),qe(ue(e,"float32"))))}}}};function JO(n,t,e,i,r,a,s){r===void 0&&(r=[1,1,1]);var o=O(n,"dy","avgPool3dBackprop"),l=O(t,"input","avgPool3dBackprop"),u=o,c=l,h=!1;l.rank===4&&(h=!0,u=V(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),c=V(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),D(u.rank===5,function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+(u.rank+".")}),D(c.rank===5,function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+(c.rank+".")}),D(Bt(i,r),function(){return"Error in avgPool3dBackprop: Either strides or dilations "+("must be 1. Got strides "+i+" and dilations '"+r+"'")}),s!=null&&D(it(a),function(){return"Error in maxPool3dBackprop: pad must be an integer when "+("using, dimRoundingMode "+s+" but got pad "+a+".")});var d=function(g){var v=va(c.shape,e,i,r,a,s);return g.avgPool3dBackprop(u,c,v)},p={dy:u,input:c},f={filterSize:e,strides:i,dilations:r,pad:a,dimRoundingMode:s},m=z.runKernelFunc(d,p,null,Wp,f);return h?V(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var ZO=U({avgPool3dBackprop_:JO});var QO={kernelName:ul,inputsToSave:["x"],gradFunc:function(n,t,e){var i=t[0],r=e,a=r.filterSize,s=r.strides,o=r.dilations,l=r.pad,u=r.dimRoundingMode,c=o??[1,1,1];return{x:function(){return ZO(n,i,a,s,c,l,u)}}}};function eE(n,t,e,i,r){var a=O(n,"dy","avgPoolBackprop"),s=O(t,"input","avgPoolBackprop");D(s.rank===a.rank,function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+a.rank+")"});var o=s,l=a,u=!1;s.rank===3&&(u=!0,o=V(s,[1,s.shape[0],s.shape[1],s.shape[2]]),l=V(a,[1,a.shape[0],a.shape[1],a.shape[2]])),D(l.rank===4,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+(l.rank+".")}),D(o.rank===4,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+(o.rank+".")});var c=function(f){var m=Ar(o.shape,e,i,1,r);return f.avgPoolBackprop(l,o,m)},h={dy:l,input:o},d={filterSize:e,strides:i,pad:r},p=z.runKernelFunc(c,h,null,Fp,d);return u?V(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var tE=U({avgPoolBackprop_:eE});var nE={kernelName:ll,inputsToSave:["x"],gradFunc:function(n,t,e){var i=t[0],r=e,a=r.filterSize,s=r.strides,o=r.pad;return{x:function(){return tE(n,i,a,s,o)}}}};var iE={kernelName:cl,inputsToSave:["a","b"],gradFunc:function(n,t,e){var i=t,r=i[0],a=i[1],s=e,o=s.transposeA,l=s.transposeB;return!o&&!l?{a:function(){return Fe(n,a,!1,!0)},b:function(){return Fe(r,n,!0,!1)}}:!o&&l?{a:function(){return Fe(n,a,!1,!1)},b:function(){return Fe(n,r,!0,!1)}}:o&&!l?{a:function(){return Fe(a,n,!1,!0)},b:function(){return Fe(r,n,!1,!1)}}:{a:function(){return Fe(a,n,!0,!0)},b:function(){return Fe(n,r,!0,!0)}}}};var rE={kernelName:hl,gradFunc:function(n,t,e){var i=e,r=i.blockShape,a=i.crops;return{x:function(){return Bs(n,r,a)}}}};var aE={kernelName:dl,gradFunc:function(n,t,e){for(var i=e,r=i.inputShape,a=i.shape,s=Array.from(a),o=r.length-1;o>=0;o--)if(r[o]===a[o])s[o]=1;else if(r[o]!==1)throw new Error("broadcastTo(): ["+r+"] cannot be broadcast to ["+a+"].");for(var l=[],o=0;o1&&l.push(o);return{x:function(){return Ae(n,l,!0)}}}};var sE={kernelName:ls,gradFunc:function(n){return{x:function(){return n.clone()}}}};var oE={kernelName:pl,gradFunc:function(n){return{x:function(){return Ee(n)}}}};var lE={kernelName:fl,inputsToSave:["x"],gradFunc:function(n,t,e){var i=t[0],r=e,a=r.clipValueMin,s=r.clipValueMax;return{x:function(){return un(Mi(Bi(i,a),zi(i,s)),n,Ee(n))}}}};var uE={kernelName:ml,saveAllInputs:!0,gradFunc:function(n,t,e){var i=t.map(function(l){return l.shape}),r=e.axis,a=Ze(r,t[0].shape)[0],s=i.map(function(l){return l[a]}),o=Dr(n,s,a);return o.map(function(l){return function(){return l}})}};var cE={kernelName:gl,inputsToSave:["x","filter"],gradFunc:function(n,t,e){var i=t,r=i[0],a=i[1],s=e,o=s.dilations,l=s.strides,u=s.pad,c=s.dataFormat;return D(si(o),function(){return"Error in gradient of conv2D: dilation rates greater than 1 "+("are not yet supported in gradients. Got dilations '"+o+"'")}),{x:function(){return wc(r.shape,n,a,l,u,c)},filter:function(){return qc(r,n,a.shape,l,u,c)}}}};var hE={kernelName:vl,inputsToSave:["dy","filter"],gradFunc:function(n,t,e){var i=t,r=i[0],a=i[1],s=e,o=s.strides,l=s.pad,u=s.dataFormat,c=s.dimRoundingMode;return{dy:function(){return Nr(n,a,o,l,u,1,c)},filter:function(){return qc(n,r,a.shape,o,l,u,c)}}}};function dE(n,t,e,i,r){var a=n;n.rank===4&&(a=V(n,[1,n.shape[0],n.shape[1],n.shape[2],n.shape[3]]));var s=t;s.rank===4&&(s=V(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),D(a.rank===5,function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+(a.shape+".")}),D(s.rank===5,function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+(s.shape+".")}),D(e.length===5,function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+(e+".")}),D(a.shape[4]===e[3],function(){return"Error in conv3dDerFilter: depth of input "+a.shape[4]+") must "+("match input depth in filter ("+e[3]+".")}),D(s.shape[4]===e[4],function(){return"Error in conv3dDerFilter: depth of dy ("+s.shape[4]+") must "+("match output depth for filter ("+e[4]+").")});var o=function(c){var h=1,d=ga(a.shape,e,i,h,r);return c.conv3dDerFilter(a,s,d)},l={x:a,y:s},u={strides:i,pad:r};return z.runKernelFunc(o,l,null,zp,u)}var pE=U({conv3DBackpropFilter_:dE});var fE={kernelName:yl,inputsToSave:["x","filter"],gradFunc:function(n,t,e){var i=e,r=i.dilations,a=i.strides,s=i.pad;D(si(r),function(){return"Error in gradient of conv3D: dilation rates greater than 1 are "+("not yet supported in gradients. Got dilations '"+r+"'")});var o=t[0],l=t[1];return{x:function(){return Qm(o.shape,n,l,a,s)},filter:function(){return pE(o,n,l.shape,a,s)}}}};var mE={kernelName:bl,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return J(gt(_c(ue(e,"float32"))),n)}}}};var gE={kernelName:wl,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return J(Pc(ue(e,"float32")),n)}}}};var vE={kernelName:Sl,inputsToSave:["x"],gradFunc:function(n,t,e){var i=t[0],r=e,a=r.axis,s=r.exclusive,o=r.reverse;return{x:function(){var l=Qt([a],i.rank),u=Lc(n,a,s,!o);return l!=null&&(u=lt(u,l)),u}}}};var yE={kernelName:Ll,inputsToSave:["x","filter"],gradFunc:function(n,t,e){var i=e,r=i.dilations,a=i.strides,s=i.pad,o=i.dimRoundingMode,l=r??[1,1];D(si(l),function(){return"Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations "+("'"+l+"'")});var u=t,c=u[0],h=u[1];D(c.rank===4,function(){return"Error in gradient of depthwiseConv2dNative: input must be "+("rank 4, but got rank "+c.rank+".")}),D(h.rank===4,function(){return"Error in gradient of depthwiseConv2dNative: filter must be "+("rank 4, but got rank "+h.rank+".")}),D(c.shape[3]===h.shape[2],function(){return"Error in gradient of depthwiseConv2d: number of input "+("channels ("+c.shape[3]+") must match the inChannels dimension ")+("in filter "+h.shape[2]+".")}),D(Bt(a,l),function(){return"Error in gradient of depthwiseConv2d: Either strides or "+("dilations must be 1. Got strides "+a+" and dilations ")+("'"+l+"'.")}),o!=null&&D(it(s),function(){return"Error in depthwiseConv2d: pad must be an integer when using, "+("dimRoundingMode "+o+" but got pad "+s+".")});var d=xn(c.shape,h.shape,a,l,s,o,!0);return{x:function(){return Jg(c.shape,n,h,d)},filter:function(){return Xg(c,n,h.shape,d)}}}};var bE={kernelName:Il,inputsToSave:["x","filter"],gradFunc:function(n,t,e){var i=t,r=i[0],a=i[1],s={x:r,filter:a,dy:n},o={x:r,filter:a,dy:n};return{x:function(){return z.runKernel(Gp,s,e)},filter:function(){return z.runKernel(Yp,o,e)}}}};var wE={kernelName:Al,inputsToSave:["a","b"],gradFunc:function(n,t){var e=t[0],i=t[1],r=Qe(e.shape,i.shape),a=function(){var o=Ie(n,ue(i,"float32")),l=mt(e.shape,r);return l.length>0?V(Ae(o,l),e.shape):o},s=function(){var o=J(n,ue(e,"float32")),l=mt(i.shape,r);l.length>0&&(o=V(Ae(o,l),i.shape));var u=qe(i);return gt(Ie(o,ue(u,"float32")))};return{a,b:s}}};var SE={kernelName:Tl,outputsToSave:[!0],gradFunc:function(n,t){var e=t[0],i=function(a){return a.eluDer(n,e)},r={dy:n,y:e};return{x:function(){return z.runKernelFunc(i,r,null,Kp)}}}};var LE={kernelName:Nl,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0],i=J(cn(gt(qe(e))),2/Math.sqrt(Math.PI));return{x:function(){return J(n,i)}}}};var IE={kernelName:xl,outputsToSave:[!0],gradFunc:function(n,t){var e=t[0];return{x:function(){return J(n,e)}}}};var AE={kernelName:Cl,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return J(n,cn(e))}}}};var TE={kernelName:Rl,gradFunc:function(n){return{x:function(){return Ee(n)}}}};var NE={kernelName:Ol,inputsToSave:["a","b"],gradFunc:function(n,t){var e=t[0],i=t[1],r=Qe(e.shape,i.shape),a=function(){var o=Ie(n,ue(i,"float32")),l=mt(e.shape,r);return l.length>0?V(Ae(o,l),e.shape):o},s=function(){var o=J(n,ue(e,"float32")),l=mt(i.shape,r);l.length>0&&(o=V(Ae(o,l),i.shape));var u=qe(i);return gt(Ie(o,ue(u,"float32")))};return{a,b:s}}};var xE={kernelName:El,inputsToSave:["x","mean","variance","scale"],gradFunc:function(n,t,e){var i=e.varianceEpsilon,r=t[0],a=t[1],s=t[2],o=t[3],l=o??we(1),u=mt(a.shape,r.shape),c=[];if(a.rank===1){for(var h=0;h0?V(Ae(n,o),e.shape):n},s=function(){var o=J(n,gt(Cs(Ie(e,i)))),l=mt(i.shape,r);return l.length>0?V(Ae(o,l),i.shape):o};return{a,b:s}}};var XE={kernelName:$l,inputsToSave:["a","b"],gradFunc:function(n,t){var e=t[0],i=t[1],r=Qe(e.shape,i.shape),a=function(){var o=J(n,ue(i,"float32")),l=mt(e.shape,r);return l.length>0?V(Ae(o,l),e.shape):o},s=function(){var o=J(n,ue(e,"float32")),l=mt(i.shape,r);return l.length>0?V(Ae(o,l),i.shape):o};return{a,b:s}}};var JE={kernelName:Xl,gradFunc:function(n){return{x:function(){return gt(n)}}}};var ZE={kernelName:Zl,inputsToSave:["indices"],gradFunc:function(n,t){var e=t[0];return{indices:function(){return Mn(e.shape,"float32")}}}};var QE={kernelName:Jl,gradFunc:function(n){return{x:function(){return Ee(n)}}}};var pv={kernelName:Ql,inputsToSave:["x"],gradFunc:function(n,t,e){var i=t[0],r=e.paddings,a=r.map(function(s){return s[0]});return{x:function(){return Be(n,a,i.shape)}}}};var eD={kernelName:eu,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:function(n,t){var e=t[0],i=t[1],r=t[2],a=e,s=i,o=Qe(a.shape,s.shape),l=function(){var c=ue(s,"float32"),h=J(n,J(c,Hn(a,ge(c,we(1))))),d=mt(a.shape,o);return d.length>0&&(h=Ae(h,d)),V(h,a.shape)},u=function(){var c=oi(a,0),h=un(c,_i(a),Ee(a)),d=J(n,J(r,h)),p=mt(s.shape,o);return p.length>0&&(d=Ae(d,p)),V(d,s.shape)};return{a:l,b:u}}};var tD={kernelName:tu,inputsToSave:["x","alpha"],gradFunc:function(n,t){var e=t[0],i=t[1],r=oi(e,0);return{x:function(){return un(r,n,J(n,i))},alpha:function(){var a=un(r,Ee(n),J(n,e)),s=mt(i.shape,n.shape);return s.length>0&&(a=Ae(a,s)),V(a,i.shape)}}}};var nD={kernelName:nu,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return Ie(n,gt(qe(e)))}}}};var iD={kernelName:ou,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0],i=J(zi(e,6),kr(e));return{x:function(){return J(n,ue(i,"float32"))}}}};var rD={kernelName:iu,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return J(n,ue(kr(e),"float32"))}}}};var aD={kernelName:ru,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return V(n,e.shape)}}}};var sD={kernelName:su,inputsToSave:["images"],gradFunc:function(n,t,e){var i=t[0],r=function(o){var l=e.alignCorners;return o.resizeBilinearBackprop(n,i,l)},a={images:i},s=function(){return z.runKernelFunc(r,a,null,Sf,e)};return{images:s}}};var oD={kernelName:au,inputsToSave:["images"],gradFunc:function(n,t,e){var i=t[0],r=function(o){var l=e.alignCorners;return o.resizeNearestNeighborBackprop(n,i,l)},a={images:i},s=function(){return z.runKernelFunc(r,a,null,wf,e)};return{images:s}}};var lD={kernelName:lu,gradFunc:function(n,t,e){var i=e.dims,r=Ze(i,n.shape);return{x:function(){return Vn(n,r)}}}};var uD={kernelName:uu,gradFunc:function(n){return{x:function(){return Ee(n)}}}};var cD={kernelName:cu,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return gt(Ie(n,J(Hn(e,1.5),2)))}}}};var hD={kernelName:hu,inputsToSave:["condition"],gradFunc:function(n,t){var e=t[0];return{condition:function(){return ue(Ee(e),"float32")},t:function(){return J(n,ue(e,n.dtype))},e:function(){return J(n,ue(ks(e),n.dtype))}}}};var dD={kernelName:du,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){var i=oi(e,we(0)),r=we(ov),a=we(lv),s=J(n,a),o=J(J(n,r),cn(ue(e,"float32")));return un(i,s,o)}}}};var pD={kernelName:vu,outputsToSave:[!0],gradFunc:function(n,t){var e=t[0];return{x:function(){return J(n,J(e,ge(we(1),e)))}}}};var fD={kernelName:gu,gradFunc:function(n){return{x:function(){return Ee(n)}}}};var mD={kernelName:fu,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return J(xs(ue(e,"float32")),n)}}}};var gD={kernelName:mu,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return J(Sc(ue(e,"float32")),n)}}}};var vD={kernelName:pu,inputsToSave:["x"],gradFunc:function(n,t,e){for(var i=t[0],r=e,a=r.begin,s=r.size,o=i.shape,l=hc(i,a,s),u=l[0],c=l[1],h=[],d=0;d0&&(o=Ae(o,l)),V(o,e.shape)},s=function(){var o=n,l=mt(i.shape,r);return l.length>0&&(o=Ae(o,l)),V(gt(o),i.shape)};return{a,b:s}}};var TD={kernelName:wu,inputsToSave:["x"],gradFunc:function(n,t,e){var i=t[0],r=i.shape.slice(),a=e.axis,s=Ze(a,i.shape);s.forEach(function(u){r[u]=1});var o=V(n,r),l=J(o,Rr(i.shape,"float32"));return{x:function(){return l}}}};var ND={kernelName:Nu,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return Ie(n,qe(xs(e)))}}}};var xD={kernelName:xu,outputsToSave:[!0],gradFunc:function(n,t){var e=t[0];return{x:function(){return J(ge(we(1),qe(e)),n)}}}};var CD={kernelName:Cu,inputsToSave:["x"],gradFunc:function(n,t,e){var i=t[0],r=e.reps,a=function(){var s=Ee(i);if(i.rank===1)for(var o=0;o{"use strict";Object.defineProperty($e,"__esModule",{value:!0});var y=Ki();var Qc=function(n,t){return Qc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,i){e.__proto__=i}||function(e,i){for(var r in i)i.hasOwnProperty(r)&&(e[r]=i[r])},Qc(n,t)};function Q(n,t){Qc(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}var qt=function(){return qt=Object.assign||function(t){for(var e,i=1,r=arguments.length;i0&&a[a.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!a||u[1]>a[0]&&u[1]1&&s===1&&i.unshift(a)}return i}function mt(n,t){for(var e=[],i=0;i1)&&e.unshift(a)}return e}function Qe(n,t){for(var e=[],i=Math.max(n.length,t.length),r=0;rt||i===n?e=!0:i=ds(n,i+1);return i}function FT(n,t,e){for(var i=[],r=n.length,a=0;a0,function(){return"variableGrads() expects at least one of the input variables to "+("be trainable, but none of the "+a+" variables is ")+"trainable."});var s=!0,o=z.gradients(n,t,null,s),l=o.value,u=o.grads;D(u.some(function(h){return h!=null}),function(){return"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."}),D(l.rank===0,function(){return"The f passed in variableGrads(f) must return a scalar, but it "+("returned a rank-"+l.rank+" tensor")});var c={};return t.forEach(function(h,d){u[d]!=null&&(c[h.name]=u[d])}),r!=null&&r.forEach(function(h){return c[h.name]=null}),{value:l,grads:c}}function Cn(n){return z.customGrad(n)}function Ds(n){var t=n.filter(function(e){return e==null}).length;if(t>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that + the f you passed encloses all operations that lead from x to y.`)}function tN(n){var t=O(n,"x","neg"),e={x:t};return z.runKernelFunc(function(i){return i.neg(t)},e,null,Xl)}var gt=U({neg_:tN});function nN(n){var t=O(n,"x","softplus"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.softplus(t);return r([t]),a},e,null,yu)}var xc=U({softplus_:nN});function iN(n){var t=O(n,"x","logSigmoid"),e=Cn(function(i){var r=gt(xc(gt(i))),a=function(s){var o=J(s,Ui(gt(i)));return o};return{value:r,gradFunc:a}});return e(t)}var fg=U({logSigmoid_:iN});function rN(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var i=O(n,"x","max"),r=function(o,l){var u=Ze(t,i.shape),c=u,h=Qt(c,i.rank),d=i;h!=null&&(d=lt(i,h),c=Nn(c.length,d.rank));var p=o.max(d,c);h!=null&&d.dispose();var f=p;if(e){var m=Zt(f.shape,Ze(t,i.shape));f=V(f,m),p.dispose()}return l([i,f]),f},a={x:i},s={reductionIndices:t,keepDims:e};return z.runKernelFunc(r,a,null,Hl,s)}var Pi=U({max_:rN});function aN(n,t){var e,i=O(n,"a","sub"),r=O(t,"b","sub");e=rt(i,r),i=e[0],r=e[1];var a=function(o,l){var u=o.subtract(i,r);return l([i,r]),u},s={a:i,b:r};return z.runKernelFunc(a,s,null,Tu)}var ge=U({sub_:aN});function sN(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var i=O(n,"x","sum");i.dtype==="bool"&&(i=ue(i,"int32"));var r=function(o,l){l([i]);var u=Ze(t,i.shape),c=Qt(u,i.rank),h=u,d=i;c!=null&&(d=lt(i,c),h=Nn(h.length,i.rank));var p=o.sum(d,h);if(e){var f=Zt(p.shape,u);p=V(p,f)}return p},a={x:i},s={axis:t,keepDims:e};return z.runKernelFunc(r,a,null,wu,s)}var Ae=U({sum_:sN});function oN(n,t){t===void 0&&(t=-1);var e=O(n,"logits","logSoftmax");if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. "+("Logits was rank "+e.rank+" and axis was "+t));var i=function(s,o){var l=!0,u=Pi(n,t,!0),c=ge(n,u),h=ge(ue(c,"float32"),_i(Ae(cn(c),t,l)));return o([h]),h},r={logits:e},a={axis:t};return z.runKernelFunc(i,r,null,Pl,a)}var mg=U({logSoftmax_:oN});function lN(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var i=O(n,"x","logSumExp"),r=Ze(t,i.shape),a=Pi(i,r,!0),s=ge(i,a),o=cn(s),l=Ae(o,r),u=_i(l),c=fe(V(a,u.shape),u);if(e){var h=Zt(c.shape,r);return V(c,h)}return c}var Cc=U({logSumExp_:lN});function uN(n,t){var e=O(n,"a","logicalAnd","bool"),i=O(t,"b","logicalAnd","bool");Qe(e.shape,i.shape);var r={a:e,b:i};return z.runKernelFunc(function(a){return a.logicalAnd(e,i)},r,null,sf)}var Mi=U({logicalAnd_:uN});function cN(n){var t=O(n,"x","logicalNot","bool"),e={x:t};return z.runKernelFunc(function(i){return i.logicalNot(t)},e,null,of)}var ks=U({logicalNot_:cN});function hN(n,t){var e=O(n,"a","logicalOr","bool"),i=O(t,"b","logicalOr","bool");Qe(e.shape,i.shape);var r={a:e,b:i};return z.runKernelFunc(function(a){return a.logicalOr(e,i)},r,null,lf)}var Rc=U({logicalOr_:hN});function dN(n,t){var e=O(n,"a","logicalXor","bool"),i=O(t,"b","logicalXor","bool");return Qe(e.shape,i.shape),Mi(Rc(n,t),ks(Mi(n,t)))}var gg=U({logicalXor_:dN});function pN(n,t,e,i,r){var a=O(n,"x","maxPool"),s=1,o=a,l=!1;a.rank===3&&(l=!0,o=V(a,[1,a.shape[0],a.shape[1],a.shape[2]])),D(o.rank===4,function(){return"Error in maxPool: input must be rank 4 but got rank "+o.rank+"."}),D(Bt(e,s),function(){return"Error in maxPool: Either strides or dilations must be 1. "+("Got strides "+e+" and dilations '"+s+"'")}),r!=null&&D(it(i),function(){return"Error in maxPool: pad must be an integer when using, "+("dimRoundingMode "+r+" but got pad "+i+".")});var u=function(p,f){var m=Ar(o.shape,t,e,1,i,r),g;return m.filterWidth===1&&m.filterHeight===1&&an(m.inShape,m.outShape)?g=o.clone():g=p.maxPool(o,m),f([o,g]),g},c={x:o},h={filterSize:t,strides:e,pad:i,dimRoundingMode:r},d=z.runKernelFunc(u,c,null,ql,h);return l?V(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Oc=U({maxPool_:pN});function fN(n,t,e,i,r,a,s){t===void 0&&(t=[1,1,1]),a===void 0&&(a="NDHWC"),s==null?s=[1,1,1]:It("dilations is deprecated, this field will be gone in v3.0.0.");var o=O(n,"x","maxPool3d"),l=o,u=!1;o.rank===4&&(u=!0,l=V(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),D(l.rank===5,function(){return"Error in maxPool3d: x must be rank 5 but got rank "+l.rank+"."}),D(a==="NDHWC",function(){return"Error in maxPool3d: Only NDHWC is currently supported, "+("but got dataFormat of "+a)}),D(Bt(e,s),function(){return"Error in maxPool3d: Either strides or dilations must be 1. "+("Got strides "+e+" and dilations '"+s+"'")}),r!=null&&D(it(i),function(){return"Error in maxPool3d: pad must be an integer when using, "+("dimRoundingMode "+r+" but got pad "+i+".")});var c=function(f,m){s==null&&(s=[1,1,1]);var g=va(l.shape,t,e,s,i,r,a),v=f.maxPool3d(l,g);return m([l,v]),v},h={x:l},d={filterSize:t,strides:e,pad:i,dimRoundingMode:r,dataFormat:a,dilations:s},p=z.runKernelFunc(c,h,null,Gl,d);return u?V(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var mN=U({maxPool3d_:fN});function gN(n,t,e,i,r){r===void 0&&(r=!1);var a=O(n,"x","maxPoolWithArgmax"),s={x:a},o={filterSize:t,strides:e,pad:i,includeBatchInIndex:r},l=z.runKernel(df,s,o);return{result:l[0],indexes:l[1]}}var vN=U({maxPoolWithArgmax_:gN});function Mn(n,t){if(t===void 0&&(t="float32"),t==="complex64"){var e=Mn(n,"float32"),i=Mn(n,"float32");return ei(e,i)}var r=vr(st(n),t);return z.makeTensor(r,n,t)}function Rr(n,t){if(t===void 0&&(t="float32"),t==="complex64"){var e=Rr(n,"float32"),i=Mn(n,"float32");return ei(e,i)}var r=Hu(st(n),t);return z.makeTensor(r,n,t)}function yN(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var i=O(n,"x","mean"),r=Ze(t,i.shape),a=Bm(i.shape,r),s=a[1],o=st(s),l=Cn(function(u){var c=we(o),h=c.dtype===u.dtype?u:ue(u,c.dtype),d=Ie(h,c),p=Ae(d,t,e),f=function(m){var g=u.shape.slice();r.forEach(function(S){g[S]=1});var v=V(m,g),b=Ie(J(v,Rr(u.shape,"float32")),o);return b};return{value:p,gradFunc:f}});return l(i)}var Sa=U({mean_:yN});function bN(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var i=O(n,"x","min"),r=function(o,l){var u=Ze(t,i.shape),c=u,h=Qt(c,i.rank),d=i;h!=null&&(d=lt(i,h),c=Nn(c.length,i.rank));var p=o.min(d,c);h!=null&&d.dispose();var f=p;if(e){var m=Zt(f.shape,u);f=V(p,m),p.dispose()}return l([i,f]),f},a={x:i},s={axis:t,keepDims:e};return z.runKernelFunc(r,a,null,Yl,s)}var Fs=U({min_:bN});function wN(n,t){var e,i=O(n,"a","minimum"),r=O(t,"b","minimum");e=rt(i,r),i=e[0],r=e[1],i.dtype==="bool"&&(i=ue(i,"int32"),r=ue(r,"int32")),Qe(i.shape,r.shape);var a=function(o,l){var u=o.minimum(i,r);return l([i,r]),u},s={a:i,b:r};return z.runKernelFunc(a,s,null,Kl)}var Ws=U({minimum_:wN});function SN(n,t){var e,i=O(n,"a","mod"),r=O(t,"b","mod");e=rt(i,r),i=e[0],r=e[1];var a=function(o,l){var u=o.mod(i,r);return l([i,r]),u},s={a:i,b:r};return z.runKernelFunc(a,s,null,jl)}var Ec=U({mod_:SN});function LN(n){var t=O(n,"x","square"),e={},i=[t],r=[];return z.runKernelFunc(function(a,s){return s([t]),a.square(t)},{x:t},null,"Square",e,i,r)}var qe=U({square_:LN});function IN(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1),n=O(n,"x","moments");var i=Ze(t,n.shape),r=Sa(n,i,e),a=r.shape;e||(a=Zt(r.shape,i));var s=qe(ge(ue(n,"float32"),V(r,a))),o=Sa(s,i,e);return{mean:r,variance:o}}var AN=U({moments_:IN});function TN(n,t,e,i){for(var r=O(t,"data","multiRNNCell"),a=pa(e,"c","multiRNNCell"),s=pa(i,"h","multiRNNCell"),o=r,l=[],u=0;u2)throw new Error("Rank of probabilities must be 1 or 2, but is "+s);e=e||Math.random();var o=s===1?V(r,[1,-1]):r,l=z.runKernelFunc(function(u){return u.multinomial(o,i,t,e)},{logits2D:o});return s===1?V(l,[l.size]):l}var CN=U({multinomial_:xN});function RN(n,t){var e,i=O(n,"a","notEqual"),r=O(t,"b","notEqual");e=rt(i,r),i=e[0],r=e[1],Qe(i.shape,r.shape);var a=function(o){return o.notEqual(i,r)},s={a:i,b:r};return z.runKernelFunc(a,s,null,pf)}var Us=U({notEqual_:RN});function ON(n){var t=O(n,"input","real"),e=function(r){return r.real(t)},i={input:t};return z.runKernelFunc(e,i,null,bf)}var La=U({real_:ON});function EN(n){var t=O(n,"x","onesLike"),e=function(r,a){if(t.dtype==="complex64"){var s=Dc(La(t)),o=Ee(Os(t));return ei(s,o)}return r.onesLike(t)},i={x:t};return z.runKernelFunc(e,i,null,Jl)}var Dc=U({onesLike_:EN});function DN(n,t){var e=O(n,"v1","outerProduct"),i=O(t,"v2","outerProduct");D(e.rank===1&&i.rank===1,function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+(e.rank+" and "+i.rank+".")});var r=V(e,[-1,1]),a=V(i,[1,-1]);return Fe(r,a)}var kN=U({outerProduct_:DN});function FN(n,t,e){e===void 0&&(e=0);var i=O(n,"x","pad");if(i.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var r=function(o,l){return l([i]),o.pad(i,t,e)},a={paddings:t,constantValue:e},s={x:i};return z.runKernelFunc(r,s,null,Ql,a)}var Hi=U({pad_:FN});function WN(n,t,e){return e===void 0&&(e=0),D(t.length===2,function(){return"Invalid number of paddings. Must be length of 2."}),Hi(n,[t],e)}var UN=U({pad1d_:WN});function BN(n,t,e){return e===void 0&&(e=0),D(t.length===2&&t[0].length===2&&t[1].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),Hi(n,t,e)}var zN=U({pad2d_:BN});function _N(n,t,e){return e===void 0&&(e=0),D(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),Hi(n,t,e)}var PN=U({pad3d_:_N});function MN(n,t,e){return e===void 0&&(e=0),D(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,function(){return"Invalid number of paddings. Must be length of 2 each."}),Hi(n,t,e)}var HN=U({pad4d_:MN});function VN(n,t,e){var i=O(n,"x","spaceToBatchND");D(i.rank>=1+t.length,function(){return"input rank "+i.rank+" should be > than [blockShape] "+t.length}),D(e.length===t.length,function(){return"paddings.shape[0] "+e.length+" must be equal to [blockShape] "+t.length}),D(i.shape.reduce(function(o,l,u){return u>0&&u<=t.length?o&&(l+e[u-1][0]+e[u-1][1])%t[u-1]===0:o},!0),function(){return"input spatial dimensions "+i.shape.slice(1)+" with paddings "+e.toString()+" must be divisible by blockShapes "+t.toString()});var r=function(o){return o.spaceToBatchND(i,t,e)},a={x:i},s={blockShape:t,paddings:e};return z.runKernelFunc(r,a,null,Su,s)}var Bs=U({spaceToBatchND_:VN});function YN(n,t,e,i,r,a){r==null&&(r=[1,1]),a==null&&(a=1),i===0&&(i="valid");var s=O(n,"x","maxPool"),o=s,l=!1;s.rank===3&&(l=!0,o=V(s,[1,s.shape[0],s.shape[1],s.shape[2]])),D(Bt(a,r),function(){return"Error in pool: Either strides or dilations must be 1. "+("Got strides "+a+" and dilations '"+r+"'")});var u=Ar(o.shape,t,a,r,i),c=[u.dilationHeight,u.dilationWidth],h;i==="same"?h=GN([u.filterHeight,u.filterWidth],c):h=[[0,0],[0,0]];var d=c[0]===1&&c[1]===1,p=qN([u.inHeight,u.inWidth],c,h),f=p[0],m=p[1],g=d?i:"valid",v=d?o:Bs(o,c,f),b=e==="avg"?function(){return bc(v,t,a,g)}:function(){return Oc(v,t,a,g)},S=b(),L=d?S:As(S,c,m);return l?V(L,[L.shape[1],L.shape[2],L.shape[3]]):L}function qN(n,t,e){var i=e.map(function(c){return c[0]}),r=e.map(function(c){return c[1]}),a=n.concat(i,r),s=t.map(function(c,h){return(c-a[h]%c)%c}),o=r.map(function(c,h){return c+s[h]}),l=t.map(function(c,h){return[i[h],o[h]]}),u=t.map(function(c,h){return[0,s[h]]});return[l,u]}function GN(n,t){var e=n.map(function(s,o){return s+(s-1)*(t[o]-1)}),i=e.map(function(s){return s-1}),r=i.map(function(s){return Math.floor(s/2)}),a=i.map(function(s,o){return s-r[o]});return i.map(function(s,o){return[r[o],a[o]]})}var vg=U({pool_:YN});function KN(n,t){var e,i=O(n,"base","pow"),r=O(t,"exp","pow");e=rt(i,r),i=e[0],r=e[1];var a={a:i,b:r},s=function(o,l){var u=o.pow(i,r);return l([i,r,u]),u};return z.runKernelFunc(s,a,null,eu)}var Hn=U({pow_:KN});function jN(n,t){var e=O(n,"x","prelu"),i=O(t,"alpha","prelu"),r=function(s,o){var l=s.prelu(e,i);return o([e,i]),l},a={x:e,alpha:i};return z.runKernelFunc(r,a,null,tu)}var kc=U({prelu_:jN});function $N(n,t,e){t===void 0&&(t=null),e===void 0&&(e=!1);var i=O(n,"x","prod"),r=function(o){i.dtype==="bool"&&(i=ue(i,"int32"));var l=Ze(t,i.shape),u=Qt(l,i.rank),c=l,h=i;u!=null&&(h=lt(i,u),c=Nn(c.length,i.rank));var d=o.prod(h,c);if(e){var p=Zt(d.shape,l);d=V(d,p)}return d},a={x:i},s={axis:t,keepDims:e};return z.runKernelFunc(r,a,null,vf,s)}var yg=U({prod_:$N});function XN(n,t,e){var i=st(n),r=null;if(e==null||e==="float32")r=new Float32Array(i);else if(e==="int32")r=new Int32Array(i);else if(e==="bool")r=new Uint8Array(i);else throw new Error("Unknown data type "+e);for(var a=0;a>>0,d-=l,d*=l,l=d>>>0,d-=l,l+=d*4294967296}return(l>>>0)*23283064365386963e-26};return u}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.alea=s})(Or,n,!1)}),QN=Vi(function(n){(function(t,e,i){function r(o){var l=this,u="";l.x=0,l.y=0,l.z=0,l.w=0,l.next=function(){var h=l.x^l.x<<11;return l.x=l.y,l.y=l.z,l.z=l.w,l.w^=l.w>>>19^h^h>>>8},o===(o|0)?l.x=o:u+=o;for(var c=0;c>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.xor128=s})(Or,n,!1)}),ex=Vi(function(n){(function(t,e,i){function r(o){var l=this,u="";l.next=function(){var h=l.x^l.x>>>2;return l.x=l.y,l.y=l.z,l.z=l.w,l.w=l.v,(l.d=l.d+362437|0)+(l.v=l.v^l.v<<4^(h^h<<1))|0},l.x=0,l.y=0,l.z=0,l.w=0,l.v=0,o===(o|0)?l.x=o:u+=o;for(var c=0;c>>4),l.next()}function a(o,l){return l.x=o.x,l.y=o.y,l.z=o.z,l.w=o.w,l.v=o.v,l.d=o.d,l}function s(o,l){var u=new r(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.xorwow=s})(Or,n,!1)}),tx=Vi(function(n){(function(t,e,i){function r(o){var l=this;l.next=function(){var c=l.x,h=l.i,d,p;return d=c[h],d^=d>>>7,p=d^d<<24,d=c[h+1&7],p^=d^d>>>10,d=c[h+3&7],p^=d^d>>>3,d=c[h+4&7],p^=d^d<<7,d=c[h+7&7],d=d^d<<13,p^=d^d<<9,c[h]=p,l.i=h+1&7,p};function u(c,h){var d,p,f=[];if(h===(h|0))p=f[0]=h;else for(h=""+h,d=0;d0;--d)c.next()}u(l,o)}function a(o,l){return l.x=o.x.slice(),l.i=o.i,l}function s(o,l){o==null&&(o=+new Date);var u=new r(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(c.x&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.xorshift7=s})(Or,n,!1)}),nx=Vi(function(n){(function(t,e,i){function r(o){var l=this;l.next=function(){var c=l.w,h=l.X,d=l.i,p,f;return l.w=c=c+1640531527|0,f=h[d+34&127],p=h[d=d+1&127],f^=f<<13,p^=p<<17,f^=f>>>15,p^=p>>>12,f=h[d]=f^p,l.i=d,f+(c^c>>>16)|0};function u(c,h){var d,p,f,m,g,v=[],b=128;for(h===(h|0)?(p=h,h=null):(h=h+"\0",p=0,b=Math.max(b,h.length)),f=0,m=-32;m>>15,p^=p<<4,p^=p>>>13,m>=0&&(g=g+1640531527|0,d=v[m&127]^=p+g,f=d==0?f+1:0);for(f>=128&&(v[(h&&h.length||0)&127]=-1),f=127,m=4*128;m>0;--m)p=v[f+34&127],d=v[f=f+1&127],p^=p<<13,d^=d<<17,p^=p>>>15,d^=d>>>12,v[f]=p^d;c.w=g,c.X=v,c.i=f}u(l,o)}function a(o,l){return l.i=o.i,l.w=o.w,l.X=o.X.slice(),l}function s(o,l){o==null&&(o=+new Date);var u=new r(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(c.X&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.xor4096=s})(Or,n,!1)}),ix=Vi(function(n){(function(t,e,i){function r(o){var l=this,u="";l.next=function(){var h=l.b,d=l.c,p=l.d,f=l.a;return h=h<<25^h>>>7^d,d=d-p|0,p=p<<24^p>>>8^f,f=f-h|0,l.b=h=h<<20^h>>>12^d,l.c=d=d-p|0,l.d=p<<16^d>>>16^f,l.a=f-h|0},l.a=0,l.b=0,l.c=2654435769|0,l.d=1367130551,o===Math.floor(o)?(l.a=o/4294967296|0,l.b=o|0):u+=o;for(var c=0;c>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.tychei=s})(Or,n,!1)}),qi=Vi(function(n){(function(t,e){var i=this,r=256,a=6,s=52,o="random",l=e.pow(r,a),u=e.pow(2,s),c=u*2,h=r-1,d;function p(L,w,N){var I=[];w=w==!0?{entropy:!0}:w||{};var C=v(g(w.entropy?[L,S(t)]:L??b(),3),I),E=new f(I),k=function(){for(var W=E.g(a),F=l,_=0;W=c;)W/=2,F/=2,_>>>=1;return(W+_)/F};return k.int32=function(){return E.g(4)|0},k.quick=function(){return E.g(4)/4294967296},k.double=k,v(S(E.S),t),(w.pass||N||function(W,F,_,H){return H&&(H.S&&m(H,E),W.state=function(){return m(E,{})}),_?(e[o]=W,F):W})(k,C,"global"in w?w.global:this==e,w.state)}e["seed"+o]=p;function f(L){var w,N=L.length,I=this,C=0,E=I.i=I.j=0,k=I.S=[];for(N||(L=[N++]);C=1||o===0);var l=Math.sqrt(-2*Math.log(o)/o);e=this.mean+this.stdDev*a*l,i=this.mean+this.stdDev*s*l,(!this.truncated||this.isValidTruncated(e))&&(r=!0)}return(!this.truncated||this.isValidTruncated(i))&&(this.nextVal=this.convertValue(i)),this.convertValue(e)},n.prototype.convertValue=function(t){return this.dtype==null||this.dtype==="float32"?t:Math.round(t)},n.prototype.isValidTruncated=function(t){return t<=this.upper&&t>=this.lower},n}(),ax=function(){function n(t,e,i,r){this.alpha=t,this.beta=1/e,this.dtype=i;var a=r||Math.random();this.randu=Fc(a.toString()),this.randn=new Wc(0,1,i,!1,this.randu()),t<1?this.d=t+2/3:this.d=t-1/3,this.c=1/Math.sqrt(9*this.d)}return n.prototype.nextValue=function(){for(var t,e,i,r,a,s;;){do r=this.randn.nextValue(),s=1+this.c*r;while(s<=0);if(s*=s*s,t=r*r,e=1-.331*t*t,i=.5*t+this.d*(1-s+Math.log(s)),a=this.randu(),a1;if(s||o||l)return Mn([0],i);var u=Math.abs(Math.ceil((t-n)/e)),c=vr(u,i);t0?o+l:o});t[a]=n.shape[e]-s}D(n.shape[e]===t.reduce(function(o,l){return o+l}),function(){return"The sum of sizes must match the size of the axis dimension."}),i=t}return i}function Gx(n,t,e){e===void 0&&(e=0);var i=O(n,"x","split"),r=function(o,l){var u=Ze(e,i.shape)[0],c=Ng(i,t,u);return o.split(i,c,u)},a={x:i},s={numOrSizeSplits:t,axis:e};return z.runKernelFunc(r,a,null,Lu,s)}var Dr=U({split_:Gx});function Yx(n,t){D(n.dtype==="float32",function(){return"The dtype for rfft() must be real value but got "+n.dtype});var e=n.shape[n.shape.length-1],i=n.size/e,r;if(t!=null&&te){var o=n.shape.map(function(v){return v});o[n.shape.length-1]=t-e,r=xt([n,Mn(o)],n.shape.length-1),e=t}else r=n;var l=Ee(r),u=V(ei(r,l),[i,e]),c=zs(u),h=Math.floor(e/2)+1,d=La(c),p=Os(c),f=Dr(d,[h,e-h],d.shape.length-1),m=Dr(p,[h,e-h],p.shape.length-1),g=r.shape.slice();return g[r.shape.length-1]=h,V(ei(f[0],m[0]),g)}var _s=U({rfft_:Yx});function Kx(n){var t=O(n,"x","sqrt"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.sqrt(t);return r([t]),a},e,null,bu)}var zt=U({sqrt_:Kx});function jx(n,t){var e,i=O(n,"a","squaredDifference"),r=O(t,"b","squaredDifference");e=rt(i,r),i=e[0],r=e[1],Qe(i.shape,r.shape);var a=function(l,u){var c=l.squaredDifference(i,r);return u([i,r]),c},s={a:i,b:r},o={};return z.runKernelFunc(a,s,null,Au,o)}var Ps=U({squaredDifference_:jx});function $x(n,t){var e=O(n,"x","squeeze");return V(e,kf(e.shape,t).newShape)}var Ms=U({squeeze_:$x});function Xx(n,t){t===void 0&&(t=0);var e=pa(n,"tensors","stack");if(D(e.length>=1,function(){return"Pass at least one tensor to tf.stack"}),e.length===1)return hn(e[0],t);var i=e[0].rank,r=e[0].shape,a=e[0].dtype;D(t<=i,function(){return"Axis must be <= rank of the tensor"}),e.forEach(function(o){Ue(r,o.shape,"All tensors passed to stack must have matching shapes"),D(a===o.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var s=e.map(function(o){return hn(o,t)});return xt(s,t)}var Gi=U({stack_:Xx});function Jx(n,t){t===void 0&&(t=0);var e=O(n,"x","step"),i={x:e},r={alpha:t};return z.runKernelFunc(function(a){return a.step(e,t)},i,null,ku,r)}var kr=U({step_:Jx});function Zx(n,t,e,i,r,a,s,o,l){r===void 0&&(r=0),a===void 0&&(a=0),s===void 0&&(s=0),o===void 0&&(o=0),l===void 0&&(l=0);var u=O(n,"x","stridedSlice"),c=function(p){i==null&&(i=new Array(t.length));var f=ws(s);if(f.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(s!==0&&o!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(s!==0&&l!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");var m=u.rank-t.length,g=ws(o),v=u.shape.slice();g.forEach(function(W){t[W]=0,e[W]=1,v.splice(W,0,1)}),u=V(u,v);var b=Cm(u.shape,f,m,t,e,i,r,a,s),S=b.begin,L=b.end,w=b.strides;t=S,e=L,i=w;var N=ws(l);N.forEach(function(W){e[W]=t[W]+1,i[W]=1});var I=bm(t,e,i),C=I.filter(function(W,F){return N.indexOf(F)===-1}),E=i.every(function(W){return W===1});if(E)return V(Be(u,t,I),C);var k=p.stridedSlice(u,t,e,i);return V(k,C)},h={x:u},d={begin:t,end:e,strides:i,beginMask:r,endMask:a,ellipsisMask:s,newAxisMask:o,shrinkAxisMask:l};return z.runKernelFunc(c,h,null,Tf,d)}var xg=U({stridedSlice_:Zx});function Qx(n){var t=O(n,"x","tan"),e={x:t};return z.runKernelFunc(function(i,r){var a=i.tan(t);return r([t]),a},e,null,Nu)}var Cg=U({tan_:Qx});function Ta(n,t,e){if(Ei(n),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");var i=An(n,e);if(i.length!==2&&i.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(i.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return ti(n,t,i,e)}function eC(n,t,e){if(Ei(n),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");var i=An(n,e);if(i.length!==4&&i.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(i.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return ti(n,t,i,e)}function tC(n,t,e){if(Ei(n),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");var i=An(n,e);if(i.length!==5&&i.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(i.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return ti(n,t,i,e)}function nC(n,t,e){if(Ei(n),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");var i=An(n,e);if(i.length!==6&&i.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(i.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||i,ti(n,t,i,e)}function iC(n,t,e){t===void 0&&(t=1),e===void 0&&(e=!0);var i=O(n,"x","topk");if(i.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");var r=i.shape[i.shape.length-1];if(t>r)throw new Error("'k' passed to topk() must be <= the last dimension ("+r+") "+("but got "+t));var a={x:i},s={k:t,sorted:e},o=z.runKernelFunc(function(c){return c.topk(i,t,e)},a,null,Nf,s),l=o[0],u=o[1];return{values:l,indices:u}}var Rg=U({topk_:iC});function rC(n,t,e,i,r){if(t===void 0&&(t=0),e===void 0&&(e=1),i!=null&&i==="bool")throw new Error("Unsupported data type $ { dtype }");for(var a=new Wc(t,e,i,!0,r),s=Tn(n,i),o=0;o0,function(){return"The input tensor must be at least 1D"});var i={x:e},r={axis:t},a=z.runKernel(xf,i,r),s=a[0],o=a[1];return{values:s,indices:o}}var Og=U({unique_:sC});function oC(n,t,e){var i=O(n,"x","unsortedSegmentSum"),r=O(t,"segmentIds","unsortedSegmentSum","int32");D(it(e),function(){return"numSegments must be of dtype int"});var a={x:i,segmentIds:r},s={numSegments:e},o=function(l,u){var c=l.unsortedSegmentSum(i,r,e);return u([r]),c};return z.runKernelFunc(o,a,null,Eu,s)}var Hc=U({unsortedSegmentSum_:oC});function lC(n,t){t===void 0&&(t=0);var e=O(n,"x","unstack");D(t>=-e.shape.length&&t0,function(){return"mask cannot be scalar"}),Ue(o.slice(a,a+s),r.shape,"mask's shape must match the first K dimensions of tensor's shape,"),l=1,u=a;u2)throw new Error("sparseIndices should be a scalar, vector, or matrix,"+(" but got shape "+n.shape+"."));var r=n.rank>0?n.shape[0]:1,a=n.rank>1?n.shape[1]:1;if(e.length!==a)throw new Error("outputShape has incorrect number of elements:,"+(" "+e.length+", should be: "+a+"."));var s=t.size;if(!(t.rank===0||t.rank===1&&s===r))throw new Error("sparseValues has incorrect shape "+(t.shape+", should be [] or ["+r+"]"));if(t.dtype!==i.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function FC(n,t,e,i){i===void 0&&(i=0);var r=O(n,"sparseIndices","sparseToDense","int32"),a=O(t,"sparseValues","sparseToDense"),s=O(i,"defaultValue","sparseToDense",a.dtype);kC(r,a,e,s);var o={sparseIndices:r,sparseValues:a,defaultValue:s},l={outputShape:e};return z.runKernelFunc(function(u){return u.sparseToDense(r,a,e,s)},o,null,Af,l)}var WC=U({sparseToDense_:FC});function UC(n,t){var e=O(t,"indices","gatherND","int32"),i=O(n,"x","gatherND"),r=function(s){return s.gatherND(i,e)},a={params:i,indices:e};return z.runKernelFunc(r,a,null,Zp)}var BC=U({gatherND_:UC});function zC(n,t){if(t==null)return n.shape.slice();if(an(n.shape,t))return t;if(n.shape.length===t.length){for(var e=[],i=0;i=0&&t<1,function(){return"rate must be a float in the range [0, 1), but got "+t+"."}),t===0)return n instanceof Y?r.clone():r;var a=zC(r,e),s=1-t,o=Ie(Cs(fe(bg(a,0,1,"float32",i),s)),s);return J(r,o)}var PC=U({dropout_:_C});function $g(n){return Math.floor(Math.pow(2,Math.ceil(Math.log(n)/Math.log(2))))}function Vc(n,t,e){for(var i=1-n%2,r=new Float32Array(n),a=0;a1,function(){return"inTopK() expects the predictions to be of rank 2 or higher, "+("but got "+i.rank)}),D(i.rank-1===r.rank,function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+(i.rank+" and targets rank "+r.rank)}),Ue(i.shape.slice(0,i.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),a=i.shape[i.shape.length-1],D(e>0&&e<=a,function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last "+("dimension ("+a+"), but got "+e)}),[4,i.data()];case 1:return s=v.sent(),[4,r.data()];case 2:for(o=v.sent(),l=[s.length/a,a],u=l[0],c=l[1],h=cs("bool",u),d=0;d0&&(e=Ae(e,i)),V(e,n.shape)}function Ys(n,t,e){if(t==="linear")return n;if(t==="relu")return Ia(n);if(t==="elu")return Ic(n);if(t==="relu6")return Bc(n);if(t==="prelu")return kc(n,e);throw new Error("Unknown fused activation "+t+".")}var Ks=function(n,t){var e=n>0;return!e||t==="linear"};function qC(n){var t=n.x,e=n.filter,i=n.strides,r=n.pad,a=n.dataFormat,s=a===void 0?"NHWC":a,o=n.dilations,l=o===void 0?[1,1]:o,u=n.dimRoundingMode,c=n.bias,h=n.activation,d=h===void 0?"linear":h,p=n.preluActivationWeights;if(d=d||"linear",Ks(z.state.gradientDepth,d)===!1){var f=Nr(t,e,i,r,s,l,u);return c!=null&&(f=fe(f,c)),Ys(f,d,p)}var m=O(t,"x","conv2d"),g=O(e,"filter","conv2d"),v=m,b=!1;m.rank===3&&(b=!0,v=V(m,[1,m.shape[0],m.shape[1],m.shape[2]])),D(v.rank===4,function(){return"Error in fused conv2d: input must be rank 4, but got rank "+(v.rank+".")}),D(g.rank===4,function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+(g.rank+".")}),u!=null&&D(it(r),function(){return"Error in fused conv2d: pad must be an integer when using, "+("dimRoundingMode "+u+" but got pad "+r+".")}),D(v.shape[3]===g.shape[2],function(){return"Error in conv2d: depth of input ("+v.shape[3]+") must match "+("input depth for filter "+g.shape[2]+".")}),D(Bt(i,l),function(){return"Error in conv2D: Either strides or dilations must be 1. "+("Got strides "+i+" and dilations '"+l+"'")}),D(s==="NHWC",function(){return"Error in conv2d: got dataFormat of "+s+" but only NHWC is currently supported."});var S=xn(v.shape,g.shape,i,l,r,u),L;c!=null&&(L=O(c,"bias","fused conv2d"),L=rt(L,m)[0],Qe(S.outShape,L.shape));var w;p!=null&&(w=O(p,"prelu weights","fused conv2d"));var N=function(F,_){var H=_,P=H[0],K=H[1],j=H[2],q=H[3],G=qs(F,j,d);D(si(l),function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 "+("are not yet supported in gradients. Got dilations '"+l+"'")});var Z=wc(K.shape,G,P,i,r),X=qc(K,G,P.shape,i,r),ee=[Z,X];if(q!=null){var ne=Gs(q,G);ee.push(ne)}return ee},I=function(F){var _=F.fusedConv2d({input:v,filter:g,convInfo:S,bias:L,activation:d,preluActivationWeights:w});return _},C={x:v,filter:g,bias:L,preluActivationWeights:w},E={strides:i,pad:r,dataFormat:s,dilations:l,dimRoundingMode:u,activation:d};if(c==null){var k=Cn(function(F,_,H){var P=z.runKernelFunc(I,C,null,Uu,E);return H([_,F,P]),b&&(P=V(P,[P.shape[1],P.shape[2],P.shape[3]])),{value:P,gradFunc:N}});return k(v,g)}else{var W=Cn(function(F,_,H,P){var K=z.runKernelFunc(I,C,null,Uu,E);return P([_,F,K,H]),b&&(K=V(K,[K.shape[1],K.shape[2],K.shape[3]])),{value:K,gradFunc:N}});return W(v,g,L)}}var GC=U({fusedConv2d_:qC});function YC(n,t,e,i){var r=n;n.rank===3&&(r=V(n,[1,n.shape[0],n.shape[1],n.shape[2]]));var a=t;a.rank===3&&(a=V(t,[1,t.shape[0],t.shape[1],t.shape[2]]));var s=function(l){return l.depthwiseConv2DDerFilter(r,a,i)},o={x:r,dy:a};return z.runKernelFunc(s,o,null,Hp)}var Xg=U({depthwiseConv2dNativeBackpropFilter_:YC});function KC(n,t,e,i){var r=t,a=!1;t.rank===3&&(a=!0,r=V(t,[1,t.shape[0],t.shape[1],t.shape[2]]));var s=function(u){return u.depthwiseConv2DDerInput(r,e,i)},o={dy:r},l=z.runKernelFunc(s,o,null,Vp);return a?V(l,[l.shape[1],l.shape[2],l.shape[3]]):l}var Jg=U({depthwiseConv2dNativeBackpropInput_:KC});function jC(n){var t=n.x,e=n.filter,i=n.strides,r=n.pad,a=n.dataFormat,s=a===void 0?"NHWC":a,o=n.dilations,l=o===void 0?[1,1]:o,u=n.dimRoundingMode,c=n.bias,h=n.activation,d=h===void 0?"linear":h,p=n.preluActivationWeights;if(Ks(z.state.gradientDepth,d)===!1){var f=ba(t,e,i,r,s,l,u);return c!=null&&(f=fe(f,c)),Ys(f,d,p)}var m=O(t,"x","depthwiseConv2d"),g=O(e,"filter","depthwiseConv2d"),v=m,b=!1;m.rank===3&&(b=!0,v=V(m,[1,m.shape[0],m.shape[1],m.shape[2]])),D(v.rank===4,function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got "+("rank "+v.rank+".")}),D(g.rank===4,function(){return"Error in fused depthwiseConv2d: filter must be rank 4, "+("but got rank "+g.rank+".")}),D(v.shape[3]===g.shape[2],function(){return"Error in fused depthwiseConv2d: number of input channels "+("("+v.shape[3]+") must match the inChannels dimension in ")+("filter "+g.shape[2]+".")}),l==null&&(l=[1,1]),D(Bt(i,l),function(){return"Error in fused depthwiseConv2d: Either strides or dilations must "+("be 1. Got strides "+i+" and dilations '"+l+"'")}),u!=null&&D(it(r),function(){return"Error in fused depthwiseConv2d: pad must be an integer when "+("using dimRoundingMode "+u+" but got pad "+r+".")});var S=xn(v.shape,g.shape,i,l,r,u,!0),L;c!=null&&(L=O(c,"bias","fused conv2d"),L=rt(L,m)[0],Qe(S.outShape,L.shape));var w;p!=null&&(w=O(p,"prelu weights","fused depthwiseConv2d"));var N=function(F,_){D(si(l),function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations "+("'"+l+"'")});var H=_[0],P=_[1],K=_[2],j=_[3],q=qs(F,K,d),G=Jg(P.shape,q,H,S),Z=Xg(P,q,H.shape,S);if(j!=null){var X=Gs(L,q);return[G,Z,X]}return[G,Z]},I=function(F){var _=F.fusedDepthwiseConv2D({input:v,filter:g,convInfo:S,bias:L,activation:d,preluActivationWeights:w});return _},C={x:v,filter:g,bias:L,preluActivationWeights:w},E={strides:i,pad:r,dataFormat:s,dilations:l,dimRoundingMode:u,activation:d};if(c==null){var k=Cn(function(F,_,H){var P=z.runKernelFunc(I,C,null,Bu,E);return H([_,F,P]),b&&(P=V(P,[P.shape[1],P.shape[2],P.shape[3]])),{value:P,gradFunc:N}});return k(v,g)}else{var W=Cn(function(F,_,H,P){var K=z.runKernelFunc(I,C,null,Bu,E);return P([_,F,K,H]),b&&(K=V(K,[K.shape[1],K.shape[2],K.shape[3]])),{value:K,gradFunc:N}});return W(v,g,L)}}var $C=U({fusedDepthwiseConv2d_:jC});function XC(n){var t,e=n.a,i=n.b,r=n.transposeA,a=r===void 0?!1:r,s=n.transposeB,o=s===void 0?!1:s,l=n.bias,u=n.activation,c=u===void 0?"linear":u,h=n.preluActivationWeights;if(Ks(z.state.gradientDepth,c)===!1){var d=Fe(e,i,a,o);return l!=null&&(d=fe(d,l)),Ys(d,c,h)}var p=O(e,"a","fused matMul"),f=O(i,"b","fused matMul");t=rt(p,f),p=t[0],f=t[1];var m=a?p.shape[p.rank-2]:p.shape[p.rank-1],g=o?f.shape[f.rank-1]:f.shape[f.rank-2],v=a?p.shape[p.rank-1]:p.shape[p.rank-2],b=o?f.shape[f.rank-2]:f.shape[f.rank-1],S=p.shape.slice(0,-2),L=f.shape.slice(0,-2),w=st(S),N=st(L);D(p.rank>=2&&f.rank>=2&&p.rank===f.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least "+("2, got ranks "+p.rank+" and "+f.rank+".")}),D(an(S,L),function(){return"Error in fused matMul: outer dimensions ("+S+") and ("+(L+") of Tensors with shapes "+p.shape+" and ")+(f.shape+" must match.")}),D(m===g,function(){return"Error in fused matMul: inner shapes ("+m+") and ("+(g+") of Tensors with shapes "+p.shape+" and ")+(f.shape+" and transposeA="+a)+(" and transposeB="+o+" must match.")});var I=p.shape.slice(0,-2).concat([v,b]),C=a?V(p,[w,m,v]):V(p,[w,v,m]),E=o?V(f,[N,b,g]):V(f,[N,g,b]),k;l!=null&&(k=O(l,"bias","fused matMul"),k=rt(k,p)[0],Qe(I,k.shape));var W;h!=null&&(W=O(h,"prelu weights","fused matMul"));var F=function(q,G){var Z=G[0],X=G[1],ee=G[2],ne=G[3],ie=qs(V(q,ee.shape),ee,c),te,re;if(!a&&!o?(te=Fe(ie,X,!1,!0),re=Fe(Z,ie,!0,!1)):!a&&o?(te=Fe(ie,X,!1,!1),re=Fe(ie,Z,!0,!1)):a&&!o?(te=Fe(X,ie,!1,!0),re=Fe(Z,ie,!1,!1)):(te=Fe(X,ie,!0,!0),re=Fe(ie,Z,!0,!0)),l!=null){var le=Gs(ne,ie);return[te,re,le]}else return[te,re]},_=function(q){var G=q.fusedBatchMatMul({a:C,b:E,transposeA:a,transposeB:o,bias:k,activation:c,preluActivationWeights:W});return G},H={a:C,b:E,bias:k,preluActivationWeights:W},P={transposeA:a,transposeB:o,activation:c};if(l==null){var K=Cn(function(q,G,Z){var X=z.runKernelFunc(_,H,null,Wu,P);return Z([q,G,X]),{value:V(X,I),gradFunc:F}});return K(C,E)}else{var j=Cn(function(q,G,Z,X){var ee=z.runKernelFunc(_,H,null,Wu,P);return X([q,G,ee,Z]),{value:V(ee,I),gradFunc:F}});return j(C,E,k)}}var JC=U({fusedMatMul_:XC});var ZC={__proto__:null,conv2d:GC,depthwiseConv2d:$C,matMul:JC};function QC(n){return Vc(n,.54,.46)}var eR=U({hammingWindow_:QC});function tR(n){return Vc(n,.5,.5)}var Zg=U({hannWindow_:tR});function nR(n,t,e,i,r){i===void 0&&(i=!1),r===void 0&&(r=0);for(var a=0,s=[];a+t<=n.size;)s.push(Be(n,a,t)),a+=e;if(i)for(;a=1&&i[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+i}),D(r==="bilinear"||r==="nearest",function(){return"method must be bilinear or nearest, but was "+r});var c=function(f){return f.cropAndResize(s,o,l,i,r,a)},h={image:s,boxes:o,boxInd:l},d={method:r,extrapolationValue:a,cropSize:i},p=z.runKernelFunc(c,h,null,Pp,d);return p}var sR=U({cropAndResize_:aR});function oR(n){var t=O(n,"image","flipLeftRight","float32");D(t.rank===4,function(){return"Error in flipLeftRight: image must be rank 4,"+("but got rank "+t.rank+".")});var e={image:t},i=z.runKernel(Jp,e,{});return i}var lR=U({flipLeftRight_:oR});function uR(n,t,e,i){e===void 0&&(e=0),i===void 0&&(i=.5);var r=O(n,"image","rotateWithOffset","float32");D(r.rank===4,function(){return"Error in rotateWithOffset: image must be rank 4,"+("but got rank "+r.rank+".")});var a={image:r},s={radians:t,fillValue:e,center:i},o=z.runKernel(Cf,a,s);return o}var cR=U({rotateWithOffset_:uR});function Fr(n,t,e,i,r,a){i==null&&(i=.5),r==null&&(r=Number.NEGATIVE_INFINITY),a==null&&(a=0);var s=n.shape[0];return e=Math.min(e,s),D(0<=i&&i<=1,function(){return"iouThreshold must be in [0, 1], but was '"+i+"'"}),D(n.rank===2,function(){return"boxes must be a 2D tensor, but was of rank '"+n.rank+"'"}),D(n.shape[1]===4,function(){return"boxes must have 4 columns, but 2nd dimension was "+n.shape[1]}),D(t.rank===1,function(){return"scores must be a 1D tensor"}),D(t.shape[0]===s,function(){return"scores has incompatible shape with boxes. Expected "+s+", "+("but was "+t.shape[0])}),D(0<=a&&a<=1,function(){return"softNmsSigma must be in [0, 1], but was '"+a+"'"}),{maxOutputSize:e,iouThreshold:i,scoreThreshold:r,softNmsSigma:a}}function hR(n,t,e,i,r){i===void 0&&(i=.5),r===void 0&&(r=Number.NEGATIVE_INFINITY);var a=O(n,"boxes","nonMaxSuppression"),s=O(t,"scores","nonMaxSuppression"),o=Fr(a,s,e,i,r);e=o.maxOutputSize,i=o.iouThreshold,r=o.scoreThreshold;var l={maxOutputSize:e,iouThreshold:i,scoreThreshold:r};return z.runKernelFunc(function(u){return u.nonMaxSuppression(a,s,e,i,r)},{boxes:a,scores:s},null,ff,l)}var dR=U({nonMaxSuppression_:hR});function fR(n,t,e){var i=pR(n,t,e),r=i<0?-(i+1):i;n.splice(r,0,t)}function pR(n,t,e){return gR(n,t,e||mR)}function mR(n,t){return n>t?1:n>>1);var o=e(t,n[a]);o>0?i=a+1:(r=a,s=!o)}return s?i:-i-1}function ev(n,t,e,i,r){return Gc(n,t,e,i,r,0).selectedIndices}function tv(n,t,e,i,r,a){return Gc(n,t,e,i,r,0,!1,a,!0)}function nv(n,t,e,i,r,a){return Gc(n,t,e,i,r,a,!0)}function Gc(n,t,e,i,r,a,s,o,l){s===void 0&&(s=!1),o===void 0&&(o=!1),l===void 0&&(l=!1);for(var u=[],c=0;cr&&u.push({score:t[c],boxIndex:c,suppressBeginIndex:0});u.sort(iv);for(var h=a>0?-.5/a:0,d=[],p=[];d.length0;){var f=u.pop(),m=f.score,g=f.boxIndex,v=f.suppressBeginIndex;if(m=v;--S){var L=vR(n,g,d[S]);if(L>=i){b=!0;break}if(f.score=f.score*yR(i,h,L),f.score<=r)break}f.suppressBeginIndex=d.length,b||(f.score===m?(d.push(g),p.push(f.score)):f.score>r&&fR(u,f,iv))}var w=d.length,N=e-w;o&&N>0&&(d.push.apply(d,new Array(N).fill(0)),p.push.apply(p,new Array(N).fill(0)));var I={selectedIndices:Er(d,"int32")};return s&&(I.selectedScores=Er(p,"float32")),l&&(I.validOutputs=we(w,"int32")),I}function vR(n,t,e){var i=n.subarray(t*4,t*4+4),r=n.subarray(e*4,e*4+4),a=Math.min(i[0],i[2]),s=Math.min(i[1],i[3]),o=Math.max(i[0],i[2]),l=Math.max(i[1],i[3]),u=Math.min(r[0],r[2]),c=Math.min(r[1],r[3]),h=Math.max(r[0],r[2]),d=Math.max(r[1],r[3]),p=(o-a)*(l-s),f=(h-u)*(d-c);if(p<=0||f<=0)return 0;var m=Math.max(a,u),g=Math.max(s,c),v=Math.min(o,h),b=Math.min(l,d),S=Math.max(v-m,0)*Math.max(b-g,0);return S/(p+f-S)}function yR(n,t,e){var i=Math.exp(t*e*e);return e<=n?i:0}function iv(n,t){return n.score-t.score||n.score===t.score&&t.boxIndex-n.boxIndex}function bR(n,t,e,i,r){return i===void 0&&(i=.5),r===void 0&&(r=Number.NEGATIVE_INFINITY),de(this,void 0,void 0,function(){var a,s,o,l,u,c,h;return pe(this,function(d){switch(d.label){case 0:return a=O(n,"boxes","nonMaxSuppressionAsync"),s=O(t,"scores","nonMaxSuppressionAsync"),o=Fr(a,s,e,i,r),e=o.maxOutputSize,i=o.iouThreshold,r=o.scoreThreshold,[4,Promise.all([a.data(),s.data()])];case 1:return l=d.sent(),u=l[0],c=l[1],h=ev(u,c,e,i,r),a!==n&&a.dispose(),s!==t&&s.dispose(),[2,h]}})})}var wR=bR;function SR(n,t,e,i,r,a){i===void 0&&(i=.5),r===void 0&&(r=Number.NEGATIVE_INFINITY),a===void 0&&(a=0);var s=O(n,"boxes","nonMaxSuppression"),o=O(t,"scores","nonMaxSuppression"),l=Fr(s,o,e,i,r,a);e=l.maxOutputSize,i=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;var u={boxes:s,scores:o},c={maxOutputSize:e,iouThreshold:i,scoreThreshold:r,softNmsSigma:a},h=z.runKernel(gf,u,c);return{selectedIndices:h[0],selectedScores:h[1]}}var LR=U({nonMaxSuppressionWithScore_:SR});function IR(n,t,e,i,r,a){return i===void 0&&(i=.5),r===void 0&&(r=Number.NEGATIVE_INFINITY),a===void 0&&(a=0),de(this,void 0,void 0,function(){var s,o,l,u,c,h,d;return pe(this,function(p){switch(p.label){case 0:return s=O(n,"boxes","nonMaxSuppressionAsync"),o=O(t,"scores","nonMaxSuppressionAsync"),l=Fr(s,o,e,i,r,a),e=l.maxOutputSize,i=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma,[4,Promise.all([s.data(),o.data()])];case 1:return u=p.sent(),c=u[0],h=u[1],d=nv(c,h,e,i,r,a),s!==n&&s.dispose(),o!==t&&o.dispose(),[2,d]}})})}var AR=IR;function TR(n,t,e,i,r,a){i===void 0&&(i=.5),r===void 0&&(r=Number.NEGATIVE_INFINITY),a===void 0&&(a=!1);var s=O(n,"boxes","nonMaxSuppression"),o=O(t,"scores","nonMaxSuppression"),l=Fr(s,o,e,i,r,null),u=l.maxOutputSize,c=l.iouThreshold,h=l.scoreThreshold,d={boxes:s,scores:o},p={maxOutputSize:u,iouThreshold:c,scoreThreshold:h,padToMaxOutputSize:a},f=z.runKernel(mf,d,p);return{selectedIndices:f[0],validOutputs:f[1]}}var NR=U({nonMaxSuppressionPadded_:TR});function xR(n,t,e,i,r,a){return i===void 0&&(i=.5),r===void 0&&(r=Number.NEGATIVE_INFINITY),a===void 0&&(a=!1),de(this,void 0,void 0,function(){var s,o,l,u,c,h,d,p,f,m;return pe(this,function(g){switch(g.label){case 0:return s=O(n,"boxes","nonMaxSuppressionAsync"),o=O(t,"scores","nonMaxSuppressionAsync"),l=Fr(s,o,e,i,r,null),u=l.maxOutputSize,c=l.iouThreshold,h=l.scoreThreshold,[4,Promise.all([s.data(),o.data()])];case 1:return d=g.sent(),p=d[0],f=d[1],m=tv(p,f,u,c,h,a),s!==n&&s.dispose(),o!==t&&o.dispose(),[2,m]}})})}var CR=xR;function RR(n,t,e){e===void 0&&(e=!1);var i=O(n,"images","resizeBilinear");D(i.rank===3||i.rank===4,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got "+("rank "+i.rank+".")}),D(t.length===2,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+(t+".")});var r=i,a=!1;i.rank===3&&(a=!0,r=V(i,[1,i.shape[0],i.shape[1],i.shape[2]]));var s=t[0],o=t[1],l=function(d,p){return p([r]),d.resizeBilinear(r,s,o,e)},u={images:r},c={alignCorners:e,size:t},h=z.runKernelFunc(l,u,null,su,c);return a?V(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var rv=U({resizeBilinear_:RR});function OR(n,t,e){e===void 0&&(e=!1);var i=O(n,"images","resizeNearestNeighbor");D(i.rank===3||i.rank===4,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got "+("rank "+i.rank+".")}),D(t.length===2,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+(t+".")}),D(i.dtype==="float32"||i.dtype==="int32",function(){return"`images` must have `int32` or `float32` as dtype"});var r=i,a=!1;i.rank===3&&(a=!0,r=V(i,[1,i.shape[0],i.shape[1],i.shape[2]]));var s=t[0],o=t[1],l={images:r},u={alignCorners:e,size:t},c=function(d,p){return p([r]),d.resizeNearestNeighbor(r,s,o,e)},h=z.runKernelFunc(c,l,null,au,u);return a?V(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var av=U({resizeNearestNeighbor_:OR});function ER(n,t,e){D(t%1===0,function(){return"bandPart(): numLower must be an integer, got "+t+"."}),D(e%1===0,function(){return"bandPart(): numUpper must be an integer, got "+e+"."});var i=O(n,"a","bandPart");D(i.rank>=2,function(){return"bandPart(): Rank must be at least 2, got "+i.rank+"."});var r=i.shape,a=i.shape.slice(-2),s=a[0],o=a[1];if(!(t<=s))throw new Error("bandPart(): numLower ("+t+")"+(" must not be greater than the number of rows ("+s+")."));if(!(e<=o))throw new Error("bandPart(): numUpper ("+e+")"+(" must not be greater than the number of columns ("+o+")."));t<0&&(t=s),e<0&&(e=o);var l=V(Uc(0,s,1,"int32"),[-1,1]),u=Uc(0,o,1,"int32"),c=ge(l,u),h=Mi(zi(c,we(+t,"int32")),Bi(c,we(-e,"int32"))),d=Mn([s,o],i.dtype);return V(Gi(Hs(V(i,[-1,s,o])).map(function(p){return un(h,p,d)})),r)}var DR=U({bandPart_:ER});function kR(n){var t;if(Array.isArray(n)){t=!1,D(n!=null&&n.length>0,function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"});for(var e=n[0].shape[0],i=function(l){D(n[l].shape[0]===e,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: "+("("+n[l].shape[0]+" vs. "+e+")")})},r=1;r0)for(var c=0;c=2,function(){return"qr() requires input tensor to have a rank >= 2, but got rank "+n.rank}),n.rank===2)return sv(n,t);var e=n.shape.slice(0,n.shape.length-2).reduce(function(l,u){return l*u}),i=Hs(V(n,[e,n.shape[n.shape.length-2],n.shape[n.shape.length-1]]),0),r=[],a=[];i.forEach(function(l){var u=sv(l,t),c=u[0],h=u[1];r.push(c),a.push(h)});var s=V(Gi(r,0),n.shape),o=V(Gi(a,0),n.shape);return[s,o]}function sv(n,t){return t===void 0&&(t=!1),z.tidy(function(){D(n.shape.length===2,function(){return"qr2d() requires a 2D Tensor, but got a "+n.shape.length+"D Tensor."});for(var e=n.shape[0],i=n.shape[1],r=sg(e),a=Fi(n),s=Ta([[1]],[1,1]),o=Fi(s),l=e>=i?i:e,u=function(h){var d,p=a,f=o,m=r;d=z.tidy(function(){var g=Be(a,[h,h],[e-h,1]),v=Vs(g),b=Be(a,[h,h],[1,1]),S=un(oi(b,0),Ta([[-1]]),Ta([[1]])),L=ge(b,J(S,v)),w=Ie(g,L);w.shape[0]===1?o=Fi(s):o=xt([s,Be(w,[1,0],[w.shape[0]-1,w.shape[1]])],0);var N=gt(Ie(Fe(S,L),v)),I=Be(a,[h,0],[e-h,i]),C=J(N,o),E=lt(o);if(h===0)a=ge(I,Fe(C,Fe(E,I)));else{var k=ge(I,Fe(C,Fe(E,I)));a=xt([Be(a,[0,0],[h,i]),k],0)}var W=lt(C),F=Be(r,[0,h],[e,r.shape[1]-h]);if(h===0)r=ge(F,Fe(Fe(F,o),W));else{var _=ge(F,Fe(Fe(F,o),W));r=xt([Be(r,[0,0],[e,h]),_],1)}return[o,a,r]}),o=d[0],a=d[1],r=d[2],Ut([p,f,m])},c=0;ci&&(r=Be(r,[0,0],[e,i]),a=Be(a,[0,0],[i,i])),[r,a]})}var UR=U({qr_:WR});(function(n){n[n.NONE=0]="NONE",n[n.MEAN=1]="MEAN",n[n.SUM=2]="SUM",n[n.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(A.Reduction||(A.Reduction={}));function BR(n,t,e){e===void 0&&(e=A.Reduction.SUM_BY_NONZERO_WEIGHTS);var i=O(n,"losses","computeWeightedLoss"),r=null;t!=null&&(r=O(t,"weights","computeWeightedLoss"));var a=r==null?i:J(i,r);if(e===A.Reduction.NONE)return a;if(e===A.Reduction.SUM)return Ae(a);if(e===A.Reduction.MEAN){if(r==null)return Sa(a);var s=i.size/r.size,o=Ie(Ae(a),Ae(r));return s>1?Ie(o,we(s)):o}if(e===A.Reduction.SUM_BY_NONZERO_WEIGHTS){if(r==null)return Ie(Ae(a),we(i.size));var l=J(r,Rr(i.shape)),u=ue(Ae(Us(l,we(0))),"float32");return Ie(Ae(a),u)}throw Error("Unknown reduction: "+e)}var qn=U({computeWeightedLoss_:BR});function zR(n,t,e,i){i===void 0&&(i=A.Reduction.SUM_BY_NONZERO_WEIGHTS);var r=O(n,"labels","absoluteDifference"),a=O(t,"predictions","absoluteDifference"),s=null;e!=null&&(s=O(e,"weights","absoluteDifference")),Ue(r.shape,a.shape,"Error in absoluteDifference: ");var o=Vt(ge(r,a));return qn(o,s,i)}var _R=U({absoluteDifference_:zR});function PR(n,t,e,i,r){r===void 0&&(r=A.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=O(n,"labels","cosineDistance"),s=O(t,"predictions","cosineDistance"),o=null;i!=null&&(o=O(i,"weights","cosineDistance")),Ue(a.shape,s.shape,"Error in cosineDistance: ");var l=we(1),u=ge(l,Ae(J(a,s),e,!0));return qn(u,o,r)}var MR=U({cosineDistance_:PR});function HR(n,t,e,i){i===void 0&&(i=A.Reduction.SUM_BY_NONZERO_WEIGHTS);var r=O(n,"labels","hingeLoss"),a=O(t,"predictions","hingeLoss"),s=null;e!=null&&(s=O(e,"weights","hingeLoss")),Ue(r.shape,a.shape,"Error in hingeLoss: ");var o=we(1);r=ge(J(we(2),r),o);var l=Ia(ge(o,J(r,a)));return qn(l,s,i)}var VR=U({hingeLoss_:HR});function qR(n,t,e,i,r){i===void 0&&(i=1),r===void 0&&(r=A.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=O(n,"labels","huberLoss"),s=O(t,"predictions","huberLoss"),o=null;e!=null&&(o=O(e,"weights","huberLoss")),Ue(a.shape,s.shape,"Error in huberLoss: ");var l=we(i),u=Vt(ge(s,a)),c=Ws(u,l),h=ge(u,c),d=fe(J(we(.5),qe(c)),J(l,h));return qn(d,o,r)}var GR=U({huberLoss_:qR});function YR(n,t,e,i,r){i===void 0&&(i=1e-7),r===void 0&&(r=A.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=O(n,"labels","logLoss"),s=O(t,"predictions","logLoss"),o=null;e!=null&&(o=O(e,"weights","logLoss")),Ue(a.shape,s.shape,"Error in logLoss: ");var l=we(1),u=we(i),c=gt(J(a,_i(fe(s,u)))),h=J(ge(l,a),_i(fe(ge(l,s),u))),d=ge(c,h);return qn(d,o,r)}var KR=U({logLoss_:YR});function jR(n,t,e,i){i===void 0&&(i=A.Reduction.SUM_BY_NONZERO_WEIGHTS);var r=O(n,"labels","meanSquaredError"),a=O(t,"predictions","meanSquaredError"),s=null;e!=null&&(s=O(e,"weights","meanSquaredError")),Ue(r.shape,a.shape,"Error in meanSquaredError: ");var o=Ps(r,a);return qn(o,s,i)}var $R=U({meanSquaredError_:jR});function XR(n,t){var e=O(n,"labels","sigmoidCrossEntropyWithLogits"),i=O(t,"logits","sigmoidCrossEntropyWithLogits");Ue(e.shape,i.shape,"Error in sigmoidCrossEntropyWithLogits: ");var r=Ia(i),a=J(i,e),s=Nc(cn(gt(Vt(i))));return fe(ge(r,a),s)}function JR(n,t,e,i,r){i===void 0&&(i=0),r===void 0&&(r=A.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=O(n,"multiClassLabels","sigmoidCrossEntropy"),s=O(t,"logits","sigmoidCrossEntropy"),o=null;if(e!=null&&(o=O(e,"weights","sigmoidCrossEntropy")),Ue(a.shape,s.shape,"Error in sigmoidCrossEntropy: "),i>0){var l=we(i),u=we(1),c=we(.5);a=fe(J(a,ge(u,l)),J(c,l))}var h=XR(a,s);return qn(h,o,r)}var ZR=U({sigmoidCrossEntropy_:JR});function QR(n,t,e){if(e===void 0&&(e=-1),e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet "+("supported. Labels / logits was rank "+t.rank+" ")+("and dim was "+e));var i=Cn(function(r,a,s){var o=!0,l=Cc(a,[e],o),u=ge(ue(a,"float32"),l);s([r,u]);var c=gt(J(u,r)),h=Ae(c,[e]),d=function(p,f){var m=f[0],g=f[1],v=Zt(p.shape,[e]);return[J(V(p,v),ge(ue(m,"float32"),cn(g))),J(V(p,v),ge(cn(g),ue(m,"float32")))]};return{value:h,gradFunc:d}});return i(n,t)}function eO(n,t,e,i,r){i===void 0&&(i=0),r===void 0&&(r=A.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=O(n,"onehotLabels","softmaxCrossEntropy"),s=O(t,"logits","softmaxCrossEntropy"),o=null;if(e!=null&&(o=O(e,"weights","softmaxCrossEntropy")),Ue(a.shape,s.shape,"Error in softmaxCrossEntropy: "),i>0){var l=we(i),u=we(1),c=we(a.shape[1]);a=fe(J(a,ge(u,l)),Ie(l,c))}var h=QR(a,s);return qn(h,o,r)}var tO=U({softmaxCrossEntropy_:eO});var nO={fft:zs,ifft:Aa,rfft:_s,irfft:Mc},iO={hammingWindow:eR,hannWindow:Zg,frame:Qg,stft:rR},rO={flipLeftRight:lR,resizeNearestNeighbor:av,resizeBilinear:rv,rotateWithOffset:cR,cropAndResize:sR,nonMaxSuppression:dR,nonMaxSuppressionAsync:wR,nonMaxSuppressionWithScore:LR,nonMaxSuppressionWithScoreAsync:AR,nonMaxSuppressionPadded:NR,nonMaxSuppressionPaddedAsync:CR},aO={bandPart:DR,gramSchmidt:FR,qr:UR},sO={absoluteDifference:_R,computeWeightedLoss:qn,cosineDistance:MR,hingeLoss:VR,huberLoss:GR,logLoss:KR,meanSquaredError:$R,sigmoidCrossEntropy:ZR,softmaxCrossEntropy:tO};var li=function(n){zn(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.minimize=function(e,i,r){i===void 0&&(i=!1);var a=this.computeGradients(e,r),s=a.value,o=a.grads;if(r!=null){var l=r.map(function(u){return{name:u.name,tensor:o[u.name]}});this.applyGradients(l)}else this.applyGradients(o);return Ut(o),i?s:(s.dispose(),null)},Object.defineProperty(t.prototype,"iterations",{get:function(){return this.iterations_==null&&(this.iterations_=0),this.iterations_},enumerable:!0,configurable:!0}),t.prototype.incrementIterations=function(){this.iterations_=this.iterations+1},t.prototype.computeGradients=function(e,i){return pg(e,i)},t.prototype.dispose=function(){this.iterations_!=null&&Ut(this.iterations_)},t.prototype.saveIterations=function(){return de(this,void 0,void 0,function(){return pe(this,function(e){return this.iterations_==null&&(this.iterations_=0),[2,{name:"iter",tensor:we(this.iterations_,"int32")}]})})},t.prototype.getWeights=function(){return de(this,void 0,void 0,function(){return pe(this,function(e){throw new Error("getWeights() is not implemented for this optimizer yet.")})})},t.prototype.setWeights=function(e){return de(this,void 0,void 0,function(){return pe(this,function(i){throw new Error("setWeights() is not implemented for this optimizer class "+(""+this.getClassName()))})})},t.prototype.extractIterations=function(e){return de(this,void 0,void 0,function(){var i;return pe(this,function(r){switch(r.label){case 0:return i=this,[4,e[0].tensor.data()];case 1:return i.iterations_=r.sent()[0],[2,e.slice(1)]}})})},t}(Om);Object.defineProperty(li,Symbol.hasInstance,{value:function(n){return n.minimize!=null&&n.computeGradients!=null&&n.applyGradients!=null}});var Yc=function(n){zn(t,n);function t(e,i,r){r===void 0&&(r=null);var a=n.call(this)||this;return a.learningRate=e,a.rho=i,a.epsilon=r,a.accumulatedGrads=[],a.accumulatedUpdates=[],r==null&&(a.epsilon=z.backend.epsilon()),a}return t.prototype.applyGradients=function(e){var i=this,r=Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e);r.forEach(function(a,s){var o=z.registeredVariables[a],l=!1;i.accumulatedGrads[s]==null&&(i.accumulatedGrads[s]={originalName:a+"/accum_grad",variable:ft(function(){return Ee(o).variable(l)})}),i.accumulatedUpdates[s]==null&&(i.accumulatedUpdates[s]={originalName:a+"/accum_var",variable:ft(function(){return Ee(o).variable(l)})});var u=Array.isArray(e)?e[s].tensor:e[a];if(u==null)return;var c=i.accumulatedGrads[s].variable,h=i.accumulatedUpdates[s].variable;ft(function(){var d=fe(J(c,i.rho),J(qe(u),1-i.rho)),p=J(Ie(zt(fe(h,i.epsilon)),zt(fe(c,i.epsilon))),u),f=fe(J(h,i.rho),J(qe(p),1-i.rho));c.assign(d),h.assign(f);var m=fe(J(p,-i.learningRate),o);o.assign(m)})}),this.incrementIterations()},t.prototype.dispose=function(){this.accumulatedUpdates!=null&&(Ut(this.accumulatedGrads.map(function(e){return e.variable})),Ut(this.accumulatedUpdates.map(function(e){return e.variable})))},t.prototype.getWeights=function(){return de(this,void 0,void 0,function(){var e;return pe(this,function(i){switch(i.label){case 0:return e=this.accumulatedGrads.concat(this.accumulatedUpdates),[4,this.saveIterations()];case 1:return[2,[i.sent()].concat(e.map(function(r){return{name:r.originalName,tensor:r.variable}}))]}})})},t.prototype.setWeights=function(e){return de(this,void 0,void 0,function(){var i,r;return pe(this,function(a){switch(a.label){case 0:return[4,this.extractIterations(e)];case 1:return e=a.sent(),i=e.length/2,r=!1,this.accumulatedGrads=e.slice(0,i).map(function(s){return{originalName:s.name,variable:s.tensor.variable(r)}}),this.accumulatedUpdates=e.slice(i,i*2).map(function(s){return{originalName:s.name,variable:s.tensor.variable(r)}}),[2]}})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},t.fromConfig=function(e,i){return new e(i.learningRate,i.rho,i.epsilon)},t.className="Adadelta",t}(li);ai(Yc);var Kc=function(n){zn(t,n);function t(e,i){i===void 0&&(i=.1);var r=n.call(this)||this;return r.learningRate=e,r.initialAccumulatorValue=i,r.accumulatedGrads=[],r}return t.prototype.applyGradients=function(e){var i=this,r=Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e);r.forEach(function(a,s){var o=z.registeredVariables[a];if(i.accumulatedGrads[s]==null){var l=!1;i.accumulatedGrads[s]={originalName:a+"/accumulator",variable:ft(function(){return Ac(o.shape,i.initialAccumulatorValue).variable(l)})}}var u=Array.isArray(e)?e[s].tensor:e[a];if(u==null)return;var c=i.accumulatedGrads[s].variable;ft(function(){var h=fe(c,qe(u));c.assign(h);var d=fe(J(Ie(u,zt(fe(h,z.backend.epsilon()))),-i.learningRate),o);o.assign(d)})}),this.incrementIterations()},t.prototype.dispose=function(){this.accumulatedGrads!=null&&Ut(this.accumulatedGrads.map(function(e){return e.variable}))},t.prototype.getWeights=function(){return de(this,void 0,void 0,function(){return pe(this,function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(this.accumulatedGrads.map(function(i){return{name:i.originalName,tensor:i.variable}}))]}})})},t.prototype.setWeights=function(e){return de(this,void 0,void 0,function(){var i;return pe(this,function(r){switch(r.label){case 0:return[4,this.extractIterations(e)];case 1:return e=r.sent(),i=!1,this.accumulatedGrads=e.map(function(a){return{originalName:a.name,variable:a.tensor.variable(i)}}),[2]}})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},t.fromConfig=function(e,i){return new e(i.learningRate,i.initialAccumulatorValue)},t.className="Adagrad",t}(li);ai(Kc);var jc=function(n){zn(t,n);function t(e,i,r,a){a===void 0&&(a=null);var s=n.call(this)||this;return s.learningRate=e,s.beta1=i,s.beta2=r,s.epsilon=a,s.accumulatedFirstMoment=[],s.accumulatedSecondMoment=[],ft(function(){s.accBeta1=we(i).variable(),s.accBeta2=we(r).variable()}),a==null&&(s.epsilon=z.backend.epsilon()),s}return t.prototype.applyGradients=function(e){var i=this,r=Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e);ft(function(){var a=ge(1,i.accBeta1),s=ge(1,i.accBeta2);r.forEach(function(o,l){var u=z.registeredVariables[o],c=!1;i.accumulatedFirstMoment[l]==null&&(i.accumulatedFirstMoment[l]={originalName:o+"/m",variable:ft(function(){return Ee(u).variable(c)})}),i.accumulatedSecondMoment[l]==null&&(i.accumulatedSecondMoment[l]={originalName:o+"/v",variable:ft(function(){return Ee(u).variable(c)})});var h=Array.isArray(e)?e[l].tensor:e[o];if(h==null)return;var d=i.accumulatedFirstMoment[l].variable,p=i.accumulatedSecondMoment[l].variable,f=fe(J(d,i.beta1),J(h,1-i.beta1)),m=fe(J(p,i.beta2),J(qe(h),1-i.beta2)),g=Ie(f,a),v=Ie(m,s);d.assign(f),p.assign(m);var b=fe(J(Ie(g,fe(zt(v),i.epsilon)),-i.learningRate),u);u.assign(b)}),i.accBeta1.assign(J(i.accBeta1,i.beta1)),i.accBeta2.assign(J(i.accBeta2,i.beta2))}),this.incrementIterations()},t.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Ut(this.accumulatedFirstMoment.map(function(e){return e.variable})),this.accumulatedSecondMoment!=null&&Ut(this.accumulatedSecondMoment.map(function(e){return e.variable}))},t.prototype.getWeights=function(){return de(this,void 0,void 0,function(){var e;return pe(this,function(i){switch(i.label){case 0:return e=this.accumulatedFirstMoment.concat(this.accumulatedSecondMoment),[4,this.saveIterations()];case 1:return[2,[i.sent()].concat(e.map(function(r){return{name:r.originalName,tensor:r.variable}}))]}})})},t.prototype.setWeights=function(e){return de(this,void 0,void 0,function(){var i,r,a=this;return pe(this,function(s){switch(s.label){case 0:return[4,this.extractIterations(e)];case 1:return e=s.sent(),ft(function(){a.accBeta1.assign(Hn(a.beta1,a.iterations_+1)),a.accBeta2.assign(Hn(a.beta2,a.iterations_+1))}),i=e.length/2,r=!1,this.accumulatedFirstMoment=e.slice(0,i).map(function(o){return{originalName:o.name,variable:o.tensor.variable(r)}}),this.accumulatedSecondMoment=e.slice(i,i*2).map(function(o){return{originalName:o.name,variable:o.tensor.variable(r)}}),[2]}})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},t.fromConfig=function(e,i){return new e(i.learningRate,i.beta1,i.beta2,i.epsilon)},t.className="Adam",t}(li);ai(jc);var $c=function(n){zn(t,n);function t(e,i,r,a,s){a===void 0&&(a=null),s===void 0&&(s=0);var o=n.call(this)||this;return o.learningRate=e,o.beta1=i,o.beta2=r,o.epsilon=a,o.decay=s,o.accumulatedFirstMoment=[],o.accumulatedWeightedInfNorm=[],ft(function(){o.iteration=we(0).variable(),o.accBeta1=we(i).variable()}),a==null&&(o.epsilon=z.backend.epsilon()),o}return t.prototype.applyGradients=function(e){var i=this,r=Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e);ft(function(){var a=ge(1,i.accBeta1),s=Ie(-i.learningRate,fe(J(i.iteration,i.decay),1));r.forEach(function(o,l){var u=z.registeredVariables[o],c=!1;i.accumulatedFirstMoment[l]==null&&(i.accumulatedFirstMoment[l]={originalName:o+"/m",variable:Ee(u).variable(c)}),i.accumulatedWeightedInfNorm[l]==null&&(i.accumulatedWeightedInfNorm[l]={originalName:o+"/v",variable:Ee(u).variable(c)});var h=Array.isArray(e)?e[l].tensor:e[o];if(h==null)return;var d=i.accumulatedFirstMoment[l].variable,p=i.accumulatedWeightedInfNorm[l].variable,f=fe(J(d,i.beta1),J(h,1-i.beta1)),m=J(p,i.beta2),g=Vt(h),v=Cr(m,g);d.assign(f),p.assign(v);var b=fe(J(Ie(s,a),Ie(f,fe(v,i.epsilon))),u);u.assign(b)}),i.iteration.assign(fe(i.iteration,1)),i.accBeta1.assign(J(i.accBeta1,i.beta1))}),this.incrementIterations()},t.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Ut(this.accumulatedFirstMoment.map(function(e){return e.variable})),this.accumulatedWeightedInfNorm!=null&&Ut(this.accumulatedWeightedInfNorm.map(function(e){return e.variable}))},t.prototype.getWeights=function(){return de(this,void 0,void 0,function(){return pe(this,function(e){throw new Error("getWeights() is not implemented for Adamax yet.")})})},t.prototype.setWeights=function(e){return de(this,void 0,void 0,function(){return pe(this,function(i){throw new Error("setWeights() is not implemented for Adamax yet.")})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},t.fromConfig=function(e,i){return new e(i.learningRate,i.beta1,i.beta2,i.epsilon,i.decay)},t.className="Adamax",t}(li);ai($c);var js=function(n){zn(t,n);function t(e){var i=n.call(this)||this;return i.learningRate=e,i.setLearningRate(e),i}return t.prototype.applyGradients=function(e){var i=this,r=Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e);r.forEach(function(a,s){var o=Array.isArray(e)?e[s].tensor:e[a];if(o==null)return;var l=z.registeredVariables[a];ft(function(){var u=fe(J(i.c,o),l);l.assign(u)})}),this.incrementIterations()},t.prototype.setLearningRate=function(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=km(we(-e))},t.prototype.dispose=function(){this.c.dispose()},t.prototype.getWeights=function(){return de(this,void 0,void 0,function(){return pe(this,function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()]]}})})},t.prototype.setWeights=function(e){return de(this,void 0,void 0,function(){return pe(this,function(i){switch(i.label){case 0:return[4,this.extractIterations(e)];case 1:if(e=i.sent(),e.length!==0)throw new Error("SGD optimizer does not have settable weights.");return[2]}})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate}},t.fromConfig=function(e,i){return new e(i.learningRate)},t.className="SGD",t}(li);ai(js);var Xc=function(n){zn(t,n);function t(e,i,r){r===void 0&&(r=!1);var a=n.call(this,e)||this;return a.learningRate=e,a.momentum=i,a.useNesterov=r,a.accumulations=[],a.m=we(a.momentum),a}return t.prototype.applyGradients=function(e){var i=this,r=Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e);r.forEach(function(a,s){var o=z.registeredVariables[a];if(i.accumulations[s]==null){var l=!1;i.accumulations[s]={originalName:a+"/momentum",variable:ft(function(){return Ee(o).variable(l)})}}var u=i.accumulations[s].variable,c=Array.isArray(e)?e[s].tensor:e[a];if(c==null)return;ft(function(){var h,d=fe(J(i.m,u),c);i.useNesterov?h=fe(J(i.c,fe(c,J(d,i.m))),o):h=fe(J(i.c,d),o),u.assign(d),o.assign(h)})}),this.incrementIterations()},t.prototype.dispose=function(){this.m.dispose(),this.accumulations!=null&&Ut(this.accumulations.map(function(e){return e.variable}))},t.prototype.setMomentum=function(e){this.momentum=e},t.prototype.getWeights=function(){return de(this,void 0,void 0,function(){return pe(this,function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(this.accumulations.map(function(i){return{name:i.originalName,tensor:i.variable}}))]}})})},t.prototype.setWeights=function(e){return de(this,void 0,void 0,function(){var i;return pe(this,function(r){switch(r.label){case 0:return[4,this.extractIterations(e)];case 1:return e=r.sent(),i=!1,this.accumulations=e.map(function(a){return{originalName:a.name,variable:a.tensor.variable(i)}}),[2]}})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},t.fromConfig=function(e,i){return new e(i.learningRate,i.momentum,i.useNesterov)},t.className="Momentum",t}(js);ai(Xc);var Jc=function(n){zn(t,n);function t(e,i,r,a,s){i===void 0&&(i=.9),r===void 0&&(r=0),a===void 0&&(a=null),s===void 0&&(s=!1);var o=n.call(this)||this;if(o.learningRate=e,o.decay=i,o.momentum=r,o.epsilon=a,o.accumulatedMeanSquares=[],o.accumulatedMoments=[],o.accumulatedMeanGrads=[],o.centered=s,a==null&&(o.epsilon=z.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.");return o}return t.prototype.applyGradients=function(e){var i=this,r=Array.isArray(e)?e.map(function(a){return a.name}):Object.keys(e);r.forEach(function(a,s){var o=z.registeredVariables[a],l=!1;i.accumulatedMeanSquares[s]==null&&(i.accumulatedMeanSquares[s]={originalName:a+"/rms",variable:ft(function(){return Ee(o).variable(l)})}),i.accumulatedMoments[s]==null&&(i.accumulatedMoments[s]={originalName:a+"/momentum",variable:ft(function(){return Ee(o).variable(l)})}),i.accumulatedMeanGrads[s]==null&&i.centered&&(i.accumulatedMeanGrads[s]={originalName:a+"/mg",variable:ft(function(){return Ee(o).variable(l)})});var u=Array.isArray(e)?e[s].tensor:e[a];if(u==null)return;var c=i.accumulatedMeanSquares[s].variable,h=i.accumulatedMoments[s].variable;ft(function(){var d=fe(J(c,i.decay),J(qe(u),1-i.decay));if(i.centered){var p=i.accumulatedMeanGrads[s].variable,f=fe(J(p,i.decay),J(u,1-i.decay)),m=Ie(J(u,i.learningRate),zt(ge(d,fe(qe(f),i.epsilon)))),g=fe(J(h,i.momentum),m);c.assign(d),p.assign(f),h.assign(g);var v=ge(o,g);o.assign(v)}else{var b=fe(J(c,i.decay),J(qe(u),1-i.decay)),g=fe(J(h,i.momentum),Ie(J(u,i.learningRate),zt(fe(b,i.epsilon))));c.assign(b),h.assign(g);var v=ge(o,g);o.assign(v)}})}),this.incrementIterations()},t.prototype.dispose=function(){this.accumulatedMeanSquares!=null&&Ut(this.accumulatedMeanSquares.map(function(e){return e.variable})),this.accumulatedMeanGrads!=null&&this.centered&&Ut(this.accumulatedMeanGrads.map(function(e){return e.variable})),this.accumulatedMoments!=null&&Ut(this.accumulatedMoments.map(function(e){return e.variable}))},t.prototype.getWeights=function(){return de(this,void 0,void 0,function(){var e;return pe(this,function(i){switch(i.label){case 0:return e=this.accumulatedMeanSquares.concat(this.accumulatedMoments),this.centered&&e.push.apply(e,this.accumulatedMeanGrads),[4,this.saveIterations()];case 1:return[2,[i.sent()].concat(e.map(function(r){return{name:r.originalName,tensor:r.variable}}))]}})})},t.prototype.setWeights=function(e){return de(this,void 0,void 0,function(){var i,r;return pe(this,function(a){switch(a.label){case 0:return[4,this.extractIterations(e)];case 1:return e=a.sent(),i=this.centered?e.length/3:e.length/2,r=!1,this.accumulatedMeanSquares=e.slice(0,i).map(function(s){return{originalName:s.name,variable:s.tensor.variable(r)}}),this.accumulatedMoments=e.slice(i,i*2).map(function(s){return{originalName:s.name,variable:s.tensor.variable(r)}}),this.centered&&(this.accumulatedMeanGrads=e.slice(i*2,i*3).map(function(s){return{originalName:s.name,variable:s.tensor.variable(r)}})),[2]}})})},t.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},t.fromConfig=function(e,i){return new e(i.learningRate,i.decay,i.momentum,i.epsilon,i.centered)},t.className="RMSProp",t}(li);ai(Jc);var Yi=function(){function n(){}return n.sgd=function(t){return new js(t)},n.momentum=function(t,e,i){return i===void 0&&(i=!1),new Xc(t,e,i)},n.rmsprop=function(t,e,i,r,a){return e===void 0&&(e=.9),i===void 0&&(i=0),r===void 0&&(r=null),a===void 0&&(a=!1),new Jc(t,e,i,r,a)},n.adam=function(t,e,i,r){return t===void 0&&(t=.001),e===void 0&&(e=.9),i===void 0&&(i=.999),r===void 0&&(r=null),new jc(t,e,i,r)},n.adadelta=function(t,e,i){return t===void 0&&(t=.001),e===void 0&&(e=.95),i===void 0&&(i=null),new Yc(t,e,i)},n.adamax=function(t,e,i,r,a){return t===void 0&&(t=.002),e===void 0&&(e=.9),i===void 0&&(i=.999),r===void 0&&(r=null),a===void 0&&(a=0),new $c(t,e,i,r,a)},n.adagrad=function(t,e){return e===void 0&&(e=.1),new Kc(t,e)},n}();var oO={sgd:Yi.sgd,momentum:Yi.momentum,adadelta:Yi.adadelta,adagrad:Yi.adagrad,rmsprop:Yi.rmsprop,adamax:Yi.adamax,adam:Yi.adam};var lO=function(){return typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:function(n){return n()}}();function uO(){return new Promise(function(n){return lO(function(){return n()})})}function cO(n,t,e){var i=e*(typeof n=="number"?n:n[0]),r=t*(typeof n=="number"?n:n[1]);return[i,r]}function hO(n,t,e,i){i===void 0&&(i=!0);var r=[];if(i)r=r.concat(t.slice(0)),r.push(n[0]/e),r=r.concat(n.slice(1));else{r=r.concat(n[0]);for(var a=t.length,s=0;s=t*2+1||r%2===1?s.push(r):a.push(r);i.push.apply(i,a),i.push(0),i.push.apply(i,s)}return i}function pO(n,t,e,i){i===void 0&&(i=!0);var r=[];i?r.push(n[0]/e):r.push(n[0]*e);for(var a=1;a0&&(o=Ae(o,l)),V(o,e.shape)},s=function(){var o=n,l=mt(i.shape,r);return l.length>0&&(o=Ae(o,l)),V(o,i.shape)};return{a,b:s}}};var qO={kernelName:el,saveAllInputs:!0,gradFunc:function(n,t){var e={};return t.forEach(function(i,r){e[r]=function(){return n.clone()}}),e}};var GO={kernelName:tl,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return Ee(e)}}}};var YO={kernelName:nl,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return Ee(e)}}}};var KO={kernelName:il,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return Ie(n,zt(ge(we(1),qe(ue(e,"float32")))))}}}};var jO={kernelName:rl,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){var i=zt(fe(we(1),qe(ue(e,"float32"))));return Ie(n,i)}}}};var $O={kernelName:ol,inputsToSave:["a","b"],gradFunc:function(n,t){var e=t[0],i=t[1],r=Qe(e.shape,i.shape),a=function(){var o=fe(qe(e),qe(i)),l=J(n,Ie(i,o)),u=mt(e.shape,r);return u.length>0&&(l=Ae(l,u)),V(l,e.shape)},s=function(){var o=fe(qe(e),qe(i)),l=gt(J(n,Ie(e,o))),u=mt(i.shape,r);return u.length>0&&(l=Ae(l,u)),V(l,i.shape)};return{a,b:s}}};var XO={kernelName:al,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return Ie(n,fe(qe(ue(e,"float32")),1))}}}};var JO={kernelName:sl,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return Ie(n,ge(we(1),qe(ue(e,"float32"))))}}}};function ZO(n,t,e,i,r,a,s){r===void 0&&(r=[1,1,1]);var o=O(n,"dy","avgPool3dBackprop"),l=O(t,"input","avgPool3dBackprop"),u=o,c=l,h=!1;l.rank===4&&(h=!0,u=V(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),c=V(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),D(u.rank===5,function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+(u.rank+".")}),D(c.rank===5,function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+(c.rank+".")}),D(Bt(i,r),function(){return"Error in avgPool3dBackprop: Either strides or dilations "+("must be 1. Got strides "+i+" and dilations '"+r+"'")}),s!=null&&D(it(a),function(){return"Error in maxPool3dBackprop: pad must be an integer when "+("using, dimRoundingMode "+s+" but got pad "+a+".")});var d=function(g){var v=va(c.shape,e,i,r,a,s);return g.avgPool3dBackprop(u,c,v)},p={dy:u,input:c},f={filterSize:e,strides:i,dilations:r,pad:a,dimRoundingMode:s},m=z.runKernelFunc(d,p,null,Wp,f);return h?V(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var QO=U({avgPool3dBackprop_:ZO});var eE={kernelName:ul,inputsToSave:["x"],gradFunc:function(n,t,e){var i=t[0],r=e,a=r.filterSize,s=r.strides,o=r.dilations,l=r.pad,u=r.dimRoundingMode,c=o??[1,1,1];return{x:function(){return QO(n,i,a,s,c,l,u)}}}};function tE(n,t,e,i,r){var a=O(n,"dy","avgPoolBackprop"),s=O(t,"input","avgPoolBackprop");D(s.rank===a.rank,function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+a.rank+")"});var o=s,l=a,u=!1;s.rank===3&&(u=!0,o=V(s,[1,s.shape[0],s.shape[1],s.shape[2]]),l=V(a,[1,a.shape[0],a.shape[1],a.shape[2]])),D(l.rank===4,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+(l.rank+".")}),D(o.rank===4,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+(o.rank+".")});var c=function(f){var m=Ar(o.shape,e,i,1,r);return f.avgPoolBackprop(l,o,m)},h={dy:l,input:o},d={filterSize:e,strides:i,pad:r},p=z.runKernelFunc(c,h,null,Fp,d);return u?V(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var nE=U({avgPoolBackprop_:tE});var iE={kernelName:ll,inputsToSave:["x"],gradFunc:function(n,t,e){var i=t[0],r=e,a=r.filterSize,s=r.strides,o=r.pad;return{x:function(){return nE(n,i,a,s,o)}}}};var rE={kernelName:cl,inputsToSave:["a","b"],gradFunc:function(n,t,e){var i=t,r=i[0],a=i[1],s=e,o=s.transposeA,l=s.transposeB;return!o&&!l?{a:function(){return Fe(n,a,!1,!0)},b:function(){return Fe(r,n,!0,!1)}}:!o&&l?{a:function(){return Fe(n,a,!1,!1)},b:function(){return Fe(n,r,!0,!1)}}:o&&!l?{a:function(){return Fe(a,n,!1,!0)},b:function(){return Fe(r,n,!1,!1)}}:{a:function(){return Fe(a,n,!0,!0)},b:function(){return Fe(n,r,!0,!0)}}}};var aE={kernelName:hl,gradFunc:function(n,t,e){var i=e,r=i.blockShape,a=i.crops;return{x:function(){return Bs(n,r,a)}}}};var sE={kernelName:dl,gradFunc:function(n,t,e){for(var i=e,r=i.inputShape,a=i.shape,s=Array.from(a),o=r.length-1;o>=0;o--)if(r[o]===a[o])s[o]=1;else if(r[o]!==1)throw new Error("broadcastTo(): ["+r+"] cannot be broadcast to ["+a+"].");for(var l=[],o=0;o1&&l.push(o);return{x:function(){return Ae(n,l,!0)}}}};var oE={kernelName:ls,gradFunc:function(n){return{x:function(){return n.clone()}}}};var lE={kernelName:pl,gradFunc:function(n){return{x:function(){return Ee(n)}}}};var uE={kernelName:fl,inputsToSave:["x"],gradFunc:function(n,t,e){var i=t[0],r=e,a=r.clipValueMin,s=r.clipValueMax;return{x:function(){return un(Mi(Bi(i,a),zi(i,s)),n,Ee(n))}}}};var cE={kernelName:ml,saveAllInputs:!0,gradFunc:function(n,t,e){var i=t.map(function(l){return l.shape}),r=e.axis,a=Ze(r,t[0].shape)[0],s=i.map(function(l){return l[a]}),o=Dr(n,s,a);return o.map(function(l){return function(){return l}})}};var hE={kernelName:gl,inputsToSave:["x","filter"],gradFunc:function(n,t,e){var i=t,r=i[0],a=i[1],s=e,o=s.dilations,l=s.strides,u=s.pad,c=s.dataFormat;return D(si(o),function(){return"Error in gradient of conv2D: dilation rates greater than 1 "+("are not yet supported in gradients. Got dilations '"+o+"'")}),{x:function(){return wc(r.shape,n,a,l,u,c)},filter:function(){return qc(r,n,a.shape,l,u,c)}}}};var dE={kernelName:vl,inputsToSave:["dy","filter"],gradFunc:function(n,t,e){var i=t,r=i[0],a=i[1],s=e,o=s.strides,l=s.pad,u=s.dataFormat,c=s.dimRoundingMode;return{dy:function(){return Nr(n,a,o,l,u,1,c)},filter:function(){return qc(n,r,a.shape,o,l,u,c)}}}};function pE(n,t,e,i,r){var a=n;n.rank===4&&(a=V(n,[1,n.shape[0],n.shape[1],n.shape[2],n.shape[3]]));var s=t;s.rank===4&&(s=V(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),D(a.rank===5,function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+(a.shape+".")}),D(s.rank===5,function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+(s.shape+".")}),D(e.length===5,function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+(e+".")}),D(a.shape[4]===e[3],function(){return"Error in conv3dDerFilter: depth of input "+a.shape[4]+") must "+("match input depth in filter ("+e[3]+".")}),D(s.shape[4]===e[4],function(){return"Error in conv3dDerFilter: depth of dy ("+s.shape[4]+") must "+("match output depth for filter ("+e[4]+").")});var o=function(c){var h=1,d=ga(a.shape,e,i,h,r);return c.conv3dDerFilter(a,s,d)},l={x:a,y:s},u={strides:i,pad:r};return z.runKernelFunc(o,l,null,zp,u)}var fE=U({conv3DBackpropFilter_:pE});var mE={kernelName:yl,inputsToSave:["x","filter"],gradFunc:function(n,t,e){var i=e,r=i.dilations,a=i.strides,s=i.pad;D(si(r),function(){return"Error in gradient of conv3D: dilation rates greater than 1 are "+("not yet supported in gradients. Got dilations '"+r+"'")});var o=t[0],l=t[1];return{x:function(){return Qm(o.shape,n,l,a,s)},filter:function(){return fE(o,n,l.shape,a,s)}}}};var gE={kernelName:bl,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return J(gt(_c(ue(e,"float32"))),n)}}}};var vE={kernelName:wl,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return J(Pc(ue(e,"float32")),n)}}}};var yE={kernelName:Sl,inputsToSave:["x"],gradFunc:function(n,t,e){var i=t[0],r=e,a=r.axis,s=r.exclusive,o=r.reverse;return{x:function(){var l=Qt([a],i.rank),u=Lc(n,a,s,!o);return l!=null&&(u=lt(u,l)),u}}}};var bE={kernelName:Ll,inputsToSave:["x","filter"],gradFunc:function(n,t,e){var i=e,r=i.dilations,a=i.strides,s=i.pad,o=i.dimRoundingMode,l=r??[1,1];D(si(l),function(){return"Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations "+("'"+l+"'")});var u=t,c=u[0],h=u[1];D(c.rank===4,function(){return"Error in gradient of depthwiseConv2dNative: input must be "+("rank 4, but got rank "+c.rank+".")}),D(h.rank===4,function(){return"Error in gradient of depthwiseConv2dNative: filter must be "+("rank 4, but got rank "+h.rank+".")}),D(c.shape[3]===h.shape[2],function(){return"Error in gradient of depthwiseConv2d: number of input "+("channels ("+c.shape[3]+") must match the inChannels dimension ")+("in filter "+h.shape[2]+".")}),D(Bt(a,l),function(){return"Error in gradient of depthwiseConv2d: Either strides or "+("dilations must be 1. Got strides "+a+" and dilations ")+("'"+l+"'.")}),o!=null&&D(it(s),function(){return"Error in depthwiseConv2d: pad must be an integer when using, "+("dimRoundingMode "+o+" but got pad "+s+".")});var d=xn(c.shape,h.shape,a,l,s,o,!0);return{x:function(){return Jg(c.shape,n,h,d)},filter:function(){return Xg(c,n,h.shape,d)}}}};var wE={kernelName:Il,inputsToSave:["x","filter"],gradFunc:function(n,t,e){var i=t,r=i[0],a=i[1],s={x:r,filter:a,dy:n},o={x:r,filter:a,dy:n};return{x:function(){return z.runKernel(Gp,s,e)},filter:function(){return z.runKernel(Yp,o,e)}}}};var SE={kernelName:Al,inputsToSave:["a","b"],gradFunc:function(n,t){var e=t[0],i=t[1],r=Qe(e.shape,i.shape),a=function(){var o=Ie(n,ue(i,"float32")),l=mt(e.shape,r);return l.length>0?V(Ae(o,l),e.shape):o},s=function(){var o=J(n,ue(e,"float32")),l=mt(i.shape,r);l.length>0&&(o=V(Ae(o,l),i.shape));var u=qe(i);return gt(Ie(o,ue(u,"float32")))};return{a,b:s}}};var LE={kernelName:Tl,outputsToSave:[!0],gradFunc:function(n,t){var e=t[0],i=function(a){return a.eluDer(n,e)},r={dy:n,y:e};return{x:function(){return z.runKernelFunc(i,r,null,Kp)}}}};var IE={kernelName:Nl,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0],i=J(cn(gt(qe(e))),2/Math.sqrt(Math.PI));return{x:function(){return J(n,i)}}}};var AE={kernelName:xl,outputsToSave:[!0],gradFunc:function(n,t){var e=t[0];return{x:function(){return J(n,e)}}}};var TE={kernelName:Cl,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return J(n,cn(e))}}}};var NE={kernelName:Rl,gradFunc:function(n){return{x:function(){return Ee(n)}}}};var xE={kernelName:Ol,inputsToSave:["a","b"],gradFunc:function(n,t){var e=t[0],i=t[1],r=Qe(e.shape,i.shape),a=function(){var o=Ie(n,ue(i,"float32")),l=mt(e.shape,r);return l.length>0?V(Ae(o,l),e.shape):o},s=function(){var o=J(n,ue(e,"float32")),l=mt(i.shape,r);l.length>0&&(o=V(Ae(o,l),i.shape));var u=qe(i);return gt(Ie(o,ue(u,"float32")))};return{a,b:s}}};var CE={kernelName:El,inputsToSave:["x","mean","variance","scale"],gradFunc:function(n,t,e){var i=e.varianceEpsilon,r=t[0],a=t[1],s=t[2],o=t[3],l=o??we(1),u=mt(a.shape,r.shape),c=[];if(a.rank===1){for(var h=0;h0?V(Ae(n,o),e.shape):n},s=function(){var o=J(n,gt(Cs(Ie(e,i)))),l=mt(i.shape,r);return l.length>0?V(Ae(o,l),i.shape):o};return{a,b:s}}};var JE={kernelName:$l,inputsToSave:["a","b"],gradFunc:function(n,t){var e=t[0],i=t[1],r=Qe(e.shape,i.shape),a=function(){var o=J(n,ue(i,"float32")),l=mt(e.shape,r);return l.length>0?V(Ae(o,l),e.shape):o},s=function(){var o=J(n,ue(e,"float32")),l=mt(i.shape,r);return l.length>0?V(Ae(o,l),i.shape):o};return{a,b:s}}};var ZE={kernelName:Xl,gradFunc:function(n){return{x:function(){return gt(n)}}}};var QE={kernelName:Zl,inputsToSave:["indices"],gradFunc:function(n,t){var e=t[0];return{indices:function(){return Mn(e.shape,"float32")}}}};var eD={kernelName:Jl,gradFunc:function(n){return{x:function(){return Ee(n)}}}};var pv={kernelName:Ql,inputsToSave:["x"],gradFunc:function(n,t,e){var i=t[0],r=e.paddings,a=r.map(function(s){return s[0]});return{x:function(){return Be(n,a,i.shape)}}}};var tD={kernelName:eu,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:function(n,t){var e=t[0],i=t[1],r=t[2],a=e,s=i,o=Qe(a.shape,s.shape),l=function(){var c=ue(s,"float32"),h=J(n,J(c,Hn(a,ge(c,we(1))))),d=mt(a.shape,o);return d.length>0&&(h=Ae(h,d)),V(h,a.shape)},u=function(){var c=oi(a,0),h=un(c,_i(a),Ee(a)),d=J(n,J(r,h)),p=mt(s.shape,o);return p.length>0&&(d=Ae(d,p)),V(d,s.shape)};return{a:l,b:u}}};var nD={kernelName:tu,inputsToSave:["x","alpha"],gradFunc:function(n,t){var e=t[0],i=t[1],r=oi(e,0);return{x:function(){return un(r,n,J(n,i))},alpha:function(){var a=un(r,Ee(n),J(n,e)),s=mt(i.shape,n.shape);return s.length>0&&(a=Ae(a,s)),V(a,i.shape)}}}};var iD={kernelName:nu,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return Ie(n,gt(qe(e)))}}}};var rD={kernelName:ou,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0],i=J(zi(e,6),kr(e));return{x:function(){return J(n,ue(i,"float32"))}}}};var aD={kernelName:iu,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return J(n,ue(kr(e),"float32"))}}}};var sD={kernelName:ru,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return V(n,e.shape)}}}};var oD={kernelName:su,inputsToSave:["images"],gradFunc:function(n,t,e){var i=t[0],r=function(o){var l=e.alignCorners;return o.resizeBilinearBackprop(n,i,l)},a={images:i},s=function(){return z.runKernelFunc(r,a,null,Sf,e)};return{images:s}}};var lD={kernelName:au,inputsToSave:["images"],gradFunc:function(n,t,e){var i=t[0],r=function(o){var l=e.alignCorners;return o.resizeNearestNeighborBackprop(n,i,l)},a={images:i},s=function(){return z.runKernelFunc(r,a,null,wf,e)};return{images:s}}};var uD={kernelName:lu,gradFunc:function(n,t,e){var i=e.dims,r=Ze(i,n.shape);return{x:function(){return Vn(n,r)}}}};var cD={kernelName:uu,gradFunc:function(n){return{x:function(){return Ee(n)}}}};var hD={kernelName:cu,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return gt(Ie(n,J(Hn(e,1.5),2)))}}}};var dD={kernelName:hu,inputsToSave:["condition"],gradFunc:function(n,t){var e=t[0];return{condition:function(){return ue(Ee(e),"float32")},t:function(){return J(n,ue(e,n.dtype))},e:function(){return J(n,ue(ks(e),n.dtype))}}}};var pD={kernelName:du,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){var i=oi(e,we(0)),r=we(ov),a=we(lv),s=J(n,a),o=J(J(n,r),cn(ue(e,"float32")));return un(i,s,o)}}}};var fD={kernelName:vu,outputsToSave:[!0],gradFunc:function(n,t){var e=t[0];return{x:function(){return J(n,J(e,ge(we(1),e)))}}}};var mD={kernelName:gu,gradFunc:function(n){return{x:function(){return Ee(n)}}}};var gD={kernelName:fu,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return J(xs(ue(e,"float32")),n)}}}};var vD={kernelName:mu,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return J(Sc(ue(e,"float32")),n)}}}};var yD={kernelName:pu,inputsToSave:["x"],gradFunc:function(n,t,e){for(var i=t[0],r=e,a=r.begin,s=r.size,o=i.shape,l=hc(i,a,s),u=l[0],c=l[1],h=[],d=0;d0&&(o=Ae(o,l)),V(o,e.shape)},s=function(){var o=n,l=mt(i.shape,r);return l.length>0&&(o=Ae(o,l)),V(gt(o),i.shape)};return{a,b:s}}};var ND={kernelName:wu,inputsToSave:["x"],gradFunc:function(n,t,e){var i=t[0],r=i.shape.slice(),a=e.axis,s=Ze(a,i.shape);s.forEach(function(u){r[u]=1});var o=V(n,r),l=J(o,Rr(i.shape,"float32"));return{x:function(){return l}}}};var xD={kernelName:Nu,inputsToSave:["x"],gradFunc:function(n,t){var e=t[0];return{x:function(){return Ie(n,qe(xs(e)))}}}};var CD={kernelName:xu,outputsToSave:[!0],gradFunc:function(n,t){var e=t[0];return{x:function(){return J(ge(we(1),qe(e)),n)}}}};var RD={kernelName:Cu,inputsToSave:["x"],gradFunc:function(n,t,e){var i=t[0],r=e.reps,a=function(){var s=Ee(i);if(i.rank===1)for(var o=0;o{"use strict";Object.defineProperty($e,"__esModule",{value:!0});var y=Ki();var Qc=function(n,t){return Qc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,i){e.__proto__=i}||function(e,i){for(var r in i)i.hasOwnProperty(r)&&(e[r]=i[r])},Qc(n,t)};function Q(n,t){Qc(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}var qt=function(){return qt=Object.assign||function(t){for(var e,i=1,r=arguments.length;i0&&a[a.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!a||u[1]>a[0]&&u[1]t?1:0}function $s(n,t){return-1*zD(n,t)}function ci(n){if(n==null)return n;for(var t=[],e=0,i=n;e=0),On(i>=e),Array.isArray(n)&&n.length>=e&&n.length<=i&&n.every(function(r){return typeof r===t})}function At(n,t){Array.isArray(n)?(y.util.assert(n.length>0,function(){return t+" is unexpectedly an empty array."}),n.forEach(function(e,i){return At(e,"element "+(i+1)+" of "+t)})):y.util.assert(Number.isInteger(n)&&n>0,function(){return"Expected "+t+" to be a positive integer, but got "+(yv(n)+".")})}function yv(n){return n===null?"null":Array.isArray(n)?"["+n.map(function(t){return yv(t)}).join(",")+"]":typeof n=="string"?'"'+n+'"':""+n}function PD(n,t){var e=y.util.now(),i,r=function(){for(var a=[],s=0;s0){var e=n+"_"+t;return Ur.set(e,1),e}else return n}var JD=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Cv(n){return!!n.match(JD)}function ZD(n){return n===parseInt(n.toString(),10)}function hi(n,t,e){t==null&&(t=0),e==null&&(e=n.length);for(var i=1,r=t;r= 2"+(" but got x shape = "+n.shape+" and y shape = "+t.shape));if(t.rank>=3){var r=n.shape.slice(-1)[0],a=t.shape.slice(-2)[0];if(r!==a)throw new Te("If rank y >= 3, then the second last dim"+(" of y must equal the last dim of x but got x shape = "+n.shape+" and ")+(" y shape = "+t.shape))}if(n.rank===2&&t.rank===2){var s=!1,o=!1;return y.fused.matMul({a:n,b:t,transposeA:s,transposeB:o,bias:i?lh(n.rank,i,dn()):null,activation:e})}else{var l=n.shape.slice(),u=l.pop();n=n.reshape([-1,u]);var c=t.shape.slice(),h=c.pop(),a=c.pop(),d=c.concat([h]),p=Array.from({length:t.rank},function(b,S){return S===0?t.rank-2:S<=t.rank-2?S-1:S});t=t.transpose(p).reshape([a,-1]);var f=l.concat(d),s=!1,o=!1;return y.fused.matMul({a:n,b:t,transposeA:s,transposeB:o,bias:i?lh(n.rank,i,dn()):null,activation:e}).reshape(f)}}function kv(n,t,e){return y.tidy(function(){return Array.isArray(t)?t=y.tensor1d(t,"int32"):t=t.toInt(),y.gather(n,t,e)})}function Ea(n){return y.mul(n,n)}function lh(n,t,e){var i=t.shape;if(t.rank!==1&&t.rank!==n)throw new M("Unexpected bias dimensions: "+t.rank+("; expected it to be 1 or "+n));if(n===5){if(e==="channelsFirst")return i.length===1?t.reshape([1,i[0],1,1,1]):t.reshape([1,i[3],i[0],i[1],i[2]]);if(e==="channelsLast")return i.length===1?t.reshape([1,1,1,1,i[0]]):t.reshape([1].concat(i))}else if(n===4){if(e==="channelsFirst")return i.length===1?t.reshape([1,i[0],1,1]):t.reshape([1,i[2],i[0],i[1]]);if(e==="channelsLast")return i.length===1?t.reshape([1,1,1,i[0]]):t.reshape([1].concat(i))}else if(n===3){if(e==="channelsFirst")return i.length===1?t.reshape([1,i[0],1]):t.reshape([1,i[1],i[0]]);if(e==="channelsLast")return i.length===1?t.reshape([1,1,i[0]]):t.reshape([1].concat(i))}else if(n<3)return t;throw new M("Unsupported input rank by biasAdd: "+t.rank)}function Dn(n,t,e){return y.tidy(function(){return e==null&&(e=dn()),ct(e),n.add(lh(n.rank,t,e))})}function nk(n,t){if(t===void 0&&(t=1),t!==1)throw new Te("Support for alpha values other than 1 ("+t+") is not implemented yet.");return y.elu(n)}function ik(n){return y.tidy(function(){return y.div(n,y.abs(n).add(1))})}function Fv(n,t,e,i){return y.tidy(function(){return y.dropout(n,t,e,i)})}function rk(n){return y.tidy(function(){var t=y.add(.5,y.mul(.2,n));return y.clipByValue(t,0,1)})}function Da(n,t,e){return e===void 0&&(e=!1),e?n():t()}var ak=["fanIn","fanOut","fanAvg"],sk=["normal","uniform","truncatedNormal"];function ok(n){Wr(ak,"FanMode",n)}function lk(n){Wr(sk,"Distribution",n)}var on=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.fromConfigUsesCustomObjects=function(){return!1},t.prototype.getConfig=function(){return{}},t}(y.serialization.Serializable),Wv=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.apply=function(e,i){return y.zeros(e,i)},t.className="Zeros",t}(on);y.serialization.registerClass(Wv);var uh=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.apply=function(e,i){return y.ones(e,i)},t.className="Ones",t}(on);y.serialization.registerClass(uh);var Uv=function(n){Q(t,n);function t(e){var i=n.call(this)||this;if(typeof e!="object")throw new M("Expected argument of type ConstantConfig but got "+e);if(e.value===void 0)throw new M("config must have value set but got "+e);return i.value=e.value,i}return t.prototype.apply=function(e,i){var r=this;return y.tidy(function(){return y.mul(y.scalar(r.value),y.ones(e,i))})},t.prototype.getConfig=function(){return{value:this.value}},t.className="Constant",t}(on);y.serialization.registerClass(Uv);var Bv=function(n){Q(t,n);function t(e){var i=n.call(this)||this;return i.DEFAULT_MINVAL=-.05,i.DEFAULT_MAXVAL=.05,i.minval=e.minval||i.DEFAULT_MINVAL,i.maxval=e.maxval||i.DEFAULT_MAXVAL,i.seed=e.seed,i}return t.prototype.apply=function(e,i){return y.randomUniform(e,this.minval,this.maxval,i)},t.prototype.getConfig=function(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}},t.className="RandomUniform",t}(on);y.serialization.registerClass(Bv);var zv=function(n){Q(t,n);function t(e){var i=n.call(this)||this;return i.DEFAULT_MEAN=0,i.DEFAULT_STDDEV=.05,i.mean=e.mean||i.DEFAULT_MEAN,i.stddev=e.stddev||i.DEFAULT_STDDEV,i.seed=e.seed,i}return t.prototype.apply=function(e,i){if(i=i||"float32",i!=="float32"&&i!=="int32")throw new Te("randomNormal does not support dType "+i+".");return Js(e,this.mean,this.stddev,i,this.seed)},t.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},t.className="RandomNormal",t}(on);y.serialization.registerClass(zv);var _v=function(n){Q(t,n);function t(e){var i=n.call(this)||this;return i.DEFAULT_MEAN=0,i.DEFAULT_STDDEV=.05,i.mean=e.mean||i.DEFAULT_MEAN,i.stddev=e.stddev||i.DEFAULT_STDDEV,i.seed=e.seed,i}return t.prototype.apply=function(e,i){if(i=i||"float32",i!=="float32"&&i!=="int32")throw new Te("truncatedNormal does not support dType "+i+".");return y.truncatedNormal(e,this.mean,this.stddev,i,this.seed)},t.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},t.className="TruncatedNormal",t}(on);y.serialization.registerClass(_v);var Pv=function(n){Q(t,n);function t(e){var i=n.call(this)||this;return i.gain=e.gain!=null?e.gain:1,i}return t.prototype.apply=function(e,i){var r=this;return y.tidy(function(){if(e.length!==2||e[0]!==e[1])throw new M("Identity matrix initializer can only be used for 2D square matrices.");return y.mul(r.gain,y.eye(e[0]))})},t.prototype.getConfig=function(){return{gain:this.gain}},t.className="Identity",t}(on);y.serialization.registerClass(Pv);function uk(n,t){t===void 0&&(t="channelsLast");var e,i;if(ct(t),n.length===2)e=n[0],i=n[1];else if([3,4,5].indexOf(n.length)!==-1){if(t==="channelsFirst"){var r=hi(n,2);e=n[1]*r,i=n[0]*r}else if(t==="channelsLast"){var r=hi(n,0,n.length-2);e=n[n.length-2]*r,i=n[n.length-1]*r}}else{var a=hi(n);e=Math.sqrt(a),i=Math.sqrt(a)}return[e,i]}var Gt=function(n){Q(t,n);function t(e){var i=n.call(this)||this;if(e.scale<0)throw new M("scale must be a positive float. Got: "+e.scale);return i.scale=e.scale==null?1:e.scale,i.mode=e.mode==null?"fanIn":e.mode,ok(i.mode),i.distribution=e.distribution==null?"normal":e.distribution,lk(i.distribution),i.seed=e.seed,i}return t.prototype.apply=function(e,i){var r=uk(e),a=r[0],s=r[1],o=this.scale;if(this.mode==="fanIn"?o/=Math.max(1,a):this.mode==="fanOut"?o/=Math.max(1,s):o/=Math.max(1,(a+s)/2),this.distribution==="normal"){var l=Math.sqrt(o);if(i=i||"float32",i!=="float32"&&i!=="int32")throw new Te(this.getClassName()+" does not support dType "+i+".");return y.truncatedNormal(e,0,l,i,this.seed)}else{var u=Math.sqrt(3*o);return y.randomUniform(e,-u,u,i)}},t.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},t.className="VarianceScaling",t}(on);y.serialization.registerClass(Gt);var ch=function(n){Q(t,n);function t(e){return n.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})||this}return t.prototype.getClassName=function(){return Gt.className},t.className="GlorotUniform",t}(Gt);y.serialization.registerClass(ch);var hh=function(n){Q(t,n);function t(e){return n.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})||this}return t.prototype.getClassName=function(){return Gt.className},t.className="GlorotNormal",t}(Gt);y.serialization.registerClass(hh);var dh=function(n){Q(t,n);function t(e){return n.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})||this}return t.prototype.getClassName=function(){return Gt.className},t.className="HeNormal",t}(Gt);y.serialization.registerClass(dh);var ph=function(n){Q(t,n);function t(e){return n.call(this,{scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})||this}return t.prototype.getClassName=function(){return Gt.className},t.className="HeUniform",t}(Gt);y.serialization.registerClass(ph);var fh=function(n){Q(t,n);function t(e){return n.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})||this}return t.prototype.getClassName=function(){return Gt.className},t.className="LeCunNormal",t}(Gt);y.serialization.registerClass(fh);var mh=function(n){Q(t,n);function t(e){return n.call(this,{scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})||this}return t.prototype.getClassName=function(){return Gt.className},t.className="LeCunNormal",t}(Gt);y.serialization.registerClass(mh);var Mv=function(n){Q(t,n);function t(e){var i=n.call(this)||this;if(i.DEFAULT_GAIN=1,i.gain=e.gain==null?i.DEFAULT_GAIN:e.gain,i.seed=e.seed,i.seed!=null)throw new Te("Random seed is not implemented for Orthogonal Initializer yet.");return i}return t.prototype.apply=function(e,i){var r=this;return y.tidy(function(){if(e.length<2)throw new Te("Shape must be at least 2D.");e[0]*e[1]>2e3&&console.warn("Orthogonal initializer is being called on a matrix with more "+("than 2000 ("+e[0]*e[1]+") elements: ")+"Slowness may result.");var a=e[0]>e[1]?[e[1],e[0]]:e,s=Js(a,0,1,"float32"),o=y.linalg.gramSchmidt(s);return e[0]>e[1]&&(o=o.transpose()),y.mul(r.gain,o)})},t.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}},t.className="Orthogonal",t}(on);y.serialization.registerClass(Mv);var Hv={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function Vv(n,t){return t===void 0&&(t={}),Na(n,y.serialization.SerializationMap.getMap().classNameMap,t,"initializer")}function at(n){return th(n)}function et(n){if(typeof n=="string"){var t=n in Hv?Hv[n]:n;if(t==="GlorotNormal")return new hh;if(t==="GlorotUniform")return new ch;if(t==="HeNormal")return new dh;if(t==="HeUniform")return new ph;if(t==="LeCunNormal")return new fh;if(t==="LeCunUniform")return new mh;var e={};return e.className=t,e.config={},Vv(e)}else return n instanceof on?n:Vv(n)}function ck(){return new Wv}function hk(){return new uh}function dk(n){return new Uv(n)}function pk(n){return new Bv(n)}function fk(n){return new zv(n)}function mk(n){return new _v(n)}function gk(n){return new Pv(n)}function vk(n){return new Gt(n)}function yk(n){return new ch(n)}function bk(n){return new hh(n)}function wk(n){return new dh(n)}function Sk(n){return new ph(n)}function Lk(n){return new fh(n)}function Ik(n){return new mh(n)}function Ak(n){return new Mv(n)}var Tk={__proto__:null,zeros:ck,ones:hk,constant:dk,randomUniform:pk,randomNormal:fk,truncatedNormal:mk,identity:gk,varianceScaling:vk,glorotUniform:yk,glorotNormal:bk,heNormal:wk,heUniform:Sk,leCunNormal:Lk,leCunUniform:Ik,orthogonal:Ak};var Nk=0;function qv(){return Nk++}var Zs={};function Qs(n){return n===void 0&&(n=""),n in Zs||(Zs[n]=0),Zs[n]+=1,n+Zs[n].toString()}function gh(n){return Array.isArray(n)&&Array.isArray(n[0])}function eo(n){return n.length===0?[]:Array.isArray(n[0])?n:[n]}function xe(n){var t;if(Array.isArray(n)){if(n.length!==1)throw new M("Expected Tensor length to be 1; got "+n.length);t=n[0]}else t=n;return t}function Ge(n){if(Array.isArray(n)&&Array.isArray(n[0])){if(n.length===1)return n=n,n[0];throw new M("Expected exactly 1 Shape; got "+n.length)}else return n}function to(n){for(var t=0,e=0,i=n;e1)throw new ui("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use `getInputAt(nodeIndex)` instead.');if(this.inboundNodes.length===0)throw new ui("Layer "+this.name+" is not connected, no input to return.");return _t(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){if(this.inboundNodes.length===0)throw new ui("Layer "+this.name+" has no inbound nodes.");if(this.inboundNodes.length>1)throw new ui("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return _t(this.getNodeAtIndex(0,"output").outputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"losses",{get:function(){return this._losses},enumerable:!0,configurable:!0}),t.prototype.calculateLosses=function(){return this.losses.map(function(e){return e()})},Object.defineProperty(t.prototype,"updates",{get:function(){return this._updates},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"built",{get:function(){return this._built},set:function(e){this._built=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainable",{get:function(){return this.trainable_},set:function(e){this._trainableWeights.forEach(function(i){return i.trainable=e}),this.trainable_=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.trainable_?this._trainableWeights.filter(function(e){return e.trainable}):[]},set:function(e){this._trainableWeights=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this._trainableWeights.filter(function(e){return!e.trainable}).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)},set:function(e){this._nonTrainableWeights=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stateful",{get:function(){return this._stateful},enumerable:!0,configurable:!0}),t.prototype.resetStates=function(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")},t.prototype.assertInputCompatibility=function(e){if(e=Xe(e),this.inputSpec==null||this.inputSpec.length===0)return;var i=Xe(this.inputSpec);if(e.length!==i.length)throw new M("Layer "+this.name+" expects "+i.length+" inputs, "+("but it received "+e.length+" input tensors. ")+("Input received: "+e));for(var r=0;r=0?l[c]:l[l.length+c];if(h!=null&&[h,null].indexOf(d)===-1)throw new M("Input "+r+" is incompatible with layer "+(this.name+": expected axis "+c+" of input shape to ")+("have value "+h+" but got shape "+l+"."))}}if(s.shape!=null)for(var p=0;p0&&Array.isArray(C[0])?v=C.map(function(W,F){return new fn(E,W,r,Xe(e),i,r.name,F)}):v=new fn(E,C,r,Xe(e),i,r.name),r.addInboundNode(e,v,null,null,I,C,i),r._refCount++,r.activityRegularizer!=null)throw new Te("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return v}})},t.prototype.warnOnIncompatibleInputShape=function(e){if(this.batchInputShape==null)return;if(e.length!==this.batchInputShape.length)console.warn("The rank of the input tensor provided (shape: "+(JSON.stringify(e)+") does not match that of the ")+("batchInputShape ("+JSON.stringify(this.batchInputShape)+") ")+("of the layer "+this.name));else{var i=!1;this.batchInputShape.forEach(function(r,a){r!=null&&e[a]!=null&&e[a]!==r&&(i=!0)}),i&&console.warn("The shape of the input tensor "+("("+JSON.stringify(e)+") does not ")+("match the expectation of layer "+this.name+": ")+(""+JSON.stringify(this.batchInputShape)))}},Object.defineProperty(t.prototype,"outputShape",{get:function(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new ui("The layer "+this.name+" has never been called and thus has no defined output shape.");for(var e=[],i=0,r=this.inboundNodes;i0)&&(t=n.sourceLayer,e=n.nodeIndex),t.inboundNodes.length===0)return[n];var i=t.inboundNodes[e];if(i.inboundLayers.length===0)return i.inputTensors;for(var r=[],a=0;a0?[4,Promise.all(t)]:[3,2];case 1:for(o=u.sent(),l=0;l=0&&Number.isInteger(t),function(){return"Verbosity level is expected to be an integer >= 0, "+("but got "+t)}),n.checkForDuplicate(e),n.constructors[t]==null&&(n.constructors[t]=[]),n.constructors[t].push(e)},n.checkForDuplicate=function(t){for(var e in n.constructors){var i=n.constructors[+e];i.forEach(function(r){if(r===t)throw new M("Duplicate callback constructor.")})}},n.clear=function(){n.constructors={}},n.createCallbacks=function(t){var e=[];for(var i in n.constructors){var r=+i;t>=r&&e.push.apply(e,n.constructors[r])}return e.map(function(a){return new a})},n.constructors={},n}();function ny(n,t,e,i,r,a,s,o,l){var u=new Zv,c=[new kk].concat(ty.createCallbacks(t));n!=null&&c.push.apply(c,n),c.push(u);var h=new Jv(c);return h.setParams({epochs:e,initialEpoch:i,samples:r,steps:a,batchSize:s,verbose:t,doValidation:o,metrics:l}),{callbackList:h,history:u}}function mn(n,t,e){return t===void 0&&(t={}),e===void 0&&(e=!1),Na(n,y.serialization.SerializationMap.getMap().classNameMap,t,"layer",e)}function io(n,t){return y.tidy(function(){n.dtype!=="float32"&&(n=n.asType("float32"));var e=y.sum(Ea(n),t,!0),i=y.fill(e.shape,vt()),r=y.sqrt(y.maximum(e,i));return y.div(n,r)})}function Zi(n,t){return y.tidy(function(){return y.mean(Ea(y.sub(t,n)),-1)})}function ro(n,t){return y.tidy(function(){return y.mean(y.abs(y.sub(t,n)),-1)})}function _r(n,t){return y.tidy(function(){var e=y.sub(n,t),i=y.clipByValue(y.abs(n),vt(),Number.MAX_VALUE),r=y.abs(y.div(e,i));return y.mul(100,y.mean(r,-1))})}function Fk(n,t){return y.tidy(function(){var e=y.clipByValue(t,vt(),Number.MAX_VALUE),i=y.log(y.add(1,e)),r=y.clipByValue(n,vt(),Number.MAX_VALUE),a=y.log(y.add(1,r));return y.mean(Ea(y.sub(i,a)),-1)})}function Wk(n,t){return y.tidy(function(){var e=y.maximum(0,y.sub(1,y.mul(n,t)));return y.mean(Ea(e),-1)})}function Uk(n,t){return y.tidy(function(){var e=y.maximum(0,y.sub(1,y.mul(n,t)));return y.mean(e,-1)})}function Bk(n,t){return y.tidy(function(){var e=y.sum(y.mul(n,t),-1),i=y.max(y.mul(y.sub(1,n),t),-1);return y.maximum(0,y.add(1,y.sub(i,e)))})}function zk(n,t){return y.tidy(function(){var e=Math.log(2),i=y.sub(t,n),r=y.sub(y.add(i,y.softplus(y.mul(-2,i))),e);return y.mean(r,-1)})}function Fa(n,t,e){return e===void 0&&(e=!1),y.tidy(function(){if(e)t=y.softmax(t);else{var i=y.sum(t,t.shape.length-1,!0);t=y.div(t,i)}return t=y.clipByValue(t,vt(),1-vt()),y.neg(y.sum(y.mul(n.toFloat(),y.log(t)),t.shape.length-1))})}function ao(n,t,e){return e===void 0&&(e=!1),y.tidy(function(){var i=y.floor(ek(n)).toInt();t=y.clipByValue(t,vt(),1-vt());var r=t.shape,a=y.oneHot(i,r[r.length-1]).reshape(r);return Fa(a,t,e)})}function _k(n,t){if(!y.util.arraysEqual(n.shape,t.shape))throw new M("logits and labels must have the same shape, but got shapes "+(JSON.stringify(n.shape)+" and "+JSON.stringify(t.shape)));return y.tidy(function(){var e=t.relu(),i=t.abs().neg();return e.sub(t.mul(n)).add(i.exp().log1p())})}function so(n,t){return y.tidy(function(){var e;return e=y.clipByValue(t,vt(),1-vt()),e=y.log(y.div(e,y.sub(1,e))),y.mean(_k(n,e),-1)})}function Pk(n,t){return y.tidy(function(){var e=y.clipByValue(n,vt(),1),i=y.clipByValue(t,vt(),1);return y.sum(y.mul(n,y.log(y.div(e,i))),-1)})}function Mk(n,t){return y.tidy(function(){var e=y.log(y.add(vt(),t));return y.mean(y.sub(t,y.mul(n,e)),-1)})}function bh(n,t){return y.tidy(function(){var e=io(n,-1),i=io(t,-1),r=y.mul(e,i);return y.neg(y.sum(r,-1))})}var oo={meanSquaredError:Zi,meanAbsoluteError:ro,meanAbsolutePercentageError:_r,meanSquaredLogarithmicError:Fk,squaredHinge:Wk,hinge:Uk,categoricalHinge:Bk,logcosh:zk,categoricalCrossentropy:Fa,sparseCategoricalCrossentropy:ao,binaryCrossentropy:so,kullbackLeiblerDivergence:Pk,poisson:Mk,cosineProximity:bh};function wh(n){if(typeof n=="string"){if(n in oo)return oo[n];var t="Unknown loss "+n;throw n.toLowerCase().includes("softmaxcrossentropy")&&(t="Unknown loss "+n+'. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy'),new M(t)}else return n}function Sh(n,t){return y.tidy(function(){var e=y.mul(.5,y.onesLike(t)),i=Ra(y.greater(t,e),n.dtype);return y.mean(y.equal(n,i),-1)})}function Lh(n,t){return y.tidy(function(){return Ra(y.equal(y.argMax(n,-1),y.argMax(t,-1)),"float32")})}function iy(n,t){return y.tidy(function(){return y.logicalAnd(n.equal(1),t.equal(1)).sum().cast("float32")})}function Hk(n,t){return y.tidy(function(){return y.logicalAnd(n.equal(1),t.equal(0)).sum().cast("float32")})}function Vk(n,t){return y.tidy(function(){return y.logicalAnd(n.equal(0),t.equal(1)).sum().cast("float32")})}function ry(n,t){return y.tidy(function(){var e=iy(n,t),i=Vk(n,t),r=e.add(i);return y.where(y.greater(r,0),e.div(r),0).cast("float32")})}function qk(n,t){return y.tidy(function(){var e=iy(n,t),i=Hk(n,t),r=e.add(i);return y.where(y.greater(r,0),e.div(r),0).cast("float32")})}function ay(n,t){return so(n,t)}function sy(n,t){return n.rank===t.rank&&(n=n.squeeze([n.rank-1])),t=t.argMax(-1),t.dtype!==n.dtype&&(t=t.asType(n.dtype)),y.equal(n,t).asType("float32")}var Gk=Zi,Yk=Zi,Kk=ro,jk=ro,$k=_r,Xk=_r,Ih=Fa,Jk=bh,oy=ao,lo={binaryAccuracy:Sh,categoricalAccuracy:Lh,precision:ry,categoricalCrossentropy:Ih,sparseCategoricalCrossentropy:oy,mse:Gk,MSE:Yk,mae:Kk,MAE:jk,mape:$k,MAPE:Xk,cosine:Jk};function Zk(n){if(typeof n=="string"&&n in lo)return lo[n];if(typeof n!="string"&&n!=null)return n;throw new M("Unknown metric "+n)}function uo(n){if(On(n!==null,"Unknown LossOrMetricFn "+n),typeof n=="string")return n;for(var t=void 0,e=0,i=Object.keys(oo);ely&&console.warn('User-defined metadata of model "'+t+'" is too large in '+("size (length="+i.length+" when serialized). It is not ")+"recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= "+(ly+"."))}}function Ah(n){if(n===null)return!0;if(typeof n=="object")if(Object.getPrototypeOf(n)===Object.prototype){for(var t=Object.keys(n),e=0,i=t;e1||o.length===1&&o[0].inboundLayers.length>1){t=!1;break}i.push.apply(i,o)}if(t)for(var l=0,u=n.layers;l0&&(i=i.slice(0,i.length-1)+" "),i+=n[r],i=i.slice(0,t[r]),i+=" ".repeat(t[r]-i.length);e(i)}function n3(n,t,e){var i;try{i=JSON.stringify(n.outputShape)}catch(o){i="multiple"}var r=n.name,a=n.getClassName(),s=[r+" ("+a+")",i,n.countParams().toString()];co(s,t,e)}function i3(n,t,e,i){var r;try{r=JSON.stringify(n.outputShape)}catch(v){r="multiple"}for(var a=[],s=0,o=n.inboundNodes;s0&&e.indexOf(l)===-1)continue;for(var u=0;ui.maxNumTensors&&(i.maxNumTensors=S),S0,function(){return"Expected at least one fetch, got none"});var e=[],i={};if(n.length===1){var r=dy(n[0],t);e=r.sorted,i=r.recipientMap}else for(var a=new Set,s=0,o=n;s0;){var c=l[l.length-1];if(e.has(c.name)){l.pop();continue}var h=u[u.length-1]===l.length-1;if(c.inputs.length===0||h)l.pop(),i.push(c),e.add(c.name),h&&u.pop();else{u.push(l.length-1);for(var d=0,p=c.inputs;d1 nodes"),On(c===0,"input layer has >1 tensors"),i.inputLayers.push(l),i.inputLayersNodeIndices.push(u),i.inputLayersTensorIndices.push(c)}i.inputNames=[],i.outputNames=[],i.feedInputShapes=[],i.feedInputNames=[],i.feedOutputNames=[];for(var p=0;p=0;)pt.splice(pt.indexOf(Wt),1);w.push(Wt)},I=[],C=[],E=0,k=i.outputs;Ern?1:0});for(var he=0,ye=le;he0)throw new M("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];for(var e=[],i=0,r=this.layers;i0)throw new M(v.length+" of "+a+" weights are not set: "+(""+v))}yh(d)},t.prototype.updatedConfig=function(){var e=this.getConfig(),i={};return i.className=this.getClassName(),i.config=e,i.kerasVersion="tfjs-layers "+Nh,i.backend="TensorFlow.js",i},t.prototype.toJSON=function(e,i){i===void 0&&(i=!0);var r=Th(this.updatedConfig());return i?JSON.stringify(r):r},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){e=Xe(e);for(var a=new Pr,s=0;s1)for(var c=0,h=u;c0){for(var m=[],g=0;g0&&G.apply(_t(X),ee)}function c(G){var Z=G.name,X=mn(G,i.customObjects!=null?i.customObjects:{});X.setFastWeightInitDuringBuild(a),s[Z]=X;var ee=G.inboundNodes;ee.forEach(function(ne){if(!(ne instanceof Array))throw new M("Corrupted configuration, expected array for nodeData: "+ne);l(X,ne)})}for(var h=i.name,d=i.layers,p=0,f=d;p0&&typeof n[Object.keys(n)[0]]=="object"){var r=[];return t.forEach(function(a){a in n?r.push(n[a]):r.push(null)}),r}else throw new Error("The model has multiple ("+i+") outputs, "+("so "+e+" must be either an array with ")+(i+" elements or an object with "+t+" keys. ")+("Provided "+e+" not understood: "+JSON.stringify(n)))}function py(n,t){return c3(n,t,"classWeight")}function fy(n,t,e,i){return Le(this,void 0,void 0,function(){var r,a,s,o,l;return ve(this,function(u){switch(u.label){case 0:if(t!=null||i!=null)throw new Error("Support sampleWeight is not implemented yet");return e!=null?(r=y.tidy(function(){if(n.shape.length===1)return n.clone();if(n.shape.length===2)if(n.shape[1]>1){var c=1;return n.argMax(c)}else{if(n.shape[1]===1)return n.reshape([n.shape[0]]);throw new Error("Encountered unexpected last-dimension size ("+n.shape[1]+") during handling of class weights. The size is expected to be >= 1.")}else throw new Error("Unexpected rank of target (y) tensor ("+n.rank+") during handling of class weights. The rank is expected to be 1 or 2.")}),o=(s=Array).from,[4,r.data()]):[3,2];case 1:return a=o.apply(s,[u.sent()]),y.dispose(r),l=[],a.forEach(function(c){if(e[c]==null)throw new Error("classWeight must contain all classes in the training data. "+("The class "+c+" exists in the data but not in ")+"classWeight");l.push(e[c])}),[2,y.tensor1d(l,"float32")];case 2:return[2,null]}})})}function h3(n,t){return y.mul(n,t)}var d3=32;function gy(n,t){var e,i,r=t;e=r.xs,i=r.ys,y.util.assert(e!=null&&i!=null,function(){return"A Dataset iterator for fitDataset() is expected to generate objects of the form `{xs: xVal, ys: yVal}`, where the two values may be `tf.Tensor`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates "+(""+t)});var a=my("input",n.inputNames,e),s=my("output",n.outputNames,i),o=a[0].shape[0];y.util.assert(a.length===n.inputs.length,function(){return"LayersModel has "+n.inputs.length+" inputs, but the dataset "+("provides "+a.length+" inputs. (Expected input keys: ")+(JSON.stringify(n.inputNames)+")")}),y.util.assert(s.length===n.outputs.length,function(){return"LayersModel has "+n.outputs.length+" outputs, but the dataset "+("provides "+s.length+" outputs. (Expected output keys: ")+(JSON.stringify(n.outputNames)+")")});for(var l=function(d){y.util.assert(a[d].shape[0]===o,function(){return"Batch size mismatch: input "+(n.inputNames[d]+" has "+a[d].shape[0]+"; ")+("expected "+o+" based on input "+n.inputNames[0]+".")})},u=0;u0&&Number.isInteger(e.epochs),function(){return"For fitDataset(), config.epochs is expected to be a positive "+("integer, but got "+e.epochs)}),y.util.assert(!i||e.batchesPerEpoch>0&&Number.isInteger(e.batchesPerEpoch),function(){return"For fitDataset(), config.batchesPerEpoch is expected to be a "+("positive integer if specified, but got "+e.batchesPerEpoch)}),y.util.assert(e.validationSplit==null,function(){return"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."}),n.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");n.isTraining=!0,X.label=1;case 1:return X.trys.push([1,,26,27]),r=e.validationData!=null,a=void 0,s=void 0,r&&(vy(e.validationData)?y.util.assert(e.validationBatches==null||e.validationBatches>0&&Number.isInteger(e.validationBatches),function(){return"For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, "+("but got "+e.validationBatches)}):(o=p3(e.validationData),a=o.xs,s=o.ys)),l=n.makeTrainFunction(),u=n.getDedupedMetricsNames(),c=void 0,r?c=u.slice().concat(u.map(function(ee){return"val_"+ee})):c=u.slice(),h=ey(e.callbacks,e.yieldEvery),d=e.verbose==null?1:e.verbose,p=ny(h,d,e.epochs,null,null,f3(t,e),null,r,c),f=p.callbackList,m=p.history,f.setModel(n),n.history=m,[4,f.onTrainBegin()];case 2:return X.sent(),n.stopTraining_=!1,g=e.initialEpoch==null?0:e.initialEpoch,[4,t.iterator()];case 3:v=X.sent(),X.label=4;case 4:return g=e.batchesPerEpoch:w.done)?r?(G=void 0,vy(e.validationData)?(Z=Xe,[4,n.evaluateDataset(e.validationData,{batches:e.validationBatches})]):[3,17]):[3,19]:[3,20];case 16:return G=Z.apply(void 0,[X.sent()]),[3,18];case 17:G=Xe(n.evaluate(a,s,{batchSize:e.validationBatchSize==null?d3:e.validationBatchSize,verbose:0})),X.label=18;case 18:for(F=0;F0)throw new Te("Verbose mode is not implemented yet.");return y.util.assert(!i||e.batches>0&&Number.isInteger(e.batches),function(){return"Test loop expects `batches` to be a positive integer, but "+("received "+JSON.stringify(e.batches))}),g3(t)?(o=t,[3,3]):[3,1];case 1:return[4,t.iterator()];case 2:o=f.sent(),f.label=3;case 3:s=o,l=0,u=0,c=function(){var m;return ve(this,function(g){switch(g.label){case 0:return[4,s.next()];case 1:return m=g.sent(),a=y.tidy(function(){if(m.value){var v=gy(n,m.value),b=v.xs,S=v.ys,L=b.concat(S),w=y.tidy(function(){return r(L)});if(y.dispose(L),u===0)for(var N=0;N0&&y.dispose(W)},N=0;N0&&Number.isInteger(n),function(){return"batchSize is required to be a positive integer, but got "+n})}function Ba(n,t,e){return n==null?[null]:Array.isArray(n)?n.map(function(i){return Ji(i,t,e-t)}):Ji(n,t,e-t)}function Rh(n,t){return y.tidy(function(){return n==null?null:Array.isArray(n)?n.map(function(e){return Rh(e,t)}):kv(n,t.dtype==="int32"?t:t.toInt())})}function Oh(n,t){for(var e=[],i=0,r=null;i=n&&(r=n),e.push([i,r]),i=r;return e}function y3(n,t,e,i,r,a,s,o,l,u,c,h,d,p,f){return Le(this,void 0,void 0,function(){var m,g,v,b,S,L,w,N,I;return ve(this,function(C){switch(C.label){case 0:if(r==null&&(r=32),a==null&&(a=1),c==null&&(c=!0),d==null&&(d=0),m=!1,l!=null&&u!=null&&(m=!0),f!=null&&(m=!0,p==null))throw new M("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");return g=n.checkNumSamples(e,r,p,"steps_per_epoch"),g!=null&&(v=pn(0,g)),s==null&&(s=1),b=ny(o,s,a,d,g,p,r,m,h),S=b.callbackList,L=b.history,S.setModel(n),n.history=L,[4,S.onTrainBegin()];case 1:C.sent(),n.stopTraining_=!1,w=function(E){var k,W,F,_,H,P;return ve(this,function(K){switch(K.label){case 0:return[4,S.onEpochBegin(E)];case 1:if(K.sent(),k={},!(p!=null))return[3,2];throw new Te("stepsPerEpoch mode is not implemented yet.");case 2:if(c==="batch")throw new Te("batch shuffling is not implemneted yet");c&&y.util.shuffle(v),W=y.tensor1d(v),F=Oh(g,r),_=function(j){var q;return ve(this,function(G){switch(G.label){case 0:return q={},[4,S.onBatchBegin(j,q)];case 1:return G.sent(),y.tidy(function(){var Z=F[j][0],X=F[j][1],ee=Ji(W,Z,X-Z);q.batch=j,q.size=X-Z;for(var ne=Rh(e,ee),ie=t(ne),te=0;te0))return[3,4];if(f=!0,i.validationData.length===2)s=i.validationData[0],o=i.validationData[1];else throw i.validationData.length===3?new Te("validationData including sample weights is not supported yet."):new M("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; "+(i.validationData+" is invalid."));return g=!0,[4,n.standardizeUserData(s,o,null,null,g,h)];case 3:return v=W.sent(),l=v[0],u=v[1],m=l.concat(u),[3,5];case 4:i.validationSplit!=null&&i.validationSplit>0&&i.validationSplit<1?(f=!0,b=Math.floor(r[0].shape[0]*(1-i.validationSplit)),S=r[0].shape[0],l=Ba(r,b,S),r=Ba(r,0,b),u=Ba(a,b,S),a=Ba(a,0,b),m=l.concat(u)):i.validationSteps!=null&&(f=!0),W.label=5;case 5:return L=r.concat(a).concat(c),n.checkTrainableWeightsConsistency(),w=n.makeTrainFunction(),N=n.getDedupedMetricsNames(),I=void 0,C=void 0,f?(n.makeTestFunction(),I=n.testFunction,C=N.slice().concat(N.map(function(F){return"val_"+F}))):(I=null,m=[],C=N.slice()),E=ey(i.callbacks,i.yieldEvery),[4,y3(n,w,L,N,h,i.epochs,i.verbose,E,I,m,i.shuffle,C,i.initialEpoch,null,null)];case 6:return k=W.sent(),[2,k];case 7:return n.isTraining=!1,Qi(r,t),Qi(a,e),Qi(l,s),Qi(u,o),c!=null&&y.dispose(c),[7];case 8:return[2]}})})}function yy(n){var t=[];n instanceof y.Tensor&&(n=[n]);for(var e=0;e0)a=!0;else if(by(n)){for(var s in n)if(n.hasOwnProperty(s)){a=!0;break}}else a=!0;if(a)throw new M("Error when checking model "+r+" expected no data, "+("but got "+n))}return[]}if(n==null)return t.map(function(g){return null});var o;if(by(n)){n=n,o=[];for(var l=0,u=t;l1)throw new M("The model "+r+" expects "+t.length+" Tensor(s), "+("but only received one Tensor. Found: Tensor with shape "+n.shape));o=[n]}if(o=yy(o),e!=null)for(var h=0;h=0&&f!==m)throw new M("Error when checking "+r+": expected "+t[h]+" "+("to have shape ["+e[h]+"], but got array with shape ")+("["+d.shape+"]."))}}return o}function S3(n,t,e){var i=ci(n.map(function(a){return a.shape[0]}));i.sort();var r=ci(t.map(function(a){return a.shape[0]}));if(r.sort(),i.length>1)throw new M("All input Tensors (x) should have the same number of samples. Got array shapes: "+(""+JSON.stringify(n.map(function(a){return a.shape}))));if(r.length>1)throw new M("All target Tensors (y) should have the same number of samples. Got array shapes: "+(""+JSON.stringify(t.map(function(a){return a.shape}))));if(i.length>0&&r.length>0&&!y.util.arraysEqual(i,r))throw new M("Input Tensors should have the same number of samples as target "+("Tensors. Found "+i[0]+" input sample(s) and "+r[0]+" target ")+"sample(s).")}function L3(n,t,e){for(var i=[Zi,so,Fa],r=0;r1)throw new M("The model expects "+t.length+" "+r+" Tensors, but only received one Tensor. Found: array with shape "+(JSON.stringify(n.shape)+"."));a=[n]}if(e!=null)for(var s=0;s1&&(i.metricsTensors.push([b,v]),i.metricsNames.push(i.outputNames[v]+"_loss"))}});var m=I3(e.metrics,this.outputNames),g=function(v,b,S){i.outputNames.length>1&&(b=i.outputNames[v]+"_"+b),i.metricsNames.push(b),i.metricsTensors.push([S,v])};Xi("metric",function(){for(var v=function(S){if(f.indexOf(S)!==-1)return"continue";var L=m[S],w=function(N){for(var I="",C,E,k,W=function(P){if(typeof P=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(P)!==-1){var K=i.internalOutputShapes[S];K[K.length-1]===1||i.lossFunctions[S]===so?["accuracy","acc"].indexOf(P)!==-1?E=Sh:["crossentropy","ce"].indexOf(P)!==-1&&(E=ay):i.lossFunctions[S]===ao?["accuracy","acc"].indexOf(P)!==-1?E=sy:["crossentropy","ce"].indexOf(P)!==-1&&(E=oy):["accuracy","acc"].indexOf(P)!==-1?E=Lh:["crossentropy","ce"].indexOf(P)!==-1&&(E=Ih);var j=void 0;["accuracy","acc"].indexOf(P)!==-1?j="acc":["crossentropy","ce"].indexOf(P)!==-1&&(j="ce"),k=E,C=I+j}else{var q=Zk(P);k=q,C=I+uo(P)}var G;Xi(C,function(){G=k}),g(S,C,G)},F=0,_=N;F<_.length;F++){var H=_[F];W(H)}};w(L)},b=0;b0){var d=[];throw i.forEach(function(p,f){p==null&&d.push(e[f])}),new M("Cannot find SymbolicTensors for output name(s): "+(""+JSON.stringify(d)))}return i},t.prototype.predictLoop=function(e,i,r){var a=this;return i===void 0&&(i=32),r===void 0&&(r=!1),y.tidy(function(){var s=a.checkNumSamples(e);if(r)throw new Te("Verbose predictLoop() is not implemented yet.");for(var o=Oh(s,i),l=a.outputs.map(function(h){return[]}),u=function(h){var d=y.tidy(function(){var p=o[h][0],f=o[h][1],m=Ba(e,p,f),g=[];if(Array.isArray(m))for(var v=0;v0&&e[0].shape[0]%a!==0)throw new M("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size "+(a+". Found: "+e[0].shape[0]+" sample(s)."));return[e,i]},t.prototype.standardizeUserData=function(e,i,r,a,s,o){return s===void 0&&(s=!0),Le(this,void 0,void 0,function(){var l,u,c,h,d,p,f,m;return ve(this,function(g){switch(g.label){case 0:if(l=this.standardizeUserDataXY(e,i,s,o),u=l[0],c=l[1],r!=null)throw new Error("sample weight is not supported yet.");if(h=null,!(a!=null))return[3,4];d=py(a,this.outputNames),h=[],p=0,g.label=1;case 1:return p0)throw new Te("Verbose mode is not implemented yet.");if(s!=null)throw new Te("steps mode in testLoop() is not implemented yet");for(var c=Oh(l,r),h=y.tensor1d(pn(0,l)),d=0;d1){var o=vv(e.slice(0,r),a);s+="_"+o}i.push(s)}return i},t.prototype.makeTrainFunction=function(){var e=this;return function(i){var r=[],a=i.slice(0,e.inputs.length),s=i.slice(e.inputs.length,e.inputs.length+e.outputs.length),o=i.slice(e.inputs.length+e.outputs.length,e.inputs.length+e.outputs.length*2),l=[],u=function(){for(var p=[],f=0;f1&&f1)throw new M("Found more than one ("+r.length+") save handlers for "+("URL '"+e+"'"));e=r[0]}if(e.save==null)throw new M("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[4,y.io.encodeWeights(this.getNamedWeights(i))];case 1:return a=S.sent(),s=!1,o=null,l=this.toJSON(o,s),u={modelTopology:l,format:A3,generatedBy:"TensorFlow.js tfjs-layers v"+Nh,convertedBy:null},c=i==null?!1:i.includeOptimizer,c&&this.optimizer!=null?(u.trainingConfig=this.getTrainingConfig(),h="optimizer",g=(m=y.io).encodeWeights,[4,this.optimizer.getWeights()]):[3,4];case 2:return[4,g.apply(m,[S.sent(),h])];case 3:d=S.sent(),p=d.data,f=d.specs,(b=a.specs).push.apply(b,f),a.data=y.io.concatenateArrayBuffers([a.data,p]),S.label=4;case 4:return this.userDefinedMetadata!=null&&(v=!0,uy(this.userDefinedMetadata,this.name,v),u.userDefinedMetadata=this.userDefinedMetadata),u.weightData=a.data,u.weightSpecs=a.specs,[2,e.save(u)]}})})},t.prototype.setUserDefinedMetadata=function(e){uy(e,this.name),this.userDefinedMetadata=e},t.prototype.getUserDefinedMetadata=function(){return this.userDefinedMetadata},t.className="Model",t}(u3);y.serialization.registerClass(fi);var T3=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.className="Functional",t}(fi);y.serialization.registerClass(T3);function N3(n,t){return Le(this,void 0,void 0,function(){var e,i,r,a,s,o,l,u;return ve(this,function(c){switch(c.label){case 0:return"modelTopology"in n||(n={modelTopology:n}),n=n,e=n.modelTopology,e.model_config!=null&&(e=e.model_config),i=Wa(e),r=mn(i,t),n.weightsManifest!=null?[4,y.io.loadWeights(n.weightsManifest,n.pathPrefix,r.weights.map(function(h){return h.originalName}))]:[3,2];case 1:for(a=c.sent(),s={},o=0,l=r.weights;o1)throw new M("Found more than one ("+e.length+") load handlers for "+("URL '"+n+"'"));n=e[0]}return[2,x3(n,void 0,t)]})})}function x3(n,t,e){return Le(this,void 0,void 0,function(){var i,r,a,s,o,l,u,c,h;return ve(this,function(d){switch(d.label){case 0:if(e==null&&(e={}),n.load==null)throw new M("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,n.load()];case 1:if(i=d.sent(),r=i.modelTopology,r.model_config!=null&&(r=r.model_config),a=e.strict==null?!0:e.strict,s=i.weightData!=null&&i.weightSpecs!=null&&a,o=mn(Wa(r),t,s),l=i.trainingConfig,l!=null&&o.loadTrainingConfig(l),i.userDefinedMetadata!=null&&o.setUserDefinedMetadata(i.userDefinedMetadata),!(i.weightData!=null))return[3,4];if(i.weightSpecs==null)throw new M("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");return u=R3(i.weightData,i.weightSpecs),c=u.modelWeights,h=u.optimizerWeights,o.loadWeights(c,a),o.optimizer!=null&&h.length>0?[4,o.optimizer.setWeights(h)]:[3,3];case 2:d.sent(),d.label=3;case 3:y.dispose(c),y.dispose(h.map(function(p){return p.tensor})),d.label=4;case 4:return[2,o]}})})}function R3(n,t){var e=y.io.decodeWeights(n,t),i={},r=[];return t.forEach(function(a){a.group==="optimizer"?r.push({name:a.name,tensor:e[a.name]}):i[a.name]=e[a.name]}),{modelWeights:i,optimizerWeights:r}}var Dh=function(n){Q(t,n);function t(e){var i=n.call(this,{inputs:[],outputs:[]})||this;if(e=e||{},i.trainable=!0,i.built=!1,i.name=e.name!=null?e.name:Qs("sequential_"),e.layers!=null)for(var r=0,a=e.layers;r 0 "+("but got "+JSON.stringify(e.filters)))},t}(Wy),Uh=function(n){Q(t,n);function t(e){var i=n.call(this,2,e)||this;return t.verifyArgs(e),i}return t.prototype.getConfig=function(){var e=n.prototype.getConfig.call(this);return delete e.rank,e},t.verifyArgs=function(e){if(typeof e.kernelSize!="number"&&!ih(e.kernelSize,"number",1,2))throw new M("Conv2D expects config.kernelSize to be number or number[] with "+("length 1 or 2, but received "+JSON.stringify(e.kernelSize)+"."))},t.className="Conv2D",t}(fo);y.serialization.registerClass(Uh);var Uy=function(n){Q(t,n);function t(e){var i=n.call(this,3,e)||this;return t.verifyArgs(e),i}return t.prototype.getConfig=function(){var e=n.prototype.getConfig.call(this);return delete e.rank,e},t.verifyArgs=function(e){if(typeof e.kernelSize!="number"&&!(Array.isArray(e.kernelSize)&&(e.kernelSize.length===1||e.kernelSize.length===3)))throw new M("Conv3D expects config.kernelSize to be number or"+(" [number, number, number], but received "+JSON.stringify(e.kernelSize)+"."))},t.className="Conv3D",t}(fo);y.serialization.registerClass(Uy);var By=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;if(i.inputSpec=[new Tt({ndim:4})],i.padding!=="same"&&i.padding!=="valid")throw new M("Conv2DTranspose currently supports only padding modes 'same' "+("and 'valid', but received padding mode "+i.padding));return i}return t.prototype.build=function(e){var i;if(e=Ge(e),e.length!==4)throw new M("Input should have rank 4; Received input shape: "+JSON.stringify(e));var r=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[r]==null)throw new M("The channel dimension of the inputs should be defined. Found `None`.");var a=e[r],s=this.kernelSize.concat([this.filters,a]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Tt({ndim:4,axes:(i={},i[r]=a,i)})],this.built=!0},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){var a=xe(e);if(a.shape.length!==4)throw new M("Conv2DTranspose.call() expects input tensor to be rank-4, but "+("received a tensor of rank-"+a.shape.length));var s=a.shape,o=s[0],l,u;r.dataFormat==="channelsFirst"?(l=2,u=3):(l=1,u=2);var c=s[l],h=s[u],d=r.kernelSize[0],p=r.kernelSize[1],f=r.strides[0],m=r.strides[1],g=po(c,f,d,r.padding),v=po(h,m,p,r.padding),b=[o,g,v,r.filters];r.dataFormat!=="channelsLast"&&(a=y.transpose(a,[0,2,3,1]));var S=y.conv2dTranspose(a,r.kernel.read(),b,r.strides,r.padding);return r.dataFormat!=="channelsLast"&&(S=y.transpose(S,[0,3,1,2])),r.bias!=null&&(S=Dn(S,r.bias.read(),r.dataFormat)),r.activation!=null&&(S=r.activation.apply(S)),S})},t.prototype.computeOutputShape=function(e){e=Ge(e);var i=e.slice(),r,a,s;this.dataFormat==="channelsFirst"?(r=1,a=2,s=3):(r=3,a=1,s=2);var o=this.kernelSize[0],l=this.kernelSize[1],u=this.strides[0],c=this.strides[1];return i[r]=this.filters,i[a]=po(i[a],u,o,this.padding),i[s]=po(i[s],c,l,this.padding),i},t.prototype.getConfig=function(){var e=n.prototype.getConfig.call(this);return delete e.dilationRate,e},t.className="Conv2DTranspose",t}(Uh);y.serialization.registerClass(By);var X3=function(n){Q(t,n);function t(e,i){var r=n.call(this,e,i)||this;if(r.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",r.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",r.depthwiseKernel=null,r.pointwiseKernel=null,i.filters==null)throw new M("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(i.kernelInitializer!=null||i.kernelRegularizer!=null||i.kernelConstraint!=null)throw new M("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(i.padding!=null&&i.padding!=="same"&&i.padding!=="valid")throw new M("SeparableConv"+r.rank+"D supports only padding modes: "+("'same' and 'valid', but received "+JSON.stringify(i.padding)));return r.depthMultiplier=i.depthMultiplier==null?1:i.depthMultiplier,r.depthwiseInitializer=et(i.depthwiseInitializer||r.DEFAULT_DEPTHWISE_INITIALIZER),r.depthwiseRegularizer=tt(i.depthwiseRegularizer),r.depthwiseConstraint=bt(i.depthwiseConstraint),r.pointwiseInitializer=et(i.depthwiseInitializer||r.DEFAULT_POINTWISE_INITIALIZER),r.pointwiseRegularizer=tt(i.pointwiseRegularizer),r.pointwiseConstraint=bt(i.pointwiseConstraint),r}return t.prototype.build=function(e){var i;if(e=Ge(e),e.length1&&(t=n.slice(1,n.length)),n=n[0]}function r(a){return a==null||Array.isArray(a)?a:[a]}return t=r(t),e=r(e),{inputs:n,initialState:t,constants:e}}function qy(n,t,e,i,r,a,s,o){return i===void 0&&(i=!1),s===void 0&&(s=!1),o===void 0&&(o=!1),y.tidy(function(){var l=t.shape.length;if(l<3)throw new M("Input should be at least 3D, but is "+l+"D.");var u=[1,0].concat(pn(2,l));if(t=y.transpose(t,u),a!=null)throw new Te("The rnn() functoin of the deeplearn.js backend does not support constants yet.");s&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),r!=null&&(r=r.asType("bool").asType("float32"),r.rank===l-1&&(r=y.expandDims(r,-1)),r=y.transpose(r,u)),i&&(t=y.reverse(t,0),r!=null&&(r=y.reverse(r,0)));var c=[],h,d=e,p=t.shape[0],f=y.unstack(t),m;r!=null&&(m=y.unstack(r));for(var g=function(L){var w=f[L],N=y.tidy(function(){return n(w,d)});if(r==null)h=N[0],d=N[1];else{var I=y.tidy(function(){var C=m[L],E=y.onesLike(C).sub(C),k=N[0].mul(C).add(d[0].mul(E)),W=d.map(function(F,_){return N[1][_].mul(C).add(F.mul(E))});return{output:k,newStates:W}});h=I.output,d=I.newStates}o&&c.push(h)},v=0;v1?ah(r,[1,a]):r}):i.cell.stateSize>1?[ah(r,[1,i.cell.stateSize])]:[r]})},Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.trainable?this.cell.trainableWeights:[]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights},enumerable:!0,configurable:!0}),t.prototype.setFastWeightInitDuringBuild=function(e){n.prototype.setFastWeightInitDuringBuild.call(this,e),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(e)},t.prototype.getConfig=function(){var e=n.prototype.getConfig.call(this),i={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(i.numConstants=this.numConstants);var r=this.cell.getConfig();return this.getClassName()===t.className&&(i.cell={className:this.cell.getClassName(),config:r}),qt({},r,e,i)},t.fromConfig=function(e,i,r){r===void 0&&(r={});var a=i.cell,s=mn(a,r);return new e(Object.assign(i,{cell:s}))},t.className="RNN",t}(De);y.serialization.registerClass(vi);var Hr=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t}(De),zh=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.DEFAULT_ACTIVATION="tanh",i.DEFAULT_KERNEL_INITIALIZER="glorotNormal",i.DEFAULT_RECURRENT_INITIALIZER="orthogonal",i.DEFAULT_BIAS_INITIALIZER="zeros",i.units=e.units,At(i.units,"units"),i.activation=gi(e.activation==null?i.DEFAULT_ACTIVATION:e.activation),i.useBias=e.useBias==null?!0:e.useBias,i.kernelInitializer=et(e.kernelInitializer||i.DEFAULT_KERNEL_INITIALIZER),i.recurrentInitializer=et(e.recurrentInitializer||i.DEFAULT_RECURRENT_INITIALIZER),i.biasInitializer=et(e.biasInitializer||i.DEFAULT_BIAS_INITIALIZER),i.kernelRegularizer=tt(e.kernelRegularizer),i.recurrentRegularizer=tt(e.recurrentRegularizer),i.biasRegularizer=tt(e.biasRegularizer),i.kernelConstraint=bt(e.kernelConstraint),i.recurrentConstraint=bt(e.recurrentConstraint),i.biasConstraint=bt(e.biasConstraint),i.dropout=Br([1,di([0,e.dropout==null?0:e.dropout])]),i.recurrentDropout=Br([1,di([0,e.recurrentDropout==null?0:e.recurrentDropout])]),i.stateSize=i.units,i.dropoutMask=null,i.recurrentDropoutMask=null,i}return t.prototype.build=function(e){e=Ge(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){if(e=e,e.length!==2)throw new M("SimpleRNNCell expects 2 input Tensors, got "+e.length+".");var a=e[1];e=e[0];var s=i.training==null?!1:i.training;01){for(var s=[0],o=2;o1)throw new M("Can not merge tensors with different batch sizes. "+("Got tensors with shapes: "+JSON.stringify(e)+"."));for(var o=e[0]==null?null:e[0].slice(1),l=1;l1){var L=pn(1,h).concat([0]);a.push(y.transpose(c,L)),p=!0}else a.push(c)}var w=r.mergeFunction(a),N=w.rank;if(p){if(N==null){var I=w.shape,C=I.length,v=I[C-1],b=[v].concat(I.slice(0,I.length-1));w=y.transpose(w.reshape([-1,v]),[1,0]).reshape(b)}else if(N>1){var L=[N-1].concat(pn(0,N-1));w=y.transpose(w,L)}}return w}}else return r.mergeFunction(e)})},t.prototype.computeOutputShape=function(e){e=e;var i;e[0]==null?i=null:i=e[0].slice(1);for(var r=1;r1)throw new M("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))},t.prototype.mergeFunction=function(e){var i=this;return y.tidy(function(){return oh(e,i.axis)})},t.prototype.computeOutputShape=function(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new M("A `Concatenate` layer should be called on a list of inputs.");for(var i=e,r=i[0].slice(),a=this.axis<0?r.length+this.axis:this.axis,s=0,o=i.slice(1);s3||t.shape.length>3)throw new Te("batchDot is not implemented for tensors of 4D or higher rank yet");if(y.util.assert(n.shape.length>=2,function(){return"batchDot requires the rank of x to be >= 2, "+("but got "+n.shape.length)}),y.util.assert(n.shape.length>=2,function(){return"batchDot requires the rank of y to be >= 2, "+("but got "+t.shape.length)}),typeof e=="number"&&(e=[e,e]),n.dtype==="complex64"||t.dtype==="complex64")throw new Te("batchDot is not implemented for complex64-type Tensors yet.");var i=n.shape.length,r=t.shape.length;e==null&&(e=[i-1,r-2]);var a=e;return y.tidy(function(){var s;if(i>r){s=i-r;for(var o=[],l=0;li){s=r-i;for(var o=[],l=0;l0){var d=void 0;i>r?d=i+r-3:d=i-1;for(var p=[],l=d;l3||r.length>3)throw new Te("Dot layer does not support tensors of 4D or higher rank yet.");var a=this.interpretAxes(i,r);if(i[a[0]]!==r[a[1]])throw new M("Dimension incompatibility: "+(i[a[0]]+" !== "+r[a[1]]))},t.prototype.mergeFunction=function(e){if(e.length!==2)throw new M("A `Dot` layer must be called on exactly 2 inputs, "+("but received "+e.length+" input(s)."));var i=e[0],r=e[1],a;return Array.isArray(this.axes)?a=this.axes.map(function(s,o){return za(s,e[o].shape.length)}):a=[za(this.axes,i.shape.length),za(this.axes,r.shape.length)],this.normalize&&(i=io(i,a[0]),r=io(r,a[1])),Q3(i,r,a)},t.prototype.interpretAxes=function(e,i){var r;return Array.isArray(this.axes)?r=this.axes:r=[za(this.axes,e.length),za(this.axes,i.length)],r},t.prototype.computeOutputShape=function(e){y.util.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),function(){return"A `Dot` layer should be called on a list of exactly 2 inputs."});var i=e[0].slice(),r=e[1].slice();if(i.length>3||r.length>3)throw new Te("Dot layer does not support tensors of 4D or higher rank yet.");var a=this.interpretAxes(i,r);i.splice(a[0],1),r.splice(a[1],1),r.splice(0,1);var s=i.concat(r);return s.length===1&&s.push(1),s},t.prototype.computeMask=function(e,i){return null},t.prototype.getConfig=function(){var e={axes:this.axes,normalize:this.normalize},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t.className="Dot",t}(er);y.serialization.registerClass(cb);var hb=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.supportsMasking=!0,i.stddev=e.stddev,i}return t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var e=n.prototype.getConfig.call(this),i={stddev:this.stddev};return Object.assign(i,e),i},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){r.invokeCallHook(e,i);var a=xe(e),s=function(){return Js(a.shape,0,r.stddev).add(a)},o=Da(s,function(){return a},i.training||!1);return o})},t.className="GaussianNoise",t}(De);y.serialization.registerClass(hb);var db=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.supportsMasking=!0,i.rate=e.rate,i}return t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var e=n.prototype.getConfig.call(this),i={rate:this.rate};return Object.assign(i,e),i},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){r.invokeCallHook(e,i);var a=xe(e);if(r.rate>0&&r.rate<1){var s=function(){var o=Math.sqrt(r.rate/(1-r.rate));return a.mul(Js(a.shape,1,o))};return Da(s,function(){return a},i.training||!1)}return a})},t.className="GaussianDropout",t}(De);y.serialization.registerClass(db);var pb=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.supportsMasking=!0,i.rate=e.rate,i.noiseShape=e.noiseShape,i}return t.prototype._getNoiseShape=function(e){return this.noiseShape||xe(e).shape},t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var e=n.prototype.getConfig.call(this),i={rate:this.rate};return Object.assign(i,e),i},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){if(r.rate<1&&r.rate>0){var a=r._getNoiseShape(e),s=function(){var o=xe(e),l=1.6732632423543772,u=1.0507009873554805,c=-l*u,h=y.greaterEqual(y.randomUniform(a),r.rate);h=Ra(h,"float32");var d=Math.pow((1-r.rate)*(1+r.rate*Math.pow(c,2)),-.5),p=-d*c*r.rate,f=o.mul(h).add(h.add(-1).mul(c));return f.mul(d).add(p)};return Da(s,function(){return xe(e)},i.training||!1)}return e})},t.className="AlphaDropout",t}(De);y.serialization.registerClass(pb);function _a(n,t,e,i,r,a){a===void 0&&(a=.001);var s;if(n.rank===2)s=y.batchNorm2d(n,t,e,i,r,a);else if(n.rank===3)s=y.batchNorm3d(n,t,e,i,r,a);else if(n.rank===4)s=y.batchNorm4d(n,t,e,i,r,a);else throw new Te("batchNormalization is not implemented for array of rank "+n.rank+" yet");return s}function e4(n,t,e,i,r){return r===void 0&&(r=.001),y.tidy(function(){var a=y.moments(n,i),s=a.mean,o=a.variance,l=_a(n,s,o,e,t,r);return[l,s,o]})}function t4(n,t,e,i,r){return r===void 0&&(r=.001),y.tidy(function(){for(var a=y.moments(n,i),s=a.mean,o=a.variance,l=[],u=0,c=pn(0,n.rank);u=0?this.axis:this.axis+e.length,a=e[r];if(a==null)throw new M("Axis "+r+" of input tensor should have a defined dimension but the layer received an input with shape "+(JSON.stringify(e)+"."));this.inputSpec=[new Tt({ndim:e.length,axes:(i={},i[r]=a,i)})];var s=[a];this.scale&&(this.gamma=this.addWeight("gamma",s,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",s,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",s,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",s,null,this.movingVarianceInitializer,null,!1),this.built=!0},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){var a=i.training==null?!1:i.training,s=xe(e),o=s.shape,l=o.length,u=pn(0,l),c=r.axis>=0?r.axis:r.axis+l;u.splice(c,1);var h=ji(1,l);h[c]=o[c];var d=u.slice();d.sort();var p=!y.util.arraysEqual(d,pn(0,l).slice(0,l-1)),f=function(){if(p){var w=r.movingMean.read().reshape(h),N=r.movingVariance.read().reshape(h),I=r.center?r.beta.read().reshape(h):null,C=r.scale?r.gamma.read().reshape(h):null;return _a(s,w,N,I,C,r.epsilon)}else return _a(s,r.movingMean.read(),r.movingVariance.read(),r.beta==null?null:r.beta.read(),r.gamma==null?null:r.gamma.read(),r.epsilon)};if(!a)return f();var m=n4(s,r.gamma.read(),r.beta.read(),u,r.epsilon),g=m[0],v=m[1],b=m[2],S=function(w,N,I){y.tidy(function(){var C=1-I,E=w.read(),k=E.sub(N).mul(C);w.write(E.sub(k))})},L=function(){S(r.movingMean,v,r.momentum),S(r.movingVariance,b,r.momentum)};return L(),g})},t.prototype.getConfig=function(){var e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:at(this.betaInitializer),gammaInitializer:at(this.gammaInitializer),movingMeanInitializer:at(this.movingMeanInitializer),movingVarianceInitializer:at(this.movingVarianceInitializer),betaRegularizer:Ye(this.betaRegularizer),gammaRegularizer:Ye(this.gammaRegularizer),betaConstraint:yt(this.betaConstraint),gammaConstraint:yt(this.gammaConstraint)},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t.className="BatchNormalization",t}(De);y.serialization.registerClass(fb);var mb=function(n){Q(t,n);function t(e){var i=this;if(e==null&&(e={}),i=n.call(this,e)||this,i.axis=e.axis==null?-1:e.axis,typeof i.axis=="number"){if(!Number.isInteger(i.axis))throw new Error("Expected axis to be an integer, but received "+i.axis)}else if(Array.isArray(i.axis))for(var r=0,a=i.axis;r=i)throw new Error("Invalid axis: "+o)}if(this.axis.length!==ci(this.axis).length)throw new Error("Found duplicate axes in: "+this.axis);var l=this.axis.map(function(c){return e[c]}),u=!0;this.scale?this.gamma=this.addWeight("gamma",l,"float32",this.gammaInitializer,this.gammaRegularizer,u):this.gamma=null,this.center?this.beta=this.addWeight("beta",l,"float32",this.betaInitializer,this.betaRegularizer,u):this.beta=null,this.built=!0},t.prototype.call=function(e,i){var r=this,a=xe(e),s=a.shape,o=s.length;return y.tidy(function(){for(var l=!0,u=y.moments(a,r.axis,l),c=u.mean,h=u.variance,d=ji(1,o),p=0,f=r.axis;p=0?i=e[2]+this.padding[0][0]+this.padding[0][1]:i=null,e[3]!=null&&e[3]>=0?r=e[3]+this.padding[1][0]+this.padding[1][1]:r=null,[e[0],e[1],i,r]):(e[1]!=null&&e[1]>=0?i=e[1]+this.padding[0][0]+this.padding[0][1]:i=null,e[2]!=null&&e[2]>=0?r=e[2]+this.padding[1][0]+this.padding[1][1]:r=null,[e[0],i,r,e[3]])},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){return i4(xe(e),r.padding,r.dataFormat)})},t.prototype.getConfig=function(){var e={padding:this.padding,dataFormat:this.dataFormat},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t.className="ZeroPadding2D",t}(De);y.serialization.registerClass(gb);function go(n,t,e,i,r,a){return y.tidy(function(){ct(r),Nv(a),en(i),e==null&&(e=[1,1]),i==null&&(i="valid"),r==null&&(r=dn()),a==null&&(a="max"),n=Wh(n,r);var s,o=i==="same"?"same":"valid";return a==="max"?s=y.maxPool(n,t,e,o):s=y.avgPool(n,t,e,o),r==="channelsFirst"&&(s=y.transpose(s,[0,3,1,2])),s})}function vb(n,t,e,i,r,a){return y.tidy(function(){ct(r),Nv(a),en(i),e==null&&(e=[1,1,1]),i==null&&(i="valid"),r==null&&(r=dn()),a==null&&(a="max"),n=ky(n,r);var s,o=i==="same"?"same":"valid";return a==="max"?s=y.maxPool3d(n,t,e,o):s=y.avgPool3d(n,t,e,o),r==="channelsFirst"&&(s=y.transpose(s,[0,4,1,2,3])),s})}var yb=function(n){Q(t,n);function t(e){var i=this;if(e.poolSize==null&&(e.poolSize=2),i=n.call(this,e)||this,typeof e.poolSize=="number")i.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")i.poolSize=e.poolSize;else throw new M("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+(""+JSON.stringify(e.poolSize)));if(At(i.poolSize,"poolSize"),e.strides==null)i.strides=i.poolSize;else if(typeof e.strides=="number")i.strides=[e.strides];else if(Array.isArray(e.strides)&&e.strides.length===1&&typeof e.strides[0]=="number")i.strides=e.strides;else throw new M("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+(""+JSON.stringify(e.strides)));return At(i.strides,"strides"),i.padding=e.padding==null?"valid":e.padding,en(i.padding),i.inputSpec=[new Tt({ndim:3})],i}return t.prototype.computeOutputShape=function(e){e=Ge(e);var i=gn(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],i,e[2]]},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){r.invokeCallHook(e,i),e=Oa(xe(e),2);var a=r.poolingFunction(xe(e),[r.poolSize[0],1],[r.strides[0],1],r.padding,"channelsLast");return y.squeeze(a,[2])})},t.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t}(De),bb=function(n){Q(t,n);function t(e){return n.call(this,e)||this}return t.prototype.poolingFunction=function(e,i,r,a,s){return ct(s),en(a),go(e,i,r,a,s,"max")},t.className="MaxPooling1D",t}(yb);y.serialization.registerClass(bb);var wb=function(n){Q(t,n);function t(e){return n.call(this,e)||this}return t.prototype.poolingFunction=function(e,i,r,a,s){return ct(s),en(a),go(e,i,r,a,s,"avg")},t.className="AveragePooling1D",t}(yb);y.serialization.registerClass(wb);var Sb=function(n){Q(t,n);function t(e){var i=this;if(e.poolSize==null&&(e.poolSize=[2,2]),i=n.call(this,e)||this,i.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)i.strides=i.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new M("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length "+(e.strides.length+"."));i.strides=e.strides}else i.strides=[e.strides,e.strides];return At(i.poolSize,"poolSize"),At(i.strides,"strides"),i.padding=e.padding==null?"valid":e.padding,i.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,ct(i.dataFormat),en(i.padding),i.inputSpec=[new Tt({ndim:4})],i}return t.prototype.computeOutputShape=function(e){e=Ge(e);var i=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2];return i=gn(i,this.poolSize[0],this.padding,this.strides[0]),r=gn(r,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],i,r]:[e[0],i,r,e[3]]},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){return r.invokeCallHook(e,i),r.poolingFunction(xe(e),r.poolSize,r.strides,r.padding,r.dataFormat)})},t.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t}(De),Lb=function(n){Q(t,n);function t(e){return n.call(this,e)||this}return t.prototype.poolingFunction=function(e,i,r,a,s){return ct(s),en(a),go(e,i,r,a,s,"max")},t.className="MaxPooling2D",t}(Sb);y.serialization.registerClass(Lb);var Ib=function(n){Q(t,n);function t(e){return n.call(this,e)||this}return t.prototype.poolingFunction=function(e,i,r,a,s){return ct(s),en(a),go(e,i,r,a,s,"avg")},t.className="AveragePooling2D",t}(Sb);y.serialization.registerClass(Ib);var Ab=function(n){Q(t,n);function t(e){var i=this;if(e.poolSize==null&&(e.poolSize=[2,2,2]),i=n.call(this,e)||this,i.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)i.strides=i.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new M("If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length "+(e.strides.length+"."));i.strides=e.strides}else i.strides=[e.strides,e.strides,e.strides];return At(i.poolSize,"poolSize"),At(i.strides,"strides"),i.padding=e.padding==null?"valid":e.padding,i.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,ct(i.dataFormat),en(i.padding),i.inputSpec=[new Tt({ndim:5})],i}return t.prototype.computeOutputShape=function(e){e=Ge(e);var i=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2],a=this.dataFormat==="channelsFirst"?e[4]:e[3];return i=gn(i,this.poolSize[0],this.padding,this.strides[0]),r=gn(r,this.poolSize[1],this.padding,this.strides[1]),a=gn(a,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],i,r,a]:[e[0],i,r,a,e[4]]},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){return r.invokeCallHook(e,i),r.poolingFunction(xe(e),r.poolSize,r.strides,r.padding,r.dataFormat)})},t.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t}(De),Tb=function(n){Q(t,n);function t(e){return n.call(this,e)||this}return t.prototype.poolingFunction=function(e,i,r,a,s){return ct(s),en(a),vb(e,i,r,a,s,"max")},t.className="MaxPooling3D",t}(Ab);y.serialization.registerClass(Tb);var Nb=function(n){Q(t,n);function t(e){return n.call(this,e)||this}return t.prototype.poolingFunction=function(e,i,r,a,s){return ct(s),en(a),vb(e,i,r,a,s,"avg")},t.className="AveragePooling3D",t}(Ab);y.serialization.registerClass(Nb);var xb=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.inputSpec=[new Tt({ndim:3})],i}return t.prototype.computeOutputShape=function(e){return[e[0],e[2]]},t.prototype.call=function(e,i){throw new Te},t}(De),Cb=function(n){Q(t,n);function t(e){return n.call(this,e||{})||this}return t.prototype.call=function(e,i){return y.tidy(function(){var r=xe(e);return y.mean(r,1)})},t.className="GlobalAveragePooling1D",t}(xb);y.serialization.registerClass(Cb);var Rb=function(n){Q(t,n);function t(e){return n.call(this,e||{})||this}return t.prototype.call=function(e,i){return y.tidy(function(){var r=xe(e);return y.max(r,1)})},t.className="GlobalMaxPooling1D",t}(xb);y.serialization.registerClass(Rb);var Ob=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,ct(i.dataFormat),i.inputSpec=[new Tt({ndim:4})],i}return t.prototype.computeOutputShape=function(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]},t.prototype.call=function(e,i){throw new Te},t.prototype.getConfig=function(){var e={dataFormat:this.dataFormat},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t}(De),Eb=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.call=function(e,i){var r=this;return y.tidy(function(){var a=xe(e);return r.dataFormat==="channelsLast"?y.mean(a,[1,2]):y.mean(a,[2,3])})},t.className="GlobalAveragePooling2D",t}(Ob);y.serialization.registerClass(Eb);var Db=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.call=function(e,i){var r=this;return y.tidy(function(){var a=xe(e);return r.dataFormat==="channelsLast"?y.max(a,[1,2]):y.max(a,[2,3])})},t.className="GlobalMaxPooling2D",t}(Ob);y.serialization.registerClass(Db);var kb=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.layer=e.layer,i}return t.prototype.build=function(e){this.built=!0},Object.defineProperty(t.prototype,"trainable",{get:function(){return this.layer!=null?this.layer.trainable:!1},set:function(e){this.layer!=null&&(this.layer.trainable=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.layer.trainableWeights},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.layer.nonTrainableWeights},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"updates",{get:function(){return this.layer._updates},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"losses",{get:function(){return this.layer.losses},enumerable:!0,configurable:!0}),t.prototype.getWeights=function(){return this.layer.getWeights()},t.prototype.setWeights=function(e){this.layer.setWeights(e)},t.prototype.getConfig=function(){var e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t.prototype.setFastWeightInitDuringBuild=function(e){n.prototype.setFastWeightInitDuringBuild.call(this,e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)},t.fromConfig=function(e,i,r){r===void 0&&(r={});var a=i.layer,s=mn(a,r);delete i.layer;var o={layer:s};return Object.assign(o,i),new e(o)},t}(De),Fb=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.supportsMasking=!0,i}return t.prototype.build=function(e){if(e=Ge(e),e.length<3)throw new M("TimeDistributed layer expects an input shape >= 3D, but received "+("input shape "+JSON.stringify(e)));this.inputSpec=[{shape:e}];var i=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(i),this.layer.built=!0),n.prototype.build.call(this,e)},t.prototype.computeOutputShape=function(e){e=Ge(e);var i=[e[0]].concat(e.slice(2)),r=this.layer.computeOutputShape(i),a=e[1];return[r[0],a].concat(r.slice(1))},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){e=xe(e);var a=function(l,u){var c=xe(r.layer.call(l,i));return[c,[]]},s=qy(a,e,[],!1,null,null,!1,!0),o=s[1];return o})},t.className="TimeDistributed",t}(kb);y.serialization.registerClass(Fb);function r4(n){Wr($D,"BidirectionalMergeMode",n)}var a4="concat",Wb=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this,r=e.layer.getConfig(),a={};a.className=e.layer.getClassName(),a.config=r,i.forwardLayer=mn(a),r.goBackwards=!(r.goBackwards===!0);var s={};if(s.className=e.layer.getClassName(),s.config=r,i.backwardLayer=mn(s),i.forwardLayer.name="forward_"+i.forwardLayer.name,i.backwardLayer.name="backward_"+i.backwardLayer.name,i.mergeMode=e.mergeMode===void 0?a4:e.mergeMode,r4(i.mergeMode),e.weights)throw new Te("weights support is not implemented for Bidirectional layer yet.");return i._stateful=e.layer.stateful,i.returnSequences=e.layer.returnSequences,i.returnState=e.layer.returnState,i.supportsMasking=!0,i._trainable=!0,i.inputSpec=e.layer.inputSpec,i.numConstants=null,i}return Object.defineProperty(t.prototype,"trainable",{get:function(){return this._trainable},set:function(e){this._trainable=e,this.forwardLayer!=null&&(this.forwardLayer.trainable=e),this.backwardLayer!=null&&(this.backwardLayer.trainable=e)},enumerable:!0,configurable:!0}),t.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())},t.prototype.setWeights=function(e){var i=e.length,r=Math.floor(i/2);this.forwardLayer.setWeights(e.slice(0,r)),this.backwardLayer.setWeights(e.slice(r))},t.prototype.computeOutputShape=function(e){var i=this.forwardLayer.computeOutputShape(e);Array.isArray(i)&&Array.isArray(i[0])||(i=[i]),i=i;var r,a,s;return this.returnState&&(s=i.slice(1)),r=i[0],r=r,this.mergeMode==="concat"?(r[r.length-1]*=2,a=[r]):this.mergeMode==null?a=[r,r.slice()]:a=[r],this.returnState?this.mergeMode==null?a.concat(s).concat(s.slice()):[r].concat(s).concat(s.slice()):_t(a)},t.prototype.apply=function(e,i){var r=i==null?null:i.initialState,a=i==null?null:i.constants;i==null&&(i={});var s=Vy(e,r,a,this.numConstants);if(e=s.inputs,r=s.initialState,a=s.constants,Array.isArray(e)&&(r=e.slice(1),e=e[0]),(r==null||r.length===0)&&a==null)return n.prototype.apply.call(this,e,i);var o=[],l=[];if(r!=null){var u=r.length;if(u%2>0)throw new M("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");i.initialState=r,o.push.apply(o,r);var c=r.map(function(S){return new Tt({shape:S.shape})});this.forwardLayer.stateSpec=c.slice(0,u/2),this.backwardLayer.stateSpec=c.slice(u/2),l.push.apply(l,c)}if(a!=null)throw new Te("Support for constants in Bidirectional layers is not implemented yet.");for(var h=o[0]instanceof fn,d=0,p=o;dt}var Hb=function(n){Q(t,n);function t(e){var i=n.call(this)||this;if(e==null&&(e={}),e.restoreBestWeights)throw new Te("restoreBestWeights = True is not implemented in EarlyStopping yet.");return i.monitor=e.monitor||"val_loss",i.minDelta=Math.abs(e.minDelta||0),i.patience=e.patience||0,i.verbose=e.verbose||0,i.mode=e.mode||"auto",i.baseline=e.baseline,["auto","min","max"].indexOf(i.mode)===-1&&(console.warn("EarlyStopping mode '"+i.mode+"' is invalid. Falling back to mode 'auto'."),i.mode="auto"),i.mode==="min"?i.monitorFunc=vo:i.mode==="max"||i.monitor.indexOf("acc")!==-1?i.monitorFunc=Mb:i.monitorFunc=vo,i.monitorFunc===vo&&(i.minDelta*=-1),i}return t.prototype.onTrainBegin=function(e){return Le(this,void 0,void 0,function(){return ve(this,function(i){return this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===vo?Infinity:-Infinity,[2]})})},t.prototype.onEpochEnd=function(e,i){return Le(this,void 0,void 0,function(){var r;return ve(this,function(a){switch(a.label){case 0:return[4,pi(i)];case 1:return a.sent(),r=this.getMonitorValue(i),r==null?[2]:(this.monitorFunc(r-this.minDelta,this.best)?(this.best=r,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)),[2])}})})},t.prototype.onTrainEnd=function(e){return Le(this,void 0,void 0,function(){return ve(this,function(i){return this.stoppedEpoch>0&&this.verbose&&console.log("Epoch "+this.stoppedEpoch+": early stopping."),[2]})})},t.prototype.getMonitorValue=function(e){e==null&&(e={});var i=e[this.monitor];return i==null&&console.warn("Metric for EarlyStopping "+this.monitor+" is not available. "+("Available metrics are: "+Object.keys(e))),i},t}(Pb);function BF(n){return new Hb(n)}var zF={earlyStopping:BF};$e.Callback=Pb;$e.CallbackList=Jv;$e.CustomCallback=Qv;$e.EarlyStopping=Hb;$e.History=Zv;$e.InputSpec=Tt;$e.LayerVariable=Yv;$e.LayersModel=fi;$e.RNN=vi;$e.Sequential=Dh;$e.SymbolicTensor=fn;$e.callbacks=zF;$e.constraints=GD;$e.initializers=Tk;$e.input=Ly;$e.layers=mF;$e.loadLayersModel=D3;$e.metrics=EF;$e.model=O3;$e.models=DF;$e.registerCallbackConstructor=k3;$e.regularizers=UF;$e.sequential=E3;$e.version_layers=Nh});var rw=be(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});var B=Ki();var qb=Object.assign||function(t){for(var e,i=1,r=arguments.length;i0&&a[a.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!a||u[1]>a[0]&&u[1]0?Object.keys(h).forEach(function(g){var v=Yn(g)[0],b=l[v];b&&(b.signatureKey=h[g],u.push(b))}):u=a;var f={};t.library!=null&&t.library.function!=null&&(f=t.library.function.reduce(function(g,v){return g[v.signature.name]=i.mapFunction(v),g},{}));var m={nodes:l,inputs:u,outputs:c,weights:s,placeholders:a,signature:e,functions:f};return o.length>0&&(m.initNodes=o),m},n.prototype.mapSignatureEntries=function(t){return Object.keys(t||{}).reduce(function(e,i){return e[t[i].name]=i,e},{})},n.prototype.mapNode=function(t){var e=Yb(t.op)||this.opMappers[t.op]||{};t.attr==null&&(t.attr={});var i={name:t.name,op:t.op,category:e.category,inputNames:(t.input||[]).map(function(r){return r.startsWith("^")?r.substr(1):r}),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:t.attr};return e.inputs!=null&&(i.inputParams=e.inputs.reduce(function(r,a){return r[a.name]={type:a.type,inputIndexStart:a.start,inputIndexEnd:a.end},r},{})),e.attrs!=null&&(i.attrParams=e.attrs.reduce(function(r,a){var s=a.type,o=void 0;switch(a.type){case"string":o=Yh(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=Yh(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"string[]":o=ed(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=ed(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"number":o=jh(t.attr,a.tfName,a.defaultValue||0),o===void 0&&!!a.tfDeprecatedName&&(o=jh(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"number[]":o=Qh(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=Qh(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool":o=Kh(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=Kh(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool[]":o=nd(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=nd(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape":o=Zh(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=Zh(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape[]":o=td(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=td(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype":o=Xh(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=Xh(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype[]":o=Jh(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=Jh(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"func":o=Kb(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=Kb(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error("Unsupported param type: "+a.type+" for op: "+t.op)}return r[a.name]={value:o,type:s},r},{})),i},n.prototype.mapFunction=function(t){var e=this,i=t.nodeDef,r=[],a=[],s={};i!=null&&(s=i.reduce(function(d,p){return d[p.name]=e.mapNode(p),p.op==="Const"&&a.push(d[p.name]),d},{}));var o=[],l=[];t.signature.inputArg.forEach(function(d){var p=Yn(d.name)[0],f={name:p,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:$h(d.type),type:"dtype"}},children:[]};f.signatureKey=d.name,o.push(f),s[p]=f});var u=Object.keys(s);u.forEach(function(d){var p=s[d];p.inputNames.forEach(function(f){var m=Yn(f)[0];p.inputs.push(s[m]),s[m].children.push(p)})});var c=t.ret;t.signature.outputArg.forEach(function(d){var p=Yn(c[d.name]),f=p[0],m=p[1],g=s[f];g!=null&&(g.defaultOutput=m,l.push(g))});var h=this.mapArgsToSignature(t);return{nodes:s,inputs:o,outputs:l,weights:a,placeholders:r,signature:h}},n.prototype.mapArgsToSignature=function(t){var e=this;return{methodName:t.signature.name,inputs:t.signature.inputArg.reduce(function(i,r){return i[r.name]=e.mapArgToTensorInfo(r),i},{}),outputs:t.signature.outputArg.reduce(function(i,r){return i[r.name]=e.mapArgToTensorInfo(r,t.ret),i},{})}},n.prototype.mapArgToTensorInfo=function(t,e){var i=t.name;return e!=null&&(i=e[i]),{name:i,dtype:t.type}},n}();function wW(n){var t=B.env().global;if(typeof t.atob!="undefined")return t.atob(n);if(typeof Buffer!="undefined")return new Buffer(n,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function $b(n,t){var e=Array.isArray(n)?String.fromCharCode.apply(null,n):wW(n);return t?e:e.toLowerCase()}function Yh(n,t,e,i){i===void 0&&(i=!1);var r=n[t];return r!=null?$b(r.s,i):e}function Kh(n,t,e){var i=n[t];return i?i.b:e}function jh(n,t,e){var i=n[t]||{},r=i.i!=null?i.i:i.f!=null?i.f:e;return typeof r=="number"?r:parseInt(r,10)}function $h(n){typeof n=="string"&&(n=yn[n]);switch(n){case yn.DT_FLOAT:return"float32";case yn.DT_INT32:case yn.DT_INT64:case yn.DT_INT8:case yn.DT_UINT8:return"int32";case yn.DT_BOOL:return"bool";case yn.DT_DOUBLE:return"float32";case yn.DT_STRING:return"string";default:return null}}function Kb(n,t,e){var i=n[t];return i&&i.func?i.func.name:e}function Xh(n,t,e){var i=n[t];return i&&i.type?$h(i.type):e}function Jh(n,t,e){var i=n[t];return i&&i.list&&i.list.type?i.list.type.map(function(r){return $h(r)}):e}function Xb(n){return n.unknownRank?void 0:n.dim!=null?n.dim.map(function(t){return typeof t.size=="number"?t.size:parseInt(t.size,10)}):[]}function Zh(n,t,e){var i=n[t];return i&&i.shape?Xb(i.shape):e}function Qh(n,t,e){var i=n[t];return i?((i.list.f&&i.list.f.length?i.list.f:i.list.i)||[]).map(function(r){return typeof r=="number"?r:parseInt(r,10)}):e}function ed(n,t,e,i){i===void 0&&(i=!1);var r=n[t];return r&&r.list&&r.list.s?r.list.s.map(function(a){return $b(a,i)}):e}function td(n,t,e){var i=n[t];return i&&i.list&&i.list.shape?i.list.shape.map(function(r){return Xb(r)}):e}function nd(n,t,e){var i=n[t];return i&&i.list&&i.list.b?i.list.b:e}var SW=function(){function n(t,e,i){var r=this;this.node=t,this.tensorMap=e,this.context=i,this.inputs=[],this.attrs={},this.inputs=t.inputNames.map(function(a){return r.getInput(a)}),t.rawAttrs!=null&&(this.attrs=Object.keys(t.rawAttrs).reduce(function(a,s){return a[s]=r.getAttr(s),a},{}))}return n.prototype.getInput=function(t){return Pt(t,this.tensorMap,this.context)},n.prototype.getAttr=function(t,e){var i=this.node.rawAttrs[t];if(i.tensor!=null)return Pt(t,this.tensorMap,this.context);if(i.i!=null||i.f!=null)return jh(this.node.rawAttrs,t,e);if(i.s!=null)return Yh(this.node.rawAttrs,t,e);if(i.b!=null)return Kh(this.node.rawAttrs,t,e);if(i.shape!=null)return Zh(this.node.rawAttrs,t,e);if(i.type!=null)return Xh(this.node.rawAttrs,t,e);if(i.list!=null){if(i.list.i!=null||i.list.f!=null)return Qh(this.node.rawAttrs,t,e);if(i.list.s!=null)return ed(this.node.rawAttrs,t,e);if(i.list.shape!=null)return td(this.node.rawAttrs,t,e);if(i.list.b!=null)return nd(this.node.rawAttrs,t,e);if(i.list.type!=null)return Jh(this.node.rawAttrs,t,e)}return e},n}();var LW=function(n,t,e){switch(n.op){case"BiasAdd":case"AddV2":case"Add":return[B.add(T("a",n,t,e),T("b",n,t,e))];case"AddN":return[B.addN(T("tensors",n,t,e))];case"FloorMod":case"Mod":return[B.mod(T("a",n,t,e),T("b",n,t,e))];case"Mul":return[B.mul(T("a",n,t,e),T("b",n,t,e))];case"RealDiv":case"Div":return[B.div(T("a",n,t,e),T("b",n,t,e))];case"DivNoNan":return[B.divNoNan(T("a",n,t,e),T("b",n,t,e))];case"FloorDiv":return[B.floorDiv(T("a",n,t,e),T("b",n,t,e))];case"Sub":return[B.sub(T("a",n,t,e),T("b",n,t,e))];case"Minimum":return[B.minimum(T("a",n,t,e),T("b",n,t,e))];case"Maximum":return[B.maximum(T("a",n,t,e),T("b",n,t,e))];case"Pow":return[B.pow(T("a",n,t,e),T("b",n,t,e))];case"SquaredDifference":return[B.squaredDifference(T("a",n,t,e),T("b",n,t,e))];default:throw TypeError("Node type "+n.op+" is not implemented")}};var IW=function(n,t,e){switch(n.op){case"Abs":case"ComplexAbs":return[B.abs(T("x",n,t,e))];case"Acos":return[B.acos(T("x",n,t,e))];case"Acosh":return[B.acosh(T("x",n,t,e))];case"Asin":return[B.asin(T("x",n,t,e))];case"Asinh":return[B.asinh(T("x",n,t,e))];case"Atan":return[B.atan(T("x",n,t,e))];case"Atan2":return[B.atan2(T("x",n,t,e),T("y",n,t,e))];case"Atanh":return[B.atanh(T("x",n,t,e))];case"Ceil":return[B.ceil(T("x",n,t,e))];case"Complex":return[B.complex(T("real",n,t,e),T("imag",n,t,e))];case"Cos":return[B.cos(T("x",n,t,e))];case"Cosh":return[B.cosh(T("x",n,t,e))];case"Elu":return[B.elu(T("x",n,t,e))];case"Erf":return[B.erf(T("x",n,t,e))];case"Exp":return[B.exp(T("x",n,t,e))];case"Expm1":return[B.expm1(T("x",n,t,e))];case"Floor":return[B.floor(T("x",n,t,e))];case"Log":return[B.log(T("x",n,t,e))];case"Log1p":return[B.log1p(T("x",n,t,e))];case"Imag":return[B.imag(T("x",n,t,e))];case"Neg":return[B.neg(T("x",n,t,e))];case"Reciprocal":return[B.reciprocal(T("x",n,t,e))];case"Real":return[B.real(T("x",n,t,e))];case"Relu":return[B.relu(T("x",n,t,e))];case"Round":return[B.round(T("x",n,t,e))];case"Selu":return[B.selu(T("x",n,t,e))];case"Sigmoid":return[B.sigmoid(T("x",n,t,e))];case"Sin":return[B.sin(T("x",n,t,e))];case"Sign":return[B.sign(T("x",n,t,e))];case"Sinh":return[B.sinh(T("x",n,t,e))];case"Softplus":return[B.softplus(T("x",n,t,e))];case"Sqrt":return[B.sqrt(T("x",n,t,e))];case"Square":return[B.square(T("x",n,t,e))];case"Tanh":return[B.tanh(T("x",n,t,e))];case"Tan":return[B.tan(T("x",n,t,e))];case"Relu6":case"ClipByValue":return[B.clipByValue(T("x",n,t,e),T("clipValueMin",n,t,e),T("clipValueMax",n,t,e))];case"Rsqrt":return[B.rsqrt(Pt(n.inputNames[0],t,e))];case"Prod":return[B.prod(T("x",n,t,e),T("axes",n,t,e))];case"LeakyRelu":return[B.leakyRelu(T("x",n,t,e),T("alpha",n,t,e))];case"Prelu":return[B.prelu(T("x",n,t,e),T("alpha",n,t,e))];default:throw TypeError("Node type "+n.op+" is not implemented")}};function ln(n,t,e){e===void 0&&(e=""),B.util.assert(AW(n,t),function(){return e+(" Shapes "+n+" and "+t+" must match")})}function AW(n,t){if(n.length!==t.length)return!1;for(var e=0;e=this.size())throw new Error("Tried to read from index "+t+", but array size is: "+this.size());var e=this.tensors[t];if(e.cleared)throw new Error("TensorArray "+this.name+": Could not read index "+t+" twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).");return this.clearAfterRead&&(e.cleared=!0),e.read=!0,e.tensor},n.prototype.readMany=function(t){var e=this;return t.map(function(i){return e.read(i)})},n.prototype.write=function(t,e){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(t<0||!this.dynamicSize&&t>=this.maxSize)throw new Error("Tried to write to index "+t+", but array is not resizeable and size is: "+this.maxSize);var i=this.tensors[t]||{};if(e.dtype!==this.dtype)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+`, +`+("2. The custom "+i+" is defined in JavaScript, ")+"but is not registered properly with tf.serialization.registerClass().");if(p!=null){for(var f={},m=0,g=Object.keys(sn);mt?1:0}function $s(n,t){return-1*_D(n,t)}function ci(n){if(n==null)return n;for(var t=[],e=0,i=n;e=0),On(i>=e),Array.isArray(n)&&n.length>=e&&n.length<=i&&n.every(function(r){return typeof r===t})}function At(n,t){Array.isArray(n)?(y.util.assert(n.length>0,function(){return t+" is unexpectedly an empty array."}),n.forEach(function(e,i){return At(e,"element "+(i+1)+" of "+t)})):y.util.assert(Number.isInteger(n)&&n>0,function(){return"Expected "+t+" to be a positive integer, but got "+(yv(n)+".")})}function yv(n){return n===null?"null":Array.isArray(n)?"["+n.map(function(t){return yv(t)}).join(",")+"]":typeof n=="string"?'"'+n+'"':""+n}function MD(n,t){var e=y.util.now(),i,r=function(){for(var a=[],s=0;s0){var e=n+"_"+t;return Ur.set(e,1),e}else return n}var ZD=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Cv(n){return!!n.match(ZD)}function QD(n){return n===parseInt(n.toString(),10)}function hi(n,t,e){t==null&&(t=0),e==null&&(e=n.length);for(var i=1,r=t;r= 2"+(" but got x shape = "+n.shape+" and y shape = "+t.shape));if(t.rank>=3){var r=n.shape.slice(-1)[0],a=t.shape.slice(-2)[0];if(r!==a)throw new Te("If rank y >= 3, then the second last dim"+(" of y must equal the last dim of x but got x shape = "+n.shape+" and ")+(" y shape = "+t.shape))}if(n.rank===2&&t.rank===2){var s=!1,o=!1;return y.fused.matMul({a:n,b:t,transposeA:s,transposeB:o,bias:i?lh(n.rank,i,dn()):null,activation:e})}else{var l=n.shape.slice(),u=l.pop();n=n.reshape([-1,u]);var c=t.shape.slice(),h=c.pop(),a=c.pop(),d=c.concat([h]),p=Array.from({length:t.rank},function(b,S){return S===0?t.rank-2:S<=t.rank-2?S-1:S});t=t.transpose(p).reshape([a,-1]);var f=l.concat(d),s=!1,o=!1;return y.fused.matMul({a:n,b:t,transposeA:s,transposeB:o,bias:i?lh(n.rank,i,dn()):null,activation:e}).reshape(f)}}function kv(n,t,e){return y.tidy(function(){return Array.isArray(t)?t=y.tensor1d(t,"int32"):t=t.toInt(),y.gather(n,t,e)})}function Ea(n){return y.mul(n,n)}function lh(n,t,e){var i=t.shape;if(t.rank!==1&&t.rank!==n)throw new M("Unexpected bias dimensions: "+t.rank+("; expected it to be 1 or "+n));if(n===5){if(e==="channelsFirst")return i.length===1?t.reshape([1,i[0],1,1,1]):t.reshape([1,i[3],i[0],i[1],i[2]]);if(e==="channelsLast")return i.length===1?t.reshape([1,1,1,1,i[0]]):t.reshape([1].concat(i))}else if(n===4){if(e==="channelsFirst")return i.length===1?t.reshape([1,i[0],1,1]):t.reshape([1,i[2],i[0],i[1]]);if(e==="channelsLast")return i.length===1?t.reshape([1,1,1,i[0]]):t.reshape([1].concat(i))}else if(n===3){if(e==="channelsFirst")return i.length===1?t.reshape([1,i[0],1]):t.reshape([1,i[1],i[0]]);if(e==="channelsLast")return i.length===1?t.reshape([1,1,i[0]]):t.reshape([1].concat(i))}else if(n<3)return t;throw new M("Unsupported input rank by biasAdd: "+t.rank)}function Dn(n,t,e){return y.tidy(function(){return e==null&&(e=dn()),ct(e),n.add(lh(n.rank,t,e))})}function ik(n,t){if(t===void 0&&(t=1),t!==1)throw new Te("Support for alpha values other than 1 ("+t+") is not implemented yet.");return y.elu(n)}function rk(n){return y.tidy(function(){return y.div(n,y.abs(n).add(1))})}function Fv(n,t,e,i){return y.tidy(function(){return y.dropout(n,t,e,i)})}function ak(n){return y.tidy(function(){var t=y.add(.5,y.mul(.2,n));return y.clipByValue(t,0,1)})}function Da(n,t,e){return e===void 0&&(e=!1),e?n():t()}var sk=["fanIn","fanOut","fanAvg"],ok=["normal","uniform","truncatedNormal"];function lk(n){Wr(sk,"FanMode",n)}function uk(n){Wr(ok,"Distribution",n)}var on=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.fromConfigUsesCustomObjects=function(){return!1},t.prototype.getConfig=function(){return{}},t}(y.serialization.Serializable),Wv=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.apply=function(e,i){return y.zeros(e,i)},t.className="Zeros",t}(on);y.serialization.registerClass(Wv);var uh=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.apply=function(e,i){return y.ones(e,i)},t.className="Ones",t}(on);y.serialization.registerClass(uh);var Uv=function(n){Q(t,n);function t(e){var i=n.call(this)||this;if(typeof e!="object")throw new M("Expected argument of type ConstantConfig but got "+e);if(e.value===void 0)throw new M("config must have value set but got "+e);return i.value=e.value,i}return t.prototype.apply=function(e,i){var r=this;return y.tidy(function(){return y.mul(y.scalar(r.value),y.ones(e,i))})},t.prototype.getConfig=function(){return{value:this.value}},t.className="Constant",t}(on);y.serialization.registerClass(Uv);var Bv=function(n){Q(t,n);function t(e){var i=n.call(this)||this;return i.DEFAULT_MINVAL=-.05,i.DEFAULT_MAXVAL=.05,i.minval=e.minval||i.DEFAULT_MINVAL,i.maxval=e.maxval||i.DEFAULT_MAXVAL,i.seed=e.seed,i}return t.prototype.apply=function(e,i){return y.randomUniform(e,this.minval,this.maxval,i)},t.prototype.getConfig=function(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}},t.className="RandomUniform",t}(on);y.serialization.registerClass(Bv);var zv=function(n){Q(t,n);function t(e){var i=n.call(this)||this;return i.DEFAULT_MEAN=0,i.DEFAULT_STDDEV=.05,i.mean=e.mean||i.DEFAULT_MEAN,i.stddev=e.stddev||i.DEFAULT_STDDEV,i.seed=e.seed,i}return t.prototype.apply=function(e,i){if(i=i||"float32",i!=="float32"&&i!=="int32")throw new Te("randomNormal does not support dType "+i+".");return Js(e,this.mean,this.stddev,i,this.seed)},t.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},t.className="RandomNormal",t}(on);y.serialization.registerClass(zv);var _v=function(n){Q(t,n);function t(e){var i=n.call(this)||this;return i.DEFAULT_MEAN=0,i.DEFAULT_STDDEV=.05,i.mean=e.mean||i.DEFAULT_MEAN,i.stddev=e.stddev||i.DEFAULT_STDDEV,i.seed=e.seed,i}return t.prototype.apply=function(e,i){if(i=i||"float32",i!=="float32"&&i!=="int32")throw new Te("truncatedNormal does not support dType "+i+".");return y.truncatedNormal(e,this.mean,this.stddev,i,this.seed)},t.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},t.className="TruncatedNormal",t}(on);y.serialization.registerClass(_v);var Pv=function(n){Q(t,n);function t(e){var i=n.call(this)||this;return i.gain=e.gain!=null?e.gain:1,i}return t.prototype.apply=function(e,i){var r=this;return y.tidy(function(){if(e.length!==2||e[0]!==e[1])throw new M("Identity matrix initializer can only be used for 2D square matrices.");return y.mul(r.gain,y.eye(e[0]))})},t.prototype.getConfig=function(){return{gain:this.gain}},t.className="Identity",t}(on);y.serialization.registerClass(Pv);function ck(n,t){t===void 0&&(t="channelsLast");var e,i;if(ct(t),n.length===2)e=n[0],i=n[1];else if([3,4,5].indexOf(n.length)!==-1){if(t==="channelsFirst"){var r=hi(n,2);e=n[1]*r,i=n[0]*r}else if(t==="channelsLast"){var r=hi(n,0,n.length-2);e=n[n.length-2]*r,i=n[n.length-1]*r}}else{var a=hi(n);e=Math.sqrt(a),i=Math.sqrt(a)}return[e,i]}var Gt=function(n){Q(t,n);function t(e){var i=n.call(this)||this;if(e.scale<0)throw new M("scale must be a positive float. Got: "+e.scale);return i.scale=e.scale==null?1:e.scale,i.mode=e.mode==null?"fanIn":e.mode,lk(i.mode),i.distribution=e.distribution==null?"normal":e.distribution,uk(i.distribution),i.seed=e.seed,i}return t.prototype.apply=function(e,i){var r=ck(e),a=r[0],s=r[1],o=this.scale;if(this.mode==="fanIn"?o/=Math.max(1,a):this.mode==="fanOut"?o/=Math.max(1,s):o/=Math.max(1,(a+s)/2),this.distribution==="normal"){var l=Math.sqrt(o);if(i=i||"float32",i!=="float32"&&i!=="int32")throw new Te(this.getClassName()+" does not support dType "+i+".");return y.truncatedNormal(e,0,l,i,this.seed)}else{var u=Math.sqrt(3*o);return y.randomUniform(e,-u,u,i)}},t.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},t.className="VarianceScaling",t}(on);y.serialization.registerClass(Gt);var ch=function(n){Q(t,n);function t(e){return n.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})||this}return t.prototype.getClassName=function(){return Gt.className},t.className="GlorotUniform",t}(Gt);y.serialization.registerClass(ch);var hh=function(n){Q(t,n);function t(e){return n.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})||this}return t.prototype.getClassName=function(){return Gt.className},t.className="GlorotNormal",t}(Gt);y.serialization.registerClass(hh);var dh=function(n){Q(t,n);function t(e){return n.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})||this}return t.prototype.getClassName=function(){return Gt.className},t.className="HeNormal",t}(Gt);y.serialization.registerClass(dh);var ph=function(n){Q(t,n);function t(e){return n.call(this,{scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})||this}return t.prototype.getClassName=function(){return Gt.className},t.className="HeUniform",t}(Gt);y.serialization.registerClass(ph);var fh=function(n){Q(t,n);function t(e){return n.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})||this}return t.prototype.getClassName=function(){return Gt.className},t.className="LeCunNormal",t}(Gt);y.serialization.registerClass(fh);var mh=function(n){Q(t,n);function t(e){return n.call(this,{scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})||this}return t.prototype.getClassName=function(){return Gt.className},t.className="LeCunNormal",t}(Gt);y.serialization.registerClass(mh);var Mv=function(n){Q(t,n);function t(e){var i=n.call(this)||this;if(i.DEFAULT_GAIN=1,i.gain=e.gain==null?i.DEFAULT_GAIN:e.gain,i.seed=e.seed,i.seed!=null)throw new Te("Random seed is not implemented for Orthogonal Initializer yet.");return i}return t.prototype.apply=function(e,i){var r=this;return y.tidy(function(){if(e.length<2)throw new Te("Shape must be at least 2D.");e[0]*e[1]>2e3&&console.warn("Orthogonal initializer is being called on a matrix with more "+("than 2000 ("+e[0]*e[1]+") elements: ")+"Slowness may result.");var a=e[0]>e[1]?[e[1],e[0]]:e,s=Js(a,0,1,"float32"),o=y.linalg.gramSchmidt(s);return e[0]>e[1]&&(o=o.transpose()),y.mul(r.gain,o)})},t.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}},t.className="Orthogonal",t}(on);y.serialization.registerClass(Mv);var Hv={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function Vv(n,t){return t===void 0&&(t={}),Na(n,y.serialization.SerializationMap.getMap().classNameMap,t,"initializer")}function at(n){return th(n)}function et(n){if(typeof n=="string"){var t=n in Hv?Hv[n]:n;if(t==="GlorotNormal")return new hh;if(t==="GlorotUniform")return new ch;if(t==="HeNormal")return new dh;if(t==="HeUniform")return new ph;if(t==="LeCunNormal")return new fh;if(t==="LeCunUniform")return new mh;var e={};return e.className=t,e.config={},Vv(e)}else return n instanceof on?n:Vv(n)}function hk(){return new Wv}function dk(){return new uh}function pk(n){return new Uv(n)}function fk(n){return new Bv(n)}function mk(n){return new zv(n)}function gk(n){return new _v(n)}function vk(n){return new Pv(n)}function yk(n){return new Gt(n)}function bk(n){return new ch(n)}function wk(n){return new hh(n)}function Sk(n){return new dh(n)}function Lk(n){return new ph(n)}function Ik(n){return new fh(n)}function Ak(n){return new mh(n)}function Tk(n){return new Mv(n)}var Nk={__proto__:null,zeros:hk,ones:dk,constant:pk,randomUniform:fk,randomNormal:mk,truncatedNormal:gk,identity:vk,varianceScaling:yk,glorotUniform:bk,glorotNormal:wk,heNormal:Sk,heUniform:Lk,leCunNormal:Ik,leCunUniform:Ak,orthogonal:Tk};var xk=0;function qv(){return xk++}var Zs={};function Qs(n){return n===void 0&&(n=""),n in Zs||(Zs[n]=0),Zs[n]+=1,n+Zs[n].toString()}function gh(n){return Array.isArray(n)&&Array.isArray(n[0])}function eo(n){return n.length===0?[]:Array.isArray(n[0])?n:[n]}function xe(n){var t;if(Array.isArray(n)){if(n.length!==1)throw new M("Expected Tensor length to be 1; got "+n.length);t=n[0]}else t=n;return t}function Ge(n){if(Array.isArray(n)&&Array.isArray(n[0])){if(n.length===1)return n=n,n[0];throw new M("Expected exactly 1 Shape; got "+n.length)}else return n}function to(n){for(var t=0,e=0,i=n;e1)throw new ui("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use `getInputAt(nodeIndex)` instead.');if(this.inboundNodes.length===0)throw new ui("Layer "+this.name+" is not connected, no input to return.");return _t(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"output",{get:function(){if(this.inboundNodes.length===0)throw new ui("Layer "+this.name+" has no inbound nodes.");if(this.inboundNodes.length>1)throw new ui("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return _t(this.getNodeAtIndex(0,"output").outputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"losses",{get:function(){return this._losses},enumerable:!0,configurable:!0}),t.prototype.calculateLosses=function(){return this.losses.map(function(e){return e()})},Object.defineProperty(t.prototype,"updates",{get:function(){return this._updates},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"built",{get:function(){return this._built},set:function(e){this._built=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainable",{get:function(){return this.trainable_},set:function(e){this._trainableWeights.forEach(function(i){return i.trainable=e}),this.trainable_=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.trainable_?this._trainableWeights.filter(function(e){return e.trainable}):[]},set:function(e){this._trainableWeights=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this._trainableWeights.filter(function(e){return!e.trainable}).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)},set:function(e){this._nonTrainableWeights=e},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"stateful",{get:function(){return this._stateful},enumerable:!0,configurable:!0}),t.prototype.resetStates=function(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")},t.prototype.assertInputCompatibility=function(e){if(e=Xe(e),this.inputSpec==null||this.inputSpec.length===0)return;var i=Xe(this.inputSpec);if(e.length!==i.length)throw new M("Layer "+this.name+" expects "+i.length+" inputs, "+("but it received "+e.length+" input tensors. ")+("Input received: "+e));for(var r=0;r=0?l[c]:l[l.length+c];if(h!=null&&[h,null].indexOf(d)===-1)throw new M("Input "+r+" is incompatible with layer "+(this.name+": expected axis "+c+" of input shape to ")+("have value "+h+" but got shape "+l+"."))}}if(s.shape!=null)for(var p=0;p0&&Array.isArray(C[0])?v=C.map(function(W,F){return new fn(E,W,r,Xe(e),i,r.name,F)}):v=new fn(E,C,r,Xe(e),i,r.name),r.addInboundNode(e,v,null,null,I,C,i),r._refCount++,r.activityRegularizer!=null)throw new Te("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return v}})},t.prototype.warnOnIncompatibleInputShape=function(e){if(this.batchInputShape==null)return;if(e.length!==this.batchInputShape.length)console.warn("The rank of the input tensor provided (shape: "+(JSON.stringify(e)+") does not match that of the ")+("batchInputShape ("+JSON.stringify(this.batchInputShape)+") ")+("of the layer "+this.name));else{var i=!1;this.batchInputShape.forEach(function(r,a){r!=null&&e[a]!=null&&e[a]!==r&&(i=!0)}),i&&console.warn("The shape of the input tensor "+("("+JSON.stringify(e)+") does not ")+("match the expectation of layer "+this.name+": ")+(""+JSON.stringify(this.batchInputShape)))}},Object.defineProperty(t.prototype,"outputShape",{get:function(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new ui("The layer "+this.name+" has never been called and thus has no defined output shape.");for(var e=[],i=0,r=this.inboundNodes;i0)&&(t=n.sourceLayer,e=n.nodeIndex),t.inboundNodes.length===0)return[n];var i=t.inboundNodes[e];if(i.inboundLayers.length===0)return i.inputTensors;for(var r=[],a=0;a0?[4,Promise.all(t)]:[3,2];case 1:for(o=u.sent(),l=0;l=0&&Number.isInteger(t),function(){return"Verbosity level is expected to be an integer >= 0, "+("but got "+t)}),n.checkForDuplicate(e),n.constructors[t]==null&&(n.constructors[t]=[]),n.constructors[t].push(e)},n.checkForDuplicate=function(t){for(var e in n.constructors){var i=n.constructors[+e];i.forEach(function(r){if(r===t)throw new M("Duplicate callback constructor.")})}},n.clear=function(){n.constructors={}},n.createCallbacks=function(t){var e=[];for(var i in n.constructors){var r=+i;t>=r&&e.push.apply(e,n.constructors[r])}return e.map(function(a){return new a})},n.constructors={},n}();function ny(n,t,e,i,r,a,s,o,l){var u=new Zv,c=[new Fk].concat(ty.createCallbacks(t));n!=null&&c.push.apply(c,n),c.push(u);var h=new Jv(c);return h.setParams({epochs:e,initialEpoch:i,samples:r,steps:a,batchSize:s,verbose:t,doValidation:o,metrics:l}),{callbackList:h,history:u}}function mn(n,t,e){return t===void 0&&(t={}),e===void 0&&(e=!1),Na(n,y.serialization.SerializationMap.getMap().classNameMap,t,"layer",e)}function io(n,t){return y.tidy(function(){n.dtype!=="float32"&&(n=n.asType("float32"));var e=y.sum(Ea(n),t,!0),i=y.fill(e.shape,vt()),r=y.sqrt(y.maximum(e,i));return y.div(n,r)})}function Zi(n,t){return y.tidy(function(){return y.mean(Ea(y.sub(t,n)),-1)})}function ro(n,t){return y.tidy(function(){return y.mean(y.abs(y.sub(t,n)),-1)})}function _r(n,t){return y.tidy(function(){var e=y.sub(n,t),i=y.clipByValue(y.abs(n),vt(),Number.MAX_VALUE),r=y.abs(y.div(e,i));return y.mul(100,y.mean(r,-1))})}function Wk(n,t){return y.tidy(function(){var e=y.clipByValue(t,vt(),Number.MAX_VALUE),i=y.log(y.add(1,e)),r=y.clipByValue(n,vt(),Number.MAX_VALUE),a=y.log(y.add(1,r));return y.mean(Ea(y.sub(i,a)),-1)})}function Uk(n,t){return y.tidy(function(){var e=y.maximum(0,y.sub(1,y.mul(n,t)));return y.mean(Ea(e),-1)})}function Bk(n,t){return y.tidy(function(){var e=y.maximum(0,y.sub(1,y.mul(n,t)));return y.mean(e,-1)})}function zk(n,t){return y.tidy(function(){var e=y.sum(y.mul(n,t),-1),i=y.max(y.mul(y.sub(1,n),t),-1);return y.maximum(0,y.add(1,y.sub(i,e)))})}function _k(n,t){return y.tidy(function(){var e=Math.log(2),i=y.sub(t,n),r=y.sub(y.add(i,y.softplus(y.mul(-2,i))),e);return y.mean(r,-1)})}function Fa(n,t,e){return e===void 0&&(e=!1),y.tidy(function(){if(e)t=y.softmax(t);else{var i=y.sum(t,t.shape.length-1,!0);t=y.div(t,i)}return t=y.clipByValue(t,vt(),1-vt()),y.neg(y.sum(y.mul(n.toFloat(),y.log(t)),t.shape.length-1))})}function ao(n,t,e){return e===void 0&&(e=!1),y.tidy(function(){var i=y.floor(tk(n)).toInt();t=y.clipByValue(t,vt(),1-vt());var r=t.shape,a=y.oneHot(i,r[r.length-1]).reshape(r);return Fa(a,t,e)})}function Pk(n,t){if(!y.util.arraysEqual(n.shape,t.shape))throw new M("logits and labels must have the same shape, but got shapes "+(JSON.stringify(n.shape)+" and "+JSON.stringify(t.shape)));return y.tidy(function(){var e=t.relu(),i=t.abs().neg();return e.sub(t.mul(n)).add(i.exp().log1p())})}function so(n,t){return y.tidy(function(){var e;return e=y.clipByValue(t,vt(),1-vt()),e=y.log(y.div(e,y.sub(1,e))),y.mean(Pk(n,e),-1)})}function Mk(n,t){return y.tidy(function(){var e=y.clipByValue(n,vt(),1),i=y.clipByValue(t,vt(),1);return y.sum(y.mul(n,y.log(y.div(e,i))),-1)})}function Hk(n,t){return y.tidy(function(){var e=y.log(y.add(vt(),t));return y.mean(y.sub(t,y.mul(n,e)),-1)})}function bh(n,t){return y.tidy(function(){var e=io(n,-1),i=io(t,-1),r=y.mul(e,i);return y.neg(y.sum(r,-1))})}var oo={meanSquaredError:Zi,meanAbsoluteError:ro,meanAbsolutePercentageError:_r,meanSquaredLogarithmicError:Wk,squaredHinge:Uk,hinge:Bk,categoricalHinge:zk,logcosh:_k,categoricalCrossentropy:Fa,sparseCategoricalCrossentropy:ao,binaryCrossentropy:so,kullbackLeiblerDivergence:Mk,poisson:Hk,cosineProximity:bh};function wh(n){if(typeof n=="string"){if(n in oo)return oo[n];var t="Unknown loss "+n;throw n.toLowerCase().includes("softmaxcrossentropy")&&(t="Unknown loss "+n+'. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy'),new M(t)}else return n}function Sh(n,t){return y.tidy(function(){var e=y.mul(.5,y.onesLike(t)),i=Ra(y.greater(t,e),n.dtype);return y.mean(y.equal(n,i),-1)})}function Lh(n,t){return y.tidy(function(){return Ra(y.equal(y.argMax(n,-1),y.argMax(t,-1)),"float32")})}function iy(n,t){return y.tidy(function(){return y.logicalAnd(n.equal(1),t.equal(1)).sum().cast("float32")})}function Vk(n,t){return y.tidy(function(){return y.logicalAnd(n.equal(1),t.equal(0)).sum().cast("float32")})}function qk(n,t){return y.tidy(function(){return y.logicalAnd(n.equal(0),t.equal(1)).sum().cast("float32")})}function ry(n,t){return y.tidy(function(){var e=iy(n,t),i=qk(n,t),r=e.add(i);return y.where(y.greater(r,0),e.div(r),0).cast("float32")})}function Gk(n,t){return y.tidy(function(){var e=iy(n,t),i=Vk(n,t),r=e.add(i);return y.where(y.greater(r,0),e.div(r),0).cast("float32")})}function ay(n,t){return so(n,t)}function sy(n,t){return n.rank===t.rank&&(n=n.squeeze([n.rank-1])),t=t.argMax(-1),t.dtype!==n.dtype&&(t=t.asType(n.dtype)),y.equal(n,t).asType("float32")}var Yk=Zi,Kk=Zi,jk=ro,$k=ro,Xk=_r,Jk=_r,Ih=Fa,Zk=bh,oy=ao,lo={binaryAccuracy:Sh,categoricalAccuracy:Lh,precision:ry,categoricalCrossentropy:Ih,sparseCategoricalCrossentropy:oy,mse:Yk,MSE:Kk,mae:jk,MAE:$k,mape:Xk,MAPE:Jk,cosine:Zk};function Qk(n){if(typeof n=="string"&&n in lo)return lo[n];if(typeof n!="string"&&n!=null)return n;throw new M("Unknown metric "+n)}function uo(n){if(On(n!==null,"Unknown LossOrMetricFn "+n),typeof n=="string")return n;for(var t=void 0,e=0,i=Object.keys(oo);ely&&console.warn('User-defined metadata of model "'+t+'" is too large in '+("size (length="+i.length+" when serialized). It is not ")+"recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= "+(ly+"."))}}function Ah(n){if(n===null)return!0;if(typeof n=="object")if(Object.getPrototypeOf(n)===Object.prototype){for(var t=Object.keys(n),e=0,i=t;e1||o.length===1&&o[0].inboundLayers.length>1){t=!1;break}i.push.apply(i,o)}if(t)for(var l=0,u=n.layers;l0&&(i=i.slice(0,i.length-1)+" "),i+=n[r],i=i.slice(0,t[r]),i+=" ".repeat(t[r]-i.length);e(i)}function i3(n,t,e){var i;try{i=JSON.stringify(n.outputShape)}catch(o){i="multiple"}var r=n.name,a=n.getClassName(),s=[r+" ("+a+")",i,n.countParams().toString()];co(s,t,e)}function r3(n,t,e,i){var r;try{r=JSON.stringify(n.outputShape)}catch(v){r="multiple"}for(var a=[],s=0,o=n.inboundNodes;s0&&e.indexOf(l)===-1)continue;for(var u=0;ui.maxNumTensors&&(i.maxNumTensors=S),S0,function(){return"Expected at least one fetch, got none"});var e=[],i={};if(n.length===1){var r=dy(n[0],t);e=r.sorted,i=r.recipientMap}else for(var a=new Set,s=0,o=n;s0;){var c=l[l.length-1];if(e.has(c.name)){l.pop();continue}var h=u[u.length-1]===l.length-1;if(c.inputs.length===0||h)l.pop(),i.push(c),e.add(c.name),h&&u.pop();else{u.push(l.length-1);for(var d=0,p=c.inputs;d1 nodes"),On(c===0,"input layer has >1 tensors"),i.inputLayers.push(l),i.inputLayersNodeIndices.push(u),i.inputLayersTensorIndices.push(c)}i.inputNames=[],i.outputNames=[],i.feedInputShapes=[],i.feedInputNames=[],i.feedOutputNames=[];for(var p=0;p=0;)pt.splice(pt.indexOf(Wt),1);w.push(Wt)},I=[],C=[],E=0,k=i.outputs;Ern?1:0});for(var he=0,ye=le;he0)throw new M("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];for(var e=[],i=0,r=this.layers;i0)throw new M(v.length+" of "+a+" weights are not set: "+(""+v))}yh(d)},t.prototype.updatedConfig=function(){var e=this.getConfig(),i={};return i.className=this.getClassName(),i.config=e,i.kerasVersion="tfjs-layers "+Nh,i.backend="TensorFlow.js",i},t.prototype.toJSON=function(e,i){i===void 0&&(i=!0);var r=Th(this.updatedConfig());return i?JSON.stringify(r):r},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){e=Xe(e);for(var a=new Pr,s=0;s1)for(var c=0,h=u;c0){for(var m=[],g=0;g0&&G.apply(_t(X),ee)}function c(G){var Z=G.name,X=mn(G,i.customObjects!=null?i.customObjects:{});X.setFastWeightInitDuringBuild(a),s[Z]=X;var ee=G.inboundNodes;ee.forEach(function(ne){if(!(ne instanceof Array))throw new M("Corrupted configuration, expected array for nodeData: "+ne);l(X,ne)})}for(var h=i.name,d=i.layers,p=0,f=d;p0&&typeof n[Object.keys(n)[0]]=="object"){var r=[];return t.forEach(function(a){a in n?r.push(n[a]):r.push(null)}),r}else throw new Error("The model has multiple ("+i+") outputs, "+("so "+e+" must be either an array with ")+(i+" elements or an object with "+t+" keys. ")+("Provided "+e+" not understood: "+JSON.stringify(n)))}function py(n,t){return h3(n,t,"classWeight")}function fy(n,t,e,i){return Le(this,void 0,void 0,function(){var r,a,s,o,l;return ve(this,function(u){switch(u.label){case 0:if(t!=null||i!=null)throw new Error("Support sampleWeight is not implemented yet");return e!=null?(r=y.tidy(function(){if(n.shape.length===1)return n.clone();if(n.shape.length===2)if(n.shape[1]>1){var c=1;return n.argMax(c)}else{if(n.shape[1]===1)return n.reshape([n.shape[0]]);throw new Error("Encountered unexpected last-dimension size ("+n.shape[1]+") during handling of class weights. The size is expected to be >= 1.")}else throw new Error("Unexpected rank of target (y) tensor ("+n.rank+") during handling of class weights. The rank is expected to be 1 or 2.")}),o=(s=Array).from,[4,r.data()]):[3,2];case 1:return a=o.apply(s,[u.sent()]),y.dispose(r),l=[],a.forEach(function(c){if(e[c]==null)throw new Error("classWeight must contain all classes in the training data. "+("The class "+c+" exists in the data but not in ")+"classWeight");l.push(e[c])}),[2,y.tensor1d(l,"float32")];case 2:return[2,null]}})})}function d3(n,t){return y.mul(n,t)}var p3=32;function gy(n,t){var e,i,r=t;e=r.xs,i=r.ys,y.util.assert(e!=null&&i!=null,function(){return"A Dataset iterator for fitDataset() is expected to generate objects of the form `{xs: xVal, ys: yVal}`, where the two values may be `tf.Tensor`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates "+(""+t)});var a=my("input",n.inputNames,e),s=my("output",n.outputNames,i),o=a[0].shape[0];y.util.assert(a.length===n.inputs.length,function(){return"LayersModel has "+n.inputs.length+" inputs, but the dataset "+("provides "+a.length+" inputs. (Expected input keys: ")+(JSON.stringify(n.inputNames)+")")}),y.util.assert(s.length===n.outputs.length,function(){return"LayersModel has "+n.outputs.length+" outputs, but the dataset "+("provides "+s.length+" outputs. (Expected output keys: ")+(JSON.stringify(n.outputNames)+")")});for(var l=function(d){y.util.assert(a[d].shape[0]===o,function(){return"Batch size mismatch: input "+(n.inputNames[d]+" has "+a[d].shape[0]+"; ")+("expected "+o+" based on input "+n.inputNames[0]+".")})},u=0;u0&&Number.isInteger(e.epochs),function(){return"For fitDataset(), config.epochs is expected to be a positive "+("integer, but got "+e.epochs)}),y.util.assert(!i||e.batchesPerEpoch>0&&Number.isInteger(e.batchesPerEpoch),function(){return"For fitDataset(), config.batchesPerEpoch is expected to be a "+("positive integer if specified, but got "+e.batchesPerEpoch)}),y.util.assert(e.validationSplit==null,function(){return"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."}),n.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");n.isTraining=!0,X.label=1;case 1:return X.trys.push([1,,26,27]),r=e.validationData!=null,a=void 0,s=void 0,r&&(vy(e.validationData)?y.util.assert(e.validationBatches==null||e.validationBatches>0&&Number.isInteger(e.validationBatches),function(){return"For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, "+("but got "+e.validationBatches)}):(o=f3(e.validationData),a=o.xs,s=o.ys)),l=n.makeTrainFunction(),u=n.getDedupedMetricsNames(),c=void 0,r?c=u.slice().concat(u.map(function(ee){return"val_"+ee})):c=u.slice(),h=ey(e.callbacks,e.yieldEvery),d=e.verbose==null?1:e.verbose,p=ny(h,d,e.epochs,null,null,m3(t,e),null,r,c),f=p.callbackList,m=p.history,f.setModel(n),n.history=m,[4,f.onTrainBegin()];case 2:return X.sent(),n.stopTraining_=!1,g=e.initialEpoch==null?0:e.initialEpoch,[4,t.iterator()];case 3:v=X.sent(),X.label=4;case 4:return g=e.batchesPerEpoch:w.done)?r?(G=void 0,vy(e.validationData)?(Z=Xe,[4,n.evaluateDataset(e.validationData,{batches:e.validationBatches})]):[3,17]):[3,19]:[3,20];case 16:return G=Z.apply(void 0,[X.sent()]),[3,18];case 17:G=Xe(n.evaluate(a,s,{batchSize:e.validationBatchSize==null?p3:e.validationBatchSize,verbose:0})),X.label=18;case 18:for(F=0;F0)throw new Te("Verbose mode is not implemented yet.");return y.util.assert(!i||e.batches>0&&Number.isInteger(e.batches),function(){return"Test loop expects `batches` to be a positive integer, but "+("received "+JSON.stringify(e.batches))}),v3(t)?(o=t,[3,3]):[3,1];case 1:return[4,t.iterator()];case 2:o=f.sent(),f.label=3;case 3:s=o,l=0,u=0,c=function(){var m;return ve(this,function(g){switch(g.label){case 0:return[4,s.next()];case 1:return m=g.sent(),a=y.tidy(function(){if(m.value){var v=gy(n,m.value),b=v.xs,S=v.ys,L=b.concat(S),w=y.tidy(function(){return r(L)});if(y.dispose(L),u===0)for(var N=0;N0&&y.dispose(W)},N=0;N0&&Number.isInteger(n),function(){return"batchSize is required to be a positive integer, but got "+n})}function Ba(n,t,e){return n==null?[null]:Array.isArray(n)?n.map(function(i){return Ji(i,t,e-t)}):Ji(n,t,e-t)}function Rh(n,t){return y.tidy(function(){return n==null?null:Array.isArray(n)?n.map(function(e){return Rh(e,t)}):kv(n,t.dtype==="int32"?t:t.toInt())})}function Oh(n,t){for(var e=[],i=0,r=null;i=n&&(r=n),e.push([i,r]),i=r;return e}function b3(n,t,e,i,r,a,s,o,l,u,c,h,d,p,f){return Le(this,void 0,void 0,function(){var m,g,v,b,S,L,w,N,I;return ve(this,function(C){switch(C.label){case 0:if(r==null&&(r=32),a==null&&(a=1),c==null&&(c=!0),d==null&&(d=0),m=!1,l!=null&&u!=null&&(m=!0),f!=null&&(m=!0,p==null))throw new M("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");return g=n.checkNumSamples(e,r,p,"steps_per_epoch"),g!=null&&(v=pn(0,g)),s==null&&(s=1),b=ny(o,s,a,d,g,p,r,m,h),S=b.callbackList,L=b.history,S.setModel(n),n.history=L,[4,S.onTrainBegin()];case 1:C.sent(),n.stopTraining_=!1,w=function(E){var k,W,F,_,H,P;return ve(this,function(K){switch(K.label){case 0:return[4,S.onEpochBegin(E)];case 1:if(K.sent(),k={},!(p!=null))return[3,2];throw new Te("stepsPerEpoch mode is not implemented yet.");case 2:if(c==="batch")throw new Te("batch shuffling is not implemneted yet");c&&y.util.shuffle(v),W=y.tensor1d(v),F=Oh(g,r),_=function(j){var q;return ve(this,function(G){switch(G.label){case 0:return q={},[4,S.onBatchBegin(j,q)];case 1:return G.sent(),y.tidy(function(){var Z=F[j][0],X=F[j][1],ee=Ji(W,Z,X-Z);q.batch=j,q.size=X-Z;for(var ne=Rh(e,ee),ie=t(ne),te=0;te0))return[3,4];if(f=!0,i.validationData.length===2)s=i.validationData[0],o=i.validationData[1];else throw i.validationData.length===3?new Te("validationData including sample weights is not supported yet."):new M("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; "+(i.validationData+" is invalid."));return g=!0,[4,n.standardizeUserData(s,o,null,null,g,h)];case 3:return v=W.sent(),l=v[0],u=v[1],m=l.concat(u),[3,5];case 4:i.validationSplit!=null&&i.validationSplit>0&&i.validationSplit<1?(f=!0,b=Math.floor(r[0].shape[0]*(1-i.validationSplit)),S=r[0].shape[0],l=Ba(r,b,S),r=Ba(r,0,b),u=Ba(a,b,S),a=Ba(a,0,b),m=l.concat(u)):i.validationSteps!=null&&(f=!0),W.label=5;case 5:return L=r.concat(a).concat(c),n.checkTrainableWeightsConsistency(),w=n.makeTrainFunction(),N=n.getDedupedMetricsNames(),I=void 0,C=void 0,f?(n.makeTestFunction(),I=n.testFunction,C=N.slice().concat(N.map(function(F){return"val_"+F}))):(I=null,m=[],C=N.slice()),E=ey(i.callbacks,i.yieldEvery),[4,b3(n,w,L,N,h,i.epochs,i.verbose,E,I,m,i.shuffle,C,i.initialEpoch,null,null)];case 6:return k=W.sent(),[2,k];case 7:return n.isTraining=!1,Qi(r,t),Qi(a,e),Qi(l,s),Qi(u,o),c!=null&&y.dispose(c),[7];case 8:return[2]}})})}function yy(n){var t=[];n instanceof y.Tensor&&(n=[n]);for(var e=0;e0)a=!0;else if(by(n)){for(var s in n)if(n.hasOwnProperty(s)){a=!0;break}}else a=!0;if(a)throw new M("Error when checking model "+r+" expected no data, "+("but got "+n))}return[]}if(n==null)return t.map(function(g){return null});var o;if(by(n)){n=n,o=[];for(var l=0,u=t;l1)throw new M("The model "+r+" expects "+t.length+" Tensor(s), "+("but only received one Tensor. Found: Tensor with shape "+n.shape));o=[n]}if(o=yy(o),e!=null)for(var h=0;h=0&&f!==m)throw new M("Error when checking "+r+": expected "+t[h]+" "+("to have shape ["+e[h]+"], but got array with shape ")+("["+d.shape+"]."))}}return o}function L3(n,t,e){var i=ci(n.map(function(a){return a.shape[0]}));i.sort();var r=ci(t.map(function(a){return a.shape[0]}));if(r.sort(),i.length>1)throw new M("All input Tensors (x) should have the same number of samples. Got array shapes: "+(""+JSON.stringify(n.map(function(a){return a.shape}))));if(r.length>1)throw new M("All target Tensors (y) should have the same number of samples. Got array shapes: "+(""+JSON.stringify(t.map(function(a){return a.shape}))));if(i.length>0&&r.length>0&&!y.util.arraysEqual(i,r))throw new M("Input Tensors should have the same number of samples as target "+("Tensors. Found "+i[0]+" input sample(s) and "+r[0]+" target ")+"sample(s).")}function I3(n,t,e){for(var i=[Zi,so,Fa],r=0;r1)throw new M("The model expects "+t.length+" "+r+" Tensors, but only received one Tensor. Found: array with shape "+(JSON.stringify(n.shape)+"."));a=[n]}if(e!=null)for(var s=0;s1&&(i.metricsTensors.push([b,v]),i.metricsNames.push(i.outputNames[v]+"_loss"))}});var m=A3(e.metrics,this.outputNames),g=function(v,b,S){i.outputNames.length>1&&(b=i.outputNames[v]+"_"+b),i.metricsNames.push(b),i.metricsTensors.push([S,v])};Xi("metric",function(){for(var v=function(S){if(f.indexOf(S)!==-1)return"continue";var L=m[S],w=function(N){for(var I="",C,E,k,W=function(P){if(typeof P=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(P)!==-1){var K=i.internalOutputShapes[S];K[K.length-1]===1||i.lossFunctions[S]===so?["accuracy","acc"].indexOf(P)!==-1?E=Sh:["crossentropy","ce"].indexOf(P)!==-1&&(E=ay):i.lossFunctions[S]===ao?["accuracy","acc"].indexOf(P)!==-1?E=sy:["crossentropy","ce"].indexOf(P)!==-1&&(E=oy):["accuracy","acc"].indexOf(P)!==-1?E=Lh:["crossentropy","ce"].indexOf(P)!==-1&&(E=Ih);var j=void 0;["accuracy","acc"].indexOf(P)!==-1?j="acc":["crossentropy","ce"].indexOf(P)!==-1&&(j="ce"),k=E,C=I+j}else{var q=Qk(P);k=q,C=I+uo(P)}var G;Xi(C,function(){G=k}),g(S,C,G)},F=0,_=N;F<_.length;F++){var H=_[F];W(H)}};w(L)},b=0;b0){var d=[];throw i.forEach(function(p,f){p==null&&d.push(e[f])}),new M("Cannot find SymbolicTensors for output name(s): "+(""+JSON.stringify(d)))}return i},t.prototype.predictLoop=function(e,i,r){var a=this;return i===void 0&&(i=32),r===void 0&&(r=!1),y.tidy(function(){var s=a.checkNumSamples(e);if(r)throw new Te("Verbose predictLoop() is not implemented yet.");for(var o=Oh(s,i),l=a.outputs.map(function(h){return[]}),u=function(h){var d=y.tidy(function(){var p=o[h][0],f=o[h][1],m=Ba(e,p,f),g=[];if(Array.isArray(m))for(var v=0;v0&&e[0].shape[0]%a!==0)throw new M("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size "+(a+". Found: "+e[0].shape[0]+" sample(s)."));return[e,i]},t.prototype.standardizeUserData=function(e,i,r,a,s,o){return s===void 0&&(s=!0),Le(this,void 0,void 0,function(){var l,u,c,h,d,p,f,m;return ve(this,function(g){switch(g.label){case 0:if(l=this.standardizeUserDataXY(e,i,s,o),u=l[0],c=l[1],r!=null)throw new Error("sample weight is not supported yet.");if(h=null,!(a!=null))return[3,4];d=py(a,this.outputNames),h=[],p=0,g.label=1;case 1:return p0)throw new Te("Verbose mode is not implemented yet.");if(s!=null)throw new Te("steps mode in testLoop() is not implemented yet");for(var c=Oh(l,r),h=y.tensor1d(pn(0,l)),d=0;d1){var o=vv(e.slice(0,r),a);s+="_"+o}i.push(s)}return i},t.prototype.makeTrainFunction=function(){var e=this;return function(i){var r=[],a=i.slice(0,e.inputs.length),s=i.slice(e.inputs.length,e.inputs.length+e.outputs.length),o=i.slice(e.inputs.length+e.outputs.length,e.inputs.length+e.outputs.length*2),l=[],u=function(){for(var p=[],f=0;f1&&f1)throw new M("Found more than one ("+r.length+") save handlers for "+("URL '"+e+"'"));e=r[0]}if(e.save==null)throw new M("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[4,y.io.encodeWeights(this.getNamedWeights(i))];case 1:return a=S.sent(),s=!1,o=null,l=this.toJSON(o,s),u={modelTopology:l,format:T3,generatedBy:"TensorFlow.js tfjs-layers v"+Nh,convertedBy:null},c=i==null?!1:i.includeOptimizer,c&&this.optimizer!=null?(u.trainingConfig=this.getTrainingConfig(),h="optimizer",g=(m=y.io).encodeWeights,[4,this.optimizer.getWeights()]):[3,4];case 2:return[4,g.apply(m,[S.sent(),h])];case 3:d=S.sent(),p=d.data,f=d.specs,(b=a.specs).push.apply(b,f),a.data=y.io.concatenateArrayBuffers([a.data,p]),S.label=4;case 4:return this.userDefinedMetadata!=null&&(v=!0,uy(this.userDefinedMetadata,this.name,v),u.userDefinedMetadata=this.userDefinedMetadata),u.weightData=a.data,u.weightSpecs=a.specs,[2,e.save(u)]}})})},t.prototype.setUserDefinedMetadata=function(e){uy(e,this.name),this.userDefinedMetadata=e},t.prototype.getUserDefinedMetadata=function(){return this.userDefinedMetadata},t.className="Model",t}(c3);y.serialization.registerClass(fi);var N3=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.className="Functional",t}(fi);y.serialization.registerClass(N3);function x3(n,t){return Le(this,void 0,void 0,function(){var e,i,r,a,s,o,l,u;return ve(this,function(c){switch(c.label){case 0:return"modelTopology"in n||(n={modelTopology:n}),n=n,e=n.modelTopology,e.model_config!=null&&(e=e.model_config),i=Wa(e),r=mn(i,t),n.weightsManifest!=null?[4,y.io.loadWeights(n.weightsManifest,n.pathPrefix,r.weights.map(function(h){return h.originalName}))]:[3,2];case 1:for(a=c.sent(),s={},o=0,l=r.weights;o1)throw new M("Found more than one ("+e.length+") load handlers for "+("URL '"+n+"'"));n=e[0]}return[2,C3(n,void 0,t)]})})}function C3(n,t,e){return Le(this,void 0,void 0,function(){var i,r,a,s,o,l,u,c,h;return ve(this,function(d){switch(d.label){case 0:if(e==null&&(e={}),n.load==null)throw new M("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,n.load()];case 1:if(i=d.sent(),r=i.modelTopology,r.model_config!=null&&(r=r.model_config),a=e.strict==null?!0:e.strict,s=i.weightData!=null&&i.weightSpecs!=null&&a,o=mn(Wa(r),t,s),l=i.trainingConfig,l!=null&&o.loadTrainingConfig(l),i.userDefinedMetadata!=null&&o.setUserDefinedMetadata(i.userDefinedMetadata),!(i.weightData!=null))return[3,4];if(i.weightSpecs==null)throw new M("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");return u=O3(i.weightData,i.weightSpecs),c=u.modelWeights,h=u.optimizerWeights,o.loadWeights(c,a),o.optimizer!=null&&h.length>0?[4,o.optimizer.setWeights(h)]:[3,3];case 2:d.sent(),d.label=3;case 3:y.dispose(c),y.dispose(h.map(function(p){return p.tensor})),d.label=4;case 4:return[2,o]}})})}function O3(n,t){var e=y.io.decodeWeights(n,t),i={},r=[];return t.forEach(function(a){a.group==="optimizer"?r.push({name:a.name,tensor:e[a.name]}):i[a.name]=e[a.name]}),{modelWeights:i,optimizerWeights:r}}var Dh=function(n){Q(t,n);function t(e){var i=n.call(this,{inputs:[],outputs:[]})||this;if(e=e||{},i.trainable=!0,i.built=!1,i.name=e.name!=null?e.name:Qs("sequential_"),e.layers!=null)for(var r=0,a=e.layers;r 0 "+("but got "+JSON.stringify(e.filters)))},t}(Wy),Uh=function(n){Q(t,n);function t(e){var i=n.call(this,2,e)||this;return t.verifyArgs(e),i}return t.prototype.getConfig=function(){var e=n.prototype.getConfig.call(this);return delete e.rank,e},t.verifyArgs=function(e){if(typeof e.kernelSize!="number"&&!ih(e.kernelSize,"number",1,2))throw new M("Conv2D expects config.kernelSize to be number or number[] with "+("length 1 or 2, but received "+JSON.stringify(e.kernelSize)+"."))},t.className="Conv2D",t}(fo);y.serialization.registerClass(Uh);var Uy=function(n){Q(t,n);function t(e){var i=n.call(this,3,e)||this;return t.verifyArgs(e),i}return t.prototype.getConfig=function(){var e=n.prototype.getConfig.call(this);return delete e.rank,e},t.verifyArgs=function(e){if(typeof e.kernelSize!="number"&&!(Array.isArray(e.kernelSize)&&(e.kernelSize.length===1||e.kernelSize.length===3)))throw new M("Conv3D expects config.kernelSize to be number or"+(" [number, number, number], but received "+JSON.stringify(e.kernelSize)+"."))},t.className="Conv3D",t}(fo);y.serialization.registerClass(Uy);var By=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;if(i.inputSpec=[new Tt({ndim:4})],i.padding!=="same"&&i.padding!=="valid")throw new M("Conv2DTranspose currently supports only padding modes 'same' "+("and 'valid', but received padding mode "+i.padding));return i}return t.prototype.build=function(e){var i;if(e=Ge(e),e.length!==4)throw new M("Input should have rank 4; Received input shape: "+JSON.stringify(e));var r=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[r]==null)throw new M("The channel dimension of the inputs should be defined. Found `None`.");var a=e[r],s=this.kernelSize.concat([this.filters,a]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Tt({ndim:4,axes:(i={},i[r]=a,i)})],this.built=!0},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){var a=xe(e);if(a.shape.length!==4)throw new M("Conv2DTranspose.call() expects input tensor to be rank-4, but "+("received a tensor of rank-"+a.shape.length));var s=a.shape,o=s[0],l,u;r.dataFormat==="channelsFirst"?(l=2,u=3):(l=1,u=2);var c=s[l],h=s[u],d=r.kernelSize[0],p=r.kernelSize[1],f=r.strides[0],m=r.strides[1],g=po(c,f,d,r.padding),v=po(h,m,p,r.padding),b=[o,g,v,r.filters];r.dataFormat!=="channelsLast"&&(a=y.transpose(a,[0,2,3,1]));var S=y.conv2dTranspose(a,r.kernel.read(),b,r.strides,r.padding);return r.dataFormat!=="channelsLast"&&(S=y.transpose(S,[0,3,1,2])),r.bias!=null&&(S=Dn(S,r.bias.read(),r.dataFormat)),r.activation!=null&&(S=r.activation.apply(S)),S})},t.prototype.computeOutputShape=function(e){e=Ge(e);var i=e.slice(),r,a,s;this.dataFormat==="channelsFirst"?(r=1,a=2,s=3):(r=3,a=1,s=2);var o=this.kernelSize[0],l=this.kernelSize[1],u=this.strides[0],c=this.strides[1];return i[r]=this.filters,i[a]=po(i[a],u,o,this.padding),i[s]=po(i[s],c,l,this.padding),i},t.prototype.getConfig=function(){var e=n.prototype.getConfig.call(this);return delete e.dilationRate,e},t.className="Conv2DTranspose",t}(Uh);y.serialization.registerClass(By);var J3=function(n){Q(t,n);function t(e,i){var r=n.call(this,e,i)||this;if(r.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",r.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",r.depthwiseKernel=null,r.pointwiseKernel=null,i.filters==null)throw new M("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(i.kernelInitializer!=null||i.kernelRegularizer!=null||i.kernelConstraint!=null)throw new M("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(i.padding!=null&&i.padding!=="same"&&i.padding!=="valid")throw new M("SeparableConv"+r.rank+"D supports only padding modes: "+("'same' and 'valid', but received "+JSON.stringify(i.padding)));return r.depthMultiplier=i.depthMultiplier==null?1:i.depthMultiplier,r.depthwiseInitializer=et(i.depthwiseInitializer||r.DEFAULT_DEPTHWISE_INITIALIZER),r.depthwiseRegularizer=tt(i.depthwiseRegularizer),r.depthwiseConstraint=bt(i.depthwiseConstraint),r.pointwiseInitializer=et(i.depthwiseInitializer||r.DEFAULT_POINTWISE_INITIALIZER),r.pointwiseRegularizer=tt(i.pointwiseRegularizer),r.pointwiseConstraint=bt(i.pointwiseConstraint),r}return t.prototype.build=function(e){var i;if(e=Ge(e),e.length1&&(t=n.slice(1,n.length)),n=n[0]}function r(a){return a==null||Array.isArray(a)?a:[a]}return t=r(t),e=r(e),{inputs:n,initialState:t,constants:e}}function qy(n,t,e,i,r,a,s,o){return i===void 0&&(i=!1),s===void 0&&(s=!1),o===void 0&&(o=!1),y.tidy(function(){var l=t.shape.length;if(l<3)throw new M("Input should be at least 3D, but is "+l+"D.");var u=[1,0].concat(pn(2,l));if(t=y.transpose(t,u),a!=null)throw new Te("The rnn() functoin of the deeplearn.js backend does not support constants yet.");s&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),r!=null&&(r=r.asType("bool").asType("float32"),r.rank===l-1&&(r=y.expandDims(r,-1)),r=y.transpose(r,u)),i&&(t=y.reverse(t,0),r!=null&&(r=y.reverse(r,0)));var c=[],h,d=e,p=t.shape[0],f=y.unstack(t),m;r!=null&&(m=y.unstack(r));for(var g=function(L){var w=f[L],N=y.tidy(function(){return n(w,d)});if(r==null)h=N[0],d=N[1];else{var I=y.tidy(function(){var C=m[L],E=y.onesLike(C).sub(C),k=N[0].mul(C).add(d[0].mul(E)),W=d.map(function(F,_){return N[1][_].mul(C).add(F.mul(E))});return{output:k,newStates:W}});h=I.output,d=I.newStates}o&&c.push(h)},v=0;v1?ah(r,[1,a]):r}):i.cell.stateSize>1?[ah(r,[1,i.cell.stateSize])]:[r]})},Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.trainable?this.cell.trainableWeights:[]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights},enumerable:!0,configurable:!0}),t.prototype.setFastWeightInitDuringBuild=function(e){n.prototype.setFastWeightInitDuringBuild.call(this,e),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(e)},t.prototype.getConfig=function(){var e=n.prototype.getConfig.call(this),i={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(i.numConstants=this.numConstants);var r=this.cell.getConfig();return this.getClassName()===t.className&&(i.cell={className:this.cell.getClassName(),config:r}),qt({},r,e,i)},t.fromConfig=function(e,i,r){r===void 0&&(r={});var a=i.cell,s=mn(a,r);return new e(Object.assign(i,{cell:s}))},t.className="RNN",t}(De);y.serialization.registerClass(vi);var Hr=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t}(De),zh=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.DEFAULT_ACTIVATION="tanh",i.DEFAULT_KERNEL_INITIALIZER="glorotNormal",i.DEFAULT_RECURRENT_INITIALIZER="orthogonal",i.DEFAULT_BIAS_INITIALIZER="zeros",i.units=e.units,At(i.units,"units"),i.activation=gi(e.activation==null?i.DEFAULT_ACTIVATION:e.activation),i.useBias=e.useBias==null?!0:e.useBias,i.kernelInitializer=et(e.kernelInitializer||i.DEFAULT_KERNEL_INITIALIZER),i.recurrentInitializer=et(e.recurrentInitializer||i.DEFAULT_RECURRENT_INITIALIZER),i.biasInitializer=et(e.biasInitializer||i.DEFAULT_BIAS_INITIALIZER),i.kernelRegularizer=tt(e.kernelRegularizer),i.recurrentRegularizer=tt(e.recurrentRegularizer),i.biasRegularizer=tt(e.biasRegularizer),i.kernelConstraint=bt(e.kernelConstraint),i.recurrentConstraint=bt(e.recurrentConstraint),i.biasConstraint=bt(e.biasConstraint),i.dropout=Br([1,di([0,e.dropout==null?0:e.dropout])]),i.recurrentDropout=Br([1,di([0,e.recurrentDropout==null?0:e.recurrentDropout])]),i.stateSize=i.units,i.dropoutMask=null,i.recurrentDropoutMask=null,i}return t.prototype.build=function(e){e=Ge(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){if(e=e,e.length!==2)throw new M("SimpleRNNCell expects 2 input Tensors, got "+e.length+".");var a=e[1];e=e[0];var s=i.training==null?!1:i.training;01){for(var s=[0],o=2;o1)throw new M("Can not merge tensors with different batch sizes. "+("Got tensors with shapes: "+JSON.stringify(e)+"."));for(var o=e[0]==null?null:e[0].slice(1),l=1;l1){var L=pn(1,h).concat([0]);a.push(y.transpose(c,L)),p=!0}else a.push(c)}var w=r.mergeFunction(a),N=w.rank;if(p){if(N==null){var I=w.shape,C=I.length,v=I[C-1],b=[v].concat(I.slice(0,I.length-1));w=y.transpose(w.reshape([-1,v]),[1,0]).reshape(b)}else if(N>1){var L=[N-1].concat(pn(0,N-1));w=y.transpose(w,L)}}return w}}else return r.mergeFunction(e)})},t.prototype.computeOutputShape=function(e){e=e;var i;e[0]==null?i=null:i=e[0].slice(1);for(var r=1;r1)throw new M("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))},t.prototype.mergeFunction=function(e){var i=this;return y.tidy(function(){return oh(e,i.axis)})},t.prototype.computeOutputShape=function(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new M("A `Concatenate` layer should be called on a list of inputs.");for(var i=e,r=i[0].slice(),a=this.axis<0?r.length+this.axis:this.axis,s=0,o=i.slice(1);s3||t.shape.length>3)throw new Te("batchDot is not implemented for tensors of 4D or higher rank yet");if(y.util.assert(n.shape.length>=2,function(){return"batchDot requires the rank of x to be >= 2, "+("but got "+n.shape.length)}),y.util.assert(n.shape.length>=2,function(){return"batchDot requires the rank of y to be >= 2, "+("but got "+t.shape.length)}),typeof e=="number"&&(e=[e,e]),n.dtype==="complex64"||t.dtype==="complex64")throw new Te("batchDot is not implemented for complex64-type Tensors yet.");var i=n.shape.length,r=t.shape.length;e==null&&(e=[i-1,r-2]);var a=e;return y.tidy(function(){var s;if(i>r){s=i-r;for(var o=[],l=0;li){s=r-i;for(var o=[],l=0;l0){var d=void 0;i>r?d=i+r-3:d=i-1;for(var p=[],l=d;l3||r.length>3)throw new Te("Dot layer does not support tensors of 4D or higher rank yet.");var a=this.interpretAxes(i,r);if(i[a[0]]!==r[a[1]])throw new M("Dimension incompatibility: "+(i[a[0]]+" !== "+r[a[1]]))},t.prototype.mergeFunction=function(e){if(e.length!==2)throw new M("A `Dot` layer must be called on exactly 2 inputs, "+("but received "+e.length+" input(s)."));var i=e[0],r=e[1],a;return Array.isArray(this.axes)?a=this.axes.map(function(s,o){return za(s,e[o].shape.length)}):a=[za(this.axes,i.shape.length),za(this.axes,r.shape.length)],this.normalize&&(i=io(i,a[0]),r=io(r,a[1])),e4(i,r,a)},t.prototype.interpretAxes=function(e,i){var r;return Array.isArray(this.axes)?r=this.axes:r=[za(this.axes,e.length),za(this.axes,i.length)],r},t.prototype.computeOutputShape=function(e){y.util.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),function(){return"A `Dot` layer should be called on a list of exactly 2 inputs."});var i=e[0].slice(),r=e[1].slice();if(i.length>3||r.length>3)throw new Te("Dot layer does not support tensors of 4D or higher rank yet.");var a=this.interpretAxes(i,r);i.splice(a[0],1),r.splice(a[1],1),r.splice(0,1);var s=i.concat(r);return s.length===1&&s.push(1),s},t.prototype.computeMask=function(e,i){return null},t.prototype.getConfig=function(){var e={axes:this.axes,normalize:this.normalize},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t.className="Dot",t}(er);y.serialization.registerClass(cb);var hb=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.supportsMasking=!0,i.stddev=e.stddev,i}return t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var e=n.prototype.getConfig.call(this),i={stddev:this.stddev};return Object.assign(i,e),i},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){r.invokeCallHook(e,i);var a=xe(e),s=function(){return Js(a.shape,0,r.stddev).add(a)},o=Da(s,function(){return a},i.training||!1);return o})},t.className="GaussianNoise",t}(De);y.serialization.registerClass(hb);var db=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.supportsMasking=!0,i.rate=e.rate,i}return t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var e=n.prototype.getConfig.call(this),i={rate:this.rate};return Object.assign(i,e),i},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){r.invokeCallHook(e,i);var a=xe(e);if(r.rate>0&&r.rate<1){var s=function(){var o=Math.sqrt(r.rate/(1-r.rate));return a.mul(Js(a.shape,1,o))};return Da(s,function(){return a},i.training||!1)}return a})},t.className="GaussianDropout",t}(De);y.serialization.registerClass(db);var pb=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.supportsMasking=!0,i.rate=e.rate,i.noiseShape=e.noiseShape,i}return t.prototype._getNoiseShape=function(e){return this.noiseShape||xe(e).shape},t.prototype.computeOutputShape=function(e){return e},t.prototype.getConfig=function(){var e=n.prototype.getConfig.call(this),i={rate:this.rate};return Object.assign(i,e),i},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){if(r.rate<1&&r.rate>0){var a=r._getNoiseShape(e),s=function(){var o=xe(e),l=1.6732632423543772,u=1.0507009873554805,c=-l*u,h=y.greaterEqual(y.randomUniform(a),r.rate);h=Ra(h,"float32");var d=Math.pow((1-r.rate)*(1+r.rate*Math.pow(c,2)),-.5),p=-d*c*r.rate,f=o.mul(h).add(h.add(-1).mul(c));return f.mul(d).add(p)};return Da(s,function(){return xe(e)},i.training||!1)}return e})},t.className="AlphaDropout",t}(De);y.serialization.registerClass(pb);function _a(n,t,e,i,r,a){a===void 0&&(a=.001);var s;if(n.rank===2)s=y.batchNorm2d(n,t,e,i,r,a);else if(n.rank===3)s=y.batchNorm3d(n,t,e,i,r,a);else if(n.rank===4)s=y.batchNorm4d(n,t,e,i,r,a);else throw new Te("batchNormalization is not implemented for array of rank "+n.rank+" yet");return s}function t4(n,t,e,i,r){return r===void 0&&(r=.001),y.tidy(function(){var a=y.moments(n,i),s=a.mean,o=a.variance,l=_a(n,s,o,e,t,r);return[l,s,o]})}function n4(n,t,e,i,r){return r===void 0&&(r=.001),y.tidy(function(){for(var a=y.moments(n,i),s=a.mean,o=a.variance,l=[],u=0,c=pn(0,n.rank);u=0?this.axis:this.axis+e.length,a=e[r];if(a==null)throw new M("Axis "+r+" of input tensor should have a defined dimension but the layer received an input with shape "+(JSON.stringify(e)+"."));this.inputSpec=[new Tt({ndim:e.length,axes:(i={},i[r]=a,i)})];var s=[a];this.scale&&(this.gamma=this.addWeight("gamma",s,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",s,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",s,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",s,null,this.movingVarianceInitializer,null,!1),this.built=!0},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){var a=i.training==null?!1:i.training,s=xe(e),o=s.shape,l=o.length,u=pn(0,l),c=r.axis>=0?r.axis:r.axis+l;u.splice(c,1);var h=ji(1,l);h[c]=o[c];var d=u.slice();d.sort();var p=!y.util.arraysEqual(d,pn(0,l).slice(0,l-1)),f=function(){if(p){var w=r.movingMean.read().reshape(h),N=r.movingVariance.read().reshape(h),I=r.center?r.beta.read().reshape(h):null,C=r.scale?r.gamma.read().reshape(h):null;return _a(s,w,N,I,C,r.epsilon)}else return _a(s,r.movingMean.read(),r.movingVariance.read(),r.beta==null?null:r.beta.read(),r.gamma==null?null:r.gamma.read(),r.epsilon)};if(!a)return f();var m=i4(s,r.gamma.read(),r.beta.read(),u,r.epsilon),g=m[0],v=m[1],b=m[2],S=function(w,N,I){y.tidy(function(){var C=1-I,E=w.read(),k=E.sub(N).mul(C);w.write(E.sub(k))})},L=function(){S(r.movingMean,v,r.momentum),S(r.movingVariance,b,r.momentum)};return L(),g})},t.prototype.getConfig=function(){var e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:at(this.betaInitializer),gammaInitializer:at(this.gammaInitializer),movingMeanInitializer:at(this.movingMeanInitializer),movingVarianceInitializer:at(this.movingVarianceInitializer),betaRegularizer:Ye(this.betaRegularizer),gammaRegularizer:Ye(this.gammaRegularizer),betaConstraint:yt(this.betaConstraint),gammaConstraint:yt(this.gammaConstraint)},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t.className="BatchNormalization",t}(De);y.serialization.registerClass(fb);var mb=function(n){Q(t,n);function t(e){var i=this;if(e==null&&(e={}),i=n.call(this,e)||this,i.axis=e.axis==null?-1:e.axis,typeof i.axis=="number"){if(!Number.isInteger(i.axis))throw new Error("Expected axis to be an integer, but received "+i.axis)}else if(Array.isArray(i.axis))for(var r=0,a=i.axis;r=i)throw new Error("Invalid axis: "+o)}if(this.axis.length!==ci(this.axis).length)throw new Error("Found duplicate axes in: "+this.axis);var l=this.axis.map(function(c){return e[c]}),u=!0;this.scale?this.gamma=this.addWeight("gamma",l,"float32",this.gammaInitializer,this.gammaRegularizer,u):this.gamma=null,this.center?this.beta=this.addWeight("beta",l,"float32",this.betaInitializer,this.betaRegularizer,u):this.beta=null,this.built=!0},t.prototype.call=function(e,i){var r=this,a=xe(e),s=a.shape,o=s.length;return y.tidy(function(){for(var l=!0,u=y.moments(a,r.axis,l),c=u.mean,h=u.variance,d=ji(1,o),p=0,f=r.axis;p=0?i=e[2]+this.padding[0][0]+this.padding[0][1]:i=null,e[3]!=null&&e[3]>=0?r=e[3]+this.padding[1][0]+this.padding[1][1]:r=null,[e[0],e[1],i,r]):(e[1]!=null&&e[1]>=0?i=e[1]+this.padding[0][0]+this.padding[0][1]:i=null,e[2]!=null&&e[2]>=0?r=e[2]+this.padding[1][0]+this.padding[1][1]:r=null,[e[0],i,r,e[3]])},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){return r4(xe(e),r.padding,r.dataFormat)})},t.prototype.getConfig=function(){var e={padding:this.padding,dataFormat:this.dataFormat},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t.className="ZeroPadding2D",t}(De);y.serialization.registerClass(gb);function go(n,t,e,i,r,a){return y.tidy(function(){ct(r),Nv(a),en(i),e==null&&(e=[1,1]),i==null&&(i="valid"),r==null&&(r=dn()),a==null&&(a="max"),n=Wh(n,r);var s,o=i==="same"?"same":"valid";return a==="max"?s=y.maxPool(n,t,e,o):s=y.avgPool(n,t,e,o),r==="channelsFirst"&&(s=y.transpose(s,[0,3,1,2])),s})}function vb(n,t,e,i,r,a){return y.tidy(function(){ct(r),Nv(a),en(i),e==null&&(e=[1,1,1]),i==null&&(i="valid"),r==null&&(r=dn()),a==null&&(a="max"),n=ky(n,r);var s,o=i==="same"?"same":"valid";return a==="max"?s=y.maxPool3d(n,t,e,o):s=y.avgPool3d(n,t,e,o),r==="channelsFirst"&&(s=y.transpose(s,[0,4,1,2,3])),s})}var yb=function(n){Q(t,n);function t(e){var i=this;if(e.poolSize==null&&(e.poolSize=2),i=n.call(this,e)||this,typeof e.poolSize=="number")i.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")i.poolSize=e.poolSize;else throw new M("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+(""+JSON.stringify(e.poolSize)));if(At(i.poolSize,"poolSize"),e.strides==null)i.strides=i.poolSize;else if(typeof e.strides=="number")i.strides=[e.strides];else if(Array.isArray(e.strides)&&e.strides.length===1&&typeof e.strides[0]=="number")i.strides=e.strides;else throw new M("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+(""+JSON.stringify(e.strides)));return At(i.strides,"strides"),i.padding=e.padding==null?"valid":e.padding,en(i.padding),i.inputSpec=[new Tt({ndim:3})],i}return t.prototype.computeOutputShape=function(e){e=Ge(e);var i=gn(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],i,e[2]]},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){r.invokeCallHook(e,i),e=Oa(xe(e),2);var a=r.poolingFunction(xe(e),[r.poolSize[0],1],[r.strides[0],1],r.padding,"channelsLast");return y.squeeze(a,[2])})},t.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t}(De),bb=function(n){Q(t,n);function t(e){return n.call(this,e)||this}return t.prototype.poolingFunction=function(e,i,r,a,s){return ct(s),en(a),go(e,i,r,a,s,"max")},t.className="MaxPooling1D",t}(yb);y.serialization.registerClass(bb);var wb=function(n){Q(t,n);function t(e){return n.call(this,e)||this}return t.prototype.poolingFunction=function(e,i,r,a,s){return ct(s),en(a),go(e,i,r,a,s,"avg")},t.className="AveragePooling1D",t}(yb);y.serialization.registerClass(wb);var Sb=function(n){Q(t,n);function t(e){var i=this;if(e.poolSize==null&&(e.poolSize=[2,2]),i=n.call(this,e)||this,i.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)i.strides=i.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new M("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length "+(e.strides.length+"."));i.strides=e.strides}else i.strides=[e.strides,e.strides];return At(i.poolSize,"poolSize"),At(i.strides,"strides"),i.padding=e.padding==null?"valid":e.padding,i.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,ct(i.dataFormat),en(i.padding),i.inputSpec=[new Tt({ndim:4})],i}return t.prototype.computeOutputShape=function(e){e=Ge(e);var i=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2];return i=gn(i,this.poolSize[0],this.padding,this.strides[0]),r=gn(r,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],i,r]:[e[0],i,r,e[3]]},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){return r.invokeCallHook(e,i),r.poolingFunction(xe(e),r.poolSize,r.strides,r.padding,r.dataFormat)})},t.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t}(De),Lb=function(n){Q(t,n);function t(e){return n.call(this,e)||this}return t.prototype.poolingFunction=function(e,i,r,a,s){return ct(s),en(a),go(e,i,r,a,s,"max")},t.className="MaxPooling2D",t}(Sb);y.serialization.registerClass(Lb);var Ib=function(n){Q(t,n);function t(e){return n.call(this,e)||this}return t.prototype.poolingFunction=function(e,i,r,a,s){return ct(s),en(a),go(e,i,r,a,s,"avg")},t.className="AveragePooling2D",t}(Sb);y.serialization.registerClass(Ib);var Ab=function(n){Q(t,n);function t(e){var i=this;if(e.poolSize==null&&(e.poolSize=[2,2,2]),i=n.call(this,e)||this,i.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)i.strides=i.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new M("If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length "+(e.strides.length+"."));i.strides=e.strides}else i.strides=[e.strides,e.strides,e.strides];return At(i.poolSize,"poolSize"),At(i.strides,"strides"),i.padding=e.padding==null?"valid":e.padding,i.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,ct(i.dataFormat),en(i.padding),i.inputSpec=[new Tt({ndim:5})],i}return t.prototype.computeOutputShape=function(e){e=Ge(e);var i=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2],a=this.dataFormat==="channelsFirst"?e[4]:e[3];return i=gn(i,this.poolSize[0],this.padding,this.strides[0]),r=gn(r,this.poolSize[1],this.padding,this.strides[1]),a=gn(a,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],i,r,a]:[e[0],i,r,a,e[4]]},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){return r.invokeCallHook(e,i),r.poolingFunction(xe(e),r.poolSize,r.strides,r.padding,r.dataFormat)})},t.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t}(De),Tb=function(n){Q(t,n);function t(e){return n.call(this,e)||this}return t.prototype.poolingFunction=function(e,i,r,a,s){return ct(s),en(a),vb(e,i,r,a,s,"max")},t.className="MaxPooling3D",t}(Ab);y.serialization.registerClass(Tb);var Nb=function(n){Q(t,n);function t(e){return n.call(this,e)||this}return t.prototype.poolingFunction=function(e,i,r,a,s){return ct(s),en(a),vb(e,i,r,a,s,"avg")},t.className="AveragePooling3D",t}(Ab);y.serialization.registerClass(Nb);var xb=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.inputSpec=[new Tt({ndim:3})],i}return t.prototype.computeOutputShape=function(e){return[e[0],e[2]]},t.prototype.call=function(e,i){throw new Te},t}(De),Cb=function(n){Q(t,n);function t(e){return n.call(this,e||{})||this}return t.prototype.call=function(e,i){return y.tidy(function(){var r=xe(e);return y.mean(r,1)})},t.className="GlobalAveragePooling1D",t}(xb);y.serialization.registerClass(Cb);var Rb=function(n){Q(t,n);function t(e){return n.call(this,e||{})||this}return t.prototype.call=function(e,i){return y.tidy(function(){var r=xe(e);return y.max(r,1)})},t.className="GlobalMaxPooling1D",t}(xb);y.serialization.registerClass(Rb);var Ob=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,ct(i.dataFormat),i.inputSpec=[new Tt({ndim:4})],i}return t.prototype.computeOutputShape=function(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]},t.prototype.call=function(e,i){throw new Te},t.prototype.getConfig=function(){var e={dataFormat:this.dataFormat},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t}(De),Eb=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.call=function(e,i){var r=this;return y.tidy(function(){var a=xe(e);return r.dataFormat==="channelsLast"?y.mean(a,[1,2]):y.mean(a,[2,3])})},t.className="GlobalAveragePooling2D",t}(Ob);y.serialization.registerClass(Eb);var Db=function(n){Q(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.call=function(e,i){var r=this;return y.tidy(function(){var a=xe(e);return r.dataFormat==="channelsLast"?y.max(a,[1,2]):y.max(a,[2,3])})},t.className="GlobalMaxPooling2D",t}(Ob);y.serialization.registerClass(Db);var kb=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.layer=e.layer,i}return t.prototype.build=function(e){this.built=!0},Object.defineProperty(t.prototype,"trainable",{get:function(){return this.layer!=null?this.layer.trainable:!1},set:function(e){this.layer!=null&&(this.layer.trainable=e)},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"trainableWeights",{get:function(){return this.layer.trainableWeights},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"nonTrainableWeights",{get:function(){return this.layer.nonTrainableWeights},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"updates",{get:function(){return this.layer._updates},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"losses",{get:function(){return this.layer.losses},enumerable:!0,configurable:!0}),t.prototype.getWeights=function(){return this.layer.getWeights()},t.prototype.setWeights=function(e){this.layer.setWeights(e)},t.prototype.getConfig=function(){var e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},i=n.prototype.getConfig.call(this);return Object.assign(e,i),e},t.prototype.setFastWeightInitDuringBuild=function(e){n.prototype.setFastWeightInitDuringBuild.call(this,e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)},t.fromConfig=function(e,i,r){r===void 0&&(r={});var a=i.layer,s=mn(a,r);delete i.layer;var o={layer:s};return Object.assign(o,i),new e(o)},t}(De),Fb=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this;return i.supportsMasking=!0,i}return t.prototype.build=function(e){if(e=Ge(e),e.length<3)throw new M("TimeDistributed layer expects an input shape >= 3D, but received "+("input shape "+JSON.stringify(e)));this.inputSpec=[{shape:e}];var i=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(i),this.layer.built=!0),n.prototype.build.call(this,e)},t.prototype.computeOutputShape=function(e){e=Ge(e);var i=[e[0]].concat(e.slice(2)),r=this.layer.computeOutputShape(i),a=e[1];return[r[0],a].concat(r.slice(1))},t.prototype.call=function(e,i){var r=this;return y.tidy(function(){e=xe(e);var a=function(l,u){var c=xe(r.layer.call(l,i));return[c,[]]},s=qy(a,e,[],!1,null,null,!1,!0),o=s[1];return o})},t.className="TimeDistributed",t}(kb);y.serialization.registerClass(Fb);function a4(n){Wr(XD,"BidirectionalMergeMode",n)}var s4="concat",Wb=function(n){Q(t,n);function t(e){var i=n.call(this,e)||this,r=e.layer.getConfig(),a={};a.className=e.layer.getClassName(),a.config=r,i.forwardLayer=mn(a),r.goBackwards=!(r.goBackwards===!0);var s={};if(s.className=e.layer.getClassName(),s.config=r,i.backwardLayer=mn(s),i.forwardLayer.name="forward_"+i.forwardLayer.name,i.backwardLayer.name="backward_"+i.backwardLayer.name,i.mergeMode=e.mergeMode===void 0?s4:e.mergeMode,a4(i.mergeMode),e.weights)throw new Te("weights support is not implemented for Bidirectional layer yet.");return i._stateful=e.layer.stateful,i.returnSequences=e.layer.returnSequences,i.returnState=e.layer.returnState,i.supportsMasking=!0,i._trainable=!0,i.inputSpec=e.layer.inputSpec,i.numConstants=null,i}return Object.defineProperty(t.prototype,"trainable",{get:function(){return this._trainable},set:function(e){this._trainable=e,this.forwardLayer!=null&&(this.forwardLayer.trainable=e),this.backwardLayer!=null&&(this.backwardLayer.trainable=e)},enumerable:!0,configurable:!0}),t.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())},t.prototype.setWeights=function(e){var i=e.length,r=Math.floor(i/2);this.forwardLayer.setWeights(e.slice(0,r)),this.backwardLayer.setWeights(e.slice(r))},t.prototype.computeOutputShape=function(e){var i=this.forwardLayer.computeOutputShape(e);Array.isArray(i)&&Array.isArray(i[0])||(i=[i]),i=i;var r,a,s;return this.returnState&&(s=i.slice(1)),r=i[0],r=r,this.mergeMode==="concat"?(r[r.length-1]*=2,a=[r]):this.mergeMode==null?a=[r,r.slice()]:a=[r],this.returnState?this.mergeMode==null?a.concat(s).concat(s.slice()):[r].concat(s).concat(s.slice()):_t(a)},t.prototype.apply=function(e,i){var r=i==null?null:i.initialState,a=i==null?null:i.constants;i==null&&(i={});var s=Vy(e,r,a,this.numConstants);if(e=s.inputs,r=s.initialState,a=s.constants,Array.isArray(e)&&(r=e.slice(1),e=e[0]),(r==null||r.length===0)&&a==null)return n.prototype.apply.call(this,e,i);var o=[],l=[];if(r!=null){var u=r.length;if(u%2>0)throw new M("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");i.initialState=r,o.push.apply(o,r);var c=r.map(function(S){return new Tt({shape:S.shape})});this.forwardLayer.stateSpec=c.slice(0,u/2),this.backwardLayer.stateSpec=c.slice(u/2),l.push.apply(l,c)}if(a!=null)throw new Te("Support for constants in Bidirectional layers is not implemented yet.");for(var h=o[0]instanceof fn,d=0,p=o;dt}var Hb=function(n){Q(t,n);function t(e){var i=n.call(this)||this;if(e==null&&(e={}),e.restoreBestWeights)throw new Te("restoreBestWeights = True is not implemented in EarlyStopping yet.");return i.monitor=e.monitor||"val_loss",i.minDelta=Math.abs(e.minDelta||0),i.patience=e.patience||0,i.verbose=e.verbose||0,i.mode=e.mode||"auto",i.baseline=e.baseline,["auto","min","max"].indexOf(i.mode)===-1&&(console.warn("EarlyStopping mode '"+i.mode+"' is invalid. Falling back to mode 'auto'."),i.mode="auto"),i.mode==="min"?i.monitorFunc=vo:i.mode==="max"||i.monitor.indexOf("acc")!==-1?i.monitorFunc=Mb:i.monitorFunc=vo,i.monitorFunc===vo&&(i.minDelta*=-1),i}return t.prototype.onTrainBegin=function(e){return Le(this,void 0,void 0,function(){return ve(this,function(i){return this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===vo?Infinity:-Infinity,[2]})})},t.prototype.onEpochEnd=function(e,i){return Le(this,void 0,void 0,function(){var r;return ve(this,function(a){switch(a.label){case 0:return[4,pi(i)];case 1:return a.sent(),r=this.getMonitorValue(i),r==null?[2]:(this.monitorFunc(r-this.minDelta,this.best)?(this.best=r,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)),[2])}})})},t.prototype.onTrainEnd=function(e){return Le(this,void 0,void 0,function(){return ve(this,function(i){return this.stoppedEpoch>0&&this.verbose&&console.log("Epoch "+this.stoppedEpoch+": early stopping."),[2]})})},t.prototype.getMonitorValue=function(e){e==null&&(e={});var i=e[this.monitor];return i==null&&console.warn("Metric for EarlyStopping "+this.monitor+" is not available. "+("Available metrics are: "+Object.keys(e))),i},t}(Pb);function zF(n){return new Hb(n)}var _F={earlyStopping:zF};$e.Callback=Pb;$e.CallbackList=Jv;$e.CustomCallback=Qv;$e.EarlyStopping=Hb;$e.History=Zv;$e.InputSpec=Tt;$e.LayerVariable=Yv;$e.LayersModel=fi;$e.RNN=vi;$e.Sequential=Dh;$e.SymbolicTensor=fn;$e.callbacks=_F;$e.constraints=YD;$e.initializers=Nk;$e.input=Ly;$e.layers=gF;$e.loadLayersModel=k3;$e.metrics=DF;$e.model=E3;$e.models=kF;$e.registerCallbackConstructor=F3;$e.regularizers=BF;$e.sequential=D3;$e.version_layers=Nh});var rw=be(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});var B=Ki();var qb=Object.assign||function(t){for(var e,i=1,r=arguments.length;i0&&a[a.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!a||u[1]>a[0]&&u[1]0?Object.keys(h).forEach(function(g){var v=Yn(g)[0],b=l[v];b&&(b.signatureKey=h[g],u.push(b))}):u=a;var f={};t.library!=null&&t.library.function!=null&&(f=t.library.function.reduce(function(g,v){return g[v.signature.name]=i.mapFunction(v),g},{}));var m={nodes:l,inputs:u,outputs:c,weights:s,placeholders:a,signature:e,functions:f};return o.length>0&&(m.initNodes=o),m},n.prototype.mapSignatureEntries=function(t){return Object.keys(t||{}).reduce(function(e,i){return e[t[i].name]=i,e},{})},n.prototype.mapNode=function(t){var e=Yb(t.op)||this.opMappers[t.op]||{};t.attr==null&&(t.attr={});var i={name:t.name,op:t.op,category:e.category,inputNames:(t.input||[]).map(function(r){return r.startsWith("^")?r.substr(1):r}),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:t.attr};return e.inputs!=null&&(i.inputParams=e.inputs.reduce(function(r,a){return r[a.name]={type:a.type,inputIndexStart:a.start,inputIndexEnd:a.end},r},{})),e.attrs!=null&&(i.attrParams=e.attrs.reduce(function(r,a){var s=a.type,o=void 0;switch(a.type){case"string":o=Yh(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=Yh(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"string[]":o=ed(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=ed(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"number":o=jh(t.attr,a.tfName,a.defaultValue||0),o===void 0&&!!a.tfDeprecatedName&&(o=jh(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"number[]":o=Qh(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=Qh(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool":o=Kh(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=Kh(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool[]":o=nd(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=nd(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape":o=Zh(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=Zh(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape[]":o=td(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=td(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype":o=Xh(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=Xh(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype[]":o=Jh(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=Jh(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"func":o=Kb(t.attr,a.tfName,a.defaultValue),o===void 0&&!!a.tfDeprecatedName&&(o=Kb(t.attr,a.tfDeprecatedName,a.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error("Unsupported param type: "+a.type+" for op: "+t.op)}return r[a.name]={value:o,type:s},r},{})),i},n.prototype.mapFunction=function(t){var e=this,i=t.nodeDef,r=[],a=[],s={};i!=null&&(s=i.reduce(function(d,p){return d[p.name]=e.mapNode(p),p.op==="Const"&&a.push(d[p.name]),d},{}));var o=[],l=[];t.signature.inputArg.forEach(function(d){var p=Yn(d.name)[0],f={name:p,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:$h(d.type),type:"dtype"}},children:[]};f.signatureKey=d.name,o.push(f),s[p]=f});var u=Object.keys(s);u.forEach(function(d){var p=s[d];p.inputNames.forEach(function(f){var m=Yn(f)[0];p.inputs.push(s[m]),s[m].children.push(p)})});var c=t.ret;t.signature.outputArg.forEach(function(d){var p=Yn(c[d.name]),f=p[0],m=p[1],g=s[f];g!=null&&(g.defaultOutput=m,l.push(g))});var h=this.mapArgsToSignature(t);return{nodes:s,inputs:o,outputs:l,weights:a,placeholders:r,signature:h}},n.prototype.mapArgsToSignature=function(t){var e=this;return{methodName:t.signature.name,inputs:t.signature.inputArg.reduce(function(i,r){return i[r.name]=e.mapArgToTensorInfo(r),i},{}),outputs:t.signature.outputArg.reduce(function(i,r){return i[r.name]=e.mapArgToTensorInfo(r,t.ret),i},{})}},n.prototype.mapArgToTensorInfo=function(t,e){var i=t.name;return e!=null&&(i=e[i]),{name:i,dtype:t.type}},n}();function SW(n){var t=B.env().global;if(typeof t.atob!="undefined")return t.atob(n);if(typeof Buffer!="undefined")return new Buffer(n,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function $b(n,t){var e=Array.isArray(n)?String.fromCharCode.apply(null,n):SW(n);return t?e:e.toLowerCase()}function Yh(n,t,e,i){i===void 0&&(i=!1);var r=n[t];return r!=null?$b(r.s,i):e}function Kh(n,t,e){var i=n[t];return i?i.b:e}function jh(n,t,e){var i=n[t]||{},r=i.i!=null?i.i:i.f!=null?i.f:e;return typeof r=="number"?r:parseInt(r,10)}function $h(n){typeof n=="string"&&(n=yn[n]);switch(n){case yn.DT_FLOAT:return"float32";case yn.DT_INT32:case yn.DT_INT64:case yn.DT_INT8:case yn.DT_UINT8:return"int32";case yn.DT_BOOL:return"bool";case yn.DT_DOUBLE:return"float32";case yn.DT_STRING:return"string";default:return null}}function Kb(n,t,e){var i=n[t];return i&&i.func?i.func.name:e}function Xh(n,t,e){var i=n[t];return i&&i.type?$h(i.type):e}function Jh(n,t,e){var i=n[t];return i&&i.list&&i.list.type?i.list.type.map(function(r){return $h(r)}):e}function Xb(n){return n.unknownRank?void 0:n.dim!=null?n.dim.map(function(t){return typeof t.size=="number"?t.size:parseInt(t.size,10)}):[]}function Zh(n,t,e){var i=n[t];return i&&i.shape?Xb(i.shape):e}function Qh(n,t,e){var i=n[t];return i?((i.list.f&&i.list.f.length?i.list.f:i.list.i)||[]).map(function(r){return typeof r=="number"?r:parseInt(r,10)}):e}function ed(n,t,e,i){i===void 0&&(i=!1);var r=n[t];return r&&r.list&&r.list.s?r.list.s.map(function(a){return $b(a,i)}):e}function td(n,t,e){var i=n[t];return i&&i.list&&i.list.shape?i.list.shape.map(function(r){return Xb(r)}):e}function nd(n,t,e){var i=n[t];return i&&i.list&&i.list.b?i.list.b:e}var LW=function(){function n(t,e,i){var r=this;this.node=t,this.tensorMap=e,this.context=i,this.inputs=[],this.attrs={},this.inputs=t.inputNames.map(function(a){return r.getInput(a)}),t.rawAttrs!=null&&(this.attrs=Object.keys(t.rawAttrs).reduce(function(a,s){return a[s]=r.getAttr(s),a},{}))}return n.prototype.getInput=function(t){return Pt(t,this.tensorMap,this.context)},n.prototype.getAttr=function(t,e){var i=this.node.rawAttrs[t];if(i.tensor!=null)return Pt(t,this.tensorMap,this.context);if(i.i!=null||i.f!=null)return jh(this.node.rawAttrs,t,e);if(i.s!=null)return Yh(this.node.rawAttrs,t,e);if(i.b!=null)return Kh(this.node.rawAttrs,t,e);if(i.shape!=null)return Zh(this.node.rawAttrs,t,e);if(i.type!=null)return Xh(this.node.rawAttrs,t,e);if(i.list!=null){if(i.list.i!=null||i.list.f!=null)return Qh(this.node.rawAttrs,t,e);if(i.list.s!=null)return ed(this.node.rawAttrs,t,e);if(i.list.shape!=null)return td(this.node.rawAttrs,t,e);if(i.list.b!=null)return nd(this.node.rawAttrs,t,e);if(i.list.type!=null)return Jh(this.node.rawAttrs,t,e)}return e},n}();var IW=function(n,t,e){switch(n.op){case"BiasAdd":case"AddV2":case"Add":return[B.add(T("a",n,t,e),T("b",n,t,e))];case"AddN":return[B.addN(T("tensors",n,t,e))];case"FloorMod":case"Mod":return[B.mod(T("a",n,t,e),T("b",n,t,e))];case"Mul":return[B.mul(T("a",n,t,e),T("b",n,t,e))];case"RealDiv":case"Div":return[B.div(T("a",n,t,e),T("b",n,t,e))];case"DivNoNan":return[B.divNoNan(T("a",n,t,e),T("b",n,t,e))];case"FloorDiv":return[B.floorDiv(T("a",n,t,e),T("b",n,t,e))];case"Sub":return[B.sub(T("a",n,t,e),T("b",n,t,e))];case"Minimum":return[B.minimum(T("a",n,t,e),T("b",n,t,e))];case"Maximum":return[B.maximum(T("a",n,t,e),T("b",n,t,e))];case"Pow":return[B.pow(T("a",n,t,e),T("b",n,t,e))];case"SquaredDifference":return[B.squaredDifference(T("a",n,t,e),T("b",n,t,e))];default:throw TypeError("Node type "+n.op+" is not implemented")}};var AW=function(n,t,e){switch(n.op){case"Abs":case"ComplexAbs":return[B.abs(T("x",n,t,e))];case"Acos":return[B.acos(T("x",n,t,e))];case"Acosh":return[B.acosh(T("x",n,t,e))];case"Asin":return[B.asin(T("x",n,t,e))];case"Asinh":return[B.asinh(T("x",n,t,e))];case"Atan":return[B.atan(T("x",n,t,e))];case"Atan2":return[B.atan2(T("x",n,t,e),T("y",n,t,e))];case"Atanh":return[B.atanh(T("x",n,t,e))];case"Ceil":return[B.ceil(T("x",n,t,e))];case"Complex":return[B.complex(T("real",n,t,e),T("imag",n,t,e))];case"Cos":return[B.cos(T("x",n,t,e))];case"Cosh":return[B.cosh(T("x",n,t,e))];case"Elu":return[B.elu(T("x",n,t,e))];case"Erf":return[B.erf(T("x",n,t,e))];case"Exp":return[B.exp(T("x",n,t,e))];case"Expm1":return[B.expm1(T("x",n,t,e))];case"Floor":return[B.floor(T("x",n,t,e))];case"Log":return[B.log(T("x",n,t,e))];case"Log1p":return[B.log1p(T("x",n,t,e))];case"Imag":return[B.imag(T("x",n,t,e))];case"Neg":return[B.neg(T("x",n,t,e))];case"Reciprocal":return[B.reciprocal(T("x",n,t,e))];case"Real":return[B.real(T("x",n,t,e))];case"Relu":return[B.relu(T("x",n,t,e))];case"Round":return[B.round(T("x",n,t,e))];case"Selu":return[B.selu(T("x",n,t,e))];case"Sigmoid":return[B.sigmoid(T("x",n,t,e))];case"Sin":return[B.sin(T("x",n,t,e))];case"Sign":return[B.sign(T("x",n,t,e))];case"Sinh":return[B.sinh(T("x",n,t,e))];case"Softplus":return[B.softplus(T("x",n,t,e))];case"Sqrt":return[B.sqrt(T("x",n,t,e))];case"Square":return[B.square(T("x",n,t,e))];case"Tanh":return[B.tanh(T("x",n,t,e))];case"Tan":return[B.tan(T("x",n,t,e))];case"Relu6":case"ClipByValue":return[B.clipByValue(T("x",n,t,e),T("clipValueMin",n,t,e),T("clipValueMax",n,t,e))];case"Rsqrt":return[B.rsqrt(Pt(n.inputNames[0],t,e))];case"Prod":return[B.prod(T("x",n,t,e),T("axes",n,t,e))];case"LeakyRelu":return[B.leakyRelu(T("x",n,t,e),T("alpha",n,t,e))];case"Prelu":return[B.prelu(T("x",n,t,e),T("alpha",n,t,e))];default:throw TypeError("Node type "+n.op+" is not implemented")}};function ln(n,t,e){e===void 0&&(e=""),B.util.assert(TW(n,t),function(){return e+(" Shapes "+n+" and "+t+" must match")})}function TW(n,t){if(n.length!==t.length)return!1;for(var e=0;e=this.size())throw new Error("Tried to read from index "+t+", but array size is: "+this.size());var e=this.tensors[t];if(e.cleared)throw new Error("TensorArray "+this.name+": Could not read index "+t+" twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).");return this.clearAfterRead&&(e.cleared=!0),e.read=!0,e.tensor},n.prototype.readMany=function(t){var e=this;return t.map(function(i){return e.read(i)})},n.prototype.write=function(t,e){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(t<0||!this.dynamicSize&&t>=this.maxSize)throw new Error("Tried to write to index "+t+", but array is not resizeable and size is: "+this.maxSize);var i=this.tensors[t]||{};if(e.dtype!==this.dtype)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+`, because the value dtype is `+e.dtype+", but TensorArray dtype is "+this.dtype+".");if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=e.shape),ln(this.elementShape,e.shape,"TensorArray "+this.name+": Could not write to TensorArray index "+t+"."),i.read)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+", because it has already been read.");if(i.written)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+", because it has already been written.");i.tensor=e,B.keep(e),i.written=!0,this.tensors[t]=i},n.prototype.writeMany=function(t,e){var i=this;if(t.length!==e.length)throw new Error("TensorArray "+this.name+": could not write multiple tensors,"+("because the index size: "+t.length+" is not the same as tensors size: "+e.length+"."));t.forEach(function(r,a){return i.write(r,e[a])})},n.prototype.gather=function(t,e){if(!!e&&e!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but gather requested dtype "+e);if(t)t=t.slice(0,this.size());else{t=[];for(var i=0;i=this.maxSize)throw new Error("Max index must be < array size ("+i+" vs. "+this.maxSize+")");this.writeMany(t,B.unstack(e,0))},n.prototype.split=function(t,e){var i=this;if(e.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+e.dtype);var r=0,a=t.map(function(c){return r+=c,r});if(r!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to tensor.shape[0], but sum of lengths is - `+r+", and tensor's shape is: "+e.shape);if(!this.dynamicSize&&t.length!==this.maxSize)throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+t.length+"), and the TensorArray is not marked as dynamically resizeable");var s=r===0?0:e.size/r,o=[];B.tidy(function(){e=B.reshape(e,[1,r,s]);for(var c=0;cthis.maxNumElements)throw new Error("TensorListResize input size "+t+" is greater maxNumElement "+this.maxNumElements+".");this.tensors.length=t},n.prototype.getItem=function(t,e,i){if(i!==this.elementDtype)throw new Error("Invalid data types; op elements "+i+", but list elements "+this.elementDtype);if(t<0||t>this.tensors.length)throw new Error("Trying to access element "+t+" in a list with "+this.tensors.length+" elements.");if(this.tensors[t]==null)throw new Error("element at index "+t+" is null.");return ln(this.tensors[t].shape,e,"TensorList shape mismatch: "),this.tensors[t]},n.prototype.setItem=function(t,e){if(e.dtype!==this.elementDtype)throw new Error("Invalid data types; op elements "+e.dtype+", but list elements "+this.elementDtype);if(t<0||this.maxNumElements!==-1&&t>=this.maxNumElements)throw new Error("Trying to set element "+t+" in a list with max "+this.maxNumElements+" elements.");ln(this.elementShape,e.shape,"TensorList shape mismatch: "),B.keep(e),this.tensors[t]=e},n.prototype.gather=function(t,e,i){var r=this;if(e!==this.elementDtype)throw new Error("Invalid data types; op elements "+e+", but list elements "+this.elementDtype);return ln(this.elementShape,i,"TensorList shape mismatch: "),t=t.slice(0,this.size()),t.length===0?B.tensor([],[0].concat(this.elementShape)):B.tidy(function(){var a=t.map(function(s){return B.reshape(r.tensors[s],i)});return B.stack(a,0)})},n.prototype.concat=function(t,e){var i=this;if(!!t&&t!==this.elementDtype)throw new Error("TensorList dtype is "+this.elementDtype+" but concat requested dtype "+t);return ln(this.elementShape,e,"TensorList shape mismatch: "),this.size()===0?B.tensor([],[0].concat(this.elementShape)):B.tidy(function(){var r=i.tensors.map(function(a){return B.reshape(a,e)});return B.concat(r,0)})},n}();function NW(n,t,e){var i=n.dtype;if(n.shape.length<1)throw new Error("Tensor must be at least a vector, but saw shape: "+n.shape);if(n.dtype!==e)throw new Error("Invalid data types; op elements "+n.dtype+", but list elements "+e);var r=n.shape.slice(1);ln(r,t,"TensorList shape mismatch: ");var a=B.unstack(n);return new wo(a,t,i)}function xW(n,t,e){return new wo([],n,t,e)}function CW(n,t,e,i){if(t.length!==n.shape[0])throw new Error("Expected len(indices) == tensor.shape[0], but saw: "+t.length+" vs. "+n.shape[0]);var r=Math.max.apply(Math,t);if(i!=null&&i!==-1&&r>=i)throw new Error("Max index must be < array size ("+r+" vs. "+i+")");var a=new wo([],e,n.dtype,i),s=B.unstack(n,0);return t.forEach(function(o,l){a.setItem(o,s[l])}),a}function RW(n,t,e){var i=0,r=t.map(function(u){return i+=u,i});if(i!==n.shape[0])throw new Error(`Expected sum of lengths to be equal to + `+r+", and tensor's shape is: "+e.shape);if(!this.dynamicSize&&t.length!==this.maxSize)throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+t.length+"), and the TensorArray is not marked as dynamically resizeable");var s=r===0?0:e.size/r,o=[];B.tidy(function(){e=B.reshape(e,[1,r,s]);for(var c=0;cthis.maxNumElements)throw new Error("TensorListResize input size "+t+" is greater maxNumElement "+this.maxNumElements+".");this.tensors.length=t},n.prototype.getItem=function(t,e,i){if(i!==this.elementDtype)throw new Error("Invalid data types; op elements "+i+", but list elements "+this.elementDtype);if(t<0||t>this.tensors.length)throw new Error("Trying to access element "+t+" in a list with "+this.tensors.length+" elements.");if(this.tensors[t]==null)throw new Error("element at index "+t+" is null.");return ln(this.tensors[t].shape,e,"TensorList shape mismatch: "),this.tensors[t]},n.prototype.setItem=function(t,e){if(e.dtype!==this.elementDtype)throw new Error("Invalid data types; op elements "+e.dtype+", but list elements "+this.elementDtype);if(t<0||this.maxNumElements!==-1&&t>=this.maxNumElements)throw new Error("Trying to set element "+t+" in a list with max "+this.maxNumElements+" elements.");ln(this.elementShape,e.shape,"TensorList shape mismatch: "),B.keep(e),this.tensors[t]=e},n.prototype.gather=function(t,e,i){var r=this;if(e!==this.elementDtype)throw new Error("Invalid data types; op elements "+e+", but list elements "+this.elementDtype);return ln(this.elementShape,i,"TensorList shape mismatch: "),t=t.slice(0,this.size()),t.length===0?B.tensor([],[0].concat(this.elementShape)):B.tidy(function(){var a=t.map(function(s){return B.reshape(r.tensors[s],i)});return B.stack(a,0)})},n.prototype.concat=function(t,e){var i=this;if(!!t&&t!==this.elementDtype)throw new Error("TensorList dtype is "+this.elementDtype+" but concat requested dtype "+t);return ln(this.elementShape,e,"TensorList shape mismatch: "),this.size()===0?B.tensor([],[0].concat(this.elementShape)):B.tidy(function(){var r=i.tensors.map(function(a){return B.reshape(a,e)});return B.concat(r,0)})},n}();function xW(n,t,e){var i=n.dtype;if(n.shape.length<1)throw new Error("Tensor must be at least a vector, but saw shape: "+n.shape);if(n.dtype!==e)throw new Error("Invalid data types; op elements "+n.dtype+", but list elements "+e);var r=n.shape.slice(1);ln(r,t,"TensorList shape mismatch: ");var a=B.unstack(n);return new wo(a,t,i)}function CW(n,t,e){return new wo([],n,t,e)}function RW(n,t,e,i){if(t.length!==n.shape[0])throw new Error("Expected len(indices) == tensor.shape[0], but saw: "+t.length+" vs. "+n.shape[0]);var r=Math.max.apply(Math,t);if(i!=null&&i!==-1&&r>=i)throw new Error("Max index must be < array size ("+r+" vs. "+i+")");var a=new wo([],e,n.dtype,i),s=B.unstack(n,0);return t.forEach(function(o,l){a.setItem(o,s[l])}),a}function OW(n,t,e){var i=0,r=t.map(function(u){return i+=u,i});if(i!==n.shape[0])throw new Error(`Expected sum of lengths to be equal to tensor.shape[0], but sum of lengths is - `+i+", and tensor's shape is: "+n.shape);for(var a=i===0?0:n.size/i,s=B.tidy(function(){var u=[];n=B.reshape(n,[1,i,a]);for(var c=0;c1)this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();else throw new Error("Cannot exit frame, the context is empty")},n.prototype.nextIteration=function(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice(),this.lastId++;var t=Object.assign({},this.contexts[this.contexts.length-1]);t.iterationId+=1,t.id=this.lastId,this.contexts.splice(-1,1,t),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else throw new Error("Cannot increase frame iteration, the context is empty")},n.prototype.getWeight=function(t){return this.weightMap[t]},n.prototype.addTensorArray=function(t){this.tensorArrayMap[t.id]=t},n.prototype.getTensorArray=function(t){return this.tensorArrayMap[t]},n.prototype.addTensorList=function(t){this.tensorListMap[t.id]=t},n.prototype.getTensorList=function(t){return this.tensorListMap[t]},n.prototype.dispose=function(t){for(var e in this.tensorArrayMap)this.tensorArrayMap[e].clearAndClose(t);for(var e in this.tensorListMap)this.tensorListMap[e].clearAndClose(t)},n}();function tw(n,t,e,i){var r=new Set,a=[],s=null,o=null,l=new Set,u=Object.keys(n).map(function(p){return Kt(p)[0]}),c=[];i!=null&&(c=i.map(function(p){return Kt(p.name)[0]}));for(var h=t.slice();h.length>0;){var d=h.pop();if((ew(d)||YW(d))&&(s==null&&(s=d,o=s.children.map(function(p){return p.name}).filter(function(p){return r.has(p)}))),r.add(d.name),e[d.name]!=null)continue;if(u.indexOf(d.name)!==-1)continue;if(c.indexOf(d.name)!==-1)continue;if(d.inputs.length===0){a.push(d.name);continue}d.inputs.forEach(function(p){if(l.has(p.name))return;l.add(p.name),h.push(p)})}return{inputs:n,outputs:t,usedNodes:r,missingInputs:a,dynamicNode:s,syncInputs:o}}function KW(n,t,e){var i=e.usedNodes,r=e.inputs,a=[],s=Object.keys(r).map(function(h){return Kt(h)[0]}).map(function(h){return n.nodes[h]}),o=n.initNodes;s.forEach(function(h){i.has(h.name)&&a.push(h)}),n.weights.forEach(function(h){i.has(h.name)&&a.push(h)}),o!=null&&o.forEach(function(h){i.has(h.name)&&a.push(h)});for(var l=new Set,u=[];a.length>0;){var c=a.pop();l.add(c.name),t[c.name]||u.push(c),c.children.forEach(function(h){!l.has(h.name)&&i.has(h.name)&&h.inputs.every(function(d){return l.has(d.name)})&&a.push(h)})}return u}var jW=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],$W=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"];function ew(n){return jW.indexOf(n.op)>=0}function YW(n){return $W.indexOf(n.op)>=0}var nw=function(){function n(t,e){var i=this;this.graph=t,this.parent=e,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._functions={},this._functionExecutorMap={},this._outputs=t.outputs,this._inputs=t.inputs,this._initNodes=t.initNodes,this._signature=t.signature,this._functions=t.functions,t.functions!=null&&Object.keys(t.functions).forEach(function(r){i._functionExecutorMap[r]=new n(t.functions[r],i)})}return Object.defineProperty(n.prototype,"weightIds",{get:function(){return this.parent?this.parent.weightIds:this._weightIds},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"functionExecutorMap",{get:function(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"weightMap",{get:function(){return this.parent?this.parent.weightMap:this._weightMap},set:function(t){var e=Object.keys(t).map(function(i){return t[i].map(function(r){return r.id})});this._weightIds=[].concat.apply([],e),this._weightMap=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"inputs",{get:function(){return this._inputs.map(function(t){return{name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"outputs",{get:function(){return this._outputs.map(function(t){return{name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"inputNodes",{get:function(){return this._inputs.map(function(t){return t.signatureKey||t.name})},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"outputNodes",{get:function(){return this._outputs.map(function(t){var e=t.signatureKey||t.name;return t.defaultOutput?e+":"+t.defaultOutput:e})},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"functions",{get:function(){var t=this;return Object.keys(this._functions).reduce(function(e,i){return e[i]=t._functions[i].signature,e},{})},enumerable:!0,configurable:!0}),n.prototype.getCompilationKey=function(t,e){var i=t.map(function(a){return a.name}).sort(),r=e.map(function(a){return a.name}).sort();return i.join(this.SEPERATOR)+"--"+r.join(this.SEPERATOR)},n.prototype.compile=function(t,e){var i=tw(t,e,this.weightMap,this._initNodes),r=i.missingInputs,a=i.dynamicNode,s=i.syncInputs;if(a!=null)throw new Error("This execution contains the node '"+a.name+"', which has "+("the dynamic op '"+a.op+"'. Please use ")+"model.executeAsync() instead. Alternatively, to avoid the "+("dynamic ops, specify the inputs ["+s+"]"));if(r.length>0){var o=e.map(function(u){return u.name}),l=Object.keys(t);throw new Error("Cannot compute the outputs ["+o+"] from the provided inputs "+("["+l+"]. Missing the following inputs: ["+r+"]"))}return KW(this.graph,this.weightMap,i)},n.prototype.execute=function(t,e){var i=this;t=this.mapInputs(t);var r=Object.keys(t).sort();this.checkInputs(t),this.checkInputShapeAndType(t),e=this.mapOutputs(e),this.checkOutputs(e);var a=r.map(function(d){return i.graph.nodes[Kt(d)[0]]}),s=e.map(function(d){return Kt(d)[0]}),o=s.map(function(d){return i.graph.nodes[d]});o.length===0&&(o=this._outputs);var l=this.getCompilationKey(a,o),u=this.compiledMap.get(l);u==null&&(u=this.compile(t,o),this.compiledMap.set(l,u));var c={},h={};return B.tidy(function(){var d=new Qb(i.weightMap,c,h,i.functionExecutorMap),p=qb({},i.weightMap);Object.keys(t).forEach(function(S){var L=Kt(S),w=L[0],N=L[1],I=[];I[N]=t[S],p[w]=I});for(var f=i.getFrozenTensorIds(p),m={},g=0;g0?(S=this.processStack(s,f,e,m,b,v,o,g,c),[4,Promise.all(S)]):[3,3];case 2:return I.sent(),[3,1];case 3:if(d==null&&!r&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead."),L=l.filter(function(C){return!ew(C)&&!Pt(C.name,m,e)}).map(function(C){return C.name}),L.length>0)throw w="",d!=null&&(w="Alternatively, to avoid the dynamic ops, use model.execute() "+("and specify the inputs ["+p+"]")),new Error("Cannot compute the outputs ["+L+"] from the provided "+("inputs ["+a+"]. Consider providing the following inputs: ")+("["+h+"]. "+w));return[2,m]}})})},n.prototype.processStack=function(t,e,i,r,a,s,o,l,u){for(var c=this,h=[],d=function(){var f=e.pop();i.currentContext=f.contexts;var m="";if(f.node.op==="Enter"&&T("isConstant",f.node,r,i)&&(m=Yn(f.node.name,i)[0]),t.indexOf(f.node)===-1){var g=Zb(f.node,r,i);m||(m=Yn(f.node.name,i)[0]);var v=i.currentContext;g instanceof Promise?h.push(g.then(function(b){return r[m]=b,i.currentContext=v,c.checkTensorForDisposal(m,f.node,r,i,s,o,l),c.processChildNodes(f.node,e,i,r,a,u),b})):(r[m]=g,p.checkTensorForDisposal(m,f.node,r,i,s,o,l),p.processChildNodes(f.node,e,i,r,a,u))}else p.processChildNodes(f.node,e,i,r,a,u)},p=this;e.length>0;)d();return h},n.prototype.processChildNodes=function(t,e,i,r,a,s){t.children.forEach(function(o){var l=Yn(o.name,i)[0];if(a[l]||!s.has(o.name))return;o.op==="Merge"?o.inputNames.some(function(u){return!!Pt(u,r,i)})&&(a[l]=!0,e.push({contexts:i.currentContext,node:o})):o.inputNames.every(function(u){return!!Pt(u,r,i)})&&(a[l]=!0,e.push({contexts:i.currentContext,node:o}))})},n.prototype.dispose=function(){var t=this;Object.keys(this.weightMap).forEach(function(e){return t.weightMap[e].forEach(function(i){return i.dispose()})})},n.prototype.checkInputShapeAndType=function(t){var e=this;Object.keys(t).forEach(function(i){var r=t[i],a=Kt(i)[0],s=e.graph.nodes[a];if(s.attrParams.shape&&s.attrParams.shape.value){var o=s.attrParams.shape.value,l=o.length===r.shape.length&&r.shape.every(function(u,c){return o[c]===-1||o[c]===u});B.util.assert(l,function(){return"The shape of dict['"+s.name+"'] provided in "+("model.execute(dict) must be ["+o+"], but was ")+("["+r.shape+"]")})}s.attrParams.dtype&&s.attrParams.dtype.value&&B.util.assert(r.dtype===s.attrParams.dtype.value,function(){return"The dtype of dict['"+s.name+"'] provided in model.execute(dict) must be "+(s.attrParams.dtype.value+", but was "+r.dtype)})})},n.prototype.mapInputs=function(t){var e={};for(var i in t)if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[i]!=null){var r=this._signature.inputs[i];e[r.name]=t[i]}else e[i]=t[i];return e},n.prototype.checkInputs=function(t){var e=this,i=Object.keys(t).filter(function(r){var a=Kt(r)[0];return e.graph.nodes[a]==null});if(i.length>0)throw new Error("The dict provided in model.execute(dict) has "+("keys: ["+i+"] that are not part of graph"))},n.prototype.mapOutputs=function(t){var e=this;return t.map(function(i){if(e._signature!=null&&e._signature.outputs!=null&&e._signature.outputs[i]!=null){var r=e._signature.outputs[i];return r.name}return i},{})},n.prototype.checkOutputs=function(t){var e=this;t.forEach(function(i){var r=Kt(i)[0];if(!e.graph.nodes[r])throw new Error("The output '"+i+"' is not found in the graph")})},n}();var XW="?tfjs-format=file",JW="model.json",iw=function(){function n(t,e){e===void 0&&(e={}),this.modelUrl=t,this.loadOptions=e,this.version="n/a",e==null&&(this.loadOptions={})}return Object.defineProperty(n.prototype,"modelVersion",{get:function(){return this.version},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"inputNodes",{get:function(){return this.executor.inputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"outputNodes",{get:function(){return this.executor.outputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"inputs",{get:function(){return this.executor.inputs},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"outputs",{get:function(){return this.executor.outputs},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"weights",{get:function(){return this.executor.weightMap},enumerable:!0,configurable:!0}),n.prototype.findIOHandler=function(){var t=this.modelUrl;if(t.load!=null)this.handler=t;else if(this.loadOptions.requestInit!=null)this.handler=B.io.browserHTTPRequest(t,this.loadOptions);else{var e=B.io.getLoadHandlers(t,this.loadOptions);if(e.length===0)e.push(B.io.browserHTTPRequest(t,this.loadOptions));else if(e.length>1)throw new Error("Found more than one ("+e.length+") load handlers for "+("URL '"+[t]+"'"));this.handler=e[0]}},n.prototype.load=function(){return kn(this,void 0,void 0,function(){var t;return vn(this,function(e){switch(e.label){case 0:if(this.findIOHandler(),this.handler.load==null)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,this.handler.load()];case 1:return t=e.sent(),[2,this.loadSync(t)]}})})},n.prototype.loadSync=function(t){this.artifacts=t;var e=this.artifacts.modelTopology,i={};this.artifacts.userDefinedMetadata!=null&&(i=this.artifacts.userDefinedMetadata.signature),this.version=e.versions.producer+"."+e.versions.minConsumer;var r=B.io.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new nw(jb.Instance.transformGraph(e,i)),this.executor.weightMap=this.convertTensorMapToTensorsMap(r),t.modelInitializer!=null){var a=jb.Instance.transformGraph(t.modelInitializer);this.initializer=new nw(a),this.initializer.weightMap=this.executor.weightMap,this.initializer.execute({},[])}return!0},n.prototype.save=function(t,e){return kn(this,void 0,void 0,function(){var i;return vn(this,function(r){if(typeof t=="string"){if(i=B.io.getSaveHandlers(t),i.length===0)throw new Error("Cannot find any save handlers for URL '"+t+"'");if(i.length>1)throw new Error("Found more than one ("+i.length+") save handlers for "+("URL '"+t+"'"));t=i[0]}if(t.save==null)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[2,t.save(this.artifacts)]})})},n.prototype.predict=function(t,e){return this.execute(t,this.outputNodes)},n.prototype.normalizeInputs=function(t){if(!(t instanceof B.Tensor)&&!Array.isArray(t))return t;if(t=Array.isArray(t)?t:[t],t.length!==this.inputNodes.length)throw new Error("Input tensor count mismatch,"+("the graph model has "+this.inputNodes.length+" placeholders, ")+("while there are "+t.length+" input tensors."));return this.inputNodes.reduce(function(e,i,r){return e[i]=t[r],e},{})},n.prototype.normalizeOutputs=function(t){return t=t||this.outputNodes,Array.isArray(t)?t:[t]},n.prototype.execute=function(t,e){t=this.normalizeInputs(t),e=this.normalizeOutputs(e);var i=this.executor.execute(t,e);return i.length>1?i:i[0]},n.prototype.executeAsync=function(t,e){return kn(this,void 0,void 0,function(){var i;return vn(this,function(r){switch(r.label){case 0:return t=this.normalizeInputs(t),e=this.normalizeOutputs(e),[4,this.executor.executeAsync(t,e)];case 1:return i=r.sent(),[2,i.length>1?i:i[0]]}})})},n.prototype.convertTensorMapToTensorsMap=function(t){return Object.keys(t).reduce(function(e,i){return e[i]=[t[i]],e},{})},n.prototype.dispose=function(){this.executor.dispose(),this.initializer&&this.initializer.dispose()},n}();function ZW(n,t){return t===void 0&&(t={}),kn(this,void 0,void 0,function(){var e;return vn(this,function(i){switch(i.label){case 0:if(n==null)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");return t==null&&(t={}),t.fromTFHub&&(n.load==null&&(n.endsWith("/")||(n=n+"/"),n=""+n+JW+XW)),e=new iw(n,t),[4,e.load()];case 1:return i.sent(),[2,e]}})})}var QW="2.6.0";tr.GraphModel=iw;tr.deregisterOp=PF;tr.loadGraphModel=ZW;tr.registerOp=_F;tr.version_converter=QW});var aw=be(()=>{});var Tw=be(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});var Ne=Ki();var rd=function(n,t){return rd=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,i){e.__proto__=i}||function(e,i){for(var r in i)i.hasOwnProperty(r)&&(e[r]=i[r])},rd(n,t)};function He(n,t){rd(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function se(n,t,e,i){return new(e||(e=Promise))(function(r,a){function s(u){try{l(i.next(u))}catch(c){a(c)}}function o(u){try{l(i.throw(u))}catch(c){a(c)}}function l(u){u.done?r(u.value):new e(function(c){c(u.value)}).then(s,o)}l((i=i.apply(n,t||[])).next())})}function oe(n,t){var e={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,r,a,s;return s={next:o(0),throw:o(1),return:o(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function o(u){return function(c){return l([u,c])}}function l(u){if(i)throw new TypeError("Generator is already executing.");for(;e;)try{if(i=1,r&&(a=u[0]&2?r.return:u[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,u[1])).done)return a;(r=0,a)&&(u=[u[0]&2,a.value]);switch(u[0]){case 0:case 1:a=u;break;case 4:return e.label++,{value:u[1],done:!1};case 5:e.label++,r=u[1],u=[0];continue;case 7:u=e.ops.pop(),e.trys.pop();continue;default:if(!(a=e.trys,a=a.length>0&&a[a.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!a||u[1]>a[0]&&u[1]>>0,d-=l,d*=l,l=d>>>0,d-=l,l+=d*4294967296}return(l>>>0)*23283064365386963e-26};return u}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.alea=s})(Vr,n,!1)}),tU=nr(function(n){(function(t,e,i){function r(o){var l=this,u="";l.x=0,l.y=0,l.z=0,l.w=0,l.next=function(){var h=l.x^l.x<<11;return l.x=l.y,l.y=l.z,l.z=l.w,l.w^=l.w>>>19^h^h>>>8},o===(o|0)?l.x=o:u+=o;for(var c=0;c>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.xor128=s})(Vr,n,!1)}),nU=nr(function(n){(function(t,e,i){function r(o){var l=this,u="";l.next=function(){var h=l.x^l.x>>>2;return l.x=l.y,l.y=l.z,l.z=l.w,l.w=l.v,(l.d=l.d+362437|0)+(l.v=l.v^l.v<<4^(h^h<<1))|0},l.x=0,l.y=0,l.z=0,l.w=0,l.v=0,o===(o|0)?l.x=o:u+=o;for(var c=0;c>>4),l.next()}function a(o,l){return l.x=o.x,l.y=o.y,l.z=o.z,l.w=o.w,l.v=o.v,l.d=o.d,l}function s(o,l){var u=new r(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.xorwow=s})(Vr,n,!1)}),iU=nr(function(n){(function(t,e,i){function r(o){var l=this;l.next=function(){var c=l.x,h=l.i,d,p;return d=c[h],d^=d>>>7,p=d^d<<24,d=c[h+1&7],p^=d^d>>>10,d=c[h+3&7],p^=d^d>>>3,d=c[h+4&7],p^=d^d<<7,d=c[h+7&7],d=d^d<<13,p^=d^d<<9,c[h]=p,l.i=h+1&7,p};function u(c,h){var d,p,f=[];if(h===(h|0))p=f[0]=h;else for(h=""+h,d=0;d0;--d)c.next()}u(l,o)}function a(o,l){return l.x=o.x.slice(),l.i=o.i,l}function s(o,l){o==null&&(o=+new Date);var u=new r(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(c.x&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.xorshift7=s})(Vr,n,!1)}),rU=nr(function(n){(function(t,e,i){function r(o){var l=this;l.next=function(){var c=l.w,h=l.X,d=l.i,p,f;return l.w=c=c+1640531527|0,f=h[d+34&127],p=h[d=d+1&127],f^=f<<13,p^=p<<17,f^=f>>>15,p^=p>>>12,f=h[d]=f^p,l.i=d,f+(c^c>>>16)|0};function u(c,h){var d,p,f,m,g,v=[],b=128;for(h===(h|0)?(p=h,h=null):(h=h+"\0",p=0,b=Math.max(b,h.length)),f=0,m=-32;m>>15,p^=p<<4,p^=p>>>13,m>=0&&(g=g+1640531527|0,d=v[m&127]^=p+g,f=d==0?f+1:0);for(f>=128&&(v[(h&&h.length||0)&127]=-1),f=127,m=4*128;m>0;--m)p=v[f+34&127],d=v[f=f+1&127],p^=p<<13,d^=d<<17,p^=p>>>15,d^=d>>>12,v[f]=p^d;c.w=g,c.X=v,c.i=f}u(l,o)}function a(o,l){return l.i=o.i,l.w=o.w,l.X=o.X.slice(),l}function s(o,l){o==null&&(o=+new Date);var u=new r(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(c.X&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.xor4096=s})(Vr,n,!1)}),aU=nr(function(n){(function(t,e,i){function r(o){var l=this,u="";l.next=function(){var h=l.b,d=l.c,p=l.d,f=l.a;return h=h<<25^h>>>7^d,d=d-p|0,p=p<<24^p>>>8^f,f=f-h|0,l.b=h=h<<20^h>>>12^d,l.c=d=d-p|0,l.d=p<<16^d>>>16^f,l.a=f-h|0},l.a=0,l.b=0,l.c=2654435769|0,l.d=1367130551,o===Math.floor(o)?(l.a=o/4294967296|0,l.b=o|0):u+=o;for(var c=0;c>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.tychei=s})(Vr,n,!1)}),ir=nr(function(n){(function(t,e){var i=this,r=256,a=6,s=52,o="random",l=e.pow(r,a),u=e.pow(2,s),c=u*2,h=r-1,d;function p(L,w,N){var I=[];w=w==!0?{entropy:!0}:w||{};var C=v(g(w.entropy?[L,S(t)]:L??b(),3),I),E=new f(I),k=function(){for(var W=E.g(a),F=l,_=0;W=c;)W/=2,F/=2,_>>>=1;return(W+_)/F};return k.int32=function(){return E.g(4)|0},k.quick=function(){return E.g(4)/4294967296},k.double=k,v(S(E.S),t),(w.pass||N||function(W,F,_,H){return H&&(H.S&&m(H,E),W.state=function(){return m(E,{})}),_?(e[o]=W,F):W})(k,C,"global"in w?w.global:this==e,w.state)}e["seed"+o]=p;function f(L){var w,N=L.length,I=this,C=0,E=I.i=I.j=0,k=I.S=[];for(N||(L=[N++]);C=this.items.length?[2,{value:null,done:!0}]:(e=this.items[this.trav],this.trav++,[2,{value:dU(e),done:!1}])})})},t}(Nt),mU=function(n){He(t,n);function t(e){var i=n.call(this)||this;return i.nextFn=e,i}return t.prototype.summary=function(){return"Function call"},t.prototype.next=function(){return se(this,void 0,void 0,function(){return oe(this,function(e){try{return[2,this.nextFn()]}catch(i){throw i.message="Error thrown while iterating through a dataset: "+i.message,i}return[2]})})},t}(Nt),bU=function(n){He(t,n);function t(e){var i=n.call(this)||this;return i.upstream=e,i.lastRead=Promise.resolve({value:null,done:!1}),i}return t.prototype.summary=function(){return this.upstream.summary()+" -> Serial"},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e=this;return oe(this,function(i){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return se(this,void 0,void 0,function(){return oe(this,function(e){return[2,this.upstream.next()]})})},t}(Nt),wU=function(n){He(t,n);function t(e,i){var r=n.call(this)||this;return r.upstream=e,r.maxCount=i,r.count=0,r.lastRead=Promise.resolve({value:null,done:!1}),r}return t.prototype.summary=function(){return this.upstream.summary()+" -> Skip"},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e=this;return oe(this,function(i){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return se(this,void 0,void 0,function(){var e;return oe(this,function(i){switch(i.label){case 0:return this.count++ Take"},t.prototype.next=function(){return se(this,void 0,void 0,function(){return oe(this,function(e){return this.count++>=this.maxCount?[2,{value:null,done:!0}]:[2,this.upstream.next()]})})},t}(Nt),LU=function(n){He(t,n);function t(e,i,r){r===void 0&&(r=!0);var a=n.call(this)||this;return a.upstream=e,a.batchSize=i,a.enableSmallLastBatch=r,a.lastRead=Promise.resolve({value:null,done:!1}),a}return t.prototype.summary=function(){return this.upstream.summary()+" -> RowMajorBatch"},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e=this;return oe(this,function(i){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return se(this,void 0,void 0,function(){var e,i;return oe(this,function(r){switch(r.label){case 0:e=[],r.label=1;case 1:return e.length0?[2,{value:e,done:!1}]:[2,{value:null,done:!0}]:(e.push(i.value),[3,1]);case 3:return[2,{value:e,done:!1}]}})})},t}(Nt),IU=function(n){He(t,n);function t(e,i){var r=n.call(this)||this;return r.upstream=e,r.predicate=i,r.lastRead=Promise.resolve({value:null,done:!1}),r}return t.prototype.summary=function(){return this.upstream.summary()+" -> Filter"},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e=this;return oe(this,function(i){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return se(this,void 0,void 0,function(){var e;return oe(this,function(i){switch(i.label){case 0:return[4,this.upstream.next()];case 1:return e=i.sent(),e.done||this.predicate(e.value)?[2,e]:(Ne.dispose(e.value),[3,0]);case 2:return[2]}})})},t}(Nt),AU=function(n){He(t,n);function t(e,i){var r=n.call(this)||this;return r.upstream=e,r.transform=i,r}return t.prototype.summary=function(){return this.upstream.summary()+" -> Map"},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e,i,r,a,s,o,l;return oe(this,function(u){switch(u.label){case 0:return[4,this.upstream.next()];case 1:if(e=u.sent(),e.done)return[2,{value:null,done:!0}];for(i=Ne.tensor_util.getTensorsInContainer(e.value),r=this.transform(e.value),a=Ne.tensor_util.getTensorsInContainer(r),s=0,o=i;s handleErrors"},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e=this;return oe(this,function(i){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return se(this,void 0,void 0,function(){var e;return oe(this,function(i){switch(i.label){case 0:i.label=1;case 1:return i.trys.push([1,3,,4]),[4,this.upstream.next()];case 2:return[2,i.sent()];case 3:return e=i.sent(),this.handler(e)?[3,4]:[2,{value:null,done:!0}];case 4:return[3,0];case 5:return[2]}})})},t}(Nt),pw=function(n){He(t,n);function t(e,i){var r=n.call(this)||this;return r.upstream=e,r.transform=i,r}return t.prototype.summary=function(){return this.upstream.summary()+" -> AsyncMap"},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e,i,r,a,s,o,l;return oe(this,function(u){switch(u.label){case 0:return[4,this.upstream.next()];case 1:return e=u.sent(),e.done?[2,{value:null,done:!0}]:(i=Ne.tensor_util.getTensorsInContainer(e.value),[4,this.transform(e.value)]);case 2:for(r=u.sent(),a=Ne.tensor_util.getTensorsInContainer(r),s=0,o=i;s Flatmap"},t.prototype.pump=function(){return se(this,void 0,void 0,function(){var e,i,r,a,s,o,l;return oe(this,function(u){switch(u.label){case 0:return[4,this.upstream.next()];case 1:if(e=u.sent(),e.done)return[2,!1];for(i=Ne.tensor_util.getTensorsInContainer(e.value),r=this.transform(e.value),a=Ne.tensor_util.getTensorsInContainer(r),this.outputQueue.pushAll(r),s=0,o=i;s Chained"},t.prototype.next=function(){return se(this,void 0,void 0,function(){return oe(this,function(e){return this.lastRead=this.readFromChain(this.lastRead),[2,this.lastRead]})})},t.prototype.readFromChain=function(e){return se(this,void 0,void 0,function(){var i,r;return oe(this,function(a){switch(a.label){case 0:return[4,e];case 1:return a.sent(),this.iterator==null?[4,this.moreIterators.next()]:[3,3];case 2:if(i=a.sent(),i.done)return[2,{value:null,done:!0}];this.iterator=i.value,this.baseErrorHandler!=null&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler)),a.label=3;case 3:return[4,this.iterator.next()];case 4:return r=a.sent(),r.done?(this.iterator=null,[2,this.readFromChain(e)]):[2,r]}})})},t}(Nt),bi;(function(n){n[n.FAIL=0]="FAIL",n[n.SHORTEST=1]="SHORTEST",n[n.LONGEST=2]="LONGEST"})(bi||(bi={}));var vU=function(n){He(t,n);function t(e,i){i===void 0&&(i=bi.FAIL);var r=n.call(this)||this;return r.iterators=e,r.mismatchMode=i,r.count=0,r.currentPromise=null,r}return t.prototype.summary=function(){var e="TODO: fill in upstream of zip summaries";return"{"+e+"} -> Zip"},t.prototype.nextState=function(e){return se(this,void 0,void 0,function(){function i(o){if(o instanceof Nt){var l=o.next();return{value:l.then(function(u){return r++,u.done&&a++,u.value}),recurse:!1}}else return{value:null,recurse:!0}}var r,a,s;return oe(this,function(o){switch(o.label){case 0:return[4,e];case 1:return o.sent(),r=0,a=0,[4,uw(this.iterators,i)];case 2:if(s=o.sent(),r===a)return[2,{value:null,done:!0}];if(a>0)switch(this.mismatchMode){case bi.FAIL:throw new Error("Zipped streams should have the same length. "+("Mismatched at element "+this.count+"."));case bi.SHORTEST:return[2,{value:null,done:!0}];case bi.LONGEST:}return this.count++,[2,{value:s,done:!1}]}})})},t.prototype.next=function(){return se(this,void 0,void 0,function(){return oe(this,function(e){return this.currentPromise=this.nextState(this.currentPromise),[2,this.currentPromise]})})},t}(Nt),fw=function(n){He(t,n);function t(e,i){var r=n.call(this)||this;return r.upstream=e,r.bufferSize=i,r.buffer=new cw(i),r}return t.prototype.summary=function(){return this.upstream.summary()+" -> Prefetch"},t.prototype.refill=function(){for(;!this.buffer.isFull();){var e=this.upstream.next();this.buffer.push(e)}},t.prototype.next=function(){return this.refill(),this.buffer.shift()},t}(Nt),xU=function(n){He(t,n);function t(e,i,r){var a=n.call(this,e,i)||this;return a.upstream=e,a.windowSize=i,a.upstreamExhausted=!1,a.random=sw(r||Ne.util.now().toString()),a.lastRead=Promise.resolve({value:null,done:!1}),a}return t.prototype.next=function(){return se(this,void 0,void 0,function(){var e=this;return oe(this,function(i){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.randomInt=function(e){return Math.floor(this.random()*e)},t.prototype.chooseIndex=function(){return this.randomInt(this.buffer.length())},t.prototype.serialNext=function(){return se(this,void 0,void 0,function(){var e,i;return oe(this,function(r){switch(r.label){case 0:this.upstreamExhausted||this.refill(),r.label=1;case 1:return this.buffer.isEmpty()?[3,3]:(e=this.chooseIndex(),[4,this.buffer.shuffleExcise(e)]);case 2:if(i=r.sent(),i.done)this.upstreamExhausted=!0;else return this.refill(),[2,i];return[3,1];case 3:return[2,{value:null,done:!0}]}})})},t}(fw);var Pa=function(){function n(){this.size=null}return n.prototype.batch=function(t,e){var i=this;e===void 0&&(e=!0);var r=this;Ne.util.assert(t>0,function(){return`batchSize needs to be positive, but it is - `+t});var a;return this.size===Infinity||this.size==null?a=this.size:e?a=Math.ceil(this.size/t):a=Math.floor(this.size/t),jt(function(){return se(i,void 0,void 0,function(){return oe(this,function(s){switch(s.label){case 0:return[4,r.iterator()];case 1:return[2,s.sent().columnMajorBatch(t,e,CU)]}})})},a)},n.prototype.concatenate=function(t){var e=this,i=this,r;return this.size===Infinity||t.size===Infinity?r=Infinity:this.size!=null&&t.size!=null?r=this.size+t.size:r=null,jt(function(){return se(e,void 0,void 0,function(){var a,s;return oe(this,function(o){switch(o.label){case 0:return[4,i.iterator()];case 1:return s=(a=o.sent()).concatenate,[4,t.iterator()];case 2:return[2,s.apply(a,[o.sent()])]}})})},r)},n.prototype.filter=function(t){var e=this,i=this,r;return this.size===Infinity?r=Infinity:r=null,jt(function(){return se(e,void 0,void 0,function(){return oe(this,function(a){switch(a.label){case 0:return[4,i.iterator()];case 1:return[2,a.sent().filter(function(s){return Ne.tidy(function(){return t(s)})})]}})})},r)},n.prototype.forEachAsync=function(t){return se(this,void 0,void 0,function(){return oe(this,function(e){switch(e.label){case 0:return[4,this.iterator()];case 1:return[2,e.sent().forEachAsync(t)]}})})},n.prototype.map=function(t){var e=this,i=this;return jt(function(){return se(e,void 0,void 0,function(){return oe(this,function(r){switch(r.label){case 0:return[4,i.iterator()];case 1:return[2,r.sent().map(function(a){return Ne.tidy(function(){return t(a)})})]}})})},this.size)},n.prototype.mapAsync=function(t){var e=this,i=this;return jt(function(){return se(e,void 0,void 0,function(){return oe(this,function(r){switch(r.label){case 0:return[4,i.iterator()];case 1:return[2,r.sent().mapAsync(t)]}})})},this.size)},n.prototype.prefetch=function(t){var e=this;if(t==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");var i=this;return jt(function(){return se(e,void 0,void 0,function(){return oe(this,function(r){switch(r.label){case 0:return[4,i.iterator()];case 1:return[2,r.sent().prefetch(t)]}})})},this.size)},n.prototype.repeat=function(t){var e=this,i=this,r;return this.size!=null&&t>0?r=this.size*t:t===0?r=0:this.size!=null&&(t===void 0||t<0)?r=Infinity:r=null,jt(function(){return se(e,void 0,void 0,function(){var a,s=this;return oe(this,function(o){return a=ad(function(){return se(s,void 0,void 0,function(){var l;return oe(this,function(u){switch(u.label){case 0:return l={},[4,i.iterator()];case 1:return[2,(l.value=u.sent(),l.done=!1,l)]}})})}),[2,gU(a.take(t))]})})},r)},n.prototype.skip=function(t){var e=this,i=this,r;return this.size!=null&&t>=0&&this.size>=t?r=this.size-t:this.size!=null&&(this.sizet?r=t:this.size!=null&&this.size<=t?r=this.size:r=null,jt(function(){return se(e,void 0,void 0,function(){return oe(this,function(a){switch(a.label){case 0:return[4,i.iterator()];case 1:return[2,a.sent().take(t)]}})})},r)},n.prototype.toArray=function(){return se(this,void 0,void 0,function(){return oe(this,function(t){switch(t.label){case 0:if(this.size===Infinity)throw new Error("Can not convert infinite data stream to array.");return[4,this.iterator()];case 1:return[2,t.sent().toArray()]}})})},n.prototype.toArrayForTest=function(){return se(this,void 0,void 0,function(){return oe(this,function(t){switch(t.label){case 0:if(this.size===Infinity)throw new Error("Can not convert infinite data stream to array.");return[4,this.iterator()];case 1:return[2,t.sent().toArrayForTest()]}})})},n.MAX_BUFFER_SIZE=1e4,n}();function jt(n,t){return t===void 0&&(t=null),new(function(e){He(i,e);function i(){var r=e!==null&&e.apply(this,arguments)||this;return r.size=t,r}return i.prototype.iterator=function(){return se(this,void 0,void 0,function(){return oe(this,function(r){return[2,n()]})})},i}(Pa))}function RU(n){var t=this;return jt(function(){return se(t,void 0,void 0,function(){return oe(this,function(e){return[2,hw(n)]})})},n.length)}function OU(n){var t=this;if(!qr(n))throw new Error("The argument to zip() must be an object or array.");var e;if(Array.isArray(n))for(var i=0;i1}),Ne.util.assert(r.length===0,function(){return"Duplicate column names found: "+r.toString()}),this.columnConfigs){for(a=0,s=Object.keys(this.columnConfigs);a14||!Number.isInteger(r))throw new Error("Invalid fftSize: it must be a power of 2 between "+("2 to 4 and 2 to 14, but got "+i.fftSize));if(i.numFrames=e.numFramesPerSpectrogram||43,i.sampleRateHz=e.sampleRateHz,i.columnTruncateLength=e.columnTruncateLength||i.fftSize,i.audioTrackConstraints=e.audioTrackConstraints,i.smoothingTimeConstant=e.smoothingTimeConstant||0,i.includeSpectrogram=!(e.includeSpectrogram===!1),i.includeWaveform=e.includeWaveform===!0,!i.includeSpectrogram&&!i.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.");return i}return t.prototype.summary=function(){return"microphone"},t.create=function(e){return e===void 0&&(e={}),se(this,void 0,void 0,function(){var i;return oe(this,function(r){switch(r.label){case 0:if(Ne.env().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");return i=new t(e),[4,i.start()];case 1:return r.sent(),[2,i]}})})},t.prototype.start=function(){return se(this,void 0,void 0,function(){var e,i,r,a;return oe(this,function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),e=this,[4,navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null?!0:this.audioTrackConstraints,video:!1})];case 1:return e.stream=s.sent(),[3,3];case 2:throw i=s.sent(),new Error("Error thrown while initializing video stream: "+i.message);case 3:if(!this.stream)throw new Error("Could not obtain audio from microphone.");if(r=window.AudioContext||window.webkitAudioContext,this.audioContext=new r,!this.sampleRateHz)this.sampleRateHz=this.audioContext.sampleRate;else if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error("Mismatch in sampling rate: "+("Expected: "+this.sampleRateHz+"; ")+("Actual: "+this.audioContext.sampleRate));return a=this.audioContext.createMediaStreamSource(this.stream),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=this.fftSize*2,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,a.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize),[2]}})})},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e,i,r,a,s;return oe(this,function(o){switch(o.label){case 0:return this.isClosed?[2,{value:null,done:!0}]:[4,this.getAudioData()];case 1:return r=o.sent(),this.includeSpectrogram&&(a=this.flattenQueue(r.freqDataQueue),e=this.getTensorFromAudioDataArray(a,[this.numFrames,this.columnTruncateLength,1])),this.includeWaveform&&(s=this.flattenQueue(r.timeDataQueue),i=this.getTensorFromAudioDataArray(s,[this.numFrames*this.fftSize,1])),[2,{value:{spectrogram:e,waveform:i},done:!1}]}})})},t.prototype.capture=function(){return se(this,void 0,void 0,function(){return oe(this,function(e){switch(e.label){case 0:return[4,this.next()];case 1:return[2,e.sent().value]}})})},t.prototype.getAudioData=function(){return se(this,void 0,void 0,function(){var e,i,r,a=this;return oe(this,function(s){return e=[],i=[],r=0,[2,new Promise(function(o){var l=setInterval(function(){a.includeSpectrogram&&(a.analyser.getFloatFrequencyData(a.freqData),a.freqData[0]===-Infinity&&o({freqDataQueue:e,timeDataQueue:i}),e.push(a.freqData.slice(0,a.columnTruncateLength))),a.includeWaveform&&(a.analyser.getFloatTimeDomainData(a.timeData),i.push(a.timeData.slice())),++r===a.numFrames&&(clearInterval(l),o({freqDataQueue:e,timeDataQueue:i}))},a.fftSize/a.sampleRateHz*1e3)})]})})},t.prototype.stop=function(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),this.stream!=null&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())},t.prototype.toArray=function(){throw new Error("Can not convert infinite audio stream to array.")},t.prototype.getSampleRate=function(){return this.sampleRateHz},t.prototype.flattenQueue=function(e){var i=e[0].length,r=new Float32Array(e.length*i);return e.forEach(function(a,s){return r.set(a,s*i)}),r},t.prototype.getTensorFromAudioDataArray=function(e,i){var r=new Float32Array(Ne.util.sizeFromShape(i));return r.set(e,r.length-e.length),Ne.tensor(r,i)},t}(Nt);var kU=function(n){He(t,n);function t(e,i){var r=n.call(this)||this;if(r.webcamVideoElement=e,r.webcamConfig=i,r.isClosed=!0,r.resize=!1,r.needToResize())if(r.resize=!0,r.cropSize=[r.webcamConfig.resizeHeight,r.webcamConfig.resizeWidth],r.cropBoxInd=Ne.tensor1d([0],"int32"),r.webcamConfig.centerCrop){var a=r.webcamConfig.resizeWidth*1/r.webcamVideoElement.width,s=r.webcamConfig.resizeHeight*1/r.webcamVideoElement.height,o=(1-a)/2,l=(1-s)/2,u=o+a,c=s+l;r.cropBox=Ne.tensor2d([l,o,c,u],[1,4])}else r.cropBox=Ne.tensor2d([0,0,1,1],[1,4]);return r}return t.prototype.summary=function(){return"webcam"},t.create=function(e,i){return i===void 0&&(i={}),se(this,void 0,void 0,function(){var r;return oe(this,function(a){switch(a.label){case 0:if(Ne.env().get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!i.resizeWidth||!i.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=i.resizeWidth,e.height=i.resizeHeight}return r=new t(e,i),[4,r.start()];case 1:return a.sent(),[2,r]}})})},t.prototype.start=function(){return se(this,void 0,void 0,function(){var e,i,r=this;return oe(this,function(a){switch(a.label){case 0:this.webcamConfig.facingMode&&Ne.util.assert(this.webcamConfig.facingMode==="user"||this.webcamConfig.facingMode==="environment",function(){return"Invalid webcam facing mode: "+r.webcamConfig.facingMode+". Please provide 'user' or 'environment'"}),a.label=1;case 1:return a.trys.push([1,3,,4]),e=this,[4,navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})];case 2:return e.stream=a.sent(),[3,4];case 3:throw i=a.sent(),i.message="Error thrown while initializing video stream: "+i.message,i;case 4:if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(s){console.log(s),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,[2,new Promise(function(s){r.webcamVideoElement.onloadedmetadata=function(){s()}})]}})})},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e;return oe(this,function(i){if(this.isClosed)return[2,{value:null,done:!0}];try{e=Ne.browser.fromPixels(this.webcamVideoElement)}catch(r){throw new Error("Error thrown converting video to pixels: "+JSON.stringify(r))}if(this.resize)try{return[2,{value:this.cropAndResizeFrame(e),done:!1}]}catch(r){throw new Error("Error thrown cropping the video: "+r.message)}finally{e.dispose()}else return[2,{value:e,done:!1}];return[2]})})},t.prototype.needToResize=function(){return!!(this.webcamConfig.resizeWidth&&this.webcamConfig.resizeHeight&&(this.webcamVideoElement.width!==this.webcamConfig.resizeWidth||this.webcamVideoElement.height!==this.webcamConfig.resizeHeight))},t.prototype.cropAndResizeFrame=function(e){var i=this;return Ne.tidy(function(){var r=e.toFloat().expandDims(0),a;a=Ne.image.cropAndResize(r,i.cropBox,i.cropBoxInd,i.cropSize,"bilinear");var s=a.shape;return a.reshape(s.slice(1))})},t.prototype.capture=function(){return se(this,void 0,void 0,function(){return oe(this,function(e){switch(e.label){case 0:return[4,this.next()];case 1:return[2,e.sent().value]}})})},t.prototype.stop=function(){var e=this.stream.getTracks();e.forEach(function(i){return i.stop()});try{this.webcamVideoElement.srcObject=null}catch(i){console.log(i),this.webcamVideoElement.src=null}this.isClosed=!0},t.prototype.toArray=function(){throw new Error("Can not convert infinite video stream to array.")},t}(Nt);var bw=function(){function n(){}return n}();var ww=function(n){He(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.split=function(e){return new FU(this,e)},t}(Nt),FU=function(n){He(t,n);function t(e,i){var r=n.call(this)||this;return r.upstream=e,r.impl=new WU(e,i),r}return t.prototype.summary=function(){return this.impl.summary()},t.prototype.next=function(){return se(this,void 0,void 0,function(){return oe(this,function(e){return[2,this.impl.next()]})})},t}(ww),WU=function(n){He(t,n);function t(e,i){var r=n.call(this)||this;return r.upstream=e,r.separator=i,r.carryover="",r}return t.prototype.summary=function(){return this.upstream.summary()+" -> Split('"+this.separator+"')"},t.prototype.pump=function(){return se(this,void 0,void 0,function(){var e,i,r,a,s;return oe(this,function(o){switch(o.label){case 0:return[4,this.upstream.next()];case 1:if(e=o.sent(),e.done)return this.carryover===""?[2,!1]:(this.outputQueue.push(this.carryover),this.carryover="",[2,!0]);for(i=e.value.split(this.separator),i[0]=this.carryover+i[0],r=0,a=i.slice(0,-1);r Utf8"},t.prototype.pump=function(){return se(this,void 0,void 0,function(){var e,i,r;return oe(this,function(a){switch(a.label){case 0:return[4,this.upstream.next()];case 1:return e=a.sent(),e.done?[2,!1]:(i=e.value,Ne.env().get("IS_BROWSER")?r=this.decoder.decode(i,{stream:!0}):r=this.decoder.write(Buffer.from(i.buffer)),this.outputQueue.push(r),[2,!0])}})})},t}(sd);var Sw=function(n){He(t,n);function t(e,i){i===void 0&&(i={});var r=n.call(this)||this;return r.file=e,r.options=i,Ne.util.assert(e instanceof Uint8Array||(Ne.env().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),function(){return"FileChunkIterator only supports File, Blob and Uint8Array right now."}),r.offset=i.offset||0,r.chunkSize=i.chunkSize||1024*1024,r}return t.prototype.summary=function(){return"FileChunks "+this.file},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e,i,r=this;return oe(this,function(a){switch(a.label){case 0:return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?[2,{value:null,done:!0}]:(e=new Promise(function(s,o){var l=r.offset+r.chunkSize;if(r.file instanceof Uint8Array)s(new Uint8Array(r.file.slice(r.offset,l)));else{var u=new FileReader;u.onload=function(h){var d=u.result;if(d instanceof ArrayBuffer&&(d=new Uint8Array(d)),!(d instanceof Uint8Array))return o(new TypeError("FileReader returned unknown type."));s(d)},u.onabort=function(h){return o(new Error("Aborted"))},u.onerror=function(h){return o(new Error(h.type))};var c=r.file.slice(r.offset,l);u.readAsArrayBuffer(c)}r.offset=l}),i={},[4,e]);case 1:return[2,(i.value=a.sent(),i.done=!1,i)]}})})},t}(BU);function PU(n,t){return t===void 0&&(t={}),se(this,void 0,void 0,function(){var e,i,r,a,s;return oe(this,function(o){switch(o.label){case 0:return typeof n=="string"?e=n:(e=n.url,i=_U(n)),[4,Ne.util.fetch(e,i)];case 1:return r=o.sent(),r.ok?(s=Uint8Array.bind,[4,r.arrayBuffer()]):[3,3];case 2:return a=new(s.apply(Uint8Array,[void 0,o.sent()])),[2,new Sw(a,t)];case 3:throw new Error(r.statusText)}})})}var _U=function(n){var t={method:n.method,headers:n.headers,body:n.body,mode:n.mode,credentials:n.credentials,cache:n.cache,redirect:n.redirect,referrer:n.referrer,integrity:n.integrity};return t};function Lw(n){return typeof n=="string"&&n.substr(0,7)==="file://"}var Iw=function(n){He(t,n);function t(e,i){i===void 0&&(i={});var r=n.call(this)||this;return r.input=e,r.options=i,r}return t.prototype.iterator=function(){return se(this,void 0,void 0,function(){var e;return oe(this,function(i){return Lw(this.input)&&Ne.env().get("IS_NODE")&&(e=require("fs"),this.input=e.readFileSync(this.input.substr(7))),[2,new Sw(this.input,this.options)]})})},t}(bw);var Aw=function(n){He(t,n);function t(e,i){i===void 0&&(i={});var r=n.call(this)||this;return r.url=e,r.fileOptions=i,r}return t.prototype.iterator=function(){return se(this,void 0,void 0,function(){return oe(this,function(e){return Lw(this.url)?[2,new Iw(this.url,this.fileOptions).iterator()]:[2,PU(this.url,this.fileOptions)]})})},t}(bw);function MU(n,t){return t===void 0&&(t={}),new yw(new Aw(n),t)}function HU(n){var t=this,e=ad(n);return jt(function(){return se(t,void 0,void 0,function(){return oe(this,function(i){return[2,e]})})})}function VU(n){var t=this;return jt(function(){return se(t,void 0,void 0,function(){var e;return oe(this,function(i){switch(i.label){case 0:return[4,n()];case 1:return e=i.sent(),[2,ad(function(){return e.next()})]}})})})}function qU(n,t){return se(this,void 0,void 0,function(){return oe(this,function(e){return[2,kU.create(n,t)]})})}function GU(n){return se(this,void 0,void 0,function(){return oe(this,function(t){return[2,DU.create(n)]})})}var YU="2.6.0";Mt.CSVDataset=yw;Mt.Dataset=Pa;Mt.FileDataSource=Iw;Mt.TextLineDataset=mw;Mt.URLDataSource=Aw;Mt.array=RU;Mt.csv=MU;Mt.func=HU;Mt.generator=VU;Mt.microphone=GU;Mt.version_data=YU;Mt.webcam=qU;Mt.zip=OU});var xw=be((Nw,ld)=>{(function(n,t,e){function i(o){var l=this,u=s();l.next=function(){var c=2091639*l.s0+l.c*23283064365386963e-26;return l.s0=l.s1,l.s1=l.s2,l.s2=c-(l.c=c|0)},l.c=1,l.s0=u(" "),l.s1=u(" "),l.s2=u(" "),l.s0-=u(o),l.s0<0&&(l.s0+=1),l.s1-=u(o),l.s1<0&&(l.s1+=1),l.s2-=u(o),l.s2<0&&(l.s2+=1),u=null}function r(o,l){return l.c=o.c,l.s0=o.s0,l.s1=o.s1,l.s2=o.s2,l}function a(o,l){var u=new i(o),c=l&&l.state,h=u.next;return h.int32=function(){return u.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,c&&(typeof c=="object"&&r(c,u),h.state=function(){return r(u,{})}),h}function s(){var o=4022871197,l=function(u){u=u.toString();for(var c=0;c>>0,h-=o,h*=o,o=h>>>0,h-=o,o+=h*4294967296}return(o>>>0)*23283064365386963e-26};return l}t&&t.exports?t.exports=a:e&&e.amd?e(function(){return a}):this.alea=a})(Nw,typeof ld=="object"&&ld,typeof define=="function"&&define)});var Rw=be((Cw,ud)=>{(function(n,t,e){function i(s){var o=this,l="";o.x=0,o.y=0,o.z=0,o.w=0,o.next=function(){var c=o.x^o.x<<11;return o.x=o.y,o.y=o.z,o.z=o.w,o.w^=o.w>>>19^c^c>>>8},s===(s|0)?o.x=s:l+=s;for(var u=0;u>>0)/4294967296};return c.double=function(){do var h=l.next()>>>11,d=(l.next()>>>0)/4294967296,p=(h+d)/(1<<21);while(p===0);return p},c.int32=l.next,c.quick=c,u&&(typeof u=="object"&&r(u,l),c.state=function(){return r(l,{})}),c}t&&t.exports?t.exports=a:e&&e.amd?e(function(){return a}):this.xor128=a})(Cw,typeof ud=="object"&&ud,typeof define=="function"&&define)});var Ew=be((Ow,cd)=>{(function(n,t,e){function i(s){var o=this,l="";o.next=function(){var c=o.x^o.x>>>2;return o.x=o.y,o.y=o.z,o.z=o.w,o.w=o.v,(o.d=o.d+362437|0)+(o.v=o.v^o.v<<4^(c^c<<1))|0},o.x=0,o.y=0,o.z=0,o.w=0,o.v=0,s===(s|0)?o.x=s:l+=s;for(var u=0;u>>4),o.next()}function r(s,o){return o.x=s.x,o.y=s.y,o.z=s.z,o.w=s.w,o.v=s.v,o.d=s.d,o}function a(s,o){var l=new i(s),u=o&&o.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var h=l.next()>>>11,d=(l.next()>>>0)/4294967296,p=(h+d)/(1<<21);while(p===0);return p},c.int32=l.next,c.quick=c,u&&(typeof u=="object"&&r(u,l),c.state=function(){return r(l,{})}),c}t&&t.exports?t.exports=a:e&&e.amd?e(function(){return a}):this.xorwow=a})(Ow,typeof cd=="object"&&cd,typeof define=="function"&&define)});var kw=be((Dw,hd)=>{(function(n,t,e){function i(s){var o=this;o.next=function(){var u=o.x,c=o.i,h,d,p;return h=u[c],h^=h>>>7,d=h^h<<24,h=u[c+1&7],d^=h^h>>>10,h=u[c+3&7],d^=h^h>>>3,h=u[c+4&7],d^=h^h<<7,h=u[c+7&7],h=h^h<<13,d^=h^h<<9,u[c]=d,o.i=c+1&7,d};function l(u,c){var h,d,p=[];if(c===(c|0))d=p[0]=c;else for(c=""+c,h=0;h0;--h)u.next()}l(o,s)}function r(s,o){return o.x=s.x.slice(),o.i=s.i,o}function a(s,o){s==null&&(s=+new Date);var l=new i(s),u=o&&o.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var h=l.next()>>>11,d=(l.next()>>>0)/4294967296,p=(h+d)/(1<<21);while(p===0);return p},c.int32=l.next,c.quick=c,u&&(u.x&&r(u,l),c.state=function(){return r(l,{})}),c}t&&t.exports?t.exports=a:e&&e.amd?e(function(){return a}):this.xorshift7=a})(Dw,typeof hd=="object"&&hd,typeof define=="function"&&define)});var Ww=be((Fw,dd)=>{(function(n,t,e){function i(s){var o=this;o.next=function(){var u=o.w,c=o.X,h=o.i,d,p;return o.w=u=u+1640531527|0,p=c[h+34&127],d=c[h=h+1&127],p^=p<<13,d^=d<<17,p^=p>>>15,d^=d>>>12,p=c[h]=p^d,o.i=h,p+(u^u>>>16)|0};function l(u,c){var h,d,p,f,m,g=[],v=128;for(c===(c|0)?(d=c,c=null):(c=c+"\0",d=0,v=Math.max(v,c.length)),p=0,f=-32;f>>15,d^=d<<4,d^=d>>>13,f>=0&&(m=m+1640531527|0,h=g[f&127]^=d+m,p=h==0?p+1:0);for(p>=128&&(g[(c&&c.length||0)&127]=-1),p=127,f=4*128;f>0;--f)d=g[p+34&127],h=g[p=p+1&127],d^=d<<13,h^=h<<17,d^=d>>>15,h^=h>>>12,g[p]=d^h;u.w=m,u.X=g,u.i=p}l(o,s)}function r(s,o){return o.i=s.i,o.w=s.w,o.X=s.X.slice(),o}function a(s,o){s==null&&(s=+new Date);var l=new i(s),u=o&&o.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var h=l.next()>>>11,d=(l.next()>>>0)/4294967296,p=(h+d)/(1<<21);while(p===0);return p},c.int32=l.next,c.quick=c,u&&(u.X&&r(u,l),c.state=function(){return r(l,{})}),c}t&&t.exports?t.exports=a:e&&e.amd?e(function(){return a}):this.xor4096=a})(Fw,typeof dd=="object"&&dd,typeof define=="function"&&define)});var Bw=be((Uw,pd)=>{(function(n,t,e){function i(s){var o=this,l="";o.next=function(){var c=o.b,h=o.c,d=o.d,p=o.a;return c=c<<25^c>>>7^h,h=h-d|0,d=d<<24^d>>>8^p,p=p-c|0,o.b=c=c<<20^c>>>12^h,o.c=h=h-d|0,o.d=d<<16^h>>>16^p,o.a=p-c|0},o.a=0,o.b=0,o.c=2654435769|0,o.d=1367130551,s===Math.floor(s)?(o.a=s/4294967296|0,o.b=s|0):l+=s;for(var u=0;u>>0)/4294967296};return c.double=function(){do var h=l.next()>>>11,d=(l.next()>>>0)/4294967296,p=(h+d)/(1<<21);while(p===0);return p},c.int32=l.next,c.quick=c,u&&(typeof u=="object"&&r(u,l),c.state=function(){return r(l,{})}),c}t&&t.exports?t.exports=a:e&&e.amd?e(function(){return a}):this.tychei=a})(Uw,typeof pd=="object"&&pd,typeof define=="function"&&define)});var zw=be((LH,Ao)=>{(function(n,t){var e=this,i=256,r=6,a=52,s="random",o=t.pow(i,r),l=t.pow(2,a),u=l*2,c=i-1,h;function d(S,L,w){var N=[];L=L==!0?{entropy:!0}:L||{};var I=g(m(L.entropy?[S,b(n)]:S??v(),3),N),C=new p(N),E=function(){for(var k=C.g(r),W=o,F=0;k=u;)k/=2,W/=2,F>>>=1;return(k+F)/W};return E.int32=function(){return C.g(4)|0},E.quick=function(){return C.g(4)/4294967296},E.double=E,g(b(C.S),n),(L.pass||w||function(k,W,F,_){return _&&(_.S&&f(_,C),k.state=function(){return f(C,{})}),F?(t[s]=k,W):k})(E,I,"global"in L?L.global:this==t,L.state)}t["seed"+s]=d;function p(S){var L,w=S.length,N=this,I=0,C=N.i=N.j=0,E=N.S=[];for(w||(S=[w++]);I{var KU=xw(),jU=Rw(),$U=Ew(),XU=kw(),JU=Ww(),ZU=Bw(),rr=zw();rr.alea=KU;rr.xor128=jU;rr.xorwow=$U;rr.xorshift7=XU;rr.xor4096=JU;rr.tychei=ZU;_w.exports=rr});var d0=be(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});var x=Ki(),QU=Pw();var fd=function(n,t){return fd=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,i){e.__proto__=i}||function(e,i){for(var r in i)i.hasOwnProperty(r)&&(e[r]=i[r])},fd(n,t)};function eB(n,t){fd(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function Mw(n,t,e,i){function r(a){return a instanceof e?a:new e(function(s){s(a)})}return new(e||(e=Promise))(function(a,s){function o(c){try{u(i.next(c))}catch(h){s(h)}}function l(c){try{u(i.throw(c))}catch(h){s(h)}}function u(c){c.done?a(c.value):r(c.value).then(o,l)}u((i=i.apply(n,t||[])).next())})}function Hw(n,t){var e={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,r,a,s;return s={next:o(0),throw:o(1),return:o(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function o(u){return function(c){return l([u,c])}}function l(u){if(i)throw new TypeError("Generator is already executing.");for(;e;)try{if(i=1,r&&(a=u[0]&2?r.return:u[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,u[1])).done)return a;(r=0,a)&&(u=[u[0]&2,a.value]);switch(u[0]){case 0:case 1:a=u;break;case 4:return e.label++,{value:u[1],done:!1};case 5:e.label++,r=u[1],u=[0];continue;case 7:u=e.ops.pop(),e.trys.pop();continue;default:if(!(a=e.trys,a=a.length>0&&a[a.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!a||u[1]>a[0]&&u[1]1)this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();else throw new Error("Cannot exit frame, the context is empty")},n.prototype.nextIteration=function(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice(),this.lastId++;var t=Object.assign({},this.contexts[this.contexts.length-1]);t.iterationId+=1,t.id=this.lastId,this.contexts.splice(-1,1,t),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else throw new Error("Cannot increase frame iteration, the context is empty")},n.prototype.getWeight=function(t){return this.weightMap[t]},n.prototype.addTensorArray=function(t){this.tensorArrayMap[t.id]=t},n.prototype.getTensorArray=function(t){return this.tensorArrayMap[t]},n.prototype.addTensorList=function(t){this.tensorListMap[t.id]=t},n.prototype.getTensorList=function(t){return this.tensorListMap[t]},n.prototype.dispose=function(t){for(var e in this.tensorArrayMap)this.tensorArrayMap[e].clearAndClose(t);for(var e in this.tensorListMap)this.tensorListMap[e].clearAndClose(t)},n}();function tw(n,t,e,i){var r=new Set,a=[],s=null,o=null,l=new Set,u=Object.keys(n).map(function(p){return Kt(p)[0]}),c=[];i!=null&&(c=i.map(function(p){return Kt(p.name)[0]}));for(var h=t.slice();h.length>0;){var d=h.pop();if((ew(d)||KW(d))&&(s==null&&(s=d,o=s.children.map(function(p){return p.name}).filter(function(p){return r.has(p)}))),r.add(d.name),e[d.name]!=null)continue;if(u.indexOf(d.name)!==-1)continue;if(c.indexOf(d.name)!==-1)continue;if(d.inputs.length===0){a.push(d.name);continue}d.inputs.forEach(function(p){if(l.has(p.name))return;l.add(p.name),h.push(p)})}return{inputs:n,outputs:t,usedNodes:r,missingInputs:a,dynamicNode:s,syncInputs:o}}function jW(n,t,e){var i=e.usedNodes,r=e.inputs,a=[],s=Object.keys(r).map(function(h){return Kt(h)[0]}).map(function(h){return n.nodes[h]}),o=n.initNodes;s.forEach(function(h){i.has(h.name)&&a.push(h)}),n.weights.forEach(function(h){i.has(h.name)&&a.push(h)}),o!=null&&o.forEach(function(h){i.has(h.name)&&a.push(h)});for(var l=new Set,u=[];a.length>0;){var c=a.pop();l.add(c.name),t[c.name]||u.push(c),c.children.forEach(function(h){!l.has(h.name)&&i.has(h.name)&&h.inputs.every(function(d){return l.has(d.name)})&&a.push(h)})}return u}var $W=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],XW=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"];function ew(n){return $W.indexOf(n.op)>=0}function KW(n){return XW.indexOf(n.op)>=0}var nw=function(){function n(t,e){var i=this;this.graph=t,this.parent=e,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._functions={},this._functionExecutorMap={},this._outputs=t.outputs,this._inputs=t.inputs,this._initNodes=t.initNodes,this._signature=t.signature,this._functions=t.functions,t.functions!=null&&Object.keys(t.functions).forEach(function(r){i._functionExecutorMap[r]=new n(t.functions[r],i)})}return Object.defineProperty(n.prototype,"weightIds",{get:function(){return this.parent?this.parent.weightIds:this._weightIds},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"functionExecutorMap",{get:function(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"weightMap",{get:function(){return this.parent?this.parent.weightMap:this._weightMap},set:function(t){var e=Object.keys(t).map(function(i){return t[i].map(function(r){return r.id})});this._weightIds=[].concat.apply([],e),this._weightMap=t},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"inputs",{get:function(){return this._inputs.map(function(t){return{name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"outputs",{get:function(){return this._outputs.map(function(t){return{name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"inputNodes",{get:function(){return this._inputs.map(function(t){return t.signatureKey||t.name})},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"outputNodes",{get:function(){return this._outputs.map(function(t){var e=t.signatureKey||t.name;return t.defaultOutput?e+":"+t.defaultOutput:e})},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"functions",{get:function(){var t=this;return Object.keys(this._functions).reduce(function(e,i){return e[i]=t._functions[i].signature,e},{})},enumerable:!0,configurable:!0}),n.prototype.getCompilationKey=function(t,e){var i=t.map(function(a){return a.name}).sort(),r=e.map(function(a){return a.name}).sort();return i.join(this.SEPERATOR)+"--"+r.join(this.SEPERATOR)},n.prototype.compile=function(t,e){var i=tw(t,e,this.weightMap,this._initNodes),r=i.missingInputs,a=i.dynamicNode,s=i.syncInputs;if(a!=null)throw new Error("This execution contains the node '"+a.name+"', which has "+("the dynamic op '"+a.op+"'. Please use ")+"model.executeAsync() instead. Alternatively, to avoid the "+("dynamic ops, specify the inputs ["+s+"]"));if(r.length>0){var o=e.map(function(u){return u.name}),l=Object.keys(t);throw new Error("Cannot compute the outputs ["+o+"] from the provided inputs "+("["+l+"]. Missing the following inputs: ["+r+"]"))}return jW(this.graph,this.weightMap,i)},n.prototype.execute=function(t,e){var i=this;t=this.mapInputs(t);var r=Object.keys(t).sort();this.checkInputs(t),this.checkInputShapeAndType(t),e=this.mapOutputs(e),this.checkOutputs(e);var a=r.map(function(d){return i.graph.nodes[Kt(d)[0]]}),s=e.map(function(d){return Kt(d)[0]}),o=s.map(function(d){return i.graph.nodes[d]});o.length===0&&(o=this._outputs);var l=this.getCompilationKey(a,o),u=this.compiledMap.get(l);u==null&&(u=this.compile(t,o),this.compiledMap.set(l,u));var c={},h={};return B.tidy(function(){var d=new Qb(i.weightMap,c,h,i.functionExecutorMap),p=qb({},i.weightMap);Object.keys(t).forEach(function(S){var L=Kt(S),w=L[0],N=L[1],I=[];I[N]=t[S],p[w]=I});for(var f=i.getFrozenTensorIds(p),m={},g=0;g0?(S=this.processStack(s,f,e,m,b,v,o,g,c),[4,Promise.all(S)]):[3,3];case 2:return I.sent(),[3,1];case 3:if(d==null&&!r&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead."),L=l.filter(function(C){return!ew(C)&&!Pt(C.name,m,e)}).map(function(C){return C.name}),L.length>0)throw w="",d!=null&&(w="Alternatively, to avoid the dynamic ops, use model.execute() "+("and specify the inputs ["+p+"]")),new Error("Cannot compute the outputs ["+L+"] from the provided "+("inputs ["+a+"]. Consider providing the following inputs: ")+("["+h+"]. "+w));return[2,m]}})})},n.prototype.processStack=function(t,e,i,r,a,s,o,l,u){for(var c=this,h=[],d=function(){var f=e.pop();i.currentContext=f.contexts;var m="";if(f.node.op==="Enter"&&T("isConstant",f.node,r,i)&&(m=Yn(f.node.name,i)[0]),t.indexOf(f.node)===-1){var g=Zb(f.node,r,i);m||(m=Yn(f.node.name,i)[0]);var v=i.currentContext;g instanceof Promise?h.push(g.then(function(b){return r[m]=b,i.currentContext=v,c.checkTensorForDisposal(m,f.node,r,i,s,o,l),c.processChildNodes(f.node,e,i,r,a,u),b})):(r[m]=g,p.checkTensorForDisposal(m,f.node,r,i,s,o,l),p.processChildNodes(f.node,e,i,r,a,u))}else p.processChildNodes(f.node,e,i,r,a,u)},p=this;e.length>0;)d();return h},n.prototype.processChildNodes=function(t,e,i,r,a,s){t.children.forEach(function(o){var l=Yn(o.name,i)[0];if(a[l]||!s.has(o.name))return;o.op==="Merge"?o.inputNames.some(function(u){return!!Pt(u,r,i)})&&(a[l]=!0,e.push({contexts:i.currentContext,node:o})):o.inputNames.every(function(u){return!!Pt(u,r,i)})&&(a[l]=!0,e.push({contexts:i.currentContext,node:o}))})},n.prototype.dispose=function(){var t=this;Object.keys(this.weightMap).forEach(function(e){return t.weightMap[e].forEach(function(i){return i.dispose()})})},n.prototype.checkInputShapeAndType=function(t){var e=this;Object.keys(t).forEach(function(i){var r=t[i],a=Kt(i)[0],s=e.graph.nodes[a];if(s.attrParams.shape&&s.attrParams.shape.value){var o=s.attrParams.shape.value,l=o.length===r.shape.length&&r.shape.every(function(u,c){return o[c]===-1||o[c]===u});B.util.assert(l,function(){return"The shape of dict['"+s.name+"'] provided in "+("model.execute(dict) must be ["+o+"], but was ")+("["+r.shape+"]")})}s.attrParams.dtype&&s.attrParams.dtype.value&&B.util.assert(r.dtype===s.attrParams.dtype.value,function(){return"The dtype of dict['"+s.name+"'] provided in model.execute(dict) must be "+(s.attrParams.dtype.value+", but was "+r.dtype)})})},n.prototype.mapInputs=function(t){var e={};for(var i in t)if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[i]!=null){var r=this._signature.inputs[i];e[r.name]=t[i]}else e[i]=t[i];return e},n.prototype.checkInputs=function(t){var e=this,i=Object.keys(t).filter(function(r){var a=Kt(r)[0];return e.graph.nodes[a]==null});if(i.length>0)throw new Error("The dict provided in model.execute(dict) has "+("keys: ["+i+"] that are not part of graph"))},n.prototype.mapOutputs=function(t){var e=this;return t.map(function(i){if(e._signature!=null&&e._signature.outputs!=null&&e._signature.outputs[i]!=null){var r=e._signature.outputs[i];return r.name}return i},{})},n.prototype.checkOutputs=function(t){var e=this;t.forEach(function(i){var r=Kt(i)[0];if(!e.graph.nodes[r])throw new Error("The output '"+i+"' is not found in the graph")})},n}();var JW="?tfjs-format=file",ZW="model.json",iw=function(){function n(t,e){e===void 0&&(e={}),this.modelUrl=t,this.loadOptions=e,this.version="n/a",e==null&&(this.loadOptions={})}return Object.defineProperty(n.prototype,"modelVersion",{get:function(){return this.version},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"inputNodes",{get:function(){return this.executor.inputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"outputNodes",{get:function(){return this.executor.outputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"inputs",{get:function(){return this.executor.inputs},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"outputs",{get:function(){return this.executor.outputs},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"weights",{get:function(){return this.executor.weightMap},enumerable:!0,configurable:!0}),n.prototype.findIOHandler=function(){var t=this.modelUrl;if(t.load!=null)this.handler=t;else if(this.loadOptions.requestInit!=null)this.handler=B.io.browserHTTPRequest(t,this.loadOptions);else{var e=B.io.getLoadHandlers(t,this.loadOptions);if(e.length===0)e.push(B.io.browserHTTPRequest(t,this.loadOptions));else if(e.length>1)throw new Error("Found more than one ("+e.length+") load handlers for "+("URL '"+[t]+"'"));this.handler=e[0]}},n.prototype.load=function(){return kn(this,void 0,void 0,function(){var t;return vn(this,function(e){switch(e.label){case 0:if(this.findIOHandler(),this.handler.load==null)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,this.handler.load()];case 1:return t=e.sent(),[2,this.loadSync(t)]}})})},n.prototype.loadSync=function(t){this.artifacts=t;var e=this.artifacts.modelTopology,i={};this.artifacts.userDefinedMetadata!=null&&(i=this.artifacts.userDefinedMetadata.signature),this.version=e.versions.producer+"."+e.versions.minConsumer;var r=B.io.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new nw(jb.Instance.transformGraph(e,i)),this.executor.weightMap=this.convertTensorMapToTensorsMap(r),t.modelInitializer!=null){var a=jb.Instance.transformGraph(t.modelInitializer);this.initializer=new nw(a),this.initializer.weightMap=this.executor.weightMap,this.initializer.execute({},[])}return!0},n.prototype.save=function(t,e){return kn(this,void 0,void 0,function(){var i;return vn(this,function(r){if(typeof t=="string"){if(i=B.io.getSaveHandlers(t),i.length===0)throw new Error("Cannot find any save handlers for URL '"+t+"'");if(i.length>1)throw new Error("Found more than one ("+i.length+") save handlers for "+("URL '"+t+"'"));t=i[0]}if(t.save==null)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[2,t.save(this.artifacts)]})})},n.prototype.predict=function(t,e){return this.execute(t,this.outputNodes)},n.prototype.normalizeInputs=function(t){if(!(t instanceof B.Tensor)&&!Array.isArray(t))return t;if(t=Array.isArray(t)?t:[t],t.length!==this.inputNodes.length)throw new Error("Input tensor count mismatch,"+("the graph model has "+this.inputNodes.length+" placeholders, ")+("while there are "+t.length+" input tensors."));return this.inputNodes.reduce(function(e,i,r){return e[i]=t[r],e},{})},n.prototype.normalizeOutputs=function(t){return t=t||this.outputNodes,Array.isArray(t)?t:[t]},n.prototype.execute=function(t,e){t=this.normalizeInputs(t),e=this.normalizeOutputs(e);var i=this.executor.execute(t,e);return i.length>1?i:i[0]},n.prototype.executeAsync=function(t,e){return kn(this,void 0,void 0,function(){var i;return vn(this,function(r){switch(r.label){case 0:return t=this.normalizeInputs(t),e=this.normalizeOutputs(e),[4,this.executor.executeAsync(t,e)];case 1:return i=r.sent(),[2,i.length>1?i:i[0]]}})})},n.prototype.convertTensorMapToTensorsMap=function(t){return Object.keys(t).reduce(function(e,i){return e[i]=[t[i]],e},{})},n.prototype.dispose=function(){this.executor.dispose(),this.initializer&&this.initializer.dispose()},n}();function QW(n,t){return t===void 0&&(t={}),kn(this,void 0,void 0,function(){var e;return vn(this,function(i){switch(i.label){case 0:if(n==null)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");return t==null&&(t={}),t.fromTFHub&&(n.load==null&&(n.endsWith("/")||(n=n+"/"),n=""+n+ZW+JW)),e=new iw(n,t),[4,e.load()];case 1:return i.sent(),[2,e]}})})}var eU="2.6.0";tr.GraphModel=iw;tr.deregisterOp=MF;tr.loadGraphModel=QW;tr.registerOp=PF;tr.version_converter=eU});var aw=be(()=>{});var Tw=be(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});var Ne=Ki();var rd=function(n,t){return rd=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,i){e.__proto__=i}||function(e,i){for(var r in i)i.hasOwnProperty(r)&&(e[r]=i[r])},rd(n,t)};function He(n,t){rd(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function se(n,t,e,i){return new(e||(e=Promise))(function(r,a){function s(u){try{l(i.next(u))}catch(c){a(c)}}function o(u){try{l(i.throw(u))}catch(c){a(c)}}function l(u){u.done?r(u.value):new e(function(c){c(u.value)}).then(s,o)}l((i=i.apply(n,t||[])).next())})}function oe(n,t){var e={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,r,a,s;return s={next:o(0),throw:o(1),return:o(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function o(u){return function(c){return l([u,c])}}function l(u){if(i)throw new TypeError("Generator is already executing.");for(;e;)try{if(i=1,r&&(a=u[0]&2?r.return:u[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,u[1])).done)return a;(r=0,a)&&(u=[u[0]&2,a.value]);switch(u[0]){case 0:case 1:a=u;break;case 4:return e.label++,{value:u[1],done:!1};case 5:e.label++,r=u[1],u=[0];continue;case 7:u=e.ops.pop(),e.trys.pop();continue;default:if(!(a=e.trys,a=a.length>0&&a[a.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!a||u[1]>a[0]&&u[1]>>0,d-=l,d*=l,l=d>>>0,d-=l,l+=d*4294967296}return(l>>>0)*23283064365386963e-26};return u}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.alea=s})(Vr,n,!1)}),nU=nr(function(n){(function(t,e,i){function r(o){var l=this,u="";l.x=0,l.y=0,l.z=0,l.w=0,l.next=function(){var h=l.x^l.x<<11;return l.x=l.y,l.y=l.z,l.z=l.w,l.w^=l.w>>>19^h^h>>>8},o===(o|0)?l.x=o:u+=o;for(var c=0;c>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.xor128=s})(Vr,n,!1)}),iU=nr(function(n){(function(t,e,i){function r(o){var l=this,u="";l.next=function(){var h=l.x^l.x>>>2;return l.x=l.y,l.y=l.z,l.z=l.w,l.w=l.v,(l.d=l.d+362437|0)+(l.v=l.v^l.v<<4^(h^h<<1))|0},l.x=0,l.y=0,l.z=0,l.w=0,l.v=0,o===(o|0)?l.x=o:u+=o;for(var c=0;c>>4),l.next()}function a(o,l){return l.x=o.x,l.y=o.y,l.z=o.z,l.w=o.w,l.v=o.v,l.d=o.d,l}function s(o,l){var u=new r(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.xorwow=s})(Vr,n,!1)}),rU=nr(function(n){(function(t,e,i){function r(o){var l=this;l.next=function(){var c=l.x,h=l.i,d,p;return d=c[h],d^=d>>>7,p=d^d<<24,d=c[h+1&7],p^=d^d>>>10,d=c[h+3&7],p^=d^d>>>3,d=c[h+4&7],p^=d^d<<7,d=c[h+7&7],d=d^d<<13,p^=d^d<<9,c[h]=p,l.i=h+1&7,p};function u(c,h){var d,p,f=[];if(h===(h|0))p=f[0]=h;else for(h=""+h,d=0;d0;--d)c.next()}u(l,o)}function a(o,l){return l.x=o.x.slice(),l.i=o.i,l}function s(o,l){o==null&&(o=+new Date);var u=new r(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(c.x&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.xorshift7=s})(Vr,n,!1)}),aU=nr(function(n){(function(t,e,i){function r(o){var l=this;l.next=function(){var c=l.w,h=l.X,d=l.i,p,f;return l.w=c=c+1640531527|0,f=h[d+34&127],p=h[d=d+1&127],f^=f<<13,p^=p<<17,f^=f>>>15,p^=p>>>12,f=h[d]=f^p,l.i=d,f+(c^c>>>16)|0};function u(c,h){var d,p,f,m,g,v=[],b=128;for(h===(h|0)?(p=h,h=null):(h=h+"\0",p=0,b=Math.max(b,h.length)),f=0,m=-32;m>>15,p^=p<<4,p^=p>>>13,m>=0&&(g=g+1640531527|0,d=v[m&127]^=p+g,f=d==0?f+1:0);for(f>=128&&(v[(h&&h.length||0)&127]=-1),f=127,m=4*128;m>0;--m)p=v[f+34&127],d=v[f=f+1&127],p^=p<<13,d^=d<<17,p^=p>>>15,d^=d>>>12,v[f]=p^d;c.w=g,c.X=v,c.i=f}u(l,o)}function a(o,l){return l.i=o.i,l.w=o.w,l.X=o.X.slice(),l}function s(o,l){o==null&&(o=+new Date);var u=new r(o),c=l&&l.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(c.X&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.xor4096=s})(Vr,n,!1)}),sU=nr(function(n){(function(t,e,i){function r(o){var l=this,u="";l.next=function(){var h=l.b,d=l.c,p=l.d,f=l.a;return h=h<<25^h>>>7^d,d=d-p|0,p=p<<24^p>>>8^f,f=f-h|0,l.b=h=h<<20^h>>>12^d,l.c=d=d-p|0,l.d=p<<16^d>>>16^f,l.a=f-h|0},l.a=0,l.b=0,l.c=2654435769|0,l.d=1367130551,o===Math.floor(o)?(l.a=o/4294967296|0,l.b=o|0):u+=o;for(var c=0;c>>0)/4294967296};return h.double=function(){do var d=u.next()>>>11,p=(u.next()>>>0)/4294967296,f=(d+p)/(1<<21);while(f===0);return f},h.int32=u.next,h.quick=h,c&&(typeof c=="object"&&a(c,u),h.state=function(){return a(u,{})}),h}e&&e.exports?e.exports=s:i&&i.amd?i(function(){return s}):this.tychei=s})(Vr,n,!1)}),ir=nr(function(n){(function(t,e){var i=this,r=256,a=6,s=52,o="random",l=e.pow(r,a),u=e.pow(2,s),c=u*2,h=r-1,d;function p(L,w,N){var I=[];w=w==!0?{entropy:!0}:w||{};var C=v(g(w.entropy?[L,S(t)]:L??b(),3),I),E=new f(I),k=function(){for(var W=E.g(a),F=l,_=0;W=c;)W/=2,F/=2,_>>>=1;return(W+_)/F};return k.int32=function(){return E.g(4)|0},k.quick=function(){return E.g(4)/4294967296},k.double=k,v(S(E.S),t),(w.pass||N||function(W,F,_,H){return H&&(H.S&&m(H,E),W.state=function(){return m(E,{})}),_?(e[o]=W,F):W})(k,C,"global"in w?w.global:this==e,w.state)}e["seed"+o]=p;function f(L){var w,N=L.length,I=this,C=0,E=I.i=I.j=0,k=I.S=[];for(N||(L=[N++]);C=this.items.length?[2,{value:null,done:!0}]:(e=this.items[this.trav],this.trav++,[2,{value:pU(e),done:!1}])})})},t}(Nt),gU=function(n){He(t,n);function t(e){var i=n.call(this)||this;return i.nextFn=e,i}return t.prototype.summary=function(){return"Function call"},t.prototype.next=function(){return se(this,void 0,void 0,function(){return oe(this,function(e){try{return[2,this.nextFn()]}catch(i){throw i.message="Error thrown while iterating through a dataset: "+i.message,i}return[2]})})},t}(Nt),wU=function(n){He(t,n);function t(e){var i=n.call(this)||this;return i.upstream=e,i.lastRead=Promise.resolve({value:null,done:!1}),i}return t.prototype.summary=function(){return this.upstream.summary()+" -> Serial"},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e=this;return oe(this,function(i){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return se(this,void 0,void 0,function(){return oe(this,function(e){return[2,this.upstream.next()]})})},t}(Nt),SU=function(n){He(t,n);function t(e,i){var r=n.call(this)||this;return r.upstream=e,r.maxCount=i,r.count=0,r.lastRead=Promise.resolve({value:null,done:!1}),r}return t.prototype.summary=function(){return this.upstream.summary()+" -> Skip"},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e=this;return oe(this,function(i){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return se(this,void 0,void 0,function(){var e;return oe(this,function(i){switch(i.label){case 0:return this.count++ Take"},t.prototype.next=function(){return se(this,void 0,void 0,function(){return oe(this,function(e){return this.count++>=this.maxCount?[2,{value:null,done:!0}]:[2,this.upstream.next()]})})},t}(Nt),IU=function(n){He(t,n);function t(e,i,r){r===void 0&&(r=!0);var a=n.call(this)||this;return a.upstream=e,a.batchSize=i,a.enableSmallLastBatch=r,a.lastRead=Promise.resolve({value:null,done:!1}),a}return t.prototype.summary=function(){return this.upstream.summary()+" -> RowMajorBatch"},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e=this;return oe(this,function(i){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return se(this,void 0,void 0,function(){var e,i;return oe(this,function(r){switch(r.label){case 0:e=[],r.label=1;case 1:return e.length0?[2,{value:e,done:!1}]:[2,{value:null,done:!0}]:(e.push(i.value),[3,1]);case 3:return[2,{value:e,done:!1}]}})})},t}(Nt),AU=function(n){He(t,n);function t(e,i){var r=n.call(this)||this;return r.upstream=e,r.predicate=i,r.lastRead=Promise.resolve({value:null,done:!1}),r}return t.prototype.summary=function(){return this.upstream.summary()+" -> Filter"},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e=this;return oe(this,function(i){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return se(this,void 0,void 0,function(){var e;return oe(this,function(i){switch(i.label){case 0:return[4,this.upstream.next()];case 1:return e=i.sent(),e.done||this.predicate(e.value)?[2,e]:(Ne.dispose(e.value),[3,0]);case 2:return[2]}})})},t}(Nt),TU=function(n){He(t,n);function t(e,i){var r=n.call(this)||this;return r.upstream=e,r.transform=i,r}return t.prototype.summary=function(){return this.upstream.summary()+" -> Map"},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e,i,r,a,s,o,l;return oe(this,function(u){switch(u.label){case 0:return[4,this.upstream.next()];case 1:if(e=u.sent(),e.done)return[2,{value:null,done:!0}];for(i=Ne.tensor_util.getTensorsInContainer(e.value),r=this.transform(e.value),a=Ne.tensor_util.getTensorsInContainer(r),s=0,o=i;s handleErrors"},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e=this;return oe(this,function(i){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return se(this,void 0,void 0,function(){var e;return oe(this,function(i){switch(i.label){case 0:i.label=1;case 1:return i.trys.push([1,3,,4]),[4,this.upstream.next()];case 2:return[2,i.sent()];case 3:return e=i.sent(),this.handler(e)?[3,4]:[2,{value:null,done:!0}];case 4:return[3,0];case 5:return[2]}})})},t}(Nt),pw=function(n){He(t,n);function t(e,i){var r=n.call(this)||this;return r.upstream=e,r.transform=i,r}return t.prototype.summary=function(){return this.upstream.summary()+" -> AsyncMap"},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e,i,r,a,s,o,l;return oe(this,function(u){switch(u.label){case 0:return[4,this.upstream.next()];case 1:return e=u.sent(),e.done?[2,{value:null,done:!0}]:(i=Ne.tensor_util.getTensorsInContainer(e.value),[4,this.transform(e.value)]);case 2:for(r=u.sent(),a=Ne.tensor_util.getTensorsInContainer(r),s=0,o=i;s Flatmap"},t.prototype.pump=function(){return se(this,void 0,void 0,function(){var e,i,r,a,s,o,l;return oe(this,function(u){switch(u.label){case 0:return[4,this.upstream.next()];case 1:if(e=u.sent(),e.done)return[2,!1];for(i=Ne.tensor_util.getTensorsInContainer(e.value),r=this.transform(e.value),a=Ne.tensor_util.getTensorsInContainer(r),this.outputQueue.pushAll(r),s=0,o=i;s Chained"},t.prototype.next=function(){return se(this,void 0,void 0,function(){return oe(this,function(e){return this.lastRead=this.readFromChain(this.lastRead),[2,this.lastRead]})})},t.prototype.readFromChain=function(e){return se(this,void 0,void 0,function(){var i,r;return oe(this,function(a){switch(a.label){case 0:return[4,e];case 1:return a.sent(),this.iterator==null?[4,this.moreIterators.next()]:[3,3];case 2:if(i=a.sent(),i.done)return[2,{value:null,done:!0}];this.iterator=i.value,this.baseErrorHandler!=null&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler)),a.label=3;case 3:return[4,this.iterator.next()];case 4:return r=a.sent(),r.done?(this.iterator=null,[2,this.readFromChain(e)]):[2,r]}})})},t}(Nt),bi;(function(n){n[n.FAIL=0]="FAIL",n[n.SHORTEST=1]="SHORTEST",n[n.LONGEST=2]="LONGEST"})(bi||(bi={}));var yU=function(n){He(t,n);function t(e,i){i===void 0&&(i=bi.FAIL);var r=n.call(this)||this;return r.iterators=e,r.mismatchMode=i,r.count=0,r.currentPromise=null,r}return t.prototype.summary=function(){var e="TODO: fill in upstream of zip summaries";return"{"+e+"} -> Zip"},t.prototype.nextState=function(e){return se(this,void 0,void 0,function(){function i(o){if(o instanceof Nt){var l=o.next();return{value:l.then(function(u){return r++,u.done&&a++,u.value}),recurse:!1}}else return{value:null,recurse:!0}}var r,a,s;return oe(this,function(o){switch(o.label){case 0:return[4,e];case 1:return o.sent(),r=0,a=0,[4,uw(this.iterators,i)];case 2:if(s=o.sent(),r===a)return[2,{value:null,done:!0}];if(a>0)switch(this.mismatchMode){case bi.FAIL:throw new Error("Zipped streams should have the same length. "+("Mismatched at element "+this.count+"."));case bi.SHORTEST:return[2,{value:null,done:!0}];case bi.LONGEST:}return this.count++,[2,{value:s,done:!1}]}})})},t.prototype.next=function(){return se(this,void 0,void 0,function(){return oe(this,function(e){return this.currentPromise=this.nextState(this.currentPromise),[2,this.currentPromise]})})},t}(Nt),fw=function(n){He(t,n);function t(e,i){var r=n.call(this)||this;return r.upstream=e,r.bufferSize=i,r.buffer=new cw(i),r}return t.prototype.summary=function(){return this.upstream.summary()+" -> Prefetch"},t.prototype.refill=function(){for(;!this.buffer.isFull();){var e=this.upstream.next();this.buffer.push(e)}},t.prototype.next=function(){return this.refill(),this.buffer.shift()},t}(Nt),CU=function(n){He(t,n);function t(e,i,r){var a=n.call(this,e,i)||this;return a.upstream=e,a.windowSize=i,a.upstreamExhausted=!1,a.random=sw(r||Ne.util.now().toString()),a.lastRead=Promise.resolve({value:null,done:!1}),a}return t.prototype.next=function(){return se(this,void 0,void 0,function(){var e=this;return oe(this,function(i){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.randomInt=function(e){return Math.floor(this.random()*e)},t.prototype.chooseIndex=function(){return this.randomInt(this.buffer.length())},t.prototype.serialNext=function(){return se(this,void 0,void 0,function(){var e,i;return oe(this,function(r){switch(r.label){case 0:this.upstreamExhausted||this.refill(),r.label=1;case 1:return this.buffer.isEmpty()?[3,3]:(e=this.chooseIndex(),[4,this.buffer.shuffleExcise(e)]);case 2:if(i=r.sent(),i.done)this.upstreamExhausted=!0;else return this.refill(),[2,i];return[3,1];case 3:return[2,{value:null,done:!0}]}})})},t}(fw);var Pa=function(){function n(){this.size=null}return n.prototype.batch=function(t,e){var i=this;e===void 0&&(e=!0);var r=this;Ne.util.assert(t>0,function(){return`batchSize needs to be positive, but it is + `+t});var a;return this.size===Infinity||this.size==null?a=this.size:e?a=Math.ceil(this.size/t):a=Math.floor(this.size/t),jt(function(){return se(i,void 0,void 0,function(){return oe(this,function(s){switch(s.label){case 0:return[4,r.iterator()];case 1:return[2,s.sent().columnMajorBatch(t,e,RU)]}})})},a)},n.prototype.concatenate=function(t){var e=this,i=this,r;return this.size===Infinity||t.size===Infinity?r=Infinity:this.size!=null&&t.size!=null?r=this.size+t.size:r=null,jt(function(){return se(e,void 0,void 0,function(){var a,s;return oe(this,function(o){switch(o.label){case 0:return[4,i.iterator()];case 1:return s=(a=o.sent()).concatenate,[4,t.iterator()];case 2:return[2,s.apply(a,[o.sent()])]}})})},r)},n.prototype.filter=function(t){var e=this,i=this,r;return this.size===Infinity?r=Infinity:r=null,jt(function(){return se(e,void 0,void 0,function(){return oe(this,function(a){switch(a.label){case 0:return[4,i.iterator()];case 1:return[2,a.sent().filter(function(s){return Ne.tidy(function(){return t(s)})})]}})})},r)},n.prototype.forEachAsync=function(t){return se(this,void 0,void 0,function(){return oe(this,function(e){switch(e.label){case 0:return[4,this.iterator()];case 1:return[2,e.sent().forEachAsync(t)]}})})},n.prototype.map=function(t){var e=this,i=this;return jt(function(){return se(e,void 0,void 0,function(){return oe(this,function(r){switch(r.label){case 0:return[4,i.iterator()];case 1:return[2,r.sent().map(function(a){return Ne.tidy(function(){return t(a)})})]}})})},this.size)},n.prototype.mapAsync=function(t){var e=this,i=this;return jt(function(){return se(e,void 0,void 0,function(){return oe(this,function(r){switch(r.label){case 0:return[4,i.iterator()];case 1:return[2,r.sent().mapAsync(t)]}})})},this.size)},n.prototype.prefetch=function(t){var e=this;if(t==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");var i=this;return jt(function(){return se(e,void 0,void 0,function(){return oe(this,function(r){switch(r.label){case 0:return[4,i.iterator()];case 1:return[2,r.sent().prefetch(t)]}})})},this.size)},n.prototype.repeat=function(t){var e=this,i=this,r;return this.size!=null&&t>0?r=this.size*t:t===0?r=0:this.size!=null&&(t===void 0||t<0)?r=Infinity:r=null,jt(function(){return se(e,void 0,void 0,function(){var a,s=this;return oe(this,function(o){return a=ad(function(){return se(s,void 0,void 0,function(){var l;return oe(this,function(u){switch(u.label){case 0:return l={},[4,i.iterator()];case 1:return[2,(l.value=u.sent(),l.done=!1,l)]}})})}),[2,vU(a.take(t))]})})},r)},n.prototype.skip=function(t){var e=this,i=this,r;return this.size!=null&&t>=0&&this.size>=t?r=this.size-t:this.size!=null&&(this.sizet?r=t:this.size!=null&&this.size<=t?r=this.size:r=null,jt(function(){return se(e,void 0,void 0,function(){return oe(this,function(a){switch(a.label){case 0:return[4,i.iterator()];case 1:return[2,a.sent().take(t)]}})})},r)},n.prototype.toArray=function(){return se(this,void 0,void 0,function(){return oe(this,function(t){switch(t.label){case 0:if(this.size===Infinity)throw new Error("Can not convert infinite data stream to array.");return[4,this.iterator()];case 1:return[2,t.sent().toArray()]}})})},n.prototype.toArrayForTest=function(){return se(this,void 0,void 0,function(){return oe(this,function(t){switch(t.label){case 0:if(this.size===Infinity)throw new Error("Can not convert infinite data stream to array.");return[4,this.iterator()];case 1:return[2,t.sent().toArrayForTest()]}})})},n.MAX_BUFFER_SIZE=1e4,n}();function jt(n,t){return t===void 0&&(t=null),new(function(e){He(i,e);function i(){var r=e!==null&&e.apply(this,arguments)||this;return r.size=t,r}return i.prototype.iterator=function(){return se(this,void 0,void 0,function(){return oe(this,function(r){return[2,n()]})})},i}(Pa))}function OU(n){var t=this;return jt(function(){return se(t,void 0,void 0,function(){return oe(this,function(e){return[2,hw(n)]})})},n.length)}function EU(n){var t=this;if(!qr(n))throw new Error("The argument to zip() must be an object or array.");var e;if(Array.isArray(n))for(var i=0;i1}),Ne.util.assert(r.length===0,function(){return"Duplicate column names found: "+r.toString()}),this.columnConfigs){for(a=0,s=Object.keys(this.columnConfigs);a14||!Number.isInteger(r))throw new Error("Invalid fftSize: it must be a power of 2 between "+("2 to 4 and 2 to 14, but got "+i.fftSize));if(i.numFrames=e.numFramesPerSpectrogram||43,i.sampleRateHz=e.sampleRateHz,i.columnTruncateLength=e.columnTruncateLength||i.fftSize,i.audioTrackConstraints=e.audioTrackConstraints,i.smoothingTimeConstant=e.smoothingTimeConstant||0,i.includeSpectrogram=!(e.includeSpectrogram===!1),i.includeWaveform=e.includeWaveform===!0,!i.includeSpectrogram&&!i.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.");return i}return t.prototype.summary=function(){return"microphone"},t.create=function(e){return e===void 0&&(e={}),se(this,void 0,void 0,function(){var i;return oe(this,function(r){switch(r.label){case 0:if(Ne.env().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");return i=new t(e),[4,i.start()];case 1:return r.sent(),[2,i]}})})},t.prototype.start=function(){return se(this,void 0,void 0,function(){var e,i,r,a;return oe(this,function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),e=this,[4,navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null?!0:this.audioTrackConstraints,video:!1})];case 1:return e.stream=s.sent(),[3,3];case 2:throw i=s.sent(),new Error("Error thrown while initializing video stream: "+i.message);case 3:if(!this.stream)throw new Error("Could not obtain audio from microphone.");if(r=window.AudioContext||window.webkitAudioContext,this.audioContext=new r,!this.sampleRateHz)this.sampleRateHz=this.audioContext.sampleRate;else if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error("Mismatch in sampling rate: "+("Expected: "+this.sampleRateHz+"; ")+("Actual: "+this.audioContext.sampleRate));return a=this.audioContext.createMediaStreamSource(this.stream),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=this.fftSize*2,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,a.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize),[2]}})})},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e,i,r,a,s;return oe(this,function(o){switch(o.label){case 0:return this.isClosed?[2,{value:null,done:!0}]:[4,this.getAudioData()];case 1:return r=o.sent(),this.includeSpectrogram&&(a=this.flattenQueue(r.freqDataQueue),e=this.getTensorFromAudioDataArray(a,[this.numFrames,this.columnTruncateLength,1])),this.includeWaveform&&(s=this.flattenQueue(r.timeDataQueue),i=this.getTensorFromAudioDataArray(s,[this.numFrames*this.fftSize,1])),[2,{value:{spectrogram:e,waveform:i},done:!1}]}})})},t.prototype.capture=function(){return se(this,void 0,void 0,function(){return oe(this,function(e){switch(e.label){case 0:return[4,this.next()];case 1:return[2,e.sent().value]}})})},t.prototype.getAudioData=function(){return se(this,void 0,void 0,function(){var e,i,r,a=this;return oe(this,function(s){return e=[],i=[],r=0,[2,new Promise(function(o){var l=setInterval(function(){a.includeSpectrogram&&(a.analyser.getFloatFrequencyData(a.freqData),a.freqData[0]===-Infinity&&o({freqDataQueue:e,timeDataQueue:i}),e.push(a.freqData.slice(0,a.columnTruncateLength))),a.includeWaveform&&(a.analyser.getFloatTimeDomainData(a.timeData),i.push(a.timeData.slice())),++r===a.numFrames&&(clearInterval(l),o({freqDataQueue:e,timeDataQueue:i}))},a.fftSize/a.sampleRateHz*1e3)})]})})},t.prototype.stop=function(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),this.stream!=null&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())},t.prototype.toArray=function(){throw new Error("Can not convert infinite audio stream to array.")},t.prototype.getSampleRate=function(){return this.sampleRateHz},t.prototype.flattenQueue=function(e){var i=e[0].length,r=new Float32Array(e.length*i);return e.forEach(function(a,s){return r.set(a,s*i)}),r},t.prototype.getTensorFromAudioDataArray=function(e,i){var r=new Float32Array(Ne.util.sizeFromShape(i));return r.set(e,r.length-e.length),Ne.tensor(r,i)},t}(Nt);var FU=function(n){He(t,n);function t(e,i){var r=n.call(this)||this;if(r.webcamVideoElement=e,r.webcamConfig=i,r.isClosed=!0,r.resize=!1,r.needToResize())if(r.resize=!0,r.cropSize=[r.webcamConfig.resizeHeight,r.webcamConfig.resizeWidth],r.cropBoxInd=Ne.tensor1d([0],"int32"),r.webcamConfig.centerCrop){var a=r.webcamConfig.resizeWidth*1/r.webcamVideoElement.width,s=r.webcamConfig.resizeHeight*1/r.webcamVideoElement.height,o=(1-a)/2,l=(1-s)/2,u=o+a,c=s+l;r.cropBox=Ne.tensor2d([l,o,c,u],[1,4])}else r.cropBox=Ne.tensor2d([0,0,1,1],[1,4]);return r}return t.prototype.summary=function(){return"webcam"},t.create=function(e,i){return i===void 0&&(i={}),se(this,void 0,void 0,function(){var r;return oe(this,function(a){switch(a.label){case 0:if(Ne.env().get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!i.resizeWidth||!i.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=i.resizeWidth,e.height=i.resizeHeight}return r=new t(e,i),[4,r.start()];case 1:return a.sent(),[2,r]}})})},t.prototype.start=function(){return se(this,void 0,void 0,function(){var e,i,r=this;return oe(this,function(a){switch(a.label){case 0:this.webcamConfig.facingMode&&Ne.util.assert(this.webcamConfig.facingMode==="user"||this.webcamConfig.facingMode==="environment",function(){return"Invalid webcam facing mode: "+r.webcamConfig.facingMode+". Please provide 'user' or 'environment'"}),a.label=1;case 1:return a.trys.push([1,3,,4]),e=this,[4,navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})];case 2:return e.stream=a.sent(),[3,4];case 3:throw i=a.sent(),i.message="Error thrown while initializing video stream: "+i.message,i;case 4:if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(s){console.log(s),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,[2,new Promise(function(s){r.webcamVideoElement.onloadedmetadata=function(){s()}})]}})})},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e;return oe(this,function(i){if(this.isClosed)return[2,{value:null,done:!0}];try{e=Ne.browser.fromPixels(this.webcamVideoElement)}catch(r){throw new Error("Error thrown converting video to pixels: "+JSON.stringify(r))}if(this.resize)try{return[2,{value:this.cropAndResizeFrame(e),done:!1}]}catch(r){throw new Error("Error thrown cropping the video: "+r.message)}finally{e.dispose()}else return[2,{value:e,done:!1}];return[2]})})},t.prototype.needToResize=function(){return!!(this.webcamConfig.resizeWidth&&this.webcamConfig.resizeHeight&&(this.webcamVideoElement.width!==this.webcamConfig.resizeWidth||this.webcamVideoElement.height!==this.webcamConfig.resizeHeight))},t.prototype.cropAndResizeFrame=function(e){var i=this;return Ne.tidy(function(){var r=e.toFloat().expandDims(0),a;a=Ne.image.cropAndResize(r,i.cropBox,i.cropBoxInd,i.cropSize,"bilinear");var s=a.shape;return a.reshape(s.slice(1))})},t.prototype.capture=function(){return se(this,void 0,void 0,function(){return oe(this,function(e){switch(e.label){case 0:return[4,this.next()];case 1:return[2,e.sent().value]}})})},t.prototype.stop=function(){var e=this.stream.getTracks();e.forEach(function(i){return i.stop()});try{this.webcamVideoElement.srcObject=null}catch(i){console.log(i),this.webcamVideoElement.src=null}this.isClosed=!0},t.prototype.toArray=function(){throw new Error("Can not convert infinite video stream to array.")},t}(Nt);var bw=function(){function n(){}return n}();var ww=function(n){He(t,n);function t(){return n!==null&&n.apply(this,arguments)||this}return t.prototype.split=function(e){return new WU(this,e)},t}(Nt),WU=function(n){He(t,n);function t(e,i){var r=n.call(this)||this;return r.upstream=e,r.impl=new UU(e,i),r}return t.prototype.summary=function(){return this.impl.summary()},t.prototype.next=function(){return se(this,void 0,void 0,function(){return oe(this,function(e){return[2,this.impl.next()]})})},t}(ww),UU=function(n){He(t,n);function t(e,i){var r=n.call(this)||this;return r.upstream=e,r.separator=i,r.carryover="",r}return t.prototype.summary=function(){return this.upstream.summary()+" -> Split('"+this.separator+"')"},t.prototype.pump=function(){return se(this,void 0,void 0,function(){var e,i,r,a,s;return oe(this,function(o){switch(o.label){case 0:return[4,this.upstream.next()];case 1:if(e=o.sent(),e.done)return this.carryover===""?[2,!1]:(this.outputQueue.push(this.carryover),this.carryover="",[2,!0]);for(i=e.value.split(this.separator),i[0]=this.carryover+i[0],r=0,a=i.slice(0,-1);r Utf8"},t.prototype.pump=function(){return se(this,void 0,void 0,function(){var e,i,r;return oe(this,function(a){switch(a.label){case 0:return[4,this.upstream.next()];case 1:return e=a.sent(),e.done?[2,!1]:(i=e.value,Ne.env().get("IS_BROWSER")?r=this.decoder.decode(i,{stream:!0}):r=this.decoder.write(Buffer.from(i.buffer)),this.outputQueue.push(r),[2,!0])}})})},t}(sd);var Sw=function(n){He(t,n);function t(e,i){i===void 0&&(i={});var r=n.call(this)||this;return r.file=e,r.options=i,Ne.util.assert(e instanceof Uint8Array||(Ne.env().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),function(){return"FileChunkIterator only supports File, Blob and Uint8Array right now."}),r.offset=i.offset||0,r.chunkSize=i.chunkSize||1024*1024,r}return t.prototype.summary=function(){return"FileChunks "+this.file},t.prototype.next=function(){return se(this,void 0,void 0,function(){var e,i,r=this;return oe(this,function(a){switch(a.label){case 0:return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?[2,{value:null,done:!0}]:(e=new Promise(function(s,o){var l=r.offset+r.chunkSize;if(r.file instanceof Uint8Array)s(new Uint8Array(r.file.slice(r.offset,l)));else{var u=new FileReader;u.onload=function(h){var d=u.result;if(d instanceof ArrayBuffer&&(d=new Uint8Array(d)),!(d instanceof Uint8Array))return o(new TypeError("FileReader returned unknown type."));s(d)},u.onabort=function(h){return o(new Error("Aborted"))},u.onerror=function(h){return o(new Error(h.type))};var c=r.file.slice(r.offset,l);u.readAsArrayBuffer(c)}r.offset=l}),i={},[4,e]);case 1:return[2,(i.value=a.sent(),i.done=!1,i)]}})})},t}(zU);function MU(n,t){return t===void 0&&(t={}),se(this,void 0,void 0,function(){var e,i,r,a,s;return oe(this,function(o){switch(o.label){case 0:return typeof n=="string"?e=n:(e=n.url,i=PU(n)),[4,Ne.util.fetch(e,i)];case 1:return r=o.sent(),r.ok?(s=Uint8Array.bind,[4,r.arrayBuffer()]):[3,3];case 2:return a=new(s.apply(Uint8Array,[void 0,o.sent()])),[2,new Sw(a,t)];case 3:throw new Error(r.statusText)}})})}var PU=function(n){var t={method:n.method,headers:n.headers,body:n.body,mode:n.mode,credentials:n.credentials,cache:n.cache,redirect:n.redirect,referrer:n.referrer,integrity:n.integrity};return t};function Lw(n){return typeof n=="string"&&n.substr(0,7)==="file://"}var Iw=function(n){He(t,n);function t(e,i){i===void 0&&(i={});var r=n.call(this)||this;return r.input=e,r.options=i,r}return t.prototype.iterator=function(){return se(this,void 0,void 0,function(){var e;return oe(this,function(i){return Lw(this.input)&&Ne.env().get("IS_NODE")&&(e=require("fs"),this.input=e.readFileSync(this.input.substr(7))),[2,new Sw(this.input,this.options)]})})},t}(bw);var Aw=function(n){He(t,n);function t(e,i){i===void 0&&(i={});var r=n.call(this)||this;return r.url=e,r.fileOptions=i,r}return t.prototype.iterator=function(){return se(this,void 0,void 0,function(){return oe(this,function(e){return Lw(this.url)?[2,new Iw(this.url,this.fileOptions).iterator()]:[2,MU(this.url,this.fileOptions)]})})},t}(bw);function HU(n,t){return t===void 0&&(t={}),new yw(new Aw(n),t)}function VU(n){var t=this,e=ad(n);return jt(function(){return se(t,void 0,void 0,function(){return oe(this,function(i){return[2,e]})})})}function qU(n){var t=this;return jt(function(){return se(t,void 0,void 0,function(){var e;return oe(this,function(i){switch(i.label){case 0:return[4,n()];case 1:return e=i.sent(),[2,ad(function(){return e.next()})]}})})})}function GU(n,t){return se(this,void 0,void 0,function(){return oe(this,function(e){return[2,FU.create(n,t)]})})}function YU(n){return se(this,void 0,void 0,function(){return oe(this,function(t){return[2,kU.create(n)]})})}var KU="2.6.0";Mt.CSVDataset=yw;Mt.Dataset=Pa;Mt.FileDataSource=Iw;Mt.TextLineDataset=mw;Mt.URLDataSource=Aw;Mt.array=OU;Mt.csv=HU;Mt.func=VU;Mt.generator=qU;Mt.microphone=YU;Mt.version_data=KU;Mt.webcam=GU;Mt.zip=EU});var xw=be((Nw,ld)=>{(function(n,t,e){function i(o){var l=this,u=s();l.next=function(){var c=2091639*l.s0+l.c*23283064365386963e-26;return l.s0=l.s1,l.s1=l.s2,l.s2=c-(l.c=c|0)},l.c=1,l.s0=u(" "),l.s1=u(" "),l.s2=u(" "),l.s0-=u(o),l.s0<0&&(l.s0+=1),l.s1-=u(o),l.s1<0&&(l.s1+=1),l.s2-=u(o),l.s2<0&&(l.s2+=1),u=null}function r(o,l){return l.c=o.c,l.s0=o.s0,l.s1=o.s1,l.s2=o.s2,l}function a(o,l){var u=new i(o),c=l&&l.state,h=u.next;return h.int32=function(){return u.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,c&&(typeof c=="object"&&r(c,u),h.state=function(){return r(u,{})}),h}function s(){var o=4022871197,l=function(u){u=u.toString();for(var c=0;c>>0,h-=o,h*=o,o=h>>>0,h-=o,o+=h*4294967296}return(o>>>0)*23283064365386963e-26};return l}t&&t.exports?t.exports=a:e&&e.amd?e(function(){return a}):this.alea=a})(Nw,typeof ld=="object"&&ld,typeof define=="function"&&define)});var Rw=be((Cw,ud)=>{(function(n,t,e){function i(s){var o=this,l="";o.x=0,o.y=0,o.z=0,o.w=0,o.next=function(){var c=o.x^o.x<<11;return o.x=o.y,o.y=o.z,o.z=o.w,o.w^=o.w>>>19^c^c>>>8},s===(s|0)?o.x=s:l+=s;for(var u=0;u>>0)/4294967296};return c.double=function(){do var h=l.next()>>>11,d=(l.next()>>>0)/4294967296,p=(h+d)/(1<<21);while(p===0);return p},c.int32=l.next,c.quick=c,u&&(typeof u=="object"&&r(u,l),c.state=function(){return r(l,{})}),c}t&&t.exports?t.exports=a:e&&e.amd?e(function(){return a}):this.xor128=a})(Cw,typeof ud=="object"&&ud,typeof define=="function"&&define)});var Ew=be((Ow,cd)=>{(function(n,t,e){function i(s){var o=this,l="";o.next=function(){var c=o.x^o.x>>>2;return o.x=o.y,o.y=o.z,o.z=o.w,o.w=o.v,(o.d=o.d+362437|0)+(o.v=o.v^o.v<<4^(c^c<<1))|0},o.x=0,o.y=0,o.z=0,o.w=0,o.v=0,s===(s|0)?o.x=s:l+=s;for(var u=0;u>>4),o.next()}function r(s,o){return o.x=s.x,o.y=s.y,o.z=s.z,o.w=s.w,o.v=s.v,o.d=s.d,o}function a(s,o){var l=new i(s),u=o&&o.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var h=l.next()>>>11,d=(l.next()>>>0)/4294967296,p=(h+d)/(1<<21);while(p===0);return p},c.int32=l.next,c.quick=c,u&&(typeof u=="object"&&r(u,l),c.state=function(){return r(l,{})}),c}t&&t.exports?t.exports=a:e&&e.amd?e(function(){return a}):this.xorwow=a})(Ow,typeof cd=="object"&&cd,typeof define=="function"&&define)});var kw=be((Dw,hd)=>{(function(n,t,e){function i(s){var o=this;o.next=function(){var u=o.x,c=o.i,h,d,p;return h=u[c],h^=h>>>7,d=h^h<<24,h=u[c+1&7],d^=h^h>>>10,h=u[c+3&7],d^=h^h>>>3,h=u[c+4&7],d^=h^h<<7,h=u[c+7&7],h=h^h<<13,d^=h^h<<9,u[c]=d,o.i=c+1&7,d};function l(u,c){var h,d,p=[];if(c===(c|0))d=p[0]=c;else for(c=""+c,h=0;h0;--h)u.next()}l(o,s)}function r(s,o){return o.x=s.x.slice(),o.i=s.i,o}function a(s,o){s==null&&(s=+new Date);var l=new i(s),u=o&&o.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var h=l.next()>>>11,d=(l.next()>>>0)/4294967296,p=(h+d)/(1<<21);while(p===0);return p},c.int32=l.next,c.quick=c,u&&(u.x&&r(u,l),c.state=function(){return r(l,{})}),c}t&&t.exports?t.exports=a:e&&e.amd?e(function(){return a}):this.xorshift7=a})(Dw,typeof hd=="object"&&hd,typeof define=="function"&&define)});var Ww=be((Fw,dd)=>{(function(n,t,e){function i(s){var o=this;o.next=function(){var u=o.w,c=o.X,h=o.i,d,p;return o.w=u=u+1640531527|0,p=c[h+34&127],d=c[h=h+1&127],p^=p<<13,d^=d<<17,p^=p>>>15,d^=d>>>12,p=c[h]=p^d,o.i=h,p+(u^u>>>16)|0};function l(u,c){var h,d,p,f,m,g=[],v=128;for(c===(c|0)?(d=c,c=null):(c=c+"\0",d=0,v=Math.max(v,c.length)),p=0,f=-32;f>>15,d^=d<<4,d^=d>>>13,f>=0&&(m=m+1640531527|0,h=g[f&127]^=d+m,p=h==0?p+1:0);for(p>=128&&(g[(c&&c.length||0)&127]=-1),p=127,f=4*128;f>0;--f)d=g[p+34&127],h=g[p=p+1&127],d^=d<<13,h^=h<<17,d^=d>>>15,h^=h>>>12,g[p]=d^h;u.w=m,u.X=g,u.i=p}l(o,s)}function r(s,o){return o.i=s.i,o.w=s.w,o.X=s.X.slice(),o}function a(s,o){s==null&&(s=+new Date);var l=new i(s),u=o&&o.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var h=l.next()>>>11,d=(l.next()>>>0)/4294967296,p=(h+d)/(1<<21);while(p===0);return p},c.int32=l.next,c.quick=c,u&&(u.X&&r(u,l),c.state=function(){return r(l,{})}),c}t&&t.exports?t.exports=a:e&&e.amd?e(function(){return a}):this.xor4096=a})(Fw,typeof dd=="object"&&dd,typeof define=="function"&&define)});var Bw=be((Uw,pd)=>{(function(n,t,e){function i(s){var o=this,l="";o.next=function(){var c=o.b,h=o.c,d=o.d,p=o.a;return c=c<<25^c>>>7^h,h=h-d|0,d=d<<24^d>>>8^p,p=p-c|0,o.b=c=c<<20^c>>>12^h,o.c=h=h-d|0,o.d=d<<16^h>>>16^p,o.a=p-c|0},o.a=0,o.b=0,o.c=2654435769|0,o.d=1367130551,s===Math.floor(s)?(o.a=s/4294967296|0,o.b=s|0):l+=s;for(var u=0;u>>0)/4294967296};return c.double=function(){do var h=l.next()>>>11,d=(l.next()>>>0)/4294967296,p=(h+d)/(1<<21);while(p===0);return p},c.int32=l.next,c.quick=c,u&&(typeof u=="object"&&r(u,l),c.state=function(){return r(l,{})}),c}t&&t.exports?t.exports=a:e&&e.amd?e(function(){return a}):this.tychei=a})(Uw,typeof pd=="object"&&pd,typeof define=="function"&&define)});var zw=be((IH,Ao)=>{(function(n,t){var e=this,i=256,r=6,a=52,s="random",o=t.pow(i,r),l=t.pow(2,a),u=l*2,c=i-1,h;function d(S,L,w){var N=[];L=L==!0?{entropy:!0}:L||{};var I=g(m(L.entropy?[S,b(n)]:S??v(),3),N),C=new p(N),E=function(){for(var k=C.g(r),W=o,F=0;k=u;)k/=2,W/=2,F>>>=1;return(k+F)/W};return E.int32=function(){return C.g(4)|0},E.quick=function(){return C.g(4)/4294967296},E.double=E,g(b(C.S),n),(L.pass||w||function(k,W,F,_){return _&&(_.S&&f(_,C),k.state=function(){return f(C,{})}),F?(t[s]=k,W):k})(E,I,"global"in L?L.global:this==t,L.state)}t["seed"+s]=d;function p(S){var L,w=S.length,N=this,I=0,C=N.i=N.j=0,E=N.S=[];for(w||(S=[w++]);I{var jU=xw(),$U=Rw(),XU=Ew(),JU=kw(),ZU=Ww(),QU=Bw(),rr=zw();rr.alea=jU;rr.xor128=$U;rr.xorwow=XU;rr.xorshift7=JU;rr.xor4096=ZU;rr.tychei=QU;_w.exports=rr});var d0=be(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});var x=Ki(),eB=Pw();var fd=function(n,t){return fd=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,i){e.__proto__=i}||function(e,i){for(var r in i)i.hasOwnProperty(r)&&(e[r]=i[r])},fd(n,t)};function tB(n,t){fd(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function Mw(n,t,e,i){function r(a){return a instanceof e?a:new e(function(s){s(a)})}return new(e||(e=Promise))(function(a,s){function o(c){try{u(i.next(c))}catch(h){s(h)}}function l(c){try{u(i.throw(c))}catch(h){s(h)}}function u(c){c.done?a(c.value):r(c.value).then(o,l)}u((i=i.apply(n,t||[])).next())})}function Hw(n,t){var e={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,r,a,s;return s={next:o(0),throw:o(1),return:o(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function o(u){return function(c){return l([u,c])}}function l(u){if(i)throw new TypeError("Generator is already executing.");for(;e;)try{if(i=1,r&&(a=u[0]&2?r.return:u[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,u[1])).done)return a;(r=0,a)&&(u=[u[0]&2,a.value]);switch(u[0]){case 0:case 1:a=u;break;case 4:return e.label++,{value:u[1],done:!1};case 5:e.label++,r=u[1],u=[0];continue;case 7:u=e.ops.pop(),e.trys.pop();continue;default:if(!(a=e.trys,a=a.length>0&&a[a.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!a||u[1]>a[0]&&u[1]f&&(f=v,m=g)}c[d]=m}return l},t.prototype.cumsum=function(e,i,r,a){if(ae(e,"cumsum"),i!==e.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(e.rank-1)+" "+("but got axis="+i));for(var s=x.upcastType(e.dtype,"int32"),o=x.zeros(e.shape,s),l=this.readSync(o.dataId),u=this.readSync(e.dataId),c=e.shape[e.rank-1],h=a?function(g,v){return g+c-v-1}:function(g,v){return g+v},d=0;da?1:0})},t.prototype.greaterEqual=function(e,i){return ae([e,i],"greaterEqual"),this.broadcastedBinaryOp(e,i,"bool",function(r,a){return r>=a?1:0})},t.prototype.logicalAnd=function(e,i){return ae([e,i],"logicalAnd"),this.broadcastedBinaryOp(e,i,"bool",function(r,a){return r&&a})},t.prototype.logicalOr=function(e,i){return ae([e,i],"logicalOr"),this.broadcastedBinaryOp(e,i,"bool",function(r,a){return r||a})},t.prototype.select=function(e,i,r){ae([e,i,r],"select");for(var a=this.readSync(e.dataId),s=this.readSync(i.dataId),o=this.readSync(r.dataId),l=x.zeros(i.shape,x.upcastType(i.dtype,r.dtype)),u=this.readSync(l.dataId),c=0,h=e.rank===0||e.rank>1||i.rank===1?1:x.util.sizeFromShape(i.shape.slice(1)),d=0;d=0&&a>=0?s:(s+a)%a})},t.prototype.maximum=function(e,i){return ae([e,i],"maximum"),this.broadcastedBinaryOp(e,i,e.dtype,function(r,a){return Math.max(r,a)})},t.prototype.all=function(e,i){ae(e,"all"),x.backend_util.assertAxesAreInnerMostDims("all",i,e.rank);for(var r=x.backend_util.computeOutAndReduceShapes(e.shape,i),a=r[0],s=r[1],o=x.zeros(a,e.dtype),l=x.util.sizeFromShape(s),u=this.readSync(o.dataId),c=this.readSync(e.dataId),h=0;h=1?r[o]=s[o]:r[o]=s[o]*(l+1)}return this.makeOutput(r,i.shape,"float32")},t.prototype.atan2=function(e,i){return ae([e,i],"atan2"),this.broadcastedBinaryOp(e,i,e.dtype,function(r,a){return Math.atan2(r,a)})},t.prototype.fusedConv2d=function(e){var i=e.input,r=e.filter,a=e.convInfo,s=e.bias,o=e.activation,l=e.preluActivationWeights,u=this.conv2d(i,r,a);return s&&(u=x.add(u,s)),o&&(u=md(this,u,o,l)),u},t.prototype.conv2d=function(e,i,r){ae([e,i],"conv2d");for(var a=r.filterHeight,s=r.filterWidth,o=r.dilationHeight,l=r.dilationWidth,u=r.padInfo.left,c=r.padInfo.top,h=r.dataFormat==="channelsLast",d=x.buffer(r.outShape,e.dtype),p=e.strides[0],f=h?e.strides[1]:e.strides[2],m=h?e.strides[2]:1,g=h?1:e.strides[1],v=d.strides[0],b=h?d.strides[1]:d.strides[2],S=h?d.strides[2]:1,L=h?1:d.strides[1],w=this.readSync(e.dataId),N=this.readSync(i.dataId),I=d.values,C=0;C=r.inHeight)continue;for(var K=H*i.strides[0],j=E+P*f,q=0;q=r.inWidth)continue;for(var ne=K+X*i.strides[1],ie=j+ee*m,te=ne,re=0;re=r.inDepth)continue;for(var k=C*i.strides[0],W=S+E*e.strides[1],F=0;F=r.inHeight)continue;for(var j=k+P*i.strides[1],q=W+K*e.strides[2],G=0;G=r.inWidth)continue;for(var ie=j+ee*i.strides[2],te=q+ne*r.inChannels,re=ie,le=0;le=r.inHeight)continue;for(var C=N*i.strides[0],E=v+I*e.strides[1],k=0;k=r.inWidth)continue;for(var P=C+_*i.strides[1],K=E+H*r.inChannels,j=W,q=P,G=0;Ghe?he=We:r==="avg"&&(ye+=We,Oe++),isNaN(he))break}if(isNaN(he))break}if(isNaN(he))break}var me=le+F;L[me]=r==="avg"?ye/Oe:he}}}return S.toTensor()},t.prototype.avgPool3d=function(e,i){return ae(e,"avgPool3d"),this.pool3d(e,i,"avg").toFloat()},t.prototype.avgPool3dBackprop=function(e,i,r){ae([e,i],"avgPool3dBackprop");for(var a=r.strideDepth,s=r.strideHeight,o=r.strideWidth,l=r.filterDepth,u=r.filterHeight,c=r.filterWidth,h=r.dilationDepth,d=r.dilationHeight,p=r.dilationWidth,f=r.effectiveFilterDepth,m=r.effectiveFilterHeight,g=r.effectiveFilterWidth,v=f-1-r.padInfo.front,b=g-1-r.padInfo.left,S=m-1-r.padInfo.top,L=x.buffer(i.shape,"float32"),w=1/(l*u*c),N=this.bufferSync(e),I=0;I=r.outDepth||Math.floor(j)!==j)continue;for(var q=0;q=r.outHeight||Math.floor(G)!==G)continue;for(var Z=0;Z=r.outWidth||Math.floor(X)!==X)continue;var ee=N.get(I,j,G,X,C);P+=ee}}}L.set(P*w,I,E,k,W,C)}return L.toTensor()},t.prototype.maxPool3d=function(e,i){return ae(e,"maxPool3d"),this.pool3d(e,i,"max").toFloat()},t.prototype.maxPool3dPositions=function(e,i){for(var r=x.buffer(i.outShape,"int32"),a=i.strideDepth,s=i.strideHeight,o=i.strideWidth,l=i.dilationDepth,u=i.dilationHeight,c=i.dilationWidth,h=i.effectiveFilterDepth,d=i.effectiveFilterHeight,p=i.effectiveFilterWidth,f=i.padInfo.front,m=i.padInfo.top,g=i.padInfo.left,v=this.bufferSync(e),b=0;b=K&&(K=ie,j=G*d*p+X*d+ne)}r.set(j,b,L,C,F,S)}}}return r.toTensor()},t.prototype.maxPool3dBackprop=function(e,i,r,a){ae([i,r],"maxPool3dBackprop");for(var s=this.maxPool3dPositions(i,a),o=a.strideDepth,l=a.strideHeight,u=a.strideWidth,c=a.dilationDepth,h=a.dilationHeight,d=a.dilationWidth,p=a.effectiveFilterDepth,f=a.effectiveFilterHeight,m=a.effectiveFilterWidth,g=p-1-a.padInfo.front,v=m-1-a.padInfo.left,b=f-1-a.padInfo.top,S=x.buffer(i.shape,"float32"),L=this.bufferSync(s),w=this.bufferSync(e),N=0;N=a.outDepth||Math.floor(K)!==K)continue;for(var j=0;j=a.outHeight||Math.floor(q)!==q)continue;for(var G=0;G=a.outWidth||Math.floor(Z)!==Z)continue;var X=p*f*m-1-L.get(N,K,q,Z,I),ee=P*f*m+j*m+G,ne=X===ee?1:0;if(ne===0)continue;var ie=w.get(N,K,q,Z,I);H+=ie*ne}}}S.set(H,N,C,E,k,I)}return S.toTensor()},t.prototype.resizeBilinear=function(e,i,r,a){ae(e,"resizeBilinear");for(var s=e.shape,o=s[0],l=s[1],u=s[2],c=s[3],h=this.readSync(e.dataId),d=new Float32Array(x.util.sizeFromShape([o,i,r,c])),p=[a&&i>1?l-1:l,a&&r>1?u-1:u],f=[a&&i>1?i-1:i,a&&r>1?r-1:r],m=0,g=p[0]/f[0],v=p[1]/f[1],b=0;b1?o-1:o,r&&d>1?l-1:l],m=[r&&h>1?h-1:h,r&&d>1?d-1:d],g=f[0]/m[0],v=f[1]/m[1],b=this.readSync(e.dataId),S=0,L=0;L1?l-1:l,a&&r>1?u-1:u],f=[a&&i>1?i-1:i,a&&r>1?r-1:r],m=p[0]/f[0],g=p[1]/f[1],v=0,b=0;b1?o-1:o,r&&d>1?l-1:l],g=[r&&h>1?h-1:h,r&&d>1?d-1:d],v=m[0]/g[0],b=m[1]/g[1],S=1/v,L=1/b,w=Math.ceil(S)*2+2,N=Math.ceil(L)*2+2,I=0;I=h)continue;var X=C+Z*e.strides[1],ee=Z*v,ne=Math.min(o-1,r?Math.round(ee):Math.floor(ee));if(E!==ne)continue;for(var ie=0;ie=d)continue;var re=X+te*e.strides[2],le=te*b,he=Math.min(l-1,r?Math.round(le):Math.floor(le));_===he&&(q+=f[re+j])}}p[H+j]=q}return x.tensor4d(p,i.shape,i.dtype)},t.prototype.localResponseNormalization4D=function(e,i,r,a,s){ae(e,"localResponseNormalization4D");var o=e.shape[3],l=o-1,u=this.readSync(e.dataId),c=e.size,h=new Float32Array(c);function d(g){for(var v=g%o,b=g-v+Math.max(0,v-i),S=g-v+Math.min(v+i,l),L=0;b<=S;b++){var w=u[b];L+=w*w}return L}for(var p=0;p=0&&o[l]1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+i});for(var a=e.shape[0],s=e.shape[1],o=e.shape[2],l=e.shape[3],u=s*i,c=o*i,h=l/(i*i),d=this.readSync(e.dataId),p=new Float32Array(a*u*c*h),f=0,m=0;m=u)continue;for(var _=f>1?(k-C)*(c-1)/(f-1):0,H=m>1?(W-E)*(h-1)/(m-1):0,P=0;P1?C*(c-1)+P*_:.5*(C+k)*(c-1);if(K<0||K>c-1){for(var j=0;j1?E*(h-1)+j*H:.5*(E+W)*(h-1);if(ne<0||ne>h-1){for(var q=0;q1?E*(h-1)+j*H:.5*(E+W)*(h-1);if(ne<0||ne>h-1){for(var q=0;q=e.size/u)throw new Error("Invalid indices: "+m+" does not index into "+e.shape);for(var S=0;S=a/s)throw new Error("Invalid indices: "+v+" does not index into "+r);for(var w=0;wo&&(o=u)}r[a]=o}return r}var Qw=ar(function(n,t){return n*t}),AB=gd(function(n,t,e,i){return{real:n*e-t*i,imag:n*i+t*e}}),e0=Yr(x.Multiply,Qw,AB),TB={kernelName:x.Multiply,backendName:"cpu",kernelFunc:e0};var t0=Kr(function(n){return 1/Math.sqrt(n)}),NB=jr(x.Rsqrt,t0),xB={kernelName:x.Rsqrt,backendName:"cpu",kernelFunc:NB};function n0(n,t,e,i,r){var a=x.slice_util.isSliceContinous(i,t,e),s=x.util.sizeFromShape(e),o=x.util.computeStrides(i);if(a){var l=x.slice_util.computeFlatOffset(t,o);return n.subarray(l,l+s)}for(var u=x.util.getTypedArrayFromDType(r,s),c=0;cj?j=ie:a==="avg"&&(q+=ie,G++)}if(isNaN(j))break}var te=F+_*S+I;g[te]=a==="avg"?q/G:j}return m}function s0(n,t,e,i,r,a){r===void 0&&(r=!1),a===void 0&&(a=!1);for(var s=x.buffer(i.outShape,"int32"),o=i.strideHeight,l=i.strideWidth,u=i.dilationHeight,c=i.dilationWidth,h=i.effectiveFilterHeight,d=i.effectiveFilterWidth,p=i.padInfo.top,f=i.padInfo.left,m=x.buffer(t,e,n),g=0;gk&&(k=K,r?W=a?((g*i.inHeight+F)*i.inWidth+H)*i.inChannels+v:(F*i.inWidth+H)*i.inChannels+v:W=_*d+P)}s.set(W,g,b,N,v)}}return s}function GB(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.x;ae(r,"avgPool");var a=i.filterSize,s=i.strides,o=i.pad,l=i.dimRoundingMode,u=1;x.util.assert(x.backend_util.eitherStridesOrDilationsAreOne(s,u),function(){return"Error in avgPool: Either strides or dilations must be 1. "+("Got strides "+s+" and dilations '"+u+"'")});var c=x.backend_util.computePool2DInfo(r.shape,a,s,u,o,l),h;if(c.filterWidth===1&&c.filterHeight===1&&x.util.arraysEqual(c.inShape,c.outShape))h=Gr({inputs:{x:r},backend:e});else{var d=e.data.get(r.dataId).values,p=x.util.computeStrides(r.shape),f=bd(d,r.shape,r.dtype,p,c,"avg");h=e.makeTensorInfo(c.outShape,r.dtype,f.values)}return h}var YB={kernelName:x.AvgPool,backendName:"cpu",kernelFunc:GB};function KB(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.dy,a=t.input,s=a;ae([r,a],"avgPoolBackprop");for(var o=i.filterSize,l=i.strides,u=i.pad,c=x.backend_util.computePool2DInfo(s.shape,o,l,1,u),h=c.strideHeight,d=c.strideWidth,p=c.filterHeight,f=c.filterWidth,m=c.dilationHeight,g=c.dilationWidth,v=c.effectiveFilterHeight,b=c.effectiveFilterWidth,S=b-1-c.padInfo.left,L=v-1-c.padInfo.top,w=x.buffer(s.shape,"float32"),N=1/(p*f),I=e.data.get(r.dataId).values,C=x.buffer(r.shape,"float32",I),E=0;E=c.outHeight||Math.floor(j)!==j)continue;for(var q=0;q=c.outWidth||Math.floor(G)!==G)continue;var Z=C.get(E,j,G,k);P+=Z}}w.set(P*N,E,W,F,k)}return e.makeTensorInfo(w.shape,w.dtype,w.values)}var jB={kernelName:x.AvgPoolBackprop,backendName:"cpu",kernelFunc:KB};function $B(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.x,a=t.scale,s=t.offset,o=t.mean,l=t.variance;x.util.assert(o.shape.length===l.shape.length,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),x.util.assert(s==null||o.shape.length===s.shape.length,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),x.util.assert(a==null||o.shape.length===a.shape.length,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}),ae([r,o,l,a,s],"batchNorm");var u=i.varianceEpsilon;u==null&&(u=.001);for(var c=e.data.get(r.dataId).values,h=e.data.get(o.dataId).values,d=e.data.get(l.dataId).values,p=a?e.data.get(a.dataId).values:new Float32Array([1]),f=s?e.data.get(s.dataId).values:new Float32Array([0]),m=new Float32Array(c.length),g=f.length,v=p.length,b=d.length,S=h.length,L=0,w=0,N=0,I=0,C=0;C=g&&(L=0),w>=S&&(w=0),N>=v&&(N=0),I>=b&&(I=0);return e.makeTensorInfo(r.shape,r.dtype,m)}var XB={kernelName:x.FusedBatchNorm,backendName:"cpu",kernelFunc:$B};var JB=Ke(x.ClipByValue,function(n,t){var e=t;return n>e.clipValueMax?e.clipValueMax:n0});if(o.length===1)return o[0];var l=o.map(function(L){return L.shape});if(x.backend_util.assertParamsConsistent(l,a),o[0].dtype==="complex64"){var u=o.map(function(L){return Va({inputs:{input:L},backend:e})}),c=o.map(function(L){return To({inputs:{input:L},backend:e})}),h=Ga({inputs:u,backend:e,attrs:{axis:r}}),d=Ga({inputs:c,backend:e,attrs:{axis:r}}),p=bn({inputs:{real:h,imag:d},backend:e});return u.forEach(function(L){return e.disposeIntermediateTensorInfo(L)}),c.forEach(function(L){return e.disposeIntermediateTensorInfo(L)}),e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(d),p}var f=o.map(function(L){var w=x.util.sizeFromShape(L.shape.slice(a)),N=[-1,w];return wi({inputs:{x:L},backend:e,attrs:{shape:N}})});s=x.backend_util.computeOutShape(f.map(function(L){return L.shape}),1);var m=x.util.getTypedArrayFromDType(o[0].dtype,x.util.sizeFromShape(s));if(f[0].shape[0]===1){var g=0;f.forEach(function(L){var w=e.data.get(L.dataId).values,N=x.util.sizeFromShape(L.shape);m.set(w,g),g+=N})}else{var v=0;f.forEach(function(L){for(var w=e.data.get(L.dataId).values,N=0,I=0;I=0&&re=0&&heie&&(ie=ke)}}}var _e=x.util.locToIndex([q,G,X,ne],K,x.util.computeStrides(H));j[_e]=ie}var Pe=h.write(x.util.toTypedArray(j,a.dtype),H,a.dtype);return{dataId:Pe,shape:H,dtype:a.dtype}}};var oz={kernelName:x.Dilation2DBackpropFilter,backendName:"cpu",kernelFunc:function(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t,a=r.x,s=r.filter,o=r.dy,l=i,u=l.strides,c=l.pad,h=l.dilations,d=e,p=x.util.toNestedArray(a.shape,d.data.get(a.dataId).values),f=x.util.toNestedArray(s.shape,d.data.get(s.dataId).values),m=x.backend_util.computeDilation2DInfo(a.shape,s.shape,u,c,"NHWC",h),g=m.batchSize,v=m.inHeight,b=m.inWidth,S=m.inChannels,L=m.outHeight,w=m.outWidth,N=m.padInfo,I=m.strideHeight,C=m.strideWidth,E=m.filterHeight,k=m.filterWidth,W=m.dilationHeight,F=m.dilationWidth,_=m.outShape;x.util.assert(o.rank===_.length,function(){return"Error in "+x.Dilation2DBackpropFilter+", dy "+("must have the same rank as output "+_.length+", but got ")+(""+o.rank)});for(var H=x.util.toNestedArray(_,d.data.get(o.dataId).values),P=x.util.makeZerosNestedTypedArray(s.shape,s.dtype),K=0;K=0&&re=0&&heee&&(ee=ye,ne=te,ie=le)}}}P[ne][ie][X]+=H[K][j][G][X]}var Oe=d.write(x.util.toTypedArray(P,a.dtype),s.shape,s.dtype);return{dataId:Oe,shape:s.shape,dtype:s.dtype}}};var lz={kernelName:x.Dilation2DBackpropInput,backendName:"cpu",kernelFunc:function(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t,a=r.x,s=r.filter,o=r.dy,l=i,u=l.strides,c=l.pad,h=l.dilations,d=e,p=x.util.toNestedArray(a.shape,d.data.get(a.dataId).values),f=x.util.toNestedArray(s.shape,d.data.get(s.dataId).values),m=x.backend_util.computeDilation2DInfo(a.shape,s.shape,u,c,"NHWC",h),g=m.batchSize,v=m.inHeight,b=m.inWidth,S=m.inChannels,L=m.outHeight,w=m.outWidth,N=m.padInfo,I=m.strideHeight,C=m.strideWidth,E=m.filterHeight,k=m.filterWidth,W=m.dilationHeight,F=m.dilationWidth,_=m.outShape;x.util.assert(o.rank===_.length,function(){return"Error in "+x.Dilation2DBackpropInput+", dy "+("must have the same rank as output "+_.length+", but got ")+(""+o.rank)});for(var H=x.util.toNestedArray(_,d.data.get(o.dataId).values),P=x.util.makeZerosNestedTypedArray(a.shape,a.dtype),K=0;K=0&&re=0&&heee&&(ee=ye,ne=re,ie=he)}}}P[K][ne][ie][X]+=H[K][j][G][X]}var Oe=d.write(x.util.toTypedArray(P,a.dtype),a.shape,a.dtype);return{dataId:Oe,shape:a.shape,dtype:a.dtype}}};var uz=ar(function(n,t){return n/t}),cz=Yr(x.Div,uz),wd={kernelName:x.Div,backendName:"cpu",kernelFunc:cz};var hz=Ke(x.Elu,function(n){return n>=0?n:Math.exp(n)-1}),dz={kernelName:x.Elu,backendName:"cpu",kernelFunc:hz};var pz=x.backend_util.ERF_P,fz=x.backend_util.ERF_A1,mz=x.backend_util.ERF_A2,gz=x.backend_util.ERF_A3,vz=x.backend_util.ERF_A4,yz=x.backend_util.ERF_A5,bz=Ke(x.Erf,function(n){var t=Math.sign(n),e=Math.abs(n),i=1/(1+pz*e);return t*(1-((((yz*i+vz)*i+gz)*i+mz)*i+fz)*i*Math.exp(-e*e))}),wz={kernelName:x.Erf,backendName:"cpu",kernelFunc:bz};function o0(n,t,e){for(var i=n.shape,r=i[0],a=i[1],s=e.data.get(n.dataId),o=s.complexTensorInfos.real,l=s.complexTensorInfos.imag,u=[r,a],c=x.util.sizeFromShape(u),h=x.util.getTypedArrayFromDType("float32",c),d=x.util.getTypedArrayFromDType("float32",c),p=0;p=0&&N=d.outHeight||Math.floor(q)!==q)continue;for(var G=0;G=d.outWidth||Math.floor(Z)!==Z)continue;var X=S*L-1-f.get(k,q,Z,W),ee=j*L+G,ne=X===ee?1:0;if(ne===0)continue;var ie=E.get(k,q,Z,W);K+=ie*ne}}I.set(K,k,F,_,W)}return e.makeTensorInfo(I.shape,I.dtype,I.values)}var Vz={kernelName:x.MaxPoolBackprop,backendName:"cpu",kernelFunc:Hz};function qz(n,t,e,i,r){var a=x.util.computeStrides(t),s=bd(n,t,e,a,r,"max"),o=s0(n,t,e,r,!0,i);return[s.values,o.values]}var Gz={kernelName:x.MaxPoolWithArgmax,backendName:"cpu",kernelFunc:function(n){var t=n.inputs,e=n.attrs,i=n.backend,r=t.x,a=e,s=a.filterSize,o=a.strides,l=a.pad,u=a.includeBatchInIndex,c=i;ae(r,"MaxPoolWithArgmax");var h=c.data.get(r.dataId).values,d=x.backend_util.computePool2DInfo(r.shape,s,o,[1,1],l),p=qz(h,r.shape,r.dtype,u,d),f=p[0],m=p[1],g=c.write(f,d.outShape,r.dtype),v=c.write(m,d.outShape,r.dtype);return[{dataId:g,shape:d.outShape,dtype:r.dtype},{dataId:v,shape:d.outShape,dtype:"int32"}]}};var Yz=x.kernel_impls.nonMaxSuppressionV4Impl,Kz={kernelName:x.NonMaxSuppressionV4,backendName:"cpu",kernelFunc:function(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t,a=r.boxes,s=r.scores,o=i,l=o.maxOutputSize,u=o.iouThreshold,c=o.scoreThreshold,h=o.padToMaxOutputSize,d=e;ae(a,"NonMaxSuppressionPadded");var p=d.data.get(a.dataId).values,f=d.data.get(s.dataId).values,m=Yz(p,f,l,u,c,h),g=m.selectedIndices,v=m.validOutputs;return[g,v]}};var jz=x.kernel_impls.nonMaxSuppressionV5Impl,$z={kernelName:x.NonMaxSuppressionV5,backendName:"cpu",kernelFunc:function(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t,a=r.boxes,s=r.scores,o=i,l=o.maxOutputSize,u=o.iouThreshold,c=o.scoreThreshold,h=o.softNmsSigma,d=e;ae(a,"NonMaxSuppressionWithScore");var p=d.data.get(a.dataId).values,f=d.data.get(s.dataId).values,m=l,g=u,v=c,b=h,S=jz(p,f,m,g,v,b),L=S.selectedIndices,w=S.selectedScores;return[L,w]}};var Xz=ar(function(n,t){return n!==t?1:0}),Jz=Yr(x.NotEqual,Xz,null,"bool"),Zz={kernelName:x.NotEqual,backendName:"cpu",kernelFunc:Jz};function Qz(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.x,a=i.paddings,s=i.constantValue;ae(r,"pad");var o=a.map(function(N,I){return N[0]+r.shape[I]+N[1]}),l=a.map(function(N){return N[0]}),u=e.data.get(r.dataId).values,c=x.util.sizeFromShape(r.shape),h=r.shape.length,d=x.util.computeStrides(r.shape),p=x.util.sizeFromShape(o),f=o.length,m=x.util.computeStrides(o),g=x.util.getTypedArrayFromDType(r.dtype,p);s!==0&&g.fill(s);for(var v=0;v=0&&j=0&&q.5?Math.ceil(n):t%2===0?t:t+1}),r_={kernelName:x.Round,backendName:"cpu",kernelFunc:i_};var a_=x.backend_util.SELU_SCALEALPHA,s_=x.backend_util.SELU_SCALE,o_=Ke(x.Selu,function(n){return n>=0?s_*n:a_*(Math.exp(n)-1)}),l_={kernelName:x.Selu,backendName:"cpu",kernelFunc:o_};var u_=Ke(x.Sigmoid,function(n){return 1/(1+Math.exp(-n))}),c_={kernelName:x.Sigmoid,backendName:"cpu",kernelFunc:u_};var h_=Ke(x.Sign,function(n){return n<0?-1:n>0?1:0}),d_={kernelName:x.Sign,backendName:"cpu",kernelFunc:h_};var p_=Ke(x.Sin,function(n){return Math.sin(n)}),f_={kernelName:x.Sin,backendName:"cpu",kernelFunc:p_};var m_=Ke(x.Sinh,function(n){return Math.sinh(n)}),g_={kernelName:x.Sinh,backendName:"cpu",kernelFunc:m_};var v_=11920928955078125e-23,u0=Math.log(v_)+2,y_=Ke(x.Softplus,function(n){var t=n>-u0,e=n0?1:e.alpha}),O_={kernelName:x.Step,backendName:"cpu",kernelFunc:R_};var E_=Ke(x.Tan,function(n){return Math.tan(n)}),D_={kernelName:x.Tan,backendName:"cpu",kernelFunc:E_};var k_=Ke(x.Tanh,function(n){return Math.tanh(n)}),F_={kernelName:x.Tanh,backendName:"cpu",kernelFunc:k_};function W_(n){var t=n.inputs,e=n.attrs,i=n.backend,r=e.axis,a=t.x;ae(a,"unique");var s=i.data.get(a.dataId).values,o=a0(s,r,a.shape,a.dtype),l=o.outputValues,u=o.outputShape,c=o.indices;return[i.makeTensorInfo(u,a.dtype,l),i.makeTensorInfo([c.length],"int32",c)]}var U_={kernelName:x.Unique,backendName:"cpu",kernelFunc:W_};var B_=[oB,FB,UB,pB,zB,PB,HB,qB,YB,jB,XB,hB,mB,ZB,lB,tz,iz,az,sz,lz,oz,wd,dz,wz,vB,bB,Tz,Nz,SB,uB,Cz,QB,Oz,Dz,Fz,IB,Uz,zz,Mz,Vz,Gz,_z,TB,Kz,$z,Zz,l0,cB,t_,ez,n_,r_,xB,l_,c_,d_,f_,g_,CB,b_,L_,A_,T_,C_,O_,OB,D_,F_,w_,U_];for(var Ld=0,h0=B_;Ld{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});var R=Ki();var Id=function(n,t){return Id=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,i){e.__proto__=i}||function(e,i){for(var r in i)i.hasOwnProperty(r)&&(e[r]=i[r])},Id(n,t)};function __(n,t){Id(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function No(n,t,e,i){function r(a){return a instanceof e?a:new e(function(s){s(a)})}return new(e||(e=Promise))(function(a,s){function o(c){try{u(i.next(c))}catch(h){s(h)}}function l(c){try{u(i.throw(c))}catch(h){s(h)}}function u(c){c.done?a(c.value):r(c.value).then(o,l)}u((i=i.apply(n,t||[])).next())})}function xo(n,t){var e={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,r,a,s;return s={next:o(0),throw:o(1),return:o(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function o(u){return function(c){return l([u,c])}}function l(u){if(i)throw new TypeError("Generator is already executing.");for(;e;)try{if(i=1,r&&(a=u[0]&2?r.return:u[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,u[1])).done)return a;(r=0,a)&&(u=[u[0]&2,a.value]);switch(u[0]){case 0:case 1:a=u;break;case 4:return e.label++,{value:u[1],done:!1};case 5:e.label++,r=u[1],u=[0];continue;case 7:u=e.ops.pop(),e.trys.pop();continue;default:if(!(a=e.trys,a=a.length>0&&a[a.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!a||u[1]>a[0]&&u[1]f&&(f=v,m=g)}c[d]=m}return l},t.prototype.cumsum=function(e,i,r,a){if(ae(e,"cumsum"),i!==e.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(e.rank-1)+" "+("but got axis="+i));for(var s=x.upcastType(e.dtype,"int32"),o=x.zeros(e.shape,s),l=this.readSync(o.dataId),u=this.readSync(e.dataId),c=e.shape[e.rank-1],h=a?function(g,v){return g+c-v-1}:function(g,v){return g+v},d=0;da?1:0})},t.prototype.greaterEqual=function(e,i){return ae([e,i],"greaterEqual"),this.broadcastedBinaryOp(e,i,"bool",function(r,a){return r>=a?1:0})},t.prototype.logicalAnd=function(e,i){return ae([e,i],"logicalAnd"),this.broadcastedBinaryOp(e,i,"bool",function(r,a){return r&&a})},t.prototype.logicalOr=function(e,i){return ae([e,i],"logicalOr"),this.broadcastedBinaryOp(e,i,"bool",function(r,a){return r||a})},t.prototype.select=function(e,i,r){ae([e,i,r],"select");for(var a=this.readSync(e.dataId),s=this.readSync(i.dataId),o=this.readSync(r.dataId),l=x.zeros(i.shape,x.upcastType(i.dtype,r.dtype)),u=this.readSync(l.dataId),c=0,h=e.rank===0||e.rank>1||i.rank===1?1:x.util.sizeFromShape(i.shape.slice(1)),d=0;d=0&&a>=0?s:(s+a)%a})},t.prototype.maximum=function(e,i){return ae([e,i],"maximum"),this.broadcastedBinaryOp(e,i,e.dtype,function(r,a){return Math.max(r,a)})},t.prototype.all=function(e,i){ae(e,"all"),x.backend_util.assertAxesAreInnerMostDims("all",i,e.rank);for(var r=x.backend_util.computeOutAndReduceShapes(e.shape,i),a=r[0],s=r[1],o=x.zeros(a,e.dtype),l=x.util.sizeFromShape(s),u=this.readSync(o.dataId),c=this.readSync(e.dataId),h=0;h=1?r[o]=s[o]:r[o]=s[o]*(l+1)}return this.makeOutput(r,i.shape,"float32")},t.prototype.atan2=function(e,i){return ae([e,i],"atan2"),this.broadcastedBinaryOp(e,i,e.dtype,function(r,a){return Math.atan2(r,a)})},t.prototype.fusedConv2d=function(e){var i=e.input,r=e.filter,a=e.convInfo,s=e.bias,o=e.activation,l=e.preluActivationWeights,u=this.conv2d(i,r,a);return s&&(u=x.add(u,s)),o&&(u=md(this,u,o,l)),u},t.prototype.conv2d=function(e,i,r){ae([e,i],"conv2d");for(var a=r.filterHeight,s=r.filterWidth,o=r.dilationHeight,l=r.dilationWidth,u=r.padInfo.left,c=r.padInfo.top,h=r.dataFormat==="channelsLast",d=x.buffer(r.outShape,e.dtype),p=e.strides[0],f=h?e.strides[1]:e.strides[2],m=h?e.strides[2]:1,g=h?1:e.strides[1],v=d.strides[0],b=h?d.strides[1]:d.strides[2],S=h?d.strides[2]:1,L=h?1:d.strides[1],w=this.readSync(e.dataId),N=this.readSync(i.dataId),I=d.values,C=0;C=r.inHeight)continue;for(var K=H*i.strides[0],j=E+P*f,q=0;q=r.inWidth)continue;for(var ne=K+X*i.strides[1],ie=j+ee*m,te=ne,re=0;re=r.inDepth)continue;for(var k=C*i.strides[0],W=S+E*e.strides[1],F=0;F=r.inHeight)continue;for(var j=k+P*i.strides[1],q=W+K*e.strides[2],G=0;G=r.inWidth)continue;for(var ie=j+ee*i.strides[2],te=q+ne*r.inChannels,re=ie,le=0;le=r.inHeight)continue;for(var C=N*i.strides[0],E=v+I*e.strides[1],k=0;k=r.inWidth)continue;for(var P=C+_*i.strides[1],K=E+H*r.inChannels,j=W,q=P,G=0;Ghe?he=We:r==="avg"&&(ye+=We,Oe++),isNaN(he))break}if(isNaN(he))break}if(isNaN(he))break}var me=le+F;L[me]=r==="avg"?ye/Oe:he}}}return S.toTensor()},t.prototype.avgPool3d=function(e,i){return ae(e,"avgPool3d"),this.pool3d(e,i,"avg").toFloat()},t.prototype.avgPool3dBackprop=function(e,i,r){ae([e,i],"avgPool3dBackprop");for(var a=r.strideDepth,s=r.strideHeight,o=r.strideWidth,l=r.filterDepth,u=r.filterHeight,c=r.filterWidth,h=r.dilationDepth,d=r.dilationHeight,p=r.dilationWidth,f=r.effectiveFilterDepth,m=r.effectiveFilterHeight,g=r.effectiveFilterWidth,v=f-1-r.padInfo.front,b=g-1-r.padInfo.left,S=m-1-r.padInfo.top,L=x.buffer(i.shape,"float32"),w=1/(l*u*c),N=this.bufferSync(e),I=0;I=r.outDepth||Math.floor(j)!==j)continue;for(var q=0;q=r.outHeight||Math.floor(G)!==G)continue;for(var Z=0;Z=r.outWidth||Math.floor(X)!==X)continue;var ee=N.get(I,j,G,X,C);P+=ee}}}L.set(P*w,I,E,k,W,C)}return L.toTensor()},t.prototype.maxPool3d=function(e,i){return ae(e,"maxPool3d"),this.pool3d(e,i,"max").toFloat()},t.prototype.maxPool3dPositions=function(e,i){for(var r=x.buffer(i.outShape,"int32"),a=i.strideDepth,s=i.strideHeight,o=i.strideWidth,l=i.dilationDepth,u=i.dilationHeight,c=i.dilationWidth,h=i.effectiveFilterDepth,d=i.effectiveFilterHeight,p=i.effectiveFilterWidth,f=i.padInfo.front,m=i.padInfo.top,g=i.padInfo.left,v=this.bufferSync(e),b=0;b=K&&(K=ie,j=G*d*p+X*d+ne)}r.set(j,b,L,C,F,S)}}}return r.toTensor()},t.prototype.maxPool3dBackprop=function(e,i,r,a){ae([i,r],"maxPool3dBackprop");for(var s=this.maxPool3dPositions(i,a),o=a.strideDepth,l=a.strideHeight,u=a.strideWidth,c=a.dilationDepth,h=a.dilationHeight,d=a.dilationWidth,p=a.effectiveFilterDepth,f=a.effectiveFilterHeight,m=a.effectiveFilterWidth,g=p-1-a.padInfo.front,v=m-1-a.padInfo.left,b=f-1-a.padInfo.top,S=x.buffer(i.shape,"float32"),L=this.bufferSync(s),w=this.bufferSync(e),N=0;N=a.outDepth||Math.floor(K)!==K)continue;for(var j=0;j=a.outHeight||Math.floor(q)!==q)continue;for(var G=0;G=a.outWidth||Math.floor(Z)!==Z)continue;var X=p*f*m-1-L.get(N,K,q,Z,I),ee=P*f*m+j*m+G,ne=X===ee?1:0;if(ne===0)continue;var ie=w.get(N,K,q,Z,I);H+=ie*ne}}}S.set(H,N,C,E,k,I)}return S.toTensor()},t.prototype.resizeBilinear=function(e,i,r,a){ae(e,"resizeBilinear");for(var s=e.shape,o=s[0],l=s[1],u=s[2],c=s[3],h=this.readSync(e.dataId),d=new Float32Array(x.util.sizeFromShape([o,i,r,c])),p=[a&&i>1?l-1:l,a&&r>1?u-1:u],f=[a&&i>1?i-1:i,a&&r>1?r-1:r],m=0,g=p[0]/f[0],v=p[1]/f[1],b=0;b1?o-1:o,r&&d>1?l-1:l],m=[r&&h>1?h-1:h,r&&d>1?d-1:d],g=f[0]/m[0],v=f[1]/m[1],b=this.readSync(e.dataId),S=0,L=0;L1?l-1:l,a&&r>1?u-1:u],f=[a&&i>1?i-1:i,a&&r>1?r-1:r],m=p[0]/f[0],g=p[1]/f[1],v=0,b=0;b1?o-1:o,r&&d>1?l-1:l],g=[r&&h>1?h-1:h,r&&d>1?d-1:d],v=m[0]/g[0],b=m[1]/g[1],S=1/v,L=1/b,w=Math.ceil(S)*2+2,N=Math.ceil(L)*2+2,I=0;I=h)continue;var X=C+Z*e.strides[1],ee=Z*v,ne=Math.min(o-1,r?Math.round(ee):Math.floor(ee));if(E!==ne)continue;for(var ie=0;ie=d)continue;var re=X+te*e.strides[2],le=te*b,he=Math.min(l-1,r?Math.round(le):Math.floor(le));_===he&&(q+=f[re+j])}}p[H+j]=q}return x.tensor4d(p,i.shape,i.dtype)},t.prototype.localResponseNormalization4D=function(e,i,r,a,s){ae(e,"localResponseNormalization4D");var o=e.shape[3],l=o-1,u=this.readSync(e.dataId),c=e.size,h=new Float32Array(c);function d(g){for(var v=g%o,b=g-v+Math.max(0,v-i),S=g-v+Math.min(v+i,l),L=0;b<=S;b++){var w=u[b];L+=w*w}return L}for(var p=0;p=0&&o[l]1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+i});for(var a=e.shape[0],s=e.shape[1],o=e.shape[2],l=e.shape[3],u=s*i,c=o*i,h=l/(i*i),d=this.readSync(e.dataId),p=new Float32Array(a*u*c*h),f=0,m=0;m=u)continue;for(var _=f>1?(k-C)*(c-1)/(f-1):0,H=m>1?(W-E)*(h-1)/(m-1):0,P=0;P1?C*(c-1)+P*_:.5*(C+k)*(c-1);if(K<0||K>c-1){for(var j=0;j1?E*(h-1)+j*H:.5*(E+W)*(h-1);if(ne<0||ne>h-1){for(var q=0;q1?E*(h-1)+j*H:.5*(E+W)*(h-1);if(ne<0||ne>h-1){for(var q=0;q=e.size/u)throw new Error("Invalid indices: "+m+" does not index into "+e.shape);for(var S=0;S=a/s)throw new Error("Invalid indices: "+v+" does not index into "+r);for(var w=0;wo&&(o=u)}r[a]=o}return r}var Qw=ar(function(n,t){return n*t}),TB=gd(function(n,t,e,i){return{real:n*e-t*i,imag:n*i+t*e}}),e0=Yr(x.Multiply,Qw,TB),NB={kernelName:x.Multiply,backendName:"cpu",kernelFunc:e0};var t0=Kr(function(n){return 1/Math.sqrt(n)}),xB=jr(x.Rsqrt,t0),CB={kernelName:x.Rsqrt,backendName:"cpu",kernelFunc:xB};function n0(n,t,e,i,r){var a=x.slice_util.isSliceContinous(i,t,e),s=x.util.sizeFromShape(e),o=x.util.computeStrides(i);if(a){var l=x.slice_util.computeFlatOffset(t,o);return n.subarray(l,l+s)}for(var u=x.util.getTypedArrayFromDType(r,s),c=0;cj?j=ie:a==="avg"&&(q+=ie,G++)}if(isNaN(j))break}var te=F+_*S+I;g[te]=a==="avg"?q/G:j}return m}function s0(n,t,e,i,r,a){r===void 0&&(r=!1),a===void 0&&(a=!1);for(var s=x.buffer(i.outShape,"int32"),o=i.strideHeight,l=i.strideWidth,u=i.dilationHeight,c=i.dilationWidth,h=i.effectiveFilterHeight,d=i.effectiveFilterWidth,p=i.padInfo.top,f=i.padInfo.left,m=x.buffer(t,e,n),g=0;gk&&(k=K,r?W=a?((g*i.inHeight+F)*i.inWidth+H)*i.inChannels+v:(F*i.inWidth+H)*i.inChannels+v:W=_*d+P)}s.set(W,g,b,N,v)}}return s}function YB(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.x;ae(r,"avgPool");var a=i.filterSize,s=i.strides,o=i.pad,l=i.dimRoundingMode,u=1;x.util.assert(x.backend_util.eitherStridesOrDilationsAreOne(s,u),function(){return"Error in avgPool: Either strides or dilations must be 1. "+("Got strides "+s+" and dilations '"+u+"'")});var c=x.backend_util.computePool2DInfo(r.shape,a,s,u,o,l),h;if(c.filterWidth===1&&c.filterHeight===1&&x.util.arraysEqual(c.inShape,c.outShape))h=Gr({inputs:{x:r},backend:e});else{var d=e.data.get(r.dataId).values,p=x.util.computeStrides(r.shape),f=bd(d,r.shape,r.dtype,p,c,"avg");h=e.makeTensorInfo(c.outShape,r.dtype,f.values)}return h}var KB={kernelName:x.AvgPool,backendName:"cpu",kernelFunc:YB};function jB(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.dy,a=t.input,s=a;ae([r,a],"avgPoolBackprop");for(var o=i.filterSize,l=i.strides,u=i.pad,c=x.backend_util.computePool2DInfo(s.shape,o,l,1,u),h=c.strideHeight,d=c.strideWidth,p=c.filterHeight,f=c.filterWidth,m=c.dilationHeight,g=c.dilationWidth,v=c.effectiveFilterHeight,b=c.effectiveFilterWidth,S=b-1-c.padInfo.left,L=v-1-c.padInfo.top,w=x.buffer(s.shape,"float32"),N=1/(p*f),I=e.data.get(r.dataId).values,C=x.buffer(r.shape,"float32",I),E=0;E=c.outHeight||Math.floor(j)!==j)continue;for(var q=0;q=c.outWidth||Math.floor(G)!==G)continue;var Z=C.get(E,j,G,k);P+=Z}}w.set(P*N,E,W,F,k)}return e.makeTensorInfo(w.shape,w.dtype,w.values)}var $B={kernelName:x.AvgPoolBackprop,backendName:"cpu",kernelFunc:jB};function XB(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.x,a=t.scale,s=t.offset,o=t.mean,l=t.variance;x.util.assert(o.shape.length===l.shape.length,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),x.util.assert(s==null||o.shape.length===s.shape.length,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),x.util.assert(a==null||o.shape.length===a.shape.length,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}),ae([r,o,l,a,s],"batchNorm");var u=i.varianceEpsilon;u==null&&(u=.001);for(var c=e.data.get(r.dataId).values,h=e.data.get(o.dataId).values,d=e.data.get(l.dataId).values,p=a?e.data.get(a.dataId).values:new Float32Array([1]),f=s?e.data.get(s.dataId).values:new Float32Array([0]),m=new Float32Array(c.length),g=f.length,v=p.length,b=d.length,S=h.length,L=0,w=0,N=0,I=0,C=0;C=g&&(L=0),w>=S&&(w=0),N>=v&&(N=0),I>=b&&(I=0);return e.makeTensorInfo(r.shape,r.dtype,m)}var JB={kernelName:x.FusedBatchNorm,backendName:"cpu",kernelFunc:XB};var ZB=Ke(x.ClipByValue,function(n,t){var e=t;return n>e.clipValueMax?e.clipValueMax:n0});if(o.length===1)return o[0];var l=o.map(function(L){return L.shape});if(x.backend_util.assertParamsConsistent(l,a),o[0].dtype==="complex64"){var u=o.map(function(L){return Va({inputs:{input:L},backend:e})}),c=o.map(function(L){return To({inputs:{input:L},backend:e})}),h=Ga({inputs:u,backend:e,attrs:{axis:r}}),d=Ga({inputs:c,backend:e,attrs:{axis:r}}),p=bn({inputs:{real:h,imag:d},backend:e});return u.forEach(function(L){return e.disposeIntermediateTensorInfo(L)}),c.forEach(function(L){return e.disposeIntermediateTensorInfo(L)}),e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(d),p}var f=o.map(function(L){var w=x.util.sizeFromShape(L.shape.slice(a)),N=[-1,w];return wi({inputs:{x:L},backend:e,attrs:{shape:N}})});s=x.backend_util.computeOutShape(f.map(function(L){return L.shape}),1);var m=x.util.getTypedArrayFromDType(o[0].dtype,x.util.sizeFromShape(s));if(f[0].shape[0]===1){var g=0;f.forEach(function(L){var w=e.data.get(L.dataId).values,N=x.util.sizeFromShape(L.shape);m.set(w,g),g+=N})}else{var v=0;f.forEach(function(L){for(var w=e.data.get(L.dataId).values,N=0,I=0;I=0&&re=0&&heie&&(ie=ke)}}}var _e=x.util.locToIndex([q,G,X,ne],K,x.util.computeStrides(H));j[_e]=ie}var Pe=h.write(x.util.toTypedArray(j,a.dtype),H,a.dtype);return{dataId:Pe,shape:H,dtype:a.dtype}}};var lz={kernelName:x.Dilation2DBackpropFilter,backendName:"cpu",kernelFunc:function(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t,a=r.x,s=r.filter,o=r.dy,l=i,u=l.strides,c=l.pad,h=l.dilations,d=e,p=x.util.toNestedArray(a.shape,d.data.get(a.dataId).values),f=x.util.toNestedArray(s.shape,d.data.get(s.dataId).values),m=x.backend_util.computeDilation2DInfo(a.shape,s.shape,u,c,"NHWC",h),g=m.batchSize,v=m.inHeight,b=m.inWidth,S=m.inChannels,L=m.outHeight,w=m.outWidth,N=m.padInfo,I=m.strideHeight,C=m.strideWidth,E=m.filterHeight,k=m.filterWidth,W=m.dilationHeight,F=m.dilationWidth,_=m.outShape;x.util.assert(o.rank===_.length,function(){return"Error in "+x.Dilation2DBackpropFilter+", dy "+("must have the same rank as output "+_.length+", but got ")+(""+o.rank)});for(var H=x.util.toNestedArray(_,d.data.get(o.dataId).values),P=x.util.makeZerosNestedTypedArray(s.shape,s.dtype),K=0;K=0&&re=0&&heee&&(ee=ye,ne=te,ie=le)}}}P[ne][ie][X]+=H[K][j][G][X]}var Oe=d.write(x.util.toTypedArray(P,a.dtype),s.shape,s.dtype);return{dataId:Oe,shape:s.shape,dtype:s.dtype}}};var uz={kernelName:x.Dilation2DBackpropInput,backendName:"cpu",kernelFunc:function(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t,a=r.x,s=r.filter,o=r.dy,l=i,u=l.strides,c=l.pad,h=l.dilations,d=e,p=x.util.toNestedArray(a.shape,d.data.get(a.dataId).values),f=x.util.toNestedArray(s.shape,d.data.get(s.dataId).values),m=x.backend_util.computeDilation2DInfo(a.shape,s.shape,u,c,"NHWC",h),g=m.batchSize,v=m.inHeight,b=m.inWidth,S=m.inChannels,L=m.outHeight,w=m.outWidth,N=m.padInfo,I=m.strideHeight,C=m.strideWidth,E=m.filterHeight,k=m.filterWidth,W=m.dilationHeight,F=m.dilationWidth,_=m.outShape;x.util.assert(o.rank===_.length,function(){return"Error in "+x.Dilation2DBackpropInput+", dy "+("must have the same rank as output "+_.length+", but got ")+(""+o.rank)});for(var H=x.util.toNestedArray(_,d.data.get(o.dataId).values),P=x.util.makeZerosNestedTypedArray(a.shape,a.dtype),K=0;K=0&&re=0&&heee&&(ee=ye,ne=re,ie=he)}}}P[K][ne][ie][X]+=H[K][j][G][X]}var Oe=d.write(x.util.toTypedArray(P,a.dtype),a.shape,a.dtype);return{dataId:Oe,shape:a.shape,dtype:a.dtype}}};var cz=ar(function(n,t){return n/t}),hz=Yr(x.Div,cz),wd={kernelName:x.Div,backendName:"cpu",kernelFunc:hz};var dz=Ke(x.Elu,function(n){return n>=0?n:Math.exp(n)-1}),pz={kernelName:x.Elu,backendName:"cpu",kernelFunc:dz};var fz=x.backend_util.ERF_P,mz=x.backend_util.ERF_A1,gz=x.backend_util.ERF_A2,vz=x.backend_util.ERF_A3,yz=x.backend_util.ERF_A4,bz=x.backend_util.ERF_A5,wz=Ke(x.Erf,function(n){var t=Math.sign(n),e=Math.abs(n),i=1/(1+fz*e);return t*(1-((((bz*i+yz)*i+vz)*i+gz)*i+mz)*i*Math.exp(-e*e))}),Sz={kernelName:x.Erf,backendName:"cpu",kernelFunc:wz};function o0(n,t,e){for(var i=n.shape,r=i[0],a=i[1],s=e.data.get(n.dataId),o=s.complexTensorInfos.real,l=s.complexTensorInfos.imag,u=[r,a],c=x.util.sizeFromShape(u),h=x.util.getTypedArrayFromDType("float32",c),d=x.util.getTypedArrayFromDType("float32",c),p=0;p=0&&N=d.outHeight||Math.floor(q)!==q)continue;for(var G=0;G=d.outWidth||Math.floor(Z)!==Z)continue;var X=S*L-1-f.get(k,q,Z,W),ee=j*L+G,ne=X===ee?1:0;if(ne===0)continue;var ie=E.get(k,q,Z,W);K+=ie*ne}}I.set(K,k,F,_,W)}return e.makeTensorInfo(I.shape,I.dtype,I.values)}var qz={kernelName:x.MaxPoolBackprop,backendName:"cpu",kernelFunc:Vz};function Gz(n,t,e,i,r){var a=x.util.computeStrides(t),s=bd(n,t,e,a,r,"max"),o=s0(n,t,e,r,!0,i);return[s.values,o.values]}var Yz={kernelName:x.MaxPoolWithArgmax,backendName:"cpu",kernelFunc:function(n){var t=n.inputs,e=n.attrs,i=n.backend,r=t.x,a=e,s=a.filterSize,o=a.strides,l=a.pad,u=a.includeBatchInIndex,c=i;ae(r,"MaxPoolWithArgmax");var h=c.data.get(r.dataId).values,d=x.backend_util.computePool2DInfo(r.shape,s,o,[1,1],l),p=Gz(h,r.shape,r.dtype,u,d),f=p[0],m=p[1],g=c.write(f,d.outShape,r.dtype),v=c.write(m,d.outShape,r.dtype);return[{dataId:g,shape:d.outShape,dtype:r.dtype},{dataId:v,shape:d.outShape,dtype:"int32"}]}};var Kz=x.kernel_impls.nonMaxSuppressionV4Impl,jz={kernelName:x.NonMaxSuppressionV4,backendName:"cpu",kernelFunc:function(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t,a=r.boxes,s=r.scores,o=i,l=o.maxOutputSize,u=o.iouThreshold,c=o.scoreThreshold,h=o.padToMaxOutputSize,d=e;ae(a,"NonMaxSuppressionPadded");var p=d.data.get(a.dataId).values,f=d.data.get(s.dataId).values,m=Kz(p,f,l,u,c,h),g=m.selectedIndices,v=m.validOutputs;return[g,v]}};var $z=x.kernel_impls.nonMaxSuppressionV5Impl,Xz={kernelName:x.NonMaxSuppressionV5,backendName:"cpu",kernelFunc:function(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t,a=r.boxes,s=r.scores,o=i,l=o.maxOutputSize,u=o.iouThreshold,c=o.scoreThreshold,h=o.softNmsSigma,d=e;ae(a,"NonMaxSuppressionWithScore");var p=d.data.get(a.dataId).values,f=d.data.get(s.dataId).values,m=l,g=u,v=c,b=h,S=$z(p,f,m,g,v,b),L=S.selectedIndices,w=S.selectedScores;return[L,w]}};var Jz=ar(function(n,t){return n!==t?1:0}),Zz=Yr(x.NotEqual,Jz,null,"bool"),Qz={kernelName:x.NotEqual,backendName:"cpu",kernelFunc:Zz};function e_(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.x,a=i.paddings,s=i.constantValue;ae(r,"pad");var o=a.map(function(N,I){return N[0]+r.shape[I]+N[1]}),l=a.map(function(N){return N[0]}),u=e.data.get(r.dataId).values,c=x.util.sizeFromShape(r.shape),h=r.shape.length,d=x.util.computeStrides(r.shape),p=x.util.sizeFromShape(o),f=o.length,m=x.util.computeStrides(o),g=x.util.getTypedArrayFromDType(r.dtype,p);s!==0&&g.fill(s);for(var v=0;v=0&&j=0&&q.5?Math.ceil(n):t%2===0?t:t+1}),a_={kernelName:x.Round,backendName:"cpu",kernelFunc:r_};var s_=x.backend_util.SELU_SCALEALPHA,o_=x.backend_util.SELU_SCALE,l_=Ke(x.Selu,function(n){return n>=0?o_*n:s_*(Math.exp(n)-1)}),u_={kernelName:x.Selu,backendName:"cpu",kernelFunc:l_};var c_=Ke(x.Sigmoid,function(n){return 1/(1+Math.exp(-n))}),h_={kernelName:x.Sigmoid,backendName:"cpu",kernelFunc:c_};var d_=Ke(x.Sign,function(n){return n<0?-1:n>0?1:0}),p_={kernelName:x.Sign,backendName:"cpu",kernelFunc:d_};var f_=Ke(x.Sin,function(n){return Math.sin(n)}),m_={kernelName:x.Sin,backendName:"cpu",kernelFunc:f_};var g_=Ke(x.Sinh,function(n){return Math.sinh(n)}),v_={kernelName:x.Sinh,backendName:"cpu",kernelFunc:g_};var y_=11920928955078125e-23,u0=Math.log(y_)+2,b_=Ke(x.Softplus,function(n){var t=n>-u0,e=n0?1:e.alpha}),E_={kernelName:x.Step,backendName:"cpu",kernelFunc:O_};var D_=Ke(x.Tan,function(n){return Math.tan(n)}),k_={kernelName:x.Tan,backendName:"cpu",kernelFunc:D_};var F_=Ke(x.Tanh,function(n){return Math.tanh(n)}),W_={kernelName:x.Tanh,backendName:"cpu",kernelFunc:F_};function U_(n){var t=n.inputs,e=n.attrs,i=n.backend,r=e.axis,a=t.x;ae(a,"unique");var s=i.data.get(a.dataId).values,o=a0(s,r,a.shape,a.dtype),l=o.outputValues,u=o.outputShape,c=o.indices;return[i.makeTensorInfo(u,a.dtype,l),i.makeTensorInfo([c.length],"int32",c)]}var B_={kernelName:x.Unique,backendName:"cpu",kernelFunc:U_};var z_=[lB,WB,BB,fB,_B,MB,VB,GB,KB,$B,JB,dB,gB,QB,uB,nz,rz,sz,oz,uz,lz,wd,pz,Sz,yB,wB,Nz,xz,LB,cB,Rz,ez,Ez,kz,Wz,AB,Bz,_z,Hz,qz,Yz,Pz,NB,jz,Xz,Qz,l0,hB,n_,tz,i_,a_,CB,u_,h_,p_,m_,v_,RB,w_,I_,T_,N_,R_,E_,EB,k_,W_,S_,B_];for(var Ld=0,h0=z_;Ld{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});var R=Ki();var Id=function(n,t){return Id=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,i){e.__proto__=i}||function(e,i){for(var r in i)i.hasOwnProperty(r)&&(e[r]=i[r])},Id(n,t)};function P_(n,t){Id(n,t);function e(){this.constructor=n}n.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function No(n,t,e,i){function r(a){return a instanceof e?a:new e(function(s){s(a)})}return new(e||(e=Promise))(function(a,s){function o(c){try{u(i.next(c))}catch(h){s(h)}}function l(c){try{u(i.throw(c))}catch(h){s(h)}}function u(c){c.done?a(c.value):r(c.value).then(o,l)}u((i=i.apply(n,t||[])).next())})}function xo(n,t){var e={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},i,r,a,s;return s={next:o(0),throw:o(1),return:o(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function o(u){return function(c){return l([u,c])}}function l(u){if(i)throw new TypeError("Generator is already executing.");for(;e;)try{if(i=1,r&&(a=u[0]&2?r.return:u[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,u[1])).done)return a;(r=0,a)&&(u=[u[0]&2,a.value]);switch(u[0]){case 0:case 1:a=u;break;case 4:return e.label++,{value:u[1],done:!1};case 5:e.label++,r=u[1],u=[0];continue;case 7:u=e.ops.pop(),e.trys.pop();continue;default:if(!(a=e.trys,a=a.length>0&&a[a.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!a||u[1]>a[0]&&u[1]e||t>e){var i="["+n+"x"+t+"]",r="["+e+"x"+e+"]";throw new Error("Requested texture size "+i+" greater than WebGL maximum on this browser / GPU "+r+".")}}function A0(n){return jn(n,function(){return n.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function Nd(n,t,e,i,r,a,s){var o=n.getAttribLocation(t,e);return o===-1?!1:(ce(n,function(){return n.bindBuffer(n.ARRAY_BUFFER,i)}),ce(n,function(){return n.vertexAttribPointer(o,r,n.FLOAT,!1,a,s)}),ce(n,function(){return n.enableVertexAttribArray(o)}),!0)}function N0(n,t,e){T0(n,e),ce(n,function(){return n.activeTexture(n.TEXTURE0+e)}),ce(n,function(){return n.bindTexture(n.TEXTURE_2D,t)})}function X_(n,t){T0(n,t),ce(n,function(){return n.activeTexture(n.TEXTURE0+t)}),ce(n,function(){return n.bindTexture(n.TEXTURE_2D,null)})}function x0(n,t,e){return jn(n,function(){return n.getUniformLocation(t,e)},'uniform "'+e+'" not present in program.')}function C0(n,t,e){return n.getUniformLocation(t,e)}function R0(n,t,e,i){ce(n,function(){return N0(n,t,i)}),ce(n,function(){return n.uniform1i(e,i)})}function J_(n){ce(n,function(){return n.bindFramebuffer(n.FRAMEBUFFER,null)}),ce(n,function(){return n.viewport(0,0,n.canvas.width,n.canvas.height)}),ce(n,function(){return n.scissor(0,0,n.canvas.width,n.canvas.height)})}function Ro(n,t,e){ce(n,function(){return n.bindFramebuffer(n.FRAMEBUFFER,e)}),ce(n,function(){return n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t,0)})}function xd(n,t){ce(n,function(){return n.bindFramebuffer(n.FRAMEBUFFER,t)}),ce(n,function(){return n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,null,0)})}function Xa(n){var t=n.checkFramebufferStatus(n.FRAMEBUFFER);if(t!==n.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+O0(n,t))}function O0(n,t){switch(t){case n.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case n.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+t}}function jn(n,t,e){var i=ce(n,function(){return t()});if(i==null)throw new Error(e);return i}function T0(n,t){var e=n.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,i=t+n.TEXTURE0;if(ie){var r="[gl.TEXTURE0, gl.TEXTURE"+e+"]";throw new Error("textureUnit must be in "+r+".")}}function or(n,t){return t===void 0&&(t=2),R.util.sizeFromShape(n.slice(0,n.length-t))}function lr(n){if(n.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[n.length>1?n[n.length-2]:1,n[n.length-1]]}function Oo(n){var t=[1,1,1],e=n.length===0||n.length===1&&n[0]===1;return e||(t=[or(n)].concat(lr(n))),t}function E0(n,t){var e;t===void 0&&(t=!1);var i=R.env().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(i=i*2,n=n.map(function(u,c){return c>=n.length-2?R.util.nearestLargerEven(n[c]):n[c]}),n.length===1&&(n=[2,n[0]])),n.length!==2){var r=R.util.squeezeShape(n);n=r.newShape}var a=R.util.sizeFromShape(n);if(n.length<=1&&a<=i)return[1,a];if(n.length===2&&n[0]<=i&&n[1]<=i)return n;if(n.length===3&&n[0]*n[1]<=i&&n[2]<=i)return[n[0]*n[1],n[2]];if(n.length===3&&n[0]<=i&&n[1]*n[2]<=i)return[n[0],n[1]*n[2]];if(n.length===4&&n[0]*n[1]*n[2]<=i&&n[3]<=i)return[n[0]*n[1]*n[2],n[3]];if(n.length===4&&n[0]<=i&&n[1]*n[2]*n[3]<=i)return[n[0],n[1]*n[2]*n[3]];if(t){var s=or(n),o=2,l=2;return n.length&&(e=lr(n),o=e[0],l=e[1]),a=s*(o/2)*(l/2),R.util.sizeToSquarishShape(a).map(function(u){return u*2})}return R.util.sizeToSquarishShape(a)}function Eo(n){return n%2===0}function Ja(n,t){if(n=n.slice(-2),t=t.slice(-2),R.util.arraysEqual(n,t))return!0;if(!n.length||!t.length)return!0;if(n[0]===0||n[1]===0||t[0]===0||t[1]===0)return!0;if(n.length!==t.length){var e=n.slice(-1)[0],i=t.slice(-1)[0];if(e===i)return!0;if(Eo(e)&&Eo(i)&&(n[0]===1||t[0]===1))return!0}return n[1]===t[1]&&Eo(n[0])&&Eo(t[0])}var Do,ko;function D0(n){if(Do==null){var t=Wn(n);Do=t.getParameter(t.MAX_TEXTURE_SIZE)}return Do}function Z_(){Do=null}function Q_(){ko=null}function k0(n){if(ko==null){var t=Wn(n);ko=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,ko)}function F0(n){if(n===0)return 0;var t,e=Wn(n);return nn(e,"EXT_disjoint_timer_query_webgl2")&&n===2?t=2:nn(e,"EXT_disjoint_timer_query")?t=1:t=0,t}function nn(n,t){var e=n.getExtension(t);return e!=null}function Cd(n){try{var t=Wn(n);if(t!=null)return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function W0(n){if(n===0)return!1;var t=Wn(n);if(n===1){if(!nn(t,"OES_texture_float"))return!1}else if(!nn(t,"EXT_color_buffer_float"))return!1;var e=Rd(t);return e}function U0(n){if(n===0)return!1;var t=Wn(n);if(n===1){if(!nn(t,"OES_texture_float"))return!1;if(!nn(t,"WEBGL_color_buffer_float"))return!1}else{if(nn(t,"EXT_color_buffer_float"))return Rd(t);var e="EXT_color_buffer_half_float";if(nn(t,e)){var i=t.getExtension(e);return eP(t,i)}return!1}var r=Rd(t);return r}function Rd(n){var t=Td(n),e=n.createTexture();n.bindTexture(n.TEXTURE_2D,e);var i=1,r=1;n.texImage2D(n.TEXTURE_2D,0,t.internalFormatFloat,i,r,0,t.textureFormatFloat,t.textureTypeFloat,null);var a=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,a),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,e,0);var s=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(e),n.deleteFramebuffer(a),s}function eP(n,t){var e=Td(n,t),i=n.createTexture();n.bindTexture(n.TEXTURE_2D,i);var r=1,a=1;n.texImage2D(n.TEXTURE_2D,0,e.internalFormatHalfFloat,r,a,0,e.textureFormatFloat,e.textureTypeHalfFloat,null);var s=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,s),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,i,0);var o=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(i),n.deleteFramebuffer(s),o}function B0(n){if(n!==2)return!1;var t=Wn(n),e=t.fenceSync!=null;return e}function Xr(n,t){Array.isArray(n)||(n=[n]),n.forEach(function(e){e!=null&&R.util.assert(e.dtype!=="complex64",function(){return t+" does not support complex64 tensors in the WebGL backend."})})}var tP={__proto__:null,callAndCheck:ce,canBeRepresented:m0,getWebGLErrorMessage:f0,getExtensionOrThrow:$a,createVertexShader:g0,createFragmentShader:v0,createProgram:y0,linkProgram:b0,validateProgram:Co,createStaticVertexBuffer:w0,createStaticIndexBuffer:S0,getNumChannels:$_,createTexture:L0,validateTextureSize:I0,createFramebuffer:A0,bindVertexBufferToProgramAttribute:Nd,bindTextureUnit:N0,unbindTextureUnit:X_,getProgramUniformLocationOrThrow:x0,getProgramUniformLocation:C0,bindTextureToProgramUniformSampler:R0,bindCanvasToFramebuffer:J_,bindColorTextureToFramebuffer:Ro,unbindColorTextureFromFramebuffer:xd,validateFramebuffer:Xa,getFramebufferErrorMessage:O0,getBatchDim:or,getRowsCols:lr,getShapeAs3D:Oo,getTextureShapeFromLogicalShape:E0,isReshapeFree:Ja,getWebGLMaxTextureSize:D0,resetMaxTextureSize:Z_,resetMaxTexturesInShader:Q_,getMaxTexturesInShader:k0,getWebGLDisjointQueryTimerVersion:F0,hasExtension:nn,isWebGLVersionEnabled:Cd,isCapableOfRenderingToFloatTexture:W0,isDownloadFloatTextureEnabled:U0,isWebGLFenceEnabled:B0,assertNotComplex:Xr};var Se=R.env();Se.registerFlag("HAS_WEBGL",function(){return Se.getNumber("WEBGL_VERSION")>0});Se.registerFlag("WEBGL_VERSION",function(){return Cd(2)?2:Cd(1)?1:0});Se.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",function(){return!1});Se.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return Se.get("WEBGL_VERSION")===2});Se.registerFlag("WEBGL_CPU_FORWARD",function(){return!0});Se.registerFlag("WEBGL_FORCE_F16_TEXTURES",function(){return!1});Se.registerFlag("WEBGL_PACK",function(){return Se.getBool("HAS_WEBGL")});Se.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return Se.getBool("WEBGL_PACK")});Se.registerFlag("WEBGL_PACK_CLIP",function(){return Se.getBool("WEBGL_PACK")});Se.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return!1});Se.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return Se.getBool("WEBGL_PACK")});Se.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",function(){return Se.getBool("WEBGL_PACK")});Se.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return Se.getBool("WEBGL_PACK")});Se.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return Se.getBool("WEBGL_PACK")});Se.registerFlag("WEBGL_PACK_REDUCE",function(){return Se.getBool("WEBGL_PACK")});Se.registerFlag("WEBGL_LAZILY_UNPACK",function(){return Se.getBool("WEBGL_PACK")});Se.registerFlag("WEBGL_CONV_IM2COL",function(){return Se.getBool("WEBGL_PACK")});Se.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return D0(Se.getNumber("WEBGL_VERSION"))});Se.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return k0(Se.getNumber("WEBGL_VERSION"))});Se.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var n=Se.getNumber("WEBGL_VERSION");return n===0?0:F0(n)});Se.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return Se.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!R.device_util.isMobile()});Se.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",function(){return W0(Se.getNumber("WEBGL_VERSION"))});Se.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return Se.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Se.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")});Se.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return U0(Se.getNumber("WEBGL_VERSION"))});Se.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return B0(Se.getNumber("WEBGL_VERSION"))});Se.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){var n=Se.getBool("WEBGL_RENDER_FLOAT32_ENABLED");return n?4:0});Se.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",function(){return-1},function(n){if(n<0&&n!==-1)throw new Error("WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never "+("delete) or at least 0, but got "+n+"."))});function nP(n){const t=new Float32Array(n.length);for(let e=0;e{const s=R.backend_util.assertAndGetBroadcastShape(t,e),o=s.length,l=R.util.computeStrides(s),u=R.util.sizeFromShape(s),c=R.util.getTypedArrayFromDType(a,u),h=t.length,d=e.length,p=R.util.computeStrides(t),f=R.util.computeStrides(e),m=R.backend_util.getBroadcastDims(t,s),g=R.backend_util.getBroadcastDims(e,s);if(m.length+g.length===0)for(let v=0;vS[I]=0);const L=R.util.locToIndex(S,h,p),w=b.slice(-d);g.forEach(I=>w[I]=0);const N=R.util.locToIndex(w,d,f);c[v]=n(i[L],r[N])}return[c,s]}}const iP=Od((n,t)=>n+t);function Jr(n){return(t,e,i)=>{const r=R.util.getTypedArrayFromDType(e,t.length);for(let a=0;aMath.ceil(n));const aP=Jr(n=>Math.exp(n));const sP=Jr(n=>Math.expm1(n));const oP=Jr(n=>Math.floor(n));const lP=Jr(n=>Math.log(n));function uP(n,t,e,i){const r=R.util.getTypedArrayFromDType(i,R.util.sizeFromShape(e));for(let a=0;ao&&(o=u)}r[a]=o}return r}const cP=Od((n,t)=>n*t);const hP=Jr(n=>1/Math.sqrt(n));function dP(n,t,e,i,r){const a=R.slice_util.isSliceContinous(i,t,e),s=R.util.sizeFromShape(e),o=R.util.computeStrides(i);if(a){const u=R.slice_util.computeFlatOffset(t,o);return n.subarray(u,u+s)}const l=R.util.getTypedArrayFromDType(r,s);for(let u=0;um+t[g]),f=R.util.locToIndex(p,i.length,o);l[u]=n[f]}return l}const pP=Od((n,t)=>n-t);function fP(n,t,e,i,r){const a=t.length,s=R.util.sizeFromShape(t),o=R.util.computeStrides(t),l=R.util.computeStrides(r),u=R.util.getTypedArrayFromDType(e,R.util.sizeFromShape(r));for(let c=0;c{for(let g=0;ge||t>e){var i="["+n+"x"+t+"]",r="["+e+"x"+e+"]";throw new Error("Requested texture size "+i+" greater than WebGL maximum on this browser / GPU "+r+".")}}function A0(n){return jn(n,function(){return n.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function Nd(n,t,e,i,r,a,s){var o=n.getAttribLocation(t,e);return o===-1?!1:(ce(n,function(){return n.bindBuffer(n.ARRAY_BUFFER,i)}),ce(n,function(){return n.vertexAttribPointer(o,r,n.FLOAT,!1,a,s)}),ce(n,function(){return n.enableVertexAttribArray(o)}),!0)}function N0(n,t,e){T0(n,e),ce(n,function(){return n.activeTexture(n.TEXTURE0+e)}),ce(n,function(){return n.bindTexture(n.TEXTURE_2D,t)})}function J_(n,t){T0(n,t),ce(n,function(){return n.activeTexture(n.TEXTURE0+t)}),ce(n,function(){return n.bindTexture(n.TEXTURE_2D,null)})}function x0(n,t,e){return jn(n,function(){return n.getUniformLocation(t,e)},'uniform "'+e+'" not present in program.')}function C0(n,t,e){return n.getUniformLocation(t,e)}function R0(n,t,e,i){ce(n,function(){return N0(n,t,i)}),ce(n,function(){return n.uniform1i(e,i)})}function Z_(n){ce(n,function(){return n.bindFramebuffer(n.FRAMEBUFFER,null)}),ce(n,function(){return n.viewport(0,0,n.canvas.width,n.canvas.height)}),ce(n,function(){return n.scissor(0,0,n.canvas.width,n.canvas.height)})}function Ro(n,t,e){ce(n,function(){return n.bindFramebuffer(n.FRAMEBUFFER,e)}),ce(n,function(){return n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t,0)})}function xd(n,t){ce(n,function(){return n.bindFramebuffer(n.FRAMEBUFFER,t)}),ce(n,function(){return n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,null,0)})}function Xa(n){var t=n.checkFramebufferStatus(n.FRAMEBUFFER);if(t!==n.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+O0(n,t))}function O0(n,t){switch(t){case n.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case n.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+t}}function jn(n,t,e){var i=ce(n,function(){return t()});if(i==null)throw new Error(e);return i}function T0(n,t){var e=n.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,i=t+n.TEXTURE0;if(ie){var r="[gl.TEXTURE0, gl.TEXTURE"+e+"]";throw new Error("textureUnit must be in "+r+".")}}function or(n,t){return t===void 0&&(t=2),R.util.sizeFromShape(n.slice(0,n.length-t))}function lr(n){if(n.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[n.length>1?n[n.length-2]:1,n[n.length-1]]}function Oo(n){var t=[1,1,1],e=n.length===0||n.length===1&&n[0]===1;return e||(t=[or(n)].concat(lr(n))),t}function E0(n,t){var e;t===void 0&&(t=!1);var i=R.env().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(i=i*2,n=n.map(function(u,c){return c>=n.length-2?R.util.nearestLargerEven(n[c]):n[c]}),n.length===1&&(n=[2,n[0]])),n.length!==2){var r=R.util.squeezeShape(n);n=r.newShape}var a=R.util.sizeFromShape(n);if(n.length<=1&&a<=i)return[1,a];if(n.length===2&&n[0]<=i&&n[1]<=i)return n;if(n.length===3&&n[0]*n[1]<=i&&n[2]<=i)return[n[0]*n[1],n[2]];if(n.length===3&&n[0]<=i&&n[1]*n[2]<=i)return[n[0],n[1]*n[2]];if(n.length===4&&n[0]*n[1]*n[2]<=i&&n[3]<=i)return[n[0]*n[1]*n[2],n[3]];if(n.length===4&&n[0]<=i&&n[1]*n[2]*n[3]<=i)return[n[0],n[1]*n[2]*n[3]];if(t){var s=or(n),o=2,l=2;return n.length&&(e=lr(n),o=e[0],l=e[1]),a=s*(o/2)*(l/2),R.util.sizeToSquarishShape(a).map(function(u){return u*2})}return R.util.sizeToSquarishShape(a)}function Eo(n){return n%2===0}function Ja(n,t){if(n=n.slice(-2),t=t.slice(-2),R.util.arraysEqual(n,t))return!0;if(!n.length||!t.length)return!0;if(n[0]===0||n[1]===0||t[0]===0||t[1]===0)return!0;if(n.length!==t.length){var e=n.slice(-1)[0],i=t.slice(-1)[0];if(e===i)return!0;if(Eo(e)&&Eo(i)&&(n[0]===1||t[0]===1))return!0}return n[1]===t[1]&&Eo(n[0])&&Eo(t[0])}var Do,ko;function D0(n){if(Do==null){var t=Wn(n);Do=t.getParameter(t.MAX_TEXTURE_SIZE)}return Do}function Q_(){Do=null}function eP(){ko=null}function k0(n){if(ko==null){var t=Wn(n);ko=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,ko)}function F0(n){if(n===0)return 0;var t,e=Wn(n);return nn(e,"EXT_disjoint_timer_query_webgl2")&&n===2?t=2:nn(e,"EXT_disjoint_timer_query")?t=1:t=0,t}function nn(n,t){var e=n.getExtension(t);return e!=null}function Cd(n){try{var t=Wn(n);if(t!=null)return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function W0(n){if(n===0)return!1;var t=Wn(n);if(n===1){if(!nn(t,"OES_texture_float"))return!1}else if(!nn(t,"EXT_color_buffer_float"))return!1;var e=Rd(t);return e}function U0(n){if(n===0)return!1;var t=Wn(n);if(n===1){if(!nn(t,"OES_texture_float"))return!1;if(!nn(t,"WEBGL_color_buffer_float"))return!1}else{if(nn(t,"EXT_color_buffer_float"))return Rd(t);var e="EXT_color_buffer_half_float";if(nn(t,e)){var i=t.getExtension(e);return tP(t,i)}return!1}var r=Rd(t);return r}function Rd(n){var t=Td(n),e=n.createTexture();n.bindTexture(n.TEXTURE_2D,e);var i=1,r=1;n.texImage2D(n.TEXTURE_2D,0,t.internalFormatFloat,i,r,0,t.textureFormatFloat,t.textureTypeFloat,null);var a=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,a),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,e,0);var s=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(e),n.deleteFramebuffer(a),s}function tP(n,t){var e=Td(n,t),i=n.createTexture();n.bindTexture(n.TEXTURE_2D,i);var r=1,a=1;n.texImage2D(n.TEXTURE_2D,0,e.internalFormatHalfFloat,r,a,0,e.textureFormatFloat,e.textureTypeHalfFloat,null);var s=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,s),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,i,0);var o=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(i),n.deleteFramebuffer(s),o}function B0(n){if(n!==2)return!1;var t=Wn(n),e=t.fenceSync!=null;return e}function Xr(n,t){Array.isArray(n)||(n=[n]),n.forEach(function(e){e!=null&&R.util.assert(e.dtype!=="complex64",function(){return t+" does not support complex64 tensors in the WebGL backend."})})}var nP={__proto__:null,callAndCheck:ce,canBeRepresented:m0,getWebGLErrorMessage:f0,getExtensionOrThrow:$a,createVertexShader:g0,createFragmentShader:v0,createProgram:y0,linkProgram:b0,validateProgram:Co,createStaticVertexBuffer:w0,createStaticIndexBuffer:S0,getNumChannels:X_,createTexture:L0,validateTextureSize:I0,createFramebuffer:A0,bindVertexBufferToProgramAttribute:Nd,bindTextureUnit:N0,unbindTextureUnit:J_,getProgramUniformLocationOrThrow:x0,getProgramUniformLocation:C0,bindTextureToProgramUniformSampler:R0,bindCanvasToFramebuffer:Z_,bindColorTextureToFramebuffer:Ro,unbindColorTextureFromFramebuffer:xd,validateFramebuffer:Xa,getFramebufferErrorMessage:O0,getBatchDim:or,getRowsCols:lr,getShapeAs3D:Oo,getTextureShapeFromLogicalShape:E0,isReshapeFree:Ja,getWebGLMaxTextureSize:D0,resetMaxTextureSize:Q_,resetMaxTexturesInShader:eP,getMaxTexturesInShader:k0,getWebGLDisjointQueryTimerVersion:F0,hasExtension:nn,isWebGLVersionEnabled:Cd,isCapableOfRenderingToFloatTexture:W0,isDownloadFloatTextureEnabled:U0,isWebGLFenceEnabled:B0,assertNotComplex:Xr};var Se=R.env();Se.registerFlag("HAS_WEBGL",function(){return Se.getNumber("WEBGL_VERSION")>0});Se.registerFlag("WEBGL_VERSION",function(){return Cd(2)?2:Cd(1)?1:0});Se.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",function(){return!1});Se.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return Se.get("WEBGL_VERSION")===2});Se.registerFlag("WEBGL_CPU_FORWARD",function(){return!0});Se.registerFlag("WEBGL_FORCE_F16_TEXTURES",function(){return!1});Se.registerFlag("WEBGL_PACK",function(){return Se.getBool("HAS_WEBGL")});Se.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return Se.getBool("WEBGL_PACK")});Se.registerFlag("WEBGL_PACK_CLIP",function(){return Se.getBool("WEBGL_PACK")});Se.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return!1});Se.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return Se.getBool("WEBGL_PACK")});Se.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",function(){return Se.getBool("WEBGL_PACK")});Se.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return Se.getBool("WEBGL_PACK")});Se.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return Se.getBool("WEBGL_PACK")});Se.registerFlag("WEBGL_PACK_REDUCE",function(){return Se.getBool("WEBGL_PACK")});Se.registerFlag("WEBGL_LAZILY_UNPACK",function(){return Se.getBool("WEBGL_PACK")});Se.registerFlag("WEBGL_CONV_IM2COL",function(){return Se.getBool("WEBGL_PACK")});Se.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return D0(Se.getNumber("WEBGL_VERSION"))});Se.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return k0(Se.getNumber("WEBGL_VERSION"))});Se.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var n=Se.getNumber("WEBGL_VERSION");return n===0?0:F0(n)});Se.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return Se.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!R.device_util.isMobile()});Se.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",function(){return W0(Se.getNumber("WEBGL_VERSION"))});Se.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return Se.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Se.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")});Se.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return U0(Se.getNumber("WEBGL_VERSION"))});Se.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return B0(Se.getNumber("WEBGL_VERSION"))});Se.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){var n=Se.getBool("WEBGL_RENDER_FLOAT32_ENABLED");return n?4:0});Se.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",function(){return-1},function(n){if(n<0&&n!==-1)throw new Error("WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never "+("delete) or at least 0, but got "+n+"."))});function iP(n){const t=new Float32Array(n.length);for(let e=0;e{const s=R.backend_util.assertAndGetBroadcastShape(t,e),o=s.length,l=R.util.computeStrides(s),u=R.util.sizeFromShape(s),c=R.util.getTypedArrayFromDType(a,u),h=t.length,d=e.length,p=R.util.computeStrides(t),f=R.util.computeStrides(e),m=R.backend_util.getBroadcastDims(t,s),g=R.backend_util.getBroadcastDims(e,s);if(m.length+g.length===0)for(let v=0;vS[I]=0);const L=R.util.locToIndex(S,h,p),w=b.slice(-d);g.forEach(I=>w[I]=0);const N=R.util.locToIndex(w,d,f);c[v]=n(i[L],r[N])}return[c,s]}}const rP=Od((n,t)=>n+t);function Jr(n){return(t,e,i)=>{const r=R.util.getTypedArrayFromDType(e,t.length);for(let a=0;aMath.ceil(n));const sP=Jr(n=>Math.exp(n));const oP=Jr(n=>Math.expm1(n));const lP=Jr(n=>Math.floor(n));const uP=Jr(n=>Math.log(n));function cP(n,t,e,i){const r=R.util.getTypedArrayFromDType(i,R.util.sizeFromShape(e));for(let a=0;ao&&(o=u)}r[a]=o}return r}const hP=Od((n,t)=>n*t);const dP=Jr(n=>1/Math.sqrt(n));function pP(n,t,e,i,r){const a=R.slice_util.isSliceContinous(i,t,e),s=R.util.sizeFromShape(e),o=R.util.computeStrides(i);if(a){const u=R.slice_util.computeFlatOffset(t,o);return n.subarray(u,u+s)}const l=R.util.getTypedArrayFromDType(r,s);for(let u=0;um+t[g]),f=R.util.locToIndex(p,i.length,o);l[u]=n[f]}return l}const fP=Od((n,t)=>n-t);function mP(n,t,e,i,r){const a=t.length,s=R.util.sizeFromShape(t),o=R.util.computeStrides(t),l=R.util.computeStrides(r),u=R.util.getTypedArrayFromDType(e,R.util.sizeFromShape(r));for(let c=0;c{for(let g=0;g":"<",l=i?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=` + `}return n}();var DP=function(){function n(t,e,i){this.variableNames=["A"];var r=t.windowSize,a=t.batchSize,s=t.outSize;i||this.variableNames.push("bestIndicesA"),this.outputShape=[a,s];var o=e==="max"?">":"<",l=i?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=` void main() { ivec2 coords = getOutputCoords(); int batch = coords[0]; @@ -69,7 +69,7 @@ Hi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed thi } setOutput(float(bestIndex)); } - `}return n}();function _0(n,t){return["x","y","z","w","u","v"].slice(0,t).map(function(e){return n+"."+e})}function $t(n,t){return t===1?[n]:_0(n,t)}function DP(n,t){if(n===1)return"rc";for(var e="",i=0;i 0.0 || val < 0.0) ? false : val != 0.0; } @@ -157,22 +157,22 @@ Hi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed thi return c / 255.0; } -`;var M0=R.backend_util.getBroadcastDims;function MP(n,t,e,i){var r=[];n.forEach(function(f){var m=R.util.sizeFromShape(f.shapeInfo.logicalShape);f.shapeInfo.isUniform?r.push("uniform float "+f.name+(m>1?"["+m+"]":"")+";"):(r.push("uniform sampler2D "+f.name+";"),r.push("uniform int offset"+f.name+";"))});var a=r.join(` -`),s=n.map(function(f){return kP(f,t,i)}).join(` -`),o=t.texShape,l=kt(),u=UP(l),c,h,d=_P(l);t.isPacked?(c=FP(t.logicalShape,o),h=zP(l)):(c=WP(t.logicalShape,o),h=BP(l)),i&&(d+=PP);var p=[d,u,h,a,c,s,e].join(` -`);return p}function Zr(n){var t=n.shapeInfo.logicalShape;switch(t.length){case 0:return HP(n);case 1:return VP(n);case 2:return qP(n);case 3:return GP(n);case 4:return YP(n);case 5:return KP(n);case 6:return jP(n);default:throw new Error(t.length+"-D input sampling is not yet supported")}}function H0(n){var t=n.shapeInfo.logicalShape;switch(t.length){case 0:return $P(n);case 1:return XP(n);case 2:return JP(n);case 3:return ZP(n);default:return QP(n)}}function kP(n,t,e){e===void 0&&(e=!1);var i="";e?i+=H0(n):i+=Zr(n);var r=n.shapeInfo.logicalShape,a=t.logicalShape;return r.length<=a.length&&(e?i+=e5(n,t):i+=t5(n,t)),i}function FP(n,t){switch(n.length){case 0:return V0();case 1:return n5(n,t);case 2:return a5(n,t);case 3:return i5(n,t);default:return r5(n,t)}}function WP(n,t){switch(n.length){case 0:return V0();case 1:return s5(n,t);case 2:return h5(n,t);case 3:return o5(n,t);case 4:return l5(n,t);case 5:return u5(n,t);case 6:return c5(n,t);default:throw new Error(n.length+"-D output sampling is not yet supported")}}function UP(n){return` +`;var M0=R.backend_util.getBroadcastDims;function HP(n,t,e,i){var r=[];n.forEach(function(f){var m=R.util.sizeFromShape(f.shapeInfo.logicalShape);f.shapeInfo.isUniform?r.push("uniform float "+f.name+(m>1?"["+m+"]":"")+";"):(r.push("uniform sampler2D "+f.name+";"),r.push("uniform int offset"+f.name+";"))});var a=r.join(` +`),s=n.map(function(f){return FP(f,t,i)}).join(` +`),o=t.texShape,l=kt(),u=BP(l),c,h,d=PP(l);t.isPacked?(c=WP(t.logicalShape,o),h=_P(l)):(c=UP(t.logicalShape,o),h=zP(l)),i&&(d+=MP);var p=[d,u,h,a,c,s,e].join(` +`);return p}function Zr(n){var t=n.shapeInfo.logicalShape;switch(t.length){case 0:return VP(n);case 1:return qP(n);case 2:return GP(n);case 3:return YP(n);case 4:return KP(n);case 5:return jP(n);case 6:return $P(n);default:throw new Error(t.length+"-D input sampling is not yet supported")}}function H0(n){var t=n.shapeInfo.logicalShape;switch(t.length){case 0:return XP(n);case 1:return JP(n);case 2:return ZP(n);case 3:return QP(n);default:return e5(n)}}function FP(n,t,e){e===void 0&&(e=!1);var i="";e?i+=H0(n):i+=Zr(n);var r=n.shapeInfo.logicalShape,a=t.logicalShape;return r.length<=a.length&&(e?i+=t5(n,t):i+=n5(n,t)),i}function WP(n,t){switch(n.length){case 0:return V0();case 1:return i5(n,t);case 2:return s5(n,t);case 3:return r5(n,t);default:return a5(n,t)}}function UP(n,t){switch(n.length){case 0:return V0();case 1:return o5(n,t);case 2:return d5(n,t);case 3:return l5(n,t);case 4:return u5(n,t);case 5:return c5(n,t);case 6:return h5(n,t);default:throw new Error(n.length+"-D output sampling is not yet supported")}}function BP(n){return` float sampleTexture(sampler2D textureSampler, vec2 uv) { return `+n.texture2D+`(textureSampler, uv).r; } - `}function BP(n){return` + `}function zP(n){return` void setOutput(float val) { `+n.output+` = vec4(val, 0, 0, 0); } - `}function zP(n){return` + `}function _P(n){return` void setOutput(vec4 val) { `+n.output+` = val; } - `}function _P(n){var t=n.version+` + `}function PP(n){var t=n.version+` precision highp float; precision highp int; precision highp sampler2D; @@ -227,10 +227,10 @@ Hi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed thi return fract((p3.x + p3.y) * p3.z); } - `+d5+` `+p5+` `+f5+` - `;return t}var d5=` + `+m5+` + `;return t}var p5=` vec2 uvFromFlat(int texNumR, int texNumC, int index) { int texR = index / texNumC; int texC = index - texR * texNumC; @@ -242,7 +242,7 @@ vec2 packedUVfrom1D(int texNumR, int texNumC, int index) { int texC = texelIndex - texR * texNumC; return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); } -`,p5=` +`,f5=` vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR, int texNumC, int row, int col) { int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2); @@ -250,7 +250,7 @@ vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR, int texC = texelIndex - texR * texNumC; return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); } -`,f5=` +`,m5=` vec2 packedUVfrom3D(int texNumR, int texNumC, int texelsInBatch, int texelsInLogicalRow, int b, int row, int col) { @@ -259,7 +259,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC, int texC = index - texR * texNumC; return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR); } -`,PP=` +`,MP=` float getChannel(vec4 frag, vec2 innerDims) { vec2 modCoord = mod(innerDims, 2.); return modCoord.x == 0. ? @@ -274,7 +274,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC, int getOutputCoords() { return 0; } - `}function n5(n,t){var e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return e[0]===1?` + `}function i5(n,t){var e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return e[0]===1?` int getOutputCoords() { return 2 * int(resultUV.x * `+e[1]+`.0); } @@ -288,7 +288,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC, vec2(`+e[0]+", "+e[1]+`)); return 2 * (resTexRC.x * `+e[1]+` + resTexRC.y); } - `}function s5(n,t){return t[0]===1?` + `}function o5(n,t){return t[0]===1?` int getOutputCoords() { return int(resultUV.x * `+t[1]+`.0); } @@ -302,7 +302,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC, vec2(`+t[0]+", "+t[1]+`)); return resTexRC.x * `+t[1]+` + resTexRC.y; } - `}function i5(n,t){var e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],i=Math.ceil(n[2]/2),r=i*Math.ceil(n[1]/2);return` + `}function r5(n,t){var e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],i=Math.ceil(n[2]/2),r=i*Math.ceil(n[1]/2);return` ivec3 getOutputCoords() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(`+e[0]+", "+e[1]+`)); @@ -316,7 +316,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC, return ivec3(b, r, c); } - `}function o5(n,t){var e=ur(["r","c","d"],n);return` + `}function l5(n,t){var e=ur(["r","c","d"],n);return` ivec3 getOutputCoords() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(`+t[0]+", "+t[1]+`)); @@ -324,7 +324,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC, `+e+` return ivec3(r, c, d); } - `}function r5(n,t){for(var e=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],i=Math.ceil(n[n.length-1]/2),r=i*Math.ceil(n[n.length-2]/2),a=r,s="",o="b, r, c",l=2;l=1?c="coords = 0;":c=o.map(function(L){return"coords."+h[L+u]+" = 0;"}).join(` + `}function t5(n,t){var e=n.name,i=e.charAt(0).toUpperCase()+e.slice(1),r="get"+i+"AtOutCoords",a=n.shapeInfo.logicalShape.length,s=t.logicalShape.length,o=M0(n.shapeInfo.logicalShape,t.logicalShape),l=Je(s),u=s-a,c,h=["x","y","z","w","u","v"];a===0?c="":s<2&&o.length>=1?c="coords = 0;":c=o.map(function(L){return"coords."+h[L+u]+" = 0;"}).join(` `);var d="";s<2&&a>0?d="coords":d=n.shapeInfo.logicalShape.map(function(L,w){return"coords."+h[w+u]}).join(", ");var p="return outputValue;",f=R.util.sizeFromShape(n.shapeInfo.logicalShape),m=f===1,g=R.util.sizeFromShape(t.logicalShape),v=g===1;if(a===1&&!m&&!v)p=` return vec4(outputValue.xy, outputValue.xy); `;else if(m&&!v)s===1?p=` @@ -704,7 +704,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC, vec4 outputValue = get`+i+"("+d+`); `+p+` } - `}function t5(n,t){var e=n.name,i=e.charAt(0).toUpperCase()+e.slice(1),r="get"+i+"AtOutCoords",a=t.texShape,s=n.shapeInfo.texShape,o=n.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!n.shapeInfo.isUniform&&o===l&&n.shapeInfo.flatOffset==null&&R.util.arraysEqual(s,a))return` + `}function n5(n,t){var e=n.name,i=e.charAt(0).toUpperCase()+e.slice(1),r="get"+i+"AtOutCoords",a=t.texShape,s=n.shapeInfo.texShape,o=n.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!n.shapeInfo.isUniform&&o===l&&n.shapeInfo.flatOffset==null&&R.util.arraysEqual(s,a))return` float `+r+`() { return sampleTexture(`+e+`, resultUV); } @@ -715,7 +715,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC, `+d+` return get`+i+"("+f+`); } - `}function Je(n){if(n<=1)return"int";if(n===2)return"ivec2";if(n===3)return"ivec3";if(n===4)return"ivec4";if(n===5)return"ivec5";if(n===6)return"ivec6";throw Error("GPU for rank "+n+" is not yet supported")}function ea(n,t){var e=JSON.parse(JSON.stringify(n));return e.shapeInfo.logicalShape=t,e}function ta(n,t){return t.map(function(e){return n[e]}).join(", ")}var m5=function(){function n(t,e,i,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,R.util.assert(t.length>2,function(){return"Packed arg"+(i.charAt(0).toUpperCase()+i.slice(1))+" supports only inputs with rank above 2."});var a=t[t.length-1],s=Math.ceil(a/e);this.outputShape=t.slice(0,-1),s>1&&this.outputShape.push(s),r||this.variableNames.push("bestIndicesA");var o=this.outputShape,l=o.length,u=Je(l),c=$t("coords",l),h,d;if(s===1){d=l+1;var p=Je(d);h=` + `}function Je(n){if(n<=1)return"int";if(n===2)return"ivec2";if(n===3)return"ivec3";if(n===4)return"ivec4";if(n===5)return"ivec5";if(n===6)return"ivec6";throw Error("GPU for rank "+n+" is not yet supported")}function ea(n,t){var e=JSON.parse(JSON.stringify(n));return e.shapeInfo.logicalShape=t,e}function ta(n,t){return t.map(function(e){return n[e]}).join(", ")}var g5=function(){function n(t,e,i,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,R.util.assert(t.length>2,function(){return"Packed arg"+(i.charAt(0).toUpperCase()+i.slice(1))+" supports only inputs with rank above 2."});var a=t[t.length-1],s=Math.ceil(a/e);this.outputShape=t.slice(0,-1),s>1&&this.outputShape.push(s),r||this.variableNames.push("bestIndicesA");var o=this.outputShape,l=o.length,u=Je(l),c=$t("coords",l),h,d;if(s===1){d=l+1;var p=Je(d);h=` `+p+" sourceLocR = "+p+"("+c.join()+`, 0); ++`+c[l-1]+`; `+p+" sourceLocG = "+p+"("+c.join()+`, 0); @@ -777,7 +777,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC, } setOutput(bestIndex); } - `}return n}();var g5=function(){function n(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,i=t.filterWidth,r=t.strideHeight,a=t.strideWidth,s=t.dilationHeight,o=t.dilationWidth,l=t.effectiveFilterHeight,u=t.effectiveFilterWidth,c=l-1-t.padInfo.top,h=u-1-t.padInfo.left,d=1/(e*i);this.userCode=` + `}return n}();var v5=function(){function n(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,i=t.filterWidth,r=t.strideHeight,a=t.strideWidth,s=t.dilationHeight,o=t.dilationWidth,l=t.effectiveFilterHeight,u=t.effectiveFilterWidth,c=l-1-t.padInfo.top,h=u-1-t.padInfo.left,d=1/(e*i);this.userCode=` const ivec2 pads = ivec2(`+c+", "+h+`); const float avgMultiplier = float(`+d+`); @@ -819,7 +819,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC, } setOutput(dotProd); } - `}return n}(),v5=function(){function n(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterDepth,i=t.filterHeight,r=t.filterWidth,a=t.strideDepth,s=t.strideHeight,o=t.strideWidth,l=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,h=t.effectiveFilterDepth,d=t.effectiveFilterHeight,p=t.effectiveFilterWidth,f=h-1-t.padInfo.front,m=d-1-t.padInfo.top,g=p-1-t.padInfo.left,v=1/(e*i*r);this.userCode=` + `}return n}(),y5=function(){function n(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterDepth,i=t.filterHeight,r=t.filterWidth,a=t.strideDepth,s=t.strideHeight,o=t.strideWidth,l=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,h=t.effectiveFilterDepth,d=t.effectiveFilterHeight,p=t.effectiveFilterWidth,f=h-1-t.padInfo.front,m=d-1-t.padInfo.top,g=p-1-t.padInfo.left,v=1/(e*i*r);this.userCode=` const ivec3 pads = ivec3(`+f+", "+m+", "+g+`); const float avgMultiplier = float(`+v+`); @@ -891,7 +891,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC, `}return n}();var Y0=` if (isnan(a)) return a; if (isnan(b)) return b; -`,Dd="return a + b;",kd="return a - b;",K0="return a * b;",y5=` +`,Dd="return a + b;",kd="return a - b;",K0="return a * b;",b5=` float s = sign(a) * sign(b); int ia = round(a); int ib = round(b); @@ -901,7 +901,7 @@ vec2 packedUVfrom3D(int texNumR, int texNumC, } else { return NAN; } -`,b5=` +`,w5=` if(a < 0.0 && floor(b) < b){ return NAN; } @@ -910,12 +910,12 @@ if (b == 0.0) { } return (round(mod(b, 2.0)) != 1) ? pow(abs(a), b) : sign(a) * pow(abs(a), b); -`,w5="return float(a == b);",S5="return float(a != b);",L5="return float(a < b);",I5="return float(a <= b);",A5="return float(a > b);",T5="return float(a >= b);",N5="return float(a >= 1.0 && b >= 1.0);",x5="return float(a >= 1.0 || b >= 1.0);",C5=Y0+` +`,S5="return float(a == b);",L5="return float(a != b);",I5="return float(a < b);",A5="return float(a <= b);",T5="return float(a > b);",N5="return float(a >= b);",x5="return float(a >= 1.0 && b >= 1.0);",C5="return float(a >= 1.0 || b >= 1.0);",R5=Y0+` return max(a, b); -`,R5=Y0+` +`,O5=Y0+` return min(a, b); -`,O5=`if (b == 0.0) return NAN; - return mod(a, b);`,E5="return (b >= 1.0) ? a : a * (b + 1.0);",j0="return (a < 0.) ? b * a : a;",wt=function(){function n(t,e,i){this.variableNames=["A","B"],this.outputShape=R.backend_util.assertAndGetBroadcastShape(e,i),this.userCode=` +`,E5=`if (b == 0.0) return NAN; + return mod(a, b);`,D5="return (b >= 1.0) ? a : a * (b + 1.0);",j0="return (a < 0.) ? b * a : a;",wt=function(){function n(t,e,i){this.variableNames=["A","B"],this.outputShape=R.backend_util.assertAndGetBroadcastShape(e,i),this.userCode=` float binaryOperation(float a, float b) { `+t+` } @@ -930,7 +930,7 @@ return (round(mod(b, 2.0)) != 1) ? result.g = isNaN.g > 0. ? NAN : result.g; result.b = isNaN.b > 0. ? NAN : result.b; result.a = isNaN.a > 0. ? NAN : result.a; -`,D5=` +`,k5=` ivec4 ia = round(a); ivec4 ib = round(b); bvec4 cond = notEqual(ib, ivec4(0)); @@ -951,7 +951,7 @@ return (round(mod(b, 2.0)) != 1) ? result[3] = idiv(ia[3], ib[3], s[3]); } return vec4(result); -`,k5=` +`,F5=` // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise. vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1))); vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1); @@ -970,41 +970,41 @@ return (round(mod(b, 2.0)) != 1) ? `,$0=` vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); -`,F5=` +`,W5=` vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.))); return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0)))); -`,W5=` - return vec4(equal(a, b)); `,U5=` - return vec4(notEqual(a, b)); + return vec4(equal(a, b)); `,B5=` - return vec4(lessThan(a, b)); + return vec4(notEqual(a, b)); `,z5=` - return vec4(lessThanEqual(a, b)); + return vec4(lessThan(a, b)); `,_5=` - return vec4(greaterThan(a, b)); + return vec4(lessThanEqual(a, b)); `,P5=` - return vec4(greaterThanEqual(a, b)); + return vec4(greaterThan(a, b)); `,M5=` + return vec4(greaterThanEqual(a, b)); +`,H5=` return vec4( vec4(greaterThanEqual(a, vec4(1.0))) * vec4(greaterThanEqual(b, vec4(1.0)))); -`,H5=` +`,V5=` return min( vec4(greaterThanEqual(a, vec4(1.0))) + vec4(greaterThanEqual(b, vec4(1.0))), vec4(1.0)); -`,V5=` +`,q5=` vec4 result = vec4(max(a, b)); vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0)); `+Fo+` return result; -`,q5=` +`,G5=` vec4 result = vec4(min(a, b)); vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0)); `+Fo+` return result; -`,G5=` +`,Y5=` vec4 result = mod(a, b); vec4 isNaN = vec4(equal(b, vec4(0.0))); `+Fo+` @@ -1041,7 +1041,7 @@ return (round(mod(b, 2.0)) != 1) ? setOutput(result); } - `}return n}();var Y5=function(){function n(t){this.variableNames=["A"],this.outputShape=t,this.userCode=` + `}return n}();var K5=function(){function n(t){this.variableNames=["A"],this.outputShape=t,this.userCode=` uniform float minVal; uniform float maxVal; @@ -1054,7 +1054,7 @@ return (round(mod(b, 2.0)) != 1) ? setOutput(clamp(value, minVal, maxVal)); } - `}return n.prototype.getCustomSetupFunc=function(t,e){var i=this;return function(r,a){i.minLoc==null&&(i.minLoc=r.getUniformLocationNoThrow(a,"minVal"),i.maxLoc=r.getUniformLocationNoThrow(a,"maxVal")),r.gl.uniform1f(i.minLoc,t),r.gl.uniform1f(i.maxLoc,e)}},n}();var K5=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode=` + `}return n.prototype.getCustomSetupFunc=function(t,e){var i=this;return function(r,a){i.minLoc==null&&(i.minLoc=r.getUniformLocationNoThrow(a,"minVal"),i.maxLoc=r.getUniformLocationNoThrow(a,"maxVal")),r.gl.uniform1f(i.minLoc,t),r.gl.uniform1f(i.maxLoc,e)}},n}();var j5=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode=` uniform float minVal; uniform float maxVal; @@ -1068,7 +1068,7 @@ return (round(mod(b, 2.0)) != 1) ? setOutput(clamp(value, vec4(minVal), vec4(maxVal))); } - `}return n.prototype.getCustomSetupFunc=function(t,e){var i=this;return function(r,a){i.minLoc==null&&(i.minLoc=r.getUniformLocationNoThrow(a,"minVal"),i.maxLoc=r.getUniformLocationNoThrow(a,"maxVal")),r.gl.uniform1f(i.minLoc,t),r.gl.uniform1f(i.maxLoc,e)}},n}();var j5=function(){function n(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode=` + `}return n.prototype.getCustomSetupFunc=function(t,e){var i=this;return function(r,a){i.minLoc==null&&(i.minLoc=r.getUniformLocationNoThrow(a,"minVal"),i.maxLoc=r.getUniformLocationNoThrow(a,"maxVal")),r.gl.uniform1f(i.minLoc,t),r.gl.uniform1f(i.maxLoc,e)}},n}();var $5=function(){function n(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode=` void main() { float re = abs(getRealAtOutCoords()); float im = abs(getImagAtOutCoords()); @@ -1081,7 +1081,7 @@ return (round(mod(b, 2.0)) != 1) ? mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx)) ); } - `}return n}();var $5=function(){function n(t){this.outputShape=[],this.outputShape=R.backend_util.computeOutShape(t,1),this.variableNames=t.map(function(l,u){return"T"+u});var e=new Array(t.length-1);e[0]=t[0][1];for(var i=1;i1?[""+(o-1)/(h-1),"(y2-y1) * height_ratio","y1*"+m+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+m],b=v[0],S=v[1],L=v[2],w=d>1?[""+(l-1)/(d-1),"(x2-x1) * width_ratio","x1*"+g+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+g],N=w[0],I=w[1],C=w[2];this.userCode=` + `}return n}();var a9=function(){function n(t,e,i,r,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var s=t[0],o=t[1],l=t[2],u=t[3],c=e[0],h=i[0],d=i[1];this.outputShape=[c,h,d,u];var p=r==="bilinear"?1:0,f=[o-1+".0",l-1+".0"],m=f[0],g=f[1],v=h>1?[""+(o-1)/(h-1),"(y2-y1) * height_ratio","y1*"+m+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+m],b=v[0],S=v[1],L=v[2],w=d>1?[""+(l-1)/(d-1),"(x2-x1) * width_ratio","x1*"+g+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+g],N=w[0],I=w[1],C=w[2];this.userCode=` const float height_ratio = float(`+b+`); const float width_ratio = float(`+N+`); void main() { @@ -1898,7 +1898,7 @@ return (round(mod(b, 2.0)) != 1) ? } setOutput(val); } - `}return n.prototype.getCustomSetupFunc=function(t){var e=this;return function(i,r){e.index==null&&(e.index=i.getUniformLocation(r,"index")),i.gl.uniform1f(e.index,t)}},n}();function Q0(n,t){if(n===1)return""+t;if(n===2)return t+".x, "+t+".y";if(n===3)return t+".x, "+t+".y, "+t+".z";if(n===4)return t+".x, "+t+".y, "+t+".z, "+t+".w";throw Error("Cumulative sum for rank "+n+" is not yet supported")}function eS(n,t){if(n===1)return""+t;if(n===2)return t+".y";if(n===3)return t+".z";if(n===4)return t+".w";throw Error("Cumulative sum for rank "+n+" is not yet supported")}var a9=function(){function n(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Ya.DENSE;var e=ja(t),i=kt();this.outputShape=t,this.userCode=` + `}return n.prototype.getCustomSetupFunc=function(t){var e=this;return function(i,r){e.index==null&&(e.index=i.getUniformLocation(r,"index")),i.gl.uniform1f(e.index,t)}},n}();function Q0(n,t){if(n===1)return""+t;if(n===2)return t+".x, "+t+".y";if(n===3)return t+".x, "+t+".y, "+t+".z";if(n===4)return t+".x, "+t+".y, "+t+".z, "+t+".w";throw Error("Cumulative sum for rank "+n+" is not yet supported")}function eS(n,t){if(n===1)return""+t;if(n===2)return t+".y";if(n===3)return t+".z";if(n===4)return t+".w";throw Error("Cumulative sum for rank "+n+" is not yet supported")}var s9=function(){function n(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Ya.DENSE;var e=ja(t),i=kt();this.outputShape=t,this.userCode=` ivec3 outCoordsFromFlatIndex(int index) { `+ur(["r","c","d"],t)+` return ivec3(r, c, d); @@ -1919,7 +1919,7 @@ return (round(mod(b, 2.0)) != 1) ? `+i.output+` = result; } - `}return n}();var s9=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Ya.DENSE;var e=ja(t),i=kt();this.outputShape=t,this.userCode=` + `}return n}();var o9=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Ya.DENSE;var e=ja(t),i=kt();this.outputShape=t,this.userCode=` ivec3 outCoordsFromFlatIndex(int index) { `+ur(["r","c","d"],t)+` return ivec3(r, c, d); @@ -1940,7 +1940,7 @@ return (round(mod(b, 2.0)) != 1) ? `+i.output+` = result; } - `}return n}();var o9=function(){function n(t,e,i){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=i,this.userCode=` + `}return n}();var l9=function(){function n(t,e,i){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=i,this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; @@ -1959,20 +1959,20 @@ return (round(mod(b, 2.0)) != 1) ? float result = `+this.getInputSamplingString()+`; setOutput(result); } - `}return n.prototype.getHeightCoordString=function(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"},n.prototype.getWidthCoordString=function(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"},n.prototype.getDepthCoordString=function(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"},n.prototype.getOutputDepthSize=function(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]},n.prototype.getInputSamplingString=function(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},n}();var l9=function(){function n(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode=` + `}return n.prototype.getHeightCoordString=function(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"},n.prototype.getWidthCoordString=function(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"},n.prototype.getDepthCoordString=function(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"},n.prototype.getOutputDepthSize=function(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]},n.prototype.getInputSamplingString=function(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},n}();var u9=function(){function n(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode=` void main() { ivec2 coords = getOutputCoords(); float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0; setOutput(val); } - `}return n}();var u9=function(){function n(t){this.variableNames=["A"],this.outTexUsage=tn.DOWNLOAD;var e=kt();this.outputShape=t,this.userCode=` + `}return n}();var c9=function(){function n(t){this.variableNames=["A"],this.outTexUsage=tn.DOWNLOAD;var e=kt();this.outputShape=t,this.userCode=` `+P0+` void main() { float x = getAAtOutCoords(); `+e.output+` = encode_float(x); } - `}return n}();var c9=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=tn.DOWNLOAD;var e=kt();this.outputShape=t,this.userCode=` + `}return n}();var h9=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=tn.DOWNLOAD;var e=kt();this.outputShape=t,this.userCode=` `+P0+` void main() { @@ -1980,7 +1980,7 @@ return (round(mod(b, 2.0)) != 1) ? float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z)); `+e.output+` = encode_float(x); } - `}return n}();var h9=function(){function n(t,e,i){i===void 0&&(i=!1),this.variableNames=["A"];var r=kt(),a=e[0],s=e[1];this.outputShape=t;var o="result";i&&(o="floor(result * 255. + 0.5)"),this.userCode=` + `}return n}();var d9=function(){function n(t,e,i){i===void 0&&(i=!1),this.variableNames=["A"];var r=kt(),a=e[0],s=e[1];this.outputShape=t;var o="result";i&&(o="floor(result * 255. + 0.5)"),this.userCode=` `+Ed(t)+` void main() { @@ -2010,7 +2010,7 @@ return (round(mod(b, 2.0)) != 1) ? `+r.output+" = vec4("+o+`, 0., 0., 0.); } - `}return n}();var d9=function(){function n(t,e,i){i===void 0&&(i=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var r=kt(),a=e[0],s=e[1];this.outputShape=t;var o="",l="result";i&&(l="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var c=0;c<=1;c++){var h=u*2+c;o+=` + `}return n}();var p9=function(){function n(t,e,i){i===void 0&&(i=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var r=kt(),a=e[0],s=e[1];this.outputShape=t;var o="",l="result";i&&(l="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var c=0;c<=1;c++){var h=u*2+c;o+=` localCoords = coords; if(localCoords[2] + `+c+" < "+t[2]+`) { localCoords[2] += `+c+`; @@ -2087,18 +2087,18 @@ return (round(mod(b, 2.0)) != 1) ? ivec2 coords = getOutputCoords(); setOutput(mulMatDFT(coords[0], coords[1])); } - `}return n}();var p9=function(){function n(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode=` + `}return n}();var f9=function(){function n(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode=` uniform float value; void main() { // Input can be obtained from uniform value. setOutput(value); } - `}return n.prototype.getCustomSetupFunc=function(t){var e=this;return function(i,r){e.valueLoc==null&&(e.valueLoc=i.getUniformLocationNoThrow(r,"value")),i.gl.uniform1f(e.valueLoc,t)}},n}();var m9=function(){function n(t,e,i){this.variableNames=["A","indices"];var r=t.slice();r[i]=e,this.outputShape=r,this.rank=r.length;var a=Je(this.rank),s=f9(t,i);this.userCode=` + `}return n.prototype.getCustomSetupFunc=function(t){var e=this;return function(i,r){e.valueLoc==null&&(e.valueLoc=i.getUniformLocationNoThrow(r,"value")),i.gl.uniform1f(e.valueLoc,t)}},n}();var g9=function(){function n(t,e,i){this.variableNames=["A","indices"];var r=t.slice();r[i]=e,this.outputShape=r,this.rank=r.length;var a=Je(this.rank),s=m9(t,i);this.userCode=` void main() { `+a+` resRC = getOutputCoords(); setOutput(getA(`+s+`)); } - `}return n}();function f9(n,t){var e=n.length;if(e>4)throw Error("Gather for rank "+e+" is not yet supported");if(e===1)return"int(getIndices(resRC))";for(var i=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[],a=0;a1?"strides[j]":"strides";this.userCode=` + `}return n}();function m9(n,t){var e=n.length;if(e>4)throw Error("Gather for rank "+e+" is not yet supported");if(e===1)return"int(getIndices(resRC))";for(var i=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[],a=0;a1?"strides[j]":"strides";this.userCode=` `+r+" strides = "+r+"("+this.strides+`); void main() { `+a+` coords = getOutputCoords(); @@ -2118,7 +2118,7 @@ return (round(mod(b, 2.0)) != 1) ? void main() { gl_Position = vec4(clipSpacePos, 1); resultUV = uv; - }`;return g0(n,e)}function aS(n){var t=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return w0(n,t)}function sS(n){var t=new Uint16Array([0,1,2,2,1,3]);return S0(n,t)}function Za(n,t,e,i,r,a){I0(t,e);var s=L0(n),o=n.TEXTURE_2D;return ce(n,function(){return n.bindTexture(o,s)}),ce(n,function(){return n.texParameteri(o,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE)}),ce(n,function(){return n.texParameteri(o,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)}),ce(n,function(){return n.texParameteri(o,n.TEXTURE_MIN_FILTER,n.NEAREST)}),ce(n,function(){return n.texParameteri(o,n.TEXTURE_MAG_FILTER,n.NEAREST)}),ce(n,function(){return n.texImage2D(o,0,i,t,e,0,r,a,null)}),ce(n,function(){return n.bindTexture(n.TEXTURE_2D,null)}),s}function Fd(n){return n.internalFormatFloat}function oS(n,t,e,i){var r=Ka(t,e),a=r[0],s=r[1];return Za(n,a,s,Fd(i),i.textureFormatFloat,n.FLOAT)}function Wd(n){return n.internalFormatHalfFloat}function lS(n,t,e,i){var r=Ka(t,e),a=r[0],s=r[1];return Za(n,a,s,Wd(i),i.textureFormatFloat,i.textureTypeHalfFloat)}function Ud(n){return n.downloadTextureFormat}function uS(n,t,e,i){var r=Ka(t,e),a=r[0],s=r[1];return Za(n,a,s,Ud(i),n.RGBA,n.UNSIGNED_BYTE)}function Bd(n){return n.internalFormatPackedFloat}function cS(n,t,e,i){var r=$r(t,e),a=r[0],s=r[1];return Za(n,a,s,Bd(i),n.RGBA,n.FLOAT)}function zd(n){return n.internalFormatPackedHalfFloat}function hS(n,t,e,i){var r=$r(t,e),a=r[0],s=r[1];return Za(n,a,s,zd(i),n.RGBA,i.textureTypeHalfFloat)}function dS(n,t,e){var i=0,r=3*4,a=3*4+2*4;ce(n,function(){return n.bindBuffer(n.ARRAY_BUFFER,e)});var s=Nd(n,t,"clipSpacePos",e,3,a,i);return s&&Nd(n,t,"uv",e,2,a,r)}function pS(n,t,e,i,r,a){ce(n,function(){return n.bindTexture(n.TEXTURE_2D,t)});var s,o,l;r instanceof Uint8Array?(s=new Uint8Array(e*i*4),o=n.UNSIGNED_BYTE,l=n.RGBA):(s=new Float32Array(e*i*4),o=n.FLOAT,l=a.internalFormatPackedFloat),s.set(r),ce(n,function(){return n.texImage2D(n.TEXTURE_2D,0,l,e,i,0,n.RGBA,o,s)}),ce(n,function(){return n.bindTexture(n.TEXTURE_2D,null)})}function fS(n,t,e){ce(n,function(){return n.bindTexture(n.TEXTURE_2D,t)}),e.data instanceof Uint8Array?ce(n,function(){return n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e.width,e.height,0,n.RGBA,n.UNSIGNED_BYTE,e.data)}):ce(n,function(){return n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,e)}),ce(n,function(){return n.bindTexture(n.TEXTURE_2D,null)})}function mS(n,t,e,i){var r=n.createBuffer();ce(n,function(){return n.bindBuffer(n.PIXEL_PACK_BUFFER,r)});var a=4,s=4,o=a*s*t*e;return ce(n,function(){return n.bufferData(n.PIXEL_PACK_BUFFER,o,n.STREAM_READ)}),ce(n,function(){return n.readPixels(0,0,e,t,n.RGBA,n.FLOAT,0)}),ce(n,function(){return n.bindBuffer(n.PIXEL_PACK_BUFFER,null)}),r}function gS(n,t,e){var i=n,r=new Float32Array(e);return i.bindBuffer(i.PIXEL_PACK_BUFFER,t),i.getBufferSubData(i.PIXEL_PACK_BUFFER,0,r),i.bindBuffer(i.PIXEL_PACK_BUFFER,null),r}function vS(n,t,e,i){var r=Ka(t,e),a=r[0],s=r[1],o=4,l=new Uint8Array(H_(t*e,o));return ce(n,function(){return n.readPixels(0,0,a,s,i.downloadTextureFormat,n.UNSIGNED_BYTE,l)}),new Float32Array(l.buffer)}function yS(n,t,e,i,r,a,s,o){var l=n,u=new Float32Array(V_(a,s));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}function bS(n,t,e){var i=new Float32Array(t*e*4);return ce(n,function(){return n.readPixels(0,0,e,t,n.RGBA,n.FLOAT,i)}),i}var v9={__proto__:null,createVertexShader:rS,createVertexBuffer:aS,createIndexBuffer:sS,getInternalFormatForFloat32MatrixTexture:Fd,createFloat32MatrixTexture:oS,getInternalFormatForFloat16MatrixTexture:Wd,createFloat16MatrixTexture:lS,getInternalFormatForUnsignedBytesMatrixTexture:Ud,createUnsignedBytesMatrixTexture:uS,getInternalFormatForPackedMatrixTexture:Bd,createPackedMatrixTexture:cS,getInternalFormatForFloat16PackedMatrixTexture:zd,createFloat16PackedMatrixTexture:hS,bindVertexProgramAttributeStreams:dS,uploadDenseMatrixToTexture:pS,uploadPixelDataToTexture:fS,createBufferFromOutputTexture:mS,downloadFloat32MatrixFromBuffer:gS,downloadByteEncodedFloatMatrixFromOutputTexture:vS,downloadPackedMatrixFromBuffer:yS,downloadMatrixFromPackedOutputTexture:bS};var wS=function(){function n(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=R.env().getNumber("WEBGL_VERSION");t!=null?(this.gl=t,p0(e,t)):this.gl=Wn(e);var i="WEBGL_color_buffer_float",r="EXT_color_buffer_half_float";if(R.env().getNumber("WEBGL_VERSION")===1){var a="OES_texture_float",s="OES_texture_half_float";if(this.textureFloatExtension=$a(this.gl,a),nn(this.gl,s))this.textureHalfFloatExtension=$a(this.gl,s);else if(R.env().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(i),nn(this.gl,r))this.colorBufferHalfFloatExtension=$a(this.gl,r);else if(R.env().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(i="EXT_color_buffer_float",nn(this.gl,i))this.colorBufferFloatExtension=this.gl.getExtension(i);else if(nn(this.gl,r))this.colorBufferHalfFloatExtension=this.gl.getExtension(r);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=aS(this.gl),this.indexBuffer=sS(this.gl),this.framebuffer=A0(this.gl),this.textureConfig=Td(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(n.prototype,"debug",{get:function(){return R.env().getBool("DEBUG")},enumerable:!0,configurable:!0}),n.prototype.dispose=function(){var t=this;if(this.disposed)return;this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");var e=this.gl;ce(e,function(){return e.finish()}),ce(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),ce(e,function(){return e.deleteFramebuffer(t.framebuffer)}),ce(e,function(){return e.bindBuffer(e.ARRAY_BUFFER,null)}),ce(e,function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)}),ce(e,function(){return e.deleteBuffer(t.indexBuffer)}),this.disposed=!0},n.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),oS(this.gl,t,e,this.textureConfig)},n.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),lS(this.gl,t,e,this.textureConfig)},n.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),uS(this.gl,t,e,this.textureConfig)},n.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),fS(this.gl,t,e)},n.prototype.uploadDenseMatrixToTexture=function(t,e,i,r){this.throwIfDisposed(),pS(this.gl,t,e,i,r,this.textureConfig)},n.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),hS(this.gl,t,e,this.textureConfig)},n.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),cS(this.gl,t,e,this.textureConfig)},n.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(xd(this.gl,this.framebuffer),this.outputTexture=null),ce(this.gl,function(){return e.gl.deleteTexture(t)})},n.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(t,e,i){var r=this;return this.downloadMatrixDriver(t,function(){return vS(r.gl,e,i,r.textureConfig)})},n.prototype.downloadPackedMatrixFromBuffer=function(t,e,i,r,a,s){return yS(this.gl,t,e,i,r,a,s,this.textureConfig)},n.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return gS(this.gl,t,e)},n.prototype.createBufferFromTexture=function(t,e,i){this.bindTextureToFrameBuffer(t);var r=mS(this.gl,e,i,this.textureConfig);return this.unbindTextureToFrameBuffer(),r},n.prototype.createAndWaitForFence=function(){var t=this.createFence(this.gl);return this.pollFence(t)},n.prototype.createFence=function(t){var e=this,i,r;if(R.env().getBool("WEBGL_FENCE_API_ENABLED")){var a=t,s=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),r=function(){var o=a.clientWaitSync(s,0,0);return o===a.ALREADY_SIGNALED||o===a.CONDITION_SATISFIED},i=s}else R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(i=this.beginQuery(),this.endQuery(),r=function(){return e.isQueryAvailable(i,R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):r=function(){return!0};return{query:i,isFencePassed:r}},n.prototype.downloadMatrixFromPackedTexture=function(t,e,i){var r=this;return this.downloadMatrixDriver(t,function(){return bS(r.gl,e,i)})},n.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,i=v0(e,t),r=rS(e),a=y0(e);return ce(e,function(){return e.attachShader(a,r)}),ce(e,function(){return e.attachShader(a,i)}),b0(e,a),this.debug&&Co(e,a),this.vertexAttrsAreBound||(this.setProgram(a),this.vertexAttrsAreBound=dS(e,this.program,this.vertexBuffer)),a},n.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),t!=null&&ce(this.gl,function(){return e.gl.deleteProgram(t)})},n.prototype.setProgram=function(t){var e=this;this.throwIfDisposed(),this.program=t,this.program!=null&&this.debug&&Co(this.gl,this.program),ce(this.gl,function(){return e.gl.useProgram(t)})},n.prototype.getUniformLocation=function(t,e,i){return i===void 0&&(i=!0),this.throwIfDisposed(),i?x0(this.gl,t,e):C0(this.gl,t,e)},n.prototype.getAttributeLocation=function(t,e){var i=this;return this.throwIfDisposed(),ce(this.gl,function(){return i.gl.getAttribLocation(t,e)})},n.prototype.getUniformLocationNoThrow=function(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)},n.prototype.setInputMatrixTexture=function(t,e,i){this.throwIfDisposed(),this.throwIfNoProgram(),R0(this.gl,t,e,i)},n.prototype.setOutputMatrixTexture=function(t,e,i){this.setOutputMatrixTextureDriver(t,i,e)},n.prototype.setOutputPackedMatrixTexture=function(t,e,i){this.throwIfDisposed();var r=$r(e,i),a=r[0],s=r[1];this.setOutputMatrixTextureDriver(t,a,s)},n.prototype.setOutputMatrixWriteRegion=function(t,e,i,r){this.setOutputMatrixWriteRegionDriver(i,t,r,e)},n.prototype.setOutputPackedMatrixWriteRegion=function(t,e,i,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},n.prototype.debugValidate=function(){this.program!=null&&Co(this.gl,this.program),Xa(this.gl)},n.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),ce(t,function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)})},n.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),ce(this.gl,function(){return t.gl.finish()})},n.prototype.getQueryTimerExtension=function(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=$a(this.gl,R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},n.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},n.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},n.prototype.beginQuery=function(){if(R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){var t=this.gl,e=this.getQueryTimerExtensionWebGL2(),i=t.createQuery();return t.beginQuery(e.TIME_ELAPSED_EXT,i),i}var r=this.getQueryTimerExtensionWebGL1(),a=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,a),a},n.prototype.endQuery=function(){if(R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){var t=this.gl,e=this.getQueryTimerExtensionWebGL2();t.endQuery(e.TIME_ELAPSED_EXT);return}var i=this.getQueryTimerExtensionWebGL1();i.endQueryEXT(i.TIME_ELAPSED_EXT)},n.prototype.waitForQueryAndGetTime=function(t){return No(this,void 0,void 0,function(){var e=this;return xo(this,function(i){switch(i.label){case 0:return[4,R.util.repeatedTry(function(){return e.disposed||e.isQueryAvailable(t,R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return i.sent(),[2,this.getQueryTime(t,R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},n.prototype.getQueryTime=function(t,e){if(e===0)return null;if(e===2){var i=this.gl,r=i.getQueryParameter(t,i.QUERY_RESULT);return r/1e6}else{var a=this.getQueryTimerExtensionWebGL1(),r=a.getQueryObjectEXT(t,a.QUERY_RESULT_EXT);return r/1e6}},n.prototype.isQueryAvailable=function(t,e){if(e===0)return!0;if(e===2){var i=this.gl,r=this.getQueryTimerExtensionWebGL2(),a=i.getQueryParameter(t,i.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),a&&!this.disjoint}else{var r=this.getQueryTimerExtensionWebGL1(),a=r.getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),a&&!this.disjoint}},n.prototype.pollFence=function(t){var e=this;return new Promise(function(i){e.addItemToPoll(function(){return t.isFencePassed()},function(){return i()})})},n.prototype.pollItems=function(){for(var t=y9(this.itemsToPoll.map(function(r){return r.isDoneFn})),e=0;e<=t;++e){var i=this.itemsToPoll[e].resolveFn;i()}this.itemsToPoll=this.itemsToPoll.slice(t+1)},n.prototype.addItemToPoll=function(t,e){var i=this;if(this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1)return;R.util.repeatedTry(function(){return i.pollItems(),i.itemsToPoll.length===0})},n.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),Ro(this.gl,t,this.framebuffer),this.debug&&Xa(this.gl)},n.prototype.unbindTextureToFrameBuffer=function(){this.outputTexture!=null?(Ro(this.gl,this.outputTexture,this.framebuffer),this.debug&&Xa(this.gl)):xd(this.gl,this.framebuffer)},n.prototype.downloadMatrixDriver=function(t,e){this.bindTextureToFrameBuffer(t);var i=e();return this.unbindTextureToFrameBuffer(),i},n.prototype.setOutputMatrixTextureDriver=function(t,e,i){this.throwIfDisposed();var r=this.gl;Ro(r,t,this.framebuffer),this.debug&&Xa(r),this.outputTexture=t,ce(r,function(){return r.viewport(0,0,e,i)}),ce(r,function(){return r.scissor(0,0,e,i)})},n.prototype.setOutputMatrixWriteRegionDriver=function(t,e,i,r){var a=this;this.throwIfDisposed(),ce(this.gl,function(){return a.gl.scissor(t,e,i,r)})},n.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},n.prototype.throwIfNoProgram=function(){if(this.program==null)throw new Error("No GPU program is currently set.")},n}();function y9(n){for(var t=0;t0&&(b.flatOffset=g.texData.slice.flatOffset),{name:t.variableNames[v],shapeInfo:b}}),s=a.map(function(g){return g.shapeInfo}),o={logicalShape:i.shape,texShape:i.texData.texShape,isUniform:!1,isPacked:i.texData.isPacked,flatOffset:null},l=MP(a,o,r,t.packedInputs),u=n.createProgram(l),c=null,h=n.getUniformLocation(u,"NAN",!1);R.env().getNumber("WEBGL_VERSION")===1&&(c=n.getUniformLocation(u,"INFINITY",!1));for(var d={},p=0;p0,l=s.isUniform?"uniform":s.texData.texShape;i+=s.shape+"_"+l+"_"+o});var r=n.userCode,a=n.constructor.name;return a+="_"+i+"_"+r,a}var L9=function(){function n(t,e,i){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var r=i.filterWidth,a=i.inChannels,s=i.strideWidth,o=i.strideHeight,l=i.padInfo,u=i.outWidth,c=i.dilationWidth,h=i.dilationHeight,d=i.dataFormat,p=l.left,f=l.top,m=a*r,g=kt(),v=d==="channelsLast",b=v?0:1,S=v?1:2,L="",w=0;w<=1;w++)for(var N=0;N<=1;N++)L+=` + }`;return g0(n,e)}function aS(n){var t=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return w0(n,t)}function sS(n){var t=new Uint16Array([0,1,2,2,1,3]);return S0(n,t)}function Za(n,t,e,i,r,a){I0(t,e);var s=L0(n),o=n.TEXTURE_2D;return ce(n,function(){return n.bindTexture(o,s)}),ce(n,function(){return n.texParameteri(o,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE)}),ce(n,function(){return n.texParameteri(o,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)}),ce(n,function(){return n.texParameteri(o,n.TEXTURE_MIN_FILTER,n.NEAREST)}),ce(n,function(){return n.texParameteri(o,n.TEXTURE_MAG_FILTER,n.NEAREST)}),ce(n,function(){return n.texImage2D(o,0,i,t,e,0,r,a,null)}),ce(n,function(){return n.bindTexture(n.TEXTURE_2D,null)}),s}function Fd(n){return n.internalFormatFloat}function oS(n,t,e,i){var r=Ka(t,e),a=r[0],s=r[1];return Za(n,a,s,Fd(i),i.textureFormatFloat,n.FLOAT)}function Wd(n){return n.internalFormatHalfFloat}function lS(n,t,e,i){var r=Ka(t,e),a=r[0],s=r[1];return Za(n,a,s,Wd(i),i.textureFormatFloat,i.textureTypeHalfFloat)}function Ud(n){return n.downloadTextureFormat}function uS(n,t,e,i){var r=Ka(t,e),a=r[0],s=r[1];return Za(n,a,s,Ud(i),n.RGBA,n.UNSIGNED_BYTE)}function Bd(n){return n.internalFormatPackedFloat}function cS(n,t,e,i){var r=$r(t,e),a=r[0],s=r[1];return Za(n,a,s,Bd(i),n.RGBA,n.FLOAT)}function zd(n){return n.internalFormatPackedHalfFloat}function hS(n,t,e,i){var r=$r(t,e),a=r[0],s=r[1];return Za(n,a,s,zd(i),n.RGBA,i.textureTypeHalfFloat)}function dS(n,t,e){var i=0,r=3*4,a=3*4+2*4;ce(n,function(){return n.bindBuffer(n.ARRAY_BUFFER,e)});var s=Nd(n,t,"clipSpacePos",e,3,a,i);return s&&Nd(n,t,"uv",e,2,a,r)}function pS(n,t,e,i,r,a){ce(n,function(){return n.bindTexture(n.TEXTURE_2D,t)});var s,o,l;r instanceof Uint8Array?(s=new Uint8Array(e*i*4),o=n.UNSIGNED_BYTE,l=n.RGBA):(s=new Float32Array(e*i*4),o=n.FLOAT,l=a.internalFormatPackedFloat),s.set(r),ce(n,function(){return n.texImage2D(n.TEXTURE_2D,0,l,e,i,0,n.RGBA,o,s)}),ce(n,function(){return n.bindTexture(n.TEXTURE_2D,null)})}function fS(n,t,e){ce(n,function(){return n.bindTexture(n.TEXTURE_2D,t)}),e.data instanceof Uint8Array?ce(n,function(){return n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e.width,e.height,0,n.RGBA,n.UNSIGNED_BYTE,e.data)}):ce(n,function(){return n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,e)}),ce(n,function(){return n.bindTexture(n.TEXTURE_2D,null)})}function mS(n,t,e,i){var r=n.createBuffer();ce(n,function(){return n.bindBuffer(n.PIXEL_PACK_BUFFER,r)});var a=4,s=4,o=a*s*t*e;return ce(n,function(){return n.bufferData(n.PIXEL_PACK_BUFFER,o,n.STREAM_READ)}),ce(n,function(){return n.readPixels(0,0,e,t,n.RGBA,n.FLOAT,0)}),ce(n,function(){return n.bindBuffer(n.PIXEL_PACK_BUFFER,null)}),r}function gS(n,t,e){var i=n,r=new Float32Array(e);return i.bindBuffer(i.PIXEL_PACK_BUFFER,t),i.getBufferSubData(i.PIXEL_PACK_BUFFER,0,r),i.bindBuffer(i.PIXEL_PACK_BUFFER,null),r}function vS(n,t,e,i){var r=Ka(t,e),a=r[0],s=r[1],o=4,l=new Uint8Array(V_(t*e,o));return ce(n,function(){return n.readPixels(0,0,a,s,i.downloadTextureFormat,n.UNSIGNED_BYTE,l)}),new Float32Array(l.buffer)}function yS(n,t,e,i,r,a,s,o){var l=n,u=new Float32Array(q_(a,s));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}function bS(n,t,e){var i=new Float32Array(t*e*4);return ce(n,function(){return n.readPixels(0,0,e,t,n.RGBA,n.FLOAT,i)}),i}var y9={__proto__:null,createVertexShader:rS,createVertexBuffer:aS,createIndexBuffer:sS,getInternalFormatForFloat32MatrixTexture:Fd,createFloat32MatrixTexture:oS,getInternalFormatForFloat16MatrixTexture:Wd,createFloat16MatrixTexture:lS,getInternalFormatForUnsignedBytesMatrixTexture:Ud,createUnsignedBytesMatrixTexture:uS,getInternalFormatForPackedMatrixTexture:Bd,createPackedMatrixTexture:cS,getInternalFormatForFloat16PackedMatrixTexture:zd,createFloat16PackedMatrixTexture:hS,bindVertexProgramAttributeStreams:dS,uploadDenseMatrixToTexture:pS,uploadPixelDataToTexture:fS,createBufferFromOutputTexture:mS,downloadFloat32MatrixFromBuffer:gS,downloadByteEncodedFloatMatrixFromOutputTexture:vS,downloadPackedMatrixFromBuffer:yS,downloadMatrixFromPackedOutputTexture:bS};var wS=function(){function n(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=R.env().getNumber("WEBGL_VERSION");t!=null?(this.gl=t,p0(e,t)):this.gl=Wn(e);var i="WEBGL_color_buffer_float",r="EXT_color_buffer_half_float";if(R.env().getNumber("WEBGL_VERSION")===1){var a="OES_texture_float",s="OES_texture_half_float";if(this.textureFloatExtension=$a(this.gl,a),nn(this.gl,s))this.textureHalfFloatExtension=$a(this.gl,s);else if(R.env().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(i),nn(this.gl,r))this.colorBufferHalfFloatExtension=$a(this.gl,r);else if(R.env().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(i="EXT_color_buffer_float",nn(this.gl,i))this.colorBufferFloatExtension=this.gl.getExtension(i);else if(nn(this.gl,r))this.colorBufferHalfFloatExtension=this.gl.getExtension(r);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=aS(this.gl),this.indexBuffer=sS(this.gl),this.framebuffer=A0(this.gl),this.textureConfig=Td(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(n.prototype,"debug",{get:function(){return R.env().getBool("DEBUG")},enumerable:!0,configurable:!0}),n.prototype.dispose=function(){var t=this;if(this.disposed)return;this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");var e=this.gl;ce(e,function(){return e.finish()}),ce(e,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),ce(e,function(){return e.deleteFramebuffer(t.framebuffer)}),ce(e,function(){return e.bindBuffer(e.ARRAY_BUFFER,null)}),ce(e,function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)}),ce(e,function(){return e.deleteBuffer(t.indexBuffer)}),this.disposed=!0},n.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),oS(this.gl,t,e,this.textureConfig)},n.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),lS(this.gl,t,e,this.textureConfig)},n.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),uS(this.gl,t,e,this.textureConfig)},n.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),fS(this.gl,t,e)},n.prototype.uploadDenseMatrixToTexture=function(t,e,i,r){this.throwIfDisposed(),pS(this.gl,t,e,i,r,this.textureConfig)},n.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),hS(this.gl,t,e,this.textureConfig)},n.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),cS(this.gl,t,e,this.textureConfig)},n.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(xd(this.gl,this.framebuffer),this.outputTexture=null),ce(this.gl,function(){return e.gl.deleteTexture(t)})},n.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(t,e,i){var r=this;return this.downloadMatrixDriver(t,function(){return vS(r.gl,e,i,r.textureConfig)})},n.prototype.downloadPackedMatrixFromBuffer=function(t,e,i,r,a,s){return yS(this.gl,t,e,i,r,a,s,this.textureConfig)},n.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return gS(this.gl,t,e)},n.prototype.createBufferFromTexture=function(t,e,i){this.bindTextureToFrameBuffer(t);var r=mS(this.gl,e,i,this.textureConfig);return this.unbindTextureToFrameBuffer(),r},n.prototype.createAndWaitForFence=function(){var t=this.createFence(this.gl);return this.pollFence(t)},n.prototype.createFence=function(t){var e=this,i,r;if(R.env().getBool("WEBGL_FENCE_API_ENABLED")){var a=t,s=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),r=function(){var o=a.clientWaitSync(s,0,0);return o===a.ALREADY_SIGNALED||o===a.CONDITION_SATISFIED},i=s}else R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(i=this.beginQuery(),this.endQuery(),r=function(){return e.isQueryAvailable(i,R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):r=function(){return!0};return{query:i,isFencePassed:r}},n.prototype.downloadMatrixFromPackedTexture=function(t,e,i){var r=this;return this.downloadMatrixDriver(t,function(){return bS(r.gl,e,i)})},n.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,i=v0(e,t),r=rS(e),a=y0(e);return ce(e,function(){return e.attachShader(a,r)}),ce(e,function(){return e.attachShader(a,i)}),b0(e,a),this.debug&&Co(e,a),this.vertexAttrsAreBound||(this.setProgram(a),this.vertexAttrsAreBound=dS(e,this.program,this.vertexBuffer)),a},n.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),t!=null&&ce(this.gl,function(){return e.gl.deleteProgram(t)})},n.prototype.setProgram=function(t){var e=this;this.throwIfDisposed(),this.program=t,this.program!=null&&this.debug&&Co(this.gl,this.program),ce(this.gl,function(){return e.gl.useProgram(t)})},n.prototype.getUniformLocation=function(t,e,i){return i===void 0&&(i=!0),this.throwIfDisposed(),i?x0(this.gl,t,e):C0(this.gl,t,e)},n.prototype.getAttributeLocation=function(t,e){var i=this;return this.throwIfDisposed(),ce(this.gl,function(){return i.gl.getAttribLocation(t,e)})},n.prototype.getUniformLocationNoThrow=function(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)},n.prototype.setInputMatrixTexture=function(t,e,i){this.throwIfDisposed(),this.throwIfNoProgram(),R0(this.gl,t,e,i)},n.prototype.setOutputMatrixTexture=function(t,e,i){this.setOutputMatrixTextureDriver(t,i,e)},n.prototype.setOutputPackedMatrixTexture=function(t,e,i){this.throwIfDisposed();var r=$r(e,i),a=r[0],s=r[1];this.setOutputMatrixTextureDriver(t,a,s)},n.prototype.setOutputMatrixWriteRegion=function(t,e,i,r){this.setOutputMatrixWriteRegionDriver(i,t,r,e)},n.prototype.setOutputPackedMatrixWriteRegion=function(t,e,i,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},n.prototype.debugValidate=function(){this.program!=null&&Co(this.gl,this.program),Xa(this.gl)},n.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),ce(t,function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)})},n.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),ce(this.gl,function(){return t.gl.finish()})},n.prototype.getQueryTimerExtension=function(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=$a(this.gl,R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},n.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},n.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},n.prototype.beginQuery=function(){if(R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){var t=this.gl,e=this.getQueryTimerExtensionWebGL2(),i=t.createQuery();return t.beginQuery(e.TIME_ELAPSED_EXT,i),i}var r=this.getQueryTimerExtensionWebGL1(),a=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,a),a},n.prototype.endQuery=function(){if(R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){var t=this.gl,e=this.getQueryTimerExtensionWebGL2();t.endQuery(e.TIME_ELAPSED_EXT);return}var i=this.getQueryTimerExtensionWebGL1();i.endQueryEXT(i.TIME_ELAPSED_EXT)},n.prototype.waitForQueryAndGetTime=function(t){return No(this,void 0,void 0,function(){var e=this;return xo(this,function(i){switch(i.label){case 0:return[4,R.util.repeatedTry(function(){return e.disposed||e.isQueryAvailable(t,R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return i.sent(),[2,this.getQueryTime(t,R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},n.prototype.getQueryTime=function(t,e){if(e===0)return null;if(e===2){var i=this.gl,r=i.getQueryParameter(t,i.QUERY_RESULT);return r/1e6}else{var a=this.getQueryTimerExtensionWebGL1(),r=a.getQueryObjectEXT(t,a.QUERY_RESULT_EXT);return r/1e6}},n.prototype.isQueryAvailable=function(t,e){if(e===0)return!0;if(e===2){var i=this.gl,r=this.getQueryTimerExtensionWebGL2(),a=i.getQueryParameter(t,i.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),a&&!this.disjoint}else{var r=this.getQueryTimerExtensionWebGL1(),a=r.getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),a&&!this.disjoint}},n.prototype.pollFence=function(t){var e=this;return new Promise(function(i){e.addItemToPoll(function(){return t.isFencePassed()},function(){return i()})})},n.prototype.pollItems=function(){for(var t=b9(this.itemsToPoll.map(function(r){return r.isDoneFn})),e=0;e<=t;++e){var i=this.itemsToPoll[e].resolveFn;i()}this.itemsToPoll=this.itemsToPoll.slice(t+1)},n.prototype.addItemToPoll=function(t,e){var i=this;if(this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1)return;R.util.repeatedTry(function(){return i.pollItems(),i.itemsToPoll.length===0})},n.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),Ro(this.gl,t,this.framebuffer),this.debug&&Xa(this.gl)},n.prototype.unbindTextureToFrameBuffer=function(){this.outputTexture!=null?(Ro(this.gl,this.outputTexture,this.framebuffer),this.debug&&Xa(this.gl)):xd(this.gl,this.framebuffer)},n.prototype.downloadMatrixDriver=function(t,e){this.bindTextureToFrameBuffer(t);var i=e();return this.unbindTextureToFrameBuffer(),i},n.prototype.setOutputMatrixTextureDriver=function(t,e,i){this.throwIfDisposed();var r=this.gl;Ro(r,t,this.framebuffer),this.debug&&Xa(r),this.outputTexture=t,ce(r,function(){return r.viewport(0,0,e,i)}),ce(r,function(){return r.scissor(0,0,e,i)})},n.prototype.setOutputMatrixWriteRegionDriver=function(t,e,i,r){var a=this;this.throwIfDisposed(),ce(this.gl,function(){return a.gl.scissor(t,e,i,r)})},n.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},n.prototype.throwIfNoProgram=function(){if(this.program==null)throw new Error("No GPU program is currently set.")},n}();function b9(n){for(var t=0;t0&&(b.flatOffset=g.texData.slice.flatOffset),{name:t.variableNames[v],shapeInfo:b}}),s=a.map(function(g){return g.shapeInfo}),o={logicalShape:i.shape,texShape:i.texData.texShape,isUniform:!1,isPacked:i.texData.isPacked,flatOffset:null},l=HP(a,o,r,t.packedInputs),u=n.createProgram(l),c=null,h=n.getUniformLocation(u,"NAN",!1);R.env().getNumber("WEBGL_VERSION")===1&&(c=n.getUniformLocation(u,"INFINITY",!1));for(var d={},p=0;p0,l=s.isUniform?"uniform":s.texData.texShape;i+=s.shape+"_"+l+"_"+o});var r=n.userCode,a=n.constructor.name;return a+="_"+i+"_"+r,a}var I9=function(){function n(t,e,i){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var r=i.filterWidth,a=i.inChannels,s=i.strideWidth,o=i.strideHeight,l=i.padInfo,u=i.outWidth,c=i.dilationWidth,h=i.dilationHeight,d=i.dataFormat,p=l.left,f=l.top,m=a*r,g=kt(),v=d==="channelsLast",b=v?0:1,S=v?1:2,L="",w=0;w<=1;w++)for(var N=0;N<=1;N++)L+=` blockIndex = rc.y + `+N+`; pos = rc.x + `+w+`; @@ -2162,7 +2162,7 @@ return (round(mod(b, 2.0)) != 1) ? `+g.output+` = result; } - `}return n}();var I9=function(){function n(t,e,i,r,a){this.variableNames=["x"],this.outputShape=[];var s=e,o=t[3]-1;this.outputShape=t;var l,u="float("+i+") + float("+r+") * sum";a===.5?l="inversesqrt("+u+")":a===1?l="1.0/("+u+")":l="exp(log("+u+") * float(-"+a+"));",this.userCode=` + `}return n}();var A9=function(){function n(t,e,i,r,a){this.variableNames=["x"],this.outputShape=[];var s=e,o=t[3]-1;this.outputShape=t;var l,u="float("+i+") + float("+r+") * sum";a===.5?l="inversesqrt("+u+")":a===1?l="1.0/("+u+")":l="exp(log("+u+") * float(-"+a+"));",this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; @@ -2181,7 +2181,7 @@ return (round(mod(b, 2.0)) != 1) ? float val = x * `+l+`; setOutput(val); } - `}return n}();var A9=function(){function n(t,e,i,r,a){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=i,this.alpha=r,this.beta=a,this.userCode=` + `}return n}();var T9=function(){function n(t,e,i,r,a){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=i,this.alpha=r,this.beta=a,this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; @@ -2236,7 +2236,7 @@ return (round(mod(b, 2.0)) != 1) ? } setOutput(result); } - `}return n}();var T9=function(){function n(t,e,i,r,a){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var s=e,o=t[3]-1;this.outputShape=t;var l,u="float("+i+") + float("+r+") * sum";a===.5?l="inversesqrt("+u+")":a===1?l="1.0/("+u+")":l="exp(log("+u+") * float(-"+a+"));",this.userCode=` + `}return n}();var N9=function(){function n(t,e,i,r,a){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var s=e,o=t[3]-1;this.outputShape=t;var l,u="float("+i+") + float("+r+") * sum";a===.5?l="inversesqrt("+u+")":a===1?l="1.0/("+u+")":l="exp(log("+u+") * float(-"+a+"));",this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords.x; @@ -2298,7 +2298,7 @@ return (round(mod(b, 2.0)) != 1) ? vec4 result = xAtOutputCoords * `+l+`; setOutput(result); } - `}return n}();var N9=function(){function n(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,i=t.strideWidth,r=t.dilationHeight,a=t.effectiveFilterHeight,s=t.effectiveFilterWidth,o=a-1-t.padInfo.top,l=s-1-t.padInfo.left,u=a*s-1;this.userCode=` + `}return n}();var x9=function(){function n(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,i=t.strideWidth,r=t.dilationHeight,a=t.effectiveFilterHeight,s=t.effectiveFilterWidth,o=a-1-t.padInfo.top,l=s-1-t.padInfo.left,u=a*s-1;this.userCode=` const ivec2 pads = ivec2(`+o+", "+l+`); void main() { @@ -2344,7 +2344,7 @@ return (round(mod(b, 2.0)) != 1) ? } setOutput(dotProd); } - `}return n}(),x9=function(){function n(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideDepth,i=t.strideHeight,r=t.strideWidth,a=t.dilationDepth,s=t.dilationHeight,o=t.dilationWidth,l=t.effectiveFilterDepth,u=t.effectiveFilterHeight,c=t.effectiveFilterWidth,h=l-1-t.padInfo.front,d=u-1-t.padInfo.top,p=c-1-t.padInfo.left,f=l*u*c-1;this.userCode=` + `}return n}(),C9=function(){function n(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideDepth,i=t.strideHeight,r=t.strideWidth,a=t.dilationDepth,s=t.dilationHeight,o=t.dilationWidth,l=t.effectiveFilterDepth,u=t.effectiveFilterHeight,c=t.effectiveFilterWidth,h=l-1-t.padInfo.front,d=u-1-t.padInfo.top,p=c-1-t.padInfo.left,f=l*u*c-1;this.userCode=` const ivec3 pads = ivec3(`+h+", "+d+", "+p+`); void main() { @@ -2442,7 +2442,7 @@ return (round(mod(b, 2.0)) != 1) ? setOutput(result); } - `}return n}();var C9=function(){function n(t,e,i){this.variableNames=["probs"],this.outputShape=[t,i],this.userCode=` + `}return n}();var R9=function(){function n(t,e,i){this.variableNames=["probs"],this.outputShape=[t,i],this.userCode=` uniform float seed; void main() { @@ -2464,18 +2464,18 @@ return (round(mod(b, 2.0)) != 1) ? // If no other event happened, last event happened. setOutput(float(`+(e-1)+`)); } - `}return n.prototype.getCustomSetupFunc=function(t){var e=this;return function(i,r){e.seedLoc==null&&(e.seedLoc=i.getUniformLocation(r,"seed")),i.gl.uniform1f(e.seedLoc,t)}},n}();var R9=function(){function n(t,e,i,r){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode=` + `}return n.prototype.getCustomSetupFunc=function(t){var e=this;return function(i,r){e.seedLoc==null&&(e.seedLoc=i.getUniformLocation(r,"seed")),i.gl.uniform1f(e.seedLoc,t)}},n}();var O9=function(){function n(t,e,i,r){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode=` void main() { ivec2 coords = getOutputCoords(); int index = round(getIndices(coords.x)); setOutput(mix(float(`+r+"), float("+i+`), float(index == coords.y))); } - `}return n}();var k9=function(){function n(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=t;var e=t.length;if(e===0)this.userCode=` + `}return n}();var F9=function(){function n(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=t;var e=t.length;if(e===0)this.userCode=` void main() { setOutput(vec4(getA(), 0., 0., 0.)); } - `;else{var i=$t("rc",e),r=Je(e),a=O9(e,t,i),s=E9(e,t[t.length-1],t[t.length-2],i),o=D9(t,i);this.userCode=` + `;else{var i=$t("rc",e),r=Je(e),a=E9(e,t,i),s=D9(e,t[t.length-1],t[t.length-2],i),o=k9(t,i);this.userCode=` void main() { `+r+` rc = getOutputCoords(); @@ -2487,7 +2487,7 @@ return (round(mod(b, 2.0)) != 1) ? setOutput(vec4(`+o+`)); } } - `}}return n}();function F9(n,t){for(var e=[],i=0;i<=1;i++)for(var r=0;r<=1;r++){for(var a=(i===0?"r":"rp1")+", "+(r===0?"c":"cp1"),s=2;s "+t[0];for(var i="",r=n-2;r= "+t[r],r "+t[0];for(var i="",r=n-2;r= "+t[r],r= `+t+`; bool rEdge = rp1 >= `+e+`; - `}function D9(n,t){var e=n.length,i=F9(e,t);return e===1?`getA(rc), + `}function k9(n,t){var e=n.length,i=W9(e,t);return e===1?`getA(rc), rc + 1 >= `+n[0]+` ? 0. : getA(rc + 1), 0, 0`:"getA("+i[0]+`), cEdge ? 0. : getA(`+i[1]+`), rEdge ? 0. : getA(`+i[2]+`), - rEdge || cEdge ? 0. : getA(`+i[3]+")"}var W9=function(){function n(t,e,i){this.variableNames=["x"],this.outputShape=e.map(function(u,c){return u[0]+t[c]+u[1]});var r=t.length,a=Je(r),s=e.map(function(u){return u[0]}).join(","),o=e.map(function(u,c){return u[0]+t[c]}).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);if(r===1){this.userCode=` + rEdge || cEdge ? 0. : getA(`+i[3]+")"}var U9=function(){function n(t,e,i){this.variableNames=["x"],this.outputShape=e.map(function(u,c){return u[0]+t[c]+u[1]});var r=t.length,a=Je(r),s=e.map(function(u){return u[0]}).join(","),o=e.map(function(u,c){return u[0]+t[c]}).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);if(r===1){this.userCode=` int start = `+s+`; int end = `+o+`; @@ -2525,7 +2525,7 @@ return (round(mod(b, 2.0)) != 1) ? setOutput(getX(`+l+`)); } } - `}return n}();var U9=function(){function n(t,e,i){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map(function(v,b){return v[0]+t[b]+v[1]});for(var r=t.length,a=Je(r),s=e.map(function(v){return v[0]}).join(","),o=e.map(function(v,b){return v[0]+t[b]}).join(","),l=$t("rc",r),u=$t("source",r),c=l[r-1]+" < "+this.outputShape[r-1],h=r===1?"source":"vec2("+u.slice(-2).join()+")",d=[a+" rc = outputLoc;",l[r-1]+` += 1; + `}return n}();var B9=function(){function n(t,e,i){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map(function(v,b){return v[0]+t[b]+v[1]});for(var r=t.length,a=Je(r),s=e.map(function(v){return v[0]}).join(","),o=e.map(function(v,b){return v[0]+t[b]}).join(","),l=$t("rc",r),u=$t("source",r),c=l[r-1]+" < "+this.outputShape[r-1],h=r===1?"source":"vec2("+u.slice(-2).join()+")",d=[a+" rc = outputLoc;",l[r-1]+` += 1; if(`+c+`) { `,r===1?"":`} rc = outputLoc; @@ -2950,7 +2950,7 @@ return (round(mod(b, 2.0)) != 1) ? getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims); `+(r>0?"}":"")+` `}this.userCode=` - `+B9(e)+` + `+z9(e)+` `+Ed(t)+` void main() { @@ -2966,12 +2966,12 @@ return (round(mod(b, 2.0)) != 1) ? setOutput(result); } - `}return n}();function B9(n){var t=ur(["r","c","d"],n);return` + `}return n}();function z9(n){var t=ur(["r","c","d"],n);return` ivec3 inputCoordsFromReshapedOutCoords(int index) { `+t+` return ivec3(r, c, d); } - `}var z9=function(){function n(t,e,i){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,a=r[1],s=r[2],o=t.shape,l=o[1],u=o[2],c=[i&&l>1?a-1:a,i&&u>1?s-1:s],h=[i&&l>1?l-1:l,i&&u>1?u-1:u],d=c[0]/h[0],p=c[1]/h[1],f=1/d,m=1/p,g=Math.ceil(f)*2+2,v=Math.ceil(m)*2+2;this.userCode=` + `}var _9=function(){function n(t,e,i){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,a=r[1],s=r[2],o=t.shape,l=o[1],u=o[2],c=[i&&l>1?a-1:a,i&&u>1?s-1:s],h=[i&&l>1?l-1:l,i&&u>1?u-1:u],d=c[0]/h[0],p=c[1]/h[1],f=1/d,m=1/p,g=Math.ceil(f)*2+2,v=Math.ceil(m)*2+2;this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; @@ -3052,7 +3052,7 @@ return (round(mod(b, 2.0)) != 1) ? setOutput(accumulator); } - `}return n}();var _9=function(){function n(t,e,i,r){this.variableNames=["A"],this.outputShape=[];var a=t[0],s=t[1],o=t[2],l=t[3];this.outputShape=[a,e,i,l];var u=[r&&e>1?s-1:s,r&&i>1?o-1:o],c=[r&&e>1?e-1:e,r&&i>1?i-1:i];this.userCode=` + `}return n}();var P9=function(){function n(t,e,i,r){this.variableNames=["A"],this.outputShape=[];var a=t[0],s=t[1],o=t[2],l=t[3];this.outputShape=[a,e,i,l];var u=[r&&e>1?s-1:s,r&&i>1?o-1:o],c=[r&&e>1?e-1:e,r&&i>1?i-1:i];this.userCode=` const vec2 effectiveInputOverOutputRatioRC = vec2( `+u[0]/c[0]+`, `+u[1]/c[1]+`); @@ -3085,7 +3085,7 @@ return (round(mod(b, 2.0)) != 1) ? setOutput(newValue); } - `}return n}();var P9=function(){function n(t,e,i,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var a=t[0],s=t[1],o=t[2],l=t[3];this.outputShape=[a,e,i,l];var u=[r&&e>1?s-1:s,r&&i>1?o-1:o],c=[r&&e>1?e-1:e,r&&i>1?i-1:i];this.userCode=` + `}return n}();var M9=function(){function n(t,e,i,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var a=t[0],s=t[1],o=t[2],l=t[3];this.outputShape=[a,e,i,l];var u=[r&&e>1?s-1:s,r&&i>1?o-1:o],c=[r&&e>1?e-1:e,r&&i>1?i-1:i];this.userCode=` const vec3 effectiveInputOverOutputRatioRC = vec3( `+u[0]/c[0]+`, `+u[1]/c[1]+`, @@ -3162,7 +3162,7 @@ return (round(mod(b, 2.0)) != 1) ? setOutput(newValue); } - `}return n}();var M9=function(){function n(t,e,i){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,a=r[1],s=r[2],o=t.shape,l=o[1],u=o[2],c=[i&&l>1?a-1:a,i&&u>1?s-1:s],h=[i&&l>1?l-1:l,i&&u>1?u-1:u],d=c[0]/h[0],p=c[1]/h[1],f=1/d,m=1/p,g=Math.ceil(f)*2+2,v=Math.ceil(m)*2+2;this.userCode=` + `}return n}();var H9=function(){function n(t,e,i){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,a=r[1],s=r[2],o=t.shape,l=o[1],u=o[2],c=[i&&l>1?a-1:a,i&&u>1?s-1:s],h=[i&&l>1?l-1:l,i&&u>1?u-1:u],d=c[0]/h[0],p=c[1]/h[1],f=1/d,m=1/p,g=Math.ceil(f)*2+2,v=Math.ceil(m)*2+2;this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; @@ -3232,7 +3232,7 @@ return (round(mod(b, 2.0)) != 1) ? setOutput(accumulator); } - `}return n}();var H9=function(){function n(t,e,i,r){this.variableNames=["A"],this.outputShape=[];var a=t[0],s=t[1],o=t[2],l=t[3];this.outputShape=[a,e,i,l];var u=[r&&e>1?s-1:s,r&&i>1?o-1:o],c=[r&&e>1?e-1:e,r&&i>1?i-1:i],h=r?"0.5":"0.0";this.userCode=` + `}return n}();var V9=function(){function n(t,e,i,r){this.variableNames=["A"],this.outputShape=[];var a=t[0],s=t[1],o=t[2],l=t[3];this.outputShape=[a,e,i,l];var u=[r&&e>1?s-1:s,r&&i>1?o-1:o],c=[r&&e>1?e-1:e,r&&i>1?i-1:i],h=r?"0.5":"0.0";this.userCode=` const vec2 effectiveInputOverOutputRatioRC = vec2( `+u[0]/c[0]+`, `+u[1]/c[1]+`); @@ -3255,7 +3255,7 @@ return (round(mod(b, 2.0)) != 1) ? setOutput(newValue); } - `}return n}();var V9=function(){function n(t,e){this.variableNames=["x"];var i=t.length;if(i>4)throw new Error("WebGL backend: Reverse of rank-"+i+" tensor is not yet supported");if(this.outputShape=t,i===1){this.userCode=` + `}return n}();var q9=function(){function n(t,e){this.variableNames=["x"];var i=t.length;if(i>4)throw new Error("WebGL backend: Reverse of rank-"+i+" tensor is not yet supported");if(this.outputShape=t,i===1){this.userCode=` void main() { int coord = getOutputCoords(); setOutput(getX(`+t[0]+` - coord - 1)); @@ -3265,7 +3265,7 @@ return (round(mod(b, 2.0)) != 1) ? `+s+` coords = getOutputCoords(); setOutput(getX(`+a+`)); } - `}return n}();var q9=function(){function n(t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;var i=t.length;if(i>4)throw new Error("WebGL backend: Reverse of rank-"+i+" tensor is not yet supported");this.outputShape=t;var r=$t("rc",i),a=r[i-1]+" + 1 < "+this.outputShape[i-1],s=r[i-2]+" + 1 < "+this.outputShape[i-2],o=Je(i);i===1?this.userCode=` + `}return n}();var G9=function(){function n(t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;var i=t.length;if(i>4)throw new Error("WebGL backend: Reverse of rank-"+i+" tensor is not yet supported");this.outputShape=t;var r=$t("rc",i),a=r[i-1]+" + 1 < "+this.outputShape[i-1],s=r[i-2]+" + 1 < "+this.outputShape[i-2],o=Je(i);i===1?this.userCode=` void main(){ int rc = getOutputCoords(); vec4 result = vec4(0.); @@ -3313,7 +3313,7 @@ return (round(mod(b, 2.0)) != 1) ? } setOutput(mix(getDefaultValue(), sum, float(found))); } - `}return n}();var G9=function(){function n(t,e){this.variableNames=["x","segmentIds"];var i=t.windowSize,r=t.batchSize,a=t.inSize,s=t.numSegments,o=s*Math.ceil(a/i);this.outputShape=[r,o];var l="0.0",u="sumValue",c=Math.floor(i/4)*4,h=i%4,d=` + `}return n}();var Y9=function(){function n(t,e){this.variableNames=["x","segmentIds"];var i=t.windowSize,r=t.batchSize,a=t.inSize,s=t.numSegments,o=s*Math.ceil(a/i);this.outputShape=[r,o];var l="0.0",u="sumValue",c=Math.floor(i/4)*4,h=i%4,d=` sumValue += dot(values, segFilter); `,p="";a%i>0&&(p=` if (inIdx < 0 || inIdx >= `+a+`) { @@ -3419,7 +3419,7 @@ return (round(mod(b, 2.0)) != 1) ? } setOutput(`+u+`); } - `}return n}();var Y9=function(){function n(t,e,i){this.variableNames=["c","a","b"],this.outputShape=e;var r,a;if(i>4)throw Error("Where for rank "+i+" is not yet supported");if(i===1)a="resRC",r="resRC";else{for(var s=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],l=[],u=0;u4)throw Error("Where for rank "+i+" is not yet supported");if(i===1)a="resRC",r="resRC";else{for(var s=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],l=[],u=0;u0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=s,this.log();var o=this.freeTextures[a].shift();return this.usedTextures[a].push(o),o}var l;return r===Ct.PACKED_2X2_FLOAT32?l=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):r===Ct.PACKED_2X2_FLOAT16?l=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):r===Ct.UNPACKED_FLOAT32?l=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):r===Ct.UNPACKED_FLOAT16?l=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):r===Ct.PACKED_4X1_UNSIGNED_BYTE&&(l=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[a].push(l),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),l},n.prototype.releaseTexture=function(t,e,i,r){if(this.freeTextures==null)return;var a=NS(i,r),s=xS(e,a,r);s in this.freeTextures||(this.freeTextures[s]=[]);var o=TS(e,a,this.gpgpu.gl,this.gpgpu.textureConfig,r),l=R.env().get("WEBGL_DELETE_TEXTURE_THRESHOLD");l!==-1&&this._numBytesAllocated>l?(this.gpgpu.deleteMatrixTexture(t),this._numBytesAllocated-=o):(this.freeTextures[s].push(t),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;var u=this.usedTextures[s],c=u.indexOf(t);if(c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u.splice(c,1),this.log()},n.prototype.log=function(){if(!this.logEnabled)return;var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")");var e=this._numBytesFree/this._numBytesAllocated;console.log("Bytes allocated: "+this._numBytesAllocated),console.log("Bytes unused: "+this._numBytesFree+" ("+Math.round(100*e)+"%)")},Object.defineProperty(n.prototype,"numBytesAllocated",{get:function(){return this._numBytesAllocated},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"numBytesFree",{get:function(){return this._numBytesFree},enumerable:!0,configurable:!0}),n.prototype.getNumUsedTextures=function(){return this.numUsedTextures},n.prototype.getNumFreeTextures=function(){return this.numFreeTextures},n.prototype.dispose=function(){var t=this;if(this.freeTextures==null)return;for(var e in this.freeTextures)this.freeTextures[e].forEach(function(i){t.gpgpu.deleteMatrixTexture(i)});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(r){t.gpgpu.deleteMatrixTexture(r)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0},n}();function Z9(n,t){var e=n;if(t===e.R32F)return 4;if(t===e.R16F)return 2;if(t===e.RGBA32F)return 16;if(t===n.RGBA)return 16;if(t===e.RGBA16F)return 8;throw new Error("Unknown internal format "+t)}function TS(n,t,e,i,r){var a=Q9(t,i),s;if(r){var o=$r(n[0],n[1]),l=o[0],u=o[1];s=l*u}else{var c=Ka(n[0],n[1]),h=c[0],d=c[1];s=h*d}var p=Z9(e,a);return s*p}function Q9(n,t){switch(n){case Ct.PACKED_2X2_FLOAT32:return Bd(t);case Ct.PACKED_2X2_FLOAT16:return zd(t);case Ct.UNPACKED_FLOAT32:return Fd(t);case Ct.UNPACKED_FLOAT16:return Wd(t);case Ct.PACKED_4X1_UNSIGNED_BYTE:return Ud(t);default:throw new Error("Unknown physical texture type "+n)}}function eM(n){return R.env().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?n?Ct.PACKED_2X2_FLOAT32:Ct.UNPACKED_FLOAT32:n?Ct.PACKED_2X2_FLOAT16:Ct.UNPACKED_FLOAT16}function NS(n,t){if(n===tn.UPLOAD)return Ct.PACKED_2X2_FLOAT32;if(n===tn.RENDER||n==null)return eM(t);if(n===tn.DOWNLOAD||n===tn.PIXELS)return Ct.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+n)}function xS(n,t,e){return n[0]+"_"+n[1]+"_"+t+"_"+e}var nM=function(){function n(t,e){this.variableNames=["A"];for(var i=new Array(t.length),r=0;r0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=s,this.log();var o=this.freeTextures[a].shift();return this.usedTextures[a].push(o),o}var l;return r===Ct.PACKED_2X2_FLOAT32?l=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):r===Ct.PACKED_2X2_FLOAT16?l=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):r===Ct.UNPACKED_FLOAT32?l=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):r===Ct.UNPACKED_FLOAT16?l=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):r===Ct.PACKED_4X1_UNSIGNED_BYTE&&(l=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[a].push(l),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),l},n.prototype.releaseTexture=function(t,e,i,r){if(this.freeTextures==null)return;var a=NS(i,r),s=xS(e,a,r);s in this.freeTextures||(this.freeTextures[s]=[]);var o=TS(e,a,this.gpgpu.gl,this.gpgpu.textureConfig,r),l=R.env().get("WEBGL_DELETE_TEXTURE_THRESHOLD");l!==-1&&this._numBytesAllocated>l?(this.gpgpu.deleteMatrixTexture(t),this._numBytesAllocated-=o):(this.freeTextures[s].push(t),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;var u=this.usedTextures[s],c=u.indexOf(t);if(c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u.splice(c,1),this.log()},n.prototype.log=function(){if(!this.logEnabled)return;var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")");var e=this._numBytesFree/this._numBytesAllocated;console.log("Bytes allocated: "+this._numBytesAllocated),console.log("Bytes unused: "+this._numBytesFree+" ("+Math.round(100*e)+"%)")},Object.defineProperty(n.prototype,"numBytesAllocated",{get:function(){return this._numBytesAllocated},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"numBytesFree",{get:function(){return this._numBytesFree},enumerable:!0,configurable:!0}),n.prototype.getNumUsedTextures=function(){return this.numUsedTextures},n.prototype.getNumFreeTextures=function(){return this.numFreeTextures},n.prototype.dispose=function(){var t=this;if(this.freeTextures==null)return;for(var e in this.freeTextures)this.freeTextures[e].forEach(function(i){t.gpgpu.deleteMatrixTexture(i)});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(r){t.gpgpu.deleteMatrixTexture(r)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0},n}();function Q9(n,t){var e=n;if(t===e.R32F)return 4;if(t===e.R16F)return 2;if(t===e.RGBA32F)return 16;if(t===n.RGBA)return 16;if(t===e.RGBA16F)return 8;throw new Error("Unknown internal format "+t)}function TS(n,t,e,i,r){var a=eM(t,i),s;if(r){var o=$r(n[0],n[1]),l=o[0],u=o[1];s=l*u}else{var c=Ka(n[0],n[1]),h=c[0],d=c[1];s=h*d}var p=Q9(e,a);return s*p}function eM(n,t){switch(n){case Ct.PACKED_2X2_FLOAT32:return Bd(t);case Ct.PACKED_2X2_FLOAT16:return zd(t);case Ct.UNPACKED_FLOAT32:return Fd(t);case Ct.UNPACKED_FLOAT16:return Wd(t);case Ct.PACKED_4X1_UNSIGNED_BYTE:return Ud(t);default:throw new Error("Unknown physical texture type "+n)}}function tM(n){return R.env().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?n?Ct.PACKED_2X2_FLOAT32:Ct.UNPACKED_FLOAT32:n?Ct.PACKED_2X2_FLOAT16:Ct.UNPACKED_FLOAT16}function NS(n,t){if(n===tn.UPLOAD)return Ct.PACKED_2X2_FLOAT32;if(n===tn.RENDER||n==null)return tM(t);if(n===tn.DOWNLOAD||n===tn.PIXELS)return Ct.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+n)}function xS(n,t,e){return n[0]+"_"+n[1]+"_"+t+"_"+e}var iM=function(){function n(t,e){this.variableNames=["A"];for(var i=new Array(t.length),r=0;r5)throw Error("Tile for rank "+t+" is not yet supported");if(t===1)return"imod(resRC, "+n[0]+")";for(var e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],i=[],r=0;r5)throw Error("Tile for rank "+t+" is not yet supported");if(t===1)return"imod(resRC, "+n[0]+")";for(var e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],i=[],r=0;r= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0); -`;function aM(n){return n===void 0&&(n=0),$n+(` +`;function sM(n){return n===void 0&&(n=0),$n+(` return x > 0.0 ? 1.0 : float(`+n+`); - `)}var DS="return -x;",kS="return ceil(x);",FS="return floor(x);",sM=` + `)}var DS="return -x;",kS="return ceil(x);",FS="return floor(x);",oM=` if (isnan(x)) { return 0.0; } return sign(x); -`,oM="return float(isnan(x));",lM="return float(isinf(x));",uM="return float(!isnan(x) && !isinf(x));",cM=` +`,lM="return float(isnan(x));",uM="return float(isinf(x));",cM="return float(!isnan(x) && !isinf(x));",hM=` // OpenGL ES does not support round function. // The algorithm is based on banker's rounding. float base = floor(x); @@ -3524,8 +3524,8 @@ return (round(mod(b, 2.0)) != 1) ? return base + 1.0; } } -`,WS="return exp(x);",US="return exp(x) - 1.0;",hM=`if (x < 0.0) return NAN; - return log(x);`,dM="return log(1.0 + x);",pM="return sqrt(x);",fM="return inversesqrt(x);",mM="return 1.0 / (1.0 + exp(-1.0 * x));",gM=` +`,WS="return exp(x);",US="return exp(x) - 1.0;",dM=`if (x < 0.0) return NAN; + return log(x);`,pM="return log(1.0 + x);",fM="return sqrt(x);",mM="return inversesqrt(x);",gM="return 1.0 / (1.0 + exp(-1.0 * x));",vM=` float epsilon = 1.1920928955078125e-7; float threshold = log(epsilon) + 2.0; @@ -3545,32 +3545,32 @@ return (round(mod(b, 2.0)) != 1) ? result = log(exp_x + 1.0); } return result; -`,vM=$n+` - if (abs(x) > 1.) { - return NAN; - } - return asin(x); `,yM=$n+` if (abs(x) > 1.) { return NAN; } - return acos(x); + return asin(x); `,bM=$n+` + if (abs(x) > 1.) { + return NAN; + } + return acos(x); +`,wM=$n+` return atan(x); -`,wM=` +`,SM=` float e2x = exp(x); return (e2x - 1.0 / e2x) / 2.0; -`,SM=` +`,LM=` float e2x = exp(-x); return (e2x + 1.0 / e2x) / 2.0; -`,LM=` +`,IM=` float e2x = exp(-2.0 * abs(x)); return sign(x) * (1.0 - e2x) / (1.0 + e2x); -`,IM=$n+"return log(x + sqrt(x * x + 1.0));",AM=$n+` +`,AM=$n+"return log(x + sqrt(x * x + 1.0));",TM=$n+` if (x < 1.0) return NAN; - return log(x + sqrt(x * x - 1.0));`,TM=$n+` + return log(x + sqrt(x * x - 1.0));`,NM=$n+` if ((x < -1.0) || (x > 1.0)) return NAN; - return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,NM=` + return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,xM=` // Error function is calculated approximately with elementary function. // See "Handbook of Mathematical Functions with Formulas, // Graphs, and Mathematical Tables", Abramowitz and Stegun. @@ -3585,7 +3585,7 @@ return (round(mod(b, 2.0)) != 1) ? x = abs(x); float t = 1.0 / (1.0 + p * x); return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x)); -`,xM="return 1.0 / x;",CM="return float(!(x >= 1.0));",RM="return float(int(x));",Uo="return x;";var OM="return x;",EM=` +`,CM="return 1.0 / x;",RM="return float(!(x >= 1.0));",OM="return float(int(x));",Uo="return x;";var EM="return x;",DM=` vec4 result = log(x); vec4 isNaN = vec4(lessThan(x, vec4(0.0))); result.r = isNaN.r == 1.0 ? NAN : result.r; @@ -3634,29 +3634,29 @@ return (round(mod(b, 2.0)) != 1) ? setOutput(y); } - `}return n}();var DM=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t;var e=t.length,i=$t("rc",e),r=Je(e),a=DP(e,i),s=i.slice(-2),o=e<=1?"rc":"vec2("+s.join(",")+")";this.userCode=` + `}return n}();var kM=function(){function n(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t;var e=t.length,i=$t("rc",e),r=Je(e),a=kP(e,i),s=i.slice(-2),o=e<=1?"rc":"vec2("+s.join(",")+")";this.userCode=` void main() { `+r+` rc = getOutputCoords(); vec4 packedInput = getA(`+a+`); setOutput(getChannel(packedInput, `+o+`)); } - `}return n}();var PS=R.backend_util.segment_util,kM=R.kernel_impls.split,FM=R.kernel_impls.tile,WM=R.kernel_impls.topkImpl,UM=R.kernel_impls.whereImpl,BM=1e-7,zM=1e-4,Bo={};function _M(n){return n in Bo||(Bo[n]={}),Bo[n]}function zo(n,t){if(t===void 0&&(t=!1),n==="linear")return t?OM:iM;if(n==="relu")return t?BS:RS;if(n==="elu")return t?_S:ES;if(n==="relu6")return t?zS:OS;if(n==="prelu")return t?$0:j0;throw new Error("Activation "+n+" has not been implemented for the WebGL backend.")}var PM=128,MM=600;function HM(){return R.env().global.screen==null?1024:R.env().global.screen.height*R.env().global.screen.width*window.devicePixelRatio*MM/1024/1024}var MS=1e3,HS=function(n){__(t,n);function t(e){var i=n.call(this)||this;if(i.pendingRead=new WeakMap,i.pendingDisposal=new WeakSet,i.dataRefCount=new WeakMap,i.numBytesInGPU=0,i.uploadWaitMs=0,i.downloadWaitMs=0,i.warnedAboutMemory=!1,i.warnedAboutCPUBackend=!1,i.pendingDeletes=0,i.disposed=!1,!R.env().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){var r=Wn(R.env().getNumber("WEBGL_VERSION"));i.binaryCache=_M(R.env().getNumber("WEBGL_VERSION")),i.gpgpu=new wS(r),i.canvas=r.canvas,i.gpgpuCreatedLocally=!0}else i.gpgpu=e,i.binaryCache={},i.gpgpuCreatedLocally=!1,i.canvas=e.gl.canvas;return i.textureManager=new J9(i.gpgpu),i.numMBBeforeWarning=HM(),i.texData=new R.DataStorage(i,R.engine()),i}return t.prototype.numDataIds=function(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes},t.prototype.write=function(e,i,r){if((R.env().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||R.env().getBool("DEBUG"))&&this.checkNumericalProblems(e),r==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");var a={};return this.texData.set(a,{shape:i,dtype:r,values:e,usage:tn.UPLOAD,refCount:1}),a},t.prototype.incRef=function(e){var i=this.texData.get(e);i.refCount++},t.prototype.decRef=function(e){if(this.texData.has(e)){var i=this.texData.get(e);i.refCount--}},t.prototype.move=function(e,i,r,a){if(R.env().getBool("DEBUG")&&this.checkNumericalProblems(i),a==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:r,dtype:a,values:i,usage:tn.UPLOAD,refCount:1})},t.prototype.disposeIntermediateTensorInfo=function(e){var i=e.dataId;if(this.texData.has(i)){var r=this.texData.get(i);r.refCount--,r.refCount<1&&this.disposeData(i)}},t.prototype.readSync=function(e){var i=this.texData.get(e),r=i.values,a=i.dtype,s=i.complexTensors,o=i.slice,l=i.shape,u=i.isPacked;if(o!=null){var c=void 0;u?c=new es(l,Uo):c=new Re(l,Uo);var h=this.runWebGLProgram(c,[{dataId:e,shape:l,dtype:a}],a),d=this.readSync(h.dataId);return this.disposeIntermediateTensorInfo(h),d}if(r!=null)return this.convertAndCacheOnCPU(e);if(a==="string")return r;var p=this.activeTimers!=null,f;p&&(f=R.util.now());var m;if(a==="complex64"){var g=s.real.dataSync(),v=s.imag.dataSync();m=R.backend_util.mergeRealAndImagArrays(g,v)}else m=this.getValuesFromTexture(e);return p&&(this.downloadWaitMs+=R.util.now()-f),this.convertAndCacheOnCPU(e,m)},t.prototype.read=function(e){return No(this,void 0,void 0,function(){var i,r,a,s,o,l,u,c,h,d,p,f,m,g,v,b,S,L,w,N,I,C;return xo(this,function(E){switch(E.label){case 0:if(this.pendingRead.has(e))return i=this.pendingRead.get(e),[2,new Promise(function(k){return i.push(k)})];if(r=this.texData.get(e),a=r.values,s=r.shape,o=r.slice,l=r.dtype,u=r.complexTensors,c=r.isPacked,o!=null)return h=void 0,c?h=new es(s,Uo):h=new Re(s,Uo),d=this.runWebGLProgram(h,[{dataId:e,shape:s,dtype:l}],l),p=this.read(d.dataId),this.disposeIntermediateTensorInfo(d),[2,p];if(a!=null)return[2,this.convertAndCacheOnCPU(e)];if(!R.env().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&R.env().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return f=null,l!=="complex64"&&R.env().get("WEBGL_BUFFER_SUPPORTED")&&(m=this.decode(e),g=this.texData.get(m.dataId),f=(C=this.gpgpu).createBufferFromTexture.apply(C,[g.texture].concat(ja(s)))),this.pendingRead.set(e,[]),l!=="complex64"?[4,this.gpgpu.createAndWaitForFence()]:[3,2];case 1:E.sent(),E.label=2;case 2:return l==="complex64"?[4,Promise.all([u.real.data(),u.imag.data()])]:[3,4];case 3:return b=E.sent(),S=b[0],L=b[1],v=R.backend_util.mergeRealAndImagArrays(S,L),[3,5];case 4:f==null?v=this.getValuesFromTexture(e):(w=R.util.sizeFromShape(s),v=this.gpgpu.downloadFloat32MatrixFromBuffer(f,w)),E.label=5;case 5:return m!=null&&this.disposeIntermediateTensorInfo(m),N=this.convertAndCacheOnCPU(e,v),I=this.pendingRead.get(e),this.pendingRead.delete(e),I.forEach(function(k){return k(N)}),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e),this.pendingDeletes--),[2,N]}})})},t.prototype.checkNumericalProblems=function(e){if(e==null)return;for(var i=0;i0?[4,Promise.all(s)]:[3,2];case 1:return u=c.sent(),l.kernelMs=R.util.sum(u),l.getExtraProfileInfo=function(){return u.map(function(h,d){return{name:o[d],ms:h}}).map(function(h){return h.name+": "+h.ms}).join(", ")},[3,3];case 2:l.kernelMs={error:"WebGL query timers are not supported in this environment."},c.label=3;case 3:return this.uploadWaitMs=0,this.downloadWaitMs=0,[2,l]}})})},t.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}},t.prototype.startTimer=function(){return R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:R.util.now(),endMs:null}},t.prototype.endTimer=function(e){return R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=R.util.now(),e)},t.prototype.getQueryTime=function(e){return No(this,void 0,void 0,function(){var i;return xo(this,function(r){return R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:(i=e,[2,i.endMs-i.startMs])})})},t.prototype.disposeData=function(e){if(this.pendingDisposal.has(e))return;if(this.pendingRead.has(e)){this.pendingDisposal.add(e),this.pendingDeletes++;return}if(!this.texData.has(e))return;this.releaseGPUData(e);var i=this.texData.get(e).complexTensors;i!=null&&(i.real.dispose(),i.imag.dispose()),this.texData.delete(e)},t.prototype.releaseGPUData=function(e){var i=this.texData.get(e),r=i.texture,a=i.dtype,s=i.texShape,o=i.usage,l=i.isPacked,u=i.slice,c=u&&u.origDataId||e,h=this.dataRefCount.get(c);h>1?this.dataRefCount.set(c,h-1):(this.dataRefCount.delete(c),r!=null&&(this.numBytesInGPU-=this.computeBytes(s,a),this.textureManager.releaseTexture(r,s,o,l)));var d=this.texData.get(e);d.texture=null,d.texShape=null,d.isPacked=!1,d.slice=null},t.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture},t.prototype.getDataInfo=function(e){return this.texData.get(e)},t.prototype.getCPUBackend=function(){return R.env().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=R.engine().findBackend("cpu")),this.cpuBackend):null},t.prototype.shouldExecuteOnCPU=function(e,i){var r=this;i===void 0&&(i=PM);var a=this.getCPUBackend();return!this.warnedAboutCPUBackend&&a==null&&(console.warn("Your application contains ops that are small enough to be executed on the CPU backend, however the CPU backend cannot be found. Consider importing the CPU backend (@tensorflow/tfjs-backend-cpu) for better performance."),this.warnedAboutCPUBackend=!0),a!=null&&e.every(function(s){return r.texData.get(s.dataId).texture==null&&R.util.sizeFromShape(s.shape)R.env().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var s=Math.floor(e.length/2),o=this.concat(e.slice(0,s),i),l=this.concat(e.slice(s),i);return this.concat([o,l],i)}if(R.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].rank>1){var u=new X5(e.map(function(f){return f.shape}),i);return this.compileAndRun(u,e)}var c=R.backend_util.computeOutShape(e.map(function(f){return f.shape}),i),h=e.map(function(f){return f.as2D(-1,R.util.sizeFromShape(f.shape.slice(i)))}),d=new $5(h.map(function(f){return f.shape})),p=this.compileAndRun(d,h);return p.reshape(c)},t.prototype.neg=function(e){var i=this,r=this.tryRunOnCpuOrThrow([e],function(){return i.cpuBackend.neg(e)});if(r)return r;if(R.env().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,DS,e.dtype);var a=new Re(e.shape,DS);return this.compileAndRun(a,[e])},t.prototype.batchMatMul=function(e,i,r,a){var s=r?e.shape[2]:e.shape[1],o=a?i.shape[1]:i.shape[2],l=r?e.shape[1]:e.shape[2],u=e.shape,c=u[0];if((s===1||o===1)&&l>MS){r&&(e=R.transpose(e,[0,2,1])),a&&(i=R.transpose(i,[0,2,1]));var h=o===1?e:e.as3D(c,l,1),d=o===1?2:1,p=o===1?i.as3D(c,1,l):i;return this.multiply(h,p).sum(d,!0)}var f=R.upcastType(e.dtype,i.dtype),m=new _d(e.shape,[c,s,o],r,a);return this.compileAndRun(m,[e,i],f)},t.prototype.fusedBatchMatMul=function(e){var i=e.a,r=e.b,a=e.transposeA,s=e.transposeB,o=e.bias,l=e.activation,u=e.preluActivationWeights,c=a?i.shape[2]:i.shape[1],h=s?r.shape[1]:r.shape[2],d=i.shape,p=d[0],f=R.upcastType(i.dtype,r.dtype),m=o!=null,g=u!=null,v=l?zo(l,!0):null,b=new _d(i.shape,[p,c,h],a,s,m,v,g),S=[i,r];return o&&S.push(o),u&&S.push(u),this.compileAndRun(b,S,f)},t.prototype.multiply=function(e,i){if(e.dtype==="complex64"){var r=this.texData.get(e.dataId),a=this.texData.get(i.dataId),s=new G0(q0.REAL,e.shape,i.shape),o=new G0(q0.IMAG,e.shape,i.shape),l=[this.makeComplexComponentTensorInfo(e,r.complexTensors.real),this.makeComplexComponentTensorInfo(e,r.complexTensors.imag),this.makeComplexComponentTensorInfo(i,a.complexTensors.real),this.makeComplexComponentTensorInfo(i,a.complexTensors.imag)],u=this.compileAndRun(s,l),c=this.compileAndRun(o,l),h=this.complex(u,c);return u.dispose(),c.dispose(),h}var d=R.upcastType(e.dtype,i.dtype);if(this.shouldExecuteOnCPU([e,i])){var r=this.texData.get(e.dataId),a=this.texData.get(i.dataId),p=AP(e.shape,i.shape,r.values,a.values,d),f=p[0],m=p[1];return this.makeOutput(m,d,f)}if(R.env().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,i,K0,e.dtype);var g=new wt(K0,e.shape,i.shape);return this.compileAndRun(g,[e,i],e.dtype)},t.prototype.localResponseNormalization4D=function(e,i,r,a,s){var o=R.env().getBool("WEBGL_PACK_NORMALIZATION")?new T9(e.shape,i,r,a,s):new I9(e.shape,i,r,a,s);return this.compileAndRun(o,[e])},t.prototype.LRNGrad=function(e,i,r,a,s,o,l){var u=new A9(i.shape,a,s,o,l);return this.compileAndRun(u,[i,r,e])},t.prototype.tile=function(e,i){if(e.dtype==="string"){var r=this.readSync(e.dataId),a=r.map(function(l){return R.util.decodeString(l)}),s=R.buffer(e.shape,e.dtype,a);return FM(s,i)}var o=new nM(e.shape,i);return this.compileAndRun(o,[e])},t.prototype.pad=function(e,i,r){var a=R.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new U9(e.shape,i,r):new W9(e.shape,i,r);return this.compileAndRun(a,[e])},t.prototype.gather=function(e,i,r){var a=this,s=this.tryRunOnCpuOrThrow([e,i],function(){return a.cpuBackend.gather(e,i,r)});if(s)return s;var o=new m9(e.shape,i.size,r);return this.compileAndRun(o,[e,i])},t.prototype.batchToSpaceND=function(e,i,r){R.util.assert(e.rank<=4,function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"});var a=i.reduce(function(h,d){return h*d}),s=R.backend_util.getReshaped(e.shape,i,a),o=R.backend_util.getPermuted(s.length,i.length),l=R.backend_util.getReshapedPermuted(e.shape,i,a),u=R.backend_util.getSliceBeginCoords(r,i.length),c=R.backend_util.getSliceSize(l,r,i.length);return R.transpose(e.reshape(s),o).reshape(l).slice(u,c)},t.prototype.spaceToBatchND=function(e,i,r){R.util.assert(e.rank<=4,function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"});var a=i.reduce(function(p,f){return p*f}),s=[[0,0]];s.push.apply(s,r);for(var o=1+i.length;oR.env().get("WEBGL_MAX_TEXTURES_IN_SHADER")){var i=Math.floor(e.length/2),r=this.addN(e.slice(0,i)),a=this.addN(e.slice(i));return this.addN([r,a])}var s=e.map(function(c){return c.dtype}).reduce(function(c,h){return R.upcastType(c,h)}),o=e.map(function(c){return c.shape}),l=R.env().getBool("WEBGL_PACK"),u=l?new OP(e[0].shape,o):new RP(e[0].shape,o);return this.compileAndRun(u,e,s)},t.prototype.subtract=function(e,i){if(e.dtype==="complex64"&&i.dtype==="complex64")return this.complexSeparableBinaryOp(e,i,kd);var r=R.upcastType(e.dtype,i.dtype);if(this.shouldExecuteOnCPU([e,i])){var a=this.texData.get(e.dataId),s=this.texData.get(i.dataId),o=xP(e.shape,i.shape,a.values,s.values,r),l=o[0],u=o[1];return this.makeOutput(u,r,l)}if(R.env().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,i,kd,e.dtype);var c=new wt(kd,e.shape,i.shape);return this.compileAndRun(c,[e,i],r)},t.prototype.pow=function(e,i){var r=R.env().getBool("WEBGL_PACK_BINARY_OPERATIONS"),a=r?new Si(k5,e.shape,i.shape):new wt(b5,e.shape,i.shape),s=R.upcastType(e.dtype,i.dtype);return this.compileAndRun(a,[e,i],s)},t.prototype.ceil=function(e){if(this.shouldExecuteOnCPU([e])){var i=yP(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,i)}if(R.env().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,kS,e.dtype);var r=new Re(e.shape,kS);return this.compileAndRun(r,[e])},t.prototype.floor=function(e){if(this.shouldExecuteOnCPU([e])){var i=SP(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,i)}if(R.env().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,FS,e.dtype);var r=new Re(e.shape,FS);return this.compileAndRun(r,[e])},t.prototype.sign=function(e){var i=new Re(e.shape,sM);return this.compileAndRun(i,[e])},t.prototype.isNaN=function(e){var i=new Re(e.shape,oM);return this.compileAndRun(i,[e],"bool")},t.prototype.isInf=function(e){var i=new Re(e.shape,lM);return this.compileAndRun(i,[e],"bool")},t.prototype.isFinite=function(e){var i=new Re(e.shape,uM);return this.compileAndRun(i,[e],"bool")},t.prototype.round=function(e){var i=new Re(e.shape,cM);return this.compileAndRun(i,[e])},t.prototype.exp=function(e){if(this.shouldExecuteOnCPU([e])){var i=bP(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,i)}if(R.env().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,WS,e.dtype);var r=new Re(e.shape,WS);return this.compileAndRun(r,[e])},t.prototype.expm1=function(e){if(this.shouldExecuteOnCPU([e])){var i=wP(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,i)}if(R.env().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,US,e.dtype);var r=new Re(e.shape,US);return this.compileAndRun(r,[e])},t.prototype.softmax=function(e,i){var r=R.util.parseAxisParam([i],e.shape),a=R.max(e,r),s=R.backend_util.expandShapeToKeepDim(a.shape,r),o=this.subtract(e,a.reshape(s)),l=this.exp(o),u=this.sum(l,r).reshape(s);return R.div(l,u)},t.prototype.log=function(e){if(this.shouldExecuteOnCPU([e])){var i=LP(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,i)}if(R.env().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,EM,e.dtype);var r=new Re(e.shape,hM);return this.compileAndRun(r,[e])},t.prototype.log1p=function(e){var i=new Re(e.shape,dM);return this.compileAndRun(i,[e])},t.prototype.sqrt=function(e){var i=new Re(e.shape,pM);return this.compileAndRun(i,[e])},t.prototype.rsqrt=function(e){if(this.shouldExecuteOnCPU([e])){var i=TP(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,i)}var r=new Re(e.shape,fM);return this.compileAndRun(r,[e])},t.prototype.reciprocal=function(e){var i=new Re(e.shape,xM);return this.compileAndRun(i,[e])},t.prototype.relu=function(e){var i;return R.env().getBool("WEBGL_PACK")?i=new es(e.shape,BS):i=new Re(e.shape,RS),this.compileAndRun(i,[e])},t.prototype.relu6=function(e){var i;return R.env().getBool("WEBGL_PACK")?i=new es(e.shape,zS):i=new Re(e.shape,OS),this.compileAndRun(i,[e])},t.prototype.prelu=function(e,i){var r=R.env().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Si($0,e.shape,i.shape):new wt(j0,e.shape,i.shape);return this.compileAndRun(r,[e,i])},t.prototype.elu=function(e){if(R.env().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,_S,e.dtype);var i=new Re(e.shape,ES);return this.compileAndRun(i,[e])},t.prototype.eluDer=function(e,i){var r=R.env().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Si(F5,e.shape,i.shape):new wt(E5,e.shape,i.shape);return this.compileAndRun(r,[e,i])},t.prototype.selu=function(e){var i=new Re(e.shape,rM);return this.compileAndRun(i,[e])},t.prototype.int=function(e){var i=new Re(e.shape,RM);return this.compileAndRun(i,[e],"int32")},t.prototype.clip=function(e,i,r){var a;R.env().getBool("WEBGL_PACK_CLIP")?a=new K5(e.shape):a=new Y5(e.shape);var s=a.getCustomSetupFunc(i,r);return this.compileAndRun(a,[e],null,s)},t.prototype.abs=function(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){var i=gP(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,i)}if(R.env().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,CS,e.dtype);var r=new Re(e.shape,CS);return this.compileAndRun(r,[e])},t.prototype.complexAbs=function(e){var i=this.texData.get(e.dataId),r=new j5(e.shape),a=[this.makeComplexComponentTensorInfo(e,i.complexTensors.real),this.makeComplexComponentTensorInfo(e,i.complexTensors.imag)];return this.compileAndRun(r,a)},t.prototype.sigmoid=function(e){var i=new Re(e.shape,mM);return this.compileAndRun(i,[e])},t.prototype.softplus=function(e){var i=new Re(e.shape,gM);return this.compileAndRun(i,[e])},t.prototype.asin=function(e){var i=new Re(e.shape,vM);return this.compileAndRun(i,[e])},t.prototype.acos=function(e){var i=new Re(e.shape,yM);return this.compileAndRun(i,[e])},t.prototype.atan=function(e){var i=new Re(e.shape,bM);return this.compileAndRun(i,[e])},t.prototype.sinh=function(e){var i=new Re(e.shape,wM);return this.compileAndRun(i,[e])},t.prototype.cosh=function(e){var i=new Re(e.shape,SM);return this.compileAndRun(i,[e])},t.prototype.tanh=function(e){var i=new Re(e.shape,LM);return this.compileAndRun(i,[e])},t.prototype.asinh=function(e){var i=new Re(e.shape,IM);return this.compileAndRun(i,[e])},t.prototype.acosh=function(e){var i=new Re(e.shape,AM);return this.compileAndRun(i,[e])},t.prototype.atanh=function(e){var i=new Re(e.shape,TM);return this.compileAndRun(i,[e])},t.prototype.erf=function(e){var i=new Re(e.shape,NM);return this.compileAndRun(i,[e])},t.prototype.step=function(e,i){var r=new Re(e.shape,aM(i));return this.compileAndRun(r,[e])},t.prototype.conv2dByMatMul=function(e,i,r,a,s,o){var l=e.shape,u=this.texData.get(e.dataId),c=r.inChannels,h=l[0]*l[1]*l[2],d=r.outChannels,p=r.dataFormat==="channelsLast",f=!1,m=!1,g=(h===1||d===1)&&c>MS,v=l[2]%2!==0&&!!u.isPacked;if(g||!R.env().getBool("WEBGL_LAZILY_UNPACK")||!R.env().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!v){var b=p?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],S=R.reshape(e,[1,b,r.inChannels]),L=R.reshape(i,[1,r.inChannels,r.outChannels]),w=this.fusedBatchMatMul({a:S,b:L,transposeA:f,transposeB:m,bias:a,activation:s,preluActivationWeights:o});return R.reshape(w,r.outShape)}var N=p?l[0]*l[1]*(l[2]+1):l[0]*l[2]*(l[3]+1),I={dataId:e.dataId,shape:[1,N,r.inChannels],dtype:e.dtype},C=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,R.util.assert(Ja(u.shape,I.shape),function(){return"packed reshape "+u.shape+" to "+I.shape+" isn't free"});var E=R.reshape(i,[1,r.inChannels,r.outChannels]),k=this.fusedBatchMatMul({a:I,b:E,transposeA:f,transposeB:m,bias:a,activation:s,preluActivationWeights:o}),W=this.texData.get(k.dataId);return R.util.assert(W.isPacked,function(){return"batchMatMul result is expected to be packed"}),u.shape=C,W.shape=r.outShape,R.engine().makeTensorFromDataId(k.dataId,r.outShape,k.dtype)},t.prototype.conv2dWithIm2Row=function(e,i,r,a,s,o){var l=r.filterWidth,u=r.filterHeight,c=r.inChannels,h=r.outWidth,d=r.outHeight,p=r.dataFormat,f=p==="channelsLast",m=l*u*c,g=d*h,v=[m,g],b=!0,S=!1,L=e.squeeze([0]),w=i.reshape([1,m,-1]),N=new L9(v,L.shape,r),I=this.compileAndRun(N,[L]).reshape([1,v[0],v[1]]),C=a!=null,E=o!=null,k=s?zo(s,!0):null,W=new _d(I.shape,[1,g,r.outChannels],b,S,C,k,E),F=[I,w];a&&F.push(a),E&&F.push(o);var _=this.compileAndRun(W,F);return f?_.reshape([1,d,h,r.outChannels]):_.reshape([1,r.outChannels,d,h])},t.prototype.fusedConv2d=function(e){var i=e.input,r=e.filter,a=e.convInfo,s=e.bias,o=e.activation,l=e.preluActivationWeights;if(a.filterHeight===1&&a.filterWidth===1&&a.dilationHeight===1&&a.dilationWidth===1&&a.strideHeight===1&&a.strideWidth===1&&(a.padInfo.type==="SAME"||a.padInfo.type==="VALID"))return this.conv2dByMatMul(i,r,a,s,o,l);if(R.env().getBool("WEBGL_CONV_IM2COL")&&i.shape[0]===1)return this.conv2dWithIm2Row(i,r,a,s,o,l);var u=s!=null,c=l!=null,h=o?zo(o,!1):null,d=new X0(a,u,h,c),p=[i,r];return s&&p.push(s),l&&p.push(l),this.compileAndRun(d,p)},t.prototype.conv2d=function(e,i,r){if(r.filterHeight===1&&r.filterWidth===1&&r.dilationHeight===1&&r.dilationWidth===1&&r.strideHeight===1&&r.strideWidth===1&&(r.padInfo.type==="SAME"||r.padInfo.type==="VALID"))return this.conv2dByMatMul(e,i,r);if(R.env().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,i,r);var a=new X0(r);return this.compileAndRun(a,[e,i])},t.prototype.conv2dDerInput=function(e,i,r){var a=new Z5(r);return this.compileAndRun(a,[e,i])},t.prototype.conv2dDerFilter=function(e,i,r){var a=new J5(r);return this.compileAndRun(a,[e,i])},t.prototype.fusedDepthwiseConv2D=function(e){var i=e.input,r=e.filter,a=e.convInfo,s=e.bias,o=e.activation,l=e.preluActivationWeights,u=R.env().getBool("WEBGL_PACK_DEPTHWISECONV")&&a.strideWidth<=2&&a.outChannels/a.inChannels===1,c=o?zo(o,u):null,h=[i,r],d=s!=null,p=l!=null;d&&h.push(s),p&&h.push(l);var f;return u?(f=new Z0(a,d,c,p),this.compileAndRun(f,h)):(f=new J0(a,d,c,p),this.compileAndRun(f,h))},t.prototype.depthwiseConv2D=function(e,i,r){var a;return R.env().getBool("WEBGL_PACK_DEPTHWISECONV")&&r.strideWidth<=2&&r.outChannels/r.inChannels===1?(a=new Z0(r),this.compileAndRun(a,[e,i])):(a=new J0(r),this.compileAndRun(a,[e,i]))},t.prototype.depthwiseConv2DDerInput=function(e,i,r){var a=new n9(r);return this.compileAndRun(a,[e,i])},t.prototype.depthwiseConv2DDerFilter=function(e,i,r){var a=new t9(r);return this.compileAndRun(a,[e,i])},t.prototype.conv3d=function(e,i,r){var a=new i9(r);return this.compileAndRun(a,[e,i])},t.prototype.conv3dDerInput=function(e,i,r){var a=new e9(r);return this.compileAndRun(a,[e,i])},t.prototype.conv3dDerFilter=function(e,i,r){var a=new Q5(r);return this.compileAndRun(a,[e,i])},t.prototype.cast=function(e,i){return R.backend_util.castTensor(e,i,this)},t.prototype.unstack=function(e,i){for(var r=e.shape[i],a=new Array(e.rank-1),s=0,o=0;o1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+i});var a=e.shape[0],s=r==="NHWC"?e.shape[1]:e.shape[2],o=r==="NHWC"?e.shape[2]:e.shape[3],l=r==="NHWC"?e.shape[3]:e.shape[1],u=s*i,c=o*i,h=l/(i*i),d=r==="NHWC"?[a,u,c,h]:[a,h,u,c],p=new o9(d,i,r);return this.compileAndRun(p,[e])},t.prototype.split=function(e,i,r){return kM(e,i,r)},t.prototype.scatterND=function(e,i,r){var a=R.backend_util.calculateShapes(i,e,r),s=a.sliceRank,o=a.numUpdates,l=a.sliceSize,u=a.strides,c=a.outputSize,h=[c/l,l],d=e.reshape([o,s]),p=i.reshape([o,l]);if(c===0)return R.backend_util.reshapeTensor(R.tensor([]),r);var f=R.scalar(0),m=new AS(o,s,d.rank,p.rank,u,h),g=this.compileAndRun(m,[p,d,f]);return g.reshape(r)},t.prototype.sparseToDense=function(e,i,r,a){var s=R.backend_util.calculateShapes(i,e,r),o=s.sliceRank,l=s.numUpdates,u=s.strides,c=s.outputSize,h=!1,d=new AS(l,o,e.rank,i.rank,u,[c,1],h),p=this.compileAndRun(d,[i,e,a]);return p.reshape(r)},t.prototype.fft=function(e){var i=!1;return this.fftImpl(e,i)},t.prototype.ifft=function(e){var i=!0;return this.fftImpl(e,i)},t.prototype.fftImpl=function(e,i){var r=this.texData.get(e.dataId),a=new iS(nS.REAL,e.shape,i),s=new iS(nS.IMAG,e.shape,i),o=[this.makeComplexComponentTensorInfo(e,r.complexTensors.real),this.makeComplexComponentTensorInfo(e,r.complexTensors.imag)],l=this.compileAndRun(a,o),u=this.compileAndRun(s,o),c=this.complex(l,u).as2D(e.shape[0],e.shape[1]);return l.dispose(),u.dispose(),c},t.prototype.gatherND=function(e,i){var r=i.shape,a=r[r.length-1],s=R.backend_util.prepareAndValidate(e,i),o=s[0],l=s[1],u=s[2],c=s[3],h=i.reshape([l,a]),d=e.reshape([e.size/u,u]),p=new g9(a,c,[l,u]),f=this.compileAndRun(p,[d,h]);return f.reshape(o)},t.prototype.fill=function(e,i,r){if(r=r||R.util.inferDtype(i),r==="string"){var a=R.util.getArrayFromDType(r,R.util.sizeFromShape(e));return a.fill(i),R.engine().makeTensor(a,e,r,this)}else{var s=new p9(e,i),o=s.getCustomSetupFunc(i);return this.compileAndRun(s,[],r,o)}},t.prototype.onesLike=function(e){if(e.dtype==="string")throw new Error("onesLike is not supported under string dtype");return this.fill(e.shape,1,e.dtype)},t.prototype.zerosLike=function(e){return this.fill(e.shape,e.dtype==="string"?"":0,e.dtype)},t.prototype.linspace=function(e,i,r){return R.backend_util.linspaceImpl(e,i,r)},t.prototype.makeTensorInfo=function(e,i,r){var a=this.write(r,e,i);return this.texData.get(a).usage=null,{dataId:a,shape:e,dtype:i}},t.prototype.makeOutput=function(e,i,r){var a=this.makeTensorInfo(e,i,r).dataId;return R.engine().makeTensorFromDataId(a,e,i,this)},t.prototype.unpackTensor=function(e){var i=new DM(e.shape);return this.runWebGLProgram(i,[e],e.dtype)},t.prototype.packTensor=function(e){var i=new k9(e.shape),r=!0;return this.runWebGLProgram(i,[e],e.dtype,null,r)},t.prototype.packedReshape=function(e,i){var r=[or(e.shape)].concat(lr(e.shape)),a={dtype:e.dtype,shape:r,dataId:e.dataId},s=[or(i)].concat(lr(i)),o=new IS(s,r),l=!0,u=this.runWebGLProgram(o,[a],e.dtype,null,l);return{dataId:u.dataId,shape:i,dtype:u.dtype}},t.prototype.decode=function(e){var i=this.texData.get(e),r=i.isPacked,a=i.shape,s=i.dtype,o=Oo(a),l;r?l=new s9(o):l=new a9(o);var u=!0,c=this.runWebGLProgram(l,[{shape:o,dtype:s,dataId:e}],s,null,u);return{dtype:s,shape:a,dataId:c.dataId}},t.prototype.runWebGLProgram=function(e,i,r,a,s){var o=this;s===void 0&&(s=!1);var l=this.makeTensorInfo(e.outputShape,r),u=this.texData.get(l.dataId);if(e.packedOutput&&(u.isPacked=!0),e.outPackingScheme===Ya.DENSE){var c=ja(e.outputShape);u.texShape=c.map(function(S){return S*2})}if(e.outTexUsage!=null&&(u.usage=e.outTexUsage),R.util.sizeFromShape(l.shape)===0)return u.values=R.util.getTypedArrayFromDType(l.dtype,0),l;var h=[],d=i.map(function(S){if(S.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var L=o.texData.get(S.dataId);if(L.texture==null){if(!e.packedInputs&&R.util.sizeFromShape(S.shape)<=R.env().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:S.shape,texData:null,isUniform:!0,uniformValues:L.values};e.packedInputs&&(L.isPacked=!0,L.shape=S.shape)}else if(!!L.isPacked!==!!e.packedInputs)S=L.isPacked?o.unpackTensor(S):o.packTensor(S),h.push(S),L=o.texData.get(S.dataId);else if(L.isPacked&&!Ja(L.shape,S.shape)){var w=S,N=S.shape;S.shape=L.shape,S=o.packedReshape(S,N),h.push(S),L=o.texData.get(S.dataId),w.shape=N}return o.uploadToGPU(S.dataId),{shape:S.shape,texData:L,isUniform:!1}});this.uploadToGPU(l.dataId);var p={shape:l.shape,texData:u,isUniform:!1},f=S9(e,d,p),m=this.getAndSaveBinary(f,function(){return b9(o.gpgpu,e,d,p)}),g=this.activeTimers!=null,v;if(g&&(v=this.startTimer()),w9(this.gpgpu,m,d,p,a),h.forEach(function(S){return o.disposeIntermediateTensorInfo(S)}),g&&(v=this.endTimer(v),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(v)})),!R.env().getBool("WEBGL_LAZILY_UNPACK")&&u.isPacked&&s===!1){var b=this.unpackTensor(l);return this.disposeIntermediateTensorInfo(l),b}return l},t.prototype.compileAndRun=function(e,i,r,a,s){s===void 0&&(s=!1),r=r||i[0].dtype;var o=this.runWebGLProgram(e,i,r,a,s);return R.engine().makeTensorFromDataId(o.dataId,o.shape,o.dtype)},t.prototype.getAndSaveBinary=function(e,i){return e in this.binaryCache||(this.binaryCache[e]=i()),this.binaryCache[e]},t.prototype.getTextureManager=function(){return this.textureManager},t.prototype.dispose=function(){var e=this;if(this.disposed)return;if(!R.env().getBool("IS_TEST")){var i=Object.keys(this.binaryCache);i.forEach(function(r){e.gpgpu.deleteProgram(e.binaryCache[r].webGLProgram),delete e.binaryCache[r]})}this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0},t.prototype.floatPrecision=function(){var e=this;return this.floatPrecisionValue==null&&(this.floatPrecisionValue=R.tidy(function(){if(!R.env().get("WEBGL_RENDER_FLOAT32_ENABLED")){var i=R.env().getBool("DEBUG");R.env().set("DEBUG",!1);var r=e.abs(R.scalar(1e-8)).dataSync()[0];if(R.env().set("DEBUG",i),r>0)return 32}return 16})),this.floatPrecisionValue},t.prototype.epsilon=function(){return this.floatPrecision()===32?BM:zM},t.prototype.uploadToGPU=function(e){var i,r=this.texData.get(e),a=r.shape,s=r.dtype,o=r.values,l=r.texture,u=r.usage,c=r.isPacked;if(l!=null)return;var h=this.activeTimers!=null,d;h&&(d=R.util.now());var p=r.texShape;if(p==null&&(p=E0(a,c),r.texShape=p),o!=null){var f=Oo(a),m=void 0,g=p[1],v=p[0],b=o instanceof Uint8Array;c?(i=$r(p[0],p[1]),g=i[0],v=i[1],m=new d9(f,[v,g],b)):m=new h9(f,[v,g],b);var S=this.makeTensorInfo([v,g],s);b?this.texData.get(S.dataId).usage=tn.PIXELS:this.texData.get(S.dataId).usage=tn.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(S.dataId),g,v,o);var L=!0,w=this.runWebGLProgram(m,[S],s,null,L),N=this.texData.get(w.dataId);r.texture=N.texture,r.texShape=N.texShape,r.isPacked=N.isPacked,r.usage=N.usage,this.disposeIntermediateTensorInfo(S),this.texData.delete(w.dataId),r.values=null,h&&(this.uploadWaitMs+=R.util.now()-d)}else{var I=this.acquireTexture(p,u,s,c);r.texture=I}},t.prototype.convertAndCacheOnCPU=function(e,i){var r=this.texData.get(e),a=r.dtype;return this.releaseGPUData(e),i!=null&&(r.values=VM(i,a)),r.values},t.prototype.acquireTexture=function(e,i,r,a){if(this.numBytesInGPU+=this.computeBytes(e,r),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){var s=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+s+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(e,i,a)},t.prototype.computeBytes=function(e,i){return e[0]*e[1]*R.util.bytesPerElement(i)},t.prototype.tryRunOnCpuOrThrow=function(e,i){if(this.shouldExecuteOnCPU(e))try{return i()}catch(r){if(R.env().getBool("IS_TEST"))throw new Error("CPU forwarding failed")}return null},t}(R.KernelBackend);function VM(n,t){if(t==="float32"||t==="complex64")return n;if(t==="int32"||t==="bool"){for(var e=t==="int32"?new Int32Array(n.length):new Uint8Array(n.length),i=0;i0?[4,Promise.all(s)]:[3,2];case 1:return u=c.sent(),l.kernelMs=R.util.sum(u),l.getExtraProfileInfo=function(){return u.map(function(h,d){return{name:o[d],ms:h}}).map(function(h){return h.name+": "+h.ms}).join(", ")},[3,3];case 2:l.kernelMs={error:"WebGL query timers are not supported in this environment."},c.label=3;case 3:return this.uploadWaitMs=0,this.downloadWaitMs=0,[2,l]}})})},t.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}},t.prototype.startTimer=function(){return R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:R.util.now(),endMs:null}},t.prototype.endTimer=function(e){return R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=R.util.now(),e)},t.prototype.getQueryTime=function(e){return No(this,void 0,void 0,function(){var i;return xo(this,function(r){return R.env().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:(i=e,[2,i.endMs-i.startMs])})})},t.prototype.disposeData=function(e){if(this.pendingDisposal.has(e))return;if(this.pendingRead.has(e)){this.pendingDisposal.add(e),this.pendingDeletes++;return}if(!this.texData.has(e))return;this.releaseGPUData(e);var i=this.texData.get(e).complexTensors;i!=null&&(i.real.dispose(),i.imag.dispose()),this.texData.delete(e)},t.prototype.releaseGPUData=function(e){var i=this.texData.get(e),r=i.texture,a=i.dtype,s=i.texShape,o=i.usage,l=i.isPacked,u=i.slice,c=u&&u.origDataId||e,h=this.dataRefCount.get(c);h>1?this.dataRefCount.set(c,h-1):(this.dataRefCount.delete(c),r!=null&&(this.numBytesInGPU-=this.computeBytes(s,a),this.textureManager.releaseTexture(r,s,o,l)));var d=this.texData.get(e);d.texture=null,d.texShape=null,d.isPacked=!1,d.slice=null},t.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture},t.prototype.getDataInfo=function(e){return this.texData.get(e)},t.prototype.getCPUBackend=function(){return R.env().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=R.engine().findBackend("cpu")),this.cpuBackend):null},t.prototype.shouldExecuteOnCPU=function(e,i){var r=this;i===void 0&&(i=MM);var a=this.getCPUBackend();return!this.warnedAboutCPUBackend&&a==null&&(console.warn("Your application contains ops that are small enough to be executed on the CPU backend, however the CPU backend cannot be found. Consider importing the CPU backend (@tensorflow/tfjs-backend-cpu) for better performance."),this.warnedAboutCPUBackend=!0),a!=null&&e.every(function(s){return r.texData.get(s.dataId).texture==null&&R.util.sizeFromShape(s.shape)R.env().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var s=Math.floor(e.length/2),o=this.concat(e.slice(0,s),i),l=this.concat(e.slice(s),i);return this.concat([o,l],i)}if(R.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].rank>1){var u=new J5(e.map(function(f){return f.shape}),i);return this.compileAndRun(u,e)}var c=R.backend_util.computeOutShape(e.map(function(f){return f.shape}),i),h=e.map(function(f){return f.as2D(-1,R.util.sizeFromShape(f.shape.slice(i)))}),d=new X5(h.map(function(f){return f.shape})),p=this.compileAndRun(d,h);return p.reshape(c)},t.prototype.neg=function(e){var i=this,r=this.tryRunOnCpuOrThrow([e],function(){return i.cpuBackend.neg(e)});if(r)return r;if(R.env().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,DS,e.dtype);var a=new Re(e.shape,DS);return this.compileAndRun(a,[e])},t.prototype.batchMatMul=function(e,i,r,a){var s=r?e.shape[2]:e.shape[1],o=a?i.shape[1]:i.shape[2],l=r?e.shape[1]:e.shape[2],u=e.shape,c=u[0];if((s===1||o===1)&&l>MS){r&&(e=R.transpose(e,[0,2,1])),a&&(i=R.transpose(i,[0,2,1]));var h=o===1?e:e.as3D(c,l,1),d=o===1?2:1,p=o===1?i.as3D(c,1,l):i;return this.multiply(h,p).sum(d,!0)}var f=R.upcastType(e.dtype,i.dtype),m=new _d(e.shape,[c,s,o],r,a);return this.compileAndRun(m,[e,i],f)},t.prototype.fusedBatchMatMul=function(e){var i=e.a,r=e.b,a=e.transposeA,s=e.transposeB,o=e.bias,l=e.activation,u=e.preluActivationWeights,c=a?i.shape[2]:i.shape[1],h=s?r.shape[1]:r.shape[2],d=i.shape,p=d[0],f=R.upcastType(i.dtype,r.dtype),m=o!=null,g=u!=null,v=l?zo(l,!0):null,b=new _d(i.shape,[p,c,h],a,s,m,v,g),S=[i,r];return o&&S.push(o),u&&S.push(u),this.compileAndRun(b,S,f)},t.prototype.multiply=function(e,i){if(e.dtype==="complex64"){var r=this.texData.get(e.dataId),a=this.texData.get(i.dataId),s=new G0(q0.REAL,e.shape,i.shape),o=new G0(q0.IMAG,e.shape,i.shape),l=[this.makeComplexComponentTensorInfo(e,r.complexTensors.real),this.makeComplexComponentTensorInfo(e,r.complexTensors.imag),this.makeComplexComponentTensorInfo(i,a.complexTensors.real),this.makeComplexComponentTensorInfo(i,a.complexTensors.imag)],u=this.compileAndRun(s,l),c=this.compileAndRun(o,l),h=this.complex(u,c);return u.dispose(),c.dispose(),h}var d=R.upcastType(e.dtype,i.dtype);if(this.shouldExecuteOnCPU([e,i])){var r=this.texData.get(e.dataId),a=this.texData.get(i.dataId),p=TP(e.shape,i.shape,r.values,a.values,d),f=p[0],m=p[1];return this.makeOutput(m,d,f)}if(R.env().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,i,K0,e.dtype);var g=new wt(K0,e.shape,i.shape);return this.compileAndRun(g,[e,i],e.dtype)},t.prototype.localResponseNormalization4D=function(e,i,r,a,s){var o=R.env().getBool("WEBGL_PACK_NORMALIZATION")?new N9(e.shape,i,r,a,s):new A9(e.shape,i,r,a,s);return this.compileAndRun(o,[e])},t.prototype.LRNGrad=function(e,i,r,a,s,o,l){var u=new T9(i.shape,a,s,o,l);return this.compileAndRun(u,[i,r,e])},t.prototype.tile=function(e,i){if(e.dtype==="string"){var r=this.readSync(e.dataId),a=r.map(function(l){return R.util.decodeString(l)}),s=R.buffer(e.shape,e.dtype,a);return WM(s,i)}var o=new iM(e.shape,i);return this.compileAndRun(o,[e])},t.prototype.pad=function(e,i,r){var a=R.env().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new B9(e.shape,i,r):new U9(e.shape,i,r);return this.compileAndRun(a,[e])},t.prototype.gather=function(e,i,r){var a=this,s=this.tryRunOnCpuOrThrow([e,i],function(){return a.cpuBackend.gather(e,i,r)});if(s)return s;var o=new g9(e.shape,i.size,r);return this.compileAndRun(o,[e,i])},t.prototype.batchToSpaceND=function(e,i,r){R.util.assert(e.rank<=4,function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"});var a=i.reduce(function(h,d){return h*d}),s=R.backend_util.getReshaped(e.shape,i,a),o=R.backend_util.getPermuted(s.length,i.length),l=R.backend_util.getReshapedPermuted(e.shape,i,a),u=R.backend_util.getSliceBeginCoords(r,i.length),c=R.backend_util.getSliceSize(l,r,i.length);return R.transpose(e.reshape(s),o).reshape(l).slice(u,c)},t.prototype.spaceToBatchND=function(e,i,r){R.util.assert(e.rank<=4,function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"});var a=i.reduce(function(p,f){return p*f}),s=[[0,0]];s.push.apply(s,r);for(var o=1+i.length;oR.env().get("WEBGL_MAX_TEXTURES_IN_SHADER")){var i=Math.floor(e.length/2),r=this.addN(e.slice(0,i)),a=this.addN(e.slice(i));return this.addN([r,a])}var s=e.map(function(c){return c.dtype}).reduce(function(c,h){return R.upcastType(c,h)}),o=e.map(function(c){return c.shape}),l=R.env().getBool("WEBGL_PACK"),u=l?new EP(e[0].shape,o):new OP(e[0].shape,o);return this.compileAndRun(u,e,s)},t.prototype.subtract=function(e,i){if(e.dtype==="complex64"&&i.dtype==="complex64")return this.complexSeparableBinaryOp(e,i,kd);var r=R.upcastType(e.dtype,i.dtype);if(this.shouldExecuteOnCPU([e,i])){var a=this.texData.get(e.dataId),s=this.texData.get(i.dataId),o=CP(e.shape,i.shape,a.values,s.values,r),l=o[0],u=o[1];return this.makeOutput(u,r,l)}if(R.env().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,i,kd,e.dtype);var c=new wt(kd,e.shape,i.shape);return this.compileAndRun(c,[e,i],r)},t.prototype.pow=function(e,i){var r=R.env().getBool("WEBGL_PACK_BINARY_OPERATIONS"),a=r?new Si(F5,e.shape,i.shape):new wt(w5,e.shape,i.shape),s=R.upcastType(e.dtype,i.dtype);return this.compileAndRun(a,[e,i],s)},t.prototype.ceil=function(e){if(this.shouldExecuteOnCPU([e])){var i=bP(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,i)}if(R.env().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,kS,e.dtype);var r=new Re(e.shape,kS);return this.compileAndRun(r,[e])},t.prototype.floor=function(e){if(this.shouldExecuteOnCPU([e])){var i=LP(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,i)}if(R.env().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,FS,e.dtype);var r=new Re(e.shape,FS);return this.compileAndRun(r,[e])},t.prototype.sign=function(e){var i=new Re(e.shape,oM);return this.compileAndRun(i,[e])},t.prototype.isNaN=function(e){var i=new Re(e.shape,lM);return this.compileAndRun(i,[e],"bool")},t.prototype.isInf=function(e){var i=new Re(e.shape,uM);return this.compileAndRun(i,[e],"bool")},t.prototype.isFinite=function(e){var i=new Re(e.shape,cM);return this.compileAndRun(i,[e],"bool")},t.prototype.round=function(e){var i=new Re(e.shape,hM);return this.compileAndRun(i,[e])},t.prototype.exp=function(e){if(this.shouldExecuteOnCPU([e])){var i=wP(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,i)}if(R.env().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,WS,e.dtype);var r=new Re(e.shape,WS);return this.compileAndRun(r,[e])},t.prototype.expm1=function(e){if(this.shouldExecuteOnCPU([e])){var i=SP(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,i)}if(R.env().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,US,e.dtype);var r=new Re(e.shape,US);return this.compileAndRun(r,[e])},t.prototype.softmax=function(e,i){var r=R.util.parseAxisParam([i],e.shape),a=R.max(e,r),s=R.backend_util.expandShapeToKeepDim(a.shape,r),o=this.subtract(e,a.reshape(s)),l=this.exp(o),u=this.sum(l,r).reshape(s);return R.div(l,u)},t.prototype.log=function(e){if(this.shouldExecuteOnCPU([e])){var i=IP(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,i)}if(R.env().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,DM,e.dtype);var r=new Re(e.shape,dM);return this.compileAndRun(r,[e])},t.prototype.log1p=function(e){var i=new Re(e.shape,pM);return this.compileAndRun(i,[e])},t.prototype.sqrt=function(e){var i=new Re(e.shape,fM);return this.compileAndRun(i,[e])},t.prototype.rsqrt=function(e){if(this.shouldExecuteOnCPU([e])){var i=NP(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,i)}var r=new Re(e.shape,mM);return this.compileAndRun(r,[e])},t.prototype.reciprocal=function(e){var i=new Re(e.shape,CM);return this.compileAndRun(i,[e])},t.prototype.relu=function(e){var i;return R.env().getBool("WEBGL_PACK")?i=new es(e.shape,BS):i=new Re(e.shape,RS),this.compileAndRun(i,[e])},t.prototype.relu6=function(e){var i;return R.env().getBool("WEBGL_PACK")?i=new es(e.shape,zS):i=new Re(e.shape,OS),this.compileAndRun(i,[e])},t.prototype.prelu=function(e,i){var r=R.env().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Si($0,e.shape,i.shape):new wt(j0,e.shape,i.shape);return this.compileAndRun(r,[e,i])},t.prototype.elu=function(e){if(R.env().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,_S,e.dtype);var i=new Re(e.shape,ES);return this.compileAndRun(i,[e])},t.prototype.eluDer=function(e,i){var r=R.env().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Si(W5,e.shape,i.shape):new wt(D5,e.shape,i.shape);return this.compileAndRun(r,[e,i])},t.prototype.selu=function(e){var i=new Re(e.shape,aM);return this.compileAndRun(i,[e])},t.prototype.int=function(e){var i=new Re(e.shape,OM);return this.compileAndRun(i,[e],"int32")},t.prototype.clip=function(e,i,r){var a;R.env().getBool("WEBGL_PACK_CLIP")?a=new j5(e.shape):a=new K5(e.shape);var s=a.getCustomSetupFunc(i,r);return this.compileAndRun(a,[e],null,s)},t.prototype.abs=function(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){var i=vP(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,i)}if(R.env().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,CS,e.dtype);var r=new Re(e.shape,CS);return this.compileAndRun(r,[e])},t.prototype.complexAbs=function(e){var i=this.texData.get(e.dataId),r=new $5(e.shape),a=[this.makeComplexComponentTensorInfo(e,i.complexTensors.real),this.makeComplexComponentTensorInfo(e,i.complexTensors.imag)];return this.compileAndRun(r,a)},t.prototype.sigmoid=function(e){var i=new Re(e.shape,gM);return this.compileAndRun(i,[e])},t.prototype.softplus=function(e){var i=new Re(e.shape,vM);return this.compileAndRun(i,[e])},t.prototype.asin=function(e){var i=new Re(e.shape,yM);return this.compileAndRun(i,[e])},t.prototype.acos=function(e){var i=new Re(e.shape,bM);return this.compileAndRun(i,[e])},t.prototype.atan=function(e){var i=new Re(e.shape,wM);return this.compileAndRun(i,[e])},t.prototype.sinh=function(e){var i=new Re(e.shape,SM);return this.compileAndRun(i,[e])},t.prototype.cosh=function(e){var i=new Re(e.shape,LM);return this.compileAndRun(i,[e])},t.prototype.tanh=function(e){var i=new Re(e.shape,IM);return this.compileAndRun(i,[e])},t.prototype.asinh=function(e){var i=new Re(e.shape,AM);return this.compileAndRun(i,[e])},t.prototype.acosh=function(e){var i=new Re(e.shape,TM);return this.compileAndRun(i,[e])},t.prototype.atanh=function(e){var i=new Re(e.shape,NM);return this.compileAndRun(i,[e])},t.prototype.erf=function(e){var i=new Re(e.shape,xM);return this.compileAndRun(i,[e])},t.prototype.step=function(e,i){var r=new Re(e.shape,sM(i));return this.compileAndRun(r,[e])},t.prototype.conv2dByMatMul=function(e,i,r,a,s,o){var l=e.shape,u=this.texData.get(e.dataId),c=r.inChannels,h=l[0]*l[1]*l[2],d=r.outChannels,p=r.dataFormat==="channelsLast",f=!1,m=!1,g=(h===1||d===1)&&c>MS,v=l[2]%2!==0&&!!u.isPacked;if(g||!R.env().getBool("WEBGL_LAZILY_UNPACK")||!R.env().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!v){var b=p?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],S=R.reshape(e,[1,b,r.inChannels]),L=R.reshape(i,[1,r.inChannels,r.outChannels]),w=this.fusedBatchMatMul({a:S,b:L,transposeA:f,transposeB:m,bias:a,activation:s,preluActivationWeights:o});return R.reshape(w,r.outShape)}var N=p?l[0]*l[1]*(l[2]+1):l[0]*l[2]*(l[3]+1),I={dataId:e.dataId,shape:[1,N,r.inChannels],dtype:e.dtype},C=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,R.util.assert(Ja(u.shape,I.shape),function(){return"packed reshape "+u.shape+" to "+I.shape+" isn't free"});var E=R.reshape(i,[1,r.inChannels,r.outChannels]),k=this.fusedBatchMatMul({a:I,b:E,transposeA:f,transposeB:m,bias:a,activation:s,preluActivationWeights:o}),W=this.texData.get(k.dataId);return R.util.assert(W.isPacked,function(){return"batchMatMul result is expected to be packed"}),u.shape=C,W.shape=r.outShape,R.engine().makeTensorFromDataId(k.dataId,r.outShape,k.dtype)},t.prototype.conv2dWithIm2Row=function(e,i,r,a,s,o){var l=r.filterWidth,u=r.filterHeight,c=r.inChannels,h=r.outWidth,d=r.outHeight,p=r.dataFormat,f=p==="channelsLast",m=l*u*c,g=d*h,v=[m,g],b=!0,S=!1,L=e.squeeze([0]),w=i.reshape([1,m,-1]),N=new I9(v,L.shape,r),I=this.compileAndRun(N,[L]).reshape([1,v[0],v[1]]),C=a!=null,E=o!=null,k=s?zo(s,!0):null,W=new _d(I.shape,[1,g,r.outChannels],b,S,C,k,E),F=[I,w];a&&F.push(a),E&&F.push(o);var _=this.compileAndRun(W,F);return f?_.reshape([1,d,h,r.outChannels]):_.reshape([1,r.outChannels,d,h])},t.prototype.fusedConv2d=function(e){var i=e.input,r=e.filter,a=e.convInfo,s=e.bias,o=e.activation,l=e.preluActivationWeights;if(a.filterHeight===1&&a.filterWidth===1&&a.dilationHeight===1&&a.dilationWidth===1&&a.strideHeight===1&&a.strideWidth===1&&(a.padInfo.type==="SAME"||a.padInfo.type==="VALID"))return this.conv2dByMatMul(i,r,a,s,o,l);if(R.env().getBool("WEBGL_CONV_IM2COL")&&i.shape[0]===1)return this.conv2dWithIm2Row(i,r,a,s,o,l);var u=s!=null,c=l!=null,h=o?zo(o,!1):null,d=new X0(a,u,h,c),p=[i,r];return s&&p.push(s),l&&p.push(l),this.compileAndRun(d,p)},t.prototype.conv2d=function(e,i,r){if(r.filterHeight===1&&r.filterWidth===1&&r.dilationHeight===1&&r.dilationWidth===1&&r.strideHeight===1&&r.strideWidth===1&&(r.padInfo.type==="SAME"||r.padInfo.type==="VALID"))return this.conv2dByMatMul(e,i,r);if(R.env().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,i,r);var a=new X0(r);return this.compileAndRun(a,[e,i])},t.prototype.conv2dDerInput=function(e,i,r){var a=new Q5(r);return this.compileAndRun(a,[e,i])},t.prototype.conv2dDerFilter=function(e,i,r){var a=new Z5(r);return this.compileAndRun(a,[e,i])},t.prototype.fusedDepthwiseConv2D=function(e){var i=e.input,r=e.filter,a=e.convInfo,s=e.bias,o=e.activation,l=e.preluActivationWeights,u=R.env().getBool("WEBGL_PACK_DEPTHWISECONV")&&a.strideWidth<=2&&a.outChannels/a.inChannels===1,c=o?zo(o,u):null,h=[i,r],d=s!=null,p=l!=null;d&&h.push(s),p&&h.push(l);var f;return u?(f=new Z0(a,d,c,p),this.compileAndRun(f,h)):(f=new J0(a,d,c,p),this.compileAndRun(f,h))},t.prototype.depthwiseConv2D=function(e,i,r){var a;return R.env().getBool("WEBGL_PACK_DEPTHWISECONV")&&r.strideWidth<=2&&r.outChannels/r.inChannels===1?(a=new Z0(r),this.compileAndRun(a,[e,i])):(a=new J0(r),this.compileAndRun(a,[e,i]))},t.prototype.depthwiseConv2DDerInput=function(e,i,r){var a=new i9(r);return this.compileAndRun(a,[e,i])},t.prototype.depthwiseConv2DDerFilter=function(e,i,r){var a=new n9(r);return this.compileAndRun(a,[e,i])},t.prototype.conv3d=function(e,i,r){var a=new r9(r);return this.compileAndRun(a,[e,i])},t.prototype.conv3dDerInput=function(e,i,r){var a=new t9(r);return this.compileAndRun(a,[e,i])},t.prototype.conv3dDerFilter=function(e,i,r){var a=new e9(r);return this.compileAndRun(a,[e,i])},t.prototype.cast=function(e,i){return R.backend_util.castTensor(e,i,this)},t.prototype.unstack=function(e,i){for(var r=e.shape[i],a=new Array(e.rank-1),s=0,o=0;o1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+i});var a=e.shape[0],s=r==="NHWC"?e.shape[1]:e.shape[2],o=r==="NHWC"?e.shape[2]:e.shape[3],l=r==="NHWC"?e.shape[3]:e.shape[1],u=s*i,c=o*i,h=l/(i*i),d=r==="NHWC"?[a,u,c,h]:[a,h,u,c],p=new l9(d,i,r);return this.compileAndRun(p,[e])},t.prototype.split=function(e,i,r){return FM(e,i,r)},t.prototype.scatterND=function(e,i,r){var a=R.backend_util.calculateShapes(i,e,r),s=a.sliceRank,o=a.numUpdates,l=a.sliceSize,u=a.strides,c=a.outputSize,h=[c/l,l],d=e.reshape([o,s]),p=i.reshape([o,l]);if(c===0)return R.backend_util.reshapeTensor(R.tensor([]),r);var f=R.scalar(0),m=new AS(o,s,d.rank,p.rank,u,h),g=this.compileAndRun(m,[p,d,f]);return g.reshape(r)},t.prototype.sparseToDense=function(e,i,r,a){var s=R.backend_util.calculateShapes(i,e,r),o=s.sliceRank,l=s.numUpdates,u=s.strides,c=s.outputSize,h=!1,d=new AS(l,o,e.rank,i.rank,u,[c,1],h),p=this.compileAndRun(d,[i,e,a]);return p.reshape(r)},t.prototype.fft=function(e){var i=!1;return this.fftImpl(e,i)},t.prototype.ifft=function(e){var i=!0;return this.fftImpl(e,i)},t.prototype.fftImpl=function(e,i){var r=this.texData.get(e.dataId),a=new iS(nS.REAL,e.shape,i),s=new iS(nS.IMAG,e.shape,i),o=[this.makeComplexComponentTensorInfo(e,r.complexTensors.real),this.makeComplexComponentTensorInfo(e,r.complexTensors.imag)],l=this.compileAndRun(a,o),u=this.compileAndRun(s,o),c=this.complex(l,u).as2D(e.shape[0],e.shape[1]);return l.dispose(),u.dispose(),c},t.prototype.gatherND=function(e,i){var r=i.shape,a=r[r.length-1],s=R.backend_util.prepareAndValidate(e,i),o=s[0],l=s[1],u=s[2],c=s[3],h=i.reshape([l,a]),d=e.reshape([e.size/u,u]),p=new v9(a,c,[l,u]),f=this.compileAndRun(p,[d,h]);return f.reshape(o)},t.prototype.fill=function(e,i,r){if(r=r||R.util.inferDtype(i),r==="string"){var a=R.util.getArrayFromDType(r,R.util.sizeFromShape(e));return a.fill(i),R.engine().makeTensor(a,e,r,this)}else{var s=new f9(e,i),o=s.getCustomSetupFunc(i);return this.compileAndRun(s,[],r,o)}},t.prototype.onesLike=function(e){if(e.dtype==="string")throw new Error("onesLike is not supported under string dtype");return this.fill(e.shape,1,e.dtype)},t.prototype.zerosLike=function(e){return this.fill(e.shape,e.dtype==="string"?"":0,e.dtype)},t.prototype.linspace=function(e,i,r){return R.backend_util.linspaceImpl(e,i,r)},t.prototype.makeTensorInfo=function(e,i,r){var a=this.write(r,e,i);return this.texData.get(a).usage=null,{dataId:a,shape:e,dtype:i}},t.prototype.makeOutput=function(e,i,r){var a=this.makeTensorInfo(e,i,r).dataId;return R.engine().makeTensorFromDataId(a,e,i,this)},t.prototype.unpackTensor=function(e){var i=new kM(e.shape);return this.runWebGLProgram(i,[e],e.dtype)},t.prototype.packTensor=function(e){var i=new F9(e.shape),r=!0;return this.runWebGLProgram(i,[e],e.dtype,null,r)},t.prototype.packedReshape=function(e,i){var r=[or(e.shape)].concat(lr(e.shape)),a={dtype:e.dtype,shape:r,dataId:e.dataId},s=[or(i)].concat(lr(i)),o=new IS(s,r),l=!0,u=this.runWebGLProgram(o,[a],e.dtype,null,l);return{dataId:u.dataId,shape:i,dtype:u.dtype}},t.prototype.decode=function(e){var i=this.texData.get(e),r=i.isPacked,a=i.shape,s=i.dtype,o=Oo(a),l;r?l=new o9(o):l=new s9(o);var u=!0,c=this.runWebGLProgram(l,[{shape:o,dtype:s,dataId:e}],s,null,u);return{dtype:s,shape:a,dataId:c.dataId}},t.prototype.runWebGLProgram=function(e,i,r,a,s){var o=this;s===void 0&&(s=!1);var l=this.makeTensorInfo(e.outputShape,r),u=this.texData.get(l.dataId);if(e.packedOutput&&(u.isPacked=!0),e.outPackingScheme===Ya.DENSE){var c=ja(e.outputShape);u.texShape=c.map(function(S){return S*2})}if(e.outTexUsage!=null&&(u.usage=e.outTexUsage),R.util.sizeFromShape(l.shape)===0)return u.values=R.util.getTypedArrayFromDType(l.dtype,0),l;var h=[],d=i.map(function(S){if(S.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var L=o.texData.get(S.dataId);if(L.texture==null){if(!e.packedInputs&&R.util.sizeFromShape(S.shape)<=R.env().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:S.shape,texData:null,isUniform:!0,uniformValues:L.values};e.packedInputs&&(L.isPacked=!0,L.shape=S.shape)}else if(!!L.isPacked!==!!e.packedInputs)S=L.isPacked?o.unpackTensor(S):o.packTensor(S),h.push(S),L=o.texData.get(S.dataId);else if(L.isPacked&&!Ja(L.shape,S.shape)){var w=S,N=S.shape;S.shape=L.shape,S=o.packedReshape(S,N),h.push(S),L=o.texData.get(S.dataId),w.shape=N}return o.uploadToGPU(S.dataId),{shape:S.shape,texData:L,isUniform:!1}});this.uploadToGPU(l.dataId);var p={shape:l.shape,texData:u,isUniform:!1},f=L9(e,d,p),m=this.getAndSaveBinary(f,function(){return w9(o.gpgpu,e,d,p)}),g=this.activeTimers!=null,v;if(g&&(v=this.startTimer()),S9(this.gpgpu,m,d,p,a),h.forEach(function(S){return o.disposeIntermediateTensorInfo(S)}),g&&(v=this.endTimer(v),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(v)})),!R.env().getBool("WEBGL_LAZILY_UNPACK")&&u.isPacked&&s===!1){var b=this.unpackTensor(l);return this.disposeIntermediateTensorInfo(l),b}return l},t.prototype.compileAndRun=function(e,i,r,a,s){s===void 0&&(s=!1),r=r||i[0].dtype;var o=this.runWebGLProgram(e,i,r,a,s);return R.engine().makeTensorFromDataId(o.dataId,o.shape,o.dtype)},t.prototype.getAndSaveBinary=function(e,i){return e in this.binaryCache||(this.binaryCache[e]=i()),this.binaryCache[e]},t.prototype.getTextureManager=function(){return this.textureManager},t.prototype.dispose=function(){var e=this;if(this.disposed)return;if(!R.env().getBool("IS_TEST")){var i=Object.keys(this.binaryCache);i.forEach(function(r){e.gpgpu.deleteProgram(e.binaryCache[r].webGLProgram),delete e.binaryCache[r]})}this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0},t.prototype.floatPrecision=function(){var e=this;return this.floatPrecisionValue==null&&(this.floatPrecisionValue=R.tidy(function(){if(!R.env().get("WEBGL_RENDER_FLOAT32_ENABLED")){var i=R.env().getBool("DEBUG");R.env().set("DEBUG",!1);var r=e.abs(R.scalar(1e-8)).dataSync()[0];if(R.env().set("DEBUG",i),r>0)return 32}return 16})),this.floatPrecisionValue},t.prototype.epsilon=function(){return this.floatPrecision()===32?zM:_M},t.prototype.uploadToGPU=function(e){var i,r=this.texData.get(e),a=r.shape,s=r.dtype,o=r.values,l=r.texture,u=r.usage,c=r.isPacked;if(l!=null)return;var h=this.activeTimers!=null,d;h&&(d=R.util.now());var p=r.texShape;if(p==null&&(p=E0(a,c),r.texShape=p),o!=null){var f=Oo(a),m=void 0,g=p[1],v=p[0],b=o instanceof Uint8Array;c?(i=$r(p[0],p[1]),g=i[0],v=i[1],m=new p9(f,[v,g],b)):m=new d9(f,[v,g],b);var S=this.makeTensorInfo([v,g],s);b?this.texData.get(S.dataId).usage=tn.PIXELS:this.texData.get(S.dataId).usage=tn.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(S.dataId),g,v,o);var L=!0,w=this.runWebGLProgram(m,[S],s,null,L),N=this.texData.get(w.dataId);r.texture=N.texture,r.texShape=N.texShape,r.isPacked=N.isPacked,r.usage=N.usage,this.disposeIntermediateTensorInfo(S),this.texData.delete(w.dataId),r.values=null,h&&(this.uploadWaitMs+=R.util.now()-d)}else{var I=this.acquireTexture(p,u,s,c);r.texture=I}},t.prototype.convertAndCacheOnCPU=function(e,i){var r=this.texData.get(e),a=r.dtype;return this.releaseGPUData(e),i!=null&&(r.values=qM(i,a)),r.values},t.prototype.acquireTexture=function(e,i,r,a){if(this.numBytesInGPU+=this.computeBytes(e,r),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){var s=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+s+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(e,i,a)},t.prototype.computeBytes=function(e,i){return e[0]*e[1]*R.util.bytesPerElement(i)},t.prototype.tryRunOnCpuOrThrow=function(e,i){if(this.shouldExecuteOnCPU(e))try{return i()}catch(r){if(R.env().getBool("IS_TEST"))throw new Error("CPU forwarding failed")}return null},t}(R.KernelBackend);function qM(n,t){if(t==="float32"||t==="complex64")return n;if(t==="int32"||t==="bool"){for(var e=t==="int32"?new Int32Array(n.length):new Uint8Array(n.length),i=0;i 0. ? NAN : result.r; result.g = isNaN.g > 0. ? NAN : result.g; result.b = isNaN.b > 0. ? NAN : result.b; result.a = isNaN.a > 0. ? NAN : result.a; -`;function _o(n){return function(t){var e=t.inputs,i=t.backend,r=e.x,a=i,s=new Re(r.shape,n);return a.runWebGLProgram(s,[r],r.dtype)}}function Hd(n,t,e,i){return function(r){var a=r.inputs,s=r.backend,o=a,l=o.a,u=o.b,c=s,h=R.env().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Si(t,l.shape,u.shape,!!e):new wt(n,l.shape,u.shape),d=i||l.dtype,p=c.runWebGLProgram(h,[l,u],d);return p}}var jM=YM+` +`;function _o(n){return function(t){var e=t.inputs,i=t.backend,r=e.x,a=i,s=new Re(r.shape,n);return a.runWebGLProgram(s,[r],r.dtype)}}function Hd(n,t,e,i){return function(r){var a=r.inputs,s=r.backend,o=a,l=o.a,u=o.b,c=s,h=R.env().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Si(t,l.shape,u.shape,!!e):new wt(n,l.shape,u.shape),d=i||l.dtype,p=c.runWebGLProgram(h,[l,u],d);return p}}var $M=KM+` return atan(a, b); -`,$M=` +`,XM=` vec4 result = atan(a, b); vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0)); - `+KM+` + `+jM+` return result; -`,XM=Hd(jM,$M),JM={kernelName:R.Atan2,backendName:"webgl",kernelFunc:XM};function Vd(n){var t=n.inputs,e=n.backend,i=t.x;return e.incRef(i.dataId),{dataId:i.dataId,shape:i.shape,dtype:i.dtype}}var ZM={kernelName:R.Identity,backendName:"webgl",kernelFunc:Vd};function QM(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.x;Xr(r,"avgPool");var a=i.filterSize,s=i.strides,o=i.pad,l=i.dimRoundingMode,u=1;R.util.assert(R.backend_util.eitherStridesOrDilationsAreOne(s,u),function(){return"Error in avgPool: Either strides or dilations must be 1. "+("Got strides "+s+" and dilations '"+u+"'")});var c=R.backend_util.computePool2DInfo(r.shape,a,s,u,o,l);if(c.filterWidth===1&&c.filterHeight===1&&R.util.arraysEqual(c.inShape,c.outShape))return Vd({inputs:{x:r},backend:e});var h=new Qa(c,"avg",!1);return e.runWebGLProgram(h,[r],"float32")}var e6={kernelName:R.AvgPool,backendName:"webgl",kernelFunc:QM};function t6(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.dy,a=t.input,s=a;Xr([r,a],"avgPoolBackprop");var o=i.filterSize,l=i.strides,u=i.pad,c=R.backend_util.computePool2DInfo(s.shape,o,l,1,u),h=new g5(c);return e.runWebGLProgram(h,[r],s.dtype)}var n6={kernelName:R.AvgPoolBackprop,backendName:"webgl",kernelFunc:t6};var i6=function(){function n(t,e,i,r,a,s){this.outputShape=[],this.variableNames=["x","mean","variance"],R.backend_util.assertAndGetBroadcastShape(t,e),R.backend_util.assertAndGetBroadcastShape(t,i);var o="0.0";r!=null&&(R.backend_util.assertAndGetBroadcastShape(t,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var l="1.0";a!=null&&(R.backend_util.assertAndGetBroadcastShape(t,a),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=` +`,JM=Hd($M,XM),ZM={kernelName:R.Atan2,backendName:"webgl",kernelFunc:JM};function Vd(n){var t=n.inputs,e=n.backend,i=t.x;return e.incRef(i.dataId),{dataId:i.dataId,shape:i.shape,dtype:i.dtype}}var QM={kernelName:R.Identity,backendName:"webgl",kernelFunc:Vd};function e6(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.x;Xr(r,"avgPool");var a=i.filterSize,s=i.strides,o=i.pad,l=i.dimRoundingMode,u=1;R.util.assert(R.backend_util.eitherStridesOrDilationsAreOne(s,u),function(){return"Error in avgPool: Either strides or dilations must be 1. "+("Got strides "+s+" and dilations '"+u+"'")});var c=R.backend_util.computePool2DInfo(r.shape,a,s,u,o,l);if(c.filterWidth===1&&c.filterHeight===1&&R.util.arraysEqual(c.inShape,c.outShape))return Vd({inputs:{x:r},backend:e});var h=new Qa(c,"avg",!1);return e.runWebGLProgram(h,[r],"float32")}var t6={kernelName:R.AvgPool,backendName:"webgl",kernelFunc:e6};function n6(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.dy,a=t.input,s=a;Xr([r,a],"avgPoolBackprop");var o=i.filterSize,l=i.strides,u=i.pad,c=R.backend_util.computePool2DInfo(s.shape,o,l,1,u),h=new v5(c);return e.runWebGLProgram(h,[r],s.dtype)}var i6={kernelName:R.AvgPoolBackprop,backendName:"webgl",kernelFunc:n6};var r6=function(){function n(t,e,i,r,a,s){this.outputShape=[],this.variableNames=["x","mean","variance"],R.backend_util.assertAndGetBroadcastShape(t,e),R.backend_util.assertAndGetBroadcastShape(t,i);var o="0.0";r!=null&&(R.backend_util.assertAndGetBroadcastShape(t,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var l="1.0";a!=null&&(R.backend_util.assertAndGetBroadcastShape(t,a),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=` void main() { float x = getXAtOutCoords(); float mean = getMeanAtOutCoords(); @@ -3666,7 +3666,7 @@ return (round(mod(b, 2.0)) != 1) ? float inv = scale * inversesqrt(variance + float(`+s+`)); setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1))); } - `}return n}();var r6=function(){function n(t,e,i,r,a,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],R.backend_util.assertAndGetBroadcastShape(t,e),R.backend_util.assertAndGetBroadcastShape(t,i);var o="vec4(0.0)";r!=null&&(R.backend_util.assertAndGetBroadcastShape(t,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var l="vec4(1.0)";a!=null&&(R.backend_util.assertAndGetBroadcastShape(t,a),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=` + `}return n}();var a6=function(){function n(t,e,i,r,a,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],R.backend_util.assertAndGetBroadcastShape(t,e),R.backend_util.assertAndGetBroadcastShape(t,i);var o="vec4(0.0)";r!=null&&(R.backend_util.assertAndGetBroadcastShape(t,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var l="vec4(1.0)";a!=null&&(R.backend_util.assertAndGetBroadcastShape(t,a),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=` void main() { vec4 offset = `+o+`; vec4 scale = `+l+`; @@ -3679,13 +3679,13 @@ return (round(mod(b, 2.0)) != 1) ? setOutput((x - mean) * inv + offset); } - `}return n}();var a6=function(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.x,a=t.mean,s=t.variance,o=t.offset,l=t.scale;R.util.assert(a.shape.length===s.shape.length,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),R.util.assert(o==null||a.shape.length===o.shape.length,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),R.util.assert(l==null||a.shape.length===l.shape.length,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."});var u=i.varianceEpsilon;u==null&&(u=.001);var c=[r,a,s],h=null;o!=null&&(h=o.shape,c.push(o));var d=null;l!=null&&(d=l.shape,c.push(l));var p=R.env().getBool("WEBGL_PACK_NORMALIZATION")?new r6(r.shape,a.shape,s.shape,h,d,u):new i6(r.shape,a.shape,s.shape,h,d,u),f=e.runWebGLProgram(p,c,c[0].dtype);return f},s6={kernelName:R.FusedBatchNorm,backendName:"webgl",kernelFunc:a6};var o6=qS+` + `}return n}();var s6=function(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.x,a=t.mean,s=t.variance,o=t.offset,l=t.scale;R.util.assert(a.shape.length===s.shape.length,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),R.util.assert(o==null||a.shape.length===o.shape.length,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),R.util.assert(l==null||a.shape.length===l.shape.length,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."});var u=i.varianceEpsilon;u==null&&(u=.001);var c=[r,a,s],h=null;o!=null&&(h=o.shape,c.push(o));var d=null;l!=null&&(d=l.shape,c.push(l));var p=R.env().getBool("WEBGL_PACK_NORMALIZATION")?new a6(r.shape,a.shape,s.shape,h,d,u):new r6(r.shape,a.shape,s.shape,h,d,u),f=e.runWebGLProgram(p,c,c[0].dtype);return f},o6={kernelName:R.FusedBatchNorm,backendName:"webgl",kernelFunc:s6};var l6=qS+` return cos(x); -`,l6=_o(o6),u6={kernelName:R.Cos,backendName:"webgl",kernelFunc:l6};var c6=` +`,u6=_o(l6),c6={kernelName:R.Cos,backendName:"webgl",kernelFunc:u6};var h6=` if (a == b) { return 1.0; }; -return a / b;`,h6=` +return a / b;`,d6=` // vec4 one = vec4(equal(a, b)); // return one + (vec4(1.0) - one) * a / b; vec4 result = a / b; @@ -3703,7 +3703,7 @@ return a / b;`,h6=` } return result; -`,d6=Hd(c6,h6,!0),p6={kernelName:R.Div,backendName:"webgl",kernelFunc:d6};var f6=function(){function n(t){this.variableNames=["Image"],this.outputShape=[];var e=t[2];this.outputShape=t,this.userCode=` +`,p6=Hd(h6,d6,!0),f6={kernelName:R.Div,backendName:"webgl",kernelFunc:p6};var m6=function(){function n(t){this.variableNames=["Image"],this.outputShape=[];var e=t[2];this.outputShape=t,this.userCode=` void main() { ivec4 coords = getOutputCoords(); int x = coords[2]; @@ -3717,7 +3717,7 @@ return a / b;`,h6=` } setOutput(outputValue); } - `}return n}();var m6={kernelName:R.FlipLeftRight,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.backend,i=t.image,r=e,a=new f6(i.shape),s=r.runWebGLProgram(a,[i],i.dtype);return s}};var g6=function(){function n(t){this.variableNames=["A"];var e=kt(),i=t[0],r=t[1];this.outputShape=t,this.userCode=` + `}return n}();var g6={kernelName:R.FlipLeftRight,backendName:"webgl",kernelFunc:function(n){var t=n.inputs,e=n.backend,i=t.image,r=e,a=new m6(i.shape),s=r.runWebGLProgram(a,[i],i.dtype);return s}};var v6=function(){function n(t){this.variableNames=["A"];var e=kt(),i=t[0],r=t[1];this.outputShape=t,this.userCode=` void main() { ivec3 coords = getOutputCoords(); int texR = coords[0]; @@ -3739,7 +3739,7 @@ return a / b;`,h6=` setOutput(floor(value * 255.0 + 0.5)); } - `}return n}();var v6=function(){function n(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var e=kt(),i=t[0],r=t[1];this.outputShape=t,this.userCode=` + `}return n}();var y6=function(){function n(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var e=kt(),i=t[0],r=t[1];this.outputShape=t,this.userCode=` void main() { ivec3 coords = getOutputCoords(); int texR = coords[0]; @@ -3773,12 +3773,12 @@ return a / b;`,h6=` `+e.output+` = result; } - `}return n}();var b6={kernelName:R.FromPixels,backendName:"webgl",kernelFunc:y6},na;function y6(n){var t=n.inputs,e=n.backend,i=n.attrs,r=t.pixels,a=i.numChannels,s=typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement,o=typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement,l=s?[r.videoWidth,r.videoHeight]:[r.width,r.height],u=l[0],c=l[1],h=[c,u],d=[c,u,a];(o||s)&&(na==null&&(na=document.createElement("canvas").getContext("2d")),na.canvas.width=u,na.canvas.height=c,na.drawImage(r,0,0,u,c),r=na.canvas);var p=e.makeTensorInfo(h,"int32");e.texData.get(p.dataId).usage=tn.PIXELS,e.gpgpu.uploadPixelDataToTexture(e.getTexture(p.dataId),r);var f=R.env().getBool("WEBGL_PACK")?new v6(d):new g6(d),m=e.runWebGLProgram(f,[p],"int32");return e.disposeData(p.dataId),m}function w6(n){for(var t=[];t.length===0||t[t.length-1].outSize!==1;){var e=t.length?t[t.length-1].outSize:n[1],i=R.backend_util.computeOptimalWindowSize(e);t.push({inSize:e,windowSize:i,outSize:Math.ceil(e/i)})}return t}function S6(n,t,e,i){for(var r=w6(n.shape),a=n,s=0;s6)throw Error("Transpose for rank "+t+" is not yet supported");for(var e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],i=new Array(t),r=0;r6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");for(var a=Je(this.rank),s=_0("rc",this.rank),o=new Array(this.rank),r=0;r6)throw Error("Transpose for rank "+t+" is not yet supported");for(var e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],i=new Array(t),r=0;r6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");for(var a=Je(this.rank),s=_0("rc",this.rank),o=new Array(this.rank),r=0;r{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});var Yd=Ki(),Kd=Vb(),jd=rw(),$S=Tw(),r8=d0(),a8=jS();var s8="2.6.0";var o8={"tfjs-core":Yd.version_core,"tfjs-backend-cpu":r8.version_cpu,"tfjs-backend-webgl":a8.version_webgl,"tfjs-data":$S.version_data,"tfjs-layers":Kd.version_layers,"tfjs-converter":jd.version_converter,tfjs:s8};Object.keys(Yd).forEach(function(n){n!=="default"&&Object.defineProperty(hr,n,{enumerable:!0,get:function(){return Yd[n]}})});Object.keys(Kd).forEach(function(n){n!=="default"&&Object.defineProperty(hr,n,{enumerable:!0,get:function(){return Kd[n]}})});Object.keys(jd).forEach(function(n){n!=="default"&&Object.defineProperty(hr,n,{enumerable:!0,get:function(){return jd[n]}})});hr.data=$S;hr.version=o8});var eL=be(Po=>{const ze=Ht(),XS=6;function l8(n){const t={strides:[n/16,n/8],anchors:[2,6]},e=[];for(let i=0;i{n.startEndTensor.dispose(),n.startPoint.dispose(),n.endPoint.dispose()},ZS=n=>({startEndTensor:n,startPoint:ze.slice(n,[0,0],[-1,2]),endPoint:ze.slice(n,[0,2],[-1,2])}),u8=(n,t)=>{const e=ze.mul(n.startPoint,t),i=ze.mul(n.endPoint,t),r=ze.concat2d([e,i],1);return ZS(r)};function c8(n,t,e){const i=ze.slice(n,[0,1],[-1,2]),r=ze.add(i,t),a=ze.slice(n,[0,3],[-1,2]),s=ze.div(a,e),o=ze.div(r,e),l=ze.div(s,2),u=ze.sub(o,l),c=ze.add(o,l),h=ze.mul(u,e),d=ze.mul(c,e),p=1;return ze.concat2d([h,d],p)}function h8(n,t){return ze.tidy(()=>{const e=n.box?n.box:n;return u8(e,t).startEndTensor.squeeze()})}class QS{constructor(n,t){this.blazeFaceModel=n,this.width=t.detector.inputSize,this.height=t.detector.inputSize,this.maxFaces=t.detector.maxFaces,this.anchorsData=l8(t.detector.inputSize),this.anchors=ze.tensor2d(this.anchorsData),this.inputSize=ze.tensor1d([this.width,this.height]),this.iouThreshold=t.detector.iouThreshold,this.scaleFaces=.8,this.scoreThreshold=t.detector.scoreThreshold}async getBoundingBoxes(n){if(!n||n.isDisposedInternal||n.shape.length!==4||n.shape[1]<1||n.shape[2]<1)return null;const[t,e,i]=ze.tidy(()=>{const u=n.resizeBilinear([this.width,this.height]),c=ze.mul(ze.sub(u.div(255),.5),2),h=this.blazeFaceModel.predict(c);let d;if(Array.isArray(h)){const g=h.sort((L,w)=>L.size-w.size),v=ze.concat([g[0],g[2]],2),b=ze.concat([g[1],g[3]],2),S=ze.concat([b,v],1);d=S.squeeze(0)}else d=h.squeeze();const p=c8(d,this.anchors,this.inputSize),f=ze.slice(d,[0,0],[-1,1]),m=ze.sigmoid(f).squeeze();return[d,p,m]}),r=await ze.image.nonMaxSuppressionAsync(e,i,this.maxFaces,this.iouThreshold,this.scoreThreshold),a=await r.array();r.dispose();const s=a.map(u=>ze.slice(e,[u,0],[1,-1])),o=await Promise.all(s.map(async u=>{const c=await u.array();return u.dispose(),c})),l=[];for(let u=0;u{const r=h8(i,e),[a,s,o]=await Promise.all([i.landmarks,r,i.probability].map(async p=>p.array())),l=i.anchor,[u,c]=e,h=a.map(p=>[(p[0]+l[0])*u,(p[1]+l[1])*c]),d={topLeft:s.slice(0,2),bottomRight:s.slice(2),landmarks:h,probability:o};return JS(i.box),i.landmarks.dispose(),i.probability.dispose(),r.dispose(),d}))}}async function d8(n){const t=await ze.loadGraphModel(n.detector.modelPath,{fromTFHub:n.detector.modelPath.includes("tfhub.dev")}),e=new QS(t,n);return e}Po.load=d8;Po.BlazeFaceModel=QS;Po.disposeBox=JS});var Xd=be($d=>{$d.MESH_ANNOTATIONS={silhouette:[10,338,297,332,284,251,389,356,454,323,361,288,397,365,379,378,400,377,152,148,176,149,150,136,172,58,132,93,234,127,162,21,54,103,67,109],lipsUpperOuter:[61,185,40,39,37,0,267,269,270,409,291],lipsLowerOuter:[146,91,181,84,17,314,405,321,375,291],lipsUpperInner:[78,191,80,81,82,13,312,311,310,415,308],lipsLowerInner:[78,95,88,178,87,14,317,402,318,324,308],rightEyeUpper0:[246,161,160,159,158,157,173],rightEyeLower0:[33,7,163,144,145,153,154,155,133],rightEyeUpper1:[247,30,29,27,28,56,190],rightEyeLower1:[130,25,110,24,23,22,26,112,243],rightEyeUpper2:[113,225,224,223,222,221,189],rightEyeLower2:[226,31,228,229,230,231,232,233,244],rightEyeLower3:[143,111,117,118,119,120,121,128,245],rightEyebrowUpper:[156,70,63,105,66,107,55,193],rightEyebrowLower:[35,124,46,53,52,65],rightEyeIris:[473,474,475,476,477],leftEyeUpper0:[466,388,387,386,385,384,398],leftEyeLower0:[263,249,390,373,374,380,381,382,362],leftEyeUpper1:[467,260,259,257,258,286,414],leftEyeLower1:[359,255,339,254,253,252,256,341,463],leftEyeUpper2:[342,445,444,443,442,441,413],leftEyeLower2:[446,261,448,449,450,451,452,453,464],leftEyeLower3:[372,340,346,347,348,349,350,357,465],leftEyebrowUpper:[383,300,293,334,296,336,285,417],leftEyebrowLower:[265,353,276,283,282,295],leftEyeIris:[468,469,470,471,472],midwayBetweenEyes:[168],noseTip:[1],noseBottom:[2],noseRightCorner:[98],noseLeftCorner:[327],rightCheek:[205],leftCheek:[425]};$d.MESH_TO_IRIS_INDICES_MAP=[{key:"EyeUpper0",indices:[9,10,11,12,13,14,15]},{key:"EyeUpper1",indices:[25,26,27,28,29,30,31]},{key:"EyeUpper2",indices:[41,42,43,44,45,46,47]},{key:"EyeLower0",indices:[0,1,2,3,4,5,6,7,8]},{key:"EyeLower1",indices:[16,17,18,19,20,21,22,23,24]},{key:"EyeLower2",indices:[32,33,34,35,36,37,38,39,40]},{key:"EyeLower3",indices:[54,55,56,57,58,59,60,61,62]},{key:"EyebrowUpper",indices:[63,64,65,66,67,68,69,70]},{key:"EyebrowLower",indices:[48,49,50,51,52,53]}]});var tL=be(dr=>{const p8=Ht();function f8(n,t){const e=[n.startPoint[0]*t[0],n.startPoint[1]*t[1]],i=[n.endPoint[0]*t[0],n.endPoint[1]*t[1]];return{startPoint:e,endPoint:i}}dr.scaleBoxCoordinates=f8;function Jd(n){return[Math.abs(n.endPoint[0]-n.startPoint[0]),Math.abs(n.endPoint[1]-n.startPoint[1])]}dr.getBoxSize=Jd;function Zd(n){return[n.startPoint[0]+(n.endPoint[0]-n.startPoint[0])/2,n.startPoint[1]+(n.endPoint[1]-n.startPoint[1])/2]}dr.getBoxCenter=Zd;function m8(n,t,e){const i=t.shape[1],r=t.shape[2],a=[[n.startPoint[1]/i,n.startPoint[0]/r,n.endPoint[1]/i,n.endPoint[0]/r]];return p8.image.cropAndResize(t,a,[0],e)}dr.cutBoxFromImageAndResize=m8;function g8(n,t=1.5){const e=Zd(n),i=Jd(n),r=[t*i[0]/2,t*i[1]/2],a=[e[0]-r[0],e[1]-r[1]],s=[e[0]+r[0],e[1]+r[1]];return{startPoint:a,endPoint:s,landmarks:n.landmarks}}dr.enlargeBox=g8;function v8(n){const t=Zd(n),e=Jd(n),i=Math.max(...e),r=i/2,a=[t[0]-r,t[1]-r],s=[t[0]+r,t[1]+r];return{startPoint:a,endPoint:s,landmarks:n.landmarks}}dr.squarifyBox=v8});var sL=be(wn=>{wn.IDENTITY_MATRIX=[[1,0,0],[0,1,0],[0,0,1]];function nL(n){return n-2*Math.PI*Math.floor((n+Math.PI)/(2*Math.PI))}wn.normalizeRadians=nL;function y8(n,t){const e=Math.PI/2-Math.atan2(-(t[1]-n[1]),t[0]-n[0]);return nL(e)}wn.computeRotation=y8;function b8(n){return n*180/Math.PI}wn.radToDegrees=b8;function iL(n,t){return[[1,0,n],[0,1,t],[0,0,1]]}function ia(n,t){let e=0;for(let i=0;i{const Xn=Ht(),Un=tL(),Li=Xd(),Ii=sL(),A8=468,T8=.25,N8=13,x8=[N8,Li.MESH_ANNOTATIONS.midwayBetweenEyes[0]],C8=3,R8=2,O8=[C8,R8],Qd=Li.MESH_ANNOTATIONS.leftEyeLower0,ep=[Qd[0],Qd[Qd.length-1]],tp=Li.MESH_ANNOTATIONS.rightEyeLower0,np=[tp[0],tp[tp.length-1]],E8=3,D8=4,k8=71,ip=76;function Mo(n,t,e,i){for(let r=0;r[a[0]*(d[0]-this.meshWidth/2),a[1]*(d[1]-this.meshHeight/2),d[2]]),o=Ii.buildRotationMatrix(e,[0,0]),l=s.map(d=>[...Ii.rotatePoint(d,o),d[2]]),u=Ii.invertTransformMatrix(i),c=[...Un.getBoxCenter({startPoint:t.startPoint,endPoint:t.endPoint}),1],h=[Ii.dot(c,u[0]),Ii.dot(c,u[1])];return l.map(d=>[d[0]+h[0],d[1]+h[1],d[2]])}getLeftToRightEyeDepthDifference(n){const t=n[ep[0]][2],e=n[np[0]][2];return t-e}getEyeBox(n,t,e,i,r=!1){const a=Un.squarifyBox(Un.enlargeBox(this.calculateLandmarksBoundingBox([n[e],n[i]]),this.irisEnlarge)),s=Un.getBoxSize(a);let o=Xn.image.cropAndResize(t,[[a.startPoint[1]/this.meshHeight,a.startPoint[0]/this.meshWidth,a.endPoint[1]/this.meshHeight,a.endPoint[0]/this.meshWidth]],[0],[this.irisSize,this.irisSize]);return r&&(o=Xn.image.flipLeftRight(o)),{box:a,boxSize:s,crop:o}}getEyeCoords(n,t,e,i=!1){const r=[];for(let a=0;a{let l=a;return o===2?l=i:o===4&&(l=r),[s[0],s[1],l]})}async predict(n,t){if(this.skipFrames=t.detector.skipFrames,this.maxFaces=t.detector.maxFaces,this.runsWithoutFaceDetector++,this.shouldUpdateRegionsOfInterest()){const i=await this.boundingBoxDetector.getBoundingBoxes(n);if(i.boxes.length===0)return this.regionsOfInterest=[],null;const r=i.boxes.map(a=>{const s=a.box.startPoint.squeeze(),o=a.box.endPoint.squeeze(),l={startPoint:s.arraySync(),endPoint:o.arraySync()};s.dispose(),o.dispose();const u=Un.scaleBoxCoordinates(l,i.scaleFactor),c=Un.enlargeBox(u),h=a.landmarks.arraySync();return a.box.startPoint.dispose(),a.box.endPoint.dispose(),a.landmarks.dispose(),a.probability.dispose(),{...c,landmarks:h}});this.updateRegionsOfInterest(r),this.runsWithoutFaceDetector=0}const e=Xn.tidy(()=>this.regionsOfInterest.map((i,r)=>{let a=0;const s=i.landmarks.length>=A8;let[o,l]=x8;s===!1&&([o,l]=O8),a=Ii.computeRotation(i.landmarks[o],i.landmarks[l]);const u=Un.getBoxCenter({startPoint:i.startPoint,endPoint:i.endPoint}),c=[u[0]/n.shape[2],u[1]/n.shape[1]];let h=n,d=Ii.IDENTITY_MATRIX;a!==0&&(h=Xn.image.rotateWithOffset(n,a,0,c),d=Ii.buildRotationMatrix(-a,u));const p={startPoint:i.startPoint,endPoint:i.endPoint},f=Un.cutBoxFromImageAndResize(p,h,[this.meshHeight,this.meshWidth]).div(255),[,m,g]=this.meshDetector.predict(f),v=Xn.reshape(g,[-1,3]);let b=v.arraySync();if(t.iris.enabled){const{box:I,boxSize:C,crop:E}=this.getEyeBox(b,f,ep[0],ep[1],!0),{box:k,boxSize:W,crop:F}=this.getEyeBox(b,f,np[0],np[1]),_=this.irisModel.predict(Xn.concat([E,F])),H=_.dataSync();_.dispose();const P=H.slice(0,ip*3),{rawCoords:K,iris:j}=this.getEyeCoords(P,I,C,!0),q=H.slice(ip*3),{rawCoords:G,iris:Z}=this.getEyeCoords(q,k,W),X=this.getLeftToRightEyeDepthDifference(b);Math.abs(X)<30?(Mo(b,K,"left"),Mo(b,G,"right")):X<1?Mo(b,K,"left",["EyeUpper0","EyeLower0"]):Mo(b,G,"right",["EyeUpper0","EyeLower0"]);const ee=this.getAdjustedIrisCoords(b,j,"left"),ne=this.getAdjustedIrisCoords(b,Z,"right");b=b.concat(ee).concat(ne)}const S=this.transformRawCoords(b,i,a,d);Xn.dispose(b);const L=Un.enlargeBox(this.calculateLandmarksBoundingBox(S)),w=m.squeeze();if(Xn.dispose(m),t.mesh.enabled){const I=Xn.tensor2d(S);this.regionsOfInterest[r]={...L,landmarks:I.arraySync()};const C={coords:I,box:L,confidence:w,image:f};return C}const N={coords:null,box:L,confidence:w,image:f};return N}));return e}updateRegionsOfInterest(n){for(let t=0;t=this.skipFrames}calculateLandmarksBoundingBox(n){const t=n.map(a=>a[0]),e=n.map(a=>a[1]),i=[Math.min(...t),Math.min(...e)],r=[Math.max(...t),Math.max(...e)];return{startPoint:i,endPoint:r,landmarks:n}}}oL.Pipeline=F8});var cL=be(uL=>{uL.UV_COORDS=[[.499976992607117,.652534008026123],[.500025987625122,.547487020492554],[.499974012374878,.602371990680695],[.482113003730774,.471979022026062],[.500150978565216,.527155995368958],[.499909996986389,.498252987861633],[.499523013830185,.40106201171875],[.289712011814117,.380764007568359],[.499954998493195,.312398016452789],[.499987006187439,.269918978214264],[.500023007392883,.107050001621246],[.500023007392883,.666234016418457],[.5000159740448,.679224014282227],[.500023007392883,.692348003387451],[.499976992607117,.695277988910675],[.499976992607117,.70593398809433],[.499976992607117,.719385027885437],[.499976992607117,.737019002437592],[.499967992305756,.781370997428894],[.499816000461578,.562981009483337],[.473773002624512,.573909997940063],[.104906998574734,.254140973091125],[.365929991006851,.409575998783112],[.338757991790771,.41302502155304],[.311120003461838,.409460008144379],[.274657994508743,.389131009578705],[.393361985683441,.403706014156342],[.345234006643295,.344011008739471],[.370094001293182,.346076011657715],[.319321990013123,.347265005111694],[.297903001308441,.353591024875641],[.24779200553894,.410809993743896],[.396889001131058,.842755019664764],[.280097991228104,.375599980354309],[.106310002505779,.399955987930298],[.2099249958992,.391353011131287],[.355807989835739,.534406006336212],[.471751004457474,.65040397644043],[.474155008792877,.680191993713379],[.439785003662109,.657229006290436],[.414617002010345,.66654098033905],[.450374007225037,.680860996246338],[.428770989179611,.682690978050232],[.374971002340317,.727805018424988],[.486716985702515,.547628998756409],[.485300987958908,.527395009994507],[.257764995098114,.314490020275116],[.401223003864288,.455172002315521],[.429818987846375,.548614978790283],[.421351999044418,.533740997314453],[.276895999908447,.532056987285614],[.483370006084442,.499586999416351],[.33721199631691,.282882988452911],[.296391993761063,.293242990970612],[.169294998049736,.193813979625702],[.447580009698868,.302609980106354],[.392390012741089,.353887975215912],[.354490011930466,.696784019470215],[.067304998636246,.730105042457581],[.442739009857178,.572826027870178],[.457098007202148,.584792017936707],[.381974011659622,.694710969924927],[.392388999462128,.694203019142151],[.277076005935669,.271932005882263],[.422551989555359,.563233017921448],[.385919004678726,.281364023685455],[.383103013038635,.255840003490448],[.331431001424789,.119714021682739],[.229923993349075,.232002973556519],[.364500999450684,.189113974571228],[.229622006416321,.299540996551514],[.173287004232407,.278747975826263],[.472878992557526,.666198015213013],[.446828007698059,.668527007102966],[.422762006521225,.673889994621277],[.445307999849319,.580065965652466],[.388103008270264,.693961024284363],[.403039008378983,.706539988517761],[.403629004955292,.693953037261963],[.460041999816895,.557139039039612],[.431158006191254,.692366003990173],[.452181994915009,.692366003990173],[.475387006998062,.692366003990173],[.465828001499176,.779190003871918],[.472328990697861,.736225962638855],[.473087012767792,.717857003211975],[.473122000694275,.704625964164734],[.473033010959625,.695277988910675],[.427942007780075,.695277988910675],[.426479011774063,.703539967536926],[.423162013292313,.711845993995667],[.4183090031147,.720062971115112],[.390094995498657,.639572978019714],[.013953999616206,.560034036636353],[.499913990497589,.58014702796936],[.413199990987778,.69539999961853],[.409626007080078,.701822996139526],[.468080013990402,.601534962654114],[.422728985548019,.585985004901886],[.463079988956451,.593783974647522],[.37211999297142,.47341400384903],[.334562003612518,.496073007583618],[.411671012639999,.546965003013611],[.242175996303558,.14767599105835],[.290776997804642,.201445996761322],[.327338010072708,.256527006626129],[.399509996175766,.748921036720276],[.441727995872498,.261676013469696],[.429764986038208,.187834024429321],[.412198007106781,.108901023864746],[.288955003023148,.398952007293701],[.218936994671822,.435410976409912],[.41278201341629,.398970007896423],[.257135003805161,.355440020561218],[.427684992551804,.437960982322693],[.448339998722076,.536936044692993],[.178560003638268,.45755398273468],[.247308000922203,.457193970680237],[.286267012357712,.467674970626831],[.332827985286713,.460712015628815],[.368755996227264,.447206974029541],[.398963987827301,.432654976844788],[.476410001516342,.405806005001068],[.189241006970406,.523923993110657],[.228962004184723,.348950982093811],[.490725994110107,.562400996685028],[.404670000076294,.485132992267609],[.019469000399113,.401564002037048],[.426243007183075,.420431017875671],[.396993011236191,.548797011375427],[.266469985246658,.376977026462555],[.439121007919312,.51895797252655],[.032313998788595,.644356966018677],[.419054001569748,.387154996395111],[.462783008813858,.505746960639954],[.238978996872902,.779744982719421],[.198220998048782,.831938028335571],[.107550002634525,.540755033493042],[.183610007166862,.740257024765015],[.134409993886948,.333683013916016],[.385764002799988,.883153975009918],[.490967005491257,.579378008842468],[.382384985685349,.508572995662689],[.174399003386497,.397670984268188],[.318785011768341,.39623498916626],[.343364000320435,.400596976280212],[.396100014448166,.710216999053955],[.187885001301765,.588537991046906],[.430987000465393,.944064974784851],[.318993002176285,.898285031318665],[.266247987747192,.869701027870178],[.500023007392883,.190576016902924],[.499976992607117,.954452991485596],[.366169989109039,.398822009563446],[.393207013607025,.39553701877594],[.410373002290726,.391080021858215],[.194993004202843,.342101991176605],[.388664990663528,.362284004688263],[.365961998701096,.355970978736877],[.343364000320435,.355356991291046],[.318785011768341,.35834002494812],[.301414996385574,.363156020641327],[.058132998645306,.319076001644135],[.301414996385574,.387449026107788],[.499987989664078,.618434011936188],[.415838003158569,.624195992946625],[.445681989192963,.566076993942261],[.465844005346298,.620640993118286],[.49992299079895,.351523995399475],[.288718998432159,.819945991039276],[.335278987884521,.852819979190826],[.440512001514435,.902418971061707],[.128294005990028,.791940987110138],[.408771991729736,.373893976211548],[.455606997013092,.451801002025604],[.499877005815506,.908990025520325],[.375436991453171,.924192011356354],[.11421000212431,.615022003650665],[.448662012815475,.695277988910675],[.4480200111866,.704632043838501],[.447111994028091,.715808033943176],[.444831997156143,.730794012546539],[.430011987686157,.766808986663818],[.406787008047104,.685672998428345],[.400738000869751,.681069016456604],[.392399996519089,.677703022956848],[.367855995893478,.663918972015381],[.247923001646996,.601333022117615],[.452769994735718,.420849978923798],[.43639200925827,.359887003898621],[.416164010763168,.368713974952698],[.413385987281799,.692366003990173],[.228018000721931,.683571994304657],[.468268007040024,.352671027183533],[.411361992359161,.804327011108398],[.499989002943039,.469825029373169],[.479153990745544,.442654013633728],[.499974012374878,.439637005329132],[.432112008333206,.493588984012604],[.499886006116867,.866917014122009],[.49991300702095,.821729004383087],[.456548988819122,.819200992584229],[.344549000263214,.745438992977142],[.37890899181366,.574010014533997],[.374292999505997,.780184984207153],[.319687992334366,.570737957954407],[.357154995203018,.604269981384277],[.295284003019333,.621580958366394],[.447750002145767,.862477004528046],[.410986006259918,.508723020553589],[.31395098567009,.775308012962341],[.354128003120422,.812552988529205],[.324548006057739,.703992962837219],[.189096003770828,.646299958229065],[.279776990413666,.71465802192688],[.1338230073452,.682700991630554],[.336768001317978,.644733011722565],[.429883986711502,.466521978378296],[.455527991056442,.548622965812683],[.437114000320435,.558896005153656],[.467287987470627,.529924988746643],[.414712011814117,.335219979286194],[.37704598903656,.322777986526489],[.344107985496521,.320150971412659],[.312875986099243,.32233202457428],[.283526003360748,.333190023899078],[.241245999932289,.382785975933075],[.102986000478268,.468762993812561],[.267612010240555,.424560010433197],[.297879010438919,.433175981044769],[.333433985710144,.433878004550934],[.366427004337311,.426115989685059],[.396012008190155,.416696012020111],[.420121014118195,.41022801399231],[.007561000064015,.480777025222778],[.432949006557465,.569517970085144],[.458638995885849,.479089021682739],[.473466008901596,.545744001865387],[.476087987422943,.563830018043518],[.468472003936768,.555056989192963],[.433990985155106,.582361996173859],[.483518004417419,.562983989715576],[.482482999563217,.57784903049469],[.42645001411438,.389798998832703],[.438998997211456,.39649498462677],[.450067013502121,.400434017181396],[.289712011814117,.368252992630005],[.276670008897781,.363372981548309],[.517862021923065,.471948027610779],[.710287988185883,.380764007568359],[.526226997375488,.573909997940063],[.895093023777008,.254140973091125],[.634069979190826,.409575998783112],[.661242008209229,.41302502155304],[.688880026340485,.409460008144379],[.725341975688934,.389131009578705],[.606630027294159,.40370500087738],[.654766023159027,.344011008739471],[.629905998706818,.346076011657715],[.680678009986877,.347265005111694],[.702096998691559,.353591024875641],[.75221198797226,.410804986953735],[.602918028831482,.842862963676453],[.719901978969574,.375599980354309],[.893692970275879,.399959981441498],[.790081977844238,.391354024410248],[.643998026847839,.534487962722778],[.528249025344849,.65040397644043],[.525849997997284,.680191040039062],[.560214996337891,.657229006290436],[.585384011268616,.66654098033905],[.549625992774963,.680860996246338],[.57122802734375,.682691991329193],[.624852001667023,.72809898853302],[.513050019741058,.547281980514526],[.51509702205658,.527251958847046],[.742246985435486,.314507007598877],[.598631024360657,.454979002475739],[.570338010787964,.548575043678284],[.578631997108459,.533622980117798],[.723087012767792,.532054007053375],[.516445994377136,.499638974666595],[.662801027297974,.282917976379395],[.70362401008606,.293271005153656],[.830704987049103,.193813979625702],[.552385985851288,.302568018436432],[.607609987258911,.353887975215912],[.645429015159607,.696707010269165],[.932694971561432,.730105042457581],[.557260990142822,.572826027870178],[.542901992797852,.584792017936707],[.6180260181427,.694710969924927],[.607590973377228,.694203019142151],[.722943007946014,.271963000297546],[.577413976192474,.563166975975037],[.614082992076874,.281386971473694],[.616907000541687,.255886018276215],[.668509006500244,.119913995265961],[.770092010498047,.232020974159241],[.635536015033722,.189248979091644],[.77039098739624,.299556016921997],[.826722025871277,.278755009174347],[.527121007442474,.666198015213013],[.553171992301941,.668527007102966],[.577238023281097,.673889994621277],[.554691970348358,.580065965652466],[.611896991729736,.693961024284363],[.59696102142334,.706539988517761],[.596370995044708,.693953037261963],[.539958000183105,.557139039039612],[.568841993808746,.692366003990173],[.547818005084991,.692366003990173],[.52461302280426,.692366003990173],[.534089982509613,.779141008853912],[.527670979499817,.736225962638855],[.526912987232208,.717857003211975],[.526877999305725,.704625964164734],[.526966989040375,.695277988910675],[.572058022022247,.695277988910675],[.573521018028259,.703539967536926],[.57683801651001,.711845993995667],[.581691026687622,.720062971115112],[.609944999217987,.639909982681274],[.986046016216278,.560034036636353],[.5867999792099,.69539999961853],[.590372025966644,.701822996139526],[.531915009021759,.601536989212036],[.577268004417419,.585934996604919],[.536915004253387,.593786001205444],[.627542972564697,.473352015018463],[.665585994720459,.495950996875763],[.588353991508484,.546862006187439],[.757824003696442,.14767599105835],[.709249973297119,.201507985591888],[.672684013843536,.256581008434296],[.600408971309662,.74900496006012],[.55826598405838,.261672019958496],[.570303976535797,.187870979309082],[.588165998458862,.109044015407562],[.711045026779175,.398952007293701],[.781069993972778,.435405015945435],[.587247014045715,.398931980133057],[.742869973182678,.355445981025696],[.572156012058258,.437651991844177],[.55186802148819,.536570012569427],[.821442008018494,.457556009292603],[.752701997756958,.457181990146637],[.71375697851181,.467626988887787],[.66711300611496,.460672974586487],[.631101012229919,.447153985500336],[.6008620262146,.432473003864288],[.523481011390686,.405627012252808],[.810747981071472,.523926019668579],[.771045982837677,.348959028720856],[.509127020835876,.562718033790588],[.595292985439301,.485023975372314],[.980530977249146,.401564002037048],[.573499977588654,.420000016689301],[.602994978427887,.548687994480133],[.733529984951019,.376977026462555],[.560611009597778,.519016981124878],[.967685997486115,.644356966018677],[.580985009670258,.387160003185272],[.537728011608124,.505385041236877],[.760966002941132,.779752969741821],[.801778972148895,.831938028335571],[.892440974712372,.54076099395752],[.816350996494293,.740260004997253],[.865594983100891,.333687007427216],[.614073991775513,.883246004581451],[.508952975273132,.579437971115112],[.617941975593567,.508316040039062],[.825608015060425,.397674977779388],[.681214988231659,.39623498916626],[.656635999679565,.400596976280212],[.603900015354156,.710216999053955],[.81208598613739,.588539004325867],[.56801301240921,.944564998149872],[.681007981300354,.898285031318665],[.733752012252808,.869701027870178],[.633830010890961,.398822009563446],[.606792986392975,.39553701877594],[.589659988880157,.391062021255493],[.805015981197357,.342108011245728],[.611334979534149,.362284004688263],[.634037971496582,.355970978736877],[.656635999679565,.355356991291046],[.681214988231659,.35834002494812],[.698584973812103,.363156020641327],[.941866993904114,.319076001644135],[.698584973812103,.387449026107788],[.584177017211914,.624107003211975],[.554318010807037,.566076993942261],[.534153997898102,.62064003944397],[.711217999458313,.819975018501282],[.664629995822906,.852871000766754],[.559099972248077,.902631998062134],[.871706008911133,.791940987110138],[.591234028339386,.373893976211548],[.544341027736664,.451583981513977],[.624562978744507,.924192011356354],[.88577002286911,.615028977394104],[.551338016986847,.695277988910675],[.551980018615723,.704632043838501],[.552887976169586,.715808033943176],[.555167973041534,.730794012546539],[.569944024085999,.767035007476807],[.593203008174896,.685675978660583],[.599261999130249,.681069016456604],[.607599973678589,.677703022956848],[.631937980651855,.663500010967255],[.752032995223999,.601315021514893],[.547226011753082,.420395016670227],[.563543975353241,.359827995300293],[.583841025829315,.368713974952698],[.586614012718201,.692366003990173],[.771915018558502,.683578014373779],[.531597018241882,.352482974529266],[.588370978832245,.804440975189209],[.52079701423645,.442565023899078],[.567984998226166,.493479013442993],[.543282985687256,.819254994392395],[.655317008495331,.745514988899231],[.621008992195129,.574018001556396],[.625559985637665,.78031200170517],[.680198013782501,.570719003677368],[.64276397228241,.604337990283966],[.704662978649139,.621529996395111],[.552012026309967,.862591981887817],[.589071989059448,.508637011051178],[.685944974422455,.775357007980347],[.645735025405884,.812640011310577],[.675342977046967,.703978002071381],[.810858011245728,.646304965019226],[.72012197971344,.714666962623596],[.866151988506317,.682704985141754],[.663187026977539,.644596993923187],[.570082008838654,.466325998306274],[.544561982154846,.548375964164734],[.562758982181549,.558784961700439],[.531987011432648,.530140042304993],[.585271000862122,.335177004337311],[.622952997684479,.32277899980545],[.655896008014679,.320163011550903],[.687132000923157,.322345972061157],[.716481983661652,.333200991153717],[.758756995201111,.382786989212036],[.897013008594513,.468769013881683],[.732392013072968,.424547016620636],[.70211398601532,.433162987232208],[.66652500629425,.433866024017334],[.633504986763,.426087975502014],[.603875994682312,.416586995124817],[.579657971858978,.409945011138916],[.992439985275269,.480777025222778],[.567192018032074,.569419980049133],[.54136598110199,.478899002075195],[.526564002037048,.546118021011353],[.523913025856018,.563830018043518],[.531529009342194,.555056989192963],[.566035985946655,.582329034805298],[.51631098985672,.563053965568542],[.5174720287323,.577877044677734],[.573594987392426,.389806985855103],[.560697972774506,.395331978797913],[.549755990505219,.399751007556915],[.710287988185883,.368252992630005],[.723330020904541,.363372981548309]]});var hL=be(W8=>{Ap(W8,{default:()=>U8});var U8=[127,34,139,11,0,37,232,231,120,72,37,39,128,121,47,232,121,128,104,69,67,175,171,148,157,154,155,118,50,101,73,39,40,9,151,108,48,115,131,194,204,211,74,40,185,80,42,183,40,92,186,230,229,118,202,212,214,83,18,17,76,61,146,160,29,30,56,157,173,106,204,194,135,214,192,203,165,98,21,71,68,51,45,4,144,24,23,77,146,91,205,50,187,201,200,18,91,106,182,90,91,181,85,84,17,206,203,36,148,171,140,92,40,39,193,189,244,159,158,28,247,246,161,236,3,196,54,68,104,193,168,8,117,228,31,189,193,55,98,97,99,126,47,100,166,79,218,155,154,26,209,49,131,135,136,150,47,126,217,223,52,53,45,51,134,211,170,140,67,69,108,43,106,91,230,119,120,226,130,247,63,53,52,238,20,242,46,70,156,78,62,96,46,53,63,143,34,227,173,155,133,123,117,111,44,125,19,236,134,51,216,206,205,154,153,22,39,37,167,200,201,208,36,142,100,57,212,202,20,60,99,28,158,157,35,226,113,160,159,27,204,202,210,113,225,46,43,202,204,62,76,77,137,123,116,41,38,72,203,129,142,64,98,240,49,102,64,41,73,74,212,216,207,42,74,184,169,170,211,170,149,176,105,66,69,122,6,168,123,147,187,96,77,90,65,55,107,89,90,180,101,100,120,63,105,104,93,137,227,15,86,85,129,102,49,14,87,86,55,8,9,100,47,121,145,23,22,88,89,179,6,122,196,88,95,96,138,172,136,215,58,172,115,48,219,42,80,81,195,3,51,43,146,61,171,175,199,81,82,38,53,46,225,144,163,110,246,33,7,52,65,66,229,228,117,34,127,234,107,108,69,109,108,151,48,64,235,62,78,191,129,209,126,111,35,143,163,161,246,117,123,50,222,65,52,19,125,141,221,55,65,3,195,197,25,7,33,220,237,44,70,71,139,122,193,245,247,130,33,71,21,162,153,158,159,170,169,150,188,174,196,216,186,92,144,160,161,2,97,167,141,125,241,164,167,37,72,38,12,145,159,160,38,82,13,63,68,71,226,35,111,158,153,154,101,50,205,206,92,165,209,198,217,165,167,97,220,115,218,133,112,243,239,238,241,214,135,169,190,173,133,171,208,32,125,44,237,86,87,178,85,86,179,84,85,180,83,84,181,201,83,182,137,93,132,76,62,183,61,76,184,57,61,185,212,57,186,214,207,187,34,143,156,79,239,237,123,137,177,44,1,4,201,194,32,64,102,129,213,215,138,59,166,219,242,99,97,2,94,141,75,59,235,24,110,228,25,130,226,23,24,229,22,23,230,26,22,231,112,26,232,189,190,243,221,56,190,28,56,221,27,28,222,29,27,223,30,29,224,247,30,225,238,79,20,166,59,75,60,75,240,147,177,215,20,79,166,187,147,213,112,233,244,233,128,245,128,114,188,114,217,174,131,115,220,217,198,236,198,131,134,177,132,58,143,35,124,110,163,7,228,110,25,356,389,368,11,302,267,452,350,349,302,303,269,357,343,277,452,453,357,333,332,297,175,152,377,384,398,382,347,348,330,303,304,270,9,336,337,278,279,360,418,262,431,304,408,409,310,415,407,270,409,410,450,348,347,422,430,434,313,314,17,306,307,375,387,388,260,286,414,398,335,406,418,364,367,416,423,358,327,251,284,298,281,5,4,373,374,253,307,320,321,425,427,411,421,313,18,321,405,406,320,404,405,315,16,17,426,425,266,377,400,369,322,391,269,417,465,464,386,257,258,466,260,388,456,399,419,284,332,333,417,285,8,346,340,261,413,441,285,327,460,328,355,371,329,392,439,438,382,341,256,429,420,360,364,394,379,277,343,437,443,444,283,275,440,363,431,262,369,297,338,337,273,375,321,450,451,349,446,342,467,293,334,282,458,461,462,276,353,383,308,324,325,276,300,293,372,345,447,382,398,362,352,345,340,274,1,19,456,248,281,436,427,425,381,256,252,269,391,393,200,199,428,266,330,329,287,273,422,250,462,328,258,286,384,265,353,342,387,259,257,424,431,430,342,353,276,273,335,424,292,325,307,366,447,345,271,303,302,423,266,371,294,455,460,279,278,294,271,272,304,432,434,427,272,407,408,394,430,431,395,369,400,334,333,299,351,417,168,352,280,411,325,319,320,295,296,336,319,403,404,330,348,349,293,298,333,323,454,447,15,16,315,358,429,279,14,15,316,285,336,9,329,349,350,374,380,252,318,402,403,6,197,419,318,319,325,367,364,365,435,367,397,344,438,439,272,271,311,195,5,281,273,287,291,396,428,199,311,271,268,283,444,445,373,254,339,263,466,249,282,334,296,449,347,346,264,447,454,336,296,299,338,10,151,278,439,455,292,407,415,358,371,355,340,345,372,390,249,466,346,347,280,442,443,282,19,94,370,441,442,295,248,419,197,263,255,359,440,275,274,300,383,368,351,412,465,263,467,466,301,368,389,380,374,386,395,378,379,412,351,419,436,426,322,373,390,388,2,164,393,370,462,461,164,0,267,302,11,12,374,373,387,268,12,13,293,300,301,446,261,340,385,384,381,330,266,425,426,423,391,429,355,437,391,327,326,440,457,438,341,382,362,459,457,461,434,430,394,414,463,362,396,369,262,354,461,457,316,403,402,315,404,403,314,405,404,313,406,405,421,418,406,366,401,361,306,408,407,291,409,408,287,410,409,432,436,410,434,416,411,264,368,383,309,438,457,352,376,401,274,275,4,421,428,262,294,327,358,433,416,367,289,455,439,462,370,326,2,326,370,305,460,455,254,449,448,255,261,446,253,450,449,252,451,450,256,452,451,341,453,452,413,464,463,441,413,414,258,442,441,257,443,442,259,444,443,260,445,444,467,342,445,459,458,250,289,392,290,290,328,460,376,433,435,250,290,392,411,416,433,341,463,464,453,464,465,357,465,412,343,412,399,360,363,440,437,399,456,420,456,363,401,435,288,372,383,353,339,255,249,448,261,255,133,243,190,133,155,112,33,246,247,33,130,25,398,384,286,362,398,414,362,463,341,263,359,467,263,249,255,466,467,260,75,60,166,238,239,79,162,127,139,72,11,37,121,232,120,73,72,39,114,128,47,233,232,128,103,104,67,152,175,148,173,157,155,119,118,101,74,73,40,107,9,108,49,48,131,32,194,211,184,74,185,191,80,183,185,40,186,119,230,118,210,202,214,84,83,17,77,76,146,161,160,30,190,56,173,182,106,194,138,135,192,129,203,98,54,21,68,5,51,4,145,144,23,90,77,91,207,205,187,83,201,18,181,91,182,180,90,181,16,85,17,205,206,36,176,148,140,165,92,39,245,193,244,27,159,28,30,247,161,174,236,196,103,54,104,55,193,8,111,117,31,221,189,55,240,98,99,142,126,100,219,166,218,112,155,26,198,209,131,169,135,150,114,47,217,224,223,53,220,45,134,32,211,140,109,67,108,146,43,91,231,230,120,113,226,247,105,63,52,241,238,242,124,46,156,95,78,96,70,46,63,116,143,227,116,123,111,1,44,19,3,236,51,207,216,205,26,154,22,165,39,167,199,200,208,101,36,100,43,57,202,242,20,99,56,28,157,124,35,113,29,160,27,211,204,210,124,113,46,106,43,204,96,62,77,227,137,116,73,41,72,36,203,142,235,64,240,48,49,64,42,41,74,214,212,207,183,42,184,210,169,211,140,170,176,104,105,69,193,122,168,50,123,187,89,96,90,66,65,107,179,89,180,119,101,120,68,63,104,234,93,227,16,15,85,209,129,49,15,14,86,107,55,9,120,100,121,153,145,22,178,88,179,197,6,196,89,88,96,135,138,136,138,215,172,218,115,219,41,42,81,5,195,51,57,43,61,208,171,199,41,81,38,224,53,225,24,144,110,105,52,66,118,229,117,227,34,234,66,107,69,10,109,151,219,48,235,183,62,191,142,129,126,116,111,143,7,163,246,118,117,50,223,222,52,94,19,141,222,221,65,196,3,197,45,220,44,156,70,139,188,122,245,139,71,162,145,153,159,149,170,150,122,188,196,206,216,92,163,144,161,164,2,167,242,141,241,0,164,37,11,72,12,144,145,160,12,38,13,70,63,71,31,226,111,157,158,154,36,101,205,203,206,165,126,209,217,98,165,97,237,220,218,237,239,241,210,214,169,140,171,32,241,125,237,179,86,178,180,85,179,181,84,180,182,83,181,194,201,182,177,137,132,184,76,183,185,61,184,186,57,185,216,212,186,192,214,187,139,34,156,218,79,237,147,123,177,45,44,4,208,201,32,98,64,129,192,213,138,235,59,219,141,242,97,97,2,141,240,75,235,229,24,228,31,25,226,230,23,229,231,22,230,232,26,231,233,112,232,244,189,243,189,221,190,222,28,221,223,27,222,224,29,223,225,30,224,113,247,225,99,60,240,213,147,215,60,20,166,192,187,213,243,112,244,244,233,245,245,128,188,188,114,174,134,131,220,174,217,236,236,198,134,215,177,58,156,143,124,25,110,7,31,228,25,264,356,368,0,11,267,451,452,349,267,302,269,350,357,277,350,452,357,299,333,297,396,175,377,381,384,382,280,347,330,269,303,270,151,9,337,344,278,360,424,418,431,270,304,409,272,310,407,322,270,410,449,450,347,432,422,434,18,313,17,291,306,375,259,387,260,424,335,418,434,364,416,391,423,327,301,251,298,275,281,4,254,373,253,375,307,321,280,425,411,200,421,18,335,321,406,321,320,405,314,315,17,423,426,266,396,377,369,270,322,269,413,417,464,385,386,258,248,456,419,298,284,333,168,417,8,448,346,261,417,413,285,326,327,328,277,355,329,309,392,438,381,382,256,279,429,360,365,364,379,355,277,437,282,443,283,281,275,363,395,431,369,299,297,337,335,273,321,348,450,349,359,446,467,283,293,282,250,458,462,300,276,383,292,308,325,283,276,293,264,372,447,346,352,340,354,274,19,363,456,281,426,436,425,380,381,252,267,269,393,421,200,428,371,266,329,432,287,422,290,250,328,385,258,384,446,265,342,386,387,257,422,424,430,445,342,276,422,273,424,306,292,307,352,366,345,268,271,302,358,423,371,327,294,460,331,279,294,303,271,304,436,432,427,304,272,408,395,394,431,378,395,400,296,334,299,6,351,168,376,352,411,307,325,320,285,295,336,320,319,404,329,330,349,334,293,333,366,323,447,316,15,315,331,358,279,317,14,316,8,285,9,277,329,350,253,374,252,319,318,403,351,6,419,324,318,325,397,367,365,288,435,397,278,344,439,310,272,311,248,195,281,375,273,291,175,396,199,312,311,268,276,283,445,390,373,339,295,282,296,448,449,346,356,264,454,337,336,299,337,338,151,294,278,455,308,292,415,429,358,355,265,340,372,388,390,466,352,346,280,295,442,282,354,19,370,285,441,295,195,248,197,457,440,274,301,300,368,417,351,465,251,301,389,385,380,386,394,395,379,399,412,419,410,436,322,387,373,388,326,2,393,354,370,461,393,164,267,268,302,12,386,374,387,312,268,13,298,293,301,265,446,340,380,385,381,280,330,425,322,426,391,420,429,437,393,391,326,344,440,438,458,459,461,364,434,394,428,396,262,274,354,457,317,316,402,316,315,403,315,314,404,314,313,405,313,421,406,323,366,361,292,306,407,306,291,408,291,287,409,287,432,410,427,434,411,372,264,383,459,309,457,366,352,401,1,274,4,418,421,262,331,294,358,435,433,367,392,289,439,328,462,326,94,2,370,289,305,455,339,254,448,359,255,446,254,253,449,253,252,450,252,256,451,256,341,452,414,413,463,286,441,414,286,258,441,258,257,442,257,259,443,259,260,444,260,467,445,309,459,250,305,289,290,305,290,460,401,376,435,309,250,392,376,411,433,453,341,464,357,453,465,343,357,412,437,343,399,344,360,440,420,437,456,360,420,363,361,401,288,265,372,353,390,339,249,339,448,255]});var fL=be(ts=>{const rp=Ht(),B8=eL(),dL=Xd(),z8=lL(),_8=cL(),P8=hL().default;class pL{constructor(n,t,e,i){this.pipeline=new z8.Pipeline(n,t,e,i),i&&(this.config=i)}async estimateFaces(n,t){t&&(this.config=t);const e=await this.pipeline.predict(n,t),i=[];for(const r of e||[]){if(r.isDisposedInternal)continue;const a=r.confidence.arraySync();if(a>=this.config.detector.minConfidence){const s=r.coords?r.coords.arraySync():null,o={};if(s&&s.length>0)for(const l in dL.MESH_ANNOTATIONS)(this.config.iris.enabled||l.includes("Iris")===!1)&&(o[l]=dL.MESH_ANNOTATIONS[l].map(u=>s[u]));i.push({confidence:a||0,box:r.box?[r.box.startPoint[0],r.box.startPoint[1],r.box.endPoint[0]-r.box.startPoint[0],r.box.endPoint[1]-r.box.startPoint[1]]:0,mesh:s,annotations:o,image:r.image?rp.clone(r.image):null})}r.confidence&&r.confidence.dispose(),r.coords&&r.coords.dispose(),r.image&&r.image.dispose()}return i}}async function M8(n){const t=await Promise.all([B8.load(n),rp.loadGraphModel(n.mesh.modelPath,{fromTFHub:n.mesh.modelPath.includes("tfhub.dev")}),rp.loadGraphModel(n.iris.modelPath,{fromTFHub:n.iris.modelPath.includes("tfhub.dev")})]),e=new pL(t[0],t[1],t[2],n);return e}ts.load=M8;ts.MediaPipeFaceMesh=pL;ts.uv_coords=_8;ts.triangulation=P8});var gL=be(Ho=>{const Ai=Ht(),Ti={};let mL={age:0,gender:""},ap=0;async function H8(n){return Ti.age||(Ti.age=await Ai.loadGraphModel(n.face.age.modelPath)),Ti.age}async function V8(n){return Ti.gender||(Ti.gender=await Ai.loadGraphModel(n.face.gender.modelPath)),Ti.gender}async function q8(n,t){if(apt.face.gender.minConfidence&&(o.gender=l[0]<=.5?"female":"male",o.confidence=u),Ai.dispose(s)}return Ai.dispose(i),mL=o,o}Ho.predict=q8;Ho.loadAge=H8;Ho.loadGender=V8});var bL=be(sp=>{const Jn=Ht(),G8=["angry","discust","fear","happy","sad","surpise","neutral"],Vo={};let vL=[],op=0;const yL=1.5;async function Y8(n){return Vo.emotion||(Vo.emotion=await Jn.loadGraphModel(n.face.emotion.modelPath)),Vo.emotion}async function K8(n,t){if(opt.face.emotion.minConfidence&&c.push({score:Math.min(.99,Math.trunc(100*yL*d[p])/100),emotion:G8[p]});c.sort((p,f)=>f.score-p.score),Jn.dispose(h)}return Jn.dispose(u),vL=c,c}sp.predict=K8;sp.load=Y8});var LL=be(wL=>{const SL=Ht();class j8{constructor(n,t){this.model=n,this.outputStride=t;const e=this.model.inputs[0].shape;SL.util.assert(e[1]===-1&&e[2]===-1,()=>`Input shape [${e[1]}, ${e[2]}] must both be equal to or -1`)}predict(n){return SL.tidy(()=>{const t=this.preprocessInput(n.toFloat()),e=t.expandDims(0),i=this.model.predict(e),r=i.map(s=>s.squeeze([0])),a=this.nameOutputResults(r);return{heatmapScores:a.heatmap.sigmoid(),offsets:a.offsets,displacementFwd:a.displacementFwd,displacementBwd:a.displacementBwd}})}dispose(){this.model.dispose()}}wL.BaseModel=j8});var lp=be(IL=>{const AL=Ht(),$8=LL();class X8 extends $8.BaseModel{preprocessInput(n){return AL.tidy(()=>AL.div(n,127.5).sub(1))}nameOutputResults(n){const[t,e,i,r]=n;return{offsets:t,heatmap:e,displacementFwd:i,displacementBwd:r}}}IL.MobileNet=X8});var NL=be(TL=>{function up(n){return Math.floor(n/2)}class J8{constructor(n,t){this.priorityQueue=new Array(n),this.numberOfElements=-1,this.getElementValue=t}enqueue(n){this.priorityQueue[++this.numberOfElements]=n,this.swim(this.numberOfElements)}dequeue(){const n=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,n}empty(){return this.numberOfElements===-1}size(){return this.numberOfElements+1}all(){return this.priorityQueue.slice(0,this.numberOfElements+1)}max(){return this.priorityQueue[0]}swim(n){for(;n>0&&this.less(up(n),n);)this.exchange(n,up(n)),n=up(n)}sink(n){for(;2*n<=this.numberOfElements;){let t=2*n;if(t{const Z8=NL();function Q8(n,t,e,i,r,a){const[s,o]=a.shape;let l=!0;const u=Math.max(e-r,0),c=Math.min(e+r+1,s);for(let h=u;ht){l=!1;break}if(!l)break}return l}function e7(n,t,e){const[i,r,a]=e.shape,s=new Z8.MaxHeap(i*r*a,({score:o})=>o);for(let o=0;o{Sn.partNames=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"];Sn.NUM_KEYPOINTS=Sn.partNames.length;Sn.partIds=Sn.partNames.reduce((n,t,e)=>(n[t]=e,n),{});const t7=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]];Sn.poseChain=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]];Sn.connectedPartIndices=t7.map(([n,t])=>[Sn.partIds[n],Sn.partIds[t]]);Sn.partChannels=["left_face","right_face","right_upper_leg_front","right_lower_leg_back","right_upper_leg_back","left_lower_leg_front","left_upper_leg_front","left_upper_leg_back","left_lower_leg_back","right_feet","right_lower_leg_front","left_feet","torso_front","torso_back","right_upper_arm_front","right_upper_arm_back","right_lower_arm_back","left_lower_arm_front","left_upper_arm_front","left_upper_arm_back","left_lower_arm_back","right_hand","right_lower_arm_front","left_hand"]});var hp=be(Ni=>{const n7=ns();function RL(n,t,e,i){return{y:i.get(n,t,e),x:i.get(n,t,e+n7.NUM_KEYPOINTS)}}Ni.getOffsetPoint=RL;function i7(n,t,e){const{heatmapY:i,heatmapX:r,id:a}=n,{y:s,x:o}=RL(i,r,a,e);return{x:n.heatmapX*t+o,y:n.heatmapY*t+s}}Ni.getImageCoords=i7;function r7(n,t){const e=new Array(t);for(let i=0;ie?e:n}Ni.clamp=cp;function a7(n,t,e,i){const r=e-n,a=i-t;return r*r+a*a}Ni.squaredDistance=a7;function s7(n,t){return{x:n.x+t.x,y:n.y+t.y}}Ni.addVectors=s7;function o7(n,t,e){return{y:cp(n.y,t,e),x:cp(n.x,t,e)}}Ni.clampVector=o7});var FL=be(OL=>{const is=ns(),ra=hp(),EL=is.poseChain.map(([n,t])=>[is.partIds[n],is.partIds[t]]),dp=EL.map(([,n])=>n),DL=EL.map(([n])=>n);function l7(n,t,e){const i=e.shape[2]/2;return{y:e.get(t.y,t.x,n),x:e.get(t.y,t.x,i+n)}}function pp(n,t,e,i){return{y:ra.clamp(Math.round(n.y/t),0,e-1),x:ra.clamp(Math.round(n.x/t),0,i-1)}}function kL(n,t,e,i,r,a,s,o=2){const[l,u]=i.shape,c=pp(t.position,a,l,u),h=l7(n,c,s),d=ra.addVectors(t.position,h);let p=d;for(let g=0;g=0;--d){const p=dp[d],f=DL[d];l[p]&&!l[f]&&(l[f]=kL(d,l[p],f,t,e,i,a))}for(let d=0;d{const c7=CL(),h7=FL(),UL=hp();function BL(n,t,{x:e,y:i},r){return n.some(({keypoints:a})=>{const s=a[r].position;return UL.squaredDistance(i,e,s.y,s.x)<=t})}function d7(n,t,e){const i=e.reduce((r,{position:a,score:s},o)=>(BL(n,t,a,o)||(r+=s),r),0);return i/e.length}const p7=1;function f7(n,t,e,i,r,a,s=.5,o=20){const l=[],u=c7.buildPartWithScoreQueue(s,p7,n),c=o*o;for(;l.length{const m7=ns();function g7(n,t,e){return n(g7(n[i].score,n[r].score,t)||e.push([n[i],n[r]]),e),[])}xi.getAdjacentKeyPoints=v7;const{NEGATIVE_INFINITY:zL,POSITIVE_INFINITY:_L}=Number;function PL(n){return n.reduce(({maxX:t,maxY:e,minX:i,minY:r},{position:{x:a,y:s}})=>({maxX:Math.max(t,a),maxY:Math.max(e,s),minX:Math.min(i,a),minY:Math.min(r,s)}),{maxX:zL,maxY:zL,minX:_L,minY:_L})}xi.getBoundingBox=PL;function y7(n){const{minX:t,minY:e,maxX:i,maxY:r}=PL(n);return[{x:t,y:e},{x:i,y:e},{x:i,y:r},{x:t,y:r}]}xi.getBoundingBoxPoints=y7;async function b7(n){return Promise.all(n.map(t=>t.buffer()))}xi.toTensorBuffers3D=b7;function ML(n,t,e){return{score:n.score,keypoints:n.keypoints.map(({score:i,part:r,position:a})=>({score:i,part:r,position:{x:a.x*e,y:a.y*t}}))}}xi.scalePose=ML;function w7(n,[t,e]){const i=n.squeeze(0),r=i.resizeBilinear([t,e]);return i.dispose(),r}xi.resizeTo=w7;function S7(n,[t,e],[i,r]){const a=n.map(s=>ML(s,t/i,e/r));return a}xi.scaleAndFlipPoses=S7});var VL=be(gp=>{const L7=Ht(),I7=lp(),A7=fp(),vp=mp();class HL{constructor(n){this.baseModel=n}async estimatePoses(n,t){const e=t.outputStride,i=n.shape[1],r=n.shape[2],a=vp.resizeTo(n,[t.inputResolution,t.inputResolution]),{heatmapScores:s,offsets:o,displacementFwd:l,displacementBwd:u}=this.baseModel.predict(a),c=await vp.toTensorBuffers3D([s,o,l,u]),h=c[0],d=c[1],p=c[2],f=c[3],m=await A7.decodeMultiplePoses(h,d,p,f,e,t.maxDetections,t.scoreThreshold,t.nmsRadius),g=vp.scaleAndFlipPoses(m,[i,r],[t.inputResolution,t.inputResolution]);return s.dispose(),o.dispose(),l.dispose(),u.dispose(),a.dispose(),g}dispose(){this.baseModel.dispose()}}gp.PoseNet=HL;async function T7(n){const t=await L7.loadGraphModel(n.modelPath),e=new I7.MobileNet(t,n.outputStride);return new HL(e)}async function N7(n){return T7(n)}gp.load=N7});var GL=be(Xt=>{const x7=lp(),qL=VL(),C7=fp(),qo=ns(),rs=mp();Xt.load=qL.load;Xt.PoseNet=qL.PoseNet;Xt.MobileNet=x7.MobileNet;Xt.decodeMultiplePoses=C7.decodeMultiplePoses;Xt.partChannels=qo.partChannels;Xt.partIds=qo.partIds;Xt.partNames=qo.partNames;Xt.poseChain=qo.poseChain;Xt.getAdjacentKeyPoints=rs.getAdjacentKeyPoints;Xt.getBoundingBox=rs.getBoundingBox;Xt.getBoundingBoxPoints=rs.getBoundingBoxPoints;Xt.scaleAndFlipPoses=rs.scaleAndFlipPoses;Xt.scalePose=rs.scalePose});var wp=be(Ci=>{const R7=Ht();function yp(n){return[Math.abs(n.endPoint[0]-n.startPoint[0]),Math.abs(n.endPoint[1]-n.startPoint[1])]}Ci.getBoxSize=yp;function bp(n){return[n.startPoint[0]+(n.endPoint[0]-n.startPoint[0])/2,n.startPoint[1]+(n.endPoint[1]-n.startPoint[1])/2]}Ci.getBoxCenter=bp;function O7(n,t,e){const i=t.shape[1],r=t.shape[2],a=[[n.startPoint[1]/i,n.startPoint[0]/r,n.endPoint[1]/i,n.endPoint[0]/r]];return R7.image.cropAndResize(t,a,[0],e)}Ci.cutBoxFromImageAndResize=O7;function E7(n,t){const e=[n.startPoint[0]*t[0],n.startPoint[1]*t[1]],i=[n.endPoint[0]*t[0],n.endPoint[1]*t[1]],r=n.palmLandmarks.map(a=>{const s=[a[0]*t[0],a[1]*t[1]];return s});return{startPoint:e,endPoint:i,palmLandmarks:r}}Ci.scaleBoxCoordinates=E7;function D7(n,t=1.5){const e=bp(n),i=yp(n),r=[t*i[0]/2,t*i[1]/2],a=[e[0]-r[0],e[1]-r[1]],s=[e[0]+r[0],e[1]+r[1]];return{startPoint:a,endPoint:s,palmLandmarks:n.palmLandmarks}}Ci.enlargeBox=D7;function k7(n){const t=bp(n),e=yp(n),i=Math.max(...e),r=i/2,a=[t[0]-r,t[1]-r],s=[t[0]+r,t[1]+r];return{startPoint:a,endPoint:s,palmLandmarks:n.palmLandmarks}}Ci.squarifyBox=k7;function F7(n,t){const e=[n.endPoint[0]-n.startPoint[0],n.endPoint[1]-n.startPoint[1]],i=[e[0]*t[0],e[1]*t[1]],r=[n.startPoint[0]+i[0],n.startPoint[1]+i[1]],a=[n.endPoint[0]+i[0],n.endPoint[1]+i[1]];return{startPoint:r,endPoint:a,palmLandmarks:n.palmLandmarks}}Ci.shiftBox=F7});var KL=be(YL=>{const je=Ht(),W7=wp();class U7{constructor(n,t,e){this.model=n,this.width=e.inputSize,this.height=e.inputSize,this.anchors=t.map(i=>[i.x_center,i.y_center]),this.anchorsTensor=je.tensor2d(this.anchors),this.inputSizeTensor=je.tensor1d([e.inputSize,e.inputSize]),this.doubleInputSizeTensor=je.tensor1d([e.inputSize*2,e.inputSize*2])}normalizeBoxes(n){return je.tidy(()=>{const t=je.slice(n,[0,0],[-1,2]),e=je.slice(n,[0,2],[-1,2]),i=je.add(je.div(t,this.inputSizeTensor),this.anchorsTensor),r=je.div(e,this.doubleInputSizeTensor),a=je.mul(je.sub(i,r),this.inputSizeTensor),s=je.mul(je.add(i,r),this.inputSizeTensor);return je.concat2d([a,s],1)})}normalizeLandmarks(n,t){return je.tidy(()=>{const e=je.add(je.div(n.reshape([-1,7,2]),this.inputSizeTensor),this.anchors[t]);return je.mul(e,this.inputSizeTensor)})}async getBoundingBoxes(n){const t=this.model.predict(n),e=t.squeeze(),i=je.tidy(()=>je.sigmoid(je.slice(e,[0,0],[-1,1])).squeeze()),r=je.slice(e,[0,1],[-1,4]),a=this.normalizeBoxes(r),s=await je.image.nonMaxSuppressionAsync(a,i,this.maxHands,this.iouThreshold,this.scoreThreshold),o=await s.array(),l=[t,s,e,a,r,i],u=je.tidy(()=>{const c=[];for(const h in o){const d=o[h],p=je.slice(a,[d,0],[1,-1]),f=je.slice(e,[d,5],[1,14]),m=je.tidy(()=>this.normalizeLandmarks(f,d).reshape([-1,2]));c.push({boxes:p,palmLandmarks:m})}return c});return l.forEach(c=>c.dispose()),u}async estimateHandBounds(n,t){this.iouThreshold=t.iouThreshold,this.scoreThreshold=t.scoreThreshold,this.maxHands=t.maxHands;const e=n.resizeBilinear([this.width,this.height]),i=e.div(255),r=i.sub(.5),a=r.mul(2);e.dispose(),i.dispose(),r.dispose();const s=await this.getBoundingBoxes(a);if(a.dispose(),!s||s.length===0)return null;const o=[];for(const l in s){const u=s[l],c=await u.boxes.array(),h=c[0].slice(0,2),d=c[0].slice(2,4),p=await u.palmLandmarks.array();u.boxes.dispose(),u.palmLandmarks.dispose(),o.push(W7.scaleBoxCoordinates({startPoint:h,endPoint:d,palmLandmarks:p},[n.shape[2]/this.width,n.shape[1]/this.height]))}return o}}YL.HandDetector=U7});var $L=be(jL=>{jL.MESH_ANNOTATIONS={thumb:[1,2,3,4],indexFinger:[5,6,7,8],middleFinger:[9,10,11,12],ringFinger:[13,14,15,16],pinky:[17,18,19,20],palmBase:[0]}});var eI=be(Ri=>{function XL(n){return n-2*Math.PI*Math.floor((n+Math.PI)/(2*Math.PI))}Ri.normalizeRadians=XL;function B7(n,t){const e=Math.PI/2-Math.atan2(-(t[1]-n[1]),t[0]-n[0]);return XL(e)}Ri.computeRotation=B7;const JL=(n,t)=>[[1,0,n],[0,1,t],[0,0,1]];function aa(n,t){let e=0;for(let i=0;i{const nI=Ht(),Bn=wp(),Oi=eI(),M7=.8,H7=[0,-.4],V7=[0,-.1],q7=1.65,iI=[0,5,9,13,17,1,2],G7=0,Y7=2;class K7{constructor(n,t,e){this.regionsOfInterest=[],this.runsWithoutHandDetector=0,this.boundingBoxDetector=n,this.meshDetector=t,this.meshWidth=e.inputSize,this.meshHeight=e.inputSize,this.enlargeFactor=e.enlargeFactor}getBoxForPalmLandmarks(n,t){const e=n.map(r=>{const a=[...r,1];return Oi.rotatePoint(a,t)}),i=this.calculateLandmarksBoundingBox(e);return Bn.enlargeBox(Bn.squarifyBox(Bn.shiftBox(i,H7)),this.enlargeFactor)}getBoxForHandLandmarks(n){const t=this.calculateLandmarksBoundingBox(n),e=Bn.enlargeBox(Bn.squarifyBox(Bn.shiftBox(t,V7)),q7),i=[];for(let r=0;r[a[0]*(d[0]-this.meshWidth/2),a[1]*(d[1]-this.meshHeight/2),d[2]]),o=Oi.buildRotationMatrix(e,[0,0]),l=s.map(d=>{const p=Oi.rotatePoint(d,o);return[...p,d[2]]}),u=Oi.invertTransformMatrix(i),c=[...Bn.getBoxCenter(t),1],h=[Oi.dot(c,u[0]),Oi.dot(c,u[1])];return l.map(d=>[d[0]+h[0],d[1]+h[1],d[2]])}async estimateHands(n,t){this.skipFrames=t.skipFrames,this.detectionConfidence=t.minConfidence,this.maxHands=t.maxHands,this.runsWithoutHandDetector++;const e=this.shouldUpdateRegionsOfInterest();if(e===!0){const r=await this.boundingBoxDetector.estimateHandBounds(n,t);this.regionsOfInterest=[];for(const a in r)this.updateRegionsOfInterest(r[a],!0,a);this.runsWithoutHandDetector=0}const i=[];if(!this.regionsOfInterest)return i;for(const r in this.regionsOfInterest){const a=this.regionsOfInterest[r][0];if(!a)return i;const s=Oi.computeRotation(a.palmLandmarks[G7],a.palmLandmarks[Y7]),o=Bn.getBoxCenter(a),l=[o[0]/n.shape[2],o[1]/n.shape[1]],u=nI.image.rotateWithOffset(n,s,0,l),c=Oi.buildRotationMatrix(-s,o),h=e?this.getBoxForPalmLandmarks(a.palmLandmarks,c):a,d=Bn.cutBoxFromImageAndResize(h,u,[this.meshWidth,this.meshHeight]),p=d.div(255);d.dispose(),u.dispose();const f=this.meshDetector.predict(p),[m,g]=f;p.dispose();const v=m.dataSync()[0];if(m.dispose(),va[0]),e=n.map(a=>a[1]),i=[Math.min(...t),Math.min(...e)],r=[Math.max(...t),Math.max(...e)];return{startPoint:i,endPoint:r}}updateRegionsOfInterest(n,t,e){if(t)this.regionsOfInterest[e]=[n];else{const i=this.regionsOfInterest[e][0];let r=0;if(i!=null&&i.startPoint!=null){const[a,s]=n.startPoint,[o,l]=n.endPoint,[u,c]=i.startPoint,[h,d]=i.endPoint,p=Math.max(a,u),f=Math.max(s,c),m=Math.min(o,h),g=Math.min(l,d),v=(m-p)*(g-f),b=(o-a)*(l-s),S=(h-u)*(d-s);r=v/(b+S-v)}this.regionsOfInterest[e][0]=r>M7?i:n}}shouldUpdateRegionsOfInterest(){return!this.regionsOfInterest||this.regionsOfInterest.length===0||this.runsWithoutHandDetector>=this.skipFrames}}tI.HandPipeline=K7});var oI=be(Sp=>{const Go=Ht(),j7=KL(),aI=$L(),$7=rI();class sI{constructor(n){this.pipeline=n}async estimateHands(n,t){this.skipFrames=t.skipFrames,this.detectionConfidence=t.minConfidence,this.maxHands=t.maxHands;const e=await this.pipeline.estimateHands(n,t),i=[];if(!e)return i;for(const r of e){if(!r)return[];const a={};for(const s of Object.keys(aI.MESH_ANNOTATIONS))a[s]=aI.MESH_ANNOTATIONS[s].map(o=>r.landmarks[o]);i.push({confidence:r.confidence||0,box:r.box?[r.box.topLeft[0],r.box.topLeft[1],r.box.bottomRight[0]-r.box.topLeft[0],r.box.bottomRight[1]-r.box.topLeft[1]]:0,landmarks:r.landmarks,annotations:a})}return i}}Sp.HandPose=sI;async function X7(n){if(Go.env().features.IS_NODE){const t=require("fs"),e=await t.readFileSync(n.replace("file://",""));return JSON.parse(e)}return Go.util.fetch(n).then(t=>t.json())}async function J7(n){const[t,e,i]=await Promise.all([X7(n.detector.anchors),Go.loadGraphModel(n.detector.modelPath,{fromTFHub:n.detector.modelPath.includes("tfhub.dev")}),Go.loadGraphModel(n.skeleton.modelPath,{fromTFHub:n.skeleton.modelPath.includes("tfhub.dev")})]),r=new j7.HandDetector(e,t,n),a=new $7.HandPipeline(r,i,n),s=new sI(a);return s}Sp.load=J7});var uI=be(lI=>{const Z7=function(n,t,e){const i=function(o,l,u){const c=new RegExp("\\b"+l+" \\w+ (\\w+)","ig");o.replace(c,(h,d)=>(u[d]=0,h))},r=function(o,l,u){const c=o.createShader(u);if(o.shaderSource(c,l),o.compileShader(c),!o.getShaderParameter(c,o.COMPILE_STATUS))throw new Error("Filter: GL compile failed",o.getShaderInfoLog(c));return c};this.uniform={},this.attribute={};const a=r(n,t,n.VERTEX_SHADER),s=r(n,e,n.FRAGMENT_SHADER);if(this.id=n.createProgram(),n.attachShader(this.id,a),n.attachShader(this.id,s),n.linkProgram(this.id),!n.getProgramParameter(this.id,n.LINK_STATUS))throw new Error("Filter: GL link failed",n.getProgramInfoLog(this.id));n.useProgram(this.id),i(t,"attribute",this.attribute);for(const o in this.attribute)this.attribute[o]=n.getAttribLocation(this.id,o);i(t,"uniform",this.uniform),i(e,"uniform",this.uniform);for(const o in this.uniform)this.uniform[o]=n.getUniformLocation(this.id,o)},Q7=function(n){n||(n={});let t=0,e=null,i=!1,r=-1,a=[null,null],s=[],o=-1,l=-1,u=null,c=null;const h=n.canvas||document.createElement("canvas"),d={},p=h.getContext("webgl")||h.getContext("experimental-webgl");if(!p)throw new Error("Filter: getContext() failed");this.addFilter=function(N){const I=Array.prototype.slice.call(arguments,1),C=w[N];s.push({func:C,args:I})},this.reset=function(){s=[]},this.apply=function(N){if(f(N.width,N.height),t=0,e||(e=p.createTexture()),p.bindTexture(p.TEXTURE_2D,e),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.NEAREST),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.NEAREST),p.texImage2D(p.TEXTURE_2D,0,p.RGBA,p.RGBA,p.UNSIGNED_BYTE,N),s.length===0){const I=b(L.FRAGMENT_IDENTITY);return v(),h}for(let I=0;I{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});var Yd=Ki(),Kd=Vb(),jd=rw(),$S=Tw(),a8=d0(),s8=jS();var o8="2.6.0";var l8={"tfjs-core":Yd.version_core,"tfjs-backend-cpu":a8.version_cpu,"tfjs-backend-webgl":s8.version_webgl,"tfjs-data":$S.version_data,"tfjs-layers":Kd.version_layers,"tfjs-converter":jd.version_converter,tfjs:o8};Object.keys(Yd).forEach(function(n){n!=="default"&&Object.defineProperty(hr,n,{enumerable:!0,get:function(){return Yd[n]}})});Object.keys(Kd).forEach(function(n){n!=="default"&&Object.defineProperty(hr,n,{enumerable:!0,get:function(){return Kd[n]}})});Object.keys(jd).forEach(function(n){n!=="default"&&Object.defineProperty(hr,n,{enumerable:!0,get:function(){return jd[n]}})});hr.data=$S;hr.version=l8});var eL=be(Po=>{const ze=Ht(),XS=6;function u8(n){const t={strides:[n/16,n/8],anchors:[2,6]},e=[];for(let i=0;i{n.startEndTensor.dispose(),n.startPoint.dispose(),n.endPoint.dispose()},ZS=n=>({startEndTensor:n,startPoint:ze.slice(n,[0,0],[-1,2]),endPoint:ze.slice(n,[0,2],[-1,2])}),c8=(n,t)=>{const e=ze.mul(n.startPoint,t),i=ze.mul(n.endPoint,t),r=ze.concat2d([e,i],1);return ZS(r)};function h8(n,t,e){const i=ze.slice(n,[0,1],[-1,2]),r=ze.add(i,t),a=ze.slice(n,[0,3],[-1,2]),s=ze.div(a,e),o=ze.div(r,e),l=ze.div(s,2),u=ze.sub(o,l),c=ze.add(o,l),h=ze.mul(u,e),d=ze.mul(c,e),p=1;return ze.concat2d([h,d],p)}function d8(n,t){return ze.tidy(()=>{const e=n.box?n.box:n;return c8(e,t).startEndTensor.squeeze()})}class QS{constructor(n,t){this.blazeFaceModel=n,this.width=t.detector.inputSize,this.height=t.detector.inputSize,this.maxFaces=t.detector.maxFaces,this.anchorsData=u8(t.detector.inputSize),this.anchors=ze.tensor2d(this.anchorsData),this.inputSize=ze.tensor1d([this.width,this.height]),this.iouThreshold=t.detector.iouThreshold,this.scaleFaces=.8,this.scoreThreshold=t.detector.scoreThreshold}async getBoundingBoxes(n){if(!n||n.isDisposedInternal||n.shape.length!==4||n.shape[1]<1||n.shape[2]<1)return null;const[t,e,i]=ze.tidy(()=>{const u=n.resizeBilinear([this.width,this.height]),c=ze.mul(ze.sub(u.div(255),.5),2),h=this.blazeFaceModel.predict(c);let d;if(Array.isArray(h)){const g=h.sort((L,w)=>L.size-w.size),v=ze.concat([g[0],g[2]],2),b=ze.concat([g[1],g[3]],2),S=ze.concat([b,v],1);d=S.squeeze(0)}else d=h.squeeze();const p=h8(d,this.anchors,this.inputSize),f=ze.slice(d,[0,0],[-1,1]),m=ze.sigmoid(f).squeeze();return[d,p,m]}),r=await ze.image.nonMaxSuppressionAsync(e,i,this.maxFaces,this.iouThreshold,this.scoreThreshold),a=await r.array();r.dispose();const s=a.map(u=>ze.slice(e,[u,0],[1,-1])),o=await Promise.all(s.map(async u=>{const c=await u.array();return u.dispose(),c})),l=[];for(let u=0;u{const r=d8(i,e),[a,s,o]=await Promise.all([i.landmarks,r,i.probability].map(async p=>p.array())),l=i.anchor,[u,c]=e,h=a.map(p=>[(p[0]+l[0])*u,(p[1]+l[1])*c]),d={topLeft:s.slice(0,2),bottomRight:s.slice(2),landmarks:h,probability:o};return JS(i.box),i.landmarks.dispose(),i.probability.dispose(),r.dispose(),d}))}}async function p8(n){const t=await ze.loadGraphModel(n.detector.modelPath,{fromTFHub:n.detector.modelPath.includes("tfhub.dev")}),e=new QS(t,n);return e}Po.load=p8;Po.BlazeFaceModel=QS;Po.disposeBox=JS});var Xd=be($d=>{$d.MESH_ANNOTATIONS={silhouette:[10,338,297,332,284,251,389,356,454,323,361,288,397,365,379,378,400,377,152,148,176,149,150,136,172,58,132,93,234,127,162,21,54,103,67,109],lipsUpperOuter:[61,185,40,39,37,0,267,269,270,409,291],lipsLowerOuter:[146,91,181,84,17,314,405,321,375,291],lipsUpperInner:[78,191,80,81,82,13,312,311,310,415,308],lipsLowerInner:[78,95,88,178,87,14,317,402,318,324,308],rightEyeUpper0:[246,161,160,159,158,157,173],rightEyeLower0:[33,7,163,144,145,153,154,155,133],rightEyeUpper1:[247,30,29,27,28,56,190],rightEyeLower1:[130,25,110,24,23,22,26,112,243],rightEyeUpper2:[113,225,224,223,222,221,189],rightEyeLower2:[226,31,228,229,230,231,232,233,244],rightEyeLower3:[143,111,117,118,119,120,121,128,245],rightEyebrowUpper:[156,70,63,105,66,107,55,193],rightEyebrowLower:[35,124,46,53,52,65],rightEyeIris:[473,474,475,476,477],leftEyeUpper0:[466,388,387,386,385,384,398],leftEyeLower0:[263,249,390,373,374,380,381,382,362],leftEyeUpper1:[467,260,259,257,258,286,414],leftEyeLower1:[359,255,339,254,253,252,256,341,463],leftEyeUpper2:[342,445,444,443,442,441,413],leftEyeLower2:[446,261,448,449,450,451,452,453,464],leftEyeLower3:[372,340,346,347,348,349,350,357,465],leftEyebrowUpper:[383,300,293,334,296,336,285,417],leftEyebrowLower:[265,353,276,283,282,295],leftEyeIris:[468,469,470,471,472],midwayBetweenEyes:[168],noseTip:[1],noseBottom:[2],noseRightCorner:[98],noseLeftCorner:[327],rightCheek:[205],leftCheek:[425]};$d.MESH_TO_IRIS_INDICES_MAP=[{key:"EyeUpper0",indices:[9,10,11,12,13,14,15]},{key:"EyeUpper1",indices:[25,26,27,28,29,30,31]},{key:"EyeUpper2",indices:[41,42,43,44,45,46,47]},{key:"EyeLower0",indices:[0,1,2,3,4,5,6,7,8]},{key:"EyeLower1",indices:[16,17,18,19,20,21,22,23,24]},{key:"EyeLower2",indices:[32,33,34,35,36,37,38,39,40]},{key:"EyeLower3",indices:[54,55,56,57,58,59,60,61,62]},{key:"EyebrowUpper",indices:[63,64,65,66,67,68,69,70]},{key:"EyebrowLower",indices:[48,49,50,51,52,53]}]});var tL=be(dr=>{const f8=Ht();function m8(n,t){const e=[n.startPoint[0]*t[0],n.startPoint[1]*t[1]],i=[n.endPoint[0]*t[0],n.endPoint[1]*t[1]];return{startPoint:e,endPoint:i}}dr.scaleBoxCoordinates=m8;function Jd(n){return[Math.abs(n.endPoint[0]-n.startPoint[0]),Math.abs(n.endPoint[1]-n.startPoint[1])]}dr.getBoxSize=Jd;function Zd(n){return[n.startPoint[0]+(n.endPoint[0]-n.startPoint[0])/2,n.startPoint[1]+(n.endPoint[1]-n.startPoint[1])/2]}dr.getBoxCenter=Zd;function g8(n,t,e){const i=t.shape[1],r=t.shape[2],a=[[n.startPoint[1]/i,n.startPoint[0]/r,n.endPoint[1]/i,n.endPoint[0]/r]];return f8.image.cropAndResize(t,a,[0],e)}dr.cutBoxFromImageAndResize=g8;function v8(n,t=1.5){const e=Zd(n),i=Jd(n),r=[t*i[0]/2,t*i[1]/2],a=[e[0]-r[0],e[1]-r[1]],s=[e[0]+r[0],e[1]+r[1]];return{startPoint:a,endPoint:s,landmarks:n.landmarks}}dr.enlargeBox=v8;function y8(n){const t=Zd(n),e=Jd(n),i=Math.max(...e),r=i/2,a=[t[0]-r,t[1]-r],s=[t[0]+r,t[1]+r];return{startPoint:a,endPoint:s,landmarks:n.landmarks}}dr.squarifyBox=y8});var sL=be(wn=>{wn.IDENTITY_MATRIX=[[1,0,0],[0,1,0],[0,0,1]];function nL(n){return n-2*Math.PI*Math.floor((n+Math.PI)/(2*Math.PI))}wn.normalizeRadians=nL;function b8(n,t){const e=Math.PI/2-Math.atan2(-(t[1]-n[1]),t[0]-n[0]);return nL(e)}wn.computeRotation=b8;function w8(n){return n*180/Math.PI}wn.radToDegrees=w8;function iL(n,t){return[[1,0,n],[0,1,t],[0,0,1]]}function ia(n,t){let e=0;for(let i=0;i{const Xn=Ht(),Un=tL(),Li=Xd(),Ii=sL(),T8=468,N8=.25,x8=13,C8=[x8,Li.MESH_ANNOTATIONS.midwayBetweenEyes[0]],R8=3,O8=2,E8=[R8,O8],Qd=Li.MESH_ANNOTATIONS.leftEyeLower0,ep=[Qd[0],Qd[Qd.length-1]],tp=Li.MESH_ANNOTATIONS.rightEyeLower0,np=[tp[0],tp[tp.length-1]],D8=3,k8=4,F8=71,ip=76;function Mo(n,t,e,i){for(let r=0;r[a[0]*(d[0]-this.meshWidth/2),a[1]*(d[1]-this.meshHeight/2),d[2]]),o=Ii.buildRotationMatrix(e,[0,0]),l=s.map(d=>[...Ii.rotatePoint(d,o),d[2]]),u=Ii.invertTransformMatrix(i),c=[...Un.getBoxCenter({startPoint:t.startPoint,endPoint:t.endPoint}),1],h=[Ii.dot(c,u[0]),Ii.dot(c,u[1])];return l.map(d=>[d[0]+h[0],d[1]+h[1],d[2]])}getLeftToRightEyeDepthDifference(n){const t=n[ep[0]][2],e=n[np[0]][2];return t-e}getEyeBox(n,t,e,i,r=!1){const a=Un.squarifyBox(Un.enlargeBox(this.calculateLandmarksBoundingBox([n[e],n[i]]),this.irisEnlarge)),s=Un.getBoxSize(a);let o=Xn.image.cropAndResize(t,[[a.startPoint[1]/this.meshHeight,a.startPoint[0]/this.meshWidth,a.endPoint[1]/this.meshHeight,a.endPoint[0]/this.meshWidth]],[0],[this.irisSize,this.irisSize]);return r&&(o=Xn.image.flipLeftRight(o)),{box:a,boxSize:s,crop:o}}getEyeCoords(n,t,e,i=!1){const r=[];for(let a=0;a{let l=a;return o===2?l=i:o===4&&(l=r),[s[0],s[1],l]})}async predict(n,t){if(this.skipFrames=t.detector.skipFrames,this.maxFaces=t.detector.maxFaces,this.runsWithoutFaceDetector++,this.shouldUpdateRegionsOfInterest()){const i=await this.boundingBoxDetector.getBoundingBoxes(n);if(i.boxes.length===0)return this.regionsOfInterest=[],null;const r=i.boxes.map(a=>{const s=a.box.startPoint.squeeze(),o=a.box.endPoint.squeeze(),l={startPoint:s.arraySync(),endPoint:o.arraySync()};s.dispose(),o.dispose();const u=Un.scaleBoxCoordinates(l,i.scaleFactor),c=Un.enlargeBox(u),h=a.landmarks.arraySync();return a.box.startPoint.dispose(),a.box.endPoint.dispose(),a.landmarks.dispose(),a.probability.dispose(),{...c,landmarks:h}});this.updateRegionsOfInterest(r),this.runsWithoutFaceDetector=0}const e=Xn.tidy(()=>this.regionsOfInterest.map((i,r)=>{let a=0;const s=i.landmarks.length>=T8;let[o,l]=C8;s===!1&&([o,l]=E8),a=Ii.computeRotation(i.landmarks[o],i.landmarks[l]);const u=Un.getBoxCenter({startPoint:i.startPoint,endPoint:i.endPoint}),c=[u[0]/n.shape[2],u[1]/n.shape[1]];let h=n,d=Ii.IDENTITY_MATRIX;a!==0&&(h=Xn.image.rotateWithOffset(n,a,0,c),d=Ii.buildRotationMatrix(-a,u));const p={startPoint:i.startPoint,endPoint:i.endPoint},f=Un.cutBoxFromImageAndResize(p,h,[this.meshHeight,this.meshWidth]).div(255),[,m,g]=this.meshDetector.predict(f),v=Xn.reshape(g,[-1,3]);let b=v.arraySync();if(t.iris.enabled){const{box:I,boxSize:C,crop:E}=this.getEyeBox(b,f,ep[0],ep[1],!0),{box:k,boxSize:W,crop:F}=this.getEyeBox(b,f,np[0],np[1]),_=this.irisModel.predict(Xn.concat([E,F])),H=_.dataSync();_.dispose();const P=H.slice(0,ip*3),{rawCoords:K,iris:j}=this.getEyeCoords(P,I,C,!0),q=H.slice(ip*3),{rawCoords:G,iris:Z}=this.getEyeCoords(q,k,W),X=this.getLeftToRightEyeDepthDifference(b);Math.abs(X)<30?(Mo(b,K,"left"),Mo(b,G,"right")):X<1?Mo(b,K,"left",["EyeUpper0","EyeLower0"]):Mo(b,G,"right",["EyeUpper0","EyeLower0"]);const ee=this.getAdjustedIrisCoords(b,j,"left"),ne=this.getAdjustedIrisCoords(b,Z,"right");b=b.concat(ee).concat(ne)}const S=this.transformRawCoords(b,i,a,d);Xn.dispose(b);const L=Un.enlargeBox(this.calculateLandmarksBoundingBox(S)),w=m.squeeze();if(Xn.dispose(m),t.mesh.enabled){const I=Xn.tensor2d(S);this.regionsOfInterest[r]={...L,landmarks:I.arraySync()};const C={coords:I,box:L,confidence:w,image:f};return C}const N={coords:null,box:L,confidence:w,image:f};return N}));return e}updateRegionsOfInterest(n){for(let t=0;t=this.skipFrames}calculateLandmarksBoundingBox(n){const t=n.map(a=>a[0]),e=n.map(a=>a[1]),i=[Math.min(...t),Math.min(...e)],r=[Math.max(...t),Math.max(...e)];return{startPoint:i,endPoint:r,landmarks:n}}}oL.Pipeline=W8});var cL=be(uL=>{uL.UV_COORDS=[[.499976992607117,.652534008026123],[.500025987625122,.547487020492554],[.499974012374878,.602371990680695],[.482113003730774,.471979022026062],[.500150978565216,.527155995368958],[.499909996986389,.498252987861633],[.499523013830185,.40106201171875],[.289712011814117,.380764007568359],[.499954998493195,.312398016452789],[.499987006187439,.269918978214264],[.500023007392883,.107050001621246],[.500023007392883,.666234016418457],[.5000159740448,.679224014282227],[.500023007392883,.692348003387451],[.499976992607117,.695277988910675],[.499976992607117,.70593398809433],[.499976992607117,.719385027885437],[.499976992607117,.737019002437592],[.499967992305756,.781370997428894],[.499816000461578,.562981009483337],[.473773002624512,.573909997940063],[.104906998574734,.254140973091125],[.365929991006851,.409575998783112],[.338757991790771,.41302502155304],[.311120003461838,.409460008144379],[.274657994508743,.389131009578705],[.393361985683441,.403706014156342],[.345234006643295,.344011008739471],[.370094001293182,.346076011657715],[.319321990013123,.347265005111694],[.297903001308441,.353591024875641],[.24779200553894,.410809993743896],[.396889001131058,.842755019664764],[.280097991228104,.375599980354309],[.106310002505779,.399955987930298],[.2099249958992,.391353011131287],[.355807989835739,.534406006336212],[.471751004457474,.65040397644043],[.474155008792877,.680191993713379],[.439785003662109,.657229006290436],[.414617002010345,.66654098033905],[.450374007225037,.680860996246338],[.428770989179611,.682690978050232],[.374971002340317,.727805018424988],[.486716985702515,.547628998756409],[.485300987958908,.527395009994507],[.257764995098114,.314490020275116],[.401223003864288,.455172002315521],[.429818987846375,.548614978790283],[.421351999044418,.533740997314453],[.276895999908447,.532056987285614],[.483370006084442,.499586999416351],[.33721199631691,.282882988452911],[.296391993761063,.293242990970612],[.169294998049736,.193813979625702],[.447580009698868,.302609980106354],[.392390012741089,.353887975215912],[.354490011930466,.696784019470215],[.067304998636246,.730105042457581],[.442739009857178,.572826027870178],[.457098007202148,.584792017936707],[.381974011659622,.694710969924927],[.392388999462128,.694203019142151],[.277076005935669,.271932005882263],[.422551989555359,.563233017921448],[.385919004678726,.281364023685455],[.383103013038635,.255840003490448],[.331431001424789,.119714021682739],[.229923993349075,.232002973556519],[.364500999450684,.189113974571228],[.229622006416321,.299540996551514],[.173287004232407,.278747975826263],[.472878992557526,.666198015213013],[.446828007698059,.668527007102966],[.422762006521225,.673889994621277],[.445307999849319,.580065965652466],[.388103008270264,.693961024284363],[.403039008378983,.706539988517761],[.403629004955292,.693953037261963],[.460041999816895,.557139039039612],[.431158006191254,.692366003990173],[.452181994915009,.692366003990173],[.475387006998062,.692366003990173],[.465828001499176,.779190003871918],[.472328990697861,.736225962638855],[.473087012767792,.717857003211975],[.473122000694275,.704625964164734],[.473033010959625,.695277988910675],[.427942007780075,.695277988910675],[.426479011774063,.703539967536926],[.423162013292313,.711845993995667],[.4183090031147,.720062971115112],[.390094995498657,.639572978019714],[.013953999616206,.560034036636353],[.499913990497589,.58014702796936],[.413199990987778,.69539999961853],[.409626007080078,.701822996139526],[.468080013990402,.601534962654114],[.422728985548019,.585985004901886],[.463079988956451,.593783974647522],[.37211999297142,.47341400384903],[.334562003612518,.496073007583618],[.411671012639999,.546965003013611],[.242175996303558,.14767599105835],[.290776997804642,.201445996761322],[.327338010072708,.256527006626129],[.399509996175766,.748921036720276],[.441727995872498,.261676013469696],[.429764986038208,.187834024429321],[.412198007106781,.108901023864746],[.288955003023148,.398952007293701],[.218936994671822,.435410976409912],[.41278201341629,.398970007896423],[.257135003805161,.355440020561218],[.427684992551804,.437960982322693],[.448339998722076,.536936044692993],[.178560003638268,.45755398273468],[.247308000922203,.457193970680237],[.286267012357712,.467674970626831],[.332827985286713,.460712015628815],[.368755996227264,.447206974029541],[.398963987827301,.432654976844788],[.476410001516342,.405806005001068],[.189241006970406,.523923993110657],[.228962004184723,.348950982093811],[.490725994110107,.562400996685028],[.404670000076294,.485132992267609],[.019469000399113,.401564002037048],[.426243007183075,.420431017875671],[.396993011236191,.548797011375427],[.266469985246658,.376977026462555],[.439121007919312,.51895797252655],[.032313998788595,.644356966018677],[.419054001569748,.387154996395111],[.462783008813858,.505746960639954],[.238978996872902,.779744982719421],[.198220998048782,.831938028335571],[.107550002634525,.540755033493042],[.183610007166862,.740257024765015],[.134409993886948,.333683013916016],[.385764002799988,.883153975009918],[.490967005491257,.579378008842468],[.382384985685349,.508572995662689],[.174399003386497,.397670984268188],[.318785011768341,.39623498916626],[.343364000320435,.400596976280212],[.396100014448166,.710216999053955],[.187885001301765,.588537991046906],[.430987000465393,.944064974784851],[.318993002176285,.898285031318665],[.266247987747192,.869701027870178],[.500023007392883,.190576016902924],[.499976992607117,.954452991485596],[.366169989109039,.398822009563446],[.393207013607025,.39553701877594],[.410373002290726,.391080021858215],[.194993004202843,.342101991176605],[.388664990663528,.362284004688263],[.365961998701096,.355970978736877],[.343364000320435,.355356991291046],[.318785011768341,.35834002494812],[.301414996385574,.363156020641327],[.058132998645306,.319076001644135],[.301414996385574,.387449026107788],[.499987989664078,.618434011936188],[.415838003158569,.624195992946625],[.445681989192963,.566076993942261],[.465844005346298,.620640993118286],[.49992299079895,.351523995399475],[.288718998432159,.819945991039276],[.335278987884521,.852819979190826],[.440512001514435,.902418971061707],[.128294005990028,.791940987110138],[.408771991729736,.373893976211548],[.455606997013092,.451801002025604],[.499877005815506,.908990025520325],[.375436991453171,.924192011356354],[.11421000212431,.615022003650665],[.448662012815475,.695277988910675],[.4480200111866,.704632043838501],[.447111994028091,.715808033943176],[.444831997156143,.730794012546539],[.430011987686157,.766808986663818],[.406787008047104,.685672998428345],[.400738000869751,.681069016456604],[.392399996519089,.677703022956848],[.367855995893478,.663918972015381],[.247923001646996,.601333022117615],[.452769994735718,.420849978923798],[.43639200925827,.359887003898621],[.416164010763168,.368713974952698],[.413385987281799,.692366003990173],[.228018000721931,.683571994304657],[.468268007040024,.352671027183533],[.411361992359161,.804327011108398],[.499989002943039,.469825029373169],[.479153990745544,.442654013633728],[.499974012374878,.439637005329132],[.432112008333206,.493588984012604],[.499886006116867,.866917014122009],[.49991300702095,.821729004383087],[.456548988819122,.819200992584229],[.344549000263214,.745438992977142],[.37890899181366,.574010014533997],[.374292999505997,.780184984207153],[.319687992334366,.570737957954407],[.357154995203018,.604269981384277],[.295284003019333,.621580958366394],[.447750002145767,.862477004528046],[.410986006259918,.508723020553589],[.31395098567009,.775308012962341],[.354128003120422,.812552988529205],[.324548006057739,.703992962837219],[.189096003770828,.646299958229065],[.279776990413666,.71465802192688],[.1338230073452,.682700991630554],[.336768001317978,.644733011722565],[.429883986711502,.466521978378296],[.455527991056442,.548622965812683],[.437114000320435,.558896005153656],[.467287987470627,.529924988746643],[.414712011814117,.335219979286194],[.37704598903656,.322777986526489],[.344107985496521,.320150971412659],[.312875986099243,.32233202457428],[.283526003360748,.333190023899078],[.241245999932289,.382785975933075],[.102986000478268,.468762993812561],[.267612010240555,.424560010433197],[.297879010438919,.433175981044769],[.333433985710144,.433878004550934],[.366427004337311,.426115989685059],[.396012008190155,.416696012020111],[.420121014118195,.41022801399231],[.007561000064015,.480777025222778],[.432949006557465,.569517970085144],[.458638995885849,.479089021682739],[.473466008901596,.545744001865387],[.476087987422943,.563830018043518],[.468472003936768,.555056989192963],[.433990985155106,.582361996173859],[.483518004417419,.562983989715576],[.482482999563217,.57784903049469],[.42645001411438,.389798998832703],[.438998997211456,.39649498462677],[.450067013502121,.400434017181396],[.289712011814117,.368252992630005],[.276670008897781,.363372981548309],[.517862021923065,.471948027610779],[.710287988185883,.380764007568359],[.526226997375488,.573909997940063],[.895093023777008,.254140973091125],[.634069979190826,.409575998783112],[.661242008209229,.41302502155304],[.688880026340485,.409460008144379],[.725341975688934,.389131009578705],[.606630027294159,.40370500087738],[.654766023159027,.344011008739471],[.629905998706818,.346076011657715],[.680678009986877,.347265005111694],[.702096998691559,.353591024875641],[.75221198797226,.410804986953735],[.602918028831482,.842862963676453],[.719901978969574,.375599980354309],[.893692970275879,.399959981441498],[.790081977844238,.391354024410248],[.643998026847839,.534487962722778],[.528249025344849,.65040397644043],[.525849997997284,.680191040039062],[.560214996337891,.657229006290436],[.585384011268616,.66654098033905],[.549625992774963,.680860996246338],[.57122802734375,.682691991329193],[.624852001667023,.72809898853302],[.513050019741058,.547281980514526],[.51509702205658,.527251958847046],[.742246985435486,.314507007598877],[.598631024360657,.454979002475739],[.570338010787964,.548575043678284],[.578631997108459,.533622980117798],[.723087012767792,.532054007053375],[.516445994377136,.499638974666595],[.662801027297974,.282917976379395],[.70362401008606,.293271005153656],[.830704987049103,.193813979625702],[.552385985851288,.302568018436432],[.607609987258911,.353887975215912],[.645429015159607,.696707010269165],[.932694971561432,.730105042457581],[.557260990142822,.572826027870178],[.542901992797852,.584792017936707],[.6180260181427,.694710969924927],[.607590973377228,.694203019142151],[.722943007946014,.271963000297546],[.577413976192474,.563166975975037],[.614082992076874,.281386971473694],[.616907000541687,.255886018276215],[.668509006500244,.119913995265961],[.770092010498047,.232020974159241],[.635536015033722,.189248979091644],[.77039098739624,.299556016921997],[.826722025871277,.278755009174347],[.527121007442474,.666198015213013],[.553171992301941,.668527007102966],[.577238023281097,.673889994621277],[.554691970348358,.580065965652466],[.611896991729736,.693961024284363],[.59696102142334,.706539988517761],[.596370995044708,.693953037261963],[.539958000183105,.557139039039612],[.568841993808746,.692366003990173],[.547818005084991,.692366003990173],[.52461302280426,.692366003990173],[.534089982509613,.779141008853912],[.527670979499817,.736225962638855],[.526912987232208,.717857003211975],[.526877999305725,.704625964164734],[.526966989040375,.695277988910675],[.572058022022247,.695277988910675],[.573521018028259,.703539967536926],[.57683801651001,.711845993995667],[.581691026687622,.720062971115112],[.609944999217987,.639909982681274],[.986046016216278,.560034036636353],[.5867999792099,.69539999961853],[.590372025966644,.701822996139526],[.531915009021759,.601536989212036],[.577268004417419,.585934996604919],[.536915004253387,.593786001205444],[.627542972564697,.473352015018463],[.665585994720459,.495950996875763],[.588353991508484,.546862006187439],[.757824003696442,.14767599105835],[.709249973297119,.201507985591888],[.672684013843536,.256581008434296],[.600408971309662,.74900496006012],[.55826598405838,.261672019958496],[.570303976535797,.187870979309082],[.588165998458862,.109044015407562],[.711045026779175,.398952007293701],[.781069993972778,.435405015945435],[.587247014045715,.398931980133057],[.742869973182678,.355445981025696],[.572156012058258,.437651991844177],[.55186802148819,.536570012569427],[.821442008018494,.457556009292603],[.752701997756958,.457181990146637],[.71375697851181,.467626988887787],[.66711300611496,.460672974586487],[.631101012229919,.447153985500336],[.6008620262146,.432473003864288],[.523481011390686,.405627012252808],[.810747981071472,.523926019668579],[.771045982837677,.348959028720856],[.509127020835876,.562718033790588],[.595292985439301,.485023975372314],[.980530977249146,.401564002037048],[.573499977588654,.420000016689301],[.602994978427887,.548687994480133],[.733529984951019,.376977026462555],[.560611009597778,.519016981124878],[.967685997486115,.644356966018677],[.580985009670258,.387160003185272],[.537728011608124,.505385041236877],[.760966002941132,.779752969741821],[.801778972148895,.831938028335571],[.892440974712372,.54076099395752],[.816350996494293,.740260004997253],[.865594983100891,.333687007427216],[.614073991775513,.883246004581451],[.508952975273132,.579437971115112],[.617941975593567,.508316040039062],[.825608015060425,.397674977779388],[.681214988231659,.39623498916626],[.656635999679565,.400596976280212],[.603900015354156,.710216999053955],[.81208598613739,.588539004325867],[.56801301240921,.944564998149872],[.681007981300354,.898285031318665],[.733752012252808,.869701027870178],[.633830010890961,.398822009563446],[.606792986392975,.39553701877594],[.589659988880157,.391062021255493],[.805015981197357,.342108011245728],[.611334979534149,.362284004688263],[.634037971496582,.355970978736877],[.656635999679565,.355356991291046],[.681214988231659,.35834002494812],[.698584973812103,.363156020641327],[.941866993904114,.319076001644135],[.698584973812103,.387449026107788],[.584177017211914,.624107003211975],[.554318010807037,.566076993942261],[.534153997898102,.62064003944397],[.711217999458313,.819975018501282],[.664629995822906,.852871000766754],[.559099972248077,.902631998062134],[.871706008911133,.791940987110138],[.591234028339386,.373893976211548],[.544341027736664,.451583981513977],[.624562978744507,.924192011356354],[.88577002286911,.615028977394104],[.551338016986847,.695277988910675],[.551980018615723,.704632043838501],[.552887976169586,.715808033943176],[.555167973041534,.730794012546539],[.569944024085999,.767035007476807],[.593203008174896,.685675978660583],[.599261999130249,.681069016456604],[.607599973678589,.677703022956848],[.631937980651855,.663500010967255],[.752032995223999,.601315021514893],[.547226011753082,.420395016670227],[.563543975353241,.359827995300293],[.583841025829315,.368713974952698],[.586614012718201,.692366003990173],[.771915018558502,.683578014373779],[.531597018241882,.352482974529266],[.588370978832245,.804440975189209],[.52079701423645,.442565023899078],[.567984998226166,.493479013442993],[.543282985687256,.819254994392395],[.655317008495331,.745514988899231],[.621008992195129,.574018001556396],[.625559985637665,.78031200170517],[.680198013782501,.570719003677368],[.64276397228241,.604337990283966],[.704662978649139,.621529996395111],[.552012026309967,.862591981887817],[.589071989059448,.508637011051178],[.685944974422455,.775357007980347],[.645735025405884,.812640011310577],[.675342977046967,.703978002071381],[.810858011245728,.646304965019226],[.72012197971344,.714666962623596],[.866151988506317,.682704985141754],[.663187026977539,.644596993923187],[.570082008838654,.466325998306274],[.544561982154846,.548375964164734],[.562758982181549,.558784961700439],[.531987011432648,.530140042304993],[.585271000862122,.335177004337311],[.622952997684479,.32277899980545],[.655896008014679,.320163011550903],[.687132000923157,.322345972061157],[.716481983661652,.333200991153717],[.758756995201111,.382786989212036],[.897013008594513,.468769013881683],[.732392013072968,.424547016620636],[.70211398601532,.433162987232208],[.66652500629425,.433866024017334],[.633504986763,.426087975502014],[.603875994682312,.416586995124817],[.579657971858978,.409945011138916],[.992439985275269,.480777025222778],[.567192018032074,.569419980049133],[.54136598110199,.478899002075195],[.526564002037048,.546118021011353],[.523913025856018,.563830018043518],[.531529009342194,.555056989192963],[.566035985946655,.582329034805298],[.51631098985672,.563053965568542],[.5174720287323,.577877044677734],[.573594987392426,.389806985855103],[.560697972774506,.395331978797913],[.549755990505219,.399751007556915],[.710287988185883,.368252992630005],[.723330020904541,.363372981548309]]});var hL=be(U8=>{Ap(U8,{default:()=>B8});var B8=[127,34,139,11,0,37,232,231,120,72,37,39,128,121,47,232,121,128,104,69,67,175,171,148,157,154,155,118,50,101,73,39,40,9,151,108,48,115,131,194,204,211,74,40,185,80,42,183,40,92,186,230,229,118,202,212,214,83,18,17,76,61,146,160,29,30,56,157,173,106,204,194,135,214,192,203,165,98,21,71,68,51,45,4,144,24,23,77,146,91,205,50,187,201,200,18,91,106,182,90,91,181,85,84,17,206,203,36,148,171,140,92,40,39,193,189,244,159,158,28,247,246,161,236,3,196,54,68,104,193,168,8,117,228,31,189,193,55,98,97,99,126,47,100,166,79,218,155,154,26,209,49,131,135,136,150,47,126,217,223,52,53,45,51,134,211,170,140,67,69,108,43,106,91,230,119,120,226,130,247,63,53,52,238,20,242,46,70,156,78,62,96,46,53,63,143,34,227,173,155,133,123,117,111,44,125,19,236,134,51,216,206,205,154,153,22,39,37,167,200,201,208,36,142,100,57,212,202,20,60,99,28,158,157,35,226,113,160,159,27,204,202,210,113,225,46,43,202,204,62,76,77,137,123,116,41,38,72,203,129,142,64,98,240,49,102,64,41,73,74,212,216,207,42,74,184,169,170,211,170,149,176,105,66,69,122,6,168,123,147,187,96,77,90,65,55,107,89,90,180,101,100,120,63,105,104,93,137,227,15,86,85,129,102,49,14,87,86,55,8,9,100,47,121,145,23,22,88,89,179,6,122,196,88,95,96,138,172,136,215,58,172,115,48,219,42,80,81,195,3,51,43,146,61,171,175,199,81,82,38,53,46,225,144,163,110,246,33,7,52,65,66,229,228,117,34,127,234,107,108,69,109,108,151,48,64,235,62,78,191,129,209,126,111,35,143,163,161,246,117,123,50,222,65,52,19,125,141,221,55,65,3,195,197,25,7,33,220,237,44,70,71,139,122,193,245,247,130,33,71,21,162,153,158,159,170,169,150,188,174,196,216,186,92,144,160,161,2,97,167,141,125,241,164,167,37,72,38,12,145,159,160,38,82,13,63,68,71,226,35,111,158,153,154,101,50,205,206,92,165,209,198,217,165,167,97,220,115,218,133,112,243,239,238,241,214,135,169,190,173,133,171,208,32,125,44,237,86,87,178,85,86,179,84,85,180,83,84,181,201,83,182,137,93,132,76,62,183,61,76,184,57,61,185,212,57,186,214,207,187,34,143,156,79,239,237,123,137,177,44,1,4,201,194,32,64,102,129,213,215,138,59,166,219,242,99,97,2,94,141,75,59,235,24,110,228,25,130,226,23,24,229,22,23,230,26,22,231,112,26,232,189,190,243,221,56,190,28,56,221,27,28,222,29,27,223,30,29,224,247,30,225,238,79,20,166,59,75,60,75,240,147,177,215,20,79,166,187,147,213,112,233,244,233,128,245,128,114,188,114,217,174,131,115,220,217,198,236,198,131,134,177,132,58,143,35,124,110,163,7,228,110,25,356,389,368,11,302,267,452,350,349,302,303,269,357,343,277,452,453,357,333,332,297,175,152,377,384,398,382,347,348,330,303,304,270,9,336,337,278,279,360,418,262,431,304,408,409,310,415,407,270,409,410,450,348,347,422,430,434,313,314,17,306,307,375,387,388,260,286,414,398,335,406,418,364,367,416,423,358,327,251,284,298,281,5,4,373,374,253,307,320,321,425,427,411,421,313,18,321,405,406,320,404,405,315,16,17,426,425,266,377,400,369,322,391,269,417,465,464,386,257,258,466,260,388,456,399,419,284,332,333,417,285,8,346,340,261,413,441,285,327,460,328,355,371,329,392,439,438,382,341,256,429,420,360,364,394,379,277,343,437,443,444,283,275,440,363,431,262,369,297,338,337,273,375,321,450,451,349,446,342,467,293,334,282,458,461,462,276,353,383,308,324,325,276,300,293,372,345,447,382,398,362,352,345,340,274,1,19,456,248,281,436,427,425,381,256,252,269,391,393,200,199,428,266,330,329,287,273,422,250,462,328,258,286,384,265,353,342,387,259,257,424,431,430,342,353,276,273,335,424,292,325,307,366,447,345,271,303,302,423,266,371,294,455,460,279,278,294,271,272,304,432,434,427,272,407,408,394,430,431,395,369,400,334,333,299,351,417,168,352,280,411,325,319,320,295,296,336,319,403,404,330,348,349,293,298,333,323,454,447,15,16,315,358,429,279,14,15,316,285,336,9,329,349,350,374,380,252,318,402,403,6,197,419,318,319,325,367,364,365,435,367,397,344,438,439,272,271,311,195,5,281,273,287,291,396,428,199,311,271,268,283,444,445,373,254,339,263,466,249,282,334,296,449,347,346,264,447,454,336,296,299,338,10,151,278,439,455,292,407,415,358,371,355,340,345,372,390,249,466,346,347,280,442,443,282,19,94,370,441,442,295,248,419,197,263,255,359,440,275,274,300,383,368,351,412,465,263,467,466,301,368,389,380,374,386,395,378,379,412,351,419,436,426,322,373,390,388,2,164,393,370,462,461,164,0,267,302,11,12,374,373,387,268,12,13,293,300,301,446,261,340,385,384,381,330,266,425,426,423,391,429,355,437,391,327,326,440,457,438,341,382,362,459,457,461,434,430,394,414,463,362,396,369,262,354,461,457,316,403,402,315,404,403,314,405,404,313,406,405,421,418,406,366,401,361,306,408,407,291,409,408,287,410,409,432,436,410,434,416,411,264,368,383,309,438,457,352,376,401,274,275,4,421,428,262,294,327,358,433,416,367,289,455,439,462,370,326,2,326,370,305,460,455,254,449,448,255,261,446,253,450,449,252,451,450,256,452,451,341,453,452,413,464,463,441,413,414,258,442,441,257,443,442,259,444,443,260,445,444,467,342,445,459,458,250,289,392,290,290,328,460,376,433,435,250,290,392,411,416,433,341,463,464,453,464,465,357,465,412,343,412,399,360,363,440,437,399,456,420,456,363,401,435,288,372,383,353,339,255,249,448,261,255,133,243,190,133,155,112,33,246,247,33,130,25,398,384,286,362,398,414,362,463,341,263,359,467,263,249,255,466,467,260,75,60,166,238,239,79,162,127,139,72,11,37,121,232,120,73,72,39,114,128,47,233,232,128,103,104,67,152,175,148,173,157,155,119,118,101,74,73,40,107,9,108,49,48,131,32,194,211,184,74,185,191,80,183,185,40,186,119,230,118,210,202,214,84,83,17,77,76,146,161,160,30,190,56,173,182,106,194,138,135,192,129,203,98,54,21,68,5,51,4,145,144,23,90,77,91,207,205,187,83,201,18,181,91,182,180,90,181,16,85,17,205,206,36,176,148,140,165,92,39,245,193,244,27,159,28,30,247,161,174,236,196,103,54,104,55,193,8,111,117,31,221,189,55,240,98,99,142,126,100,219,166,218,112,155,26,198,209,131,169,135,150,114,47,217,224,223,53,220,45,134,32,211,140,109,67,108,146,43,91,231,230,120,113,226,247,105,63,52,241,238,242,124,46,156,95,78,96,70,46,63,116,143,227,116,123,111,1,44,19,3,236,51,207,216,205,26,154,22,165,39,167,199,200,208,101,36,100,43,57,202,242,20,99,56,28,157,124,35,113,29,160,27,211,204,210,124,113,46,106,43,204,96,62,77,227,137,116,73,41,72,36,203,142,235,64,240,48,49,64,42,41,74,214,212,207,183,42,184,210,169,211,140,170,176,104,105,69,193,122,168,50,123,187,89,96,90,66,65,107,179,89,180,119,101,120,68,63,104,234,93,227,16,15,85,209,129,49,15,14,86,107,55,9,120,100,121,153,145,22,178,88,179,197,6,196,89,88,96,135,138,136,138,215,172,218,115,219,41,42,81,5,195,51,57,43,61,208,171,199,41,81,38,224,53,225,24,144,110,105,52,66,118,229,117,227,34,234,66,107,69,10,109,151,219,48,235,183,62,191,142,129,126,116,111,143,7,163,246,118,117,50,223,222,52,94,19,141,222,221,65,196,3,197,45,220,44,156,70,139,188,122,245,139,71,162,145,153,159,149,170,150,122,188,196,206,216,92,163,144,161,164,2,167,242,141,241,0,164,37,11,72,12,144,145,160,12,38,13,70,63,71,31,226,111,157,158,154,36,101,205,203,206,165,126,209,217,98,165,97,237,220,218,237,239,241,210,214,169,140,171,32,241,125,237,179,86,178,180,85,179,181,84,180,182,83,181,194,201,182,177,137,132,184,76,183,185,61,184,186,57,185,216,212,186,192,214,187,139,34,156,218,79,237,147,123,177,45,44,4,208,201,32,98,64,129,192,213,138,235,59,219,141,242,97,97,2,141,240,75,235,229,24,228,31,25,226,230,23,229,231,22,230,232,26,231,233,112,232,244,189,243,189,221,190,222,28,221,223,27,222,224,29,223,225,30,224,113,247,225,99,60,240,213,147,215,60,20,166,192,187,213,243,112,244,244,233,245,245,128,188,188,114,174,134,131,220,174,217,236,236,198,134,215,177,58,156,143,124,25,110,7,31,228,25,264,356,368,0,11,267,451,452,349,267,302,269,350,357,277,350,452,357,299,333,297,396,175,377,381,384,382,280,347,330,269,303,270,151,9,337,344,278,360,424,418,431,270,304,409,272,310,407,322,270,410,449,450,347,432,422,434,18,313,17,291,306,375,259,387,260,424,335,418,434,364,416,391,423,327,301,251,298,275,281,4,254,373,253,375,307,321,280,425,411,200,421,18,335,321,406,321,320,405,314,315,17,423,426,266,396,377,369,270,322,269,413,417,464,385,386,258,248,456,419,298,284,333,168,417,8,448,346,261,417,413,285,326,327,328,277,355,329,309,392,438,381,382,256,279,429,360,365,364,379,355,277,437,282,443,283,281,275,363,395,431,369,299,297,337,335,273,321,348,450,349,359,446,467,283,293,282,250,458,462,300,276,383,292,308,325,283,276,293,264,372,447,346,352,340,354,274,19,363,456,281,426,436,425,380,381,252,267,269,393,421,200,428,371,266,329,432,287,422,290,250,328,385,258,384,446,265,342,386,387,257,422,424,430,445,342,276,422,273,424,306,292,307,352,366,345,268,271,302,358,423,371,327,294,460,331,279,294,303,271,304,436,432,427,304,272,408,395,394,431,378,395,400,296,334,299,6,351,168,376,352,411,307,325,320,285,295,336,320,319,404,329,330,349,334,293,333,366,323,447,316,15,315,331,358,279,317,14,316,8,285,9,277,329,350,253,374,252,319,318,403,351,6,419,324,318,325,397,367,365,288,435,397,278,344,439,310,272,311,248,195,281,375,273,291,175,396,199,312,311,268,276,283,445,390,373,339,295,282,296,448,449,346,356,264,454,337,336,299,337,338,151,294,278,455,308,292,415,429,358,355,265,340,372,388,390,466,352,346,280,295,442,282,354,19,370,285,441,295,195,248,197,457,440,274,301,300,368,417,351,465,251,301,389,385,380,386,394,395,379,399,412,419,410,436,322,387,373,388,326,2,393,354,370,461,393,164,267,268,302,12,386,374,387,312,268,13,298,293,301,265,446,340,380,385,381,280,330,425,322,426,391,420,429,437,393,391,326,344,440,438,458,459,461,364,434,394,428,396,262,274,354,457,317,316,402,316,315,403,315,314,404,314,313,405,313,421,406,323,366,361,292,306,407,306,291,408,291,287,409,287,432,410,427,434,411,372,264,383,459,309,457,366,352,401,1,274,4,418,421,262,331,294,358,435,433,367,392,289,439,328,462,326,94,2,370,289,305,455,339,254,448,359,255,446,254,253,449,253,252,450,252,256,451,256,341,452,414,413,463,286,441,414,286,258,441,258,257,442,257,259,443,259,260,444,260,467,445,309,459,250,305,289,290,305,290,460,401,376,435,309,250,392,376,411,433,453,341,464,357,453,465,343,357,412,437,343,399,344,360,440,420,437,456,360,420,363,361,401,288,265,372,353,390,339,249,339,448,255]});var fL=be(ts=>{const rp=Ht(),z8=eL(),dL=Xd(),_8=lL(),P8=cL(),M8=hL().default;class pL{constructor(n,t,e,i){this.pipeline=new _8.Pipeline(n,t,e,i),i&&(this.config=i)}async estimateFaces(n,t){t&&(this.config=t);const e=await this.pipeline.predict(n,t),i=[];for(const r of e||[]){if(r.isDisposedInternal)continue;const a=r.confidence.arraySync();if(a>=this.config.detector.minConfidence){const s=r.coords?r.coords.arraySync():null,o={};if(s&&s.length>0)for(const l in dL.MESH_ANNOTATIONS)(this.config.iris.enabled||l.includes("Iris")===!1)&&(o[l]=dL.MESH_ANNOTATIONS[l].map(u=>s[u]));i.push({confidence:a||0,box:r.box?[r.box.startPoint[0],r.box.startPoint[1],r.box.endPoint[0]-r.box.startPoint[0],r.box.endPoint[1]-r.box.startPoint[1]]:0,mesh:s,annotations:o,image:r.image?rp.clone(r.image):null})}r.confidence&&r.confidence.dispose(),r.coords&&r.coords.dispose(),r.image&&r.image.dispose()}return i}}async function H8(n){const t=await Promise.all([z8.load(n),rp.loadGraphModel(n.mesh.modelPath,{fromTFHub:n.mesh.modelPath.includes("tfhub.dev")}),rp.loadGraphModel(n.iris.modelPath,{fromTFHub:n.iris.modelPath.includes("tfhub.dev")})]),e=new pL(t[0],t[1],t[2],n);return e}ts.load=H8;ts.MediaPipeFaceMesh=pL;ts.uv_coords=P8;ts.triangulation=M8});var gL=be(Ho=>{const Ai=Ht(),Ti={};let mL={age:0,gender:""},ap=0;async function V8(n){return Ti.age||(Ti.age=await Ai.loadGraphModel(n.face.age.modelPath)),Ti.age}async function q8(n){return Ti.gender||(Ti.gender=await Ai.loadGraphModel(n.face.gender.modelPath)),Ti.gender}async function G8(n,t){if(apt.face.gender.minConfidence&&(o.gender=l[0]<=.5?"female":"male",o.confidence=u),Ai.dispose(s)}return Ai.dispose(i),mL=o,o}Ho.predict=G8;Ho.loadAge=V8;Ho.loadGender=q8});var bL=be(sp=>{const Jn=Ht(),Y8=["angry","discust","fear","happy","sad","surpise","neutral"],Vo={};let vL=[],op=0;const yL=1.5;async function K8(n){return Vo.emotion||(Vo.emotion=await Jn.loadGraphModel(n.face.emotion.modelPath)),Vo.emotion}async function j8(n,t){if(opt.face.emotion.minConfidence&&c.push({score:Math.min(.99,Math.trunc(100*yL*d[p])/100),emotion:Y8[p]});c.sort((p,f)=>f.score-p.score),Jn.dispose(h)}return Jn.dispose(u),vL=c,c}sp.predict=j8;sp.load=K8});var LL=be(wL=>{const SL=Ht();class $8{constructor(n,t){this.model=n,this.outputStride=t;const e=this.model.inputs[0].shape;SL.util.assert(e[1]===-1&&e[2]===-1,()=>`Input shape [${e[1]}, ${e[2]}] must both be equal to or -1`)}predict(n){return SL.tidy(()=>{const t=this.preprocessInput(n.toFloat()),e=t.expandDims(0),i=this.model.predict(e),r=i.map(s=>s.squeeze([0])),a=this.nameOutputResults(r);return{heatmapScores:a.heatmap.sigmoid(),offsets:a.offsets,displacementFwd:a.displacementFwd,displacementBwd:a.displacementBwd}})}dispose(){this.model.dispose()}}wL.BaseModel=$8});var lp=be(IL=>{const AL=Ht(),X8=LL();class J8 extends X8.BaseModel{preprocessInput(n){return AL.tidy(()=>AL.div(n,127.5).sub(1))}nameOutputResults(n){const[t,e,i,r]=n;return{offsets:t,heatmap:e,displacementFwd:i,displacementBwd:r}}}IL.MobileNet=J8});var NL=be(TL=>{function up(n){return Math.floor(n/2)}class Z8{constructor(n,t){this.priorityQueue=new Array(n),this.numberOfElements=-1,this.getElementValue=t}enqueue(n){this.priorityQueue[++this.numberOfElements]=n,this.swim(this.numberOfElements)}dequeue(){const n=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,n}empty(){return this.numberOfElements===-1}size(){return this.numberOfElements+1}all(){return this.priorityQueue.slice(0,this.numberOfElements+1)}max(){return this.priorityQueue[0]}swim(n){for(;n>0&&this.less(up(n),n);)this.exchange(n,up(n)),n=up(n)}sink(n){for(;2*n<=this.numberOfElements;){let t=2*n;if(t{const Q8=NL();function e7(n,t,e,i,r,a){const[s,o]=a.shape;let l=!0;const u=Math.max(e-r,0),c=Math.min(e+r+1,s);for(let h=u;ht){l=!1;break}if(!l)break}return l}function t7(n,t,e){const[i,r,a]=e.shape,s=new Q8.MaxHeap(i*r*a,({score:o})=>o);for(let o=0;o{Sn.partNames=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"];Sn.NUM_KEYPOINTS=Sn.partNames.length;Sn.partIds=Sn.partNames.reduce((n,t,e)=>(n[t]=e,n),{});const n7=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]];Sn.poseChain=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]];Sn.connectedPartIndices=n7.map(([n,t])=>[Sn.partIds[n],Sn.partIds[t]]);Sn.partChannels=["left_face","right_face","right_upper_leg_front","right_lower_leg_back","right_upper_leg_back","left_lower_leg_front","left_upper_leg_front","left_upper_leg_back","left_lower_leg_back","right_feet","right_lower_leg_front","left_feet","torso_front","torso_back","right_upper_arm_front","right_upper_arm_back","right_lower_arm_back","left_lower_arm_front","left_upper_arm_front","left_upper_arm_back","left_lower_arm_back","right_hand","right_lower_arm_front","left_hand"]});var hp=be(Ni=>{const i7=ns();function RL(n,t,e,i){return{y:i.get(n,t,e),x:i.get(n,t,e+i7.NUM_KEYPOINTS)}}Ni.getOffsetPoint=RL;function r7(n,t,e){const{heatmapY:i,heatmapX:r,id:a}=n,{y:s,x:o}=RL(i,r,a,e);return{x:n.heatmapX*t+o,y:n.heatmapY*t+s}}Ni.getImageCoords=r7;function a7(n,t){const e=new Array(t);for(let i=0;ie?e:n}Ni.clamp=cp;function s7(n,t,e,i){const r=e-n,a=i-t;return r*r+a*a}Ni.squaredDistance=s7;function o7(n,t){return{x:n.x+t.x,y:n.y+t.y}}Ni.addVectors=o7;function l7(n,t,e){return{y:cp(n.y,t,e),x:cp(n.x,t,e)}}Ni.clampVector=l7});var FL=be(OL=>{const is=ns(),ra=hp(),EL=is.poseChain.map(([n,t])=>[is.partIds[n],is.partIds[t]]),dp=EL.map(([,n])=>n),DL=EL.map(([n])=>n);function u7(n,t,e){const i=e.shape[2]/2;return{y:e.get(t.y,t.x,n),x:e.get(t.y,t.x,i+n)}}function pp(n,t,e,i){return{y:ra.clamp(Math.round(n.y/t),0,e-1),x:ra.clamp(Math.round(n.x/t),0,i-1)}}function kL(n,t,e,i,r,a,s,o=2){const[l,u]=i.shape,c=pp(t.position,a,l,u),h=u7(n,c,s),d=ra.addVectors(t.position,h);let p=d;for(let g=0;g=0;--d){const p=dp[d],f=DL[d];l[p]&&!l[f]&&(l[f]=kL(d,l[p],f,t,e,i,a))}for(let d=0;d{const h7=CL(),d7=FL(),UL=hp();function BL(n,t,{x:e,y:i},r){return n.some(({keypoints:a})=>{const s=a[r].position;return UL.squaredDistance(i,e,s.y,s.x)<=t})}function p7(n,t,e){const i=e.reduce((r,{position:a,score:s},o)=>(BL(n,t,a,o)||(r+=s),r),0);return i/e.length}const f7=1;function m7(n,t,e,i,r,a,s=.5,o=20){const l=[],u=h7.buildPartWithScoreQueue(s,f7,n),c=o*o;for(;l.length{const g7=ns();function v7(n,t,e){return n(v7(n[i].score,n[r].score,t)||e.push([n[i],n[r]]),e),[])}xi.getAdjacentKeyPoints=y7;const{NEGATIVE_INFINITY:zL,POSITIVE_INFINITY:_L}=Number;function PL(n){return n.reduce(({maxX:t,maxY:e,minX:i,minY:r},{position:{x:a,y:s}})=>({maxX:Math.max(t,a),maxY:Math.max(e,s),minX:Math.min(i,a),minY:Math.min(r,s)}),{maxX:zL,maxY:zL,minX:_L,minY:_L})}xi.getBoundingBox=PL;function b7(n){const{minX:t,minY:e,maxX:i,maxY:r}=PL(n);return[{x:t,y:e},{x:i,y:e},{x:i,y:r},{x:t,y:r}]}xi.getBoundingBoxPoints=b7;async function w7(n){return Promise.all(n.map(t=>t.buffer()))}xi.toTensorBuffers3D=w7;function ML(n,t,e){return{score:n.score,keypoints:n.keypoints.map(({score:i,part:r,position:a})=>({score:i,part:r,position:{x:a.x*e,y:a.y*t}}))}}xi.scalePose=ML;function S7(n,[t,e]){const i=n.squeeze(0),r=i.resizeBilinear([t,e]);return i.dispose(),r}xi.resizeTo=S7;function L7(n,[t,e],[i,r]){const a=n.map(s=>ML(s,t/i,e/r));return a}xi.scaleAndFlipPoses=L7});var VL=be(gp=>{const I7=Ht(),A7=lp(),T7=fp(),vp=mp();class HL{constructor(n){this.baseModel=n}async estimatePoses(n,t){const e=t.outputStride,i=n.shape[1],r=n.shape[2],a=vp.resizeTo(n,[t.inputResolution,t.inputResolution]),{heatmapScores:s,offsets:o,displacementFwd:l,displacementBwd:u}=this.baseModel.predict(a),c=await vp.toTensorBuffers3D([s,o,l,u]),h=c[0],d=c[1],p=c[2],f=c[3],m=await T7.decodeMultiplePoses(h,d,p,f,e,t.maxDetections,t.scoreThreshold,t.nmsRadius),g=vp.scaleAndFlipPoses(m,[i,r],[t.inputResolution,t.inputResolution]);return s.dispose(),o.dispose(),l.dispose(),u.dispose(),a.dispose(),g}dispose(){this.baseModel.dispose()}}gp.PoseNet=HL;async function N7(n){const t=await I7.loadGraphModel(n.modelPath),e=new A7.MobileNet(t,n.outputStride);return new HL(e)}async function x7(n){return N7(n)}gp.load=x7});var GL=be(Xt=>{const C7=lp(),qL=VL(),R7=fp(),qo=ns(),rs=mp();Xt.load=qL.load;Xt.PoseNet=qL.PoseNet;Xt.MobileNet=C7.MobileNet;Xt.decodeMultiplePoses=R7.decodeMultiplePoses;Xt.partChannels=qo.partChannels;Xt.partIds=qo.partIds;Xt.partNames=qo.partNames;Xt.poseChain=qo.poseChain;Xt.getAdjacentKeyPoints=rs.getAdjacentKeyPoints;Xt.getBoundingBox=rs.getBoundingBox;Xt.getBoundingBoxPoints=rs.getBoundingBoxPoints;Xt.scaleAndFlipPoses=rs.scaleAndFlipPoses;Xt.scalePose=rs.scalePose});var wp=be(Ci=>{const O7=Ht();function yp(n){return[Math.abs(n.endPoint[0]-n.startPoint[0]),Math.abs(n.endPoint[1]-n.startPoint[1])]}Ci.getBoxSize=yp;function bp(n){return[n.startPoint[0]+(n.endPoint[0]-n.startPoint[0])/2,n.startPoint[1]+(n.endPoint[1]-n.startPoint[1])/2]}Ci.getBoxCenter=bp;function E7(n,t,e){const i=t.shape[1],r=t.shape[2],a=[[n.startPoint[1]/i,n.startPoint[0]/r,n.endPoint[1]/i,n.endPoint[0]/r]];return O7.image.cropAndResize(t,a,[0],e)}Ci.cutBoxFromImageAndResize=E7;function D7(n,t){const e=[n.startPoint[0]*t[0],n.startPoint[1]*t[1]],i=[n.endPoint[0]*t[0],n.endPoint[1]*t[1]],r=n.palmLandmarks.map(a=>{const s=[a[0]*t[0],a[1]*t[1]];return s});return{startPoint:e,endPoint:i,palmLandmarks:r}}Ci.scaleBoxCoordinates=D7;function k7(n,t=1.5){const e=bp(n),i=yp(n),r=[t*i[0]/2,t*i[1]/2],a=[e[0]-r[0],e[1]-r[1]],s=[e[0]+r[0],e[1]+r[1]];return{startPoint:a,endPoint:s,palmLandmarks:n.palmLandmarks}}Ci.enlargeBox=k7;function F7(n){const t=bp(n),e=yp(n),i=Math.max(...e),r=i/2,a=[t[0]-r,t[1]-r],s=[t[0]+r,t[1]+r];return{startPoint:a,endPoint:s,palmLandmarks:n.palmLandmarks}}Ci.squarifyBox=F7;function W7(n,t){const e=[n.endPoint[0]-n.startPoint[0],n.endPoint[1]-n.startPoint[1]],i=[e[0]*t[0],e[1]*t[1]],r=[n.startPoint[0]+i[0],n.startPoint[1]+i[1]],a=[n.endPoint[0]+i[0],n.endPoint[1]+i[1]];return{startPoint:r,endPoint:a,palmLandmarks:n.palmLandmarks}}Ci.shiftBox=W7});var KL=be(YL=>{const je=Ht(),U7=wp();class B7{constructor(n,t,e){this.model=n,this.width=e.inputSize,this.height=e.inputSize,this.anchors=t.map(i=>[i.x_center,i.y_center]),this.anchorsTensor=je.tensor2d(this.anchors),this.inputSizeTensor=je.tensor1d([e.inputSize,e.inputSize]),this.doubleInputSizeTensor=je.tensor1d([e.inputSize*2,e.inputSize*2])}normalizeBoxes(n){return je.tidy(()=>{const t=je.slice(n,[0,0],[-1,2]),e=je.slice(n,[0,2],[-1,2]),i=je.add(je.div(t,this.inputSizeTensor),this.anchorsTensor),r=je.div(e,this.doubleInputSizeTensor),a=je.mul(je.sub(i,r),this.inputSizeTensor),s=je.mul(je.add(i,r),this.inputSizeTensor);return je.concat2d([a,s],1)})}normalizeLandmarks(n,t){return je.tidy(()=>{const e=je.add(je.div(n.reshape([-1,7,2]),this.inputSizeTensor),this.anchors[t]);return je.mul(e,this.inputSizeTensor)})}async getBoundingBoxes(n){const t=this.model.predict(n),e=t.squeeze(),i=je.tidy(()=>je.sigmoid(je.slice(e,[0,0],[-1,1])).squeeze()),r=je.slice(e,[0,1],[-1,4]),a=this.normalizeBoxes(r),s=await je.image.nonMaxSuppressionAsync(a,i,this.maxHands,this.iouThreshold,this.scoreThreshold),o=await s.array(),l=[t,s,e,a,r,i],u=je.tidy(()=>{const c=[];for(const h in o){const d=o[h],p=je.slice(a,[d,0],[1,-1]),f=je.slice(e,[d,5],[1,14]),m=je.tidy(()=>this.normalizeLandmarks(f,d).reshape([-1,2]));c.push({boxes:p,palmLandmarks:m})}return c});return l.forEach(c=>c.dispose()),u}async estimateHandBounds(n,t){this.iouThreshold=t.iouThreshold,this.scoreThreshold=t.scoreThreshold,this.maxHands=t.maxHands;const e=n.resizeBilinear([this.width,this.height]),i=e.div(255),r=i.sub(.5),a=r.mul(2);e.dispose(),i.dispose(),r.dispose();const s=await this.getBoundingBoxes(a);if(a.dispose(),!s||s.length===0)return null;const o=[];for(const l in s){const u=s[l],c=await u.boxes.array(),h=c[0].slice(0,2),d=c[0].slice(2,4),p=await u.palmLandmarks.array();u.boxes.dispose(),u.palmLandmarks.dispose(),o.push(U7.scaleBoxCoordinates({startPoint:h,endPoint:d,palmLandmarks:p},[n.shape[2]/this.width,n.shape[1]/this.height]))}return o}}YL.HandDetector=B7});var $L=be(jL=>{jL.MESH_ANNOTATIONS={thumb:[1,2,3,4],indexFinger:[5,6,7,8],middleFinger:[9,10,11,12],ringFinger:[13,14,15,16],pinky:[17,18,19,20],palmBase:[0]}});var eI=be(Ri=>{function XL(n){return n-2*Math.PI*Math.floor((n+Math.PI)/(2*Math.PI))}Ri.normalizeRadians=XL;function z7(n,t){const e=Math.PI/2-Math.atan2(-(t[1]-n[1]),t[0]-n[0]);return XL(e)}Ri.computeRotation=z7;const JL=(n,t)=>[[1,0,n],[0,1,t],[0,0,1]];function aa(n,t){let e=0;for(let i=0;i{const nI=Ht(),Bn=wp(),Oi=eI(),H7=.8,V7=[0,-.4],q7=[0,-.1],G7=1.65,iI=[0,5,9,13,17,1,2],Y7=0,K7=2;class j7{constructor(n,t,e){this.regionsOfInterest=[],this.runsWithoutHandDetector=0,this.boundingBoxDetector=n,this.meshDetector=t,this.meshWidth=e.inputSize,this.meshHeight=e.inputSize,this.enlargeFactor=e.enlargeFactor}getBoxForPalmLandmarks(n,t){const e=n.map(r=>{const a=[...r,1];return Oi.rotatePoint(a,t)}),i=this.calculateLandmarksBoundingBox(e);return Bn.enlargeBox(Bn.squarifyBox(Bn.shiftBox(i,V7)),this.enlargeFactor)}getBoxForHandLandmarks(n){const t=this.calculateLandmarksBoundingBox(n),e=Bn.enlargeBox(Bn.squarifyBox(Bn.shiftBox(t,q7)),G7),i=[];for(let r=0;r[a[0]*(d[0]-this.meshWidth/2),a[1]*(d[1]-this.meshHeight/2),d[2]]),o=Oi.buildRotationMatrix(e,[0,0]),l=s.map(d=>{const p=Oi.rotatePoint(d,o);return[...p,d[2]]}),u=Oi.invertTransformMatrix(i),c=[...Bn.getBoxCenter(t),1],h=[Oi.dot(c,u[0]),Oi.dot(c,u[1])];return l.map(d=>[d[0]+h[0],d[1]+h[1],d[2]])}async estimateHands(n,t){this.skipFrames=t.skipFrames,this.detectionConfidence=t.minConfidence,this.maxHands=t.maxHands,this.runsWithoutHandDetector++;const e=this.shouldUpdateRegionsOfInterest();if(e===!0){const r=await this.boundingBoxDetector.estimateHandBounds(n,t);this.regionsOfInterest=[];for(const a in r)this.updateRegionsOfInterest(r[a],!0,a);this.runsWithoutHandDetector=0}const i=[];if(!this.regionsOfInterest)return i;for(const r in this.regionsOfInterest){const a=this.regionsOfInterest[r][0];if(!a)return i;const s=Oi.computeRotation(a.palmLandmarks[Y7],a.palmLandmarks[K7]),o=Bn.getBoxCenter(a),l=[o[0]/n.shape[2],o[1]/n.shape[1]],u=nI.image.rotateWithOffset(n,s,0,l),c=Oi.buildRotationMatrix(-s,o),h=e?this.getBoxForPalmLandmarks(a.palmLandmarks,c):a,d=Bn.cutBoxFromImageAndResize(h,u,[this.meshWidth,this.meshHeight]),p=d.div(255);d.dispose(),u.dispose();const f=this.meshDetector.predict(p),[m,g]=f;p.dispose();const v=m.dataSync()[0];if(m.dispose(),va[0]),e=n.map(a=>a[1]),i=[Math.min(...t),Math.min(...e)],r=[Math.max(...t),Math.max(...e)];return{startPoint:i,endPoint:r}}updateRegionsOfInterest(n,t,e){if(t)this.regionsOfInterest[e]=[n];else{const i=this.regionsOfInterest[e][0];let r=0;if(i!=null&&i.startPoint!=null){const[a,s]=n.startPoint,[o,l]=n.endPoint,[u,c]=i.startPoint,[h,d]=i.endPoint,p=Math.max(a,u),f=Math.max(s,c),m=Math.min(o,h),g=Math.min(l,d),v=(m-p)*(g-f),b=(o-a)*(l-s),S=(h-u)*(d-s);r=v/(b+S-v)}this.regionsOfInterest[e][0]=r>H7?i:n}}shouldUpdateRegionsOfInterest(){return!this.regionsOfInterest||this.regionsOfInterest.length===0||this.runsWithoutHandDetector>=this.skipFrames}}tI.HandPipeline=j7});var oI=be(Sp=>{const Go=Ht(),$7=KL(),aI=$L(),X7=rI();class sI{constructor(n){this.pipeline=n}async estimateHands(n,t){this.skipFrames=t.skipFrames,this.detectionConfidence=t.minConfidence,this.maxHands=t.maxHands;const e=await this.pipeline.estimateHands(n,t),i=[];if(!e)return i;for(const r of e){if(!r)return[];const a={};for(const s of Object.keys(aI.MESH_ANNOTATIONS))a[s]=aI.MESH_ANNOTATIONS[s].map(o=>r.landmarks[o]);i.push({confidence:r.confidence||0,box:r.box?[r.box.topLeft[0],r.box.topLeft[1],r.box.bottomRight[0]-r.box.topLeft[0],r.box.bottomRight[1]-r.box.topLeft[1]]:0,landmarks:r.landmarks,annotations:a})}return i}}Sp.HandPose=sI;async function J7(n){if(Go.env().features.IS_NODE){const t=require("fs"),e=await t.readFileSync(n.replace("file://",""));return JSON.parse(e)}return Go.util.fetch(n).then(t=>t.json())}async function Z7(n){const[t,e,i]=await Promise.all([J7(n.detector.anchors),Go.loadGraphModel(n.detector.modelPath,{fromTFHub:n.detector.modelPath.includes("tfhub.dev")}),Go.loadGraphModel(n.skeleton.modelPath,{fromTFHub:n.skeleton.modelPath.includes("tfhub.dev")})]),r=new $7.HandDetector(e,t,n),a=new X7.HandPipeline(r,i,n),s=new sI(a);return s}Sp.load=Z7});var uI=be(lI=>{const Q7=function(n,t,e){const i=function(o,l,u){const c=new RegExp("\\b"+l+" \\w+ (\\w+)","ig");o.replace(c,(h,d)=>(u[d]=0,h))},r=function(o,l,u){const c=o.createShader(u);if(o.shaderSource(c,l),o.compileShader(c),!o.getShaderParameter(c,o.COMPILE_STATUS))throw new Error("Filter: GL compile failed",o.getShaderInfoLog(c));return c};this.uniform={},this.attribute={};const a=r(n,t,n.VERTEX_SHADER),s=r(n,e,n.FRAGMENT_SHADER);if(this.id=n.createProgram(),n.attachShader(this.id,a),n.attachShader(this.id,s),n.linkProgram(this.id),!n.getProgramParameter(this.id,n.LINK_STATUS))throw new Error("Filter: GL link failed",n.getProgramInfoLog(this.id));n.useProgram(this.id),i(t,"attribute",this.attribute);for(const o in this.attribute)this.attribute[o]=n.getAttribLocation(this.id,o);i(t,"uniform",this.uniform),i(e,"uniform",this.uniform);for(const o in this.uniform)this.uniform[o]=n.getUniformLocation(this.id,o)},eH=function(n){n||(n={});let t=0,e=null,i=!1,r=-1,a=[null,null],s=[],o=-1,l=-1,u=null,c=null;const h=n.canvas||document.createElement("canvas"),d={},p=h.getContext("webgl")||h.getContext("experimental-webgl");if(!p)throw new Error("Filter: getContext() failed");this.addFilter=function(N){const I=Array.prototype.slice.call(arguments,1),C=w[N];s.push({func:C,args:I})},this.reset=function(){s=[]},this.apply=function(N){if(f(N.width,N.height),t=0,e||(e=p.createTexture()),p.bindTexture(p.TEXTURE_2D,e),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.NEAREST),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.NEAREST),p.texImage2D(p.TEXTURE_2D,0,p.RGBA,p.RGBA,p.UNSIGNED_BYTE,N),s.length===0){const I=b(L.FRAGMENT_IDENTITY);return v(),h}for(let I=0;I{Ap(eH,{default:()=>tH});var tH={backend:"webgl",console:!0,scoped:!1,videoOptimized:!0,filter:{enabled:!0,return:!0,brightness:0,contrast:0,sharpness:0,blur:0,saturation:0,hue:0,negative:!1,sepia:!1,vintage:!1,kodachrome:!1,technicolor:!1,polaroid:!1,pixelate:0},face:{enabled:!0,detector:{modelPath:"../models/blazeface/back/model.json",inputSize:256,maxFaces:10,skipFrames:10,minConfidence:.5,iouThreshold:.3,scoreThreshold:.7},mesh:{enabled:!0,modelPath:"../models/facemesh/model.json",inputSize:192},iris:{enabled:!0,modelPath:"../models/iris/model.json",enlargeFactor:2.3,inputSize:64},age:{enabled:!0,modelPath:"../models/ssrnet-age/imdb/model.json",inputSize:64,skipFrames:10},gender:{enabled:!0,minConfidence:.8,modelPath:"../models/ssrnet-gender/imdb/model.json"},emotion:{enabled:!0,inputSize:64,minConfidence:.5,skipFrames:10,modelPath:"../models/emotion/model.json"}},body:{enabled:!0,modelPath:"../models/posenet/model.json",inputResolution:257,outputStride:16,maxDetections:10,scoreThreshold:.7,nmsRadius:20},hand:{enabled:!0,inputSize:256,skipFrames:10,minConfidence:.5,iouThreshold:.3,scoreThreshold:.7,enlargeFactor:1.65,maxHands:10,detector:{anchors:"../models/handdetect/anchors.json",modelPath:"../models/handdetect/model.json"},skeleton:{modelPath:"../models/handskeleton/model.json"}}}});var dI=be((nV,hI)=>{hI.exports={name:"@vladmandic/human",version:"0.3.9",description:"human: 3D Face Detection, Iris Tracking and Age & Gender Prediction",sideEffects:!1,main:"dist/human.cjs",module:"dist/human.esm.js",browser:"dist/human.esm.js",author:"Vladimir Mandic ",bugs:{url:"https://github.com/vladmandic/human/issues"},homepage:"https://github.com/vladmandic/human#readme",license:"MIT",engines:{node:">=14.0.0"},repository:{type:"git",url:"git+https://github.com/vladmandic/human.git"},dependencies:{},peerDependencies:{},devDependencies:{"@vladmandic/pilogger":"^0.2.6",dayjs:"^1.9.3","simple-git":"^2.21.0","@tensorflow/tfjs":"^2.6.0","@tensorflow/tfjs-node":"^2.6.0",esbuild:"^0.7.15",eslint:"^7.10.0","eslint-config-airbnb-base":"^14.2.0","eslint-plugin-import":"^2.22.1","eslint-plugin-json":"^2.1.2","eslint-plugin-node":"^11.1.0","eslint-plugin-promise":"^4.2.1",rimraf:"^3.0.2"},scripts:{start:"node --trace-warnings --unhandled-rejections=strict --trace-uncaught --no-deprecation src/node.js",lint:"eslint src/*.js demo/*.js","build-iife":"esbuild --bundle --platform=browser --sourcemap --target=esnext --format=iife --minify --external:fs --global-name=human --metafile=dist/human.json --outfile=dist/human.js src/human.js","build-esm-bundle":"esbuild --bundle --platform=browser --sourcemap --target=esnext --format=esm --minify --external:fs --metafile=dist/human.esm.json --outfile=dist/human.esm.js src/human.js","build-esm-nobundle":"esbuild --bundle --platform=browser --sourcemap --target=esnext --format=esm --minify --external:@tensorflow --external:fs --metafile=dist/human.esm-nobundle.json --outfile=dist/human.esm-nobundle.js src/human.js","build-node":"esbuild --bundle --platform=node --sourcemap --target=esnext --format=cjs --external:@tensorflow --metafile=dist/human.cjs.json --outfile=dist/human.cjs src/human.js",build:"rimraf dist/* && npm run build-iife && npm run build-esm-bundle && npm run build-esm-nobundle && npm run build-node && ls -l dist/",update:"npm update --depth 20 && npm dedupe && npm prune && npm audit",changelog:"node changelog.js"},keywords:["tensorflowjs","face-detection","face-geometry","body-tracking","hand-tracking","iris-tracking","age-estimation","emotion-detection","gender-prediction","gesture-recognition"]}});const Ft=Ht(),pI=fL(),Yo=gL(),Lp=bL(),fI=GL(),mI=oI(),nH=uI(),Ko=cI().default,iH=dI(),rH={face:{detector:{skipFrames:0},age:{skipFrames:0},emotion:{skipFrames:0}},hand:{skipFrames:0}},ut=()=>typeof performance!="undefined"?performance.now():parseInt(Number(process.hrtime.bigint())/1e3/1e3);function jo(...n){const t=e=>e&&typeof e=="object";return n.reduce((e,i)=>(Object.keys(i||{}).forEach(r=>{const a=e[r],s=i[r];Array.isArray(a)&&Array.isArray(s)?e[r]=a.concat(...s):t(a)&&t(s)?e[r]=jo(a,s):e[r]=s}),e),{})}function aH(n){if(!n)return"input is not defined";if(Ft.ENV.flags.IS_NODE&&!(n instanceof Ft.Tensor))return"input must be a tensor";try{Ft.getBackend()}catch{return"backend not loaded"}return null}class sH{constructor(){this.tf=Ft,this.version=iH.version,this.defaults=Ko,this.config=Ko,this.fx=Ft.ENV.flags.IS_BROWSER&&typeof document!="undefined"?new nH.Canvas:null,this.state="idle",this.numTensors=0,this.analyzeMemoryLeaks=!1,this.models={facemesh:null,posenet:null,handpose:null,iris:null,age:null,gender:null,emotion:null},this.facemesh=pI,this.ssrnet=Yo,this.emotion=Lp,this.posenet=fI,this.handpose=mI}log(...n){n&&this.config.console&&console.log(...n)}analyze(...n){if(!this.analyzeMemoryLeaks)return;const t=Ft.engine().state.numTensors,e=this.numTensors;this.numTensors=t;const i=t-e;i!==0&&this.log(...n,i)}async load(n){n&&(this.config=jo(Ko,n)),this.config.face.enabled&&!this.models.facemesh&&(this.log("Load model: Face"),this.models.facemesh=await pI.load(this.config.face)),this.config.body.enabled&&!this.models.posenet&&(this.log("Load model: Body"),this.models.posenet=await fI.load(this.config.body)),this.config.hand.enabled&&!this.models.handpose&&(this.log("Load model: Hand"),this.models.handpose=await mI.load(this.config.hand)),this.config.face.enabled&&this.config.face.age.enabled&&!this.models.age&&(this.log("Load model: Age"),this.models.age=await Yo.loadAge(this.config)),this.config.face.enabled&&this.config.face.gender.enabled&&!this.models.gender&&(this.log("Load model: Gender"),this.models.gender=await Yo.loadGender(this.config)),this.config.face.enabled&&this.config.face.emotion.enabled&&!this.models.emotion&&(this.log("Load model: Emotion"),this.models.emotion=await Lp.load(this.config))}tfImage(n){let t;if(this.fx&&this.config.filter.enabled&&!(n instanceof Ft.Tensor)){const i=n.naturalWidth||n.videoWidth||n.width||n.shape&&n.shape[1]>0,r=n.naturalHeight||n.videoHeight||n.height||n.shape&&n.shape[2]>0,a=new OffscreenCanvas(i,r),s=a.getContext("2d");n instanceof ImageData?s.putImageData(n,0,0):s.drawImage(n,0,0,i,r,0,0,a.width,a.height),this.fx.reset(),this.fx.addFilter("brightness",this.config.filter.brightness),this.config.filter.contrast!==0&&this.fx.addFilter("contrast",this.config.filter.contrast),this.config.filter.sharpness!==0&&this.fx.addFilter("sharpen",this.config.filter.sharpness),this.config.filter.blur!==0&&this.fx.addFilter("blur",this.config.filter.blur),this.config.filter.saturation!==0&&this.fx.addFilter("saturation",this.config.filter.saturation),this.config.filter.hue!==0&&this.fx.addFilter("hue",this.config.filter.hue),this.config.filter.negative&&this.fx.addFilter("negative"),this.config.filter.sepia&&this.fx.addFilter("sepia"),this.config.filter.vintage&&this.fx.addFilter("brownie"),this.config.filter.sepia&&this.fx.addFilter("sepia"),this.config.filter.kodachrome&&this.fx.addFilter("kodachrome"),this.config.filter.technicolor&&this.fx.addFilter("technicolor"),this.config.filter.polaroid&&this.fx.addFilter("polaroid"),this.config.filter.pixelate!==0&&this.fx.addFilter("pixelate",this.config.filter.pixelate),t=this.fx.apply(a)}let e;if(n instanceof Ft.Tensor)e=Ft.clone(n);else{const i=Ft.browser.fromPixels(t||n),r=i.toFloat();e=r.expandDims(0),i.dispose(),r.dispose()}return{tensor:e,canvas:this.config.filter.return?t:null}}async detect(n,t={}){this.state="config";const e={};let i;i=ut(),this.config=jo(Ko,t),this.config.videoOptimized||(this.config=jo(this.config,rH)),e.config=Math.trunc(ut()-i),i=ut(),this.state="check";const r=aH(n);return r?(this.log(r,n),{error:r}):(e.sanity=Math.trunc(ut()-i),new Promise(async a=>{const s=ut();i=ut(),Ft.getBackend()!==this.config.backend&&(this.state="backend",this.log("Human library setting backend:",this.config.backend),await Ft.setBackend(this.config.backend),await Ft.ready()),e.backend=Math.trunc(ut()-i);const o=Object.values(this.models).filter(p=>p).length;o===0&&(this.log("Human library starting"),this.log("Configuration:",this.config),this.log("Flags:",Ft.ENV.flags)),i=ut(),this.state="load",await this.load(),e.load=Math.trunc(ut()-i),this.config.scoped&&Ft.engine().startScope(),this.analyze("Start Detect:"),i=ut();const l=this.tfImage(n);e.image=Math.trunc(ut()-i);const u=l.tensor;this.state="run:body",i=ut(),this.analyze("Start PoseNet");const c=this.config.body.enabled?await this.models.posenet.estimatePoses(u,this.config.body):[];this.analyze("End PoseNet:"),e.body=Math.trunc(ut()-i),this.state="run:hand",i=ut(),this.analyze("Start HandPose:");const h=this.config.hand.enabled?await this.models.handpose.estimateHands(u,this.config.hand):[];this.analyze("End HandPose:"),e.hand=Math.trunc(ut()-i);const d=[];if(this.config.face.enabled){this.state="run:face",i=ut(),this.analyze("Start FaceMesh:");const p=await this.models.facemesh.estimateFaces(u,this.config.face);e.face=Math.trunc(ut()-i);for(const f of p){if(!f.image||f.image.isDisposedInternal){this.log("face object is disposed:",f.image);continue}this.state="run:agegender",i=ut();const m=this.config.face.age.enabled||this.config.face.gender.enabled?await Yo.predict(f.image,this.config):{};e.agegender=Math.trunc(ut()-i),this.state="run:emotion",i=ut();const g=this.config.face.emotion.enabled?await Lp.predict(f.image,this.config):{};e.emotion=Math.trunc(ut()-i),f.image.dispose();const v=f.annotations.leftEyeIris&&f.annotations.rightEyeIris?Math.max(f.annotations.leftEyeIris[3][0]-f.annotations.leftEyeIris[1][0],f.annotations.rightEyeIris[3][0]-f.annotations.rightEyeIris[1][0]):0;d.push({confidence:f.confidence,box:f.box,mesh:f.mesh,annotations:f.annotations,age:m.age,gender:m.gender,agConfidence:m.confidence,emotion:g,iris:v!==0?Math.trunc(100*11.7/v)/100:0}),this.analyze("End FaceMesh:")}}u.dispose(),this.state="idle",this.config.scoped&&Ft.engine().endScope(),this.analyze("End Scope:"),e.total=Math.trunc(ut()-s),a({face:d,body:c,hand:h,performance:e,canvas:l.canvas})}))}}export{sH as default}; +`)};lI.Canvas=eH});var cI=be(tH=>{Ap(tH,{default:()=>nH});var nH={backend:"webgl",console:!0,scoped:!1,videoOptimized:!0,filter:{enabled:!0,return:!0,brightness:0,contrast:0,sharpness:0,blur:0,saturation:0,hue:0,negative:!1,sepia:!1,vintage:!1,kodachrome:!1,technicolor:!1,polaroid:!1,pixelate:0},face:{enabled:!0,detector:{modelPath:"../models/blazeface/back/model.json",inputSize:256,maxFaces:10,skipFrames:10,minConfidence:.5,iouThreshold:.3,scoreThreshold:.7},mesh:{enabled:!0,modelPath:"../models/facemesh/model.json",inputSize:192},iris:{enabled:!0,modelPath:"../models/iris/model.json",enlargeFactor:2.3,inputSize:64},age:{enabled:!0,modelPath:"../models/ssrnet-age/imdb/model.json",inputSize:64,skipFrames:10},gender:{enabled:!0,minConfidence:.8,modelPath:"../models/ssrnet-gender/imdb/model.json"},emotion:{enabled:!0,inputSize:64,minConfidence:.5,skipFrames:10,modelPath:"../models/emotion/model.json"}},body:{enabled:!0,modelPath:"../models/posenet/model.json",inputResolution:257,outputStride:16,maxDetections:10,scoreThreshold:.7,nmsRadius:20},hand:{enabled:!0,inputSize:256,skipFrames:10,minConfidence:.5,iouThreshold:.3,scoreThreshold:.7,enlargeFactor:1.65,maxHands:10,detector:{anchors:"../models/handdetect/anchors.json",modelPath:"../models/handdetect/model.json"},skeleton:{modelPath:"../models/handskeleton/model.json"}}}});var dI=be((iV,hI)=>{hI.exports={name:"@vladmandic/human",version:"0.4.1",description:"human: 3D Face Detection, Iris Tracking and Age & Gender Prediction",sideEffects:!1,main:"dist/human.cjs",module:"dist/human.esm.js",browser:"dist/human.esm.js",author:"Vladimir Mandic ",bugs:{url:"https://github.com/vladmandic/human/issues"},homepage:"https://github.com/vladmandic/human#readme",license:"MIT",engines:{node:">=14.0.0"},repository:{type:"git",url:"git+https://github.com/vladmandic/human.git"},dependencies:{},peerDependencies:{},devDependencies:{"@vladmandic/pilogger":"^0.2.6",dayjs:"^1.9.3","simple-git":"^2.21.0","@tensorflow/tfjs":"^2.6.0","@tensorflow/tfjs-node":"^2.6.0",esbuild:"^0.7.15",eslint:"^7.10.0","eslint-config-airbnb-base":"^14.2.0","eslint-plugin-import":"^2.22.1","eslint-plugin-json":"^2.1.2","eslint-plugin-node":"^11.1.0","eslint-plugin-promise":"^4.2.1",rimraf:"^3.0.2"},scripts:{start:"node --trace-warnings --unhandled-rejections=strict --trace-uncaught --no-deprecation src/node.js",lint:"eslint src/*.js demo/*.js","build-iife":"esbuild --bundle --platform=browser --sourcemap --target=esnext --format=iife --minify --external:fs --global-name=Human --metafile=dist/human.json --outfile=dist/human.js src/human.js","build-esm-bundle":"esbuild --bundle --platform=browser --sourcemap --target=esnext --format=esm --minify --external:fs --metafile=dist/human.esm.json --outfile=dist/human.esm.js src/human.js","build-esm-nobundle":"esbuild --bundle --platform=browser --sourcemap --target=esnext --format=esm --minify --external:@tensorflow --external:fs --metafile=dist/human.esm-nobundle.json --outfile=dist/human.esm-nobundle.js src/human.js","build-node":"esbuild --bundle --platform=node --sourcemap --target=esnext --format=cjs --external:@tensorflow --metafile=dist/human.cjs.json --outfile=dist/human.cjs src/human.js",build:"rimraf dist/* && npm run build-iife && npm run build-esm-bundle && npm run build-esm-nobundle && npm run build-node && ls -l dist/",update:"npm update --depth 20 && npm dedupe && npm prune && npm audit",changelog:"node changelog.js"},keywords:["tensorflowjs","face-detection","face-geometry","body-tracking","hand-tracking","iris-tracking","age-estimation","emotion-detection","gender-prediction","gesture-recognition"]}});const Ft=Ht(),pI=fL(),Yo=gL(),Lp=bL(),fI=GL(),mI=oI(),iH=uI(),Ko=cI().default,rH=dI();let gI=!0;const aH={face:{detector:{skipFrames:0},age:{skipFrames:0},emotion:{skipFrames:0}},hand:{skipFrames:0}},ut=()=>typeof performance!="undefined"?performance.now():parseInt(Number(process.hrtime.bigint())/1e3/1e3);function jo(...n){const t=e=>e&&typeof e=="object";return n.reduce((e,i)=>(Object.keys(i||{}).forEach(r=>{const a=e[r],s=i[r];Array.isArray(a)&&Array.isArray(s)?e[r]=a.concat(...s):t(a)&&t(s)?e[r]=jo(a,s):e[r]=s}),e),{})}function sH(n){if(!n)return"input is not defined";if(Ft.ENV.flags.IS_NODE&&!(n instanceof Ft.Tensor))return"input must be a tensor";try{Ft.getBackend()}catch{return"backend not loaded"}return null}class oH{constructor(){this.tf=Ft,this.version=rH.version,this.defaults=Ko,this.config=Ko,this.fx=Ft.ENV.flags.IS_BROWSER&&typeof document!="undefined"?new iH.Canvas:null,this.state="idle",this.numTensors=0,this.analyzeMemoryLeaks=!1,this.models={facemesh:null,posenet:null,handpose:null,iris:null,age:null,gender:null,emotion:null},this.facemesh=pI,this.ssrnet=Yo,this.emotion=Lp,this.posenet=fI,this.handpose=mI}log(...n){n&&this.config.console&&console.log(...n)}analyze(...n){if(!this.analyzeMemoryLeaks)return;const t=Ft.engine().state.numTensors,e=this.numTensors;this.numTensors=t;const i=t-e;i!==0&&this.log(...n,i)}async load(n){n&&(this.config=jo(Ko,n)),this.config.face.enabled&&!this.models.facemesh&&(this.log("Load model: Face"),this.models.facemesh=await pI.load(this.config.face)),this.config.body.enabled&&!this.models.posenet&&(this.log("Load model: Body"),this.models.posenet=await fI.load(this.config.body)),this.config.hand.enabled&&!this.models.handpose&&(this.log("Load model: Hand"),this.models.handpose=await mI.load(this.config.hand)),this.config.face.enabled&&this.config.face.age.enabled&&!this.models.age&&(this.log("Load model: Age"),this.models.age=await Yo.loadAge(this.config)),this.config.face.enabled&&this.config.face.gender.enabled&&!this.models.gender&&(this.log("Load model: Gender"),this.models.gender=await Yo.loadGender(this.config)),this.config.face.enabled&&this.config.face.emotion.enabled&&!this.models.emotion&&(this.log("Load model: Emotion"),this.models.emotion=await Lp.load(this.config))}tfImage(n){let t;if(this.fx&&this.config.filter.enabled&&!(n instanceof Ft.Tensor)){const i=n.naturalWidth||n.videoWidth||n.width||n.shape&&n.shape[1]>0,r=n.naturalHeight||n.videoHeight||n.height||n.shape&&n.shape[2]>0,a=new OffscreenCanvas(i,r),s=a.getContext("2d");n instanceof ImageData?s.putImageData(n,0,0):s.drawImage(n,0,0,i,r,0,0,a.width,a.height),this.fx.reset(),this.fx.addFilter("brightness",this.config.filter.brightness),this.config.filter.contrast!==0&&this.fx.addFilter("contrast",this.config.filter.contrast),this.config.filter.sharpness!==0&&this.fx.addFilter("sharpen",this.config.filter.sharpness),this.config.filter.blur!==0&&this.fx.addFilter("blur",this.config.filter.blur),this.config.filter.saturation!==0&&this.fx.addFilter("saturation",this.config.filter.saturation),this.config.filter.hue!==0&&this.fx.addFilter("hue",this.config.filter.hue),this.config.filter.negative&&this.fx.addFilter("negative"),this.config.filter.sepia&&this.fx.addFilter("sepia"),this.config.filter.vintage&&this.fx.addFilter("brownie"),this.config.filter.sepia&&this.fx.addFilter("sepia"),this.config.filter.kodachrome&&this.fx.addFilter("kodachrome"),this.config.filter.technicolor&&this.fx.addFilter("technicolor"),this.config.filter.polaroid&&this.fx.addFilter("polaroid"),this.config.filter.pixelate!==0&&this.fx.addFilter("pixelate",this.config.filter.pixelate),t=this.fx.apply(a)}let e;if(n instanceof Ft.Tensor)e=Ft.clone(n);else{const i=Ft.browser.fromPixels(t||n),r=i.toFloat();e=r.expandDims(0),i.dispose(),r.dispose()}return{tensor:e,canvas:this.config.filter.return?t:null}}async detect(n,t={}){this.state="config";const e={};let i;i=ut(),this.config=jo(Ko,t),this.config.videoOptimized||(this.config=jo(this.config,aH)),e.config=Math.trunc(ut()-i),i=ut(),this.state="check";const r=sH(n);return r?(this.log(r,n),{error:r}):(e.sanity=Math.trunc(ut()-i),new Promise(async a=>{const s=ut();i=ut(),Ft.getBackend()!==this.config.backend&&(this.state="backend",this.log("Human library setting backend:",this.config.backend),await Ft.setBackend(this.config.backend),await Ft.ready()),e.backend=Math.trunc(ut()-i),gI&&(this.log("Human library starting"),this.log("Configuration:",this.config),this.log("Flags:",Ft.ENV.flags),gI=!1),i=ut(),this.state="load",await this.load(),e.load=Math.trunc(ut()-i),this.config.scoped&&Ft.engine().startScope(),this.analyze("Start Detect:"),i=ut();const o=this.tfImage(n);e.image=Math.trunc(ut()-i);const l=o.tensor;this.state="run:body",i=ut(),this.analyze("Start PoseNet");const u=this.config.body.enabled?await this.models.posenet.estimatePoses(l,this.config.body):[];this.analyze("End PoseNet:"),e.body=Math.trunc(ut()-i),this.state="run:hand",i=ut(),this.analyze("Start HandPose:");const c=this.config.hand.enabled?await this.models.handpose.estimateHands(l,this.config.hand):[];this.analyze("End HandPose:"),e.hand=Math.trunc(ut()-i);const h=[];if(this.config.face.enabled){this.state="run:face",i=ut(),this.analyze("Start FaceMesh:");const d=await this.models.facemesh.estimateFaces(l,this.config.face);e.face=Math.trunc(ut()-i);for(const p of d){if(!p.image||p.image.isDisposedInternal){this.log("face object is disposed:",p.image);continue}this.state="run:agegender",i=ut();const f=this.config.face.age.enabled||this.config.face.gender.enabled?await Yo.predict(p.image,this.config):{};e.agegender=Math.trunc(ut()-i),this.state="run:emotion",i=ut();const m=this.config.face.emotion.enabled?await Lp.predict(p.image,this.config):{};e.emotion=Math.trunc(ut()-i),p.image.dispose();const g=p.annotations.leftEyeIris&&p.annotations.rightEyeIris?Math.max(p.annotations.leftEyeIris[3][0]-p.annotations.leftEyeIris[1][0],p.annotations.rightEyeIris[3][0]-p.annotations.rightEyeIris[1][0]):0;h.push({confidence:p.confidence,box:p.box,mesh:p.mesh,annotations:p.annotations,age:f.age,gender:f.gender,agConfidence:f.confidence,emotion:m,iris:g!==0?Math.trunc(100*11.7/g)/100:0}),this.analyze("End FaceMesh:")}}l.dispose(),this.state="idle",this.config.scoped&&Ft.engine().endScope(),this.analyze("End Scope:"),e.total=Math.trunc(ut()-s),a({face:h,body:u,hand:c,performance:e,canvas:o.canvas})}))}}export{oH as default}; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use diff --git a/dist/human.esm.js.map b/dist/human.esm.js.map index f184f530..cea2e2d3 100644 --- a/dist/human.esm.js.map +++ b/dist/human.esm.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["empty:/home/vlado/dev/human/node_modules/node-fetch/browser.js", "empty:util", "empty:crypto", "../node_modules/@tensorflow/tfjs-core/src/backends/backend.ts", "../node_modules/@tensorflow/tfjs-core/src/environment.ts", "../node_modules/@tensorflow/tfjs-core/src/global_util.ts", "../node_modules/@tensorflow/tfjs-core/src/kernel_names.ts", "../node_modules/@tensorflow/tfjs-core/src/kernel_registry.ts", "../node_modules/@tensorflow/tfjs-core/src/util.ts", "../node_modules/@tensorflow/tfjs-core/src/profiler.ts", "../node_modules/@tensorflow/tfjs-core/src/tape.ts", "../node_modules/@tensorflow/tfjs-core/src/tensor_format.ts", "../node_modules/@tensorflow/tfjs-core/src/tensor.ts", "../node_modules/@tensorflow/tfjs-core/src/types.ts", "../node_modules/@tensorflow/tfjs-core/src/tensor_util.ts", "../node_modules/@tensorflow/tfjs-core/src/engine.ts", "../node_modules/@tensorflow/tfjs-core/src/device_util.ts", "../node_modules/@tensorflow/tfjs-core/src/flags.ts", "../node_modules/@tensorflow/tfjs-core/src/tensor_util_env.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/operation.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/complex.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/tensor_ops_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/tensor.ts", "../node_modules/@tensorflow/tfjs-core/src/io/types.ts", "../node_modules/@tensorflow/tfjs-core/src/io/io_utils.ts", "../node_modules/@tensorflow/tfjs-core/src/io/router_registry.ts", "../node_modules/@tensorflow/tfjs-core/src/io/indexed_db.ts", "../node_modules/@tensorflow/tfjs-core/src/io/local_storage.ts", "../node_modules/@tensorflow/tfjs-core/src/io/model_management.ts", "../node_modules/@tensorflow/tfjs-core/src/platforms/platform_browser.ts", "../node_modules/@tensorflow/tfjs-core/src/platforms/platform_node.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/buffer.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/cast.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/clone.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/print.ts", "../node_modules/@tensorflow/tfjs-core/src/base_side_effects.ts", "../node_modules/@tensorflow/tfjs-core/src/io/browser_files.ts", "../node_modules/@tensorflow/tfjs-core/src/io/progress.ts", "../node_modules/@tensorflow/tfjs-core/src/io/weights_loader.ts", "../node_modules/@tensorflow/tfjs-core/src/io/http.ts", "../node_modules/@tensorflow/tfjs-core/src/io/passthrough.ts", "../node_modules/@tensorflow/tfjs-core/src/io/io.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/reshape.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/mat_mul.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/one_hot.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/transpose.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/confusion_matrix.ts", "../node_modules/@tensorflow/tfjs-core/src/math.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/tensor3d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/browser.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/gather_nd_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/scatter_nd_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/slice_util.ts", "../node_modules/@tensorflow/tfjs-core/src/serialization.ts", "../node_modules/@tensorflow/tfjs-core/src/test_util.ts", "../node_modules/@tensorflow/tfjs-core/src/version.ts", "../node_modules/@tensorflow/tfjs-core/src/globals.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/add.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/floorDiv.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/div.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/mul.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/abs.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/acos.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/acosh.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/add_n.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/axis_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/all.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/any.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/arg_max.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/arg_min.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/asin.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/asinh.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/atan.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/atan2.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/atanh.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/conv_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/avg_pool.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/avg_pool_3d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/concat_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/concat.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/sigmoid.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/slice.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/tanh.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/basic_lstm_cell.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/batch_to_space_nd.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/batchnorm_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/batchnorm.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/batchnorm2d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/batchnorm3d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/batchnorm4d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/broadcast_to.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/ceil.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/clip_by_value.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/concat_1d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/concat_2d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/concat_3d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/concat_4d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/conv2d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/conv1d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/conv2d_backprop_input.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/conv2d_transpose.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/conv3d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/conv3d_backprop_input.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/conv3d_transpose.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/cos.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/cosh.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/cumsum.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/depth_to_space.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/depthwise_conv2d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/diag.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/dilation2d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/broadcast_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/equal.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/where.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/zeros_like.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/div_no_nan.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/dot.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/elu.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/erf.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/exp.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/expand_dims.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/expm1.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/tile.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/eye.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/fill.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/floor.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/reduce_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/segment_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/gather.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/greater.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/greater_equal.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/imag.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/is_finite.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/is_inf.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/is_nan.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/maximum.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/scalar.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/leaky_relu.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/less.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/less_equal.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/linspace.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/local_response_normalization.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/log.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/log1p.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/neg.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/softplus.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/log_sigmoid.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/max.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/sub.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/sum.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/log_softmax.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/log_sum_exp.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/logical_and.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/logical_not.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/logical_or.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/logical_xor.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/max_pool.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/max_pool_3d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/max_pool_with_argmax.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/zeros.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/ones.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/mean.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/min.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/minimum.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/mod.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/square.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/moments.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/multi_rnn_cell.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/multinomial.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/not_equal.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/real.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/ones_like.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/outer_product.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/pad.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/pad1d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/pad2d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/pad3d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/pad4d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/space_to_batch_nd.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/pool.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/pow.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/prelu.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/prod.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/rand.ts", "../node_modules/@tensorflow/tfjs-core/node_modules/seedrandom/lib/alea.js", "../node_modules/@tensorflow/tfjs-core/node_modules/seedrandom/lib/xor128.js", "../node_modules/@tensorflow/tfjs-core/node_modules/seedrandom/lib/xorwow.js", "../node_modules/@tensorflow/tfjs-core/node_modules/seedrandom/lib/xorshift7.js", "../node_modules/@tensorflow/tfjs-core/node_modules/seedrandom/lib/xor4096.js", "../node_modules/@tensorflow/tfjs-core/node_modules/seedrandom/lib/tychei.js", "../node_modules/@tensorflow/tfjs-core/node_modules/seedrandom/seedrandom.js", "../node_modules/@tensorflow/tfjs-core/node_modules/seedrandom/index.js", "../node_modules/@tensorflow/tfjs-core/src/ops/rand_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/random_gamma.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/random_normal.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/random_uniform.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/tensor1d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/range.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/reciprocal.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/relu.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/relu6.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/reverse.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/reverse_1d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/reverse_2d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/reverse_3d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/reverse_4d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/round.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/rsqrt.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/selu.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/separable_conv2d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/setdiff1d_async.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/sign.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/sin.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/sinh.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/slice1d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/slice2d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/slice3d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/slice4d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/softmax.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/spectral/fft.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/spectral/ifft.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/spectral/irfft.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/split_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/split.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/spectral/rfft.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/sqrt.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/squared_difference.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/squeeze.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/stack.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/step.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/strided_slice.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/tan.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/tensor2d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/tensor4d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/tensor5d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/tensor6d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/topk.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/truncated_normal.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/unique.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/unsorted_segment_sum.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/unstack.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/variable.ts", "../node_modules/@tensorflow/tfjs-core/src/backends/where_impl.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/where_async.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/boolean_mask.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/compare.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/binary_ops.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/norm.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/moving_average.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/scatter_nd.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/sparse_to_dense_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/sparse_to_dense.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/gather_nd.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/dropout_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/dropout.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/signal_ops_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/in_top_k.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/conv2d_backprop_filter.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/fused_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/fused/conv2d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/depthwise_conv2d_native_backprop_filter.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/depthwise_conv2d_native_backprop_input.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/fused/depthwise_conv2d.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/fused/mat_mul.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/fused_ops.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/signal/hamming_window.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/signal/hann_window.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/signal/frame.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/signal/stft.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/image/crop_and_resize.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/image/flip_left_right.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/image/rotate_with_offset.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/nonmax_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/image/non_max_suppression.ts", "../node_modules/@tensorflow/tfjs-core/src/backends/array_util.ts", "../node_modules/@tensorflow/tfjs-core/src/backends/non_max_suppression_impl.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/image/non_max_suppression_async.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/image/non_max_suppression_with_score.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/image/non_max_suppression_with_score_async.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/image/non_max_suppression_padded.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/image/non_max_suppression_padded_async.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/image/resize_bilinear.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/image/resize_nearest_neighbor.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/linalg/band_part.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/linalg/gram_schmidt.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/linalg/qr.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/loss_ops_utils.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/losses/compute_weighted_loss.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/losses/absolute_difference.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/losses/cosine_distance.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/losses/hinge_loss.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/losses/huber_loss.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/losses/log_loss.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/losses/mean_squared_error.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/losses/sigmoid_cross_entropy.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/losses/softmax_cross_entropy.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/ops.ts", "../node_modules/@tensorflow/tfjs-core/src/optimizers/optimizer.ts", "../node_modules/@tensorflow/tfjs-core/src/optimizers/adadelta_optimizer.ts", "../node_modules/@tensorflow/tfjs-core/src/optimizers/adagrad_optimizer.ts", "../node_modules/@tensorflow/tfjs-core/src/optimizers/adam_optimizer.ts", "../node_modules/@tensorflow/tfjs-core/src/optimizers/adamax_optimizer.ts", "../node_modules/@tensorflow/tfjs-core/src/optimizers/sgd_optimizer.ts", "../node_modules/@tensorflow/tfjs-core/src/optimizers/momentum_optimizer.ts", "../node_modules/@tensorflow/tfjs-core/src/optimizers/rmsprop_optimizer.ts", "../node_modules/@tensorflow/tfjs-core/src/optimizers/optimizer_constructors.ts", "../node_modules/@tensorflow/tfjs-core/src/train.ts", "../node_modules/@tensorflow/tfjs-core/src/browser_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/rotate_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/array_ops_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/selu_util.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/erf_util.ts", "../node_modules/@tensorflow/tfjs-core/src/log.ts", "../node_modules/@tensorflow/tfjs-core/src/backends/complex_util.ts", "../node_modules/@tensorflow/tfjs-core/src/backends/backend_util.ts", "../node_modules/@tensorflow/tfjs-core/src/backends/split_shared.ts", "../node_modules/@tensorflow/tfjs-core/src/backends/tile_impl.ts", "../node_modules/@tensorflow/tfjs-core/src/backends/topk_impl.ts", "../node_modules/@tensorflow/tfjs-core/src/backends/kernel_impls.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Abs_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Acos_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Acosh_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Add_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/AddN_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/ArgMax_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/ArgMin_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Asin_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Asinh_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Atan2_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Atan_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Atanh_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/avg_pool_3d_backprop.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/AvgPool3D_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/avg_pool_backprop.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/AvgPool_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/BatchMatMul_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/BatchToSpaceND_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/BroadcastTo_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Cast_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Ceil_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/ClipByValue_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Concat_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Conv2D_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Conv2DBackpropInput_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/conv3d_backprop_filter.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Conv3D_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Cos_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Cosh_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Cumsum_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/DepthwiseConv2dNative_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Dilation2D_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Div_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Elu_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Erf_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Exp_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Expm1_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Floor_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/FloorDiv_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/FusedBatchNorm_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/GatherV2_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/GreaterEqual_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Identity_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/IsFinite_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/IsInf_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/IsNan_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Log1p_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Log_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/LogSoftmax_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/local_response_normalization_backprop.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/LRN_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/min_max_grad_util.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Max_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Maximum_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/max_pool_3d_backprop.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/MaxPool3D_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/ops/max_pool_backprop.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/MaxPool_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Min_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Minimum_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Mod_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Multiply_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Negate_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/OneHot_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/OnesLike_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/PadV2_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Pow_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Prelu_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Reciprocal_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Relu6_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Relu_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Reshape_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/ResizeBilinear_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/ResizeNearestNeighbor_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Reverse_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Round_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Rsqrt_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/SelectV2_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Selu_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Sigmoid_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Sign_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Sin_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Sinh_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Slice_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Softmax_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Softplus_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/SpaceToBatchND_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/SplitV_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Sqrt_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Square_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/SquaredDifference_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Step_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Sub_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Sum_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Tan_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Tanh_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Tile_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Transpose_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/Unpack_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/UnsortedSegmentSum_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/gradients/ZerosLike_grad.ts", "../node_modules/@tensorflow/tfjs-core/src/register_all_gradients.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/abs.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/acos.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/acosh.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/add_strict.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/add.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/all.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/any.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/arg_max.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/arg_min.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/as_scalar.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/as_type.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/as1d.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/as2d.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/as3d.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/as4d.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/as5d.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/asin.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/asinh.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/atan.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/atan2.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/atanh.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/avg_pool.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/batch_to_space_nd.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/batchnorm.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/broadcast_to.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/cast.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/ceil.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/clip_by_value.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/concat.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/conv1d.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/conv2d_transpose.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/conv2d.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/cos.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/cosh.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/cumsum.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/depth_to_space.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/depthwise_conv2D_deprecated.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/depthwise_conv2d.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/dilation2d.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/div_no_nan.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/div_strict.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/div.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/dot.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/elu.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/equal_strict.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/equal.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/erf.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/exp.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/expand_dims.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/expm1.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/fft.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/flatten.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/floor.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/floorDiv.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/gather.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/greater_equal_strict.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/greater_equal.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/greater_strict.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/greater.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/ifft.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/irfft.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/is_finite.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/is_inf.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/is_nan.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/leaky_relu.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/less_equal_strict.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/less_equal.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/less_strict.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/less.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/local_response_normalization.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/log_sigmoid.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/log_softmax.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/log_sum_exp.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/log.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/log1p.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/logical_and.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/logical_not.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/logical_or.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/logical_xor.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/mat_mul.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/max_pool.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/max.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/maximum_strict.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/maximum.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/mean.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/min.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/minimum_strict.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/minimum.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/mod_strict.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/mod.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/mul_strict.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/mul.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/neg.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/norm.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/not_equal_strict.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/not_equal.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/one_hot.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/ones_like.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/pad.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/pool.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/pow_strict.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/pow.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/prelu.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/prod.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/reciprocal.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/relu.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/relu6.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/reshape_as.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/reshape.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/resize_bilinear.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/resize_nearest_neighbor.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/reverse.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/rfft.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/round.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/rsqrt.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/selu.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/separable_conv2d.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/sigmoid.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/sign.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/sin.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/sinh.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/slice.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/softmax.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/softplus.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/space_to_batch_nd.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/split.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/sqrt.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/square.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/squared_difference.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/squared_difference_strict.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/squeeze.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/stack.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/step.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/strided_slice.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/sub_strict.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/sub.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/sum.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/tan.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/tanh.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/tile.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/to_bool.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/to_float.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/to_int.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/topk.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/transpose.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/unique.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/unsorted_segment_sum.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/unstack.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/where.ts", "../node_modules/@tensorflow/tfjs-core/src/public/chained_ops/zeros_like.ts", "../node_modules/@tensorflow/tfjs-layers/src/backend/common.ts", "../node_modules/@tensorflow/tfjs-layers/src/errors.ts", "../node_modules/@tensorflow/tfjs-layers/src/utils/generic_utils.ts", "../node_modules/@tensorflow/tfjs-layers/src/constraints.ts", "../node_modules/@tensorflow/tfjs-layers/src/exports_constraints.ts", "../node_modules/@tensorflow/tfjs-layers/src/keras_format/common.ts", "../node_modules/@tensorflow/tfjs-layers/src/common.ts", "../node_modules/@tensorflow/tfjs-layers/src/utils/math_utils.ts", "../node_modules/@tensorflow/tfjs-layers/src/backend/tfjs_backend.ts", "../node_modules/@tensorflow/tfjs-layers/src/keras_format/initializer_config.ts", "../node_modules/@tensorflow/tfjs-layers/src/initializers.ts", "../node_modules/@tensorflow/tfjs-layers/src/exports_initializers.ts", "../node_modules/@tensorflow/tfjs-layers/src/backend/state.ts", "../node_modules/@tensorflow/tfjs-layers/src/utils/types_utils.ts", "../node_modules/@tensorflow/tfjs-layers/src/utils/variable_utils.ts", "../node_modules/@tensorflow/tfjs-layers/src/variables.ts", "../node_modules/@tensorflow/tfjs-layers/src/engine/topology.ts", "../node_modules/@tensorflow/tfjs-layers/src/engine/input_layer.ts", "../node_modules/@tensorflow/tfjs-layers/src/logs.ts", "../node_modules/@tensorflow/tfjs-layers/src/base_callbacks.ts", "../node_modules/@tensorflow/tfjs-layers/src/layers/serialization.ts", "../node_modules/@tensorflow/tfjs-layers/src/losses.ts", "../node_modules/@tensorflow/tfjs-layers/src/metrics.ts", "../node_modules/@tensorflow/tfjs-layers/src/optimizers.ts", "../node_modules/@tensorflow/tfjs-layers/src/user_defined_metadata.ts", "../node_modules/@tensorflow/tfjs-layers/src/utils/layer_utils.ts", "../node_modules/@tensorflow/tfjs-layers/src/utils/serialization_utils.ts", "../node_modules/@tensorflow/tfjs-layers/src/version.ts", "../node_modules/@tensorflow/tfjs-layers/src/engine/executor.ts", "../node_modules/@tensorflow/tfjs-layers/src/engine/container.ts", "../node_modules/@tensorflow/tfjs-layers/src/engine/training_utils.ts", "../node_modules/@tensorflow/tfjs-layers/src/engine/training_dataset.ts", "../node_modules/@tensorflow/tfjs-layers/src/engine/training_tensors.ts", "../node_modules/@tensorflow/tfjs-layers/src/engine/training.ts", "../node_modules/@tensorflow/tfjs-layers/src/models.ts", "../node_modules/@tensorflow/tfjs-layers/src/exports.ts", "../node_modules/@tensorflow/tfjs-layers/src/activations.ts", "../node_modules/@tensorflow/tfjs-layers/src/regularizers.ts", "../node_modules/@tensorflow/tfjs-layers/src/layers/advanced_activations.ts", "../node_modules/@tensorflow/tfjs-layers/src/utils/conv_utils.ts", "../node_modules/@tensorflow/tfjs-layers/src/layers/convolutional.ts", "../node_modules/@tensorflow/tfjs-layers/src/layers/convolutional_depthwise.ts", "../node_modules/@tensorflow/tfjs-layers/src/layers/recurrent.ts", "../node_modules/@tensorflow/tfjs-layers/src/layers/convolutional_recurrent.ts", "../node_modules/@tensorflow/tfjs-layers/src/layers/core.ts", "../node_modules/@tensorflow/tfjs-layers/src/layers/embeddings.ts", "../node_modules/@tensorflow/tfjs-layers/src/layers/merge.ts", "../node_modules/@tensorflow/tfjs-layers/src/layers/noise.ts", "../node_modules/@tensorflow/tfjs-layers/src/layers/normalization.ts", "../node_modules/@tensorflow/tfjs-layers/src/layers/padding.ts", "../node_modules/@tensorflow/tfjs-layers/src/layers/pooling.ts", "../node_modules/@tensorflow/tfjs-layers/src/layers/wrappers.ts", "../node_modules/@tensorflow/tfjs-layers/src/exports_layers.ts", "../node_modules/@tensorflow/tfjs-layers/src/exports_metrics.ts", "../node_modules/@tensorflow/tfjs-layers/src/exports_models.ts", "../node_modules/@tensorflow/tfjs-layers/src/exports_regularizers.ts", "../node_modules/@tensorflow/tfjs-layers/src/callbacks.ts", "../node_modules/@tensorflow/tfjs-converter/src/data/compiled_api.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/custom_op/register.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/executors/utils.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/arithmetic.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/basic_math.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/control.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/convolution.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/creation.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/dynamic.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/evaluation.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/graph.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/image.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/logical.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/matrices.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/normalization.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/reduction.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/slice_join.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/spectral.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/op_list/transformation.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/operation_mapper.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/custom_op/node_value_impl.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/executors/arithmetic_executor.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/executors/basic_math_executor.ts", "../node_modules/@tensorflow/tfjs-converter/src/executor/tensor_utils.ts", "../node_modules/@tensorflow/tfjs-converter/src/executor/tensor_array.ts", "../node_modules/@tensorflow/tfjs-converter/src/executor/tensor_list.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/executors/control_executor.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/executors/convolution_executor.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/executors/creation_executor.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/executors/dynamic_executor.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/executors/evaluation_executor.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/executors/graph_executor.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/executors/image_executor.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/executors/logical_executor.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/executors/matrices_executor.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/executors/normalization_executor.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/executors/reduction_executor.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/executors/slice_join_executor.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/executors/spectral_executor.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/executors/transformation_executor.ts", "../node_modules/@tensorflow/tfjs-converter/src/operations/operation_executor.ts", "../node_modules/@tensorflow/tfjs-converter/src/executor/execution_context.ts", "../node_modules/@tensorflow/tfjs-converter/src/executor/model_analysis.ts", "../node_modules/@tensorflow/tfjs-converter/src/executor/graph_executor.ts", "../node_modules/@tensorflow/tfjs-converter/src/executor/graph_model.ts", "../node_modules/@tensorflow/tfjs-converter/src/version.ts", "empty:/home/vlado/dev/human/node_modules/string_decoder/lib/string_decoder.js", "../node_modules/@tensorflow/tfjs-data/node_modules/seedrandom/lib/alea.js", "../node_modules/@tensorflow/tfjs-data/node_modules/seedrandom/lib/xor128.js", "../node_modules/@tensorflow/tfjs-data/node_modules/seedrandom/lib/xorwow.js", "../node_modules/@tensorflow/tfjs-data/node_modules/seedrandom/lib/xorshift7.js", "../node_modules/@tensorflow/tfjs-data/node_modules/seedrandom/lib/xor4096.js", "../node_modules/@tensorflow/tfjs-data/node_modules/seedrandom/lib/tychei.js", "../node_modules/@tensorflow/tfjs-data/node_modules/seedrandom/seedrandom.js", "../node_modules/@tensorflow/tfjs-data/node_modules/seedrandom/index.js", "../node_modules/@tensorflow/tfjs-data/src/util/deep_map.ts", "../node_modules/@tensorflow/tfjs-data/src/util/deep_clone.ts", "../node_modules/@tensorflow/tfjs-data/src/util/ring_buffer.ts", "../node_modules/@tensorflow/tfjs-data/src/util/growing_ring_buffer.ts", "../node_modules/@tensorflow/tfjs-data/src/iterators/lazy_iterator.ts", "../node_modules/@tensorflow/tfjs-data/src/dataset.ts", "../node_modules/@tensorflow/tfjs-data/src/datasets/text_line_dataset.ts", "../node_modules/@tensorflow/tfjs-data/src/datasets/csv_dataset.ts", "../node_modules/@tensorflow/tfjs-data/src/iterators/microphone_iterator.ts", "../node_modules/@tensorflow/tfjs-data/src/iterators/webcam_iterator.ts", "../node_modules/@tensorflow/tfjs-data/src/datasource.ts", "../node_modules/@tensorflow/tfjs-data/src/iterators/string_iterator.ts", "../node_modules/@tensorflow/tfjs-data/src/iterators/byte_chunk_iterator.ts", "../node_modules/@tensorflow/tfjs-data/src/iterators/file_chunk_iterator.ts", "../node_modules/@tensorflow/tfjs-data/src/iterators/url_chunk_iterator.ts", "../node_modules/@tensorflow/tfjs-data/src/util/source_util.ts", "../node_modules/@tensorflow/tfjs-data/src/sources/file_data_source.ts", "../node_modules/@tensorflow/tfjs-data/src/sources/url_data_source.ts", "../node_modules/@tensorflow/tfjs-data/src/readers.ts", "../node_modules/@tensorflow/tfjs-data/src/version.ts", "../node_modules/seedrandom/lib/alea.js", "../node_modules/seedrandom/lib/xor128.js", "../node_modules/seedrandom/lib/xorwow.js", "../node_modules/seedrandom/lib/xorshift7.js", "../node_modules/seedrandom/lib/xor4096.js", "../node_modules/seedrandom/lib/tychei.js", "../node_modules/seedrandom/seedrandom.js", "../node_modules/seedrandom/index.js", "../node_modules/@tensorflow/tfjs-backend-cpu/src/cpu_util.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/backend_cpu.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Abs.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/utils/binary_impl.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Complex.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Identity.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Real.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Cast.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/utils/kernel_utils.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Add.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/utils/unary_impl.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/utils/unary_utils.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Ceil.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Exp.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Expm1.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Floor.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Log.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Max_impl.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Multiply.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Rsqrt.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Slice.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sub.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Transpose_impl.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Unique_impl.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/shared.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/version.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/base.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Acos.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Acosh.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Asin.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Asinh.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Atan.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Atanh.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/utils/pool_utils.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/AvgPool.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/AvgPoolBackprop.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/BatchNorm.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Clip.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Imag.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Reshape.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Concat.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Cos.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Cosh.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Dilation2D.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Dilation2DBackpropFilter.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Dilation2DBackpropInput.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Div.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Elu.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Erf.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/utils/fft_utils.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/FFT.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/FlipLeftRight.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/IFFT.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/IsFinite.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/IsInf.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/IsNaN.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Log1p.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/LogicalNot.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Max.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/MaxPool.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/MaxPoolBackprop.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/MaxPoolWithArgmax_impl.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/MaxPoolWithArgmax.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/NonMaxSuppressionV4.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/NonMaxSuppressionV5.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/NotEqual.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/PadV2.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Reciprocal.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/RotateWithOffset.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Round.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Selu.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sigmoid.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sign.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sin.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sinh.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Softplus.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Transpose.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SpaceToBatchND.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Sqrt.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Square.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/SquaredDifference.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Step.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Tan.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Tanh.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/kernels/Unique.ts", "../node_modules/@tensorflow/tfjs-backend-cpu/src/register_all_kernels.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/canvas_util.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/tex_util.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/webgl_util.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/flags_webgl.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Abs.js", "../node_modules/@tensorflow/tfjs-backend-webgl/node_modules/@tensorflow/tfjs-backend-cpu/dist/utils/binary_impl.js", "../node_modules/@tensorflow/tfjs-backend-webgl/node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Add.js", "../node_modules/@tensorflow/tfjs-backend-webgl/node_modules/@tensorflow/tfjs-backend-cpu/dist/utils/unary_impl.js", "../node_modules/@tensorflow/tfjs-backend-webgl/node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Ceil.js", "../node_modules/@tensorflow/tfjs-backend-webgl/node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Exp.js", "../node_modules/@tensorflow/tfjs-backend-webgl/node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Expm1.js", "../node_modules/@tensorflow/tfjs-backend-webgl/node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Floor.js", "../node_modules/@tensorflow/tfjs-backend-webgl/node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Log.js", "../node_modules/@tensorflow/tfjs-backend-webgl/node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Max_impl.js", "../node_modules/@tensorflow/tfjs-backend-webgl/node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Multiply.js", "../node_modules/@tensorflow/tfjs-backend-webgl/node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Rsqrt.js", "../node_modules/@tensorflow/tfjs-backend-webgl/node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Slice.js", "../node_modules/@tensorflow/tfjs-backend-webgl/node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Sub.js", "../node_modules/@tensorflow/tfjs-backend-webgl/node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Transpose_impl.js", "../node_modules/@tensorflow/tfjs-backend-webgl/node_modules/@tensorflow/tfjs-backend-cpu/dist/kernels/Unique_impl.js", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernel_utils/shared.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/addn_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/addn_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/argminmax_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/packing_util.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/glsl_version.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/shader_compiler_util.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/shader_compiler.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/argminmax_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/avg_pool_backprop_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/binaryop_complex_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/binaryop_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/binaryop_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/clip_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/clip_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/complex_abs_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/concat_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/concat_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/conv_backprop_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/conv_backprop_gpu_depthwise.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/conv_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/conv_gpu_depthwise.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/conv_packed_gpu_depthwise.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/crop_and_resize_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/cumsum_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/decode_matrix_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/decode_matrix_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/depth_to_space_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/diag_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/encode_float_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/encode_float_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/encode_matrix_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/encode_matrix_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/fft_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/fill_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/gather_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/gather_nd_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/gpgpu_util.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/gpgpu_context.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/gpgpu_math.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/im2col_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/lrn_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/lrn_grad_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/lrn_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/max_pool_backprop_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/mulmat_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/multinomial_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/onehot_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/pack_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/pad_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/pad_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/pool_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/reduce_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/reshape_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/resize_bilinear_backprop_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/resize_bilinear_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/resize_bilinear_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/resize_nearest_neighbor_backprop_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/resize_nearest_neighbor_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/reverse_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/reverse_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/scatter_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/segment_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/select_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/slice_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/slice_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/strided_slice_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/texture_manager.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/tile_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/unaryop_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/unaryop_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/unpack_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/backend_webgl.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/version.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/webgl.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/base.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernel_utils/kernel_funcs_utils.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Atan2.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Identity.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/AvgPool.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/AvgPoolBackprop.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/batchnorm_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/batchnorm_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/BatchNorm.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Cos.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Div.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/flip_left_right_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FlipLeftRight.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FromPixels_utils/from_pixels_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FromPixels_utils/from_pixels_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/FromPixels.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernel_utils/reduce.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernel_utils/reshape.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Reshape.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Max_impl.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/transpose_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/transpose_packed_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Transpose_impl.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Max.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/MaxPool.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/MaxPoolBackprop.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/MaxPoolWithArgmax_impl.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/MaxPoolWithArgmax.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/NonMaxSuppressionV3.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/NonMaxSuppressionV4.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/NonMaxSuppressionV5.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/rotate_gpu.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/RotateWithOffset.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Sin.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Square.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/SquaredDifference.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Tan.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Transpose.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/kernels/Unique.ts", "../node_modules/@tensorflow/tfjs-backend-webgl/src/register_all_kernels.ts", "../node_modules/@tensorflow/tfjs/src/version.ts", "../node_modules/@tensorflow/tfjs/src/index.ts", "../src/facemesh/blazeface.js", "../src/facemesh/keypoints.js", "../src/facemesh/box.js", "../src/facemesh/util.js", "../src/facemesh/pipeline.js", "../src/facemesh/uvcoords.js", "../src/facemesh/triangulation.js", "../src/facemesh/facemesh.js", "../src/ssrnet/ssrnet.js", "../src/emotion/emotion.js", "../src/posenet/modelBase.js", "../src/posenet/modelMobileNet.js", "../src/posenet/heapSort.js", "../src/posenet/buildParts.js", "../src/posenet/keypoints.js", "../src/posenet/vectors.js", "../src/posenet/decodePose.js", "../src/posenet/decodeMultiple.js", "../src/posenet/util.js", "../src/posenet/modelPoseNet.js", "../src/posenet/posenet.js", "../src/handpose/box.js", "../src/handpose/handdetector.js", "../src/handpose/keypoints.js", "../src/handpose/util.js", "../src/handpose/pipeline.js", "../src/handpose/handpose.js", "../src/imagefx.js", "../config.js", "../src/human.js"], - "sourcesContent": ["", "", "", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Conv2DInfo, Conv3DInfo} from '../ops/conv_util';\nimport {FusedBatchMatMulConfig, FusedConv2DConfig} from '../ops/fused_types';\nimport {Backend, DataId, Scalar, Tensor, Tensor1D, Tensor2D, Tensor3D, Tensor4D, Tensor5D} from '../tensor';\nimport {BackendValues, DataType, Rank, ShapeMap} from '../types';\n\nexport const EPSILON_FLOAT32 = 1e-7;\nexport const EPSILON_FLOAT16 = 1e-4;\n\n// Required information for all backends.\nexport interface BackendTimingInfo {\n kernelMs: number|{error: string};\n getExtraProfileInfo?(): string; // a field for additional timing information\n // e.g. packing / unpacking for WebGL backend\n}\n\nexport interface TensorStorage {\n read(dataId: DataId): Promise;\n readSync(dataId: DataId): BackendValues;\n disposeData(dataId: DataId): void;\n write(values: BackendValues, shape: number[], dtype: DataType): DataId;\n move(dataId: DataId, values: BackendValues, shape: number[], dtype: DataType):\n void;\n memory(): {unreliable: boolean;}; // Backend-specific information.\n /** Returns number of data ids currently in the storage. */\n numDataIds(): number;\n}\n\n/** Convenient class for storing tensor-related data. */\nexport class DataStorage {\n private data = new WeakMap();\n private dataIdsCount = 0;\n\n constructor(private backend: KernelBackend, private dataMover: DataMover) {}\n\n get(dataId: DataId) {\n if (!this.data.has(dataId)) {\n this.dataMover.moveData(this.backend, dataId);\n }\n return this.data.get(dataId);\n }\n\n set(dataId: DataId, value: T): void {\n this.dataIdsCount++;\n this.data.set(dataId, value);\n }\n\n has(dataId: DataId): boolean {\n return this.data.has(dataId);\n }\n\n delete(dataId: DataId): boolean {\n this.dataIdsCount--;\n return this.data.delete(dataId);\n }\n\n numDataIds(): number {\n return this.dataIdsCount;\n }\n}\n\nexport interface DataMover {\n /**\n * To be called by backends whenever they see a dataId that they don't own.\n * Upon calling this method, the mover will fetch the tensor from another\n * backend and register it with the current active backend.\n */\n moveData(backend: KernelBackend, dataId: DataId): void;\n}\n\nexport interface BackendTimer {\n time(f: () => void): Promise;\n}\n\n/**\n * The interface that defines the kernels that should be implemented when\n * adding a new backend. New backends don't need to implement every one of the\n * methods, this can be done gradually (throw an error for unimplemented\n * methods).\n */\nexport class KernelBackend implements TensorStorage, Backend, BackendTimer {\n time(f: () => void): Promise {\n return notYetImplemented('time');\n }\n read(dataId: object): Promise {\n return notYetImplemented('read');\n }\n readSync(dataId: object): BackendValues {\n return notYetImplemented('readSync');\n }\n numDataIds(): number {\n return notYetImplemented('numDataIds');\n }\n disposeData(dataId: object): void {\n return notYetImplemented('disposeData');\n }\n write(values: BackendValues, shape: number[], dtype: DataType): DataId {\n return notYetImplemented('write');\n }\n move(dataId: DataId, values: BackendValues, shape: number[], dtype: DataType):\n void {\n return notYetImplemented('move');\n }\n memory(): {unreliable: boolean; reasons?: string[]} {\n return notYetImplemented('memory');\n }\n /** Returns the highest precision for floats in bits (e.g. 16 or 32) */\n floatPrecision(): 16|32 {\n return notYetImplemented('floatPrecision');\n }\n /** Returns the smallest representable number. */\n epsilon(): number {\n return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16;\n }\n\n batchMatMul(\n a: Tensor3D, b: Tensor3D, transposeA: boolean,\n transposeB: boolean): Tensor3D {\n return notYetImplemented('batchMatMul');\n }\n\n fusedBatchMatMul(\n {a, b, transposeA, transposeB, bias, activation, preluActivationWeights}:\n FusedBatchMatMulConfig): Tensor3D {\n return notYetImplemented('fusedBatchMatMul');\n }\n\n slice(x: T, begin: number[], size: number[]): T {\n return notYetImplemented('slice');\n }\n stridedSlice(\n x: T, begin: number[], end: number[], strides: number[]): T {\n return notYetImplemented('stridedSlice');\n }\n unstack(x: Tensor, axis: number): Tensor[] {\n return notYetImplemented('unstack');\n }\n reverse(a: T, axis: number[]): T {\n return notYetImplemented('reverse');\n }\n\n concat(tensors: Tensor[], axis: number): Tensor {\n return notYetImplemented('concat');\n }\n\n neg(a: T): T {\n return notYetImplemented('neg');\n }\n\n add(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('add');\n }\n addN(tensors: T[]): T {\n return notYetImplemented('addN');\n }\n subtract(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('subtract');\n }\n multiply(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('multiply');\n }\n realDivide(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('realDivide');\n }\n floorDiv(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('floorDiv');\n }\n\n sum(x: Tensor, axes: number[]): Tensor {\n return notYetImplemented('sum');\n }\n prod(x: Tensor, axes: number[]): Tensor {\n return notYetImplemented('prod');\n }\n\n unsortedSegmentSum(\n x: T, segmentIds: Tensor1D, numSegments: number): Tensor {\n return notYetImplemented('unsortedSegmentSum');\n }\n\n argMin(x: Tensor, axis: number): Tensor {\n return notYetImplemented('argMin');\n }\n argMax(x: Tensor, axis: number): Tensor {\n return notYetImplemented('argMax');\n }\n\n equal(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('equal');\n }\n notEqual(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('notEqual');\n }\n\n less(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('less');\n }\n lessEqual(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('lessEqual');\n }\n\n greater(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('greater');\n }\n greaterEqual(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('greaterEqual');\n }\n\n logicalNot(a: T): T {\n return notYetImplemented('logicalNot');\n }\n logicalAnd(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('logicalAnd');\n }\n logicalOr(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('logicalOr');\n }\n\n where(condition: Tensor): Tensor2D {\n return notYetImplemented('where');\n }\n select(condition: Tensor, a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('select');\n }\n\n topk(x: T, k: number, sorted: boolean): [T, T] {\n return notYetImplemented('topk');\n }\n\n min(x: Tensor, axes: number[]): Tensor {\n return notYetImplemented('min');\n }\n minimum(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('minimum');\n }\n\n mod(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('mod');\n }\n\n max(x: Tensor, axes: number[]): Tensor {\n return notYetImplemented('max');\n }\n maximum(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('maximum');\n }\n\n all(x: Tensor, axes: number[]): Tensor {\n return notYetImplemented('all');\n }\n any(x: Tensor, axes: number[]): Tensor {\n return notYetImplemented('any');\n }\n\n squaredDifference(a: Tensor, b: Tensor): Tensor {\n return notYetImplemented('squaredDifference');\n }\n\n ceil(x: T): T {\n return notYetImplemented('ceil');\n }\n floor(x: T): T {\n return notYetImplemented('floor');\n }\n round(x: T): T {\n return notYetImplemented('round');\n }\n\n sign(x: T): T {\n return notYetImplemented('sign');\n }\n\n isNaN(x: T): T {\n return notYetImplemented('isNaN');\n }\n isInf(x: T): T {\n return notYetImplemented('isInf');\n }\n isFinite(x: T): T {\n return notYetImplemented('isFinite');\n }\n\n pow(a: T, b: Tensor): T {\n return notYetImplemented('pow');\n }\n exp(x: T): T {\n return notYetImplemented('exp');\n }\n expm1(x: T): T {\n return notYetImplemented('expm1');\n }\n softmax(x: T, dim: number): T {\n return notYetImplemented('softmax');\n }\n log(x: T): T {\n return notYetImplemented('log');\n }\n log1p(x: T): T {\n return notYetImplemented('log1p');\n }\n sqrt(x: T): T {\n return notYetImplemented('sqrt');\n }\n rsqrt(x: T): T {\n return notYetImplemented('rsqrt');\n }\n square(x: T): T {\n return notYetImplemented('square');\n }\n reciprocal(x: T): T {\n return notYetImplemented('reciprocal');\n }\n relu(x: T): T {\n return notYetImplemented('relu');\n }\n relu6(x: T): T {\n return notYetImplemented('relu6');\n }\n prelu(x: T, a: T): T {\n return notYetImplemented('prelu');\n }\n elu(x: T): T {\n return notYetImplemented('elu');\n }\n eluDer(dy: T, y: T): T {\n return notYetImplemented('eluDer');\n }\n selu(x: T): T {\n return notYetImplemented('selu');\n }\n int(x: T): T {\n return notYetImplemented('int');\n }\n\n clip(x: T, min: number, max: number): T {\n return notYetImplemented('clip');\n }\n\n abs(x: T): T {\n return notYetImplemented('abs');\n }\n complexAbs(x: T): T {\n return notYetImplemented('complexAbs');\n }\n\n sigmoid(x: T): T {\n return notYetImplemented('sigmoid');\n }\n\n softplus(x: T): T {\n return notYetImplemented('softplus');\n }\n\n sin(x: T): T {\n return notYetImplemented('sin');\n }\n cos(x: T): T {\n return notYetImplemented('cos');\n }\n tan(x: T): T {\n return notYetImplemented('tan');\n }\n\n asin(x: T): T {\n return notYetImplemented('asin');\n }\n acos(x: T): T {\n return notYetImplemented('acos');\n }\n atan(x: T): T {\n return notYetImplemented('atan');\n }\n atan2(a: T, b: T): T {\n return notYetImplemented('atan2');\n }\n\n sinh(x: T): T {\n return notYetImplemented('sinh');\n }\n cosh(x: T): T {\n return notYetImplemented('cosh');\n }\n tanh(x: T): T {\n return notYetImplemented('tanh');\n }\n\n asinh(x: T): T {\n return notYetImplemented('asinh');\n }\n acosh(x: T): T {\n return notYetImplemented('acosh');\n }\n atanh(x: T): T {\n return notYetImplemented('atanh');\n }\n\n erf(x: T): T {\n return notYetImplemented('erf');\n }\n\n step(x: T, alpha: number): T {\n return notYetImplemented('step');\n }\n\n fusedConv2d(\n {input, filter, convInfo, bias, activation, preluActivationWeights}:\n FusedConv2DConfig): Tensor4D {\n return notYetImplemented('fusedConv2d');\n }\n\n conv2d(x: Tensor4D, filter: Tensor4D, convInfo: Conv2DInfo): Tensor4D {\n return notYetImplemented('conv2d');\n }\n conv2dDerInput(dy: Tensor4D, filter: Tensor4D, convInfo: Conv2DInfo):\n Tensor4D {\n return notYetImplemented('conv2dDerInput');\n }\n conv2dDerFilter(x: Tensor4D, dY: Tensor4D, convInfo: Conv2DInfo): Tensor4D {\n return notYetImplemented('conv2dDerFilter');\n }\n\n fusedDepthwiseConv2D(\n {input, filter, convInfo, bias, activation, preluActivationWeights}:\n FusedConv2DConfig): Tensor4D {\n return notYetImplemented('fusedDepthwiseConv2D');\n }\n\n depthwiseConv2D(input: Tensor4D, filter: Tensor4D, convInfo: Conv2DInfo):\n Tensor4D {\n return notYetImplemented('depthwiseConv2D');\n }\n depthwiseConv2DDerInput(dy: Tensor4D, filter: Tensor4D, convInfo: Conv2DInfo):\n Tensor4D {\n return notYetImplemented('depthwiseConv2DDerInput');\n }\n depthwiseConv2DDerFilter(x: Tensor4D, dY: Tensor4D, convInfo: Conv2DInfo):\n Tensor4D {\n return notYetImplemented('depthwiseConv2DDerFilter');\n }\n conv3d(x: Tensor5D, filter: Tensor5D, convInfo: Conv3DInfo): Tensor5D {\n return notYetImplemented('conv3d');\n }\n conv3dDerInput(dy: Tensor5D, filter: Tensor5D, convInfo: Conv3DInfo):\n Tensor5D {\n return notYetImplemented('conv3dDerInput');\n }\n conv3dDerFilter(x: Tensor5D, dY: Tensor5D, convInfo: Conv3DInfo): Tensor5D {\n return notYetImplemented('conv3dDerFilter');\n }\n maxPool(x: Tensor4D, convInfo: Conv2DInfo): Tensor4D {\n return notYetImplemented('maxPool');\n }\n maxPoolBackprop(dy: Tensor4D, x: Tensor4D, y: Tensor4D, convInfo: Conv2DInfo):\n Tensor4D {\n return notYetImplemented('maxPoolBackprop');\n }\n avgPool(x: Tensor4D, convInfo: Conv2DInfo): Tensor4D {\n return notYetImplemented('avgPool');\n }\n avgPoolBackprop(dy: Tensor4D, x: Tensor4D, convInfo: Conv2DInfo): Tensor4D {\n return notYetImplemented('avgPoolBackprop');\n }\n avgPool3d(x: Tensor5D, convInfo: Conv3DInfo): Tensor5D {\n return notYetImplemented('avgPool3d');\n }\n avgPool3dBackprop(dy: Tensor5D, x: Tensor5D, convInfo: Conv3DInfo): Tensor5D {\n return notYetImplemented('avgPool3dBackprop');\n }\n maxPool3d(x: Tensor5D, convInfo: Conv3DInfo): Tensor5D {\n return notYetImplemented('maxPool3d');\n }\n maxPool3dBackprop(\n dy: Tensor5D, x: Tensor5D, y: Tensor5D, convInfo: Conv3DInfo): Tensor5D {\n return notYetImplemented('maxPool3dBackprop');\n }\n\n reshape(x: T, shape: ShapeMap[R]):\n Tensor {\n return notYetImplemented('reshape');\n }\n cast(x: T, dtype: DataType): T {\n return notYetImplemented('cast');\n }\n\n tile(x: T, reps: number[]): T {\n return notYetImplemented('tile');\n }\n\n pad(\n x: T, paddings: Array<[number, number]>, constantValue: number): T {\n return notYetImplemented('pad');\n }\n\n transpose(x: T, perm: number[]): T {\n return notYetImplemented('transpose');\n }\n\n gather(x: T, indices: Tensor1D, axis: number): T {\n return notYetImplemented('gather');\n }\n\n gatherND(x: Tensor, indices: Tensor): Tensor {\n return notYetImplemented('gatherND');\n }\n\n scatterND(\n indices: Tensor, updates: Tensor, shape: ShapeMap[R]): Tensor {\n return notYetImplemented('scatterND');\n }\n\n batchToSpaceND(\n x: T, blockShape: number[], crops: number[][]): T {\n return notYetImplemented('batchToSpaceND');\n }\n\n spaceToBatchND(\n x: T, blockShape: number[], paddings: number[][]): T {\n return notYetImplemented('spaceToBatchND');\n }\n\n resizeBilinear(\n x: Tensor4D, newHeight: number, newWidth: number,\n alignCorners: boolean): Tensor4D {\n return notYetImplemented('resizeBilinear');\n }\n\n resizeBilinearBackprop(dy: Tensor4D, x: Tensor4D, alignCorners: boolean):\n Tensor4D {\n return notYetImplemented('resizeBilinearBackprop');\n }\n\n resizeNearestNeighbor(\n x: Tensor4D, newHEight: number, newWidth: number,\n alignCorners: boolean): Tensor4D {\n return notYetImplemented('resizeNearestNeighbor');\n }\n\n resizeNearestNeighborBackprop(\n dy: Tensor4D, x: Tensor4D, alignCorners: boolean): Tensor4D {\n return notYetImplemented('resizeNearestNeighborBackprop');\n }\n\n batchNorm(\n x: Tensor4D, mean: Tensor4D|Tensor1D, variance: Tensor4D|Tensor1D,\n offset?: Tensor4D|Tensor1D, scale?: Tensor4D|Tensor1D,\n varianceEpsilon?: number): Tensor4D {\n return notYetImplemented('batchNorm');\n }\n\n localResponseNormalization4D(\n x: Tensor4D, radius: number, bias: number, alpha: number,\n beta: number): Tensor4D {\n return notYetImplemented('localResponseNormalization4D');\n }\n\n LRNGrad(\n dy: Tensor4D, inputImage: Tensor4D, outputImage: Tensor4D, radius: number,\n bias: number, alpha: number, beta: number): Tensor4D {\n return notYetImplemented('LRNGrad');\n }\n\n multinomial(\n logits: Tensor2D, normalized: boolean, numSamples: number,\n seed: number): Tensor2D {\n return notYetImplemented('multinomial');\n }\n\n oneHot(indices: Tensor1D, depth: number, onValue: number, offValue: number):\n Tensor2D {\n return notYetImplemented('oneHot');\n }\n\n cumsum(x: Tensor, axis: number, exclusive: boolean, reverse: boolean):\n Tensor {\n return notYetImplemented('cumsum');\n }\n\n nonMaxSuppression(\n boxes: Tensor2D, scores: Tensor1D, maxOutputSize: number,\n iouThreshold: number, scoreThreshold?: number): Tensor1D {\n return notYetImplemented('nonMaxSuppression');\n }\n\n fft(x: Tensor2D): Tensor2D {\n return notYetImplemented('fft');\n }\n ifft(x: Tensor2D): Tensor2D {\n return notYetImplemented('ifft');\n }\n complex(real: T, imag: T): T {\n return notYetImplemented('complex');\n }\n real(input: T): T {\n return notYetImplemented('real');\n }\n imag(input: T): T {\n return notYetImplemented('imag');\n }\n\n cropAndResize(\n image: Tensor4D, boxes: Tensor2D, boxIndex: Tensor1D,\n cropSize: [number, number], method: 'bilinear'|'nearest',\n extrapolationValue: number): Tensor4D {\n return notYetImplemented('cropAndResize');\n }\n\n depthToSpace(x: Tensor4D, blockSize: number, dataFormat: string): Tensor4D {\n return notYetImplemented('depthToSpace');\n }\n\n // Aligns with the \"SplitV\" kernel in TensorFlow.\n split(value: T, sizeSplits: number[], axis: number): T[] {\n return notYetImplemented('split');\n }\n\n sparseToDense(\n sparseIndices: Tensor, sparseValues: Tensor, outputShape: ShapeMap[R],\n defaultValue: Scalar): Tensor {\n return notYetImplemented('sparseToDense');\n }\n\n diag(x: Tensor): Tensor {\n return notYetImplemented('diag');\n }\n\n fill(\n shape: ShapeMap[R], value: number|string, dtype?: DataType): Tensor {\n return notYetImplemented('fill');\n }\n\n onesLike(x: Tensor): Tensor {\n return notYetImplemented('onesLike');\n }\n\n zerosLike(x: Tensor): Tensor {\n return notYetImplemented('zerosLike');\n }\n\n linspace(start: number, stop: number, num: number): Tensor1D {\n return notYetImplemented('linspace');\n }\n\n dispose(): void {\n return notYetImplemented('dispose');\n }\n}\n\nfunction notYetImplemented(kernelName: string): never {\n throw new Error(\n `'${kernelName}' not yet implemented or not found in the registry. ` +\n `This kernel may not be supported by the tfjs backend you have chosen`);\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Platform} from './platforms/platform';\n\n// Expects flags from URL in the format ?tfjsflags=FLAG1:1,FLAG2:true.\nconst TENSORFLOWJS_FLAGS_PREFIX = 'tfjsflags';\n\ntype FlagValue = number|boolean;\ntype FlagEvaluationFn = (() => FlagValue)|(() => Promise);\nexport type Flags = {\n [featureName: string]: FlagValue\n};\nexport type FlagRegistryEntry = {\n evaluationFn: FlagEvaluationFn;\n setHook?: (value: FlagValue) => void;\n};\n\n/**\n * The environment contains evaluated flags as well as the registered platform.\n * This is always used as a global singleton and can be retrieved with\n * `tf.env()`.\n *\n * @doc {heading: 'Environment'}\n */\nexport class Environment {\n private flags: Flags = {};\n private flagRegistry: {[flagName: string]: FlagRegistryEntry} = {};\n\n private urlFlags: Flags = {};\n\n platformName: string;\n platform: Platform;\n\n // tslint:disable-next-line: no-any\n constructor(public global: any) {\n this.populateURLFlags();\n }\n\n setPlatform(platformName: string, platform: Platform) {\n if (this.platform != null) {\n console.warn(\n `Platform ${this.platformName} has already been set. ` +\n `Overwriting the platform with ${platform}.`);\n }\n this.platformName = platformName;\n this.platform = platform;\n }\n\n registerFlag(\n flagName: string, evaluationFn: FlagEvaluationFn,\n setHook?: (value: FlagValue) => void) {\n this.flagRegistry[flagName] = {evaluationFn, setHook};\n\n // Override the flag value from the URL. This has to happen here because the\n // environment is initialized before flags get registered.\n if (this.urlFlags[flagName] != null) {\n const flagValue = this.urlFlags[flagName];\n console.warn(\n `Setting feature override from URL ${flagName}: ${flagValue}.`);\n this.set(flagName, flagValue);\n }\n }\n\n async getAsync(flagName: string): Promise {\n if (flagName in this.flags) {\n return this.flags[flagName];\n }\n\n this.flags[flagName] = await this.evaluateFlag(flagName);\n return this.flags[flagName];\n }\n\n get(flagName: string): FlagValue {\n if (flagName in this.flags) {\n return this.flags[flagName];\n }\n\n const flagValue = this.evaluateFlag(flagName);\n if (flagValue instanceof Promise) {\n throw new Error(\n `Flag ${flagName} cannot be synchronously evaluated. ` +\n `Please use getAsync() instead.`);\n }\n\n this.flags[flagName] = flagValue;\n\n return this.flags[flagName];\n }\n\n getNumber(flagName: string): number {\n return this.get(flagName) as number;\n }\n\n getBool(flagName: string): boolean {\n return this.get(flagName) as boolean;\n }\n\n getFlags(): Flags {\n return this.flags;\n }\n // For backwards compatibility.\n get features(): Flags {\n return this.flags;\n }\n\n set(flagName: string, value: FlagValue): void {\n if (this.flagRegistry[flagName] == null) {\n throw new Error(\n `Cannot set flag ${flagName} as it has not been registered.`);\n }\n this.flags[flagName] = value;\n if (this.flagRegistry[flagName].setHook != null) {\n this.flagRegistry[flagName].setHook(value);\n }\n }\n\n private evaluateFlag(flagName: string): FlagValue|Promise {\n if (this.flagRegistry[flagName] == null) {\n throw new Error(\n `Cannot evaluate flag '${flagName}': no evaluation function found.`);\n }\n return this.flagRegistry[flagName].evaluationFn();\n }\n\n setFlags(flags: Flags) {\n this.flags = Object.assign({}, flags);\n }\n\n reset() {\n this.flags = {};\n this.urlFlags = {};\n this.populateURLFlags();\n }\n\n private populateURLFlags(): void {\n if (typeof this.global === 'undefined' ||\n typeof this.global.location === 'undefined' ||\n typeof this.global.location.search === 'undefined') {\n return;\n }\n\n const urlParams = getQueryParams(this.global.location.search);\n if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) {\n const keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(',');\n keyValues.forEach(keyValue => {\n const [key, value] = keyValue.split(':') as [string, string];\n this.urlFlags[key] = parseValue(key, value);\n });\n }\n }\n}\n\nexport function getQueryParams(queryString: string): {[key: string]: string} {\n const params = {};\n queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (s, ...t) => {\n decodeParam(params, t[0], t[1]);\n return t.join('=');\n });\n return params;\n}\n\nfunction decodeParam(\n params: {[key: string]: string}, name: string, value?: string) {\n params[decodeURIComponent(name)] = decodeURIComponent(value || '');\n}\n\nfunction parseValue(flagName: string, value: string): FlagValue {\n value = value.toLowerCase();\n if (value === 'true' || value === 'false') {\n return value === 'true';\n } else if (`${+ value}` === value) {\n return +value;\n }\n throw new Error(\n `Could not parse value flag value ${value} for flag ${flagName}.`);\n}\n\n/**\n * Returns the current environment (a global singleton).\n *\n * The environment object contains the evaluated feature values as well as the\n * active platform.\n *\n * @doc {heading: 'Environment'}\n */\nexport function env() {\n return ENV;\n}\n\nexport let ENV: Environment = null;\nexport function setEnvironmentGlobal(environment: Environment) {\n ENV = environment;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Note that the identifier globalNameSpace is scoped to this module, but will\n// always resolve to the same global object regardless of how the module is\n// resolved.\n// tslint:disable-next-line:no-any\nlet globalNameSpace: {_tfGlobals: Map};\n// tslint:disable-next-line:no-any\nexport function getGlobalNamespace(): {_tfGlobals: Map} {\n if (globalNameSpace == null) {\n // tslint:disable-next-line:no-any\n let ns: any;\n if (typeof (window) !== 'undefined') {\n ns = window;\n } else if (typeof (global) !== 'undefined') {\n ns = global;\n } else if (typeof (process) !== 'undefined') {\n ns = process;\n } else if (typeof (self) !== 'undefined') {\n ns = self;\n } else {\n throw new Error('Could not find a global object');\n }\n globalNameSpace = ns;\n }\n return globalNameSpace;\n}\n\n// tslint:disable-next-line:no-any\nfunction getGlobalMap(): Map {\n const ns = getGlobalNamespace();\n if (ns._tfGlobals == null) {\n ns._tfGlobals = new Map();\n }\n return ns._tfGlobals;\n}\n\n/**\n * Returns a globally accessible 'singleton' object.\n *\n * @param key the name of the object\n * @param init a function to initialize to initialize this object\n * the first time it is fetched.\n */\nexport function getGlobal(key: string, init: () => T): T {\n const globalMap = getGlobalMap();\n if (globalMap.has(key)) {\n return globalMap.get(key);\n } else {\n const singleton = init();\n globalMap.set(key, singleton);\n return globalMap.get(key);\n }\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n// Allow UpperCamelCase variable names\n// tslint:disable: variable-name\n// Unfortunately just enabling PascalCase per file (tslint:enable:\n// allow-pascal-case) doesn't work.\nimport {NamedTensorInfoMap, TensorInfo} from './kernel_registry';\nimport {ExplicitPadding} from './ops/conv_util';\nimport {Activation} from './ops/fused_types';\nimport {DataType, PixelData} from './types';\n\nexport const Abs = 'Abs';\nexport type AbsInputs = UnaryInputs;\n\nexport const Acos = 'Acos';\nexport type AcosInputs = UnaryInputs;\n\nexport const Acosh = 'Acosh';\nexport type AcoshInputs = UnaryInputs;\n\nexport const Add = 'Add';\nexport type AddInputs = BinaryInputs;\n\nexport const AddN = 'AddN';\nexport type AddNInputs = TensorInfo[];\n\nexport const All = 'All';\nexport type AllInputs = Pick;\nexport interface AllAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Any = 'Any';\nexport type AnyInputs = Pick;\nexport interface AnyAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const ArgMax = 'ArgMax';\nexport type ArgMaxInputs = Pick;\nexport interface ArgMaxAttrs {\n axis: number;\n}\n\nexport const ArgMin = 'ArgMin';\nexport type ArgMinInputs = Pick;\nexport interface ArgMinAttrs {\n axis: number;\n}\n\nexport const Asin = 'Asin';\nexport type AsinInputs = UnaryInputs;\n\nexport const Asinh = 'Asinh';\nexport type AsinhInputs = UnaryInputs;\n\nexport const Atan = 'Atan';\nexport type AtanInputs = UnaryInputs;\n\nexport const Atanh = 'Atanh';\nexport type AtanhInputs = UnaryInputs;\n\nexport const Atan2 = 'Atan2';\nexport type Atan2Inputs = BinaryInputs;\n\nexport const AvgPool = 'AvgPool';\nexport type AvgPoolInputs = Pick;\nexport interface AvgPoolAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const AvgPoolBackprop = 'AvgPoolBackprop';\nexport type AvgPoolBackpropInputs = Pick;\nexport interface AvgPoolBackpropAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n}\n\nexport const AvgPool3D = 'AvgPool3D';\nexport type AvgPool3DInputs = Pick;\nexport interface AvgPool3DAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n dataFormat: 'NDHWC'|'NCDHW';\n dilations?: [number, number, number]|number;\n}\n\nexport const AvgPool3DBackprop = 'AvgPool3DBackprop';\nexport type AvgPool3DBackpropInputs = Pick;\nexport interface AvgPool3DBackpropAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dilations: [number, number, number]|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const BatchMatMul = 'BatchMatMul';\nexport type BatchMatMulInputs = Pick;\nexport interface BatchMatMulAttrs {\n transposeA: boolean;\n transposeB: boolean;\n}\n\nexport const BatchToSpaceND = 'BatchToSpaceND';\nexport type BatchToSpaceNDInputs = Pick;\nexport interface BatchToSpaceNDAttrs {\n blockShape: number[];\n crops: number[][];\n}\n\nexport type BinaryInputs = Pick;\n\nexport const BroadcastTo = 'BroadcastTo';\nexport type BroadcastToInputs = Pick;\nexport interface BroadCastToAttrs {\n shape: number[];\n inputShape: number[]; // for gradient\n}\n\nexport const Cast = 'Cast';\nexport type CastInputs = UnaryInputs;\nexport interface CastAttrs {\n dtype: DataType;\n}\n\nexport const Ceil = 'Ceil';\nexport type CeilInputs = UnaryInputs;\n\nexport const ClipByValue = 'ClipByValue';\nexport type ClipByValueInputs = UnaryInputs;\nexport interface ClipByValueAttrs {\n clipValueMin: number;\n clipValueMax: number;\n}\n\nexport const Complex = 'Complex';\nexport type ComplexInputs = Pick;\n\nexport const Concat = 'Concat';\nexport type ConcatInputs = TensorInfo[];\nexport interface ConcatAttrs {\n axis: number;\n}\n\nexport const Conv2D = 'Conv2D';\nexport type Conv2DInputs = Pick;\nexport interface Conv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const Conv2DBackpropFilter = 'Conv2DBackpropFilter';\nexport type Conv2DBackpropFilterInputs = Pick;\nexport interface Conv2DBackpropFilterAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const Conv2DBackpropInput = 'Conv2DBackpropInput';\nexport type Conv2DBackpropInputInputs = Pick;\nexport interface Conv2DBackpropInputAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dimRoundingMode?: 'floor'|'round'|'ceil';\n inputShape: [number, number, number, number];\n}\n\nexport const Conv3D = 'Conv3D';\nexport type Conv3DInputs = Pick;\nexport interface Conv3DAttrs {\n strides: [number, number, number]|number;\n pad: 'valid'|'same';\n dataFormat: 'NDHWC'|'NCDHW';\n dilations: [number, number, number]|number;\n}\n\nexport const Conv3DBackpropFilterV2 = 'Conv3DBackpropFilterV2';\nexport type Conv3DBackpropFilterInputs = Pick;\n\nexport interface Conv3DBackpropFilterAttrs {\n strides: [number, number, number]|number;\n pad: 'valid'|'same';\n}\n\nexport const Conv3DBackpropInputV2 = 'Conv3DBackpropInputV2';\nexport type Conv3DBackpropInputInputs = Pick;\nexport interface Conv3DBackpropInputAttrs {\n pad: 'valid'|'same';\n}\n\nexport const Cos = 'Cos';\nexport type CosInputs = UnaryInputs;\n\nexport const Cosh = 'Cosh';\nexport type CoshInputs = UnaryInputs;\n\nexport const Cumsum = 'Cumsum';\nexport type CumsumInputs = Pick;\nexport interface CumsumAttrs {\n axis: number;\n exclusive: boolean;\n reverse: boolean;\n}\n\nexport const CropAndResize = 'CropAndResize';\nexport type CropAndResizeInputs =\n Pick;\nexport interface CropAndResizeAttrs {\n cropSize: [number, number];\n method: 'bilinear'|'nearest';\n extrapolationValue: number;\n}\n\nexport const DepthToSpace = 'DepthToSpace';\nexport type DepthToSpaceInputs = Pick;\nexport interface DepthToSpaceAttrs {\n blockSize: number;\n dataFormat: 'NHWC'|'NCHW';\n}\n\nexport const DepthwiseConv2dNative = 'DepthwiseConv2dNative';\nexport type DepthwiseConv2dNativeInputs =\n Pick;\nexport interface DepthwiseConv2dNativeAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const DepthwiseConv2dNativeBackpropFilter =\n 'DepthwiseConv2dNativeBackpropFilter';\nexport type DepthwiseConv2dNativeBackpropFilterInputs =\n Pick;\n\nexport const DepthwiseConv2dNativeBackpropInput =\n 'DepthwiseConv2dNativeBackpropInput';\nexport type DepthwiseConv2dNativeBackpropInputInputs =\n Pick;\n\nexport const Diag = 'Diag';\nexport type DiagInputs = Pick;\n\nexport const Dilation2D = 'Dilation2D';\nexport type Dilation2DInputs = Pick;\nexport interface Dilation2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n dilations: [number, number]|number;\n}\n\nexport const Dilation2DBackpropInput = 'Dilation2DBackpropInput';\nexport type Dilation2DBackpropInputInputs =\n Pick;\n\nexport const Dilation2DBackpropFilter = 'Dilation2DBackpropFilter';\nexport type Dilation2DBackpropFilterInputs =\n Pick;\n\nexport const Div = 'Div';\nexport type DivInputs = BinaryInputs;\n\nexport const Elu = 'Elu';\nexport type EluInputs = Pick;\n\nexport const EluGrad = 'EluGrad';\nexport type EluGradInputs = Pick;\n\nexport const Erf = 'Erf';\nexport type ErfInputs = UnaryInputs;\n\nexport const Equal = 'Equal';\nexport type EqualInputs = BinaryInputs;\n\nexport const Exp = 'Exp';\nexport type ExpInputs = UnaryInputs;\n\nexport const Expm1 = 'Expm1';\nexport type Expm1Inputs = UnaryInputs;\n\nexport const FFT = 'FFT';\nexport type FFTInputs = Pick;\n\nexport const Fill = 'Fill';\nexport interface FillAttrs {\n shape: number[];\n value: number|string;\n dtype: DataType;\n}\n\nexport const FlipLeftRight = 'FlipLeftRight';\nexport type FlipLeftRightInputs = Pick;\n\nexport const Floor = 'Floor';\nexport type FloorInputs = UnaryInputs;\n\nexport const FloorDiv = 'FloorDiv';\nexport type FloorDivInputs = BinaryInputs;\n\nexport const FusedBatchNorm = 'FusedBatchNorm';\nexport type FusedBatchNormInputs =\n Pick;\nexport interface FusedBatchNormAttrs {\n varianceEpsilon: number;\n}\n\nexport const GatherV2 = 'GatherV2';\nexport type GatherV2Inputs = Pick;\nexport interface GatherV2Attrs {\n axis: number;\n}\n\nexport const GatherNd = 'GatherNd';\nexport type GatherNdInputs = Pick;\n\nexport const Greater = 'Greater';\nexport type GreaterInputs = BinaryInputs;\n\nexport const GreaterEqual = 'GreaterEqual';\nexport type GreaterEqualInputs = BinaryInputs;\n\nexport const Identity = 'Identity';\nexport type IdentityInputs = Pick;\n\nexport const IFFT = 'IFFT';\nexport type IFFTInputs = Pick;\n\nexport const Imag = 'Imag';\nexport type ImagInputs = Pick;\n\nexport const IsFinite = 'IsFinite';\nexport type IsFiniteInputs = UnaryInputs;\n\nexport const IsInf = 'IsInf';\nexport type IsInfInputs = UnaryInputs;\n\nexport const IsNan = 'IsNan';\nexport type IsNanInputs = UnaryInputs;\n\nexport const Less = 'Less';\nexport type LessInputs = BinaryInputs;\n\nexport const LessEqual = 'LessEqual';\nexport type LessEqualInputs = BinaryInputs;\n\nexport const LinSpace = 'LinSpace';\nexport interface LinSpaceAttrs {\n start: number;\n stop: number;\n num: number;\n}\nexport const Log = 'Log';\nexport type LogInputs = UnaryInputs;\n\nexport const Log1p = 'Log1p';\nexport type Log1pInputs = UnaryInputs;\n\nexport const LogicalAnd = 'LogicalAnd';\nexport type LogicalAndInputs = BinaryInputs;\n\nexport const LogicalNot = 'LogicalNot';\nexport type LogicalNotInputs = Pick;\n\nexport const LogicalOr = 'LogicalOr';\nexport type LogicalOrInputs = BinaryInputs;\n\nexport const LogSoftmax = 'LogSoftmax';\nexport type LogSoftmaxInputs = Pick;\nexport interface LogSoftmaxAttrs {\n axis: number;\n}\n\nexport const LRN = 'LRN';\nexport type LRNInputs = Pick;\nexport interface LRNAttrs {\n depthRadius: number;\n bias: number;\n alpha: number;\n beta: number;\n}\n\nexport const LRNBackprop = 'LRNBackprop';\nexport type LRNBackpropInputs = Pick;\nexport interface LRNBackpropAttrs {\n depthRadius: number;\n bias: number;\n alpha: number;\n beta: number;\n}\n\nexport const Max = 'Max';\nexport type MaxInputs = Pick;\nexport interface MaxAttrs {\n reductionIndices: number|number[];\n keepDims: boolean;\n}\n\nexport const Maximum = 'Maximum';\nexport type MaximumInputs = BinaryInputs;\n\nexport const MaxPool = 'MaxPool';\nexport type MaxPoolInputs = Pick;\nexport interface MaxPoolAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPoolBackprop = 'MaxPoolBackprop';\nexport type MaxPoolBackpropInputs =\n Pick;\nexport interface MaxPoolBackpropAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPool3D = 'MaxPool3D';\nexport type MaxPool3DInputs = Pick;\nexport interface MaxPool3DAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dataFormat: 'NDHWC'|'NCDHW';\n dilations?: [number, number, number]|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPool3DBackprop = 'MaxPool3DBackprop';\nexport type MaxPool3DBackpropInputs =\n Pick;\nexport interface MaxPool3DBackpropAttrs {\n filterSize: [number, number, number]|number;\n strides: [number, number, number]|number;\n pad: 'valid'|'same'|number;\n dilations?: [number, number, number]|number;\n dimRoundingMode?: 'floor'|'round'|'ceil';\n}\n\nexport const MaxPoolWithArgmax = 'MaxPoolWithArgmax';\nexport type MaxPoolWithArgmaxInputs = Pick;\nexport interface MaxPoolWithArgmaxAttrs {\n filterSize: [number, number]|number;\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n includeBatchInIndex: boolean;\n}\n\nexport const Mean = 'Mean';\nexport type MeanInputs = Pick;\nexport interface MeanAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Min = 'Min';\nexport type MinInputs = Pick;\nexport interface MinAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Minimum = 'Minimum';\nexport type MinimumInputs = BinaryInputs;\n\nexport const Mod = 'Mod';\nexport type ModInputs = BinaryInputs;\n\nexport const Multiply = 'Multiply';\nexport type MultiplyInputs = BinaryInputs;\n\nexport const Negate = 'Negate';\nexport type NegateInputs = UnaryInputs;\n\nexport const NotEqual = 'NotEqual';\nexport type NotEqualInputs = BinaryInputs;\n\nexport const NonMaxSuppressionV3 = 'NonMaxSuppressionV3';\nexport type NonMaxSuppressionV3Inputs =\n Pick;\nexport interface NonMaxSuppressionV3Attrs {\n maxOutputSize: number;\n iouThreshold: number;\n scoreThreshold: number;\n}\n\nexport const NonMaxSuppressionV4 = 'NonMaxSuppressionV4';\nexport type NonMaxSuppressionV4Inputs =\n Pick;\nexport interface NonMaxSuppressionV4Attrs {\n maxOutputSize: number;\n iouThreshold: number;\n scoreThreshold: number;\n padToMaxOutputSize: boolean;\n}\n\nexport const NonMaxSuppressionV5 = 'NonMaxSuppressionV5';\nexport type NonMaxSuppressionV5Inputs =\n Pick;\nexport interface NonMaxSuppressionV5Attrs {\n maxOutputSize: number;\n iouThreshold: number;\n scoreThreshold: number;\n softNmsSigma: number;\n}\n\nexport const OnesLike = 'OnesLike';\nexport type OnesLikeInputs = UnaryInputs;\n\nexport const OneHot = 'OneHot';\nexport type OneHotInputs = Pick;\nexport interface OneHotAttrs {\n depth: number;\n onValue: number;\n offValue: number;\n}\n\nexport const PadV2 = 'PadV2';\nexport type PadV2Inputs = Pick;\nexport interface PadV2Attrs {\n paddings: Array<[number, number]>;\n constantValue: number;\n}\n\nexport const Pool = 'Pool';\nexport type PoolInputs = Pick;\n\nexport const Pow = 'Pow';\nexport type PowInputs = BinaryInputs;\n\nexport const Prelu = 'Prelu';\nexport type PreluInputs = Pick;\n\nexport const Prod = 'Prod';\nexport type ProdInputs = Pick;\nexport interface ProdAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const Range = 'Range';\nexport interface RangeAttrs {\n start: number;\n stop: number;\n step: number;\n dtype: 'float32'|'int32';\n}\n\nexport const Real = 'Real';\nexport type RealInputs = Pick;\n\nexport const Reciprocal = 'Reciprocal';\nexport type ReciprocalInputs = UnaryInputs;\n\nexport const Relu = 'Relu';\nexport type ReluInputs = Pick;\n\nexport const Reshape = 'Reshape';\nexport type ReshapeInputs = Pick;\nexport interface ReshapeAttrs {\n shape: number[];\n}\n\nexport const ResizeNearestNeighbor = 'ResizeNearestNeighbor';\nexport type ResizeNearestNeighborInputs = Pick;\nexport interface ResizeNearestNeighborAttrs {\n alignCorners: boolean;\n size: [number, number];\n}\n\nexport const ResizeNearestNeighborGrad = 'ResizeNearestNeighborGrad';\nexport type ResizeNearestNeighborGradInputs =\n Pick;\n\nexport const ResizeBilinear = 'ResizeBilinear';\nexport type ResizeBilinearInputs = Pick;\nexport interface ResizeBilinearAttrs {\n alignCorners: boolean;\n size: [number, number];\n}\n\nexport const ResizeBilinearGrad = 'ResizeBilinearGrad';\nexport type ResizeBilinearGradInputs = Pick;\n\nexport const Relu6 = 'Relu6';\nexport type Relu6Inputs = Pick;\n\nexport const Reverse = 'Reverse';\nexport type ReverseInputs = Pick;\nexport interface ReverseAttrs {\n dims: number|number[];\n}\n\nexport const Round = 'Round';\nexport type RoundInputs = UnaryInputs;\n\nexport const Rsqrt = 'Rsqrt';\nexport type RsqrtInputs = UnaryInputs;\n\nexport const ScatterNd = 'ScatterNd';\nexport type ScatterNdInputs = Pick;\nexport interface ScatterNdAttrs {\n shape: number[];\n}\n\nexport const SelectV2 = 'SelectV2';\nexport type SelectV2Inputs = Pick;\n\nexport const Selu = 'Selu';\nexport type SeluInputs = Pick;\n\nexport const Slice = 'Slice';\nexport type SliceInputs = Pick;\nexport interface SliceAttrs {\n begin: number|number[];\n size: number|number[];\n}\nexport const Sin = 'Sin';\nexport type SinInputs = UnaryInputs;\n\nexport const Sinh = 'Sinh';\nexport type SinhInputs = UnaryInputs;\n\nexport const Sign = 'Sign';\nexport type SignInputs = UnaryInputs;\n\nexport const Sigmoid = 'Sigmoid';\nexport type SigmoidInputs = UnaryInputs;\n\nexport const Softplus = 'Softplus';\nexport type SoftplusInputs = UnaryInputs;\n\nexport const Sqrt = 'Sqrt';\nexport type SqrtInputs = UnaryInputs;\n\nexport const Sum = 'Sum';\nexport type SumInputs = Pick;\nexport interface SumAttrs {\n axis: number|number[];\n keepDims: boolean;\n}\n\nexport const SpaceToBatchND = 'SpaceToBatchND';\nexport type SpaceToBatchNDInputs = Pick;\nexport interface SpaceToBatchNDAttrs {\n blockShape: number[];\n paddings: number[][];\n}\n\nexport const SplitV = 'SplitV';\nexport type SplitVInputs = Pick;\nexport interface SplitVAttrs {\n numOrSizeSplits: number[]|number;\n axis: number;\n}\n\nexport const Softmax = 'Softmax';\nexport type SoftmaxInputs = Pick;\nexport interface SoftmaxAttrs {\n dim: number;\n}\n\nexport const SquaredDifference = 'SquaredDifference';\nexport type SquaredDifferenceInputs = BinaryInputs;\n\nexport const Square = 'Square';\nexport type SquareInputs = Pick;\n\nexport const Sub = 'Sub';\nexport type SubInputs = BinaryInputs;\n\nexport const SparseToDense = 'SparseToDense';\nexport type SparseToDenseInputs =\n Pick;\nexport interface SparseToDenseAttrs {\n outputShape: number[];\n}\n\nexport const StridedSlice = 'StridedSlice';\nexport type StridedSliceInputs = Pick;\nexport interface StridedSliceAttrs {\n begin: number[];\n end: number[];\n strides: number[];\n beginMask: number;\n endMask: number;\n ellipsisMask: number;\n newAxisMask: number;\n shrinkAxisMask: number;\n}\n\nexport const Tan = 'Tan';\nexport type TanInputs = UnaryInputs;\n\nexport const Tanh = 'Tanh';\nexport type TanhInputs = UnaryInputs;\n\nexport const Tile = 'Tile';\nexport type TileInputs = Pick;\nexport interface TileAttrs {\n reps: number[];\n}\n\nexport const TopK = 'TopK';\nexport type TopKInputs = Pick;\nexport interface TopKAttrs {\n k: number;\n sorted: boolean;\n}\n\nexport const Transpose = 'Transpose';\nexport type TransposeInputs = Pick;\nexport interface TransposeAttrs {\n perm: number[];\n}\n\nexport const Unique = 'Unique';\nexport type UniqueInputs = Pick;\nexport interface UniqueAttrs {\n axis: number;\n}\n\nexport type UnaryInputs = Pick;\n\nexport const Unpack = 'Unpack';\nexport type UnpackInputs = Pick;\nexport interface UnpackAttrs {\n axis: number;\n}\n\nexport const UnsortedSegmentSum = 'UnsortedSegmentSum';\nexport type UnsortedSegmentSumInputs =\n Pick;\nexport interface UnsortedSegmentSumAttrs {\n numSegments: number;\n}\n\nexport const ZerosLike = 'ZerosLike';\nexport type ZerosLikeInputs = UnaryInputs;\n\n/**\n * TensorFlow.js-only kernels\n */\nexport const Step = 'Step';\nexport type StepInputs = UnaryInputs;\nexport interface StepAttrs {\n alpha: number;\n}\n\nexport const FromPixels = 'FromPixels';\nexport interface FromPixelsInputs {\n pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n HTMLVideoElement;\n}\nexport interface FromPixelsAttrs {\n numChannels: number;\n}\n\nexport const RotateWithOffset = 'RotateWithOffset';\nexport type RotateWithOffsetInputs = Pick;\nexport interface RotateWithOffsetAttrs {\n radians: number;\n fillValue: number|[number, number, number];\n center: number|[number, number];\n}\n\nexport const _FusedMatMul = '_FusedMatMul';\n// tslint:disable-next-line: class-name\nexport interface _FusedMatMulInputs extends NamedTensorInfoMap {\n a: TensorInfo;\n b: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\n// tslint:disable-next-line: class-name\nexport interface _FusedMatMulAttrs {\n transposeA: boolean;\n transposeB: boolean;\n activation: Activation;\n}\n\nexport const FusedConv2D = 'FusedConv2D';\nexport interface FusedConv2DInputs extends NamedTensorInfoMap {\n x: TensorInfo;\n filter: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\nexport interface FusedConv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number|ExplicitPadding;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode: 'floor'|'round'|'ceil';\n activation: Activation;\n}\n\nexport const FusedDepthwiseConv2D = 'FusedDepthwiseConv2D';\nexport interface FusedDepthwiseConv2DInputs extends NamedTensorInfoMap {\n x: TensorInfo;\n filter: TensorInfo;\n bias?: TensorInfo;\n preluActivationWeights?: TensorInfo;\n}\nexport interface FusedDepthwiseConv2DAttrs {\n strides: [number, number]|number;\n pad: 'valid'|'same'|number;\n dataFormat: 'NHWC'|'NCHW';\n dilations: [number, number]|number;\n dimRoundingMode: 'floor'|'round'|'ceil';\n activation: Activation;\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {env} from './environment';\n\nimport {getGlobal} from './global_util';\nimport {NamedGradientMap} from './tape';\nimport {Tensor} from './tensor';\nimport {DataType, RecursiveArray} from './types';\n\nconst kernelRegistry =\n getGlobal('kernelRegistry', () => new Map());\nconst gradRegistry =\n getGlobal('gradRegistry', () => new Map());\n\nexport type DataId = object;\n\ntype AttributeValue =\n number|number[]|boolean|boolean[]|string|string[]|NamedAttrMap;\n\n/** These are extra non-tensor/primitive params passed to kernel functions. */\nexport type Attribute = AttributeValue|RecursiveArray;\n\n/** Specifies the code to run when executing a kernel. */\nexport type KernelFunc = (params: {\n inputs: NamedTensorInfoMap,\n backend: {},\n attrs?: NamedAttrMap,\n}) => TensorInfo|TensorInfo[];\n\n/** The function to run when computing a gradient during backprop. */\nexport type GradFunc =\n (dy: Tensor|Tensor[], saved: Tensor[], attrs: NamedAttrMap) =>\n NamedGradientMap;\n\n/** Function that gets called after the backend initializes. */\nexport type KernelSetupFunc = (backend: {}) => void;\n/** Function that gets called right before the backend is disposed. */\nexport type KernelDisposeFunc = KernelSetupFunc;\n\n/** Config object for registering a kernel in the global registry. */\nexport interface KernelConfig {\n kernelName: string;\n backendName: string;\n kernelFunc: KernelFunc;\n setupFunc?: KernelSetupFunc;\n disposeFunc?: KernelDisposeFunc;\n}\n\n/** Config object for registering a gradient in the global registry. */\nexport interface GradConfig {\n kernelName: string;\n inputsToSave?: string[];\n // When saveAllInputs is true, all inputs will be saved. Only use this flag\n // if inputs is an array of Tensors.\n saveAllInputs?: boolean;\n outputsToSave?: boolean[];\n gradFunc: GradFunc;\n}\n\n/** Holds metadata for a given tensor. */\nexport interface TensorInfo {\n dataId: DataId;\n shape: number[];\n dtype: DataType;\n}\n\nexport interface NamedTensorInfoMap {\n [name: string]: TensorInfo;\n}\n\nexport interface NamedAttrMap {\n [name: string]: Attribute;\n}\n\n/**\n * Returns the kernel function (code) associated with the provided names.\n *\n * @param kernelName The official name of the kernel.\n * @param backendName The official name of the backend.\n */\nexport function getKernel(\n kernelName: string, backendName: string): KernelConfig {\n const key = makeKey(kernelName, backendName);\n return kernelRegistry.get(key);\n}\n\n/**\n * Returns the registered gradient info associated with the provided kernel.\n * @param kernelName The official TF kernel name.\n */\nexport function getGradient(kernelName: string): GradConfig {\n return gradRegistry.get(kernelName);\n}\n\nexport function getKernelsForBackend(backendName: string): KernelConfig[] {\n const it = kernelRegistry.entries();\n const result: KernelConfig[] = [];\n\n while (true) {\n const {done, value} = it.next();\n if (done) {\n break;\n }\n const [key, config] = value;\n const [backend, ] = key.split('_');\n if (backend === backendName) {\n result.push(config);\n }\n }\n return result;\n}\n\n/**\n * Registers the function (forward pass) for the kernel in a global registry.\n *\n * @param config A config object with the following properties:\n * - `kernelName` The official name of the kernel.\n * - `backendName` The official name of the backend.\n * - `kernelFunc` The function to run during the forward pass of the kernel.\n * - `setupFunc` Optional. Gets called once, after the backend initializes.\n * - `disposeFunc` Optional. Gets called once, right before the backend is\n * disposed.\n */\nexport function registerKernel(config: KernelConfig) {\n const {kernelName, backendName} = config;\n const key = makeKey(kernelName, backendName);\n if (kernelRegistry.has(key)) {\n console.warn(\n `The kernel '${kernelName}' for backend ` +\n `'${backendName}' is already registered`);\n }\n kernelRegistry.set(key, config);\n}\n\n/**\n * Registers a gradient function for a given kernel in the global registry,\n * to be used during the back-propagation of that kernel.\n *\n * @param config An object with the following properties:\n * - `kernelName` The name of the kernel that the gradient function is for.\n * - `gradFunc` The function to run during back-propagation.\n */\nexport function registerGradient(config: GradConfig) {\n const {kernelName} = config;\n\n if (gradRegistry.has(kernelName)) {\n // TODO (yassogba) after 3.0 assess whether we need to keep this gated\n // to debug mode.\n if (env().getBool('DEBUG')) {\n console.warn(`Overriding the gradient for '${kernelName}'`);\n }\n }\n gradRegistry.set(kernelName, config);\n}\n\n/**\n * Removes the kernel function from the registry.\n *\n * @param kernelName The official name of the kernel.\n * @param backendName The official name of the backend.\n *\n */\nexport function unregisterKernel(\n kernelName: string, backendName: string): void {\n const key = makeKey(kernelName, backendName);\n if (!kernelRegistry.has(key)) {\n throw new Error(\n `The kernel '${kernelName}' for backend ` +\n `'${backendName}' is not registered`);\n }\n kernelRegistry.delete(key);\n}\n\n/** Removes the registered gradient from the global registry. */\nexport function unregisterGradient(kernelName: string): void {\n if (!gradRegistry.has(kernelName)) {\n throw new Error(\n `The gradient '${kernelName}' for backend is not registered`);\n }\n gradRegistry.delete(kernelName);\n}\n\n/**\n * Finds kernels that have already been registered to a backend and re-registers\n * them for a new backend. Useful for registering custom backends.\n * @param registeredBackendName Already registered backend.\n * @param newBackendName New backend.\n */\nexport function copyRegisteredKernels(\n registeredBackendName: string, newBackendName: string): void {\n const kernels = getKernelsForBackend(registeredBackendName);\n kernels.forEach(kernelConfig => {\n const newKernelConfig =\n Object.assign({}, kernelConfig, {backendName: newBackendName});\n registerKernel(newKernelConfig);\n });\n}\n\nfunction makeKey(kernelName: string, backendName: string) {\n return `${backendName}_${kernelName}`;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from './environment';\nimport {BackendValues, DataType, DataTypeMap, FlatVector, NumericDataType, RecursiveArray, TensorLike, TypedArray} from './types';\n\n/**\n * Shuffles the array in-place using Fisher-Yates algorithm.\n *\n * ```js\n * const a = [1, 2, 3, 4, 5];\n * tf.util.shuffle(a);\n * console.log(a);\n * ```\n *\n * @param array The array to shuffle in-place.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\n// tslint:disable-next-line:no-any\nexport function shuffle(array: any[]|Uint32Array|Int32Array|\n Float32Array): void {\n let counter = array.length;\n let temp = 0;\n let index = 0;\n // While there are elements in the array\n while (counter > 0) {\n // Pick a random index\n index = (Math.random() * counter) | 0;\n // Decrease counter by 1\n counter--;\n // And swap the last element with it\n temp = array[counter];\n array[counter] = array[index];\n array[index] = temp;\n }\n}\n\n/** Clamps a value to a specified range. */\nexport function clamp(min: number, x: number, max: number): number {\n return Math.max(min, Math.min(x, max));\n}\n\nexport function nearestLargerEven(val: number): number {\n return val % 2 === 0 ? val : val + 1;\n}\n\nexport function sum(arr: number[]): number {\n let sum = 0;\n for (let i = 0; i < arr.length; i++) {\n sum += arr[i];\n }\n return sum;\n}\n\n/**\n * Returns a sample from a uniform [a, b) distribution.\n *\n * @param a The minimum support (inclusive).\n * @param b The maximum support (exclusive).\n * @return A pseudorandom number on the half-open interval [a,b).\n */\nexport function randUniform(a: number, b: number) {\n const r = Math.random();\n return (b * r) + (1 - r) * a;\n}\n\n/** Returns the squared Euclidean distance between two vectors. */\nexport function distSquared(a: FlatVector, b: FlatVector): number {\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n const diff = Number(a[i]) - Number(b[i]);\n result += diff * diff;\n }\n return result;\n}\n\n/**\n * Asserts that the expression is true. Otherwise throws an error with the\n * provided message.\n *\n * ```js\n * const x = 2;\n * tf.util.assert(x === 2, 'x is not 2');\n * ```\n *\n * @param expr The expression to assert (as a boolean).\n * @param msg A function that returns the message to report when throwing an\n * error. We use a function for performance reasons.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function assert(expr: boolean, msg: () => string) {\n if (!expr) {\n throw new Error(typeof msg === 'string' ? msg : msg());\n }\n}\n\nexport function assertShapesMatch(\n shapeA: number[], shapeB: number[], errorMessagePrefix = ''): void {\n assert(\n arraysEqual(shapeA, shapeB),\n () => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`);\n}\n\nexport function assertNonNull(a: TensorLike): void {\n assert(\n a != null,\n () => `The input to the tensor constructor must be a non-null value.`);\n}\n\n// NOTE: We explicitly type out what T extends instead of any so that\n// util.flatten on a nested array of number doesn't try to infer T as a\n// number[][], causing us to explicitly type util.flatten().\n/**\n * Flattens an arbitrarily nested array.\n *\n * ```js\n * const a = [[1, 2], [3, 4], [5, [6, [7]]]];\n * const flat = tf.util.flatten(a);\n * console.log(flat);\n * ```\n *\n * @param arr The nested array to flatten.\n * @param result The destination array which holds the elements.\n * @param skipTypedArray If true, avoids flattening the typed arrays. Defaults\n * to false.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function\nflatten|TypedArray>(\n arr: T|RecursiveArray, result: T[] = [], skipTypedArray = false): T[] {\n if (result == null) {\n result = [];\n }\n if (Array.isArray(arr) || isTypedArray(arr) && !skipTypedArray) {\n for (let i = 0; i < arr.length; ++i) {\n flatten(arr[i], result, skipTypedArray);\n }\n } else {\n result.push(arr as T);\n }\n return result;\n}\n\n/**\n * Returns the size (number of elements) of the tensor given its shape.\n *\n * ```js\n * const shape = [3, 4, 2];\n * const size = tf.util.sizeFromShape(shape);\n * console.log(size);\n * ```\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function sizeFromShape(shape: number[]): number {\n if (shape.length === 0) {\n // Scalar.\n return 1;\n }\n let size = shape[0];\n for (let i = 1; i < shape.length; i++) {\n size *= shape[i];\n }\n return size;\n}\n\nexport function isScalarShape(shape: number[]): boolean {\n return shape.length === 0;\n}\n\nexport function arraysEqual(n1: FlatVector, n2: FlatVector) {\n if (n1 === n2) {\n return true;\n }\n if (n1 == null || n2 == null) {\n return false;\n }\n\n if (n1.length !== n2.length) {\n return false;\n }\n for (let i = 0; i < n1.length; i++) {\n if (n1[i] !== n2[i]) {\n return false;\n }\n }\n return true;\n}\n\nexport function isInt(a: number): boolean {\n return a % 1 === 0;\n}\n\nexport function tanh(x: number): number {\n // tslint:disable-next-line:no-any\n if ((Math as any).tanh != null) {\n // tslint:disable-next-line:no-any\n return (Math as any).tanh(x);\n }\n if (x === Infinity) {\n return 1;\n } else if (x === -Infinity) {\n return -1;\n } else {\n const e2x = Math.exp(2 * x);\n return (e2x - 1) / (e2x + 1);\n }\n}\n\nexport function sizeToSquarishShape(size: number): [number, number] {\n const width = Math.ceil(Math.sqrt(size));\n return [width, Math.ceil(size / width)];\n}\n\n/**\n * Creates a new array with randomized indicies to a given quantity.\n *\n * ```js\n * const randomTen = tf.util.createShuffledIndices(10);\n * console.log(randomTen);\n * ```\n *\n * @param number Quantity of how many shuffled indicies to create.\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function createShuffledIndices(n: number): Uint32Array {\n const shuffledIndices = new Uint32Array(n);\n for (let i = 0; i < n; ++i) {\n shuffledIndices[i] = i;\n }\n shuffle(shuffledIndices);\n return shuffledIndices;\n}\n\nexport function rightPad(a: string, size: number): string {\n if (size <= a.length) {\n return a;\n }\n return a + ' '.repeat(size - a.length);\n}\n\nexport function repeatedTry(\n checkFn: () => boolean, delayFn = (counter: number) => 0,\n maxCounter?: number): Promise {\n return new Promise((resolve, reject) => {\n let tryCount = 0;\n\n const tryFn = () => {\n if (checkFn()) {\n resolve();\n return;\n }\n\n tryCount++;\n\n const nextBackoff = delayFn(tryCount);\n\n if (maxCounter != null && tryCount >= maxCounter) {\n reject();\n return;\n }\n setTimeout(tryFn, nextBackoff);\n };\n\n tryFn();\n });\n}\n\n/**\n * Given the full size of the array and a shape that may contain -1 as the\n * implicit dimension, returns the inferred shape where -1 is replaced.\n * E.g. For shape=[2, -1, 3] and size=24, it will return [2, 4, 3].\n *\n * @param shape The shape, which may contain -1 in some dimension.\n * @param size The full size (number of elements) of the array.\n * @return The inferred shape where -1 is replaced with the inferred size.\n */\nexport function inferFromImplicitShape(\n shape: number[], size: number): number[] {\n let shapeProd = 1;\n let implicitIdx = -1;\n\n for (let i = 0; i < shape.length; ++i) {\n if (shape[i] >= 0) {\n shapeProd *= shape[i];\n } else if (shape[i] === -1) {\n if (implicitIdx !== -1) {\n throw Error(\n `Shapes can only have 1 implicit size. ` +\n `Found -1 at dim ${implicitIdx} and dim ${i}`);\n }\n implicitIdx = i;\n } else if (shape[i] < 0) {\n throw Error(`Shapes can not be < 0. Found ${shape[i]} at dim ${i}`);\n }\n }\n\n if (implicitIdx === -1) {\n if (size > 0 && size !== shapeProd) {\n throw Error(`Size(${size}) must match the product of shape ${shape}`);\n }\n return shape;\n }\n\n if (shapeProd === 0) {\n throw Error(\n `Cannot infer the missing size in [${shape}] when ` +\n `there are 0 elements`);\n }\n if (size % shapeProd !== 0) {\n throw Error(\n `The implicit shape can't be a fractional number. ` +\n `Got ${size} / ${shapeProd}`);\n }\n\n const newShape = shape.slice();\n newShape[implicitIdx] = size / shapeProd;\n return newShape;\n}\n\nexport function parseAxisParam(\n axis: number|number[], shape: number[]): number[] {\n const rank = shape.length;\n\n // Normalize input\n axis = axis == null ? shape.map((s, i) => i) : [].concat(axis);\n\n // Check for valid range\n assert(\n axis.every(ax => ax >= -rank && ax < rank),\n () =>\n `All values in axis param must be in range [-${rank}, ${rank}) but ` +\n `got axis ${axis}`);\n\n // Check for only integers\n assert(\n axis.every(ax => isInt(ax)),\n () => `All values in axis param must be integers but ` +\n `got axis ${axis}`);\n\n // Handle negative axis.\n return axis.map(a => a < 0 ? rank + a : a);\n}\n\n/** Reduces the shape by removing all dimensions of shape 1. */\nexport function squeezeShape(shape: number[], axis?: number[]):\n {newShape: number[], keptDims: number[]} {\n const newShape: number[] = [];\n const keptDims: number[] = [];\n const isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0;\n const axes = (axis == null || isEmptyArray) ?\n null :\n parseAxisParam(axis, shape).sort();\n let j = 0;\n for (let i = 0; i < shape.length; ++i) {\n if (axes != null) {\n if (axes[j] === i && shape[i] !== 1) {\n throw new Error(\n `Can't squeeze axis ${i} since its dim '${shape[i]}' is not 1`);\n }\n if ((axes[j] == null || axes[j] > i) && shape[i] === 1) {\n newShape.push(shape[i]);\n keptDims.push(i);\n }\n if (axes[j] <= i) {\n j++;\n }\n }\n if (shape[i] !== 1) {\n newShape.push(shape[i]);\n keptDims.push(i);\n }\n }\n return {newShape, keptDims};\n}\n\nexport function getTypedArrayFromDType(\n dtype: D, size: number): DataTypeMap[D] {\n let values = null;\n if (dtype == null || dtype === 'float32') {\n values = new Float32Array(size);\n } else if (dtype === 'int32') {\n values = new Int32Array(size);\n } else if (dtype === 'bool') {\n values = new Uint8Array(size);\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n return values as DataTypeMap[D];\n}\n\nexport function getArrayFromDType(\n dtype: D, size: number): DataTypeMap[D] {\n let values = null;\n if (dtype == null || dtype === 'float32') {\n values = new Float32Array(size);\n } else if (dtype === 'int32') {\n values = new Int32Array(size);\n } else if (dtype === 'bool') {\n values = new Uint8Array(size);\n } else if (dtype === 'string') {\n values = new Array<'string'>(size);\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n return values as DataTypeMap[D];\n}\n\nexport function checkConversionForErrors(\n vals: DataTypeMap[D]|number[], dtype: D): void {\n for (let i = 0; i < vals.length; i++) {\n const num = vals[i] as number;\n if (isNaN(num) || !isFinite(num)) {\n throw Error(`A tensor of type ${dtype} being uploaded contains ${num}.`);\n }\n }\n}\n\n/** Returns true if the dtype is valid. */\nexport function isValidDtype(dtype: DataType): boolean {\n return dtype === 'bool' || dtype === 'complex64' || dtype === 'float32' ||\n dtype === 'int32' || dtype === 'string';\n}\n\n/**\n * Returns true if the new type can't encode the old type without loss of\n * precision.\n */\nexport function hasEncodingLoss(oldType: DataType, newType: DataType): boolean {\n if (newType === 'complex64') {\n return false;\n }\n if (newType === 'float32' && oldType !== 'complex64') {\n return false;\n }\n if (newType === 'int32' && oldType !== 'float32' && oldType !== 'complex64') {\n return false;\n }\n if (newType === 'bool' && oldType === 'bool') {\n return false;\n }\n return true;\n}\n\nexport function isTypedArray(a: {}): a is Float32Array|Int32Array|Uint8Array {\n return a instanceof Float32Array || a instanceof Int32Array ||\n a instanceof Uint8Array;\n}\n\nexport function bytesPerElement(dtype: DataType): number {\n if (dtype === 'float32' || dtype === 'int32') {\n return 4;\n } else if (dtype === 'complex64') {\n return 8;\n } else if (dtype === 'bool') {\n return 1;\n } else {\n throw new Error(`Unknown dtype ${dtype}`);\n }\n}\n\n/**\n * Returns the approximate number of bytes allocated in the string array - 2\n * bytes per character. Computing the exact bytes for a native string in JS is\n * not possible since it depends on the encoding of the html page that serves\n * the website.\n */\nexport function bytesFromStringArray(arr: Uint8Array[]): number {\n if (arr == null) {\n return 0;\n }\n let bytes = 0;\n arr.forEach(x => bytes += x.length);\n return bytes;\n}\n\n/** Returns true if the value is a string. */\nexport function isString(value: {}): value is string {\n return typeof value === 'string' || value instanceof String;\n}\n\nexport function isBoolean(value: {}): boolean {\n return typeof value === 'boolean';\n}\n\nexport function isNumber(value: {}): boolean {\n return typeof value === 'number';\n}\n\nexport function inferDtype(values: TensorLike): DataType {\n if (Array.isArray(values)) {\n return inferDtype(values[0]);\n }\n if (values instanceof Float32Array) {\n return 'float32';\n } else if (values instanceof Int32Array || values instanceof Uint8Array) {\n return 'int32';\n } else if (isNumber(values)) {\n return 'float32';\n } else if (isString(values)) {\n return 'string';\n } else if (isBoolean(values)) {\n return 'bool';\n }\n return 'float32';\n}\n\nexport function isFunction(f: Function) {\n return !!(f && f.constructor && f.call && f.apply);\n}\n\nexport function nearestDivisor(size: number, start: number): number {\n for (let i = start; i < size; ++i) {\n if (size % i === 0) {\n return i;\n }\n }\n return size;\n}\n\nexport function computeStrides(shape: number[]): number[] {\n const rank = shape.length;\n if (rank < 2) {\n return [];\n }\n\n // Last dimension has implicit stride of 1, thus having D-1 (instead of D)\n // strides.\n const strides = new Array(rank - 1);\n strides[rank - 2] = shape[rank - 1];\n for (let i = rank - 3; i >= 0; --i) {\n strides[i] = strides[i + 1] * shape[i + 1];\n }\n return strides;\n}\n\n/**\n * Create typed array for scalar value. Used for storing in `DataStorage`.\n */\nexport function createScalarValue(\n value: DataType, dtype: DataType): BackendValues {\n if (dtype === 'string') {\n return encodeString(value);\n }\n\n return toTypedArray([value], dtype);\n}\n\nexport function toTypedArray(a: TensorLike, dtype: DataType): TypedArray {\n if (dtype === 'string') {\n throw new Error('Cannot convert a string[] to a TypedArray');\n }\n if (Array.isArray(a)) {\n a = flatten(a);\n }\n\n if (env().getBool('DEBUG')) {\n checkConversionForErrors(a as number[], dtype);\n }\n if (noConversionNeeded(a, dtype)) {\n return a as TypedArray;\n }\n if (dtype == null || dtype === 'float32' || dtype === 'complex64') {\n return new Float32Array(a as number[]);\n } else if (dtype === 'int32') {\n return new Int32Array(a as number[]);\n } else if (dtype === 'bool') {\n const bool = new Uint8Array((a as number[]).length);\n for (let i = 0; i < bool.length; ++i) {\n if (Math.round((a as number[])[i]) !== 0) {\n bool[i] = 1;\n }\n }\n return bool;\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n}\n\nfunction createNestedArray(offset: number, shape: number[], a: TypedArray) {\n const ret = new Array();\n if (shape.length === 1) {\n const d = shape[0];\n for (let i = 0; i < d; i++) {\n ret[i] = a[offset + i];\n }\n } else {\n const d = shape[0];\n const rest = shape.slice(1);\n const len = rest.reduce((acc, c) => acc * c);\n for (let i = 0; i < d; i++) {\n ret[i] = createNestedArray(offset + i * len, rest, a);\n }\n }\n return ret;\n}\n\n// Provide a nested array of TypedArray in given shape.\nexport function toNestedArray(shape: number[], a: TypedArray) {\n if (shape.length === 0) {\n // Scalar type should return a single number.\n return a[0];\n }\n const size = shape.reduce((acc, c) => acc * c);\n if (size === 0) {\n // A tensor with shape zero should be turned into empty list.\n return [];\n }\n if (size !== a.length) {\n throw new Error(`[${shape}] does not match the input size ${a.length}.`);\n }\n\n return createNestedArray(0, shape, a);\n}\n\nfunction noConversionNeeded(a: TensorLike, dtype: DataType): boolean {\n return (a instanceof Float32Array && dtype === 'float32') ||\n (a instanceof Int32Array && dtype === 'int32') ||\n (a instanceof Uint8Array && dtype === 'bool');\n}\n\nexport function makeOnesTypedArray(\n size: number, dtype: D): DataTypeMap[D] {\n const array = makeZerosTypedArray(size, dtype);\n for (let i = 0; i < array.length; i++) {\n array[i] = 1;\n }\n return array;\n}\n\nexport function makeZerosTypedArray(\n size: number, dtype: D): DataTypeMap[D] {\n if (dtype == null || dtype === 'float32' || dtype === 'complex64') {\n return new Float32Array(size) as DataTypeMap[D];\n } else if (dtype === 'int32') {\n return new Int32Array(size) as DataTypeMap[D];\n } else if (dtype === 'bool') {\n return new Uint8Array(size) as DataTypeMap[D];\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n}\n\n/**\n * Make nested `TypedArray` filled with zeros.\n * @param shape The shape information for the nested array.\n * @param dtype dtype of the array element.\n */\nexport function makeZerosNestedTypedArray(\n shape: number[], dtype: D) {\n const size = shape.reduce((prev, curr) => prev * curr, 1);\n if (dtype == null || dtype === 'float32') {\n return toNestedArray(shape, new Float32Array(size));\n } else if (dtype === 'int32') {\n return toNestedArray(shape, new Int32Array(size));\n } else if (dtype === 'bool') {\n return toNestedArray(shape, new Uint8Array(size));\n } else {\n throw new Error(`Unknown data type ${dtype}`);\n }\n}\n\n/**\n * Returns the current high-resolution time in milliseconds relative to an\n * arbitrary time in the past. It works across different platforms (node.js,\n * browsers).\n *\n * ```js\n * console.log(tf.util.now());\n * ```\n *\n * @doc {heading: 'Util', namespace: 'util'}\n */\nexport function now(): number {\n return env().platform.now();\n}\n\nexport function assertNonNegativeIntegerDimensions(shape: number[]) {\n shape.forEach(dimSize => {\n assert(\n Number.isInteger(dimSize) && dimSize >= 0,\n () =>\n `Tensor must have a shape comprised of positive integers but got ` +\n `shape [${shape}].`);\n });\n}\n\n/**\n * Returns a platform-specific implementation of\n * [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).\n *\n * If `fetch` is defined on the global object (`window`, `process`, etc.),\n * `tf.util.fetch` returns that function.\n *\n * If not, `tf.util.fetch` returns a platform-specific solution.\n *\n * ```js\n * const resource = await tf.util.fetch('https://unpkg.com/@tensorflow/tfjs');\n * // handle response\n * ```\n *\n * @doc {heading: 'Util'}\n */\nexport function fetch(\n path: string, requestInits?: RequestInit): Promise {\n return env().platform.fetch(path, requestInits);\n}\n\n/**\n * Encodes the provided string into bytes using the provided encoding scheme.\n *\n * @param s The string to encode.\n * @param encoding The encoding scheme. Defaults to utf-8.\n *\n * @doc {heading: 'Util'}\n */\nexport function encodeString(s: string, encoding = 'utf-8'): Uint8Array {\n encoding = encoding || 'utf-8';\n return env().platform.encode(s, encoding);\n}\n\n/**\n * Decodes the provided bytes into a string using the provided encoding scheme.\n * @param bytes The bytes to decode.\n *\n * @param encoding The encoding scheme. Defaults to utf-8.\n *\n * @doc {heading: 'Util'}\n */\nexport function decodeString(bytes: Uint8Array, encoding = 'utf-8'): string {\n encoding = encoding || 'utf-8';\n return env().platform.decode(bytes, encoding);\n}\n\n/**\n * Computes flat index for a given location (multidimentionsal index) in a\n * Tensor/multidimensional array.\n *\n * @param locs Location in the tensor.\n * @param rank Rank of the tensor.\n * @param strides Tensor strides.\n */\nexport function locToIndex(\n locs: number[], rank: number, strides: number[]): number {\n if (rank === 0) {\n return 0;\n } else if (rank === 1) {\n return locs[0];\n }\n let index = locs[locs.length - 1];\n for (let i = 0; i < locs.length - 1; ++i) {\n index += strides[i] * locs[i];\n }\n return index;\n}\n\n/**\n * Computes the location (multidimensional index) in a tensor/multidimentional\n * array for a given flat index.\n *\n * @param index Index in flat array.\n * @param rank Rank of tensor.\n * @param strides Strides of tensor.\n */\nexport function indexToLoc(\n index: number, rank: number, strides: number[]): number[] {\n if (rank === 0) {\n return [];\n } else if (rank === 1) {\n return [index];\n }\n const locs: number[] = new Array(rank);\n for (let i = 0; i < locs.length - 1; ++i) {\n locs[i] = Math.floor(index / strides[i]);\n index -= locs[i] * strides[i];\n }\n locs[locs.length - 1] = index;\n return locs;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendTimer} from './backends/backend';\nimport {Tensor} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport {DataType, DataTypeMap, TypedArray} from './types';\nimport * as util from './util';\n\nexport type KernelProfile = {\n kernelName: string,\n outputs: Tensor[],\n inputs: NamedTensorMap,\n timeMs: Promise,\n extraInfo: Promise\n};\n\nexport class Profiler {\n constructor(private backendTimer: BackendTimer, private logger?: Logger) {\n if (logger == null) {\n this.logger = new Logger();\n }\n }\n\n profileKernel(kernelName: string, inputs: NamedTensorMap, f: () => Tensor[]):\n KernelProfile {\n let outputs: Tensor[];\n const holdResultWrapperFn = () => {\n outputs = f();\n };\n const timer = this.backendTimer.time(holdResultWrapperFn);\n\n for (let i = 0; i < outputs.length; i++) {\n const output = outputs[i];\n // Dangling promise here because we don't want to propagate up\n // asynchronicity.\n output.data().then(tensorVals => {\n checkComputationForErrors(tensorVals, output.dtype, kernelName);\n });\n }\n\n const kernelProfile = {\n kernelName,\n outputs,\n inputs,\n timeMs: timer.then(timing => timing.kernelMs),\n extraInfo: timer.then(\n timing => timing.getExtraProfileInfo != null ?\n timing.getExtraProfileInfo() :\n '')\n };\n return kernelProfile;\n }\n\n logKernelProfile(kernelProfile: KernelProfile): void {\n const {kernelName, outputs, timeMs, inputs, extraInfo} = kernelProfile;\n\n outputs.forEach(result => {\n Promise.all([result.data(), timeMs, extraInfo]).then(valueContainer => {\n this.logger.logKernelProfile(\n kernelName, result, valueContainer[0], valueContainer[1], inputs,\n valueContainer[2]);\n });\n });\n }\n}\n\nexport function checkComputationForErrors(\n vals: DataTypeMap[D], dtype: D, kernelName: string): boolean {\n if (dtype !== 'float32') {\n // Only floating point computations will generate NaN values\n return false;\n }\n for (let i = 0; i < vals.length; i++) {\n const num = vals[i] as number;\n if (isNaN(num) || !isFinite(num)) {\n // Throwing custom exception so behavior is testable.\n console.warn(`Found ${num} in the result of '${kernelName}'`);\n return true;\n }\n }\n return false;\n}\n\nexport class Logger {\n logKernelProfile(\n name: string, result: Tensor, vals: TypedArray,\n timeMs: number|{error: string}, inputs: NamedTensorMap,\n extraInfo?: string) {\n const time = typeof timeMs === 'number' ? util.rightPad(`${timeMs}ms`, 9) :\n timeMs['error'];\n const paddedName = util.rightPad(name, 25);\n const rank = result.rank;\n const size = result.size;\n const shape = util.rightPad(result.shape.toString(), 14);\n let inputShapesDescription = '';\n\n for (const name in inputs) {\n const input = inputs[name];\n if (input != null) {\n // The input might be a non-tensor (e.g HTMLImageElement), in which case\n // we claim the output shape as input shape.\n const inputShape = input.shape || result.shape;\n const inputRank = inputShape.length;\n inputShapesDescription +=\n `${name}: ${inputRank}D ${inputRank > 0 ? inputShape : ''} `;\n }\n }\n\n console.log(\n `%c${paddedName}\\t%c${time}\\t%c${rank}D ${shape}\\t%c${size}\\t%c${\n inputShapesDescription}\\t%c${extraInfo}`,\n 'font-weight:bold', 'color:red', 'color:blue', 'color: orange',\n 'color: green', 'color: steelblue');\n }\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from './tensor';\nimport {NamedTensorMap} from './tensor_types';\nimport * as util from './util';\n\nexport interface TapeNode {\n id: number;\n kernelName: string;\n outputs: Tensor[];\n inputs: NamedTensorMap;\n // Optional params, defined only for ops with gradient impl.\n gradient?: (dys: Tensor[]) => NamedGradientMap;\n saved?: Tensor[];\n}\n\nexport type NamedGradientMap = {\n [inputName: string]: () => Tensor;\n};\n\n/**\n * Computes a list of TapeNodes that connect x to y, filtering everything else\n * out and preserving the order of the original tape elements.\n *\n * @param tape The tape elements to filter.\n * @param xs The input Tensors.\n * @param y The output Tensor.\n */\nexport function getFilteredNodesXToY(\n tape: TapeNode[], xs: Tensor[], y: Tensor): TapeNode[] {\n // Forward pass to compute all the nodes and Tensors that are transitively a\n // function of x.\n const tensorsFromX: {[tensorId: number]: boolean} = {};\n const nodesFromX: {[nodeId: number]: boolean} = {};\n for (let i = 0; i < xs.length; i++) {\n tensorsFromX[xs[i].id] = true;\n }\n\n for (let i = 0; i < tape.length; i++) {\n const node = tape[i];\n const nodeInputs = node.inputs;\n for (const inputName in nodeInputs) {\n const input = nodeInputs[inputName];\n\n let anyInputFromX = false;\n for (let j = 0; j < xs.length; j++) {\n if (tensorsFromX[input.id]) {\n node.outputs.forEach(output => tensorsFromX[output.id] = true);\n anyInputFromX = true;\n nodesFromX[node.id] = true;\n break;\n }\n }\n\n if (anyInputFromX) {\n break;\n }\n }\n }\n\n // Backward pass to find all of the nodes and Tensors that lead to y.\n const tensorsLeadToY: {[tensorId: number]: boolean} = {};\n tensorsLeadToY[y.id] = true;\n const nodesToY: {[nodeId: number]: boolean} = {};\n\n for (let i = tape.length - 1; i >= 0; i--) {\n const node = tape[i];\n const nodeInputs = node.inputs;\n\n // If any of the outputs lead to y, mark all of the inputs as leading to y.\n for (let j = 0; j < node.outputs.length; j++) {\n if (tensorsLeadToY[node.outputs[j].id]) {\n for (const inputName in nodeInputs) {\n tensorsLeadToY[nodeInputs[inputName].id] = true;\n nodesToY[node.id] = true;\n }\n break;\n }\n }\n }\n\n // Return the paths that come from x and lead to y.\n const filteredTape: TapeNode[] = [];\n for (let i = 0; i < tape.length; i++) {\n const node = tape[i];\n\n if (nodesFromX[node.id] && nodesToY[node.id]) {\n // Prune the inputs from the node that aren't a function of x.\n const prunedInputs: {[inputName: string]: Tensor} = {};\n for (const inputName in node.inputs) {\n const nodeInput = node.inputs[inputName];\n if (tensorsFromX[nodeInput.id]) {\n prunedInputs[inputName] = nodeInput;\n }\n }\n\n // Copy the node and overwrite inputsAndArgs to the pruned version.\n const prunedNode = Object.assign({}, node);\n prunedNode.inputs = prunedInputs;\n prunedNode.outputs = node.outputs;\n\n filteredTape.push(prunedNode);\n }\n }\n\n return filteredTape;\n}\n\n/**\n * Backpropagate gradients through the filtered TapeNodes.\n *\n * @param tensorAccumulatedGradientMap A map of Tensor to its gradient. This map\n * is mutated by this method.\n * @param filteredTape The filtered TapeNodes to backprop through.\n */\nexport function backpropagateGradients(\n tensorAccumulatedGradientMap: {[tensorId: number]: Tensor},\n filteredTape: TapeNode[], tidy: (f: Function) => Tensor,\n add: (a: Tensor, b: Tensor) => Tensor) {\n // Walk the tape backward and keep a map of Tensor to its gradient.\n for (let i = filteredTape.length - 1; i >= 0; i--) {\n const node = filteredTape[i];\n\n const dys: Tensor[] = [];\n node.outputs.forEach(o => {\n const gradTensor = tensorAccumulatedGradientMap[o.id];\n if (gradTensor != null) {\n dys.push(gradTensor);\n } else {\n // This particular output is not in the back-propagation subgraph, so it\n // does not affect the final output, thus we put null for its dy.\n dys.push(null);\n }\n });\n\n if (node.gradient == null) {\n throw new Error(\n `Cannot compute gradient: gradient function not found ` +\n `for ${node.kernelName}.`);\n }\n\n // Backprop dy through this node and accumulate gradients over the inputs.\n const inputGradients = node.gradient(dys);\n\n for (const inputName in node.inputs) {\n if (!(inputName in inputGradients)) {\n throw new Error(\n `Cannot backprop through input ${inputName}. ` +\n `Available gradients found: ${Object.keys(inputGradients)}.`);\n }\n\n // Call the gradient function.\n const dx = tidy(() => inputGradients[inputName]());\n if (dx.dtype !== 'float32') {\n throw new Error(\n `Error in gradient for op ${\n node.kernelName}. The gradient of input ` +\n `${inputName} must have 'float32' dtype, but has '${dx.dtype}'`);\n }\n const x = node.inputs[inputName];\n if (!util.arraysEqual(dx.shape, x.shape)) {\n throw new Error(\n `Error in gradient for op ${\n node.kernelName}. The gradient of input ` +\n `'${inputName}' has shape '${dx.shape}', which does not match ` +\n `the shape of the input '${x.shape}'`);\n }\n\n if (tensorAccumulatedGradientMap[x.id] == null) {\n tensorAccumulatedGradientMap[x.id] = dx;\n } else {\n const curGradient = tensorAccumulatedGradientMap[x.id];\n tensorAccumulatedGradientMap[x.id] = add(curGradient, dx);\n curGradient.dispose();\n }\n }\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {DataType, TypedArray} from './types';\nimport {computeStrides, isString, rightPad, sizeFromShape} from './util';\n\n// Maximum number of values before we decide to show ellipsis.\nconst FORMAT_LIMIT_NUM_VALS = 20;\n// Number of first and last values to show when displaying a, b,...,y, z.\nconst FORMAT_NUM_FIRST_LAST_VALS = 3;\n// Number of significant digits to show.\nconst FORMAT_NUM_SIG_DIGITS = 7;\n\nexport function tensorToString(\n vals: TypedArray|string[], shape: number[], dtype: DataType,\n verbose: boolean) {\n const strides = computeStrides(shape);\n const padPerCol = computeMaxSizePerColumn(vals, shape, dtype, strides);\n const rank = shape.length;\n const valsLines = subTensorToString(vals, shape, dtype, strides, padPerCol);\n const lines = ['Tensor'];\n if (verbose) {\n lines.push(` dtype: ${dtype}`);\n lines.push(` rank: ${rank}`);\n lines.push(` shape: [${shape}]`);\n lines.push(` values:`);\n }\n lines.push(valsLines.map(l => ' ' + l).join('\\n'));\n return lines.join('\\n');\n}\n\nfunction computeMaxSizePerColumn(\n vals: TypedArray|string[], shape: number[], dtype: DataType,\n strides: number[]): number[] {\n const n = sizeFromShape(shape);\n const numCols = strides[strides.length - 1];\n const padPerCol = new Array(numCols).fill(0);\n const rank = shape.length;\n const valuesOrTuples =\n dtype === 'complex64' ? createComplexTuples(vals) : vals;\n\n if (rank > 1) {\n for (let row = 0; row < n / numCols; row++) {\n const offset = row * numCols;\n for (let j = 0; j < numCols; j++) {\n padPerCol[j] = Math.max(\n padPerCol[j],\n valToString(valuesOrTuples[offset + j], 0, dtype).length);\n }\n }\n }\n return padPerCol;\n}\n\nfunction valToString(\n val: number|string|[number, number], pad: number, dtype: DataType) {\n let valStr: string;\n if (Array.isArray(val)) {\n valStr = `${parseFloat(val[0].toFixed(FORMAT_NUM_SIG_DIGITS))} + ` +\n `${parseFloat(val[1].toFixed(FORMAT_NUM_SIG_DIGITS))}j`;\n } else if (isString(val)) {\n valStr = `'${val}'`;\n } else if (dtype === 'bool') {\n valStr = boolNumToString(val);\n } else {\n valStr = parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString();\n }\n\n return rightPad(valStr, pad);\n}\n\nfunction boolNumToString(v: number): string {\n return v === 0 ? 'false' : 'true';\n}\n\nfunction subTensorToString(\n vals: TypedArray|string[], shape: number[], dtype: DataType,\n strides: number[], padPerCol: number[], isLast = true): string[] {\n const storagePerElement = dtype === 'complex64' ? 2 : 1;\n\n const size = shape[0];\n const rank = shape.length;\n if (rank === 0) {\n if (dtype === 'complex64') {\n const complexTuple = createComplexTuples(vals);\n return [valToString(complexTuple[0], 0, dtype)];\n }\n if (dtype === 'bool') {\n return [boolNumToString(vals[0] as number)];\n }\n return [vals[0].toString()];\n }\n\n if (rank === 1) {\n if (size > FORMAT_LIMIT_NUM_VALS) {\n const firstValsSize = FORMAT_NUM_FIRST_LAST_VALS * storagePerElement;\n\n let firstVals = Array.from(\n vals.slice(0, firstValsSize));\n let lastVals = Array.from(vals.slice(\n (size - FORMAT_NUM_FIRST_LAST_VALS) * storagePerElement,\n size * storagePerElement));\n if (dtype === 'complex64') {\n firstVals = createComplexTuples(firstVals);\n lastVals = createComplexTuples(lastVals);\n }\n return [\n '[' +\n firstVals.map((x, i) => valToString(x, padPerCol[i], dtype))\n .join(', ') +\n ', ..., ' +\n lastVals\n .map(\n (x, i) => valToString(\n x, padPerCol[size - FORMAT_NUM_FIRST_LAST_VALS + i], dtype))\n .join(', ') +\n ']'\n ];\n }\n const displayVals: Array =\n dtype === 'complex64' ? createComplexTuples(vals) :\n Array.from(vals);\n\n return [\n '[' +\n displayVals.map((x, i) => valToString(x, padPerCol[i], dtype))\n .join(', ') +\n ']'\n ];\n }\n\n // The array is rank 2 or more.\n const subshape = shape.slice(1);\n const substrides = strides.slice(1);\n const stride = strides[0] * storagePerElement;\n const lines: string[] = [];\n if (size > FORMAT_LIMIT_NUM_VALS) {\n for (let i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) {\n const start = i * stride;\n const end = start + stride;\n lines.push(...subTensorToString(\n vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n false /* isLast */));\n }\n lines.push('...');\n for (let i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) {\n const start = i * stride;\n const end = start + stride;\n lines.push(...subTensorToString(\n vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n i === size - 1 /* isLast */));\n }\n } else {\n for (let i = 0; i < size; i++) {\n const start = i * stride;\n const end = start + stride;\n lines.push(...subTensorToString(\n vals.slice(start, end), subshape, dtype, substrides, padPerCol,\n i === size - 1 /* isLast */));\n }\n }\n const sep = rank === 2 ? ',' : '';\n lines[0] = '[' + lines[0] + sep;\n for (let i = 1; i < lines.length - 1; i++) {\n lines[i] = ' ' + lines[i] + sep;\n }\n let newLineSep = ',\\n';\n for (let i = 2; i < rank; i++) {\n newLineSep += '\\n';\n }\n lines[lines.length - 1] =\n ' ' + lines[lines.length - 1] + ']' + (isLast ? '' : newLineSep);\n return lines;\n}\n\nfunction createComplexTuples(vals: Array<{}>|\n TypedArray): Array<[number, number]> {\n const complexTuples: Array<[number, number]> = [];\n for (let i = 0; i < vals.length; i += 2) {\n complexTuples.push([vals[i], vals[i + 1]] as [number, number]);\n }\n return complexTuples;\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {tensorToString} from './tensor_format';\nimport {ArrayMap, BackendValues, DataType, DataTypeMap, DataValues, NumericDataType, Rank, ShapeMap, SingleValueMap, TypedArray} from './types';\nimport * as util from './util';\nimport {computeStrides, toNestedArray} from './util';\n\nexport interface TensorData {\n dataId?: DataId;\n values?: DataTypeMap[D];\n}\n\n// This interface mimics KernelBackend (in backend.ts), which would create a\n// circular dependency if imported.\nexport interface Backend {}\n\n/**\n * A mutable object, similar to `tf.Tensor`, that allows users to set values\n * at locations before converting to an immutable `tf.Tensor`.\n *\n * See `tf.buffer` for creating a tensor buffer.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class TensorBuffer {\n size: number;\n shape: ShapeMap[R];\n strides: number[];\n values: DataTypeMap[D];\n\n constructor(shape: ShapeMap[R], public dtype: D, values?: DataTypeMap[D]) {\n this.shape = shape.slice() as ShapeMap[R];\n this.size = util.sizeFromShape(shape);\n\n if (values != null) {\n const n = values.length;\n util.assert(\n n === this.size,\n () => `Length of values '${n}' does not match the size ` +\n `inferred by the shape '${this.size}'.`);\n }\n if (dtype === 'complex64') {\n throw new Error(\n `complex64 dtype TensorBuffers are not supported. Please create ` +\n `a TensorBuffer for the real and imaginary parts separately and ` +\n `call tf.complex(real, imag).`);\n }\n this.values = values || util.getArrayFromDType(dtype, this.size);\n this.strides = computeStrides(shape);\n }\n\n /**\n * Sets a value in the buffer at a given location.\n *\n * @param value The value to set.\n * @param locs The location indices.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\n set(value: SingleValueMap[D], ...locs: number[]): void {\n if (locs.length === 0) {\n locs = [0];\n }\n util.assert(\n locs.length === this.rank,\n () => `The number of provided coordinates (${locs.length}) must ` +\n `match the rank (${this.rank})`);\n\n const index = this.locToIndex(locs);\n this.values[index] = value as number;\n }\n\n /**\n * Returns the value in the buffer at the provided location.\n *\n * @param locs The location indices.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\n get(...locs: number[]): SingleValueMap[D] {\n if (locs.length === 0) {\n locs = [0];\n }\n let i = 0;\n for (const loc of locs) {\n if (loc < 0 || loc >= this.shape[i]) {\n const msg = `Requested out of range element at ${locs}. ` +\n ` Buffer shape=${this.shape}`;\n throw new Error(msg);\n }\n i++;\n }\n let index = locs[locs.length - 1];\n for (let i = 0; i < locs.length - 1; ++i) {\n index += this.strides[i] * locs[i];\n }\n return this.values[index] as SingleValueMap[D];\n }\n\n locToIndex(locs: number[]): number {\n if (this.rank === 0) {\n return 0;\n } else if (this.rank === 1) {\n return locs[0];\n }\n let index = locs[locs.length - 1];\n for (let i = 0; i < locs.length - 1; ++i) {\n index += this.strides[i] * locs[i];\n }\n return index;\n }\n\n indexToLoc(index: number): number[] {\n if (this.rank === 0) {\n return [];\n } else if (this.rank === 1) {\n return [index];\n }\n const locs: number[] = new Array(this.shape.length);\n for (let i = 0; i < locs.length - 1; ++i) {\n locs[i] = Math.floor(index / this.strides[i]);\n index -= locs[i] * this.strides[i];\n }\n locs[locs.length - 1] = index;\n return locs;\n }\n\n get rank() {\n return this.shape.length;\n }\n\n /**\n * Creates an immutable `tf.Tensor` object from the buffer.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\n toTensor(): Tensor {\n return trackerFn().makeTensor(this.values, this.shape, this.dtype) as\n Tensor;\n }\n}\n\nexport interface TensorTracker {\n makeTensor(\n values: DataValues, shape: number[], dtype: DataType,\n backend?: Backend): Tensor;\n makeVariable(\n initialValue: Tensor, trainable?: boolean, name?: string,\n dtype?: DataType): Variable;\n incRef(a: Tensor, backend: Backend): void;\n disposeTensor(t: Tensor): void;\n disposeVariable(v: Variable): void;\n read(dataId: DataId): Promise;\n readSync(dataId: DataId): BackendValues;\n}\n\n/**\n * The Tensor class calls into this handler to delegate chaining operations.\n */\nexport interface OpHandler {\n cast(x: T, dtype: DataType): T;\n buffer(\n shape: ShapeMap[R], dtype: D,\n values?: DataTypeMap[D]): TensorBuffer;\n print(x: T, verbose: boolean): void;\n clone(x: T): T;\n // TODO(yassogba) bring reshape back?\n}\n\n// For tracking tensor creation and disposal.\nlet trackerFn: () => TensorTracker = null;\n// Used by chaining methods to call into ops.\nlet opHandler: OpHandler = null;\n// Used to warn about deprecated methods.\nlet deprecationWarningFn: (msg: string) => void = null;\n// This here so that we can use this method on dev branches and keep the\n// functionality at master.\n// tslint:disable-next-line:no-unused-expression\n[deprecationWarningFn];\n\n/**\n * An external consumer can register itself as the tensor tracker. This way\n * the Tensor class can notify the tracker for every tensor created and\n * disposed.\n */\nexport function setTensorTracker(fn: () => TensorTracker) {\n trackerFn = fn;\n}\n\n/**\n * An external consumer can register itself as the op handler. This way the\n * Tensor class can have chaining methods that call into ops via the op\n * handler.\n */\nexport function setOpHandler(handler: OpHandler) {\n opHandler = handler;\n}\n\n/**\n * Sets the deprecation warning function to be used by this file. This way the\n * Tensor class can be a leaf but still use the environment.\n */\nexport function setDeprecationWarningFn(fn: (msg: string) => void) {\n deprecationWarningFn = fn;\n}\n\n/**\n * We wrap data id since we use weak map to avoid memory leaks.\n * Since we have our own memory management, we have a reference counter\n * mapping a tensor to its data, so there is always a pointer (even if that\n * data is otherwise garbage collectable).\n * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/\n * Global_Objects/WeakMap\n */\nexport type DataId = object; // object instead of {} to force non-primitive.\n\n// Declare this namespace to make Tensor class augmentation work in google3.\nexport declare namespace Tensor {}\n/**\n * A `tf.Tensor` object represents an immutable, multidimensional array of\n * numbers that has a shape and a data type.\n *\n * See `tf.tensor` for details on how to create a `tf.Tensor`.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class Tensor {\n /** Unique id of this tensor. */\n readonly id: number;\n /**\n * Id of the bucket holding the data for this tensor. Multiple arrays can\n * point to the same bucket (e.g. when calling array.reshape()).\n */\n dataId: DataId;\n /** The shape of the tensor. */\n readonly shape: ShapeMap[R];\n /** Number of elements in the tensor. */\n readonly size: number;\n /** The data type for the array. */\n readonly dtype: DataType;\n /** The rank type for the array (see `Rank` enum). */\n readonly rankType: R;\n\n /** Whether this tensor has been globally kept. */\n kept = false;\n /** The id of the scope this tensor is being tracked in. */\n scopeId: number;\n\n /**\n * Number of elements to skip in each dimension when indexing. See\n * https://docs.scipy.org/doc/numpy/reference/generated/\\\n * numpy.ndarray.strides.html\n */\n readonly strides: number[];\n\n constructor(shape: ShapeMap[R], dtype: DataType, dataId: DataId, id: number) {\n this.shape = shape.slice() as ShapeMap[R];\n this.dtype = dtype || 'float32';\n this.size = util.sizeFromShape(shape);\n this.strides = computeStrides(shape);\n this.dataId = dataId;\n this.id = id;\n this.rankType = (this.rank < 5 ? this.rank.toString() : 'higher') as R;\n }\n\n get rank(): number {\n return this.shape.length;\n }\n\n /**\n * Returns a promise of `tf.TensorBuffer` that holds the underlying data.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n async buffer(): Promise> {\n const vals = await this.data();\n return opHandler.buffer(this.shape, this.dtype as D, vals);\n }\n\n /**\n * Returns a `tf.TensorBuffer` that holds the underlying data.\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n bufferSync(): TensorBuffer {\n return opHandler.buffer(this.shape, this.dtype as D, this.dataSync());\n }\n\n /**\n * Returns the tensor data as a nested array. The transfer of data is done\n * asynchronously.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n async array(): Promise {\n const vals = await this.data();\n return toNestedArray(this.shape, vals) as ArrayMap[R];\n }\n\n /**\n * Returns the tensor data as a nested array. The transfer of data is done\n * synchronously.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n arraySync(): ArrayMap[R] {\n return toNestedArray(this.shape, this.dataSync()) as ArrayMap[R];\n }\n\n /**\n * Asynchronously downloads the values from the `tf.Tensor`. Returns a\n * promise of `TypedArray` that resolves when the computation has finished.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n async data(): Promise {\n this.throwIfDisposed();\n const data = trackerFn().read(this.dataId);\n if (this.dtype === 'string') {\n const bytes = await data as Uint8Array[];\n try {\n return bytes.map(b => util.decodeString(b)) as DataTypeMap[D];\n } catch {\n throw new Error(\n 'Failed to decode the string bytes into utf-8. ' +\n 'To get the original bytes, call tensor.bytes().');\n }\n }\n return data as Promise;\n }\n\n /**\n * Synchronously downloads the values from the `tf.Tensor`. This blocks the\n * UI thread until the values are ready, which can cause performance issues.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n dataSync(): DataTypeMap[D] {\n this.throwIfDisposed();\n const data = trackerFn().readSync(this.dataId);\n if (this.dtype === 'string') {\n try {\n return (data as Uint8Array[]).map(b => util.decodeString(b)) as\n DataTypeMap[D];\n } catch {\n throw new Error(\n 'Failed to decode the string bytes into utf-8. ' +\n 'To get the original bytes, call tensor.bytes().');\n }\n }\n return data as DataTypeMap[D];\n }\n\n /** Returns the underlying bytes of the tensor's data. */\n async bytes(): Promise {\n this.throwIfDisposed();\n const data = await trackerFn().read(this.dataId);\n if (this.dtype === 'string') {\n return data as Uint8Array[];\n } else {\n return new Uint8Array((data as TypedArray).buffer);\n }\n }\n\n /**\n * Disposes `tf.Tensor` from memory.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n trackerFn().disposeTensor(this);\n this.isDisposedInternal = true;\n }\n\n protected isDisposedInternal = false;\n get isDisposed(): boolean {\n return this.isDisposedInternal;\n }\n\n throwIfDisposed() {\n if (this.isDisposed) {\n throw new Error(`Tensor is disposed.`);\n }\n }\n\n /**\n * Prints the `tf.Tensor`. See `tf.print` for details.\n *\n * @param verbose Whether to print verbose information about the tensor,\n * including dtype and size.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n print(verbose = false): void {\n return opHandler.print(this, verbose);\n }\n\n /**\n * Returns a copy of the tensor. See `tf.clone` for details.\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n clone(this: T): T {\n this.throwIfDisposed();\n return opHandler.clone(this);\n }\n\n /**\n * Returns a human-readable description of the tensor. Useful for logging.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n toString(verbose = false): string {\n const vals = this.dataSync();\n return tensorToString(vals, this.shape, this.dtype, verbose);\n }\n\n cast(dtype: DataType): T {\n this.throwIfDisposed();\n return opHandler.cast(this as T, dtype);\n }\n variable(trainable = true, name?: string, dtype?: DataType): Variable {\n this.throwIfDisposed();\n return trackerFn().makeVariable(this, trainable, name, dtype) as\n Variable;\n }\n}\nObject.defineProperty(Tensor, Symbol.hasInstance, {\n value: (instance: Tensor) => {\n // Implementation note: we should use properties of the object that will be\n // defined before the constructor body has finished executing (methods).\n // This is because when this code is transpiled by babel, babel will call\n // classCallCheck before the constructor body is run.\n // See https://github.com/tensorflow/tfjs/issues/3384 for backstory.\n return !!instance && instance.data != null && instance.dataSync != null &&\n instance.throwIfDisposed != null;\n }\n});\n\nexport interface NumericTensor extends Tensor {\n dtype: NumericDataType;\n dataSync(): DataTypeMap[D];\n data(): Promise;\n}\n\nexport interface StringTensor extends Tensor {\n dtype: 'string';\n dataSync(): DataTypeMap[D];\n data(): Promise;\n}\n\n/** @doclink Tensor */\nexport type Scalar = Tensor;\n/** @doclink Tensor */\nexport type Tensor1D = Tensor;\n/** @doclink Tensor */\nexport type Tensor2D = Tensor;\n/** @doclink Tensor */\nexport type Tensor3D = Tensor;\n/** @doclink Tensor */\nexport type Tensor4D = Tensor;\n/** @doclink Tensor */\nexport type Tensor5D = Tensor;\n/** @doclink Tensor */\nexport type Tensor6D = Tensor;\n\n/**\n * A mutable `tf.Tensor`, useful for persisting state, e.g. for training.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\nexport class Variable extends Tensor {\n name: string;\n\n constructor(\n initialValue: Tensor, public trainable: boolean, name: string,\n tensorId: number) {\n super(\n initialValue.shape, initialValue.dtype, initialValue.dataId, tensorId);\n this.name = name;\n }\n\n /**\n * Assign a new `tf.Tensor` to this variable. The new `tf.Tensor` must have\n * the same shape and dtype as the old `tf.Tensor`.\n *\n * @param newValue New tensor to be assigned to this variable.\n *\n * @doc {heading: 'Tensors', subheading: 'Classes'}\n */\n assign(newValue: Tensor): void {\n if (newValue.dtype !== this.dtype) {\n throw new Error(\n `dtype of the new value (${newValue.dtype}) and ` +\n `previous value (${this.dtype}) must match`);\n }\n if (!util.arraysEqual(newValue.shape, this.shape)) {\n throw new Error(\n `shape of the new value (${newValue.shape}) and ` +\n `previous value (${this.shape}) must match`);\n }\n trackerFn().disposeTensor(this);\n this.dataId = newValue.dataId;\n trackerFn().incRef(this, null /* backend */);\n }\n\n dispose(): void {\n trackerFn().disposeVariable(this);\n this.isDisposedInternal = true;\n }\n}\n\nObject.defineProperty(Variable, Symbol.hasInstance, {\n value: (instance: Variable) => {\n return instance instanceof Tensor && instance.assign != null &&\n instance.assign instanceof Function;\n }\n});\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/** @docalias number[] */\nexport interface ShapeMap {\n R0: number[];\n R1: [number];\n R2: [number, number];\n R3: [number, number, number];\n R4: [number, number, number, number];\n R5: [number, number, number, number, number];\n R6: [number, number, number, number, number, number];\n}\n\n/** @docalias number[] */\nexport interface ArrayMap {\n R0: number;\n R1: number[];\n R2: number[][];\n R3: number[][][];\n R4: number[][][][];\n R5: number[][][][][];\n R6: number[][][][][][];\n}\n\nexport interface DataTypeMap {\n float32: Float32Array;\n int32: Int32Array;\n bool: Uint8Array;\n complex64: Float32Array;\n string: string[];\n}\n\nexport interface SingleValueMap {\n bool: boolean;\n int32: number;\n float32: number;\n complex64: number;\n string: string;\n}\n\n/** @docalias 'float32'|'int32'|'bool'|'complex64'|'string' */\nexport type DataType = keyof DataTypeMap;\nexport type NumericDataType = 'float32'|'int32'|'bool'|'complex64';\nexport type TypedArray = Float32Array|Int32Array|Uint8Array;\n/** Tensor data used in tensor creation and user-facing API. */\nexport type DataValues = DataTypeMap[DataType];\n/** The underlying tensor data that gets stored in a backend. */\nexport type BackendValues = Float32Array|Int32Array|Uint8Array|Uint8Array[];\n\nexport enum Rank {\n R0 = 'R0',\n R1 = 'R1',\n R2 = 'R2',\n R3 = 'R3',\n R4 = 'R4',\n R5 = 'R5',\n R6 = 'R6'\n}\n\nexport type FlatVector = boolean[]|number[]|TypedArray;\nexport type RegularArray =\n T[]|T[][]|T[][][]|T[][][][]|T[][][][][]|T[][][][][][];\n\n// tslint:disable-next-line:no-any\nexport interface RecursiveArray {\n [index: number]: T|RecursiveArray;\n}\n\n// Looks for upcasting types. Used, for example, in operations with mixed dtype\n// inputs.\nenum UpcastInt32AndMap {\n 'float32' = 'float32',\n 'int32' = 'int32',\n 'bool' = 'int32',\n 'complex64' = 'complex64'\n}\n\nenum UpcastBoolAndMap {\n 'float32' = 'float32',\n 'int32' = 'int32',\n 'bool' = 'bool',\n 'complex64' = 'complex64'\n}\n\nenum UpcastFloat32AndMap {\n 'float32' = 'float32',\n 'int32' = 'float32',\n 'bool' = 'float32',\n 'complex64' = 'complex64'\n}\n\nenum UpcastComplex64AndMap {\n 'float32' = 'complex64',\n 'int32' = 'complex64',\n 'bool' = 'complex64',\n 'complex64' = 'complex64'\n}\n\nconst upcastTypeMap = {\n 'float32': UpcastFloat32AndMap,\n 'int32': UpcastInt32AndMap,\n 'bool': UpcastBoolAndMap,\n 'complex64': UpcastComplex64AndMap\n};\n\nexport function upcastType(typeA: DataType, typeB: DataType): DataType {\n if (typeA === 'string' || typeB === 'string') {\n if (typeA === 'string' && typeB === 'string') {\n return 'string';\n }\n throw new Error(`Can not upcast ${typeA} with ${typeB}`);\n }\n return upcastTypeMap[typeA][typeB];\n}\n\n/** Returns the output type after summation. */\nexport function sumOutType(type: DataType): DataType {\n return upcastType(type, 'int32');\n}\n\n/** @docalias TypedArray|Array */\nexport type TensorLike =\n TypedArray|number|boolean|string|RecursiveArray|\n RecursiveArray|RecursiveArray|Uint8Array[];\nexport type ScalarLike = number|boolean|string|Uint8Array;\n/** @docalias TypedArray|Array */\nexport type TensorLike1D = TypedArray|number[]|boolean[]|string[]|Uint8Array[];\n/** @docalias TypedArray|Array */\nexport type TensorLike2D = TypedArray|number[]|number[][]|boolean[]|boolean[][]|\n string[]|string[][]|Uint8Array[]|Uint8Array[][];\n/** @docalias TypedArray|Array */\nexport type TensorLike3D = TypedArray|number[]|number[][][]|boolean[]|\n boolean[][][]|string[]|string[][][]|Uint8Array[]|Uint8Array[][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike4D = TypedArray|number[]|number[][][][]|boolean[]|\n boolean[][][][]|string[]|string[][][][]|Uint8Array[]|Uint8Array[][][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike5D =\n TypedArray|number[]|number[][][][][]|boolean[]|boolean[][][][][]|string[]|\n string[][][][][]|Uint8Array[]|Uint8Array[][][][][];\n/** @docalias TypedArray|Array */\nexport type TensorLike6D =\n TypedArray|number[]|number[][][][][][]|boolean[]|boolean[][][][][][]|\n string[]|string[][][][][][]|Uint8Array[]|Uint8Array[][][][][];\n\n/** Type for representing image dat in Uint8Array type. */\nexport interface PixelData {\n width: number;\n height: number;\n data: Uint8Array;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from './tensor';\nimport {TensorContainer, TensorContainerArray} from './tensor_types';\nimport {upcastType} from './types';\nimport {assert} from './util';\n\nexport function makeTypesMatch(a: T, b: T): [T, T] {\n if (a.dtype === b.dtype) {\n return [a, b];\n }\n const dtype = upcastType(a.dtype, b.dtype);\n return [a.cast(dtype), b.cast(dtype)];\n}\n\nexport function assertTypesMatch(a: Tensor, b: Tensor): void {\n assert(\n a.dtype === b.dtype,\n () => `The dtypes of the first(${a.dtype}) and` +\n ` second(${b.dtype}) input must match`);\n}\n\nexport function isTensorInList(tensor: Tensor, tensorList: Tensor[]): boolean {\n return tensorList.some(x => x.id === tensor.id);\n}\n\n/**\n * Extracts any `Tensor`s found within the provided object.\n *\n * @param container an object that may be a `Tensor` or may directly contain\n * `Tensor`s, such as a `Tensor[]` or `{key: Tensor, ...}`. In general it\n * is safe to pass any object here, except that `Promise`s are not\n * supported.\n * @returns An array of `Tensors` found within the passed object. If the\n * argument is simply a `Tensor', a list containing that `Tensor` is\n * returned. If the object is not a `Tensor` or does not\n * contain `Tensors`, an empty list is returned.\n */\nexport function getTensorsInContainer(result: TensorContainer): Tensor[] {\n const list: Tensor[] = [];\n const seen = new Set<{}|void>();\n walkTensorContainer(result, list, seen);\n return list;\n}\n\nfunction walkTensorContainer(\n container: TensorContainer, list: Tensor[], seen: Set<{}|void>): void {\n if (container == null) {\n return;\n }\n if (container instanceof Tensor) {\n list.push(container);\n return;\n }\n if (!isIterable(container)) {\n return;\n }\n // Iteration over keys works also for arrays.\n const iterable = container as TensorContainerArray;\n for (const k in iterable) {\n const val = iterable[k];\n if (!seen.has(val)) {\n seen.add(val);\n walkTensorContainer(val, list, seen);\n }\n }\n}\n\n// tslint:disable-next-line:no-any\nfunction isIterable(obj: any): boolean {\n return Array.isArray(obj) || typeof obj === 'object';\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {BackendTimingInfo, DataMover, KernelBackend} from './backends/backend';\nimport {Environment, setEnvironmentGlobal} from './environment';\nimport {getGlobalNamespace} from './global_util';\nimport {Add, Cast} from './kernel_names';\nimport {getGradient, getKernel, getKernelsForBackend, GradFunc, NamedAttrMap, TensorInfo} from './kernel_registry';\nimport {KernelProfile, Profiler} from './profiler';\nimport {backpropagateGradients, getFilteredNodesXToY, TapeNode} from './tape';\nimport {DataId, setTensorTracker, Tensor, TensorTracker, Variable} from './tensor';\nimport {GradSaveFunc, NamedTensorMap, NamedVariableMap, TensorContainer} from './tensor_types';\nimport {getTensorsInContainer} from './tensor_util';\nimport {BackendValues, DataType, DataValues} from './types';\nimport * as util from './util';\nimport {bytesFromStringArray, makeOnesTypedArray, now, sizeFromShape} from './util';\n\n/**\n * A function that computes an output. The save function is for saving tensors\n * computed in the forward pass, that we need in the backward pass.\n */\nexport type ForwardFunc = (backend: KernelBackend, save?: GradSaveFunc) => T;\n\n/**\n * @docalias (a: Tensor, b: Tensor,..., save?: Function) => {\n * value: Tensor,\n * gradFunc: (dy: Tensor, saved?: NamedTensorMap) => Tensor | Tensor[]\n * }\n */\nexport type CustomGradientFunc =\n (...inputs: Array) => {\n value: T;\n gradFunc: (dy: T, saved: Tensor[]) => Tensor | Tensor[];\n };\n\nexport type MemoryInfo = {\n numTensors: number; numDataBuffers: number; numBytes: number;\n unreliable?: boolean; reasons: string[];\n};\n\ntype KernelInfo = {\n name: string; bytesAdded: number; totalBytesSnapshot: number;\n tensorsAdded: number;\n totalTensorsSnapshot: number;\n inputShapes: number[][];\n outputShapes: number[][];\n kernelTimeMs: number | {error: string} | Promise;\n extraInfo: string | Promise;\n};\n\nexport type ProfileInfo = {\n newBytes: number; newTensors: number; peakBytes: number;\n kernels: KernelInfo[];\n result: TensorContainer;\n};\n\nexport interface TimingInfo extends BackendTimingInfo {\n wallMs: number;\n}\n\n/** @docalias Function */\nexport type ScopeFn = () => T;\n\ninterface ScopeState {\n track: Tensor[];\n name: string;\n id: number;\n}\n\nclass EngineState {\n // Public since optimizers will use it.\n registeredVariables: NamedVariableMap = {};\n\n nextTapeNodeId = 0;\n numBytes = 0;\n numTensors = 0;\n numStringTensors = 0;\n numDataBuffers = 0;\n\n activeTape: TapeNode[];\n // Number of nested tf.grad() statements when computing higher-order\n // gradients. E.g. `1` for first-order gradients and `2` for second-order\n // gradients. Used to track if the tape should be removed after a backprop.\n gradientDepth = 0;\n // Number of nested kernel calls. When kernel depth is greater than 1, we turn\n // off the tape.\n kernelDepth = 0;\n\n // Keep Tensors that parallel the tapes.\n activeScope: ScopeState;\n scopeStack: ScopeState[] = [];\n /**\n * Keeps track of the number of data moves during a kernel execution. We\n * maintain a stack since kernels can call other kernels, recursively.\n */\n numDataMovesStack: number[] = [];\n nextScopeId = 0;\n\n tensorInfo = new WeakMap();\n\n profiling = false;\n activeProfile: ProfileInfo =\n {newBytes: 0, newTensors: 0, peakBytes: 0, kernels: [], result: null};\n\n dispose() {\n for (const variableName in this.registeredVariables) {\n this.registeredVariables[variableName].dispose();\n }\n }\n}\n\nexport class Engine implements TensorTracker, DataMover {\n state: EngineState;\n backendName: string;\n registry: {[id: string]: KernelBackend} = {};\n registryFactory: {\n [id: string]: {\n factory: () => KernelBackend | Promise,\n priority: number\n }\n } = {};\n\n private profiler: Profiler;\n private backendInstance: KernelBackend;\n private pendingBackendInit: Promise;\n private pendingBackendInitId = 0;\n\n constructor(public ENV: Environment) {\n this.state = new EngineState();\n }\n\n async ready(): Promise {\n if (this.pendingBackendInit != null) {\n return this.pendingBackendInit.then(() => {});\n }\n if (this.backendInstance != null) {\n return;\n }\n const sortedBackends = this.getSortedBackends();\n\n for (let i = 0; i < sortedBackends.length; i++) {\n const backendName = sortedBackends[i];\n const success = await this.initializeBackend(backendName).success;\n if (success) {\n await this.setBackend(backendName);\n return;\n }\n }\n\n throw new Error(\n `Could not initialize any backends, all backend initializations ` +\n `failed.`);\n }\n\n get backend(): KernelBackend {\n if (this.pendingBackendInit != null) {\n throw new Error(\n `Backend '${this.backendName}' has not yet been initialized. Make ` +\n `sure to await tf.ready() or await tf.setBackend() before calling ` +\n `other methods`);\n }\n if (this.backendInstance == null) {\n const {name, asyncInit} = this.initializeBackendsAndReturnBest();\n if (asyncInit) {\n throw new Error(\n `The highest priority backend '${name}' has not yet been ` +\n `initialized. Make sure to await tf.ready() or ` +\n `await tf.setBackend() before calling other methods`);\n }\n this.setBackend(name);\n }\n return this.backendInstance;\n }\n\n backendNames(): string[] {\n return Object.keys(this.registryFactory);\n }\n\n findBackend(backendName: string): KernelBackend {\n if (!(backendName in this.registry)) {\n // If the backend hasn't been initialized but we have a registry entry for\n // it, initialize it and return it.\n if (backendName in this.registryFactory) {\n const {asyncInit} = this.initializeBackend(backendName);\n if (asyncInit) {\n // Backend is not ready yet.\n return null;\n }\n } else {\n return null;\n }\n }\n return this.registry[backendName];\n }\n\n findBackendFactory(backendName: string):\n () => KernelBackend | Promise {\n if (!(backendName in this.registryFactory)) {\n return null;\n }\n return this.registryFactory[backendName].factory;\n }\n\n registerBackend(\n backendName: string,\n factory: () => KernelBackend | Promise,\n priority = 1): boolean {\n if (backendName in this.registryFactory) {\n console.warn(\n `${backendName} backend was already registered. ` +\n `Reusing existing backend factory.`);\n return false;\n }\n this.registryFactory[backendName] = {factory, priority};\n return true;\n }\n\n async setBackend(backendName: string): Promise {\n if (this.registryFactory[backendName] == null) {\n throw new Error(`Backend name '${backendName}' not found in registry`);\n }\n this.backendName = backendName;\n if (this.registry[backendName] == null) {\n this.backendInstance = null;\n const {success, asyncInit} = this.initializeBackend(backendName);\n const result = asyncInit ? await success : success;\n if (!result) {\n return false;\n }\n }\n this.backendInstance = this.registry[backendName];\n this.setupRegisteredKernels();\n // Reset the profiler.\n this.profiler = new Profiler(this.backendInstance);\n\n return true;\n }\n\n private setupRegisteredKernels(): void {\n const kernels = getKernelsForBackend(this.backendName);\n kernels.forEach(kernel => {\n if (kernel.setupFunc != null) {\n kernel.setupFunc(this.backendInstance);\n }\n });\n }\n\n private disposeRegisteredKernels(backendName: string): void {\n const kernels = getKernelsForBackend(backendName);\n kernels.forEach(kernel => {\n if (kernel.disposeFunc != null) {\n kernel.disposeFunc(this.registry[backendName]);\n }\n });\n }\n\n /**\n * Initializes a backend by looking up the backend name in the factory\n * registry and calling the factory method. Returns a boolean representing\n * whether the initialization of the backend suceeded. Throws an error if\n * there is no backend in the factory registry.\n */\n private initializeBackend(backendName: string):\n {success: boolean|Promise, asyncInit: boolean} {\n const registryFactoryEntry = this.registryFactory[backendName];\n if (registryFactoryEntry == null) {\n throw new Error(\n `Cannot initialize backend ${backendName}, no registration found.`);\n }\n\n try {\n const backend = registryFactoryEntry.factory();\n /* Test if the factory returns a promise.\n Done in a more liberal way than\n previous 'Promise.resolve(backend)===backend'\n as we needed to account for custom Promise\n implementations (e.g. Angular) */\n if (backend && !(backend instanceof KernelBackend)\n && typeof backend.then === 'function') {\n const promiseId = ++this.pendingBackendInitId;\n const success =\n backend\n .then(backendInstance => {\n // Outdated promise. Another backend was set in the meantime.\n if (promiseId < this.pendingBackendInitId) {\n return false;\n }\n this.registry[backendName] = backendInstance;\n this.pendingBackendInit = null;\n return true;\n })\n .catch(err => {\n // Outdated promise. Another backend was set in the meantime.\n if (promiseId < this.pendingBackendInitId) {\n return false;\n }\n this.pendingBackendInit = null;\n console.warn(\n `Initialization of backend ${backendName} failed`);\n console.warn(err.stack || err.message);\n return false;\n });\n this.pendingBackendInit = success;\n return {success, asyncInit: true};\n } else {\n this.registry[backendName] = backend as KernelBackend;\n return {success: true, asyncInit: false};\n }\n } catch (err) {\n console.warn(`Initialization of backend ${backendName} failed`);\n console.warn(err.stack || err.message);\n return {success: false, asyncInit: false};\n }\n }\n\n removeBackend(backendName: string): void {\n if (!(backendName in this.registryFactory)) {\n throw new Error(`${backendName} backend not found in registry`);\n }\n if (this.backendName === backendName && this.pendingBackendInit != null) {\n // There is a pending promise of the backend we want to remove. Make it\n // obsolete.\n this.pendingBackendInitId++;\n }\n\n if (backendName in this.registry) {\n this.disposeRegisteredKernels(backendName);\n this.registry[backendName].dispose();\n delete this.registry[backendName];\n }\n\n delete this.registryFactory[backendName];\n\n // Unset the backend if it is active.\n if (this.backendName === backendName) {\n this.pendingBackendInit = null;\n this.backendName = null;\n this.backendInstance = null;\n }\n }\n\n private getSortedBackends(): string[] {\n if (Object.keys(this.registryFactory).length === 0) {\n throw new Error('No backend found in registry.');\n }\n return Object.keys(this.registryFactory).sort((a: string, b: string) => {\n // Highest priority comes first.\n return this.registryFactory[b].priority -\n this.registryFactory[a].priority;\n });\n }\n\n private initializeBackendsAndReturnBest():\n {name: string, asyncInit: boolean} {\n const sortedBackends = this.getSortedBackends();\n\n for (let i = 0; i < sortedBackends.length; i++) {\n const backendName = sortedBackends[i];\n const {success, asyncInit} = this.initializeBackend(backendName);\n if (asyncInit || success) {\n return {name: backendName, asyncInit};\n }\n }\n throw new Error(\n `Could not initialize any backends, all backend initializations ` +\n `failed.`);\n }\n\n moveData(backend: KernelBackend, dataId: DataId) {\n const info = this.state.tensorInfo.get(dataId);\n const srcBackend = info.backend;\n const values = this.readSync(dataId);\n // Delete the tensor from the old backend and move it to the new\n // backend.\n srcBackend.disposeData(dataId);\n info.backend = backend;\n backend.move(dataId, values, info.shape, info.dtype);\n if (this.shouldCheckForMemLeaks()) {\n // Track the number of moves during a kernel execution to correctly\n // detect memory leaks.\n this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++;\n }\n }\n\n tidy(nameOrFn: string|ScopeFn, fn?: ScopeFn):\n T {\n let name: string = null;\n if (fn == null) {\n // Called with only 1 argument.\n if (typeof nameOrFn !== 'function') {\n throw new Error('Please provide a function to tidy()');\n }\n fn = nameOrFn;\n } else {\n // Called with 2 arguments.\n if (typeof nameOrFn !== 'string' && !(nameOrFn instanceof String)) {\n throw new Error(\n 'When calling with two arguments, the first argument ' +\n 'to tidy() must be a string');\n }\n if (typeof fn !== 'function') {\n throw new Error(\n 'When calling with two arguments, the 2nd argument ' +\n 'to tidy() must be a function');\n }\n name = nameOrFn as string;\n // TODO(nsthorat,smilkov): Do operation logging and performance\n // profiling.\n }\n let result: T;\n return this.scopedRun(\n () => this.startScope(name), () => this.endScope(result), () => {\n result = fn();\n if (result instanceof Promise) {\n console.error('Cannot return a Promise inside of tidy.');\n }\n return result;\n });\n }\n\n private scopedRun(start: () => void, end: () => void, f: () => T): T {\n start();\n try {\n const res = f();\n end();\n return res;\n } catch (ex) {\n end();\n throw ex;\n }\n }\n\n private static nextTensorId = 0;\n private nextTensorId(): number {\n return Engine.nextTensorId++;\n }\n\n private static nextVariableId = 0;\n private nextVariableId(): number {\n return Engine.nextVariableId++;\n }\n\n /**\n * This method is called instead of the public-facing tensor.clone() when\n * saving a tensor for backwards pass. It makes sure to add the clone\n * operation to the tape regardless of being called inside a kernel\n * execution.\n *\n * This method will go away once all kernels are modularized since we won't\n * need to turn off the tape inside runKernel().\n */\n private clone(x: Tensor): Tensor {\n const y = this.makeTensorFromDataId(x.dataId, x.shape, x.dtype);\n const inputs = {x};\n const grad = (dy: Tensor) => ({\n x: () => {\n const dtype = 'float32';\n const gradInputs = {x: dy};\n const attrs = {dtype};\n\n return ENGINE.runKernelFunc(\n backend => backend.cast(dy, dtype),\n gradInputs as {} as NamedTensorMap, null /* grad */, Cast,\n attrs as {} as NamedAttrMap);\n }\n });\n const saved: Tensor[] = [];\n this.addTapeNode(this.state.activeScope.name, inputs, [y], grad, saved, {});\n return y;\n }\n\n /**\n * Execute a kernel with the given name and return the output tensor.\n *\n * @param kernelName The name of the kernel to execute.\n * @param inputs A map of input names to tensors.\n * @param attrs A map of attribute names to their values. An attribute is a\n * primitive (non-tensor) input to the kernel.\n * @param inputsToSave A list of tensors, inputs to save for the backprop\n * computation.\n * @param outputsToSave A list of booleans, specifying which output to save\n * for the backprop computation. These are booleans since the output\n * tensors are not visible to the user.\n */\n runKernel(\n kernelName: string, inputs: NamedTensorMap, attrs: NamedAttrMap,\n inputsToSave?: Tensor[], outputsToSave?: boolean[]): Tensor|Tensor[] {\n const forwardFunc: null = null;\n const backwardsFunc: null = null;\n // Call runKernel as a stop-gap until we modularize all kernels.\n // Once we modularize all kernels, we will remove the existing\n // `runKernelFunc`.\n return this.runKernelFunc(\n forwardFunc, inputs, backwardsFunc, kernelName, attrs, inputsToSave,\n outputsToSave);\n }\n\n private shouldCheckForMemLeaks(): boolean {\n return this.ENV.getBool('IS_TEST');\n }\n\n private checkKernelForMemLeak(\n kernelName: string, numDataIdsBefore: number,\n outInfos: TensorInfo[]): void {\n const numDataIdsAfter = this.backend.numDataIds();\n\n // Count the number of data ids associated with the result of the kernel.\n let numOutputDataIds = 0;\n outInfos.forEach(info => {\n // Complex numbers allocate 3 data ids, one for 'real', one for\n // 'imaginary', and one for the container that holds the former two.\n numOutputDataIds += (info.dtype === 'complex64' ? 3 : 1);\n });\n\n // Account for the number of moves during kernel execution. A \"data move\"\n // can happen in the middle of a kernel execution, placing a new (key,value)\n // pair in the data storage. Since data moves have net zero effect (we\n // always remove the data from the old backend), we have to cancel them out\n // when detecting memory leaks.\n const numMoves =\n this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1];\n const dataIdsLeaked =\n numDataIdsAfter - numDataIdsBefore - numOutputDataIds - numMoves;\n if (dataIdsLeaked > 0) {\n throw new Error(\n `Backend '${this.backendName}' has an internal memory leak ` +\n `(${dataIdsLeaked} data ids) after running '${kernelName}'`);\n }\n }\n\n /**\n * @deprecated Use `runKernel` for newly added kernels. Keep using this method\n * only for kernels that are not yet fully modularized.\n */\n runKernelFunc(\n forwardFunc: ForwardFunc, inputs: I,\n backwardsFunc?: (dy: T, saved: Tensor[]) => {[P in keyof I]: () => I[P]},\n kernelName?: string, attrs?: NamedAttrMap, inputsToSave?: Tensor[],\n outputsToSave?: boolean[]): T {\n let outputs: Tensor[];\n let saved: Tensor[] = [];\n const isTapeOn = this.isTapeOn();\n if (kernelName == null) {\n kernelName =\n this.state.activeScope != null ? this.state.activeScope.name : '';\n }\n\n const startingBytecount = this.state.numBytes;\n const startingNumTensors = this.state.numTensors;\n\n if (this.shouldCheckForMemLeaks()) {\n this.state.numDataMovesStack.push(0);\n }\n\n let kernelFunc: () => Tensor[];\n const kernel = getKernel(kernelName, this.backendName);\n let out: TensorInfo|TensorInfo[];\n if (kernel != null) {\n kernelFunc = () => {\n const numDataIdsBefore = this.backend.numDataIds();\n out = kernel.kernelFunc({inputs, attrs, backend: this.backend});\n const outInfos = Array.isArray(out) ? out : [out];\n if (this.shouldCheckForMemLeaks()) {\n this.checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos);\n }\n const outTensors = outInfos.map(\n ({dataId, shape, dtype}) =>\n this.makeTensorFromDataId(dataId, shape, dtype));\n\n // Save the inputs and outputs.\n // Do not save unless we are recording to the tape. Otherwise it would\n // cause a mem leak since we would never run backprop, which disposes\n // the kept tensors.\n if (isTapeOn) {\n let tensorsToSave =\n this.getTensorsForGradient(kernelName, inputs, outTensors);\n if (tensorsToSave == null) {\n // Fallback for ops that call runKernelFunc and pass in\n // inputsToSave and outputsToSave. Currently this is the set of ops\n // with kernel support in the WASM backend. Once those ops and\n // respective gradients are modularised we can remove this path.\n if (outputsToSave == null) {\n outputsToSave = [];\n }\n const outsToSave = outTensors.filter((_, i) => outputsToSave[i]);\n tensorsToSave = (inputsToSave || []).slice().concat(outsToSave);\n }\n saved = this.saveTensorsForBackwardMode(tensorsToSave);\n }\n return outTensors;\n };\n } else {\n const saveFunc: GradSaveFunc = (tensors) => {\n // Do not save unless we are recording to the tape. Otherwise it would\n // cause a mem leak since we would never run backprop, which disposes\n // the kept tensors.\n if (!isTapeOn) {\n return;\n }\n saved = tensors.map(tensor => this.keep(this.clone(tensor)));\n };\n\n kernelFunc = () => {\n const numDataIdsBefore = this.backend.numDataIds();\n out = this.tidy(() => forwardFunc(this.backend, saveFunc));\n const outs = (Array.isArray(out) ? out : [out]) as Tensor[];\n if (this.shouldCheckForMemLeaks()) {\n this.checkKernelForMemLeak(kernelName, numDataIdsBefore, outs);\n }\n return outs;\n };\n }\n\n // Stop recording to a tape when running a kernel.\n let kernelProfile: KernelProfile;\n this.scopedRun(\n () => this.state.kernelDepth++, () => this.state.kernelDepth--, () => {\n if (!this.ENV.getBool('DEBUG') && !this.state.profiling) {\n outputs = kernelFunc();\n } else {\n kernelProfile = this.profiler.profileKernel(\n kernelName, inputs, () => kernelFunc());\n if (this.ENV.getBool('DEBUG')) {\n this.profiler.logKernelProfile(kernelProfile);\n }\n outputs = kernelProfile.outputs;\n }\n });\n\n if (isTapeOn) {\n this.addTapeNode(\n kernelName, inputs, outputs, backwardsFunc, saved, attrs);\n }\n\n if (this.state.profiling) {\n this.state.activeProfile.kernels.push({\n name: kernelName,\n bytesAdded: this.state.numBytes - startingBytecount,\n totalBytesSnapshot: this.state.numBytes,\n tensorsAdded: this.state.numTensors - startingNumTensors,\n totalTensorsSnapshot: this.state.numTensors,\n inputShapes: Object.keys(inputs).map(\n key => inputs[key] != null ? inputs[key].shape : null),\n outputShapes: outputs.map(item => item.shape),\n kernelTimeMs: kernelProfile.timeMs,\n extraInfo: kernelProfile.extraInfo\n });\n }\n return (Array.isArray(out) ? outputs : outputs[0]) as T;\n }\n\n /**\n * Saves tensors used in forward mode for use in backward mode.\n *\n * @param tensors the list of tensors to save.\n */\n private saveTensorsForBackwardMode(tensors: Tensor[]): Tensor[] {\n const saved = tensors.map(tensor => this.keep(this.clone(tensor)));\n return saved;\n }\n\n /**\n * Returns a list of tensors to save for a given gradient calculation.\n *\n * Returns undefined if their is no registered gradient for this kernel in the\n * gradient registry.\n *\n * @param kernelName name of kernel to look up gradient for.\n * @param inputs a map of input tensors.\n * @param outputs an array of output tensors from forward mode of kernel.\n */\n private getTensorsForGradient(\n kernelName: string, inputs: NamedTensorMap,\n outputs: Tensor[]): Tensor[]|null {\n const gradConfig = getGradient(kernelName);\n if (gradConfig != null) {\n const inputsToSave: string[] = gradConfig.inputsToSave || [];\n const outputsToSave: boolean[] = gradConfig.outputsToSave || [];\n\n // If saveAllInputs is true, all inputs will be saved. Otherwise, inputs\n // specified in inputsToSave will be saved.\n let inputTensorsToSave: Tensor[];\n if (gradConfig.saveAllInputs) {\n util.assert(\n Array.isArray(inputs),\n () => 'saveAllInputs is true, expected inputs to be an array.');\n\n inputTensorsToSave = Object.keys(inputs).map((key) => inputs[key]);\n } else {\n inputTensorsToSave = inputsToSave.map((inputName) => inputs[inputName]);\n }\n\n const outputTensorsToSave: Tensor[] =\n outputs.filter((_, i) => outputsToSave[i]);\n\n return inputTensorsToSave.concat(outputTensorsToSave);\n }\n // TODO(yassogba) throw exception here once all runkernelFunc calls with\n // inputsToSave/outputsToSave are removed\n return null;\n }\n\n /**\n * Internal method used by public APIs for tensor creation. Makes a new\n * tensor with the provided shape, dtype and values. It always\n * creates a new data id and writes the values to the underlying backend.\n */\n makeTensor(\n values: DataValues, shape: number[], dtype: DataType,\n backend?: KernelBackend): Tensor {\n if (values == null) {\n throw new Error('Values passed to engine.makeTensor() are null');\n }\n dtype = dtype || 'float32';\n backend = backend || this.backend;\n let backendVals = values as BackendValues;\n if (dtype === 'string' && util.isString(values[0])) {\n backendVals = (values as string[]).map(d => util.encodeString(d));\n }\n const dataId = backend.write(backendVals, shape, dtype);\n const t = new Tensor(shape, dtype, dataId, this.nextTensorId());\n this.incRef(t, backend);\n\n // Count bytes for string tensors.\n if (dtype === 'string') {\n const info = this.state.tensorInfo.get(dataId);\n const newBytes = bytesFromStringArray(backendVals as Uint8Array[]);\n this.state.numBytes += newBytes - info.bytes;\n info.bytes = newBytes;\n }\n return t;\n }\n\n /**\n * Internal method used by backends. Makes a new tensor\n * that is a wrapper around an existing data id. It doesn't create\n * a new data id, only increments the ref count used in memory tracking.\n */\n makeTensorFromDataId(\n dataId: DataId, shape: number[], dtype: DataType,\n backend?: KernelBackend): Tensor {\n dtype = dtype || 'float32';\n const t = new Tensor(shape, dtype, dataId, this.nextTensorId());\n this.incRef(t, backend);\n return t;\n }\n\n makeVariable(\n initialValue: Tensor, trainable = true, name?: string,\n dtype?: DataType): Variable {\n name = name || this.nextVariableId().toString();\n if (dtype != null && dtype !== initialValue.dtype) {\n initialValue = initialValue.cast(dtype);\n }\n const v = new Variable(initialValue, trainable, name, this.nextTensorId());\n if (this.state.registeredVariables[v.name] != null) {\n throw new Error(`Variable with name ${v.name} was already registered`);\n }\n this.state.registeredVariables[v.name] = v;\n this.incRef(v, this.backend);\n return v;\n }\n\n incRef(a: Tensor, backend: KernelBackend): void {\n const refCount = this.state.tensorInfo.has(a.dataId) ?\n this.state.tensorInfo.get(a.dataId).refCount :\n 0;\n this.state.numTensors++;\n if (a.dtype === 'string') {\n this.state.numStringTensors++;\n }\n if (refCount === 0) {\n this.state.numDataBuffers++;\n\n // Bytes for complex numbers are counted by their components. Bytes for\n // string tensors are counted when writing values.\n let bytes = 0;\n if (a.dtype !== 'complex64' && a.dtype !== 'string') {\n bytes = a.size * util.bytesPerElement(a.dtype);\n }\n this.state.tensorInfo.set(a.dataId, {\n backend: backend || this.backend,\n dtype: a.dtype,\n shape: a.shape,\n bytes,\n refCount: 0\n });\n this.state.numBytes += bytes;\n }\n\n this.state.tensorInfo.get(a.dataId).refCount++;\n\n if (!(a instanceof Variable)) {\n this.track(a);\n }\n }\n\n disposeTensor(a: Tensor): void {\n if (!this.state.tensorInfo.has(a.dataId)) {\n return;\n }\n\n this.state.numTensors--;\n if (a.dtype === 'string') {\n this.state.numStringTensors--;\n }\n const info = this.state.tensorInfo.get(a.dataId);\n const refCount = info.refCount;\n\n if (refCount <= 1) {\n // Don't count bytes for complex numbers as they are counted by their\n // components.\n if (a.dtype !== 'complex64') {\n this.state.numBytes -= info.bytes;\n }\n this.state.numDataBuffers--;\n\n info.backend.disposeData(a.dataId);\n this.state.tensorInfo.delete(a.dataId);\n } else {\n this.state.tensorInfo.get(a.dataId).refCount--;\n }\n // TODO(nsthorat): Construct an error and save the stack trace for\n // debugging when in debug mode. Creating a stack trace is too expensive\n // to do unconditionally.\n }\n\n disposeVariables(): void {\n for (const varName in this.state.registeredVariables) {\n const v = this.state.registeredVariables[varName];\n this.disposeVariable(v);\n }\n }\n\n disposeVariable(v: Variable): void {\n this.disposeTensor(v);\n if (this.state.registeredVariables[v.name] != null) {\n delete this.state.registeredVariables[v.name];\n }\n }\n\n memory(): MemoryInfo {\n const info = this.backend.memory() as MemoryInfo;\n info.numTensors = this.state.numTensors;\n info.numDataBuffers = this.state.numDataBuffers;\n info.numBytes = this.state.numBytes;\n if (this.state.numStringTensors > 0) {\n info.unreliable = true;\n if (info.reasons == null) {\n info.reasons = [];\n }\n info.reasons.push(\n 'Memory usage by string tensors is approximate ' +\n '(2 bytes per character)');\n }\n return info;\n }\n\n async profile(query: () => (TensorContainer | Promise)):\n Promise {\n this.state.profiling = true;\n\n const startBytes = this.state.numBytes;\n const startNumTensors = this.state.numTensors;\n\n this.state.activeProfile.kernels = [];\n this.state.activeProfile.result = await query();\n\n this.state.profiling = false;\n\n this.state.activeProfile.peakBytes = Math.max(\n ...this.state.activeProfile.kernels.map(d => d.totalBytesSnapshot));\n this.state.activeProfile.newBytes = this.state.numBytes - startBytes;\n this.state.activeProfile.newTensors =\n this.state.numTensors - startNumTensors;\n for (const kernel of this.state.activeProfile.kernels) {\n kernel.kernelTimeMs = await kernel.kernelTimeMs;\n kernel.extraInfo = await kernel.extraInfo;\n }\n return this.state.activeProfile;\n }\n\n isTapeOn(): boolean {\n return this.state.gradientDepth > 0 && this.state.kernelDepth === 0;\n }\n\n private addTapeNode(\n kernelName: string, inputs: NamedTensorMap, outputs: Tensor[],\n gradientsFunc: GradFunc, saved: Tensor[], attrs: NamedAttrMap): void {\n const tapeNode: TapeNode =\n {id: this.state.nextTapeNodeId++, kernelName, inputs, outputs, saved};\n\n const gradConfig = getGradient(kernelName);\n if (gradConfig != null) {\n gradientsFunc = gradConfig.gradFunc;\n }\n if (gradientsFunc != null) {\n tapeNode.gradient = (dys: Tensor[]) => {\n // TODO(smilkov): To optimize back-prop, pass dys that are not used in\n // the backprop graph to the user as null instead of zeros\n dys = dys.map((dy, i) => {\n if (dy == null) {\n const output = outputs[i];\n const vals = util.makeZerosTypedArray(output.size, output.dtype);\n return this.makeTensor(vals, output.shape, output.dtype);\n }\n return dy;\n });\n // Grad functions of ops with single outputs expect a dy, while ops\n // with multiple outputs expect dys (array of dy).\n return gradientsFunc(dys.length > 1 ? dys : dys[0], saved, attrs);\n };\n }\n this.state.activeTape.push(tapeNode);\n }\n\n keep(result: T): T {\n result.kept = true;\n return result;\n }\n\n private startTape() {\n if (this.state.gradientDepth === 0) {\n this.state.activeTape = [];\n }\n this.state.gradientDepth++;\n }\n\n private endTape() {\n this.state.gradientDepth--;\n }\n\n /**\n * Start a scope. Use this with endScope() to achieve the same functionality\n * as scope() without the need for a function closure.\n */\n startScope(name?: string) {\n const scopeInfo: ScopeState = {\n track: [],\n name: 'unnamed scope',\n id: this.state.nextScopeId++\n };\n if (name) {\n scopeInfo.name = name;\n }\n this.state.scopeStack.push(scopeInfo);\n this.state.activeScope = scopeInfo;\n }\n\n /**\n * End a scope. Use this with startScope() to achieve the same functionality\n * as scope() without the need for a function closure.\n */\n endScope(result?: TensorContainer) {\n const tensorsToTrackInParent = getTensorsInContainer(result);\n const tensorsToTrackInParentSet =\n new Set(tensorsToTrackInParent.map(t => t.id));\n\n // Dispose the arrays tracked in this scope.\n for (let i = 0; i < this.state.activeScope.track.length; i++) {\n const tensor = this.state.activeScope.track[i];\n if (!tensor.kept && !tensorsToTrackInParentSet.has(tensor.id)) {\n tensor.dispose();\n }\n }\n\n const oldScope = this.state.scopeStack.pop();\n this.state.activeScope = this.state.scopeStack.length === 0 ?\n null :\n this.state.scopeStack[this.state.scopeStack.length - 1];\n\n // Track the current result in the parent scope.\n tensorsToTrackInParent.forEach(tensor => {\n // Only track the tensor if was allocated in the inner scope and is not\n // globally kept.\n if (!tensor.kept && tensor.scopeId === oldScope.id) {\n this.track(tensor);\n }\n });\n }\n\n /**\n * Returns gradients of `f` with respect to each of the `xs`. The gradients\n * returned are of the same length as `xs`, but some might be null if `f`\n * was not a function of that `x`. It also takes optional dy to multiply the\n * gradient, which defaults to `1`.\n */\n gradients(\n f: () => T, xs: Tensor[], dy?: T,\n allowNoGradients = false): {value: T, grads: Tensor[]} {\n util.assert(\n xs.length > 0, () => 'gradients() received an empty list of xs.');\n if (dy != null && dy.dtype !== 'float32') {\n throw new Error(`dy must have 'float32' dtype, but has '${dy.dtype}'`);\n }\n\n const y = this.scopedRun(\n () => this.startTape(), () => this.endTape(),\n () => this.tidy('forward', f));\n\n util.assert(\n y instanceof Tensor,\n () => 'The result y returned by f() must be a tensor.');\n // Filter out the nodes that don't connect x => y.\n const filteredTape = getFilteredNodesXToY(this.state.activeTape, xs, y);\n if (!allowNoGradients && filteredTape.length === 0 && xs.length > 0) {\n throw new Error(\n 'Cannot compute gradient of y=f(x) with respect to x. Make sure ' +\n 'that the f you passed encloses all operations that lead from x ' +\n 'to y.');\n }\n\n return this.tidy('backward', () => {\n const accumulatedGradientMap: {[tensorId: number]: Tensor} = {};\n accumulatedGradientMap[y.id] = (dy == null) ? ones(y.shape) : dy;\n\n // Backprop gradients through the filtered nodes.\n backpropagateGradients(\n accumulatedGradientMap, filteredTape,\n // Pass the tidy function to avoid circular dep with `tape.ts`.\n f => this.tidy(f as ScopeFn),\n // Pass an add function to avoide a circular dep with `tape.ts`.\n add);\n const grads = xs.map(x => accumulatedGradientMap[x.id]);\n\n if (this.state.gradientDepth === 0) {\n // This means that we are not computing higher-order gradients\n // and can clean up the tape.\n this.state.activeTape.forEach(node => {\n for (const tensor of node.saved) {\n tensor.dispose();\n }\n });\n this.state.activeTape = null;\n }\n return {value: y, grads};\n });\n }\n\n customGrad(f: CustomGradientFunc):\n (...args: Array) => T {\n util.assert(\n util.isFunction(f),\n () => 'The f passed in customGrad(f) must be a function.');\n return (...inputs: Tensor[]): T => {\n util.assert(\n inputs.every(t => t instanceof Tensor),\n () => 'The args passed in customGrad(f)(x1, x2,...) must all be ' +\n 'tensors');\n\n let res: {\n value: T,\n gradFunc: (dy: T, saved: Tensor[]) => Tensor | Tensor[],\n };\n const inputMap: NamedTensorMap = {};\n inputs.forEach((input, i) => {\n inputMap[i] = input;\n });\n return this.runKernelFunc(\n (_, save) => {\n res = f(...[...inputs, save]);\n util.assert(\n res.value instanceof Tensor,\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.value` is a tensor');\n util.assert(\n util.isFunction(res.gradFunc),\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.gradFunc` is a function.');\n return res.value;\n },\n inputMap,\n (dy: T, saved: Tensor[]) => {\n const gradRes = res.gradFunc(dy, saved);\n const grads: Tensor[] =\n Array.isArray(gradRes) ? gradRes : [gradRes];\n util.assert(\n grads.length === inputs.length,\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.gradFunc` is a function that returns ' +\n 'the same number of tensors as inputs passed to f(...).');\n util.assert(\n grads.every(t => t instanceof Tensor),\n () => 'The function f passed in customGrad(f) must return an ' +\n 'object where `obj.gradFunc` is a function that returns ' +\n 'a list of only tensors.');\n const gradMap: {[key: string]: () => Tensor} = {};\n grads.forEach((grad, i) => {\n gradMap[i] = () => grad;\n });\n return gradMap;\n });\n };\n }\n\n readSync(dataId: DataId): BackendValues {\n // Route the read to the correct backend.\n const info = this.state.tensorInfo.get(dataId);\n return info.backend.readSync(dataId);\n }\n read(dataId: DataId): Promise {\n // Route the read to the correct backend.\n const info = this.state.tensorInfo.get(dataId);\n return info.backend.read(dataId);\n }\n\n async time(query: () => void): Promise {\n const start = now();\n const timingInfo = await this.backend.time(query) as TimingInfo;\n timingInfo.wallMs = now() - start;\n return timingInfo;\n }\n\n /**\n * Tracks a Tensor in the current scope to be automatically cleaned up\n * when the current scope ends, and returns the value.\n *\n * @param result The Tensor to track in the current scope.\n */\n private track(result: T): T {\n if (this.state.activeScope != null) {\n result.scopeId = this.state.activeScope.id;\n this.state.activeScope.track.push(result);\n }\n\n return result;\n }\n\n get registeredVariables(): NamedVariableMap {\n return this.state.registeredVariables;\n }\n\n /**\n * Resets the engine state. Removes all backends but does not remove\n * registered backend factories.\n */\n reset(): void {\n // Make any pending promise obsolete.\n this.pendingBackendInitId++;\n\n this.state.dispose();\n this.ENV.reset();\n this.state = new EngineState();\n\n for (const backendName in this.registry) {\n this.disposeRegisteredKernels(backendName);\n this.registry[backendName].dispose();\n delete this.registry[backendName];\n }\n this.backendName = null;\n this.backendInstance = null;\n this.pendingBackendInit = null;\n }\n}\n\nfunction ones(shape: number[]): Tensor {\n const values = makeOnesTypedArray(sizeFromShape(shape), 'float32');\n return ENGINE.makeTensor(values, shape, 'float32');\n}\n\nexport function getOrMakeEngine(): Engine {\n const ns = getGlobalNamespace() as {} as {_tfengine: Engine};\n if (ns._tfengine == null) {\n const environment = new Environment(ns);\n ns._tfengine = new Engine(environment);\n }\n setEnvironmentGlobal(ns._tfengine.ENV);\n\n // Tell the current tensor interface that the global engine is responsible\n // for tracking.\n setTensorTracker(() => ns._tfengine);\n return ns._tfengine;\n}\n\nexport const ENGINE = getOrMakeEngine();\n\n/**\n * A implementation of the add op for use within engine and tape.\n *\n * This allows us to avoid a circular dependency between add.ts and engine.\n * It is exported to be available in tape tests.\n */\nexport function add(a: Tensor, b: Tensor): Tensor {\n // We duplicate Add here to avoid a circular dependency with add.ts.\n const inputs = {a, b};\n return ENGINE.runKernelFunc((backend, save) => {\n const res = backend.add(a, b);\n save([a, b]);\n return res;\n }, inputs as {} as NamedTensorMap, null /* gradient */, Add);\n}\n", "/**\n * @license\n * Copyright 2017 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// tslint:disable-next-line:no-any\nfunction _isNavigatorDefined(): boolean {\n return typeof navigator !== 'undefined' && navigator != null;\n}\n\nexport function isMobile(): boolean {\n if (_isNavigatorDefined()) {\n // tslint:disable-next-line:no-any\n const a = navigator.userAgent || navigator.vendor || (window as any).opera;\n // tslint:disable-next-line:max-line-length\n return /(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i\n .test(a) ||\n // tslint:disable-next-line:max-line-length\n /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\\-|your|zeto|zte\\-/i\n .test(a.substr(0, 4));\n }\n return false;\n}\n\nexport function isBrowser(): boolean {\n return (typeof window !== 'undefined' && window.document != null) ||\n //@ts-ignore\n (typeof WorkerGlobalScope !== 'undefined');\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport './engine';\n\nimport * as device_util from './device_util';\nimport {env} from './environment';\n\nconst ENV = env();\n\n/**\n * This file contains environment-related flag registrations.\n */\n\n/** Whether to enable debug mode. */\nENV.registerFlag('DEBUG', () => false, debugValue => {\n if (debugValue) {\n console.warn(\n 'Debugging mode is ON. The output of every math call will ' +\n 'be downloaded to CPU and checked for NaNs. ' +\n 'This significantly impacts performance.');\n }\n});\n\n/** Whether we are in a browser (as versus, say, node.js) environment. */\nENV.registerFlag('IS_BROWSER', () => device_util.isBrowser());\n\n/** Whether we are in a browser (as versus, say, node.js) environment. */\nENV.registerFlag(\n 'IS_NODE',\n () => (typeof process !== 'undefined') &&\n (typeof process.versions !== 'undefined') &&\n (typeof process.versions.node !== 'undefined'));\n\n/** Whether this browser is Chrome. */\nENV.registerFlag(\n 'IS_CHROME',\n () => typeof navigator !== 'undefined' && navigator != null &&\n navigator.userAgent != null && /Chrome/.test(navigator.userAgent) &&\n /Google Inc/.test(navigator.vendor));\n\n/**\n * True when the environment is \"production\" where we disable safety checks\n * to gain performance.\n */\nENV.registerFlag('PROD', () => false);\n\n/**\n * Whether to do sanity checks when inferring a shape from user-provided\n * values, used when creating a new tensor.\n */\nENV.registerFlag(\n 'TENSORLIKE_CHECK_SHAPE_CONSISTENCY', () => ENV.getBool('DEBUG'));\n\n/** Whether deprecation warnings are enabled. */\nENV.registerFlag('DEPRECATION_WARNINGS_ENABLED', () => true);\n\n/** True if running unit tests. */\nENV.registerFlag('IS_TEST', () => false);\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from './engine';\nimport {env} from './environment';\nimport {Tensor} from './tensor';\nimport {DataType, TensorLike} from './types';\nimport {assert, flatten, inferDtype, isTypedArray, toTypedArray} from './util';\n\nexport function inferShape(val: TensorLike, dtype?: DataType): number[] {\n let firstElem: typeof val = val;\n\n if (isTypedArray(val)) {\n return dtype === 'string' ? [] : [val.length];\n }\n if (!Array.isArray(val)) {\n return []; // Scalar.\n }\n const shape: number[] = [];\n\n while (Array.isArray(firstElem) ||\n isTypedArray(firstElem) && dtype !== 'string') {\n shape.push(firstElem.length);\n firstElem = firstElem[0];\n }\n if (Array.isArray(val) &&\n env().getBool('TENSORLIKE_CHECK_SHAPE_CONSISTENCY')) {\n deepAssertShapeConsistency(val, shape, []);\n }\n\n return shape;\n}\n\nfunction deepAssertShapeConsistency(\n val: TensorLike, shape: number[], indices: number[]) {\n indices = indices || [];\n if (!(Array.isArray(val)) && !isTypedArray(val)) {\n assert(\n shape.length === 0,\n () => `Element arr[${indices.join('][')}] is a primitive, ` +\n `but should be an array/TypedArray of ${shape[0]} elements`);\n return;\n }\n assert(\n shape.length > 0,\n () => `Element arr[${indices.join('][')}] should be a primitive, ` +\n `but is an array of ${val.length} elements`);\n assert(\n val.length === shape[0],\n () => `Element arr[${indices.join('][')}] should have ${shape[0]} ` +\n `elements, but has ${val.length} elements`);\n const subShape = shape.slice(1);\n for (let i = 0; i < val.length; ++i) {\n deepAssertShapeConsistency(val[i], subShape, indices.concat(i));\n }\n}\n\nfunction assertDtype(\n expectedDtype: DataType|'numeric', actualDType: DataType, argName: string,\n functionName: string) {\n if (expectedDtype == null) {\n return;\n }\n if (expectedDtype !== 'numeric' && expectedDtype !== actualDType ||\n expectedDtype === 'numeric' && actualDType === 'string') {\n throw new Error(\n `Argument '${argName}' passed to '${functionName}' must ` +\n `be ${expectedDtype} tensor, but got ${actualDType} tensor`);\n }\n}\n\nexport function convertToTensor(\n x: T|TensorLike, argName: string, functionName: string,\n parseAsDtype: DataType|'numeric' = 'numeric'): T {\n if (x instanceof Tensor) {\n assertDtype(parseAsDtype, x.dtype, argName, functionName);\n return x;\n }\n let inferredDtype = inferDtype(x);\n // If the user expects a bool/int/float, use that info to update the\n // inferredDtype when it is not a string.\n if (inferredDtype !== 'string' &&\n ['bool', 'int32', 'float32'].indexOf(parseAsDtype) >= 0) {\n inferredDtype = parseAsDtype as DataType;\n }\n assertDtype(parseAsDtype, inferredDtype, argName, functionName);\n\n if ((x == null) ||\n (!isTypedArray(x) && !Array.isArray(x) && typeof x !== 'number' &&\n typeof x !== 'boolean' && typeof x !== 'string')) {\n const type = x == null ? 'null' : (x as {}).constructor.name;\n throw new Error(\n `Argument '${argName}' passed to '${functionName}' must be a ` +\n `Tensor or TensorLike, but got '${type}'`);\n }\n const inferredShape = inferShape(x, inferredDtype);\n if (!isTypedArray(x) && !Array.isArray(x)) {\n x = [x] as number[];\n }\n const skipTypedArray = true;\n const values = inferredDtype !== 'string' ?\n toTypedArray(x, inferredDtype as DataType) :\n flatten(x as string[], [], skipTypedArray) as string[];\n return ENGINE.makeTensor(values, inferredShape, inferredDtype) as T;\n}\n\nexport function convertToTensorArray(\n arg: Array, argName: string, functionName: string,\n parseAsDtype: DataType|'numeric' = 'numeric'): T[] {\n if (!Array.isArray(arg)) {\n throw new Error(\n `Argument ${argName} passed to ${functionName} must be a ` +\n '`Tensor[]` or `TensorLike[]`');\n }\n const tensors = arg as T[];\n return tensors.map(\n (t, i) => convertToTensor(t, `${argName}[${i}]`, functionName),\n parseAsDtype);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\n\nexport const OP_SCOPE_SUFFIX = '__op';\n\n/**\n * Used for wrapping functions that perform math operations on\n * Tensors. The function will be wrapped in a named scope that cleans all\n * memory usage after the function is done.\n */\nexport function op(f: {[name: string]: T}): T {\n const keys = Object.keys(f);\n if (keys.length !== 1) {\n throw new Error(\n `Please provide an object with a single key ` +\n `(operation name) mapping to a function. Got an object with ` +\n `${keys.length} keys.`);\n }\n\n let opName = keys[0];\n const fn = f[opName];\n\n // Strip the underscore from the end of the function name.\n if (opName.endsWith('_')) {\n opName = opName.substring(0, opName.length - 1);\n }\n\n // add an __op suffix to distinguish ops from kernels in tf.profile\n opName = opName + OP_SCOPE_SUFFIX;\n\n // tslint:disable-next-line:no-any\n const f2 = (...args: any[]) => {\n ENGINE.startScope(opName);\n try {\n const result = fn(...args);\n if (result instanceof Promise) {\n console.error('Cannot return a Promise inside of tidy.');\n }\n ENGINE.endScope(result);\n return result;\n } catch (ex) {\n ENGINE.endScope(null);\n throw ex;\n }\n };\n Object.defineProperty(f2, 'name', {value: opName, configurable: true});\n\n // tslint:disable-next-line:no-any\n return f2 as any as T;\n}\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE, ForwardFunc} from '../engine';\nimport {Complex, ComplexInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Converts two real numbers to a complex number.\n *\n * Given a tensor `real` representing the real part of a complex number, and a\n * tensor `imag` representing the imaginary part of a complex number, this\n * operation returns complex numbers elementwise of the form [r0, i0, r1, i1],\n * where r represents the real part and i represents the imag part.\n *\n * The input tensors real and imag must have the same shape.\n *\n * ```js\n * const real = tf.tensor1d([2.25, 3.25]);\n * const imag = tf.tensor1d([4.75, 5.75]);\n * const complex = tf.complex(real, imag);\n *\n * complex.print();\n * ```\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction complex_(real: T|TensorLike, imag: T|TensorLike): T {\n const $real = convertToTensor(real, 'real', 'complex');\n const $imag = convertToTensor(imag, 'imag', 'complex');\n util.assertShapesMatch(\n $real.shape, $imag.shape,\n `real and imag shapes, ${$real.shape} and ${$imag.shape}, ` +\n `must match in call to tf.complex().`);\n\n const forward: ForwardFunc = (backend) => {\n return backend.complex($real, $imag);\n };\n const inputs: ComplexInputs = {real: $real, imag: $imag};\n return ENGINE.runKernelFunc(\n forward, inputs as {} as NamedTensorMap, null /* gradient */,\n Complex) as T;\n}\n\nexport const complex = op({complex_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Tensor} from '../tensor';\nimport {TensorLike, TypedArray} from '../types';\nimport {DataType} from '../types';\nimport {assert, assertNonNegativeIntegerDimensions, flatten, inferDtype, isTypedArray, sizeFromShape, toTypedArray} from '../util';\n\n/** This is shared code across all tensor creation methods. */\nexport function makeTensor(\n values: TensorLike, shape: number[], inferredShape: number[],\n dtype?: DataType): Tensor {\n if (dtype == null) {\n dtype = inferDtype(values);\n }\n if (dtype === 'complex64') {\n throw new Error(\n `Cannot construct a complex64 tensor directly. ` +\n `Please use tf.complex(real, imag).`);\n }\n if (!isTypedArray(values) && !Array.isArray(values) &&\n typeof values !== 'number' && typeof values !== 'boolean' &&\n typeof values !== 'string') {\n throw new Error(\n 'values passed to tensor(values) must be a number/boolean/string or ' +\n 'an array of numbers/booleans/strings, or a TypedArray');\n }\n if (shape != null) {\n assertNonNegativeIntegerDimensions(shape);\n\n const providedSize = sizeFromShape(shape);\n const inferredSize = sizeFromShape(inferredShape);\n assert(\n providedSize === inferredSize,\n () =>\n `Based on the provided shape, [${shape}], the tensor should have ` +\n `${providedSize} values but has ${inferredSize}`);\n\n for (let i = 0; i < inferredShape.length; ++i) {\n const inferred = inferredShape[i];\n const flatDimsDontMatch = i === inferredShape.length - 1 ?\n inferred !== sizeFromShape(shape.slice(i)) :\n true;\n assert(\n inferredShape[i] === shape[i] || !flatDimsDontMatch,\n () => `Error creating a new Tensor. Inferred shape ` +\n `(${inferredShape}) does not match the provided ` +\n `shape (${shape}). `);\n }\n }\n\n if (!isTypedArray(values) && !Array.isArray(values)) {\n values = [values] as number[];\n }\n\n shape = shape || inferredShape;\n values = dtype !== 'string' ?\n toTypedArray(values, dtype) :\n flatten(values as string[], [], true) as string[];\n return ENGINE.makeTensor(values as TypedArray, shape, dtype);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport {DataType, Rank, ShapeMap} from '../types';\n\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates a `tf.Tensor` with the provided values, shape and dtype.\n *\n * ```js\n * // Pass an array of values to create a vector.\n * tf.tensor([1, 2, 3, 4]).print();\n * ```\n *\n * ```js\n * // Pass a nested array of values to make a matrix or a higher\n * // dimensional tensor.\n * tf.tensor([[1, 2], [3, 4]]).print();\n * ```\n *\n * ```js\n * // Pass a flat array and specify a shape yourself.\n * tf.tensor([1, 2, 3, 4], [2, 2]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n * or a flat array, or a `TypedArray`. If the values are strings,\n * they will be encoded as utf-8 and kept as `Uint8Array[]`.\n * @param shape The shape of the tensor. Optional. If not provided,\n * it is inferred from `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor(\n values: TensorLike, shape?: ShapeMap[R], dtype?: DataType): Tensor {\n const inferredShape = inferShape(values, dtype);\n return makeTensor(values, shape, inferredShape, dtype) as Tensor;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/* Type definitions for exporting and importing of models. */\n\n/**\n * A map from Tensor dtype to number of bytes per element of the Tensor.\n */\nexport const DTYPE_VALUE_SIZE_MAP: {[dtype: string]: number} = {\n 'float32': 4,\n 'float16': 2,\n 'int32': 4,\n 'uint16': 2,\n 'uint8': 1,\n 'bool': 1,\n 'complex64': 8\n};\n\n/**\n * A weight manifest.\n *\n * The weight manifest consists of an ordered list of weight-manifest groups.\n * Each weight-manifest group (\"group\" for short hereafter) consists of a\n * number of weight values stored in a number of paths.\n * See the documentation of `WeightManifestGroupConfig` below for more details.\n */\nexport declare type WeightsManifestConfig = WeightsManifestGroupConfig[];\n\n/**\n * A weight-manifest group.\n *\n * Consists of an ordered list of weight values encoded in binary format,\n * stored in an ordered list of paths.\n */\nexport declare interface WeightsManifestGroupConfig {\n /**\n * An ordered list of paths.\n *\n * Paths are intentionally abstract in order to be general. For example, they\n * can be relative URL paths or relative paths on the file system.\n */\n paths: string[];\n\n /**\n * Specifications of the weights stored in the paths.\n */\n weights: WeightsManifestEntry[];\n}\n\n/**\n * Group to which the weight belongs.\n *\n * - 'optimizer': Weight from a stateful optimizer.\n */\nexport type WeightGroup = 'model'|'optimizer';\n\n/**\n * An entry in the weight manifest.\n *\n * The entry contains specification of a weight.\n */\nexport declare interface WeightsManifestEntry {\n /**\n * Name of the weight, e.g., 'Dense_1/bias'\n */\n name: string;\n\n /**\n * Shape of the weight.\n */\n shape: number[];\n\n /**\n * Data type of the weight.\n */\n dtype: 'float32'|'int32'|'bool'|'string'|'complex64';\n\n /**\n * Type of the weight.\n *\n * Optional.\n *\n * The value 'optimizer' indicates the weight belongs to an optimizer\n * (i.e., used only during model training and not during inference).\n */\n group?: WeightGroup;\n\n /**\n * Information for dequantization of the weight.\n */\n quantization?: {\n scale?: number, // The scaling constant to multiply by.\n min?: number, // The (possibly nudged) minimum weight to add.\n dtype: 'uint16'|'uint8'|'float16' // The dtype of the quantized weights.\n };\n}\n\n/**\n * Options for saving a model.\n * @innamespace io\n */\nexport interface SaveConfig {\n /**\n * Whether to save only the trainable weights of the model, ignoring the\n * non-trainable ones.\n */\n trainableOnly?: boolean;\n\n /**\n * Whether the optimizer will be saved (if exists).\n *\n * Default: `false`.\n */\n includeOptimizer?: boolean;\n}\n\n/**\n * Result of a saving operation.\n */\nexport interface SaveResult {\n /**\n * Information about the model artifacts saved.\n */\n modelArtifactsInfo: ModelArtifactsInfo;\n\n /**\n * HTTP responses from the server that handled the model-saving request (if\n * any). This is applicable only to server-based saving routes.\n */\n responses?: Response[];\n\n /**\n * Error messages and related data (if any).\n */\n errors?: Array<{}|string>;\n}\n\nexport declare interface ModelArtifactsInfo {\n /**\n * Timestamp for when the model is saved.\n */\n dateSaved: Date;\n\n /**\n * TODO (cais,yassogba) consider removing GraphDef as GraphDefs now\n * come in a JSON format and none of our IOHandlers support a non json\n * format. We could conder replacing this with 'Binary' if we want to\n * allow future handlers to save to non json formats (though they will\n * probably want more information than 'Binary').\n * Type of the model topology\n *\n * Type of the model topology\n *\n * Possible values:\n * - JSON: JSON config (human-readable, e.g., Keras JSON).\n * - GraphDef: TensorFlow\n * [GraphDef](https://www.tensorflow.org/extend/tool_developers/#graphdef)\n * protocol buffer (binary).\n */\n modelTopologyType: 'JSON'|'GraphDef';\n\n /**\n * Size of model topology (Keras JSON or GraphDef), in bytes.\n */\n modelTopologyBytes?: number;\n\n /**\n * Size of weight specification or manifest, in bytes.\n */\n weightSpecsBytes?: number;\n\n /**\n * Size of weight value data, in bytes.\n */\n weightDataBytes?: number;\n}\n\n/** Model training configuration. */\nexport declare interface TrainingConfig {\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n // See\n // tslint:disable-next-line:max-line-length\n // https://github.com/tensorflow/tfjs-layers/blob/master/src/keras_format/training_config.ts\n /** Optimizer used for the model training. */\n optimizer_config: {};\n\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n /** Loss function(s) for the model's output(s). */\n loss: string|string[]|{[key: string]: string};\n\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n /** Metric function(s) for the model's output(s). */\n metrics?: string[]|{[key: string]: string};\n\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n weighted_metrics?: string[];\n\n // TODO(cais): Tighten the typing once keras spec is available to tfjs-core.\n sample_weight_mode?: string;\n\n loss_weights?: number[]|{[key: string]: number};\n}\n\n/**\n * The serialized artifacts of a model, including topology and weights.\n *\n * The `modelTopology`, `trainingConfig`, `weightSpecs` and `weightData` fields\n * of this interface are optional, in order to support topology- or weights-only\n * saving and loading.\n *\n * Note this interface is used internally in IOHandlers. For the file format\n * written to disk as `model.json`, see `ModelJSON`.\n */\nexport declare interface ModelArtifacts {\n /**\n * Model topology.\n *\n * For Keras-style `tf.Model`s, this is a JSON object.\n * For TensorFlow-style models (e.g., `SavedModel`), this is the JSON\n * encoding of the `GraphDef` protocol buffer.\n */\n modelTopology?: {}|ArrayBuffer;\n\n /**\n * Serialized configuration for the model's training.\n */\n trainingConfig?: TrainingConfig;\n\n /**\n * Weight specifications.\n *\n * This corresponds to the weightsData below.\n */\n weightSpecs?: WeightsManifestEntry[];\n\n /**\n * Binary buffer for all weight values concatenated in the order specified\n * by `weightSpecs`.\n */\n weightData?: ArrayBuffer;\n\n /**\n * Hard-coded format name for models saved from TensorFlow.js or converted\n * by TensorFlow.js Converter.\n */\n format?: string;\n\n /**\n * What library is responsible for originally generating this artifact.\n *\n * Used for debugging purposes. E.g., 'TensorFlow.js v1.0.0'.\n */\n generatedBy?: string;\n\n /**\n * What library or tool is responsible for converting the original model\n * to this format, applicable only if the model is output by a converter.\n *\n * Used for debugging purposes. E.g., 'TensorFlow.js Converter v1.0.0'.\n *\n * A value of `null` means the model artifacts are generated without any\n * conversion process (e.g., saved directly from a TensorFlow.js\n * `tf.LayersModel` instance.)\n */\n convertedBy?: string|null;\n\n /**\n * User-defined metadata about the model.\n */\n userDefinedMetadata?: {};\n\n /**\n * Initializer for the model.\n */\n modelInitializer?: {};\n}\n\n/**\n * The on-disk format of the `model.json` file.\n *\n * TF.js 1.0 always populates the optional fields when writing model.json.\n * Prior versions did not provide those fields.\n */\nexport declare interface ModelJSON {\n /**\n * Model topology.\n *\n * For Keras-style `tf.Model`s, this is a JSON object.\n * For TensorFlow-style models (e.g., `SavedModel`), this is the JSON\n * encoding of the `GraphDef` protocol buffer.\n */\n modelTopology: {};\n\n /** Model training configuration. */\n trainingConfig?: TrainingConfig;\n\n /**\n * Weights manifest.\n *\n * The weights manifest consists of an ordered list of weight-manifest\n * groups. Each weight-manifest group consists of a number of weight values\n * stored in a number of paths. See the documentation of\n * `WeightsManifestConfig` for more details.\n */\n weightsManifest: WeightsManifestConfig;\n\n /**\n * Hard-coded format name for models saved from TensorFlow.js or converted\n * by TensorFlow.js Converter.\n */\n format?: string;\n\n /**\n * What library is responsible for originally generating this artifact.\n *\n * Used for debugging purposes. E.g., 'TensorFlow.js v1.0.0'.\n */\n generatedBy?: string;\n\n /**\n * What library or tool is responsible for converting the original model\n * to this format, applicable only if the model is output by a converter.\n *\n * Used for debugging purposes. E.g., 'TensorFlow.js Converter v1.0.0'.\n *\n * A value of `null` means the model artifacts are generated without any\n * conversion process (e.g., saved directly from a TensorFlow.js\n * `tf.LayersModel` instance.)\n */\n convertedBy?: string|null;\n\n /**\n * User-defined metadata about the model.\n */\n userDefinedMetadata?: {};\n\n /**\n * Initializer for the model.\n */\n modelInitializer?: {};\n}\n\n/**\n * Type definition for handlers of loading operations.\n */\nexport type LoadHandler = () => Promise;\n\n/**\n * Type definition for handlers of saving operations.\n */\nexport type SaveHandler = (modelArtifact: ModelArtifacts) =>\n Promise;\n\n/**\n * Interface for a model import/export handler.\n *\n * The `save` and `load` handlers are both optional, in order to allow handlers\n * that support only saving or loading.\n */\n// tslint:disable-next-line:interface-name\nexport interface IOHandler {\n save?: SaveHandler;\n load?: LoadHandler;\n}\n\n/**\n * An interface for the manager of a model store.\n *\n * A model store is defined as a storage medium on which multiple models can\n * be stored. Each stored model has a unique `path` as its identifier.\n * A `ModelStoreManager` for the store allows actions including\n *\n * - Listing the models stored in the store.\n * - Deleting a model from the store.\n */\nexport interface ModelStoreManager {\n /**\n * List all models in the model store.\n *\n * @returns A dictionary mapping paths of existing models to their\n * model artifacts info. Model artifacts info include type of the model's\n * topology, byte sizes of the topology, weights, etc.\n */\n listModels(): Promise<{[path: string]: ModelArtifactsInfo}>;\n\n /**\n * Remove a model specified by `path`.\n *\n * @param path\n * @returns ModelArtifactsInfo of the deleted model (if and only if deletion\n * is successful).\n * @throws Error if deletion fails, e.g., if no model exists at `path`.\n */\n removeModel(path: string): Promise;\n}\n\n/**\n * Callback for the progress of a long-running action such as an HTTP\n * request for a large binary object.\n *\n * `fraction` should be a number in the [0, 1] interval, indicating how\n * much of the action has completed.\n */\nexport type OnProgressCallback = (fraction: number) => void;\n\n/** @innamespace io */\nexport interface LoadOptions {\n /**\n * RequestInit (options) for HTTP requests.\n *\n * For detailed information on the supported fields, see\n * [https://developer.mozilla.org/en-US/docs/Web/API/Request/Request](\n * https://developer.mozilla.org/en-US/docs/Web/API/Request/Request)\n */\n requestInit?: RequestInit;\n\n /**\n * Progress callback.\n */\n onProgress?: OnProgressCallback;\n\n /**\n * A function used to override the `window.fetch` function.\n */\n fetchFunc?: Function;\n\n /**\n * Strict loading model: whether extraneous weights or missing\n * weights should trigger an `Error`.\n *\n * If `true`, require that the provided weights exactly match those\n * required by the layers. `false` means that both extra weights\n * and missing weights will be silently ignored.\n *\n * Default: `true`.\n */\n strict?: boolean;\n\n /**\n * Path prefix for weight files, by default this is calculated from the\n * path of the model JSON file.\n *\n * For instance, if the path to the model JSON file is\n * `http://localhost/foo/model.json`, then the default path prefix will be\n * `http://localhost/foo/`. If a weight file has the path value\n * `group1-shard1of2` in the weight manifest, then the weight file will be\n * loaded from `http://localhost/foo/group1-shard1of2` by default. However,\n * if you provide a `weightPathPrefix` value of\n * `http://localhost/foo/alt-weights`, then the weight file will be loaded\n * from the path `http://localhost/foo/alt-weights/group1-shard1of2` instead.\n */\n weightPathPrefix?: string;\n\n /**\n * Whether the module or model is to be loaded from TF Hub.\n *\n * Setting this to `true` allows passing a TF-Hub module URL, omitting the\n * standard model file name and the query parameters.\n *\n * Default: `false`.\n */\n fromTFHub?: boolean;\n\n /**\n * An async function to convert weight file name to URL. The weight file\n * names are stored in model.json's weightsManifest.paths field. By default we\n * consider weight files are colocated with the model.json file. For example:\n * model.json URL: https://www.google.com/models/1/model.json\n * group1-shard1of1.bin url:\n * https://www.google.com/models/1/group1-shard1of1.bin\n *\n * With this func you can convert the weight file name to any URL.\n */\n weightUrlConverter?: (weightFileName: string) => Promise;\n}\n\n/**\n * Additional options for Platform.fetch\n */\nexport interface RequestDetails {\n /**\n * Is this request for a binary file (as opposed to a json file)\n */\n isBinary?: boolean;\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {complex} from '../ops/complex';\n\nimport {tensor} from '../ops/tensor';\nimport {NamedTensor, NamedTensorMap} from '../tensor_types';\nimport {TypedArray} from '../types';\nimport {sizeFromShape} from '../util';\n\nimport {DTYPE_VALUE_SIZE_MAP, ModelArtifacts, ModelArtifactsInfo, WeightGroup, WeightsManifestEntry} from './types';\n\n/** Number of bytes reserved for the length of the string. (32bit integer). */\nconst NUM_BYTES_STRING_LENGTH = 4;\n\n/**\n * Encode a map from names to weight values as an ArrayBuffer, along with an\n * `Array` of `WeightsManifestEntry` as specification of the encoded weights.\n *\n * This function does not perform sharding.\n *\n * This function is the reverse of `decodeWeights`.\n *\n * @param tensors A map (\"dict\") from names to tensors.\n * @param group Group to which the weights belong (optional).\n * @returns A `Promise` of\n * - A flat `ArrayBuffer` with all the binary values of the `Tensor`s\n * concatenated.\n * - An `Array` of `WeightManifestEntry`s, carrying information including\n * tensor names, `dtype`s and shapes.\n * @throws Error: on unsupported tensor `dtype`.\n */\nexport async function encodeWeights(\n tensors: NamedTensorMap|NamedTensor[], group?: WeightGroup):\n Promise<{data: ArrayBuffer, specs: WeightsManifestEntry[]}> {\n // TODO(adarob, cais): Support quantization.\n const specs: WeightsManifestEntry[] = [];\n const dataPromises: Array> = [];\n\n const names: string[] = Array.isArray(tensors) ?\n tensors.map(tensor => tensor.name) :\n Object.keys(tensors);\n\n for (let i = 0; i < names.length; ++i) {\n const name = names[i];\n const t = Array.isArray(tensors) ? tensors[i].tensor : tensors[name];\n if (t.dtype !== 'float32' && t.dtype !== 'int32' && t.dtype !== 'bool' &&\n t.dtype !== 'string' && t.dtype !== 'complex64') {\n throw new Error(`Unsupported dtype in weight '${name}': ${t.dtype}`);\n }\n const spec: WeightsManifestEntry = {name, shape: t.shape, dtype: t.dtype};\n if (t.dtype === 'string') {\n const utf8bytes = new Promise(async resolve => {\n const vals = await t.bytes() as Uint8Array[];\n const totalNumBytes = vals.reduce((p, c) => p + c.length, 0) +\n NUM_BYTES_STRING_LENGTH * vals.length;\n const bytes = new Uint8Array(totalNumBytes);\n let offset = 0;\n for (let i = 0; i < vals.length; i++) {\n const val = vals[i];\n const bytesOfLength =\n new Uint8Array(new Uint32Array([val.length]).buffer);\n bytes.set(bytesOfLength, offset);\n offset += NUM_BYTES_STRING_LENGTH;\n bytes.set(val, offset);\n offset += val.length;\n }\n resolve(bytes);\n });\n dataPromises.push(utf8bytes);\n } else {\n dataPromises.push(t.data());\n }\n if (group != null) {\n spec.group = group;\n }\n specs.push(spec);\n }\n\n const tensorValues = await Promise.all(dataPromises);\n return {data: concatenateTypedArrays(tensorValues), specs};\n}\n\n/**\n * Decode flat ArrayBuffer as weights.\n *\n * This function does not handle sharding.\n *\n * This function is the reverse of `encodeWeights`.\n *\n * @param buffer A flat ArrayBuffer carrying the binary values of the tensors\n * concatenated in the order specified in `specs`.\n * @param specs Specifications of the names, dtypes and shapes of the tensors\n * whose value are encoded by `buffer`.\n * @return A map from tensor name to tensor value, with the names corresponding\n * to names in `specs`.\n * @throws Error, if any of the tensors has unsupported dtype.\n */\nexport function decodeWeights(\n buffer: ArrayBuffer, specs: WeightsManifestEntry[]): NamedTensorMap {\n // TODO(adarob, cais): Support quantization.\n const out: NamedTensorMap = {};\n let float16Decode: (buffer: Uint16Array) => Float32Array | undefined;\n let offset = 0;\n for (const spec of specs) {\n const name = spec.name;\n const dtype = spec.dtype;\n const shape = spec.shape;\n const size = sizeFromShape(shape);\n let values: TypedArray|string[]|Uint8Array[];\n\n if ('quantization' in spec) {\n const quantization = spec.quantization;\n if (quantization.dtype === 'uint8' || quantization.dtype === 'uint16') {\n if (!('min' in quantization && 'scale' in quantization)) {\n throw new Error(\n `Weight ${spec.name} with quantization ${quantization.dtype} ` +\n `doesn't have corresponding metadata min and scale.`);\n }\n } else if (quantization.dtype === 'float16') {\n if (dtype !== 'float32') {\n throw new Error(\n `Weight ${spec.name} is quantized with ${quantization.dtype} ` +\n `which only supports weights of type float32 not ${dtype}.`);\n }\n } else {\n throw new Error(\n `Weight ${spec.name} has unknown ` +\n `quantization dtype ${quantization.dtype}. ` +\n `Supported quantization dtypes are: ` +\n `'uint8', 'uint16', and 'float16'.`);\n }\n const quantizationSizeFactor = DTYPE_VALUE_SIZE_MAP[quantization.dtype];\n const byteBuffer =\n buffer.slice(offset, offset + size * quantizationSizeFactor);\n const quantizedArray = (quantization.dtype === 'uint8') ?\n new Uint8Array(byteBuffer) :\n new Uint16Array(byteBuffer);\n if (dtype === 'float32') {\n if (quantization.dtype === 'uint8' || quantization.dtype === 'uint16') {\n values = new Float32Array(quantizedArray.length);\n for (let i = 0; i < quantizedArray.length; i++) {\n const v = quantizedArray[i];\n values[i] = v * quantization.scale + quantization.min;\n }\n } else if (quantization.dtype === 'float16') {\n if (float16Decode === undefined) {\n float16Decode = getFloat16Decoder();\n }\n values = float16Decode(quantizedArray as Uint16Array);\n } else {\n throw new Error(\n `Unsupported quantization type ${quantization.dtype} ` +\n `for weight type float32.`);\n }\n } else if (dtype === 'int32') {\n if (quantization.dtype !== 'uint8' && quantization.dtype !== 'uint16') {\n throw new Error(\n `Unsupported quantization type ${quantization.dtype} ` +\n `for weight type int32.`);\n }\n values = new Int32Array(quantizedArray.length);\n for (let i = 0; i < quantizedArray.length; i++) {\n const v = quantizedArray[i];\n values[i] = Math.round(v * quantization.scale + quantization.min);\n }\n } else {\n throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);\n }\n offset += size * quantizationSizeFactor;\n } else if (dtype === 'string') {\n const size = sizeFromShape(spec.shape);\n values = [];\n for (let i = 0; i < size; i++) {\n const byteLength = new Uint32Array(\n buffer.slice(offset, offset + NUM_BYTES_STRING_LENGTH))[0];\n offset += NUM_BYTES_STRING_LENGTH;\n const bytes = new Uint8Array(buffer.slice(offset, offset + byteLength));\n (values as Uint8Array[]).push(bytes);\n offset += byteLength;\n }\n } else {\n const dtypeFactor = DTYPE_VALUE_SIZE_MAP[dtype];\n const byteBuffer = buffer.slice(offset, offset + size * dtypeFactor);\n\n if (dtype === 'float32') {\n values = new Float32Array(byteBuffer);\n } else if (dtype === 'int32') {\n values = new Int32Array(byteBuffer);\n } else if (dtype === 'bool') {\n values = new Uint8Array(byteBuffer);\n } else if (dtype === 'complex64') {\n values = new Float32Array(byteBuffer);\n const real = new Float32Array(values.length / 2);\n const image = new Float32Array(values.length / 2);\n for (let i = 0; i < real.length; i++) {\n real[i] = values[i * 2];\n image[i] = values[i * 2 + 1];\n }\n const realTensor = tensor(real, shape, 'float32');\n const imageTensor = tensor(image, shape, 'float32');\n out[name] = complex(realTensor, imageTensor);\n } else {\n throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`);\n }\n offset += size * dtypeFactor;\n }\n if (dtype !== 'complex64') {\n out[name] = tensor(values, shape, dtype);\n }\n }\n return out;\n}\n\n/**\n * Concatenate TypedArrays into an ArrayBuffer.\n */\nexport function concatenateTypedArrays(xs: TypedArray[]): ArrayBuffer {\n // TODO(adarob, cais): Support quantization.\n if (xs === null) {\n throw new Error(`Invalid input value: ${JSON.stringify(xs)}`);\n }\n\n let totalByteLength = 0;\n\n // `normalizedXs` is here for this reason: a `TypedArray`'s `buffer'\n // can have a different byte length from that of the `TypedArray` itself,\n // for example, when the `TypedArray` is created from an offset in an\n // `ArrayBuffer`. `normliazedXs` holds `TypedArray`s whose `buffer`s match\n // the `TypedArray` in byte length. If an element of `xs` does not show\n // this property, a new `TypedArray` that satisfy this property will be\n // constructed and pushed into `normalizedXs`.\n const normalizedXs: TypedArray[] = [];\n xs.forEach((x: TypedArray) => {\n totalByteLength += x.byteLength;\n // tslint:disable:no-any\n normalizedXs.push(\n x.byteLength === x.buffer.byteLength ? x :\n new (x.constructor as any)(x));\n if (!(x as any instanceof Float32Array || x as any instanceof Int32Array ||\n x as any instanceof Uint8Array)) {\n throw new Error(`Unsupported TypedArray subtype: ${x.constructor.name}`);\n }\n // tslint:enable:no-any\n });\n\n const y = new Uint8Array(totalByteLength);\n let offset = 0;\n normalizedXs.forEach((x: TypedArray) => {\n y.set(new Uint8Array(x.buffer), offset);\n offset += x.byteLength;\n });\n\n return y.buffer;\n}\n\n// Use Buffer on Node.js instead of Blob/atob/btoa\nconst useNodeBuffer = typeof Buffer !== 'undefined' &&\n (typeof Blob === 'undefined' || typeof atob === 'undefined' ||\n typeof btoa === 'undefined');\n\n/**\n * Calculate the byte length of a JavaScript string.\n *\n * Note that a JavaScript string can contain wide characters, therefore the\n * length of the string is not necessarily equal to the byte length.\n *\n * @param str Input string.\n * @returns Byte length.\n */\nexport function stringByteLength(str: string): number {\n if (useNodeBuffer) {\n return Buffer.byteLength(str);\n }\n return new Blob([str]).size;\n}\n\n/**\n * Encode an ArrayBuffer as a base64 encoded string.\n *\n * @param buffer `ArrayBuffer` to be converted.\n * @returns A string that base64-encodes `buffer`.\n */\nexport function arrayBufferToBase64String(buffer: ArrayBuffer): string {\n if (useNodeBuffer) {\n return Buffer.from(buffer).toString('base64');\n }\n const buf = new Uint8Array(buffer);\n let s = '';\n for (let i = 0, l = buf.length; i < l; i++) {\n s += String.fromCharCode(buf[i]);\n }\n return btoa(s);\n}\n\n/**\n * Decode a base64 string as an ArrayBuffer.\n *\n * @param str Base64 string.\n * @returns Decoded `ArrayBuffer`.\n */\nexport function base64StringToArrayBuffer(str: string): ArrayBuffer {\n if (useNodeBuffer) {\n const buf = Buffer.from(str, 'base64');\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);\n }\n const s = atob(str);\n const buffer = new Uint8Array(s.length);\n for (let i = 0; i < s.length; ++i) {\n buffer.set([s.charCodeAt(i)], i);\n }\n return buffer.buffer;\n}\n\n/**\n * Concatenate a number of ArrayBuffers into one.\n *\n * @param buffers A number of array buffers to concatenate.\n * @returns Result of concatenating `buffers` in order.\n */\nexport function concatenateArrayBuffers(buffers: ArrayBuffer[]): ArrayBuffer {\n if (buffers.length === 1) {\n return buffers[0];\n }\n\n let totalByteLength = 0;\n buffers.forEach((buffer: ArrayBuffer) => {\n totalByteLength += buffer.byteLength;\n });\n\n const temp = new Uint8Array(totalByteLength);\n let offset = 0;\n buffers.forEach((buffer: ArrayBuffer) => {\n temp.set(new Uint8Array(buffer), offset);\n offset += buffer.byteLength;\n });\n return temp.buffer;\n}\n\n/**\n * Get the basename of a path.\n *\n * Behaves in a way analogous to Linux's basename command.\n *\n * @param path\n */\nexport function basename(path: string): string {\n const SEPARATOR = '/';\n path = path.trim();\n while (path.endsWith(SEPARATOR)) {\n path = path.slice(0, path.length - 1);\n }\n const items = path.split(SEPARATOR);\n return items[items.length - 1];\n}\n\n/**\n * Populate ModelArtifactsInfo fields for a model with JSON topology.\n * @param modelArtifacts\n * @returns A ModelArtifactsInfo object.\n */\nexport function getModelArtifactsInfoForJSON(modelArtifacts: ModelArtifacts):\n ModelArtifactsInfo {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error('Expected JSON model topology, received ArrayBuffer.');\n }\n\n return {\n dateSaved: new Date(),\n modelTopologyType: 'JSON',\n modelTopologyBytes: modelArtifacts.modelTopology == null ?\n 0 :\n stringByteLength(JSON.stringify(modelArtifacts.modelTopology)),\n weightSpecsBytes: modelArtifacts.weightSpecs == null ?\n 0 :\n stringByteLength(JSON.stringify(modelArtifacts.weightSpecs)),\n weightDataBytes: modelArtifacts.weightData == null ?\n 0 :\n modelArtifacts.weightData.byteLength,\n };\n}\n\n/**\n * Computes mantisa table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 2048 mantissa lookup values.\n */\nfunction computeFloat16MantisaTable(): Uint32Array {\n const convertMantissa = (i: number): number => {\n let m = i << 13;\n let e = 0;\n\n while ((m & 0x00800000) === 0) {\n e -= 0x00800000;\n m <<= 1;\n }\n m &= ~0x00800000;\n e += 0x38800000;\n\n return m | e;\n };\n\n const mantisaTable = new Uint32Array(2048);\n\n mantisaTable[0] = 0;\n for (let i = 1; i < 1024; i++) {\n mantisaTable[i] = convertMantissa(i);\n }\n for (let i = 1024; i < 2048; i++) {\n mantisaTable[i] = 0x38000000 + ((i - 1024) << 13);\n }\n\n return mantisaTable;\n}\n\n/**\n * Computes exponent table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 64 exponent lookup values.\n */\nfunction computeFloat16ExponentTable(): Uint32Array {\n const exponentTable = new Uint32Array(64);\n\n exponentTable[0] = 0;\n exponentTable[31] = 0x47800000;\n exponentTable[32] = 0x80000000;\n exponentTable[63] = 0xc7800000;\n for (let i = 1; i < 31; i++) {\n exponentTable[i] = i << 23;\n }\n for (let i = 33; i < 63; i++) {\n exponentTable[i] = 0x80000000 + ((i - 32) << 23);\n }\n\n return exponentTable;\n}\n\n/**\n * Computes offset table for casting Float16 to Float32\n * See http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n *\n * @returns Uint32Array, 6d offset values.\n */\nfunction computeFloat16OffsetTable(): Uint32Array {\n const offsetTable = new Uint32Array(64);\n\n for (let i = 0; i < 64; i++) {\n offsetTable[i] = 1024;\n }\n offsetTable[0] = offsetTable[32] = 0;\n\n return offsetTable;\n}\n\n/**\n * Retrieve a Float16 decoder which will decode a ByteArray of Float16 values\n * to a Float32Array.\n *\n * @returns Function (buffer: Uint16Array) => Float32Array which decodes\n * the Uint16Array of Float16 bytes to a Float32Array.\n */\nexport function getFloat16Decoder(): (buffer: Uint16Array) => Float32Array {\n // Algorithm is based off of\n // http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf\n\n // Cache lookup tables\n const mantisaTable = computeFloat16MantisaTable();\n const exponentTable = computeFloat16ExponentTable();\n const offsetTable = computeFloat16OffsetTable();\n\n return (quantizedArray: Uint16Array) => {\n const buffer = new ArrayBuffer(4 * quantizedArray.length);\n const bufferUint32View = new Uint32Array(buffer);\n for (let index = 0; index < quantizedArray.length; index++) {\n const float16Bits = quantizedArray[index];\n const float32Bits =\n mantisaTable[offsetTable[float16Bits >> 10] + (float16Bits & 0x3ff)] +\n exponentTable[float16Bits >> 10];\n bufferUint32View[index] = float32Bits;\n }\n return new Float32Array(buffer);\n };\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {IOHandler, LoadOptions} from './types';\n\nexport type IORouter = (url: string|string[], loadOptions?: LoadOptions) =>\n IOHandler;\n\nexport class IORouterRegistry {\n // Singleton instance.\n private static instance: IORouterRegistry;\n\n private saveRouters: IORouter[];\n private loadRouters: IORouter[];\n\n private constructor() {\n this.saveRouters = [];\n this.loadRouters = [];\n }\n\n private static getInstance(): IORouterRegistry {\n if (IORouterRegistry.instance == null) {\n IORouterRegistry.instance = new IORouterRegistry();\n }\n return IORouterRegistry.instance;\n }\n\n /**\n * Register a save-handler router.\n *\n * @param saveRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `save` method defined or `null`.\n */\n static registerSaveRouter(saveRouter: IORouter) {\n IORouterRegistry.getInstance().saveRouters.push(saveRouter);\n }\n\n /**\n * Register a load-handler router.\n *\n * @param loadRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `load` method defined or `null`.\n */\n static registerLoadRouter(loadRouter: IORouter) {\n IORouterRegistry.getInstance().loadRouters.push(loadRouter);\n }\n\n /**\n * Look up IOHandler for saving, given a URL-like string.\n *\n * @param url\n * @returns If only one match is found, an instance of IOHandler with the\n * `save` method defined. If no match is found, `null`.\n * @throws Error, if more than one match is found.\n */\n static getSaveHandlers(url: string|string[]): IOHandler[] {\n return IORouterRegistry.getHandlers(url, 'save');\n }\n\n /**\n * Look up IOHandler for loading, given a URL-like string.\n *\n * @param url\n * @param loadOptions Optional, custom load options.\n * @returns All valid handlers for `url`, given the currently registered\n * handler routers.\n */\n static getLoadHandlers(url: string|string[], loadOptions?: LoadOptions):\n IOHandler[] {\n return IORouterRegistry.getHandlers(url, 'load', loadOptions);\n }\n\n private static getHandlers(\n url: string|string[], handlerType: 'save'|'load',\n loadOptions?: LoadOptions): IOHandler[] {\n const validHandlers: IOHandler[] = [];\n const routers = handlerType === 'load' ?\n IORouterRegistry.getInstance().loadRouters :\n IORouterRegistry.getInstance().saveRouters;\n routers.forEach(router => {\n const handler = router(url, loadOptions);\n if (handler !== null) {\n validHandlers.push(handler);\n }\n });\n return validHandlers;\n }\n}\n\nexport const registerSaveRouter = (loudRouter: IORouter) =>\n IORouterRegistry.registerSaveRouter(loudRouter);\nexport const registerLoadRouter = (loudRouter: IORouter) =>\n IORouterRegistry.registerLoadRouter(loudRouter);\nexport const getSaveHandlers = (url: string|string[]) =>\n IORouterRegistry.getSaveHandlers(url);\nexport const getLoadHandlers =\n (url: string|string[], loadOptions?: LoadOptions) =>\n IORouterRegistry.getLoadHandlers(url, loadOptions);\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\n\nimport {env} from '../environment';\n\nimport {getModelArtifactsInfoForJSON} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelArtifactsInfo, ModelStoreManager, SaveResult} from './types';\n\nconst DATABASE_NAME = 'tensorflowjs';\nconst DATABASE_VERSION = 1;\n\n// Model data and ModelArtifactsInfo (metadata) are stored in two separate\n// stores for efficient access of the list of stored models and their metadata.\n// 1. The object store for model data: topology, weights and weight manifests.\nconst MODEL_STORE_NAME = 'models_store';\n// 2. The object store for ModelArtifactsInfo, including meta-information such\n// as the type of topology (JSON vs binary), byte size of the topology, byte\n// size of the weights, etc.\nconst INFO_STORE_NAME = 'model_info_store';\n\n/**\n * Delete the entire database for tensorflow.js, including the models store.\n */\nexport async function deleteDatabase(): Promise {\n const idbFactory = getIndexedDBFactory();\n\n return new Promise((resolve, reject) => {\n const deleteRequest = idbFactory.deleteDatabase(DATABASE_NAME);\n deleteRequest.onsuccess = () => resolve();\n deleteRequest.onerror = error => reject(error);\n });\n}\n\nfunction getIndexedDBFactory(): IDBFactory {\n if (!env().getBool('IS_BROWSER')) {\n // TODO(cais): Add more info about what IOHandler subtypes are available.\n // Maybe point to a doc page on the web and/or automatically determine\n // the available IOHandlers and print them in the error message.\n throw new Error(\n 'Failed to obtain IndexedDB factory because the current environment' +\n 'is not a web browser.');\n }\n // tslint:disable-next-line:no-any\n const theWindow: any = typeof window === 'undefined' ? self : window;\n const factory = theWindow.indexedDB || theWindow.mozIndexedDB ||\n theWindow.webkitIndexedDB || theWindow.msIndexedDB ||\n theWindow.shimIndexedDB;\n if (factory == null) {\n throw new Error(\n 'The current browser does not appear to support IndexedDB.');\n }\n return factory;\n}\n\nfunction setUpDatabase(openRequest: IDBRequest) {\n const db = openRequest.result as IDBDatabase;\n db.createObjectStore(MODEL_STORE_NAME, {keyPath: 'modelPath'});\n db.createObjectStore(INFO_STORE_NAME, {keyPath: 'modelPath'});\n}\n\n/**\n * IOHandler subclass: Browser IndexedDB.\n *\n * See the doc string of `browserIndexedDB` for more details.\n */\nexport class BrowserIndexedDB implements IOHandler {\n protected readonly indexedDB: IDBFactory;\n protected readonly modelPath: string;\n\n static readonly URL_SCHEME = 'indexeddb://';\n\n constructor(modelPath: string) {\n this.indexedDB = getIndexedDBFactory();\n\n if (modelPath == null || !modelPath) {\n throw new Error(\n 'For IndexedDB, modelPath must not be null, undefined or empty.');\n }\n this.modelPath = modelPath;\n }\n\n async save(modelArtifacts: ModelArtifacts): Promise {\n // TODO(cais): Support saving GraphDef models.\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserLocalStorage.save() does not support saving model topology ' +\n 'in binary formats yet.');\n }\n\n return this.databaseAction(this.modelPath, modelArtifacts) as\n Promise;\n }\n\n async load(): Promise {\n return this.databaseAction(this.modelPath) as Promise;\n }\n\n /**\n * Perform database action to put model artifacts into or read model artifacts\n * from IndexedDB object store.\n *\n * Whether the action is put or get depends on whether `modelArtifacts` is\n * specified. If it is specified, the action will be put; otherwise the action\n * will be get.\n *\n * @param modelPath A unique string path for the model.\n * @param modelArtifacts If specified, it will be the model artifacts to be\n * stored in IndexedDB.\n * @returns A `Promise` of `SaveResult`, if the action is put, or a `Promise`\n * of `ModelArtifacts`, if the action is get.\n */\n private databaseAction(modelPath: string, modelArtifacts?: ModelArtifacts):\n Promise {\n return new Promise((resolve, reject) => {\n const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n\n if (modelArtifacts == null) {\n // Read model out from object store.\n const modelTx = db.transaction(MODEL_STORE_NAME, 'readonly');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n const getRequest = modelStore.get(this.modelPath);\n getRequest.onsuccess = () => {\n if (getRequest.result == null) {\n db.close();\n return reject(new Error(\n `Cannot find model with path '${this.modelPath}' ` +\n `in IndexedDB.`));\n } else {\n resolve(getRequest.result.modelArtifacts);\n }\n };\n getRequest.onerror = error => {\n db.close();\n return reject(getRequest.error);\n };\n modelTx.oncomplete = () => db.close();\n } else {\n // Put model into object store.\n const modelArtifactsInfo: ModelArtifactsInfo =\n getModelArtifactsInfoForJSON(modelArtifacts);\n // First, put ModelArtifactsInfo into info store.\n const infoTx = db.transaction(INFO_STORE_NAME, 'readwrite');\n let infoStore = infoTx.objectStore(INFO_STORE_NAME);\n const putInfoRequest =\n infoStore.put({modelPath: this.modelPath, modelArtifactsInfo});\n let modelTx: IDBTransaction;\n putInfoRequest.onsuccess = () => {\n // Second, put model data into model store.\n modelTx = db.transaction(MODEL_STORE_NAME, 'readwrite');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n const putModelRequest = modelStore.put({\n modelPath: this.modelPath,\n modelArtifacts,\n modelArtifactsInfo\n });\n putModelRequest.onsuccess = () => resolve({modelArtifactsInfo});\n putModelRequest.onerror = error => {\n // If the put-model request fails, roll back the info entry as\n // well.\n infoStore = infoTx.objectStore(INFO_STORE_NAME);\n const deleteInfoRequest = infoStore.delete(this.modelPath);\n deleteInfoRequest.onsuccess = () => {\n db.close();\n return reject(putModelRequest.error);\n };\n deleteInfoRequest.onerror = error => {\n db.close();\n return reject(putModelRequest.error);\n };\n };\n };\n putInfoRequest.onerror = error => {\n db.close();\n return reject(putInfoRequest.error);\n };\n infoTx.oncomplete = () => {\n if (modelTx == null) {\n db.close();\n } else {\n modelTx.oncomplete = () => db.close();\n }\n };\n }\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n}\n\nexport const indexedDBRouter: IORouter = (url: string|string[]) => {\n if (!env().getBool('IS_BROWSER')) {\n return null;\n } else {\n if (!Array.isArray(url) && url.startsWith(BrowserIndexedDB.URL_SCHEME)) {\n return browserIndexedDB(url.slice(BrowserIndexedDB.URL_SCHEME.length));\n } else {\n return null;\n }\n }\n};\nIORouterRegistry.registerSaveRouter(indexedDBRouter);\nIORouterRegistry.registerLoadRouter(indexedDBRouter);\n\n/**\n * Creates a browser IndexedDB IOHandler for saving and loading models.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(\n * tf.layers.dense({units: 1, inputShape: [100], activation: 'sigmoid'}));\n *\n * const saveResult = await model.save('indexeddb://MyModel'));\n * console.log(saveResult);\n * ```\n *\n * @param modelPath A unique identifier for the model to be saved. Must be a\n * non-empty string.\n * @returns An instance of `BrowserIndexedDB` (sublcass of `IOHandler`),\n * which can be used with, e.g., `tf.Model.save`.\n */\nexport function browserIndexedDB(modelPath: string): IOHandler {\n return new BrowserIndexedDB(modelPath);\n}\n\nfunction maybeStripScheme(key: string) {\n return key.startsWith(BrowserIndexedDB.URL_SCHEME) ?\n key.slice(BrowserIndexedDB.URL_SCHEME.length) :\n key;\n}\n\nexport class BrowserIndexedDBManager implements ModelStoreManager {\n private indexedDB: IDBFactory;\n\n constructor() {\n this.indexedDB = getIndexedDBFactory();\n }\n\n async listModels(): Promise<{[path: string]: ModelArtifactsInfo}> {\n return new Promise<{[path: string]: ModelArtifactsInfo}>(\n (resolve, reject) => {\n const openRequest =\n this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n const tx = db.transaction(INFO_STORE_NAME, 'readonly');\n const store = tx.objectStore(INFO_STORE_NAME);\n // tslint:disable:max-line-length\n // Need to cast `store` as `any` here because TypeScript's DOM\n // library does not have the `getAll()` method even though the\n // method is supported in the latest version of most mainstream\n // browsers:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAll\n // tslint:enable:max-line-length\n // tslint:disable-next-line:no-any\n const getAllInfoRequest = (store as any).getAll() as IDBRequest;\n getAllInfoRequest.onsuccess = () => {\n const out: {[path: string]: ModelArtifactsInfo} = {};\n for (const item of getAllInfoRequest.result) {\n out[item.modelPath] = item.modelArtifactsInfo;\n }\n resolve(out);\n };\n getAllInfoRequest.onerror = error => {\n db.close();\n return reject(getAllInfoRequest.error);\n };\n tx.oncomplete = () => db.close();\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n\n async removeModel(path: string): Promise {\n path = maybeStripScheme(path);\n return new Promise((resolve, reject) => {\n const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION);\n openRequest.onupgradeneeded = () => setUpDatabase(openRequest);\n\n openRequest.onsuccess = () => {\n const db = openRequest.result;\n const infoTx = db.transaction(INFO_STORE_NAME, 'readwrite');\n const infoStore = infoTx.objectStore(INFO_STORE_NAME);\n\n const getInfoRequest = infoStore.get(path);\n let modelTx: IDBTransaction;\n getInfoRequest.onsuccess = () => {\n if (getInfoRequest.result == null) {\n db.close();\n return reject(new Error(\n `Cannot find model with path '${path}' ` +\n `in IndexedDB.`));\n } else {\n // First, delete the entry in the info store.\n const deleteInfoRequest = infoStore.delete(path);\n const deleteModelData = () => {\n // Second, delete the entry in the model store.\n modelTx = db.transaction(MODEL_STORE_NAME, 'readwrite');\n const modelStore = modelTx.objectStore(MODEL_STORE_NAME);\n const deleteModelRequest = modelStore.delete(path);\n deleteModelRequest.onsuccess = () =>\n resolve(getInfoRequest.result.modelArtifactsInfo);\n deleteModelRequest.onerror = error =>\n reject(getInfoRequest.error);\n };\n // Proceed with deleting model data regardless of whether deletion\n // of info data succeeds or not.\n deleteInfoRequest.onsuccess = deleteModelData;\n deleteInfoRequest.onerror = error => {\n deleteModelData();\n db.close();\n return reject(getInfoRequest.error);\n };\n }\n };\n getInfoRequest.onerror = error => {\n db.close();\n return reject(getInfoRequest.error);\n };\n\n infoTx.oncomplete = () => {\n if (modelTx == null) {\n db.close();\n } else {\n modelTx.oncomplete = () => db.close();\n }\n };\n };\n openRequest.onerror = error => reject(openRequest.error);\n });\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\nimport {env} from '../environment';\n\nimport {assert} from '../util';\nimport {arrayBufferToBase64String, base64StringToArrayBuffer, getModelArtifactsInfoForJSON} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelArtifactsInfo, ModelStoreManager, SaveResult} from './types';\n\nconst PATH_SEPARATOR = '/';\nconst PATH_PREFIX = 'tensorflowjs_models';\nconst INFO_SUFFIX = 'info';\nconst MODEL_TOPOLOGY_SUFFIX = 'model_topology';\nconst WEIGHT_SPECS_SUFFIX = 'weight_specs';\nconst WEIGHT_DATA_SUFFIX = 'weight_data';\nconst MODEL_METADATA_SUFFIX = 'model_metadata';\n\n/**\n * Purge all tensorflow.js-saved model artifacts from local storage.\n *\n * @returns Paths of the models purged.\n */\nexport function purgeLocalStorageArtifacts(): string[] {\n if (!env().getBool('IS_BROWSER') || typeof window === 'undefined' ||\n typeof window.localStorage === 'undefined') {\n throw new Error(\n 'purgeLocalStorageModels() cannot proceed because local storage is ' +\n 'unavailable in the current environment.');\n }\n const LS = window.localStorage;\n const purgedModelPaths: string[] = [];\n for (let i = 0; i < LS.length; ++i) {\n const key = LS.key(i);\n const prefix = PATH_PREFIX + PATH_SEPARATOR;\n if (key.startsWith(prefix) && key.length > prefix.length) {\n LS.removeItem(key);\n const modelName = getModelPathFromKey(key);\n if (purgedModelPaths.indexOf(modelName) === -1) {\n purgedModelPaths.push(modelName);\n }\n }\n }\n return purgedModelPaths;\n}\n\nfunction getModelKeys(path: string): {\n info: string,\n topology: string,\n weightSpecs: string,\n weightData: string,\n modelMetadata: string\n} {\n return {\n info: [PATH_PREFIX, path, INFO_SUFFIX].join(PATH_SEPARATOR),\n topology: [PATH_PREFIX, path, MODEL_TOPOLOGY_SUFFIX].join(PATH_SEPARATOR),\n weightSpecs: [PATH_PREFIX, path, WEIGHT_SPECS_SUFFIX].join(PATH_SEPARATOR),\n weightData: [PATH_PREFIX, path, WEIGHT_DATA_SUFFIX].join(PATH_SEPARATOR),\n modelMetadata:\n [PATH_PREFIX, path, MODEL_METADATA_SUFFIX].join(PATH_SEPARATOR)\n };\n}\n\n/**\n * Get model path from a local-storage key.\n *\n * E.g., 'tensorflowjs_models/my/model/1/info' --> 'my/model/1'\n *\n * @param key\n */\nfunction getModelPathFromKey(key: string) {\n const items = key.split(PATH_SEPARATOR);\n if (items.length < 3) {\n throw new Error(`Invalid key format: ${key}`);\n }\n return items.slice(1, items.length - 1).join(PATH_SEPARATOR);\n}\n\nfunction maybeStripScheme(key: string) {\n return key.startsWith(BrowserLocalStorage.URL_SCHEME) ?\n key.slice(BrowserLocalStorage.URL_SCHEME.length) :\n key;\n}\n\ndeclare type LocalStorageKeys = {\n info: string,\n topology: string,\n weightSpecs: string,\n weightData: string,\n modelMetadata: string\n};\n\n/**\n * IOHandler subclass: Browser Local Storage.\n *\n * See the doc string to `browserLocalStorage` for more details.\n */\nexport class BrowserLocalStorage implements IOHandler {\n protected readonly LS: Storage;\n protected readonly modelPath: string;\n protected readonly keys: LocalStorageKeys;\n\n static readonly URL_SCHEME = 'localstorage://';\n\n constructor(modelPath: string) {\n if (!env().getBool('IS_BROWSER') || typeof window === 'undefined' ||\n typeof window.localStorage === 'undefined') {\n // TODO(cais): Add more info about what IOHandler subtypes are\n // available.\n // Maybe point to a doc page on the web and/or automatically determine\n // the available IOHandlers and print them in the error message.\n throw new Error(\n 'The current environment does not support local storage.');\n }\n this.LS = window.localStorage;\n\n if (modelPath == null || !modelPath) {\n throw new Error(\n 'For local storage, modelPath must not be null, undefined or empty.');\n }\n this.modelPath = modelPath;\n this.keys = getModelKeys(this.modelPath);\n }\n\n /**\n * Save model artifacts to browser local storage.\n *\n * See the documentation to `browserLocalStorage` for details on the saved\n * artifacts.\n *\n * @param modelArtifacts The model artifacts to be stored.\n * @returns An instance of SaveResult.\n */\n async save(modelArtifacts: ModelArtifacts): Promise {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserLocalStorage.save() does not support saving model topology ' +\n 'in binary formats yet.');\n } else {\n const topology = JSON.stringify(modelArtifacts.modelTopology);\n const weightSpecs = JSON.stringify(modelArtifacts.weightSpecs);\n\n const modelArtifactsInfo: ModelArtifactsInfo =\n getModelArtifactsInfoForJSON(modelArtifacts);\n\n try {\n this.LS.setItem(this.keys.info, JSON.stringify(modelArtifactsInfo));\n this.LS.setItem(this.keys.topology, topology);\n this.LS.setItem(this.keys.weightSpecs, weightSpecs);\n this.LS.setItem(\n this.keys.weightData,\n arrayBufferToBase64String(modelArtifacts.weightData));\n this.LS.setItem(this.keys.modelMetadata, JSON.stringify({\n format: modelArtifacts.format,\n generatedBy: modelArtifacts.generatedBy,\n convertedBy: modelArtifacts.convertedBy,\n userDefinedMetadata: modelArtifacts.userDefinedMetadata\n }));\n\n return {modelArtifactsInfo};\n } catch (err) {\n // If saving failed, clean up all items saved so far.\n this.LS.removeItem(this.keys.info);\n this.LS.removeItem(this.keys.topology);\n this.LS.removeItem(this.keys.weightSpecs);\n this.LS.removeItem(this.keys.weightData);\n this.LS.removeItem(this.keys.modelMetadata);\n\n throw new Error(\n `Failed to save model '${this.modelPath}' to local storage: ` +\n `size quota being exceeded is a possible cause of this failure: ` +\n `modelTopologyBytes=${modelArtifactsInfo.modelTopologyBytes}, ` +\n `weightSpecsBytes=${modelArtifactsInfo.weightSpecsBytes}, ` +\n `weightDataBytes=${modelArtifactsInfo.weightDataBytes}.`);\n }\n }\n }\n\n /**\n * Load a model from local storage.\n *\n * See the documentation to `browserLocalStorage` for details on the saved\n * artifacts.\n *\n * @returns The loaded model (if loading succeeds).\n */\n async load(): Promise {\n const info =\n JSON.parse(this.LS.getItem(this.keys.info)) as ModelArtifactsInfo;\n if (info == null) {\n throw new Error(\n `In local storage, there is no model with name '${this.modelPath}'`);\n }\n\n if (info.modelTopologyType !== 'JSON') {\n throw new Error(\n 'BrowserLocalStorage does not support loading non-JSON model ' +\n 'topology yet.');\n }\n\n const out: ModelArtifacts = {};\n\n // Load topology.\n const topology = JSON.parse(this.LS.getItem(this.keys.topology));\n if (topology == null) {\n throw new Error(\n `In local storage, the topology of model '${this.modelPath}' ` +\n `is missing.`);\n }\n out.modelTopology = topology;\n\n // Load weight specs.\n const weightSpecs = JSON.parse(this.LS.getItem(this.keys.weightSpecs));\n if (weightSpecs == null) {\n throw new Error(\n `In local storage, the weight specs of model '${this.modelPath}' ` +\n `are missing.`);\n }\n out.weightSpecs = weightSpecs;\n\n // Load meta-data fields.\n const metadataString = this.LS.getItem(this.keys.modelMetadata);\n if (metadataString != null) {\n const metadata = JSON.parse(metadataString) as ModelArtifacts;\n out.format = metadata['format'];\n out.generatedBy = metadata['generatedBy'];\n out.convertedBy = metadata['convertedBy'];\n out.userDefinedMetadata = metadata['userDefinedMetadata'];\n }\n\n // Load weight data.\n const weightDataBase64 = this.LS.getItem(this.keys.weightData);\n if (weightDataBase64 == null) {\n throw new Error(\n `In local storage, the binary weight values of model ` +\n `'${this.modelPath}' are missing.`);\n }\n out.weightData = base64StringToArrayBuffer(weightDataBase64);\n\n return out;\n }\n}\n\nexport const localStorageRouter: IORouter = (url: string|string[]) => {\n if (!env().getBool('IS_BROWSER')) {\n return null;\n } else {\n if (!Array.isArray(url) && url.startsWith(BrowserLocalStorage.URL_SCHEME)) {\n return browserLocalStorage(\n url.slice(BrowserLocalStorage.URL_SCHEME.length));\n } else {\n return null;\n }\n }\n};\nIORouterRegistry.registerSaveRouter(localStorageRouter);\nIORouterRegistry.registerLoadRouter(localStorageRouter);\n\n/**\n * Factory function for local storage IOHandler.\n *\n * This `IOHandler` supports both `save` and `load`.\n *\n * For each model's saved artifacts, four items are saved to local storage.\n * - `${PATH_SEPARATOR}/${modelPath}/info`: Contains meta-info about the\n * model, such as date saved, type of the topology, size in bytes, etc.\n * - `${PATH_SEPARATOR}/${modelPath}/topology`: Model topology. For Keras-\n * style models, this is a stringized JSON.\n * - `${PATH_SEPARATOR}/${modelPath}/weight_specs`: Weight specs of the\n * model, can be used to decode the saved binary weight values (see\n * item below).\n * - `${PATH_SEPARATOR}/${modelPath}/weight_data`: Concatenated binary\n * weight values, stored as a base64-encoded string.\n *\n * Saving may throw an `Error` if the total size of the artifacts exceed the\n * browser-specific quota.\n *\n * @param modelPath A unique identifier for the model to be saved. Must be a\n * non-empty string.\n * @returns An instance of `IOHandler`, which can be used with, e.g.,\n * `tf.Model.save`.\n */\nexport function browserLocalStorage(modelPath: string): IOHandler {\n return new BrowserLocalStorage(modelPath);\n}\n\nexport class BrowserLocalStorageManager implements ModelStoreManager {\n private readonly LS: Storage;\n\n constructor() {\n assert(\n env().getBool('IS_BROWSER'),\n () => 'Current environment is not a web browser');\n assert(\n typeof window === 'undefined' ||\n typeof window.localStorage !== 'undefined',\n () => 'Current browser does not appear to support localStorage');\n this.LS = window.localStorage;\n }\n\n async listModels(): Promise<{[path: string]: ModelArtifactsInfo}> {\n const out: {[path: string]: ModelArtifactsInfo} = {};\n const prefix = PATH_PREFIX + PATH_SEPARATOR;\n const suffix = PATH_SEPARATOR + INFO_SUFFIX;\n for (let i = 0; i < this.LS.length; ++i) {\n const key = this.LS.key(i);\n if (key.startsWith(prefix) && key.endsWith(suffix)) {\n const modelPath = getModelPathFromKey(key);\n out[modelPath] = JSON.parse(this.LS.getItem(key)) as ModelArtifactsInfo;\n }\n }\n return out;\n }\n\n async removeModel(path: string): Promise {\n path = maybeStripScheme(path);\n const keys = getModelKeys(path);\n if (this.LS.getItem(keys.info) == null) {\n throw new Error(`Cannot find model at path '${path}'`);\n }\n const info = JSON.parse(this.LS.getItem(keys.info)) as ModelArtifactsInfo;\n\n this.LS.removeItem(keys.info);\n this.LS.removeItem(keys.topology);\n this.LS.removeItem(keys.weightSpecs);\n this.LS.removeItem(keys.weightData);\n return info;\n }\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Classes and functions for model management across multiple storage mediums.\n *\n * Supported client actions:\n * - Listing models on all registered storage mediums.\n * - Remove model by URL from any registered storage mediums, by using URL\n * string.\n * - Moving or copying model from one path to another in the same medium or from\n * one medium to another, by using URL strings.\n */\n\nimport {assert} from '../util';\n\nimport {IORouterRegistry} from './router_registry';\nimport {ModelArtifactsInfo, ModelStoreManager} from './types';\n\nconst URL_SCHEME_SUFFIX = '://';\n\nexport class ModelStoreManagerRegistry {\n // Singleton instance.\n private static instance: ModelStoreManagerRegistry;\n\n private managers: {[scheme: string]: ModelStoreManager};\n\n private constructor() {\n this.managers = {};\n }\n\n private static getInstance(): ModelStoreManagerRegistry {\n if (ModelStoreManagerRegistry.instance == null) {\n ModelStoreManagerRegistry.instance = new ModelStoreManagerRegistry();\n }\n return ModelStoreManagerRegistry.instance;\n }\n\n /**\n * Register a save-handler router.\n *\n * @param saveRouter A function that maps a URL-like string onto an instance\n * of `IOHandler` with the `save` method defined or `null`.\n */\n static registerManager(scheme: string, manager: ModelStoreManager) {\n assert(scheme != null, () => 'scheme must not be undefined or null.');\n if (scheme.endsWith(URL_SCHEME_SUFFIX)) {\n scheme = scheme.slice(0, scheme.indexOf(URL_SCHEME_SUFFIX));\n }\n assert(scheme.length > 0, () => 'scheme must not be an empty string.');\n const registry = ModelStoreManagerRegistry.getInstance();\n assert(\n registry.managers[scheme] == null,\n () => `A model store manager is already registered for scheme '${\n scheme}'.`);\n registry.managers[scheme] = manager;\n }\n\n static getManager(scheme: string): ModelStoreManager {\n const manager = this.getInstance().managers[scheme];\n if (manager == null) {\n throw new Error(`Cannot find model manager for scheme '${scheme}'`);\n }\n return manager;\n }\n\n static getSchemes(): string[] {\n return Object.keys(this.getInstance().managers);\n }\n}\n\n/**\n * Helper method for parsing a URL string into a scheme and a path.\n *\n * @param url E.g., 'localstorage://my-model'\n * @returns A dictionary with two fields: scheme and path.\n * Scheme: e.g., 'localstorage' in the example above.\n * Path: e.g., 'my-model' in the example above.\n */\nfunction parseURL(url: string): {scheme: string, path: string} {\n if (url.indexOf(URL_SCHEME_SUFFIX) === -1) {\n throw new Error(\n `The url string provided does not contain a scheme. ` +\n `Supported schemes are: ` +\n `${ModelStoreManagerRegistry.getSchemes().join(',')}`);\n }\n return {\n scheme: url.split(URL_SCHEME_SUFFIX)[0],\n path: url.split(URL_SCHEME_SUFFIX)[1],\n };\n}\n\nasync function cloneModelInternal(\n sourceURL: string, destURL: string,\n deleteSource = false): Promise {\n assert(\n sourceURL !== destURL,\n () => `Old path and new path are the same: '${sourceURL}'`);\n\n const loadHandlers = IORouterRegistry.getLoadHandlers(sourceURL);\n assert(\n loadHandlers.length > 0,\n () => `Copying failed because no load handler is found for source URL ${\n sourceURL}.`);\n assert(\n loadHandlers.length < 2,\n () => `Copying failed because more than one (${loadHandlers.length}) ` +\n `load handlers for source URL ${sourceURL}.`);\n const loadHandler = loadHandlers[0];\n\n const saveHandlers = IORouterRegistry.getSaveHandlers(destURL);\n assert(\n saveHandlers.length > 0,\n () => `Copying failed because no save handler is found for destination ` +\n `URL ${destURL}.`);\n assert(\n saveHandlers.length < 2,\n () => `Copying failed because more than one (${loadHandlers.length}) ` +\n `save handlers for destination URL ${destURL}.`);\n const saveHandler = saveHandlers[0];\n\n const sourceScheme = parseURL(sourceURL).scheme;\n const sourcePath = parseURL(sourceURL).path;\n const sameMedium = sourceScheme === parseURL(sourceURL).scheme;\n\n const modelArtifacts = await loadHandler.load();\n\n // If moving within the same storage medium, remove the old model as soon as\n // the loading is done. Without doing this, it is possible that the combined\n // size of the two models will cause the cloning to fail.\n if (deleteSource && sameMedium) {\n await ModelStoreManagerRegistry.getManager(sourceScheme)\n .removeModel(sourcePath);\n }\n\n const saveResult = await saveHandler.save(modelArtifacts);\n\n // If moving between mediums, the deletion is done after the save succeeds.\n // This guards against the case in which saving to the destination medium\n // fails.\n if (deleteSource && !sameMedium) {\n await ModelStoreManagerRegistry.getManager(sourceScheme)\n .removeModel(sourcePath);\n }\n\n return saveResult.modelArtifactsInfo;\n}\n\n/**\n * List all models stored in registered storage mediums.\n *\n * For a web browser environment, the registered mediums are Local Storage and\n * IndexedDB.\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Delete the model.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n * ```\n *\n * @returns A `Promise` of a dictionary mapping URLs of existing models to\n * their model artifacts info. URLs include medium-specific schemes, e.g.,\n * 'indexeddb://my/model/1'. Model artifacts info include type of the\n * model's topology, byte sizes of the topology, weights, etc.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function listModels(): Promise<{[url: string]: ModelArtifactsInfo}> {\n const schemes = ModelStoreManagerRegistry.getSchemes();\n const out: {[url: string]: ModelArtifactsInfo} = {};\n for (const scheme of schemes) {\n const schemeOut =\n await ModelStoreManagerRegistry.getManager(scheme).listModels();\n for (const path in schemeOut) {\n const url = scheme + URL_SCHEME_SUFFIX + path;\n out[url] = schemeOut[path];\n }\n }\n return out;\n}\n\n/**\n * Remove a model specified by URL from a reigstered storage medium.\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Delete the model.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n * ```\n *\n * @param url A URL to a stored model, with a scheme prefix, e.g.,\n * 'localstorage://my-model-1', 'indexeddb://my/model/2'.\n * @returns ModelArtifactsInfo of the deleted model (if and only if deletion\n * is successful).\n * @throws Error if deletion fails, e.g., if no model exists at `path`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function removeModel(url: string): Promise {\n const schemeAndPath = parseURL(url);\n const manager = ModelStoreManagerRegistry.getManager(schemeAndPath.scheme);\n return manager.removeModel(schemeAndPath.path);\n}\n\n/**\n * Copy a model from one URL to another.\n *\n * This function supports:\n *\n * 1. Copying within a storage medium, e.g.,\n * `tf.io.copyModel('localstorage://model-1', 'localstorage://model-2')`\n * 2. Copying between two storage mediums, e.g.,\n * `tf.io.copyModel('localstorage://model-1', 'indexeddb://model-1')`\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Copy the model, from Local Storage to IndexedDB.\n * await tf.io.copyModel(\n * 'localstorage://demo/management/model1',\n * 'indexeddb://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Remove both models.\n * await tf.io.removeModel('localstorage://demo/management/model1');\n * await tf.io.removeModel('indexeddb://demo/management/model1');\n * ```\n *\n * @param sourceURL Source URL of copying.\n * @param destURL Destination URL of copying.\n * @returns ModelArtifactsInfo of the copied model (if and only if copying\n * is successful).\n * @throws Error if copying fails, e.g., if no model exists at `sourceURL`, or\n * if `oldPath` and `newPath` are identical.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function copyModel(\n sourceURL: string, destURL: string): Promise {\n const deleteSource = false;\n return cloneModelInternal(sourceURL, destURL, deleteSource);\n}\n\n/**\n * Move a model from one URL to another.\n *\n * This function supports:\n *\n * 1. Moving within a storage medium, e.g.,\n * `tf.io.moveModel('localstorage://model-1', 'localstorage://model-2')`\n * 2. Moving between two storage mediums, e.g.,\n * `tf.io.moveModel('localstorage://model-1', 'indexeddb://model-1')`\n *\n * ```js\n * // First create and save a model.\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * await model.save('localstorage://demo/management/model1');\n *\n * // Then list existing models.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Move the model, from Local Storage to IndexedDB.\n * await tf.io.moveModel(\n * 'localstorage://demo/management/model1',\n * 'indexeddb://demo/management/model1');\n *\n * // List models again.\n * console.log(JSON.stringify(await tf.io.listModels()));\n *\n * // Remove the moved model.\n * await tf.io.removeModel('indexeddb://demo/management/model1');\n * ```\n *\n * @param sourceURL Source URL of moving.\n * @param destURL Destination URL of moving.\n * @returns ModelArtifactsInfo of the copied model (if and only if copying\n * is successful).\n * @throws Error if moving fails, e.g., if no model exists at `sourceURL`, or\n * if `oldPath` and `newPath` are identical.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Management',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nasync function moveModel(\n sourceURL: string, destURL: string): Promise {\n const deleteSource = true;\n return cloneModelInternal(sourceURL, destURL, deleteSource);\n}\n\nexport {moveModel, copyModel, removeModel, listModels};\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport '../flags';\n\nimport {env} from '../environment';\nimport {BrowserIndexedDB, BrowserIndexedDBManager} from '../io/indexed_db';\nimport {BrowserLocalStorage, BrowserLocalStorageManager} from '../io/local_storage';\nimport {ModelStoreManagerRegistry} from '../io/model_management';\n\nimport {Platform} from './platform';\n\nexport class PlatformBrowser implements Platform {\n // According to the spec, the built-in encoder can do only UTF-8 encoding.\n // https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder\n private textEncoder: TextEncoder;\n\n fetch(path: string, init?: RequestInit): Promise {\n return fetch(path, init);\n }\n\n now(): number {\n return performance.now();\n }\n\n encode(text: string, encoding: string): Uint8Array {\n if (encoding !== 'utf-8' && encoding !== 'utf8') {\n throw new Error(\n `Browser's encoder only supports utf-8, but got ${encoding}`);\n }\n if (this.textEncoder == null) {\n this.textEncoder = new TextEncoder();\n }\n return this.textEncoder.encode(text);\n }\n decode(bytes: Uint8Array, encoding: string): string {\n return new TextDecoder(encoding).decode(bytes);\n }\n}\n\nif (env().get('IS_BROWSER')) {\n env().setPlatform('browser', new PlatformBrowser());\n\n // Register LocalStorage IOHandler\n try {\n ModelStoreManagerRegistry.registerManager(\n BrowserLocalStorage.URL_SCHEME, new BrowserLocalStorageManager());\n } catch (err) {\n }\n\n // Register IndexedDB IOHandler\n try {\n ModelStoreManagerRegistry.registerManager(\n BrowserIndexedDB.URL_SCHEME, new BrowserIndexedDBManager());\n } catch (err) {\n }\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {env} from '../environment';\n\nimport {Platform} from './platform';\n\n// We are wrapping this within an object so it can be stubbed by Jasmine.\nexport const getNodeFetch = {\n // tslint:disable-next-line:no-require-imports\n importFetch: () => require('node-fetch')\n};\n\ntype FetchFn = (url: string, init?: RequestInit) => Promise;\nlet systemFetch: FetchFn;\n// These getters and setters are for testing so we don't export a mutable\n// variable.\nexport function resetSystemFetch() {\n systemFetch = null;\n}\nexport function setSystemFetch(fetchFn: FetchFn) {\n systemFetch = fetchFn;\n}\nexport function getSystemFetch(): FetchFn {\n return systemFetch;\n}\n\nexport class PlatformNode implements Platform {\n private textEncoder: TextEncoder;\n // tslint:disable-next-line:no-any\n util: any;\n\n constructor() {\n // tslint:disable-next-line:no-require-imports\n this.util = require('util');\n // According to the spec, the built-in encoder can do only UTF-8 encoding.\n // https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder/TextEncoder\n this.textEncoder = new this.util.TextEncoder();\n }\n\n fetch(path: string, requestInits?: RequestInit): Promise {\n if (env().global.fetch != null) {\n return env().global.fetch(path, requestInits);\n }\n\n if (systemFetch == null) {\n systemFetch = getNodeFetch.importFetch();\n }\n return systemFetch(path, requestInits);\n }\n\n now(): number {\n const time = process.hrtime();\n return time[0] * 1000 + time[1] / 1000000;\n }\n\n encode(text: string, encoding: string): Uint8Array {\n if (encoding !== 'utf-8' && encoding !== 'utf8') {\n throw new Error(\n `Node built-in encoder only supports utf-8, but got ${encoding}`);\n }\n return this.textEncoder.encode(text);\n }\n decode(bytes: Uint8Array, encoding: string): string {\n if (bytes.length === 0) {\n return '';\n }\n return new this.util.TextDecoder(encoding).decode(bytes);\n }\n}\n\nif (env().get('IS_NODE')) {\n env().setPlatform('node', new PlatformNode());\n}\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {TensorBuffer} from '../tensor';\nimport {DataType, DataTypeMap, Rank, ShapeMap} from '../types';\nimport * as util from '../util';\n\n/**\n * Creates an empty `tf.TensorBuffer` with the specified `shape` and `dtype`.\n *\n * The values are stored in CPU as `TypedArray`. Fill the buffer using\n * `buffer.set()`, or by modifying directly `buffer.values`.\n *\n * When done, call `buffer.toTensor()` to get an immutable `tf.Tensor` with\n * those values.\n *\n * ```js\n * // Create a buffer and set values at particular indices.\n * const buffer = tf.buffer([2, 2]);\n * buffer.set(3, 0, 0);\n * buffer.set(5, 1, 0);\n *\n * // Convert the buffer back to a tensor.\n * buffer.toTensor().print();\n * ```\n *\n * @param shape An array of integers defining the output tensor shape.\n * @param dtype The dtype of the buffer. Defaults to 'float32'.\n * @param values The values of the buffer as `TypedArray`. Defaults to\n * zeros.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function buffer(\n shape: ShapeMap[R], dtype: D = 'float32' as D,\n values?: DataTypeMap[D]): TensorBuffer {\n dtype = dtype || 'float32' as D;\n util.assertNonNegativeIntegerDimensions(shape);\n return new TensorBuffer(shape, dtype, values);\n}\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE} from '../engine';\nimport {Cast, CastAttrs, CastInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {DataType, TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Casts a `tf.Tensor` to a new dtype.\n *\n * ```js\n * const x = tf.tensor1d([1.5, 2.5, 3]);\n * tf.cast(x, 'int32').print();\n * ```\n * @param x The input tensor to be casted.\n * @param dtype The dtype to cast the input tensor to.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction cast_(x: T|TensorLike, dtype: DataType): T {\n const $x = convertToTensor(x, 'x', 'cast');\n\n // Sanity checks.\n if (!util.isValidDtype(dtype)) {\n throw new Error(`Failed to cast to unknown dtype ${dtype}`);\n }\n if (dtype === 'string' && $x.dtype !== 'string' ||\n dtype !== 'string' && $x.dtype === 'string') {\n throw new Error('Only strings can be casted to strings');\n }\n\n const inputs: CastInputs = {x: $x};\n const attrs: CastAttrs = {dtype};\n\n return ENGINE.runKernelFunc(\n backend => backend.cast($x, dtype), inputs as {} as NamedTensorMap,\n null /* grad */, Cast, attrs as {} as NamedAttrMap);\n}\n\nexport const cast = op({cast_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Identity, IdentityInputs} from '../kernel_names';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\n\n/**\n * Creates a new tensor with the same values and shape as the specified\n * tensor.\n *\n * ```js\n * const x = tf.tensor([1, 2]);\n *\n * x.clone().print();\n * ```\n *\n * @param x The tensor to clone.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction clone_(x: T|TensorLike): T {\n const $x = convertToTensor(x, 'x', 'clone', null);\n const forward = () =>\n ENGINE.makeTensorFromDataId($x.dataId, $x.shape, $x.dtype) as T;\n\n const inputs: IdentityInputs = {x: $x};\n\n // Note this op is called tf.identity in python. Hence the kernel name used\n // here.\n return ENGINE.runKernelFunc(\n forward, inputs as {} as NamedTensorMap, null /* grad */, Identity);\n}\n\nexport const clone = op({clone_});\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor} from '../tensor';\n\n/**\n * Prints information about the `tf.Tensor` including its data.\n *\n * ```js\n * const verbose = true;\n * tf.tensor2d([1, 2, 3, 4], [2, 2]).print(verbose);\n * ```\n * @param x The tensor to be printed.\n * @param verbose Whether to print verbose information about the ` Tensor`,\n * including dtype and size.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function print(x: T, verbose = false): void {\n console.log(x.toString(verbose));\n}\n", "/**\n * @license\n * Copyright 2020 Google Inc. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Required side effectful code for tfjs-core\n\n// Set up Engine and ENV\nimport {getOrMakeEngine} from './engine';\ngetOrMakeEngine();\n\n// Register backend-agnostic flags.\nimport './flags';\n// Register platforms\nimport './platforms/platform_browser';\nimport './platforms/platform_node';\n\n// Set up OpHandler\nimport {buffer} from './ops/buffer';\nimport {cast} from './ops/cast';\nimport {clone} from './ops/clone';\nimport {print} from './ops/print';\nimport {OpHandler, setOpHandler} from './tensor';\nconst opHandler: OpHandler = {\n buffer,\n cast,\n clone,\n print\n};\nsetOpHandler(opHandler);\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * IOHandlers related to files, such as browser-triggered file downloads,\n * user-selected files in browser.\n */\n\nimport '../flags';\nimport {env} from '../environment';\n\nimport {basename, concatenateArrayBuffers, getModelArtifactsInfoForJSON} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, ModelArtifacts, ModelJSON, SaveResult, WeightsManifestConfig, WeightsManifestEntry} from './types';\n\nconst DEFAULT_FILE_NAME_PREFIX = 'model';\nconst DEFAULT_JSON_EXTENSION_NAME = '.json';\nconst DEFAULT_WEIGHT_DATA_EXTENSION_NAME = '.weights.bin';\n\nfunction defer(f: () => T): Promise {\n return new Promise(resolve => setTimeout(resolve)).then(f);\n}\n\nexport class BrowserDownloads implements IOHandler {\n private readonly modelTopologyFileName: string;\n private readonly weightDataFileName: string;\n private readonly jsonAnchor: HTMLAnchorElement;\n private readonly weightDataAnchor: HTMLAnchorElement;\n\n static readonly URL_SCHEME = 'downloads://';\n\n constructor(fileNamePrefix?: string) {\n if (!env().getBool('IS_BROWSER')) {\n // TODO(cais): Provide info on what IOHandlers are available under the\n // current environment.\n throw new Error(\n 'browserDownloads() cannot proceed because the current environment ' +\n 'is not a browser.');\n }\n\n if (fileNamePrefix.startsWith(BrowserDownloads.URL_SCHEME)) {\n fileNamePrefix = fileNamePrefix.slice(BrowserDownloads.URL_SCHEME.length);\n }\n if (fileNamePrefix == null || fileNamePrefix.length === 0) {\n fileNamePrefix = DEFAULT_FILE_NAME_PREFIX;\n }\n\n this.modelTopologyFileName = fileNamePrefix + DEFAULT_JSON_EXTENSION_NAME;\n this.weightDataFileName =\n fileNamePrefix + DEFAULT_WEIGHT_DATA_EXTENSION_NAME;\n }\n\n async save(modelArtifacts: ModelArtifacts): Promise {\n if (typeof (document) === 'undefined') {\n throw new Error(\n 'Browser downloads are not supported in ' +\n 'this environment since `document` is not present');\n }\n const weightsURL = window.URL.createObjectURL(new Blob(\n [modelArtifacts.weightData], {type: 'application/octet-stream'}));\n\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserDownloads.save() does not support saving model topology ' +\n 'in binary formats yet.');\n } else {\n const weightsManifest: WeightsManifestConfig = [{\n paths: ['./' + this.weightDataFileName],\n weights: modelArtifacts.weightSpecs\n }];\n const modelTopologyAndWeightManifest: ModelJSON = {\n modelTopology: modelArtifacts.modelTopology,\n format: modelArtifacts.format,\n generatedBy: modelArtifacts.generatedBy,\n convertedBy: modelArtifacts.convertedBy,\n weightsManifest\n };\n const modelTopologyAndWeightManifestURL =\n window.URL.createObjectURL(new Blob(\n [JSON.stringify(modelTopologyAndWeightManifest)],\n {type: 'application/json'}));\n\n // If anchor elements are not provided, create them without attaching them\n // to parents, so that the downloaded file names can be controlled.\n const jsonAnchor = this.jsonAnchor == null ? document.createElement('a') :\n this.jsonAnchor;\n jsonAnchor.download = this.modelTopologyFileName;\n jsonAnchor.href = modelTopologyAndWeightManifestURL;\n // Trigger downloads by evoking a click event on the download anchors.\n // When multiple downloads are started synchronously, Firefox will only\n // save the last one.\n await defer(() => jsonAnchor.dispatchEvent(new MouseEvent('click')));\n\n if (modelArtifacts.weightData != null) {\n const weightDataAnchor = this.weightDataAnchor == null ?\n document.createElement('a') :\n this.weightDataAnchor;\n weightDataAnchor.download = this.weightDataFileName;\n weightDataAnchor.href = weightsURL;\n await defer(\n () => weightDataAnchor.dispatchEvent(new MouseEvent('click')));\n }\n\n return {modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts)};\n }\n }\n}\n\nclass BrowserFiles implements IOHandler {\n private readonly files: File[];\n\n constructor(files: File[]) {\n if (files == null || files.length < 1) {\n throw new Error(\n `When calling browserFiles, at least 1 file is required, ` +\n `but received ${files}`);\n }\n this.files = files;\n }\n\n async load(): Promise {\n const jsonFile = this.files[0];\n const weightFiles = this.files.slice(1);\n\n return new Promise((resolve, reject) => {\n const jsonReader = new FileReader();\n jsonReader.onload = (event: Event) => {\n // tslint:disable-next-line:no-any\n const modelJSON = JSON.parse((event.target as any).result) as ModelJSON;\n const modelTopology = modelJSON.modelTopology;\n if (modelTopology == null) {\n reject(new Error(\n `modelTopology field is missing from file ${jsonFile.name}`));\n return;\n }\n\n if (weightFiles.length === 0) {\n resolve({modelTopology});\n }\n\n const weightsManifest = modelJSON.weightsManifest;\n if (weightsManifest == null) {\n reject(new Error(\n `weightManifest field is missing from file ${jsonFile.name}`));\n return;\n }\n\n let pathToFile: {[path: string]: File};\n try {\n pathToFile =\n this.checkManifestAndWeightFiles(weightsManifest, weightFiles);\n } catch (err) {\n reject(err);\n return;\n }\n\n const weightSpecs: WeightsManifestEntry[] = [];\n const paths: string[] = [];\n const perFileBuffers: ArrayBuffer[] = [];\n weightsManifest.forEach(weightsGroup => {\n weightsGroup.paths.forEach(path => {\n paths.push(path);\n perFileBuffers.push(null);\n });\n weightSpecs.push(...weightsGroup.weights);\n });\n\n weightsManifest.forEach(weightsGroup => {\n weightsGroup.paths.forEach(path => {\n const weightFileReader = new FileReader();\n weightFileReader.onload = (event: Event) => {\n // tslint:disable-next-line:no-any\n const weightData = (event.target as any).result as ArrayBuffer;\n const index = paths.indexOf(path);\n perFileBuffers[index] = weightData;\n if (perFileBuffers.indexOf(null) === -1) {\n resolve({\n modelTopology,\n weightSpecs,\n weightData: concatenateArrayBuffers(perFileBuffers),\n format: modelJSON.format,\n generatedBy: modelJSON.generatedBy,\n convertedBy: modelJSON.convertedBy,\n userDefinedMetadata: modelJSON.userDefinedMetadata\n });\n }\n };\n weightFileReader.onerror = error =>\n reject(`Failed to weights data from file of path '${path}'.`);\n weightFileReader.readAsArrayBuffer(pathToFile[path]);\n });\n });\n };\n jsonReader.onerror = error => reject(\n `Failed to read model topology and weights manifest JSON ` +\n `from file '${jsonFile.name}'. BrowserFiles supports loading ` +\n `Keras-style tf.Model artifacts only.`);\n jsonReader.readAsText(jsonFile);\n });\n }\n\n /**\n * Check the compatibility between weights manifest and weight files.\n */\n private checkManifestAndWeightFiles(\n manifest: WeightsManifestConfig, files: File[]): {[path: string]: File} {\n const basenames: string[] = [];\n const fileNames = files.map(file => basename(file.name));\n const pathToFile: {[path: string]: File} = {};\n for (const group of manifest) {\n group.paths.forEach(path => {\n const pathBasename = basename(path);\n if (basenames.indexOf(pathBasename) !== -1) {\n throw new Error(\n `Duplicate file basename found in weights manifest: ` +\n `'${pathBasename}'`);\n }\n basenames.push(pathBasename);\n if (fileNames.indexOf(pathBasename) === -1) {\n throw new Error(\n `Weight file with basename '${pathBasename}' is not provided.`);\n } else {\n pathToFile[path] = files[fileNames.indexOf(pathBasename)];\n }\n });\n }\n\n if (basenames.length !== files.length) {\n throw new Error(\n `Mismatch in the number of files in weights manifest ` +\n `(${basenames.length}) and the number of weight files provided ` +\n `(${files.length}).`);\n }\n return pathToFile;\n }\n}\n\nexport const browserDownloadsRouter: IORouter = (url: string|string[]) => {\n if (!env().getBool('IS_BROWSER')) {\n return null;\n } else {\n if (!Array.isArray(url) && url.startsWith(BrowserDownloads.URL_SCHEME)) {\n return browserDownloads(url.slice(BrowserDownloads.URL_SCHEME.length));\n } else {\n return null;\n }\n }\n};\nIORouterRegistry.registerSaveRouter(browserDownloadsRouter);\n\n/**\n * Creates an IOHandler that triggers file downloads from the browser.\n *\n * The returned `IOHandler` instance can be used as model exporting methods such\n * as `tf.Model.save` and supports only saving.\n *\n * ```js\n * const model = tf.sequential();\n * model.add(tf.layers.dense(\n * {units: 1, inputShape: [10], activation: 'sigmoid'}));\n * const saveResult = await model.save('downloads://mymodel');\n * // This will trigger downloading of two files:\n * // 'mymodel.json' and 'mymodel.weights.bin'.\n * console.log(saveResult);\n * ```\n *\n * @param fileNamePrefix Prefix name of the files to be downloaded. For use with\n * `tf.Model`, `fileNamePrefix` should follow either of the following two\n * formats:\n * 1. `null` or `undefined`, in which case the default file\n * names will be used:\n * - 'model.json' for the JSON file containing the model topology and\n * weights manifest.\n * - 'model.weights.bin' for the binary file containing the binary weight\n * values.\n * 2. A single string or an Array of a single string, as the file name prefix.\n * For example, if `'foo'` is provided, the downloaded JSON\n * file and binary weights file will be named 'foo.json' and\n * 'foo.weights.bin', respectively.\n * @param config Additional configuration for triggering downloads.\n * @returns An instance of `BrowserDownloads` `IOHandler`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Loading',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nexport function browserDownloads(fileNamePrefix = 'model'): IOHandler {\n return new BrowserDownloads(fileNamePrefix);\n}\n\n/**\n * Creates an IOHandler that loads model artifacts from user-selected files.\n *\n * This method can be used for loading from files such as user-selected files\n * in the browser.\n * When used in conjunction with `tf.loadLayersModel`, an instance of\n * `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.\n *\n * ```js\n * // Note: This code snippet won't run properly without the actual file input\n * // elements in the HTML DOM.\n *\n * // Suppose there are two HTML file input (``)\n * // elements.\n * const uploadJSONInput = document.getElementById('upload-json');\n * const uploadWeightsInput = document.getElementById('upload-weights');\n * const model = await tf.loadLayersModel(tf.io.browserFiles(\n * [uploadJSONInput.files[0], uploadWeightsInput.files[0]]));\n * ```\n *\n * @param files `File`s to load from. Currently, this function supports only\n * loading from files that contain Keras-style models (i.e., `tf.Model`s), for\n * which an `Array` of `File`s is expected (in that order):\n * - A JSON file containing the model topology and weight manifest.\n * - Optionally, One or more binary files containing the binary weights.\n * These files must have names that match the paths in the `weightsManifest`\n * contained by the aforementioned JSON file, or errors will be thrown\n * during loading. These weights files have the same format as the ones\n * generated by `tensorflowjs_converter` that comes with the `tensorflowjs`\n * Python PIP package. If no weights files are provided, only the model\n * topology will be loaded from the JSON file above.\n * @returns An instance of `Files` `IOHandler`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Loading',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nexport function browserFiles(files: File[]): IOHandler {\n return new BrowserFiles(files);\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {assert} from '../util';\n\nimport {OnProgressCallback} from './types';\n\n/**\n * Monitor Promise.all progress, fire onProgress callback function.\n *\n * @param promises Promise list going to be monitored\n * @param onProgress Callback function. Fired when a promise resolved.\n * @param startFraction Optional fraction start. Default to 0.\n * @param endFraction Optional fraction end. Default to 1.\n */\nexport function monitorPromisesProgress(\n promises: Array>, onProgress: OnProgressCallback,\n startFraction?: number, endFraction?: number) {\n checkPromises(promises);\n startFraction = startFraction == null ? 0 : startFraction;\n endFraction = endFraction == null ? 1 : endFraction;\n checkFraction(startFraction, endFraction);\n let resolvedPromise = 0;\n\n const registerMonitor = (promise: Promise<{}>) => {\n promise.then(value => {\n const fraction = startFraction +\n ++resolvedPromise / promises.length * (endFraction - startFraction);\n // pass fraction as parameter to callback function.\n onProgress(fraction);\n return value;\n });\n return promise;\n };\n\n function checkPromises(promises: Array>): void {\n assert(\n promises != null && Array.isArray(promises) && promises.length > 0,\n () => 'promises must be a none empty array');\n }\n\n function checkFraction(startFraction: number, endFraction: number): void {\n assert(\n startFraction >= 0 && startFraction <= 1,\n () => `Progress fraction must be in range [0, 1], but ` +\n `got startFraction ${startFraction}`);\n assert(\n endFraction >= 0 && endFraction <= 1,\n () => `Progress fraction must be in range [0, 1], but ` +\n `got endFraction ${endFraction}`);\n assert(\n endFraction >= startFraction,\n () => `startFraction must be no more than endFraction, but ` +\n `got startFraction ${startFraction} and endFraction ` +\n `${endFraction}`);\n }\n\n return Promise.all(promises.map(registerMonitor));\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {env} from '../environment';\n\nimport {NamedTensorMap} from '../tensor_types';\nimport * as util from '../util';\nimport {decodeWeights} from './io_utils';\nimport {monitorPromisesProgress} from './progress';\nimport {DTYPE_VALUE_SIZE_MAP, LoadOptions, WeightsManifestConfig, WeightsManifestEntry} from './types';\n\n/**\n * Reads binary weights data from a number of URLs.\n *\n * @param fetchURLs URLs to send the HTTP requests at, using `fetch` calls.\n * @param requestOptions RequestInit (options) for the HTTP requests.\n * @param fetchFunc Optional overriding value for the `window.fetch` function.\n * @param onProgress Optional, progress callback function, fired periodically\n * before the load is completed.\n * @returns A `Promise` of an Array of `ArrayBuffer`. The Array has the same\n * length as `fetchURLs`.\n */\nexport async function loadWeightsAsArrayBuffer(\n fetchURLs: string[], loadOptions?: LoadOptions): Promise {\n if (loadOptions == null) {\n loadOptions = {};\n }\n\n const fetchFunc = loadOptions.fetchFunc == null ? env().platform.fetch :\n loadOptions.fetchFunc;\n\n // Create the requests for all of the weights in parallel.\n const requests = fetchURLs.map(\n fetchURL =>\n fetchFunc(fetchURL, loadOptions.requestInit, {isBinary: true}));\n\n const fetchStartFraction = 0;\n const fetchEndFraction = 0.5;\n\n const responses = loadOptions.onProgress == null ?\n await Promise.all(requests) :\n await monitorPromisesProgress(\n requests, loadOptions.onProgress, fetchStartFraction,\n fetchEndFraction);\n\n const bufferPromises = responses.map(response => response.arrayBuffer());\n\n const bufferStartFraction = 0.5;\n const bufferEndFraction = 1;\n\n const buffers = loadOptions.onProgress == null ?\n await Promise.all(bufferPromises) :\n await monitorPromisesProgress(\n bufferPromises, loadOptions.onProgress, bufferStartFraction,\n bufferEndFraction);\n return buffers;\n}\n\n/**\n * Reads a weights manifest JSON configuration, fetches the weights and\n * returns them as `Tensor`s.\n *\n * @param manifest The weights manifest JSON.\n * @param filePathPrefix The path prefix for filenames given in the manifest.\n * Defaults to the empty string.\n * @param weightNames The names of the weights to be fetched.\n */\nexport async function loadWeights(\n manifest: WeightsManifestConfig, filePathPrefix = '',\n weightNames?: string[],\n requestInit?: RequestInit): Promise {\n // TODO(nsthorat): Groups are currently fetched atomically. If you need a\n // single weight from a group, the whole group will be fetched. At a future\n // date, we should support fetching only the individual shards within a\n // group that are needed to reconstruct the requested weight.\n // TODO(cais): Use `decodeWeights` for implementation.\n\n const fetchWeights = (fetchUrls: string[]) =>\n loadWeightsAsArrayBuffer(fetchUrls, {requestInit});\n const loadWeights = weightsLoaderFactory(fetchWeights);\n\n return loadWeights(manifest, filePathPrefix, weightNames);\n}\n\n/**\n * Creates a function, which reads a weights manifest JSON configuration,\n * fetches the weight files using the specified function and returns them as\n * `Tensor`s.\n *\n * ```js\n * // example for creating a nodejs weight loader, which reads the weight files\n * // from disk using fs.readFileSync\n *\n * import * as fs from 'fs'\n *\n * const fetchWeightsFromDisk = (filePaths: string[]) =>\n * filePaths.map(filePath => fs.readFileSync(filePath).buffer)\n *\n * const loadWeights = tf.io.weightsLoaderFactory(fetchWeightsFromDisk)\n *\n * const manifest = JSON.parse(\n * fs.readFileSync('./my_model-weights_manifest').toString()\n * )\n * const weightMap = await loadWeights(manifest, './')\n * ```\n * @param fetchWeightsFunction The function used for fetching the weight files.\n * @returns Weight loading function.\n */\nexport function weightsLoaderFactory(\n fetchWeightsFunction: (fetchUrls: string[]) => Promise):\n (manifest: WeightsManifestConfig, filePathPrefix?: string,\n weightNames?: string[]) => Promise {\n return async(\n manifest: WeightsManifestConfig, filePathPrefix = '',\n weightNames?: string[]): Promise => {\n // Collect all the groups, weights, and their relative offsets to be\n // fetched.\n const groupIndicesToFetchMap = manifest.map(() => false);\n const groupWeightsToFetch: {\n [group: number]: Array<{\n manifestEntry: WeightsManifestEntry; groupOffset: number;\n sizeBytes: number;\n }>\n } = {};\n const weightsFound =\n weightNames != null ? weightNames.map(() => false) : [];\n const allManifestWeightNames: string[] = [];\n manifest.forEach((manifestGroupConfig, groupIndex) => {\n let groupOffset = 0;\n manifestGroupConfig.weights.forEach(weightsEntry => {\n const rawDtype = ('quantization' in weightsEntry) ?\n weightsEntry.quantization.dtype :\n weightsEntry.dtype;\n\n const weightsBytes = DTYPE_VALUE_SIZE_MAP[rawDtype] *\n util.sizeFromShape(weightsEntry.shape);\n\n const enqueueWeightsForFetchingFn = () => {\n groupIndicesToFetchMap[groupIndex] = true;\n if (groupWeightsToFetch[groupIndex] == null) {\n groupWeightsToFetch[groupIndex] = [];\n }\n\n groupWeightsToFetch[groupIndex].push({\n manifestEntry: weightsEntry,\n groupOffset,\n sizeBytes: weightsBytes\n });\n };\n\n if (weightNames != null) {\n weightNames.forEach((weightName, weightIndex) => {\n if (weightName === weightsEntry.name) {\n enqueueWeightsForFetchingFn();\n weightsFound[weightIndex] = true;\n }\n });\n } else {\n enqueueWeightsForFetchingFn();\n }\n\n allManifestWeightNames.push(weightsEntry.name);\n groupOffset += weightsBytes;\n });\n });\n\n if (!weightsFound.every(found => found)) {\n const weightsNotFound = weightNames.filter((_, i) => !weightsFound[i]);\n throw new Error(\n `Could not find weights in manifest with names: ` +\n `${weightsNotFound.join(', ')}. \\n` +\n `Manifest JSON has weights with names: ` +\n `${allManifestWeightNames.join(', ')}.`);\n }\n\n // Convert the one-hot boolean groupId => shouldFetch map to a list of group\n // IDs.\n const groupIndicesToFetch =\n groupIndicesToFetchMap.reduce((accumulator, shouldFetch, i) => {\n if (shouldFetch) {\n accumulator.push(i);\n }\n return accumulator;\n }, []);\n\n const fetchUrls: string[] = [];\n groupIndicesToFetch.forEach(i => {\n manifest[i].paths.forEach(filepath => {\n const fetchUrl = filePathPrefix +\n (!filePathPrefix.endsWith('/') ? '/' : '') + filepath;\n fetchUrls.push(fetchUrl);\n });\n });\n const buffers = await fetchWeightsFunction(fetchUrls);\n\n const weightsTensorMap: NamedTensorMap = {};\n let bufferIndexOffset = 0;\n groupIndicesToFetch.forEach(i => {\n const numBuffers = manifest[i].paths.length;\n\n let groupBytes = 0;\n for (let i = 0; i < numBuffers; i++) {\n groupBytes += buffers[bufferIndexOffset + i].byteLength;\n }\n\n // Create a buffer for the whole group.\n const groupBuffer = new ArrayBuffer(groupBytes);\n const groupByteBuffer = new Uint8Array(groupBuffer);\n let groupBufferOffset = 0;\n for (let i = 0; i < numBuffers; i++) {\n const buffer = new Uint8Array(buffers[bufferIndexOffset + i]);\n groupByteBuffer.set(buffer, groupBufferOffset);\n groupBufferOffset += buffer.byteLength;\n }\n\n const weightsEntries = groupWeightsToFetch[i];\n weightsEntries.forEach(weightsEntry => {\n const byteBuffer = groupBuffer.slice(\n weightsEntry.groupOffset,\n weightsEntry.groupOffset + weightsEntry.sizeBytes);\n const nameToTensorMap =\n decodeWeights(byteBuffer, [weightsEntry.manifestEntry]);\n for (const name in nameToTensorMap) {\n weightsTensorMap[name] = nameToTensorMap[name];\n }\n });\n\n bufferIndexOffset += numBuffers;\n });\n\n return weightsTensorMap;\n };\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * IOHandler implementations based on HTTP requests in the web browser.\n *\n * Uses [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).\n */\n\nimport {env} from '../environment';\n\nimport {assert} from '../util';\nimport {concatenateArrayBuffers, getModelArtifactsInfoForJSON} from './io_utils';\nimport {IORouter, IORouterRegistry} from './router_registry';\nimport {IOHandler, LoadOptions, ModelArtifacts, ModelJSON, OnProgressCallback, SaveResult, WeightsManifestConfig, WeightsManifestEntry} from './types';\nimport {loadWeightsAsArrayBuffer} from './weights_loader';\n\nconst OCTET_STREAM_MIME_TYPE = 'application/octet-stream';\nconst JSON_TYPE = 'application/json';\nexport class HTTPRequest implements IOHandler {\n protected readonly path: string;\n protected readonly requestInit: RequestInit;\n\n private readonly fetch: Function;\n private readonly weightUrlConverter: (weightName: string) => Promise;\n\n readonly DEFAULT_METHOD = 'POST';\n\n static readonly URL_SCHEME_REGEX = /^https?:\\/\\//;\n\n private readonly weightPathPrefix: string;\n private readonly onProgress: OnProgressCallback;\n\n constructor(path: string, loadOptions?: LoadOptions) {\n if (loadOptions == null) {\n loadOptions = {};\n }\n this.weightPathPrefix = loadOptions.weightPathPrefix;\n this.onProgress = loadOptions.onProgress;\n this.weightUrlConverter = loadOptions.weightUrlConverter;\n\n if (loadOptions.fetchFunc != null) {\n assert(\n typeof loadOptions.fetchFunc === 'function',\n () => 'Must pass a function that matches the signature of ' +\n '`fetch` (see ' +\n 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)');\n this.fetch = loadOptions.fetchFunc;\n } else {\n this.fetch = env().platform.fetch;\n }\n\n assert(\n path != null && path.length > 0,\n () => 'URL path for http must not be null, undefined or ' +\n 'empty.');\n\n if (Array.isArray(path)) {\n assert(\n path.length === 2,\n () => 'URL paths for http must have a length of 2, ' +\n `(actual length is ${path.length}).`);\n }\n this.path = path;\n\n if (loadOptions.requestInit != null &&\n loadOptions.requestInit.body != null) {\n throw new Error(\n 'requestInit is expected to have no pre-existing body, but has one.');\n }\n this.requestInit = loadOptions.requestInit || {};\n }\n\n async save(modelArtifacts: ModelArtifacts): Promise {\n if (modelArtifacts.modelTopology instanceof ArrayBuffer) {\n throw new Error(\n 'BrowserHTTPRequest.save() does not support saving model topology ' +\n 'in binary formats yet.');\n }\n\n const init = Object.assign({method: this.DEFAULT_METHOD}, this.requestInit);\n init.body = new FormData();\n\n const weightsManifest: WeightsManifestConfig = [{\n paths: ['./model.weights.bin'],\n weights: modelArtifacts.weightSpecs,\n }];\n const modelTopologyAndWeightManifest: ModelJSON = {\n modelTopology: modelArtifacts.modelTopology,\n format: modelArtifacts.format,\n generatedBy: modelArtifacts.generatedBy,\n convertedBy: modelArtifacts.convertedBy,\n userDefinedMetadata: modelArtifacts.userDefinedMetadata,\n weightsManifest\n };\n\n init.body.append(\n 'model.json',\n new Blob(\n [JSON.stringify(modelTopologyAndWeightManifest)],\n {type: JSON_TYPE}),\n 'model.json');\n\n if (modelArtifacts.weightData != null) {\n init.body.append(\n 'model.weights.bin',\n new Blob([modelArtifacts.weightData], {type: OCTET_STREAM_MIME_TYPE}),\n 'model.weights.bin');\n }\n\n const response = await this.fetch(this.path, init);\n\n if (response.ok) {\n return {\n modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts),\n responses: [response],\n };\n } else {\n throw new Error(\n `BrowserHTTPRequest.save() failed due to HTTP response status ` +\n `${response.status}.`);\n }\n }\n\n /**\n * Load model artifacts via HTTP request(s).\n *\n * See the documentation to `tf.io.http` for details on the saved\n * artifacts.\n *\n * @returns The loaded model artifacts (if loading succeeds).\n */\n async load(): Promise {\n const modelConfigRequest = await this.fetch(this.path, this.requestInit);\n\n if (!modelConfigRequest.ok) {\n throw new Error(\n `Request to ${this.path} failed with status code ` +\n `${modelConfigRequest.status}. Please verify this URL points to ` +\n `the model JSON of the model to load.`);\n }\n let modelConfig: ModelJSON;\n try {\n modelConfig = await modelConfigRequest.json();\n } catch (e) {\n let message = `Failed to parse model JSON of response from ${this.path}.`;\n // TODO(nsthorat): Remove this after some time when we're comfortable that\n // .pb files are mostly gone.\n if (this.path.endsWith('.pb')) {\n message += ' Your path contains a .pb file extension. ' +\n 'Support for .pb models have been removed in TensorFlow.js 1.0 ' +\n 'in favor of .json models. You can re-convert your Python ' +\n 'TensorFlow model using the TensorFlow.js 1.0 conversion scripts ' +\n 'or you can convert your.pb models with the \\'pb2json\\'' +\n 'NPM script in the tensorflow/tfjs-converter repository.';\n } else {\n message += ' Please make sure the server is serving valid ' +\n 'JSON for this request.';\n }\n throw new Error(message);\n }\n const modelTopology = modelConfig.modelTopology;\n const weightsManifest = modelConfig.weightsManifest;\n const generatedBy = modelConfig.generatedBy;\n const convertedBy = modelConfig.convertedBy;\n const format = modelConfig.format;\n const userDefinedMetadata = modelConfig.userDefinedMetadata;\n\n // We do not allow both modelTopology and weightsManifest to be missing.\n if (modelTopology == null && weightsManifest == null) {\n throw new Error(\n `The JSON from HTTP path ${this.path} contains neither model ` +\n `topology or manifest for weights.`);\n }\n\n let weightSpecs: WeightsManifestEntry[];\n let weightData: ArrayBuffer;\n if (weightsManifest != null) {\n const results = await this.loadWeights(weightsManifest);\n [weightSpecs, weightData] = results;\n }\n\n const artifacts: ModelArtifacts = {\n modelTopology,\n weightSpecs,\n weightData,\n userDefinedMetadata,\n generatedBy,\n convertedBy,\n format\n };\n\n const initializer = modelConfig.modelInitializer;\n if (initializer) {\n artifacts.modelInitializer = initializer;\n }\n\n return artifacts;\n }\n\n private async loadWeights(weightsManifest: WeightsManifestConfig):\n Promise<[WeightsManifestEntry[], ArrayBuffer]> {\n const weightPath = Array.isArray(this.path) ? this.path[1] : this.path;\n const [prefix, suffix] = parseUrl(weightPath);\n const pathPrefix = this.weightPathPrefix || prefix;\n\n const weightSpecs = [];\n for (const entry of weightsManifest) {\n weightSpecs.push(...entry.weights);\n }\n\n const fetchURLs: string[] = [];\n const urlPromises: Array> = [];\n for (const weightsGroup of weightsManifest) {\n for (const path of weightsGroup.paths) {\n if (this.weightUrlConverter != null) {\n urlPromises.push(this.weightUrlConverter(path));\n } else {\n fetchURLs.push(pathPrefix + path + suffix);\n }\n }\n }\n\n if (this.weightUrlConverter) {\n fetchURLs.push(...await Promise.all(urlPromises));\n }\n\n const buffers = await loadWeightsAsArrayBuffer(fetchURLs, {\n requestInit: this.requestInit,\n fetchFunc: this.fetch,\n onProgress: this.onProgress\n });\n return [weightSpecs, concatenateArrayBuffers(buffers)];\n }\n}\n\n/**\n * Extract the prefix and suffix of the url, where the prefix is the path before\n * the last file, and suffix is the search params after the last file.\n * ```\n * const url = 'http://tfhub.dev/model/1/tensorflowjs_model.pb?tfjs-format=file'\n * [prefix, suffix] = parseUrl(url)\n * // prefix = 'http://tfhub.dev/model/1/'\n * // suffix = '?tfjs-format=file'\n * ```\n * @param url the model url to be parsed.\n */\nexport function parseUrl(url: string): [string, string] {\n const lastSlash = url.lastIndexOf('/');\n const lastSearchParam = url.lastIndexOf('?');\n const prefix = url.substring(0, lastSlash);\n const suffix =\n lastSearchParam > lastSlash ? url.substring(lastSearchParam) : '';\n return [prefix + '/', suffix];\n}\n\nexport function isHTTPScheme(url: string): boolean {\n return url.match(HTTPRequest.URL_SCHEME_REGEX) != null;\n}\n\nexport const httpRouter: IORouter =\n (url: string, loadOptions?: LoadOptions) => {\n if (typeof fetch === 'undefined' &&\n (loadOptions == null || loadOptions.fetchFunc == null)) {\n // `http` uses `fetch` or `node-fetch`, if one wants to use it in\n // an environment that is not the browser or node they have to setup a\n // global fetch polyfill.\n return null;\n } else {\n let isHTTP = true;\n if (Array.isArray(url)) {\n isHTTP = url.every(urlItem => isHTTPScheme(urlItem));\n } else {\n isHTTP = isHTTPScheme(url);\n }\n if (isHTTP) {\n return http(url, loadOptions);\n }\n }\n return null;\n };\nIORouterRegistry.registerSaveRouter(httpRouter);\nIORouterRegistry.registerLoadRouter(httpRouter);\n\n/**\n * Creates an IOHandler subtype that sends model artifacts to HTTP server.\n *\n * An HTTP request of the `multipart/form-data` mime type will be sent to the\n * `path` URL. The form data includes artifacts that represent the topology\n * and/or weights of the model. In the case of Keras-style `tf.Model`, two\n * blobs (files) exist in form-data:\n * - A JSON file consisting of `modelTopology` and `weightsManifest`.\n * - A binary weights file consisting of the concatenated weight values.\n * These files are in the same format as the one generated by\n * [tfjs_converter](https://js.tensorflow.org/tutorials/import-keras.html).\n *\n * The following code snippet exemplifies the client-side code that uses this\n * function:\n *\n * ```js\n * const model = tf.sequential();\n * model.add(\n * tf.layers.dense({units: 1, inputShape: [100], activation: 'sigmoid'}));\n *\n * const saveResult = await model.save(tf.io.http(\n * 'http://model-server:5000/upload', {requestInit: {method: 'PUT'}}));\n * console.log(saveResult);\n * ```\n *\n * If the default `POST` method is to be used, without any custom parameters\n * such as headers, you can simply pass an HTTP or HTTPS URL to `model.save`:\n *\n * ```js\n * const saveResult = await model.save('http://model-server:5000/upload');\n * ```\n *\n * The following GitHub Gist\n * https://gist.github.com/dsmilkov/1b6046fd6132d7408d5257b0976f7864\n * implements a server based on [flask](https://github.com/pallets/flask) that\n * can receive the request. Upon receiving the model artifacts via the requst,\n * this particular server reconsistutes instances of [Keras\n * Models](https://keras.io/models/model/) in memory.\n *\n *\n * @param path A URL path to the model.\n * Can be an absolute HTTP path (e.g.,\n * 'http://localhost:8000/model-upload)') or a relative path (e.g.,\n * './model-upload').\n * @param requestInit Request configurations to be used when sending\n * HTTP request to server using `fetch`. It can contain fields such as\n * `method`, `credentials`, `headers`, `mode`, etc. See\n * https://developer.mozilla.org/en-US/docs/Web/API/Request/Request\n * for more information. `requestInit` must not have a body, because the\n * body will be set by TensorFlow.js. File blobs representing the model\n * topology (filename: 'model.json') and the weights of the model (filename:\n * 'model.weights.bin') will be appended to the body. If `requestInit` has a\n * `body`, an Error will be thrown.\n * @param loadOptions Optional configuration for the loading. It includes the\n * following fields:\n * - weightPathPrefix Optional, this specifies the path prefix for weight\n * files, by default this is calculated from the path param.\n * - fetchFunc Optional, custom `fetch` function. E.g., in Node.js,\n * the `fetch` from node-fetch can be used here.\n * - onProgress Optional, progress callback function, fired periodically\n * before the load is completed.\n * @returns An instance of `IOHandler`.\n *\n * @doc {\n * heading: 'Models',\n * subheading: 'Loading',\n * namespace: 'io',\n * ignoreCI: true\n * }\n */\nexport function http(path: string, loadOptions?: LoadOptions): IOHandler {\n return new HTTPRequest(path, loadOptions);\n}\n\n/**\n * Deprecated. Use `tf.io.http`.\n * @param path\n * @param loadOptions\n */\nexport function browserHTTPRequest(\n path: string, loadOptions?: LoadOptions): IOHandler {\n return http(path, loadOptions);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * IOHandlers that pass through the in-memory ModelArtifacts format.\n */\n\nimport {IOHandler, ModelArtifacts, SaveResult, TrainingConfig, WeightsManifestEntry} from './types';\n\nclass PassthroughLoader implements IOHandler {\n constructor(private readonly modelArtifacts?: ModelArtifacts) {}\n\n async load(): Promise {\n return this.modelArtifacts;\n }\n}\n\nclass PassthroughSaver implements IOHandler {\n constructor(\n private readonly saveHandler:\n (artifacts: ModelArtifacts) => Promise) {}\n\n async save(modelArtifacts: ModelArtifacts) {\n return this.saveHandler(modelArtifacts);\n }\n}\n\n/**\n * Creates an IOHandler that loads model artifacts from memory.\n *\n * When used in conjunction with `tf.loadLayersModel`, an instance of\n * `tf.LayersModel` (Keras-style) can be constructed from the loaded artifacts.\n *\n * ```js\n * const model = await tf.loadLayersModel(tf.io.fromMemory(\n * modelTopology, weightSpecs, weightData));\n * ```\n *\n * @param modelArtifacts a object containing model topology (i.e., parsed from\n * the JSON format).\n * @param weightSpecs An array of `WeightsManifestEntry` objects describing the\n * names, shapes, types, and quantization of the weight data.\n * @param weightData A single `ArrayBuffer` containing the weight data,\n * concatenated in the order described by the weightSpecs.\n * @param trainingConfig Model training configuration. Optional.\n *\n * @returns A passthrough `IOHandler` that simply loads the provided data.\n */\nexport function fromMemory(\n modelArtifacts: {}|ModelArtifacts, weightSpecs?: WeightsManifestEntry[],\n weightData?: ArrayBuffer, trainingConfig?: TrainingConfig): IOHandler {\n if (arguments.length === 1) {\n const isModelArtifacts =\n (modelArtifacts as ModelArtifacts).modelTopology != null ||\n (modelArtifacts as ModelArtifacts).weightSpecs != null;\n if (isModelArtifacts) {\n return new PassthroughLoader(modelArtifacts as ModelArtifacts);\n } else {\n // Legacy support: with only modelTopology.\n // TODO(cais): Remove this deprecated API.\n console.warn(\n 'Please call tf.io.fromMemory() with only one argument. ' +\n 'The argument should be of type ModelArtifacts. ' +\n 'The multi-argument signature of tf.io.fromMemory() has been ' +\n 'deprecated and will be removed in a future release.');\n return new PassthroughLoader({modelTopology: modelArtifacts as {}});\n }\n } else {\n // Legacy support.\n // TODO(cais): Remove this deprecated API.\n console.warn(\n 'Please call tf.io.fromMemory() with only one argument. ' +\n 'The argument should be of type ModelArtifacts. ' +\n 'The multi-argument signature of tf.io.fromMemory() has been ' +\n 'deprecated and will be removed in a future release.');\n return new PassthroughLoader({\n modelTopology: modelArtifacts as {},\n weightSpecs,\n weightData,\n trainingConfig\n });\n }\n}\n\n/**\n * Creates an IOHandler that passes saved model artifacts to a callback.\n *\n * ```js\n * function handleSave(artifacts) {\n * // ... do something with the artifacts ...\n * return {modelArtifactsInfo: {...}, ...};\n * }\n *\n * const saveResult = model.save(tf.io.withSaveHandler(handleSave));\n * ```\n *\n * @param saveHandler A function that accepts a `ModelArtifacts` and returns a\n * `SaveResult`.\n */\nexport function withSaveHandler(\n saveHandler: (artifacts: ModelArtifacts) =>\n Promise): IOHandler {\n return new PassthroughSaver(saveHandler);\n}\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n// Importing local_storage and indexed_db is necessary for the routers to be\n// registered.\nimport './indexed_db';\nimport './local_storage';\n\nimport {browserFiles} from './browser_files';\nimport {browserHTTPRequest, http, isHTTPScheme} from './http';\nimport {concatenateArrayBuffers, decodeWeights, encodeWeights, getModelArtifactsInfoForJSON} from './io_utils';\nimport {fromMemory, withSaveHandler} from './passthrough';\nimport {getLoadHandlers, getSaveHandlers, registerLoadRouter, registerSaveRouter} from './router_registry';\nimport {IOHandler, LoadHandler, LoadOptions, ModelArtifacts, ModelArtifactsInfo, ModelJSON, ModelStoreManager, OnProgressCallback, RequestDetails, SaveConfig, SaveHandler, SaveResult, WeightGroup, WeightsManifestConfig, WeightsManifestEntry} from './types';\nimport {loadWeights, weightsLoaderFactory} from './weights_loader';\n\nexport {copyModel, listModels, moveModel, removeModel} from './model_management';\nexport {\n browserFiles,\n browserHTTPRequest,\n concatenateArrayBuffers,\n decodeWeights,\n encodeWeights,\n fromMemory,\n getLoadHandlers,\n getModelArtifactsInfoForJSON,\n getSaveHandlers,\n http,\n IOHandler,\n isHTTPScheme,\n LoadHandler,\n LoadOptions,\n loadWeights,\n ModelArtifacts,\n ModelArtifactsInfo,\n ModelJSON,\n ModelStoreManager,\n OnProgressCallback,\n registerLoadRouter,\n registerSaveRouter,\n RequestDetails,\n SaveConfig,\n SaveHandler,\n SaveResult,\n WeightGroup,\n weightsLoaderFactory,\n WeightsManifestConfig,\n WeightsManifestEntry,\n withSaveHandler\n};\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {KernelBackend} from '../backends/backend';\nimport {ENGINE, ForwardFunc} from '../engine';\nimport {Reshape, ReshapeAttrs, ReshapeInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {GradSaveFunc, NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {Rank, ShapeMap, TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Reshapes a `tf.Tensor` to a given shape.\n *\n * Given an input tensor, returns a new tensor with the same values as the\n * input tensor with shape `shape`.\n *\n * If one component of shape is the special value -1, the size of that\n * dimension is computed so that the total size remains constant. In\n * particular, a shape of [-1] flattens into 1-D. At most one component of\n * shape can be -1.\n *\n * If shape is 1-D or higher, then the operation returns a tensor with shape\n * shape filled with the values of tensor. In this case, the number of\n * elements implied by shape must be the same as the number of elements in\n * tensor.\n *\n * ```js\n * const x = tf.tensor1d([1, 2, 3, 4]);\n * x.reshape([2, 2]).print();\n * ```\n *\n * @param x The input tensor to be reshaped.\n * @param shape An array of integers defining the output tensor shape.\n *\n * @doc {heading: 'Tensors', subheading: 'Transformations'}\n */\nfunction reshape_(\n x: Tensor|TensorLike, shape: ShapeMap[R]): Tensor {\n const $x = convertToTensor(x, 'x', 'reshape', null);\n\n const inputs: ReshapeInputs = {x: $x};\n const attrs: ReshapeAttrs = {shape};\n const forward: ForwardFunc<\n Tensor> = (backend: KernelBackend, save: GradSaveFunc) => {\n shape = util.inferFromImplicitShape(shape, $x.size) as ShapeMap[R];\n util.assert(\n $x.size === util.sizeFromShape(shape),\n () => 'new shape and old shape must have the same number of elements.');\n save([$x]);\n return backend.reshape($x, shape);\n };\n return ENGINE.runKernelFunc(\n forward, inputs as {} as NamedTensorMap, null /* grad */, Reshape,\n attrs as {} as NamedAttrMap);\n}\nexport const reshape = op({reshape_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\nimport {ENGINE, ForwardFunc} from '../engine';\nimport {BatchMatMul, BatchMatMulAttrs, BatchMatMulInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor3D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {makeTypesMatch} from '../tensor_util';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Computes the dot product of two matrices, A * B. These must be matrices.\n *\n * ```js\n * const a = tf.tensor2d([1, 2], [1, 2]);\n * const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);\n *\n * a.matMul(b).print(); // or tf.matMul(a, b)\n * ```\n * @param a First matrix in dot product operation.\n * @param b Second matrix in dot product operation.\n * @param transposeA If true, `a` is transposed before multiplication.\n * @param transposeB If true, `b` is transposed before multiplication.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction matMul_(\n a: T|TensorLike, b: T|TensorLike, transposeA = false,\n transposeB = false): T {\n let $a = convertToTensor(a, 'a', 'matMul');\n let $b = convertToTensor(b, 'b', 'matMul');\n [$a, $b] = makeTypesMatch($a, $b);\n\n util.assert(\n $a.rank >= 2 && $b.rank >= 2 && $a.rank === $b.rank,\n () => `Error in matMul: inputs must have the same rank of at least 2, ` +\n `got ranks ${$a.rank} and ${$b.rank}.`);\n\n const innerShapeA =\n transposeA ? $a.shape[$a.rank - 2] : $a.shape[$a.rank - 1];\n const innerShapeB =\n transposeB ? $b.shape[$b.rank - 1] : $b.shape[$b.rank - 2];\n\n const outerShapeA =\n transposeA ? $a.shape[$a.rank - 1] : $a.shape[$a.rank - 2];\n const outerShapeB =\n transposeB ? $b.shape[$b.rank - 2] : $b.shape[$b.rank - 1];\n\n const outerDimsA = $a.shape.slice(0, -2);\n const outerDimsB = $b.shape.slice(0, -2);\n const batchDimA = util.sizeFromShape(outerDimsA);\n const batchDimB = util.sizeFromShape(outerDimsB);\n\n util.assert(\n util.arraysEqual(outerDimsA, outerDimsB),\n () => `Error in matMul: outer dimensions (${outerDimsA}) and (` +\n `${outerDimsB}) of Tensors with shapes ${$a.shape} and ` +\n `${$b.shape} must match.`);\n\n util.assert(\n innerShapeA === innerShapeB,\n () => `Error in matMul: inner shapes (${innerShapeA}) and (` +\n `${innerShapeB}) of Tensors with shapes ${$a.shape} and ` +\n `${$b.shape} and transposeA=${transposeA}` +\n ` and transposeB=${transposeB} must match.`);\n\n const outShape = $a.shape.slice(0, -2).concat([outerShapeA, outerShapeB]);\n\n const a3D = transposeA ? reshape($a, [batchDimA, innerShapeA, outerShapeA]) :\n reshape($a, [batchDimA, outerShapeA, innerShapeA]);\n const b3D = transposeB ? reshape($b, [batchDimB, outerShapeB, innerShapeB]) :\n reshape($b, [batchDimB, innerShapeB, outerShapeB]);\n\n const forward: ForwardFunc = (backend, save) => {\n save([a3D, b3D]);\n\n return backend.batchMatMul(\n a3D as Tensor3D, b3D as Tensor3D, transposeA, transposeB);\n };\n\n const inputs: BatchMatMulInputs = {a: a3D, b: b3D};\n\n const attrs: BatchMatMulAttrs = {transposeA, transposeB};\n\n const res = ENGINE.runKernelFunc(\n forward, inputs as {} as NamedTensorMap, null /* grad */, BatchMatMul,\n attrs as {} as NamedAttrMap);\n\n return reshape(res, outShape) as T;\n}\n\nexport const matMul = op({matMul_});\n", "/**\n * @license\n * Copyright 2020 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE, ForwardFunc} from '../engine';\nimport {OneHot, OneHotAttrs, OneHotInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\n\nimport {op} from './operation';\nimport {reshape} from './reshape';\n\n/**\n * Creates a one-hot `tf.Tensor`. The locations represented by `indices` take\n * value `onValue` (defaults to 1), while all other locations take value\n * `offValue` (defaults to 0). If `indices` is rank `R`, the output has rank\n * `R+1` with the last axis of size `depth`.\n *\n * ```js\n * tf.oneHot(tf.tensor1d([0, 1], 'int32'), 3).print();\n * ```\n *\n * @param indices `tf.Tensor` of indices with dtype `int32`.\n * @param depth The depth of the one hot dimension.\n * @param onValue A number used to fill in the output when the index matches\n * the location.\n * @param offValue A number used to fill in the output when the index does\n * not match the location.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nfunction oneHot_(\n indices: Tensor|TensorLike, depth: number, onValue = 1,\n offValue = 0): Tensor {\n if (depth < 2) {\n throw new Error(`Error in oneHot: depth must be >=2, but it is ${depth}`);\n }\n const $indices = convertToTensor(indices, 'indices', 'oneHot', 'int32');\n const outShape = [...$indices.shape, depth];\n\n const forward: ForwardFunc = (backend, save) => {\n save([$indices]);\n return reshape(\n backend.oneHot(\n reshape($indices, [$indices.size]), depth, onValue, offValue),\n outShape);\n };\n\n const inputs: OneHotInputs = {indices: $indices};\n const attrs: OneHotAttrs = {depth, onValue, offValue};\n\n return ENGINE.runKernelFunc(\n forward, inputs as unknown as NamedTensorMap, null /* grad */, OneHot,\n attrs as unknown as NamedAttrMap);\n}\n\nexport const oneHot = op({oneHot_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {Transpose, TransposeAttrs, TransposeInputs} from '../kernel_names';\nimport {NamedAttrMap} from '../kernel_registry';\nimport {Tensor} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {op} from './operation';\n\n/**\n * Transposes the `tf.Tensor`. Permutes the dimensions according to `perm`.\n *\n * The returned `tf.Tensor`'s dimension `i` will correspond to the input\n * dimension `perm[i]`. If `perm` is not given, it is set to `[n-1...0]`,\n * where `n` is the rank of the input `tf.Tensor`. Hence by default, this\n * operation performs a regular matrix transpose on 2-D input `tf.Tensor`s.\n *\n * ```js\n * const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]);\n *\n * a.transpose().print(); // or tf.transpose(a)\n * ```\n *\n * @param x The tensor to transpose.\n * @param perm The permutation of the dimensions of a.\n *\n * @doc {heading: 'Operations', subheading: 'Matrices'}\n */\nfunction transpose_(x: T|TensorLike, perm?: number[]): T {\n const $x = convertToTensor(x, 'x', 'transpose');\n\n if (perm == null) {\n perm = $x.shape.map((s, i) => i).reverse();\n }\n util.assert(\n $x.rank === perm.length,\n () => `Error in transpose: rank of input ${$x.rank} ` +\n `must match length of perm ${perm}.`);\n perm.forEach(axis => {\n util.assert(\n axis >= 0 && axis < $x.rank,\n () => `All entries in 'perm' must be between 0 and ${$x.rank - 1}` +\n ` but got ${perm}`);\n });\n\n if ($x.rank <= 1) {\n return $x.clone();\n }\n\n const inputs: TransposeInputs = {x: $x};\n const attrs: TransposeAttrs = {perm};\n\n return ENGINE.runKernelFunc(\n backend => backend.transpose($x, perm), inputs as {} as NamedTensorMap,\n null /* gradient */, Transpose, attrs as {} as NamedAttrMap);\n}\n\nexport const transpose = op({transpose_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor1D, Tensor2D} from '../tensor';\nimport {convertToTensor} from '../tensor_util_env';\nimport {TensorLike} from '../types';\nimport * as util from '../util';\n\nimport {cast} from './cast';\nimport {matMul} from './mat_mul';\nimport {oneHot} from './one_hot';\nimport {op} from './operation';\nimport {transpose} from './transpose';\n\n/**\n * Computes the confusion matrix from true labels and predicted labels.\n *\n * ```js\n * const labels = tf.tensor1d([0, 1, 2, 1, 0], 'int32');\n * const predictions = tf.tensor1d([0, 2, 2, 1, 0], 'int32');\n * const numClasses = 3;\n * const out = tf.math.confusionMatrix(labels, predictions, numClasses);\n * out.print();\n * // Expected output matrix:\n * // [[2, 0, 0],\n * // [0, 1, 1],\n * // [0, 0, 1]]\n * ```\n *\n * @param labels The target labels, assumed to be 0-based integers\n * for the classes. The shape is `[numExamples]`, where\n * `numExamples` is the number of examples included.\n * @param predictions The predicted classes, assumed to be\n * 0-based integers for the classes. Must have the same shape as `labels`.\n * @param numClasses Number of all classes, as an integer.\n * Its value must be larger than the largest element in `labels` and\n * `predictions`.\n * @returns The confusion matrix as a int32-type 2D tensor. The value at\n * row `r` and column `c` is the number of times examples of actual class\n * `r` were predicted as class `c`.\n *\n * @doc {heading: 'Operations', subheading: 'Evaluation'}\n */\nexport function confusionMatrix_(\n labels: Tensor1D|TensorLike, predictions: Tensor1D|TensorLike,\n numClasses: number): Tensor2D {\n const $labels = convertToTensor(labels, 'labels', 'confusionMatrix');\n const $predictions =\n convertToTensor(predictions, 'predictions', 'confusionMatrix');\n\n util.assert(\n numClasses == null || numClasses > 0 && Number.isInteger(numClasses),\n () => `If provided, numClasses must be a positive integer, ` +\n `but got ${numClasses}`);\n util.assert(\n $labels.rank === 1,\n () => `Expected the rank of labels to be 1, but got ${$labels.rank}`);\n util.assert(\n $predictions.rank === 1,\n () => `Expected the rank of predictions to be 1, ` +\n `but got ${$predictions.rank}`);\n util.assert(\n $labels.shape[0] === $predictions.shape[0],\n () => `Mismatch in the number of examples: ` +\n `${$labels.shape[0]} vs. ${$predictions.shape[0]}. ` +\n `Labels and predictions should have the same number of elements.`);\n util.assert(\n numClasses > 0 && Number.isInteger(numClasses),\n () => `numClasses is required to be a positive integer, but got ` +\n `${numClasses}`);\n // TODO(cais): In the future, if oneHot supports tensors inputs for\n // `numClasses`, `confusionMatrix` can make `numClasses` optional.\n\n const oneHotLabels = oneHot(cast($labels, 'int32'), numClasses) as Tensor2D;\n const oneHotPredictions =\n oneHot(cast($predictions, 'int32'), numClasses) as Tensor2D;\n const oneHotLabelsT: Tensor2D = transpose(oneHotLabels);\n return cast(matMul(oneHotLabelsT, oneHotPredictions), 'int32');\n}\n\nexport const confusionMatrix = op({confusionMatrix_});\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\n/**\n * Exports under the tf.math.* namespace.\n */\n\nimport {confusionMatrix} from './ops/confusion_matrix';\n\nexport {confusionMatrix};\n", "/**\n * @license\n * Copyright 2018 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {Tensor3D} from '../tensor';\nimport {inferShape} from '../tensor_util_env';\nimport {TensorLike3D} from '../types';\nimport {DataType} from '../types';\nimport {assertNonNull} from '../util';\nimport {makeTensor} from './tensor_ops_util';\n\n/**\n * Creates rank-3 `tf.Tensor` with the provided values, shape and dtype.\n *\n * The same functionality can be achieved with `tf.tensor`, but in general\n * we recommend using `tf.tensor3d` as it makes the code more readable.\n *\n * ```js\n * // Pass a nested array.\n * tf.tensor3d([[[1], [2]], [[3], [4]]]).print();\n * ```\n * ```js\n * // Pass a flat array and specify a shape.\n * tf.tensor3d([1, 2, 3, 4], [2, 2, 1]).print();\n * ```\n *\n * @param values The values of the tensor. Can be nested array of numbers,\n * or a flat array, or a `TypedArray`.\n * @param shape The shape of the tensor. If not provided, it is inferred from\n * `values`.\n * @param dtype The data type.\n *\n * @doc {heading: 'Tensors', subheading: 'Creation'}\n */\nexport function tensor3d(\n values: TensorLike3D, shape?: [number, number, number],\n dtype?: DataType): Tensor3D {\n assertNonNull(values);\n if (shape != null && shape.length !== 3) {\n throw new Error('tensor3d() requires shape to have three numbers');\n }\n const inferredShape = inferShape(values, dtype);\n if (inferredShape.length !== 3 && inferredShape.length !== 1) {\n throw new Error(\n 'tensor3d() requires values to be number[][][] or flat/TypedArray');\n }\n if (inferredShape.length === 1 && shape == null) {\n throw new Error(\n 'tensor3d() requires shape to be provided when `values` ' +\n 'are a flat array');\n }\n return makeTensor(values, shape, inferredShape, dtype) as Tensor3D;\n}\n", "/**\n * @license\n * Copyright 2019 Google LLC. All Rights Reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * =============================================================================\n */\n\nimport {ENGINE} from '../engine';\nimport {FromPixels, FromPixelsAttrs, FromPixelsInputs} from '../kernel_names';\nimport {getKernel, NamedAttrMap} from '../kernel_registry';\nimport {Tensor, Tensor2D, Tensor3D} from '../tensor';\nimport {NamedTensorMap} from '../tensor_types';\nimport {convertToTensor} from '../tensor_util_env';\nimport {PixelData, TensorLike} from '../types';\n\nimport {cast} from './cast';\nimport {op} from './operation';\nimport {tensor3d} from './tensor3d';\n\nlet fromPixels2DContext: CanvasRenderingContext2D;\n\n/**\n * Creates a `tf.Tensor` from an image.\n *\n * ```js\n * const image = new ImageData(1, 1);\n * image.data[0] = 100;\n * image.data[1] = 150;\n * image.data[2] = 200;\n * image.data[3] = 255;\n *\n * tf.browser.fromPixels(image).print();\n * ```\n *\n * @param pixels The input image to construct the tensor from. The\n * supported image types are all 4-channel. You can also pass in an image\n * object with following attributes:\n * `{data: Uint8Array; width: number; height: number}`\n * @param numChannels The number of channels of the output tensor. A\n * numChannels value less than 4 allows you to ignore channels. Defaults to\n * 3 (ignores alpha channel of input image).\n *\n * @doc {heading: 'Browser', namespace: 'browser', ignoreCI: true}\n */\nfunction fromPixels_(\n pixels: PixelData|ImageData|HTMLImageElement|HTMLCanvasElement|\n HTMLVideoElement,\n numChannels = 3): Tensor3D {\n // Sanity checks.\n if (numChannels > 4) {\n throw new Error(\n 'Cannot construct Tensor with more than 4 channels from pixels.');\n }\n if (pixels == null) {\n throw new Error('pixels passed to tf.browser.fromPixels() can not be null');\n }\n let isPixelData = false;\n let isImageData = false;\n let isVideo = false;\n let isImage = false;\n let isCanvasLike = false;\n if ((pixels as PixelData).data instanceof Uint8Array) {\n isPixelData = true;\n } else if (\n typeof (ImageData) !== 'undefined' && pixels instanceof ImageData) {\n isImageData = true;\n } else if (\n typeof (HTMLVideoElement) !== 'undefined' &&\n pixels instanceof HTMLVideoElement) {\n isVideo = true;\n } else if (\n typeof (HTMLImageElement) !== 'undefined' &&\n pixels instanceof HTMLImageElement) {\n isImage = true;\n // tslint:disable-next-line: no-any\n } else if ((pixels as any).getContext != null) {\n isCanvasLike = true;\n } else {\n throw new Error(\n 'pixels passed to tf.browser.fromPixels() must be either an ' +\n `HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData ` +\n `in browser, or OffscreenCanvas, ImageData in webworker` +\n ` or {data: Uint32Array, width: number, height: number}, ` +\n `but was ${(pixels as {}).constructor.name}`);\n }\n if (isVideo) {\n const HAVE_CURRENT_DATA_READY_STATE = 2;\n if (isVideo &&\n (pixels as HTMLVideoElement).readyState <\n HAVE_CURRENT_DATA_READY_STATE) {\n throw new Error(\n 'The video element has not loaded data yet. Please wait for ' +\n '`loadeddata` event on the