From 13eee532cc042e334c06c9b15f3dfd7421c835b7 Mon Sep 17 00:00:00 2001 From: Vladimir Mandic Date: Sat, 11 Sep 2021 10:29:31 -0400 Subject: [PATCH] simplify dependencies --- .npmignore | 1 - CHANGELOG.md | 14 +- build.json | 40 +- dist/human.esm.js | 76223 ++++++++++++------------------------- dist/human.esm.js.map | 4 +- dist/human.js | 69497 +-------------------------------- dist/tfjs.esm.js | 60413 +---------------------------- package.json | 28 +- test/build.log | 168 + types/dist/tfjs.esm.d.ts | 2725 +- 10 files changed, 29545 insertions(+), 179568 deletions(-) create mode 100644 test/build.log diff --git a/.npmignore b/.npmignore index 1e071ede..64c274ec 100644 --- a/.npmignore +++ b/.npmignore @@ -6,4 +6,3 @@ test wiki dist/tfjs.esm.js dist/tfjs.esm.js.map -types/dist/tfjs.esm.d.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d14cfd0..5c79ff18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,16 +1,18 @@ -# @vladmandic/human +# packageJson - Version: **2.1.5** - Description: **Human: AI-powered 3D Face Detection & Rotation Tracking, Face Description & Recognition, Body Pose Tracking, 3D Hand & Finger Tracking, Iris Analysis, Age & Gender & Emotion Prediction, Gesture Recognition** + Version: **undefined** + Description: **undefined** - Author: **Vladimir Mandic ** - License: **MIT** + Author: **undefined** + License: **undefined** Repository: **** ## Changelog -### **HEAD -> main** 2021/09/06 mandic00@live.com +### **HEAD -> main** 2021/09/10 mandic00@live.com +- remove old build server +- change build process - add benchmark info - simplify canvas handling in nodejs - full rebuild diff --git a/build.json b/build.json index 762c9a32..7ef4414a 100644 --- a/build.json +++ b/build.json @@ -5,21 +5,21 @@ "console": true, "output": "test/build.log" }, + "profiles": { + "production": ["clean", "compile", "typings", "typedoc", "lint", "changelog"], + "development": ["serve", "watch", "compile"] + }, "clean": { - "enabled": true, "locations": ["dist/*", "types/*", "typedoc/*"] }, "lint": { - "enabled": true, "locations": [ "src/**/*.ts", "test/*.js", "demo/**/*.js" ], "rules": { } }, "changelog": { - "enabled": true, "log": "CHANGELOG.md" }, "serve": { - "enabled": true, "sslKey": "node_modules/@vladmandic/build/cert/https.key", "sslCrt": "node_modules/@vladmandic/build/cert/https.crt", "httpPort": 10030, @@ -29,21 +29,14 @@ "defaultFile": "index.html" }, "build": { - "enabled": true, "global": { "target": "es2018", "sourcemap": true, "banner": { "js": "/*\n Human\n homepage: \n author: '\n*/\n" } }, - "production": { - "minify": false - }, - "development": { - "minify": false - }, "targets": [ { - "name": "tfjs for nodejs with cpu", + "name": "tfjs/nodejs/cpu", "platform": "node", "format": "cjs", "input": "tfjs/tf-node.ts", @@ -52,7 +45,7 @@ "external": ["@tensorflow"] }, { - "name": "human for nodejs with cpu", + "name": "human/nodejs/cpu", "platform": "node", "format": "cjs", "input": "src/human.ts", @@ -61,7 +54,7 @@ "external": ["@tensorflow"] }, { - "name": "tfjs for nodejs with gpu", + "name": "tfjs/nodejs/gpu", "platform": "node", "format": "cjs", "input": "tfjs/tf-node-gpu.ts", @@ -70,7 +63,7 @@ "external": ["@tensorflow"] }, { - "name": "human for nodejs with gpu", + "name": "human/nodejs/gpu", "platform": "node", "format": "cjs", "input": "src/human.ts", @@ -79,7 +72,7 @@ "external": ["@tensorflow"] }, { - "name": "tfjs for nodejs with wasm", + "name": "tfjs/nodejs/wasm", "platform": "node", "format": "cjs", "input": "tfjs/tf-node-wasm.ts", @@ -88,7 +81,7 @@ "external": ["@tensorflow"] }, { - "name": "human for nodejs with wasm", + "name": "human/nodejs/wasm", "platform": "node", "format": "cjs", "input": "src/human.ts", @@ -97,7 +90,7 @@ "external": ["@tensorflow"] }, { - "name": "tfjs for browser esm nobundle", + "name": "tfjs/browser/esm/nobundle", "platform": "browser", "format": "esm", "input": "tfjs/tf-browser.ts", @@ -106,7 +99,7 @@ "external": ["@tensorflow", "fs", "os", "buffer", "util"] }, { - "name": "human for browser esm nobundle", + "name": "human/browser/esm/nobundle", "platform": "browser", "format": "esm", "input": "src/human.ts", @@ -115,25 +108,27 @@ "external": ["@tensorflow", "fs", "os", "buffer", "util"] }, { - "name": "tfjs for browser esm bundle", + "name": "tfjs/browser/esm/bundle", "platform": "browser", "format": "esm", "input": "tfjs/tf-browser.ts", "output": "dist/tfjs.esm.js", "sourcemap": false, + "minify": true, "external": ["fs", "os", "buffer", "util"] }, { - "name": "human for browser iife bundle", + "name": "human/browser/iife/bundle", "platform": "browser", "format": "iife", "input": "src/human.ts", "output": "dist/human.js", "sourcemap": false, + "minify": true, "external": ["fs", "os", "buffer", "util"] }, { - "name": "human for browser esm bundle", + "name": "human/browser/esm/bundle", "platform": "browser", "format": "esm", "input": "src/human.ts", @@ -146,7 +141,6 @@ ] }, "watch": { - "enabled": true, "locations": [ "src/**", "tfjs/*" ] }, "typescript": { diff --git a/dist/human.esm.js b/dist/human.esm.js index 4273255f..0ddd6c33 100644 --- a/dist/human.esm.js +++ b/dist/human.esm.js @@ -9,10 +9,10 @@ var __markAsModule = (target) => __defProp(target, "__esModule", { value: true } var __require = typeof require !== "undefined" ? require : (x) => { throw new Error('Dynamic require of "' + x + '" is not supported'); }; -var __export = (target, all6) => { +var __export = (target, all2) => { __markAsModule(target); - for (var name in all6) - __defProp(target, name, { get: all6[name], enumerable: true }); + for (var name in all2) + __defProp(target, name, { get: all2[name], enumerable: true }); }; var __accessCheck = (obj, member, msg) => { if (!member.has(obj)) @@ -44,9 +44,9 @@ function join(folder, file) { } function log(...msg) { const dt = new Date(); - const ts = `${dt.getHours().toString().padStart(2, "0")}:${dt.getMinutes().toString().padStart(2, "0")}:${dt.getSeconds().toString().padStart(2, "0")}.${dt.getMilliseconds().toString().padStart(3, "0")}`; + const ts2 = `${dt.getHours().toString().padStart(2, "0")}:${dt.getMinutes().toString().padStart(2, "0")}:${dt.getSeconds().toString().padStart(2, "0")}.${dt.getMilliseconds().toString().padStart(3, "0")}`; if (msg) - console.log(ts, "Human:", ...msg); + console.log(ts2, "Human:", ...msg); } var now = () => { if (typeof performance !== "undefined") @@ -195,6583 +195,4062 @@ function info() { // dist/tfjs.esm.js var tfjs_esm_exports = {}; __export(tfjs_esm_exports, { - Abs: () => Abs, - Acos: () => Acos, - Acosh: () => Acosh, - AdadeltaOptimizer: () => AdadeltaOptimizer, - AdagradOptimizer: () => AdagradOptimizer, - AdamOptimizer: () => AdamOptimizer, - AdamaxOptimizer: () => AdamaxOptimizer, - Add: () => Add, - AddN: () => AddN, - All: () => All, - Any: () => Any, - ArgMax: () => ArgMax, - ArgMin: () => ArgMin, - Asin: () => Asin, - Asinh: () => Asinh, - Atan: () => Atan, - Atan2: () => Atan2, - Atanh: () => Atanh, - AvgPool: () => AvgPool, - AvgPool3D: () => AvgPool3D, - AvgPool3DGrad: () => AvgPool3DGrad, - AvgPoolGrad: () => AvgPoolGrad, - BackendWasm: () => BackendWasm, - BatchMatMul: () => BatchMatMul, - BatchToSpaceND: () => BatchToSpaceND, - Bincount: () => Bincount, - BroadcastArgs: () => BroadcastArgs, - BroadcastTo: () => BroadcastTo, - Callback: () => Callback, - CallbackList: () => CallbackList, - Cast: () => Cast, - Ceil: () => Ceil, - ClipByValue: () => ClipByValue, - Complex: () => Complex, - ComplexAbs: () => ComplexAbs, - Concat: () => Concat, - Conv2D: () => Conv2D, - Conv2DBackpropFilter: () => Conv2DBackpropFilter, - Conv2DBackpropInput: () => Conv2DBackpropInput, - Conv3D: () => Conv3D, - Conv3DBackpropFilterV2: () => Conv3DBackpropFilterV2, - Conv3DBackpropInputV2: () => Conv3DBackpropInputV2, - Cos: () => Cos, - Cosh: () => Cosh, - CropAndResize: () => CropAndResize, - Cumsum: () => Cumsum, - CustomCallback: () => CustomCallback, - DataStorage: () => DataStorage, - DenseBincount: () => DenseBincount, - DepthToSpace: () => DepthToSpace, - DepthwiseConv2dNative: () => DepthwiseConv2dNative, - DepthwiseConv2dNativeBackpropFilter: () => DepthwiseConv2dNativeBackpropFilter, - DepthwiseConv2dNativeBackpropInput: () => DepthwiseConv2dNativeBackpropInput, - Diag: () => Diag, - Dilation2D: () => Dilation2D, - Dilation2DBackpropFilter: () => Dilation2DBackpropFilter, - Dilation2DBackpropInput: () => Dilation2DBackpropInput, - ENV: () => ENV, - EarlyStopping: () => EarlyStopping, - Einsum: () => Einsum, - Elu: () => Elu, - EluGrad: () => EluGrad, - Environment: () => Environment, - Equal: () => Equal, - Erf: () => Erf, - Exp: () => Exp, - ExpandDims: () => ExpandDims, - Expm1: () => Expm1, - FFT: () => FFT, - Fill: () => Fill, - FlipLeftRight: () => FlipLeftRight, - Floor: () => Floor, - FloorDiv: () => FloorDiv, - FromPixels: () => FromPixels, - FusedBatchNorm: () => FusedBatchNorm, - FusedConv2D: () => FusedConv2D, - FusedDepthwiseConv2D: () => FusedDepthwiseConv2D, - GPGPUContext: () => GPGPUContext, - GatherNd: () => GatherNd, - GatherV2: () => GatherV2, - GraphModel: () => GraphModel, - Greater: () => Greater, - GreaterEqual: () => GreaterEqual, - History: () => History, - IFFT: () => IFFT, - Identity: () => Identity, - Imag: () => Imag, - InputSpec: () => InputSpec, - IsFinite: () => IsFinite, - IsInf: () => IsInf, - IsNan: () => IsNan, - KernelBackend: () => KernelBackend, - LRN: () => LRN, - LRNGrad: () => LRNGrad, - LayerVariable: () => LayerVariable, - LayersModel: () => LayersModel, - LeakyRelu: () => LeakyRelu, - Less: () => Less, - LessEqual: () => LessEqual, - LinSpace: () => LinSpace, - Log: () => Log, - Log1p: () => Log1p, - LogSoftmax: () => LogSoftmax, - LogicalAnd: () => LogicalAnd, - LogicalNot: () => LogicalNot, - LogicalOr: () => LogicalOr, - MathBackendCPU: () => MathBackendCPU, - MathBackendWebGL: () => MathBackendWebGL, - Max: () => Max, - MaxPool: () => MaxPool, - MaxPool3D: () => MaxPool3D, - MaxPool3DGrad: () => MaxPool3DGrad, - MaxPoolGrad: () => MaxPoolGrad, - MaxPoolWithArgmax: () => MaxPoolWithArgmax, - Maximum: () => Maximum, - Mean: () => Mean, - Min: () => Min, - Minimum: () => Minimum, - MirrorPad: () => MirrorPad, - Mod: () => Mod, - MomentumOptimizer: () => MomentumOptimizer, - Multinomial: () => Multinomial, - Multiply: () => Multiply, - Neg: () => Neg, - NonMaxSuppressionV3: () => NonMaxSuppressionV3, - NonMaxSuppressionV4: () => NonMaxSuppressionV4, - NonMaxSuppressionV5: () => NonMaxSuppressionV5, - NotEqual: () => NotEqual, - OP_SCOPE_SUFFIX: () => OP_SCOPE_SUFFIX, - OneHot: () => OneHot, - OnesLike: () => OnesLike, - Optimizer: () => Optimizer, - Pack: () => Pack, - PadV2: () => PadV2, - Pool: () => Pool, - Pow: () => Pow, - Prelu: () => Prelu, - Prod: () => Prod, - RMSPropOptimizer: () => RMSPropOptimizer, - RNN: () => RNN, - Range: () => Range, - Rank: () => Rank, - Real: () => Real, - RealDiv: () => RealDiv, - Reciprocal: () => Reciprocal, - Reduction: () => Reduction, - Relu: () => Relu, - Relu6: () => Relu6, - Reshape: () => Reshape, - ResizeBilinear: () => ResizeBilinear, - ResizeBilinearGrad: () => ResizeBilinearGrad, - ResizeNearestNeighbor: () => ResizeNearestNeighbor, - ResizeNearestNeighborGrad: () => ResizeNearestNeighborGrad, - Reverse: () => Reverse, - RotateWithOffset: () => RotateWithOffset, - Round: () => Round, - Rsqrt: () => Rsqrt, - SGDOptimizer: () => SGDOptimizer, - ScatterNd: () => ScatterNd, - Select: () => Select, - Selu: () => Selu, - Sequential: () => Sequential, - Sigmoid: () => Sigmoid, - Sign: () => Sign, - Sin: () => Sin, - Sinh: () => Sinh, - Slice: () => Slice, - Softmax: () => Softmax, - Softplus: () => Softplus, - SpaceToBatchND: () => SpaceToBatchND, - SparseFillEmptyRows: () => SparseFillEmptyRows, - SparseReshape: () => SparseReshape, - SparseSegmentMean: () => SparseSegmentMean, - SparseSegmentSum: () => SparseSegmentSum, - SparseToDense: () => SparseToDense, - SplitV: () => SplitV, - Sqrt: () => Sqrt, - Square: () => Square, - SquaredDifference: () => SquaredDifference, - Step: () => Step, - StridedSlice: () => StridedSlice, - StringNGrams: () => StringNGrams, - StringSplit: () => StringSplit, - StringToHashBucketFast: () => StringToHashBucketFast, - Sub: () => Sub, - Sum: () => Sum, - SymbolicTensor: () => SymbolicTensor, - Tan: () => Tan, - Tanh: () => Tanh, - Tensor: () => Tensor, - TensorBuffer: () => TensorBuffer, - Tile: () => Tile, - TopK: () => TopK, - Transform: () => Transform, - Transpose: () => Transpose, - Unique: () => Unique, - Unpack: () => Unpack, - UnsortedSegmentSum: () => UnsortedSegmentSum, - Variable: () => Variable, - ZerosLike: () => ZerosLike, - _FusedMatMul: () => _FusedMatMul, - abs: () => abs, - acos: () => acos, - acosh: () => acosh, - add: () => add2, - addN: () => addN, - all: () => all, - any: () => any, - argMax: () => argMax, - argMin: () => argMin, - asin: () => asin, - asinh: () => asinh, - atan: () => atan, - atan2: () => atan2, - atanh: () => atanh, - avgPool: () => avgPool, - avgPool3d: () => avgPool3d, - backend: () => backend, - backend_util: () => backend_util_exports, - basicLSTMCell: () => basicLSTMCell, - batchNorm: () => batchNorm, - batchNorm2d: () => batchNorm2d, - batchNorm3d: () => batchNorm3d, - batchNorm4d: () => batchNorm4d, - batchToSpaceND: () => batchToSpaceND, - bincount: () => bincount, - booleanMaskAsync: () => booleanMaskAsync, - broadcastArgs: () => broadcastArgs, - broadcastTo: () => broadcastTo, - browser: () => browser_exports, - buffer: () => buffer, - callbacks: () => callbacks, - cast: () => cast, - ceil: () => ceil, - clipByValue: () => clipByValue, - clone: () => clone, - complex: () => complex, - concat: () => concat, - concat1d: () => concat1d, - concat2d: () => concat2d, - concat3d: () => concat3d, - concat4d: () => concat4d, - constraints: () => exports_constraints_exports, - conv1d: () => conv1d, - conv2d: () => conv2d, - conv2dTranspose: () => conv2dTranspose, - conv3d: () => conv3d, - conv3dTranspose: () => conv3dTranspose, - copyRegisteredKernels: () => copyRegisteredKernels, - cos: () => cos, - cosh: () => cosh, - cosineWindow: () => cosineWindow, - cumsum: () => cumsum, - customGrad: () => customGrad, - data: () => dist_exports, - denseBincount: () => denseBincount, - deprecationWarn: () => deprecationWarn, - depthToSpace: () => depthToSpace, - depthwiseConv2d: () => depthwiseConv2d, - deregisterOp: () => deregisterOp, - device_util: () => device_util_exports, - diag: () => diag, - dilation2d: () => dilation2d, - disableDeprecationWarnings: () => disableDeprecationWarnings, - dispose: () => dispose, - disposeVariables: () => disposeVariables, - div: () => div, - divNoNan: () => divNoNan, - dot: () => dot, - dropout: () => dropout, - einsum: () => einsum, - elu: () => elu, - enableDebugMode: () => enableDebugMode, - enableProdMode: () => enableProdMode, - enclosingPowerOfTwo: () => enclosingPowerOfTwo, - engine: () => engine, - env: () => env, - equal: () => equal, - erf: () => erf, - exp: () => exp, - expandDims: () => expandDims, - expm1: () => expm1, - eye: () => eye, - fft: () => fft, - fill: () => fill, - findBackend: () => findBackend, - findBackendFactory: () => findBackendFactory, - floor: () => floor, - floorDiv: () => floorDiv, - forceHalfFloat: () => forceHalfFloat, - fused: () => fused_ops_exports, - gather: () => gather, - gatherND: () => gatherND, - gather_util: () => gather_nd_util_exports, - getBackend: () => getBackend, - getGradient: () => getGradient, - getKernel: () => getKernel, - getKernelsForBackend: () => getKernelsForBackend, - gpgpu_util: () => gpgpu_util_exports, - grad: () => grad, - grads: () => grads, - greater: () => greater, - greaterEqual: () => greaterEqual, - ifft: () => ifft, - imag: () => imag, - image: () => image, - inTopKAsync: () => inTopKAsync, - initializers: () => exports_initializers_exports, - input: () => input, - io: () => io_exports, - irfft: () => irfft, - isFinite: () => isFinite2, - isInf: () => isInf, - isNaN: () => isNaN2, - keep: () => keep, - kernel_impls: () => kernel_impls_exports, - layers: () => exports_layers_exports, - leakyRelu: () => leakyRelu, - less: () => less, - lessEqual: () => lessEqual, - linalg: () => linalg, - linspace: () => linspace, - loadGraphModel: () => loadGraphModel, - loadLayersModel: () => loadLayersModel, - localResponseNormalization: () => localResponseNormalization, - log: () => log5, - log1p: () => log1p, - logSigmoid: () => logSigmoid, - logSoftmax: () => logSoftmax, - logSumExp: () => logSumExp, - logicalAnd: () => logicalAnd, - logicalNot: () => logicalNot, - logicalOr: () => logicalOr, - logicalXor: () => logicalXor, - losses: () => losses, - matMul: () => matMul, - math: () => math_exports, - max: () => max, - maxPool: () => maxPool, - maxPool3d: () => maxPool3d, - maxPoolWithArgmax: () => maxPoolWithArgmax, - maximum: () => maximum, - mean: () => mean, - memory: () => memory, - meshgrid: () => meshgrid, - metrics: () => exports_metrics_exports, - min: () => min, - minimum: () => minimum, - mirrorPad: () => mirrorPad, - mod: () => mod, - model: () => model, - models: () => exports_models_exports, - moments: () => moments, - movingAverage: () => movingAverage, - mul: () => mul, - multiRNNCell: () => multiRNNCell, - multinomial: () => multinomial, - neg: () => neg, - nextFrame: () => nextFrame, - norm: () => norm, - notEqual: () => notEqual, - oneHot: () => oneHot, - ones: () => ones2, - onesLike: () => onesLike, - op: () => op, - outerProduct: () => outerProduct, - pad: () => pad, - pad1d: () => pad1d, - pad2d: () => pad2d, - pad3d: () => pad3d, - pad4d: () => pad4d, - pool: () => pool, - pow: () => pow, - prelu: () => prelu, - print: () => print2, - prod: () => prod, - profile: () => profile, - rand: () => rand, - randomGamma: () => randomGamma, - randomNormal: () => randomNormal, - randomUniform: () => randomUniform, - range: () => range, - ready: () => ready, - real: () => real, - reciprocal: () => reciprocal, - registerBackend: () => registerBackend, - registerCallbackConstructor: () => registerCallbackConstructor, - registerGradient: () => registerGradient, - registerKernel: () => registerKernel, - registerOp: () => registerOp, - regularizers: () => exports_regularizers_exports, - relu: () => relu, - relu6: () => relu6, - removeBackend: () => removeBackend, - reshape: () => reshape, - reverse: () => reverse, - reverse1d: () => reverse1d, - reverse2d: () => reverse2d, - reverse3d: () => reverse3d, - reverse4d: () => reverse4d, - rfft: () => rfft, - round: () => round2, - rsqrt: () => rsqrt, - scalar: () => scalar, - scatterND: () => scatterND, - scatter_util: () => scatter_nd_util_exports, - selu: () => selu, - separableConv2d: () => separableConv2d, - sequential: () => sequential, - serialization: () => serialization_exports, - setBackend: () => setBackend, - setPlatform: () => setPlatform, - setWasmPath: () => setWasmPath, - setWasmPaths: () => setWasmPaths, - setWebGLContext: () => setWebGLContext, - setdiff1dAsync: () => setdiff1dAsync, - shared: () => shared_exports, - sigmoid: () => sigmoid, - sign: () => sign, - signal: () => signal, - sin: () => sin, - sinh: () => sinh, - slice: () => slice, - slice1d: () => slice1d, - slice2d: () => slice2d, - slice3d: () => slice3d, - slice4d: () => slice4d, - slice_util: () => slice_util_exports, - softmax: () => softmax, - softplus: () => softplus, - spaceToBatchND: () => spaceToBatchND, - sparse: () => sparse, - sparseToDense: () => sparseToDense, - spectral: () => spectral, - split: () => split, - sqrt: () => sqrt, - square: () => square, - squaredDifference: () => squaredDifference, - squeeze: () => squeeze, - stack: () => stack, - step: () => step, - stridedSlice: () => stridedSlice, - string: () => string, - sub: () => sub, - sum: () => sum2, - sumOutType: () => sumOutType, - tan: () => tan, - tanh: () => tanh2, - tensor: () => tensor, - tensor1d: () => tensor1d, - tensor2d: () => tensor2d, - tensor3d: () => tensor3d, - tensor4d: () => tensor4d, - tensor5d: () => tensor5d, - tensor6d: () => tensor6d, - tensor_util: () => tensor_util_exports, - test_util: () => test_util_exports, - tidy: () => tidy, - tile: () => tile, - time: () => time, - topk: () => topk, - train: () => train, - transpose: () => transpose, - truncatedNormal: () => truncatedNormal, - unique: () => unique, - unregisterGradient: () => unregisterGradient, - unregisterKernel: () => unregisterKernel, - unsortedSegmentSum: () => unsortedSegmentSum, - unstack: () => unstack, - upcastType: () => upcastType, - util: () => util_exports, - valueAndGrad: () => valueAndGrad, - valueAndGrads: () => valueAndGrads, - variable: () => variable, - variableGrads: () => variableGrads, - version: () => version16, - version_converter: () => version11, - version_core: () => version9, - version_cpu: () => version13, - version_layers: () => version10, - version_wasm: () => version15, - version_webgl: () => version14, - webgl: () => webgl, - webgl_util: () => webgl_util_exports, - where: () => where, - whereAsync: () => whereAsync, - zeros: () => zeros, - zerosLike: () => zerosLike + Abs: () => Vs, + Acos: () => Ni, + Acosh: () => Ti, + AdadeltaOptimizer: () => xp, + AdagradOptimizer: () => yp, + AdamOptimizer: () => bp, + AdamaxOptimizer: () => wp, + Add: () => Wn, + AddN: () => So, + All: () => Ei, + Any: () => Ai, + ArgMax: () => Io, + ArgMin: () => Xa, + Asin: () => $i, + Asinh: () => Di, + Atan: () => Ri, + Atan2: () => Oi, + Atanh: () => Fi, + AvgPool: () => No, + AvgPool3D: () => Ya, + AvgPool3DGrad: () => xc, + AvgPoolGrad: () => gc, + BackendWasm: () => My, + BatchMatMul: () => To, + BatchToSpaceND: () => Ws, + Bincount: () => yc, + BroadcastArgs: () => Zh, + BroadcastTo: () => XI, + Callback: () => mv, + CallbackList: () => C_, + Cast: () => Qn, + Ceil: () => Eo, + ClipByValue: () => eo, + Complex: () => bc, + ComplexAbs: () => Za, + Concat: () => js, + Conv2D: () => Ao, + Conv2DBackpropFilter: () => wc, + Conv2DBackpropInput: () => $o, + Conv3D: () => Ja, + Conv3DBackpropFilterV2: () => kc, + Conv3DBackpropInputV2: () => _c, + Cos: () => Do, + Cosh: () => Ro, + CropAndResize: () => Pi, + Cumsum: () => Fo, + CustomCallback: () => I_, + DataStorage: () => Ka, + DenseBincount: () => vc, + DepthToSpace: () => Mi, + DepthwiseConv2dNative: () => Oo, + DepthwiseConv2dNativeBackpropFilter: () => Cc, + DepthwiseConv2dNativeBackpropInput: () => Sc, + Diag: () => Ic, + Dilation2D: () => Qa, + Dilation2DBackpropFilter: () => Dm, + Dilation2DBackpropInput: () => $m, + ENV: () => gw, + EarlyStopping: () => fv, + Einsum: () => Nc, + Elu: () => Mo, + EluGrad: () => Tc, + Environment: () => Yh, + Equal: () => zi, + Erf: () => Li, + Exp: () => Lo, + ExpandDims: () => Gs, + Expm1: () => Bi, + FFT: () => Ec, + Fill: () => el, + FlipLeftRight: () => Vi, + Floor: () => zo, + FloorDiv: () => Bo, + FromPixels: () => Rm, + FusedBatchNorm: () => Vo, + FusedConv2D: () => ni, + FusedDepthwiseConv2D: () => oi, + GPGPUContext: () => hy, + GatherNd: () => Wi, + GatherV2: () => Us, + GraphModel: () => jv, + Greater: () => ji, + GreaterEqual: () => Wo, + History: () => S_, + IFFT: () => Ac, + Identity: () => to, + Imag: () => $c, + InputSpec: () => _t, + IsFinite: () => Gi, + IsInf: () => Ui, + IsNan: () => Hi, + KernelBackend: () => Ls, + LRN: () => tl, + LRNGrad: () => Rc, + LayerVariable: () => Yg, + LayersModel: () => Xn, + LeakyRelu: () => jo, + Less: () => qi, + LessEqual: () => Ki, + LinSpace: () => Dc, + Log: () => Go, + Log1p: () => Xi, + LogSoftmax: () => YI, + LogicalAnd: () => Yi, + LogicalNot: () => jl, + LogicalOr: () => Gl, + MathBackendCPU: () => Pu, + MathBackendWebGL: () => Hu, + Max: () => Uo, + MaxPool: () => qo, + MaxPool3D: () => rl, + MaxPool3DGrad: () => Oc, + MaxPoolGrad: () => Fc, + MaxPoolWithArgmax: () => Pc, + Maximum: () => Ho, + Mean: () => Ko, + Min: () => Xo, + Minimum: () => Yo, + MirrorPad: () => Zo, + Mod: () => Zi, + MomentumOptimizer: () => kp, + Multinomial: () => Mc, + Multiply: () => Jo, + Neg: () => Hs, + NonMaxSuppressionV3: () => Qi, + NonMaxSuppressionV4: () => ea, + NonMaxSuppressionV5: () => ta, + NotEqual: () => Ji, + OP_SCOPE_SUFFIX: () => S1, + OneHot: () => Qo, + OnesLike: () => qs, + Optimizer: () => Wr, + Pack: () => Ks, + PadV2: () => es, + Pool: () => fse, + Pow: () => ts, + Prelu: () => rs, + Prod: () => ra, + RMSPropOptimizer: () => _p, + RNN: () => On, + Range: () => nl, + Rank: () => Iw, + Real: () => Lc, + RealDiv: () => Po, + Reciprocal: () => na, + Reduction: () => qt, + Relu: () => ns, + Relu6: () => ss, + Reshape: () => Xs, + ResizeBilinear: () => os, + ResizeBilinearGrad: () => Bc, + ResizeNearestNeighbor: () => ol, + ResizeNearestNeighborGrad: () => zc, + Reverse: () => is, + RotateWithOffset: () => ma, + Round: () => as, + Rsqrt: () => ls, + SGDOptimizer: () => dl, + ScatterNd: () => oa, + Select: () => Ys, + Selu: () => sa, + Sequential: () => $a, + Sigmoid: () => cs, + Sign: () => aa, + Sin: () => us, + Sinh: () => ia, + Slice: () => Zs, + Softmax: () => fs, + Softplus: () => la, + SpaceToBatchND: () => Js, + SparseFillEmptyRows: () => Vc, + SparseReshape: () => Wc, + SparseSegmentMean: () => jc, + SparseSegmentSum: () => Gc, + SparseToDense: () => Uc, + SplitV: () => Qs, + Sqrt: () => ps, + Square: () => sl, + SquaredDifference: () => ds, + Step: () => ro, + StridedSlice: () => ua, + StringNGrams: () => Hc, + StringSplit: () => qc, + StringToHashBucketFast: () => Kc, + Sub: () => hs, + Sum: () => ms, + SymbolicTensor: () => on, + Tan: () => gs, + Tanh: () => xs, + Tensor: () => je, + TensorBuffer: () => ct, + Tile: () => jn, + TopK: () => ca, + Transform: () => pa, + Transpose: () => ys, + Unique: () => Xc, + Unpack: () => ei, + UnsortedSegmentSum: () => il, + Variable: () => ul, + ZerosLike: () => ti, + _FusedMatMul: () => ri, + abs: () => Tt, + acos: () => tk, + acosh: () => rk, + add: () => Y, + addN: () => nk, + all: () => Gm, + any: () => lp, + argMax: () => ba, + argMin: () => ok, + asin: () => sk, + asinh: () => ik, + atan: () => ak, + atan2: () => lk, + atanh: () => uk, + avgPool: () => nu, + avgPool3d: () => Um, + backend: () => kN, + backend_util: () => S, + basicLSTMCell: () => b4, + batchNorm: () => ai, + batchNorm2d: () => fk, + batchNorm3d: () => dk, + batchNorm4d: () => hk, + batchToSpaceND: () => ou, + bincount: () => Hm, + booleanMaskAsync: () => XIe, + broadcastArgs: () => gk, + broadcastTo: () => su, + browser: () => cg, + buffer: () => Se, + callbacks: () => PX, + cast: () => J, + ceil: () => xk, + clipByValue: () => Sr, + clone: () => hn, + complex: () => $n, + concat: () => tt, + concat1d: () => yk, + concat2d: () => bk, + concat3d: () => wk, + concat4d: () => kk, + constraints: () => PE, + conv1d: () => qm, + conv2d: () => Dn, + conv2dTranspose: () => Km, + conv3d: () => Xm, + conv3dTranspose: () => _k, + copyRegisteredKernels: () => wse, + cos: () => iu, + cosh: () => Ym, + cosineWindow: () => Tg, + cumsum: () => Zm, + customGrad: () => Qr, + data: () => s0, + denseBincount: () => vk, + deprecationWarn: () => ek, + depthToSpace: () => Ck, + depthwiseConv2d: () => ka, + deregisterOp: () => LX, + device_util: () => Ql, + diag: () => K4, + dilation2d: () => Sk, + disableDeprecationWarnings: () => nue, + dispose: () => Ae, + disposeVariables: () => oue, + div: () => ue, + divNoNan: () => Ik, + dot: () => rU, + dropout: () => UN, + einsum: () => Nk, + elu: () => _a, + enableDebugMode: () => rue, + enableProdMode: () => tue, + enclosingPowerOfTwo: () => HN, + engine: () => ks, + env: () => j, + equal: () => Dr, + erf: () => Tk, + exp: () => tr, + expandDims: () => gr, + expm1: () => Ek, + eye: () => pp, + fft: () => gu, + fill: () => _s, + findBackend: () => cue, + findBackendFactory: () => pue, + floor: () => va, + floorDiv: () => jm, + forceHalfFloat: () => BP, + fused: () => lo, + gather: () => li, + gatherND: () => jN, + gather_util: () => pg, + getBackend: () => lue, + getGradient: () => bw, + getKernel: () => Om, + getKernelsForBackend: () => Jh, + gpgpu_util: () => VO, + grad: () => NU, + grads: () => TU, + greater: () => Ht, + greaterEqual: () => Un, + ifft: () => fl, + imag: () => au, + image: () => bn, + inTopKAsync: () => sNe, + initializers: () => rA, + input: () => O_, + io: () => $r, + irfft: () => ff, + isFinite: () => xU, + isInf: () => bU, + isNaN: () => Ak, + keep: () => Dt, + kernel_impls: () => Mr, + layers: () => MA, + leakyRelu: () => lu, + less: () => Jm, + lessEqual: () => Hn, + linalg: () => RT, + linspace: () => $k, + loadGraphModel: () => m7, + loadLayersModel: () => K5, + localResponseNormalization: () => Dk, + log: () => Ir, + log1p: () => uu, + logSigmoid: () => FU, + logSoftmax: () => Qm, + logSumExp: () => Pk, + logicalAnd: () => Fr, + logicalNot: () => cu, + logicalOr: () => tf, + logicalXor: () => HU, + losses: () => tFe, + matMul: () => Me, + math: () => oN, + max: () => Vr, + maxPool: () => pu, + maxPool3d: () => rf, + maxPoolWithArgmax: () => Mk, + maximum: () => Rn, + mean: () => Ct, + memory: () => Wm, + meshgrid: () => JU, + metrics: () => LA, + min: () => mp, + minimum: () => Ca, + mirrorPad: () => Lk, + mod: () => zk, + model: () => H5, + models: () => zA, + moments: () => fp, + movingAverage: () => k1e, + mul: () => F, + multiRNNCell: () => iH, + multinomial: () => Bk, + neg: () => Ke, + nextFrame: () => xf, + norm: () => Ig, + notEqual: () => ci, + oneHot: () => xa, + ones: () => rr, + onesLike: () => xr, + op: () => I, + outerProduct: () => pH, + pad: () => xn, + pad1d: () => dH, + pad2d: () => gH, + pad3d: () => yH, + pad4d: () => wH, + pool: () => SH, + pow: () => yn, + prelu: () => fu, + print: () => Gw, + prod: () => nf, + profile: () => sue, + rand: () => AH, + randomGamma: () => LH, + randomNormal: () => _g, + randomUniform: () => vs, + range: () => Sa, + ready: () => aue, + real: () => ml, + reciprocal: () => Zk, + registerBackend: () => ap, + registerCallbackConstructor: () => X5, + registerGradient: () => ZI, + registerKernel: () => Ul, + registerOp: () => MX, + regularizers: () => BA, + relu: () => Or, + relu6: () => of, + removeBackend: () => uue, + reshape: () => O, + reverse: () => lr, + reverse1d: () => qH, + reverse2d: () => XH, + reverse3d: () => ZH, + reverse4d: () => QH, + rfft: () => xu, + round: () => sf, + rsqrt: () => af, + scalar: () => ce, + scatterND: () => VN, + scatter_util: () => fg, + selu: () => lf, + separableConv2d: () => Jk, + sequential: () => q5, + serialization: () => ee, + setBackend: () => VG, + setPlatform: () => mue, + setWasmPath: () => Hoe, + setWasmPaths: () => qoe, + setWebGLContext: () => W0, + setdiff1dAsync: () => Qk, + shared: () => Yx, + sigmoid: () => Jr, + sign: () => e_, + signal: () => TRe, + sin: () => uf, + sinh: () => cf, + slice: () => Oe, + slice1d: () => pf, + slice2d: () => vg, + slice3d: () => mf, + slice4d: () => hp, + slice_util: () => ar, + softmax: () => hu, + softplus: () => ui, + spaceToBatchND: () => mu, + sparse: () => gf, + sparseToDense: () => Ng, + spectral: () => vRe, + split: () => mr, + sqrt: () => St, + square: () => We, + squaredDifference: () => df, + squeeze: () => en, + stack: () => nr, + step: () => Ia, + stridedSlice: () => t_, + string: () => Pg, + sub: () => le, + sum: () => me, + sumOutType: () => Zl, + tan: () => r_, + tanh: () => wa, + tensor: () => vr, + tensor1d: () => At, + tensor2d: () => pi, + tensor3d: () => Kw, + tensor4d: () => Sq, + tensor5d: () => Iq, + tensor6d: () => Nq, + tensor_util: () => io, + test_util: () => wN, + tidy: () => z, + tile: () => Rr, + time: () => iue, + topk: () => n_, + train: () => vu, + transpose: () => Ve, + truncatedNormal: () => yu, + unique: () => Cg, + unregisterGradient: () => bse, + unregisterKernel: () => yse, + unsortedSegmentSum: () => o_, + unstack: () => Nr, + upcastType: () => pr, + util: () => b, + valueAndGrad: () => EU, + valueAndGrads: () => AU, + variable: () => s_, + variableGrads: () => yg, + version: () => FWt, + version_converter: () => f7, + version_core: () => BG, + version_cpu: () => q7, + version_layers: () => Vf, + version_wasm: () => Koe, + version_webgl: () => PJ, + webgl: () => Cwt, + webgl_util: () => $O, + where: () => Et, + whereAsync: () => hf, + zeros: () => ht, + zerosLike: () => Ie }); -var __create = Object.create; -var __defProp2 = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __markAsModule2 = (target) => __defProp2(target, "__esModule", { value: true }); -var __require2 = typeof __require !== "undefined" ? __require : (x) => { - throw new Error('Dynamic require of "' + x + '" is not supported'); +var jW = Object.create; +var qh = Object.defineProperty; +var GW = Object.getOwnPropertyDescriptor; +var UW = Object.getOwnPropertyNames; +var HW = Object.getPrototypeOf; +var qW = Object.prototype.hasOwnProperty; +var FI = (r) => qh(r, "__esModule", { value: true }); +var pc = typeof __require != "undefined" ? __require : (r) => { + throw new Error('Dynamic require of "' + r + '" is not supported'); }; -var __commonJS = (cb, mod4) => function __require22() { - return mod4 || (0, cb[Object.keys(cb)[0]])((mod4 = { exports: {} }).exports, mod4), mod4.exports; +var Ut = (r, e) => () => (e || r((e = { exports: {} }).exports, e), e.exports); +var He = (r, e) => { + FI(r); + for (var t in e) + qh(r, t, { get: e[t], enumerable: true }); }; -var __export2 = (target, all52) => { - __markAsModule2(target); - for (var name in all52) - __defProp2(target, name, { get: all52[name], enumerable: true }); +var KW = (r, e, t) => { + if (e && typeof e == "object" || typeof e == "function") + for (let n of UW(e)) + !qW.call(r, n) && n !== "default" && qh(r, n, { get: () => e[n], enumerable: !(t = GW(e, n)) || t.enumerable }); + return r; }; -var __reExport = (target, module, desc) => { - if (module && typeof module === "object" || typeof module === "function") { - for (let key of __getOwnPropNames(module)) - if (!__hasOwnProp.call(target, key) && key !== "default") - __defProp2(target, key, { get: () => module[key], enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable }); +var Bl = (r) => KW(FI(qh(r != null ? jW(HW(r)) : {}, "default", r && r.__esModule && "default" in r ? { get: () => r.default, enumerable: true } : { value: r, enumerable: true })), r); +var l1 = Ut((_se, a1) => { + a1.exports = Vt; + var no = null; + try { + no = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; + } catch (r) { } - return target; -}; -var __toModule = (module) => { - return __reExport(__markAsModule2(__defProp2(module != null ? __create(__getProtoOf(module)) : {}, "default", module && module.__esModule && "default" in module ? { get: () => module.default, enumerable: true } : { value: module, enumerable: true })), module); -}; -var require_long = __commonJS({ - "node_modules/.pnpm/long@4.0.0/node_modules/long/src/long.js"(exports, module) { - module.exports = Long2; - var wasm = null; - try { - wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([ - 0, - 97, - 115, - 109, - 1, - 0, - 0, - 0, - 1, - 13, - 2, - 96, - 0, - 1, - 127, - 96, - 4, - 127, - 127, - 127, - 127, - 1, - 127, - 3, - 7, - 6, - 0, - 1, - 1, - 1, - 1, - 1, - 6, - 6, - 1, - 127, - 1, - 65, - 0, - 11, - 7, - 50, - 6, - 3, - 109, - 117, - 108, - 0, - 1, - 5, - 100, - 105, - 118, - 95, - 115, - 0, - 2, - 5, - 100, - 105, - 118, - 95, - 117, - 0, - 3, - 5, - 114, - 101, - 109, - 95, - 115, - 0, - 4, - 5, - 114, - 101, - 109, - 95, - 117, - 0, - 5, - 8, - 103, - 101, - 116, - 95, - 104, - 105, - 103, - 104, - 0, - 0, - 10, - 191, - 1, - 6, - 4, - 0, - 35, - 0, - 11, - 36, - 1, - 1, - 126, - 32, - 0, - 173, - 32, - 1, - 173, - 66, - 32, - 134, - 132, - 32, - 2, - 173, - 32, - 3, - 173, - 66, - 32, - 134, - 132, - 126, - 34, - 4, - 66, - 32, - 135, - 167, - 36, - 0, - 32, - 4, - 167, - 11, - 36, - 1, - 1, - 126, - 32, - 0, - 173, - 32, - 1, - 173, - 66, - 32, - 134, - 132, - 32, - 2, - 173, - 32, - 3, - 173, - 66, - 32, - 134, - 132, - 127, - 34, - 4, - 66, - 32, - 135, - 167, - 36, - 0, - 32, - 4, - 167, - 11, - 36, - 1, - 1, - 126, - 32, - 0, - 173, - 32, - 1, - 173, - 66, - 32, - 134, - 132, - 32, - 2, - 173, - 32, - 3, - 173, - 66, - 32, - 134, - 132, - 128, - 34, - 4, - 66, - 32, - 135, - 167, - 36, - 0, - 32, - 4, - 167, - 11, - 36, - 1, - 1, - 126, - 32, - 0, - 173, - 32, - 1, - 173, - 66, - 32, - 134, - 132, - 32, - 2, - 173, - 32, - 3, - 173, - 66, - 32, - 134, - 132, - 129, - 34, - 4, - 66, - 32, - 135, - 167, - 36, - 0, - 32, - 4, - 167, - 11, - 36, - 1, - 1, - 126, - 32, - 0, - 173, - 32, - 1, - 173, - 66, - 32, - 134, - 132, - 32, - 2, - 173, - 32, - 3, - 173, - 66, - 32, - 134, - 132, - 130, - 34, - 4, - 66, - 32, - 135, - 167, - 36, - 0, - 32, - 4, - 167, - 11 - ])), {}).exports; - } catch (e) { + function Vt(r, e, t) { + this.low = r | 0, this.high = e | 0, this.unsigned = !!t; + } + Vt.prototype.__isLong__; + Object.defineProperty(Vt.prototype, "__isLong__", { value: true }); + function En(r) { + return (r && r.__isLong__) === true; + } + Vt.isLong = En; + var JI = {}, QI = {}; + function Hl(r, e) { + var t, n, o; + return e ? (r >>>= 0, (o = 0 <= r && r < 256) && (n = QI[r], n) ? n : (t = Wt(r, (r | 0) < 0 ? -1 : 0, true), o && (QI[r] = t), t)) : (r |= 0, (o = -128 <= r && r < 128) && (n = JI[r], n) ? n : (t = Wt(r, r < 0 ? -1 : 0, false), o && (JI[r] = t), t)); + } + Vt.fromInt = Hl; + function oo(r, e) { + if (isNaN(r)) + return e ? ql : so; + if (e) { + if (r < 0) + return ql; + if (r >= t1) + return i1; + } else { + if (r <= -r1) + return An; + if (r + 1 >= r1) + return s1; } - function Long2(low, high, unsigned) { - this.low = low | 0; - this.high = high | 0; - this.unsigned = !!unsigned; + return r < 0 ? oo(-r, e).neg() : Wt(r % Zc | 0, r / Zc | 0, e); + } + Vt.fromNumber = oo; + function Wt(r, e, t) { + return new Vt(r, e, t); + } + Vt.fromBits = Wt; + var Qh = Math.pow; + function kw(r, e, t) { + if (r.length === 0) + throw Error("empty string"); + if (r === "NaN" || r === "Infinity" || r === "+Infinity" || r === "-Infinity") + return so; + if (typeof e == "number" ? (t = e, e = false) : e = !!e, t = t || 10, t < 2 || 36 < t) + throw RangeError("radix"); + var n; + if ((n = r.indexOf("-")) > 0) + throw Error("interior hyphen"); + if (n === 0) + return kw(r.substring(1), e, t).neg(); + for (var o = oo(Qh(t, 8)), s = so, a = 0; a < r.length; a += 8) { + var i = Math.min(8, r.length - a), l = parseInt(r.substring(a, a + i), t); + if (i < 8) { + var u = oo(Qh(t, i)); + s = s.mul(u).add(oo(l)); + } else + s = s.mul(o), s = s.add(oo(l)); } - Long2.prototype.__isLong__; - Object.defineProperty(Long2.prototype, "__isLong__", { value: true }); - function isLong(obj) { - return (obj && obj["__isLong__"]) === true; + return s.unsigned = e, s; + } + Vt.fromString = kw; + function bs(r, e) { + return typeof r == "number" ? oo(r, e) : typeof r == "string" ? kw(r, e) : Wt(r.low, r.high, typeof e == "boolean" ? e : r.unsigned); + } + Vt.fromValue = bs; + var e1 = 1 << 16, Sj = 1 << 24, Zc = e1 * e1, t1 = Zc * Zc, r1 = t1 / 2, n1 = Hl(Sj), so = Hl(0); + Vt.ZERO = so; + var ql = Hl(0, true); + Vt.UZERO = ql; + var Jc = Hl(1); + Vt.ONE = Jc; + var o1 = Hl(1, true); + Vt.UONE = o1; + var _w = Hl(-1); + Vt.NEG_ONE = _w; + var s1 = Wt(4294967295 | 0, 2147483647 | 0, false); + Vt.MAX_VALUE = s1; + var i1 = Wt(4294967295 | 0, 4294967295 | 0, true); + Vt.MAX_UNSIGNED_VALUE = i1; + var An = Wt(0, 2147483648 | 0, false); + Vt.MIN_VALUE = An; + var be = Vt.prototype; + be.toInt = function() { + return this.unsigned ? this.low >>> 0 : this.low; + }; + be.toNumber = function() { + return this.unsigned ? (this.high >>> 0) * Zc + (this.low >>> 0) : this.high * Zc + (this.low >>> 0); + }; + be.toString = function(e) { + if (e = e || 10, e < 2 || 36 < e) + throw RangeError("radix"); + if (this.isZero()) + return "0"; + if (this.isNegative()) + if (this.eq(An)) { + var t = oo(e), n = this.div(t), o = n.mul(t).sub(this); + return n.toString(e) + o.toInt().toString(e); + } else + return "-" + this.neg().toString(e); + for (var s = oo(Qh(e, 6), this.unsigned), a = this, i = ""; ; ) { + var l = a.div(s), u = a.sub(l.mul(s)).toInt() >>> 0, c = u.toString(e); + if (a = l, a.isZero()) + return c + i; + for (; c.length < 6; ) + c = "0" + c; + i = "" + c + i; } - Long2.isLong = isLong; - var INT_CACHE = {}; - var UINT_CACHE = {}; - function fromInt(value, unsigned) { - var obj, cachedObj, cache; - if (unsigned) { - value >>>= 0; - if (cache = 0 <= value && value < 256) { - cachedObj = UINT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true); - if (cache) - UINT_CACHE[value] = obj; - return obj; - } else { - value |= 0; - if (cache = -128 <= value && value < 128) { - cachedObj = INT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = fromBits(value, value < 0 ? -1 : 0, false); - if (cache) - INT_CACHE[value] = obj; - return obj; - } + }; + be.getHighBits = function() { + return this.high; + }; + be.getHighBitsUnsigned = function() { + return this.high >>> 0; + }; + be.getLowBits = function() { + return this.low; + }; + be.getLowBitsUnsigned = function() { + return this.low >>> 0; + }; + be.getNumBitsAbs = function() { + if (this.isNegative()) + return this.eq(An) ? 64 : this.neg().getNumBitsAbs(); + for (var e = this.high != 0 ? this.high : this.low, t = 31; t > 0 && (e & 1 << t) == 0; t--) + ; + return this.high != 0 ? t + 33 : t + 1; + }; + be.isZero = function() { + return this.high === 0 && this.low === 0; + }; + be.eqz = be.isZero; + be.isNegative = function() { + return !this.unsigned && this.high < 0; + }; + be.isPositive = function() { + return this.unsigned || this.high >= 0; + }; + be.isOdd = function() { + return (this.low & 1) == 1; + }; + be.isEven = function() { + return (this.low & 1) == 0; + }; + be.equals = function(e) { + return En(e) || (e = bs(e)), this.unsigned !== e.unsigned && this.high >>> 31 == 1 && e.high >>> 31 == 1 ? false : this.high === e.high && this.low === e.low; + }; + be.eq = be.equals; + be.notEquals = function(e) { + return !this.eq(e); + }; + be.neq = be.notEquals; + be.ne = be.notEquals; + be.lessThan = function(e) { + return this.comp(e) < 0; + }; + be.lt = be.lessThan; + be.lessThanOrEqual = function(e) { + return this.comp(e) <= 0; + }; + be.lte = be.lessThanOrEqual; + be.le = be.lessThanOrEqual; + be.greaterThan = function(e) { + return this.comp(e) > 0; + }; + be.gt = be.greaterThan; + be.greaterThanOrEqual = function(e) { + return this.comp(e) >= 0; + }; + be.gte = be.greaterThanOrEqual; + be.ge = be.greaterThanOrEqual; + be.compare = function(e) { + if (En(e) || (e = bs(e)), this.eq(e)) + return 0; + var t = this.isNegative(), n = e.isNegative(); + return t && !n ? -1 : !t && n ? 1 : this.unsigned ? e.high >>> 0 > this.high >>> 0 || e.high === this.high && e.low >>> 0 > this.low >>> 0 ? -1 : 1 : this.sub(e).isNegative() ? -1 : 1; + }; + be.comp = be.compare; + be.negate = function() { + return !this.unsigned && this.eq(An) ? An : this.not().add(Jc); + }; + be.neg = be.negate; + be.add = function(e) { + En(e) || (e = bs(e)); + var t = this.high >>> 16, n = this.high & 65535, o = this.low >>> 16, s = this.low & 65535, a = e.high >>> 16, i = e.high & 65535, l = e.low >>> 16, u = e.low & 65535, c = 0, p = 0, m = 0, f = 0; + return f += s + u, m += f >>> 16, f &= 65535, m += o + l, p += m >>> 16, m &= 65535, p += n + i, c += p >>> 16, p &= 65535, c += t + a, c &= 65535, Wt(m << 16 | f, c << 16 | p, this.unsigned); + }; + be.subtract = function(e) { + return En(e) || (e = bs(e)), this.add(e.neg()); + }; + be.sub = be.subtract; + be.multiply = function(e) { + if (this.isZero()) + return so; + if (En(e) || (e = bs(e)), no) { + var t = no.mul(this.low, this.high, e.low, e.high); + return Wt(t, no.get_high(), this.unsigned); } - Long2.fromInt = fromInt; - function fromNumber(value, unsigned) { - if (isNaN(value)) - return unsigned ? UZERO : ZERO; - if (unsigned) { - if (value < 0) - return UZERO; - if (value >= TWO_PWR_64_DBL) - return MAX_UNSIGNED_VALUE; - } else { - if (value <= -TWO_PWR_63_DBL) - return MIN_VALUE; - if (value + 1 >= TWO_PWR_63_DBL) - return MAX_VALUE; - } - if (value < 0) - return fromNumber(-value, unsigned).neg(); - return fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned); + if (e.isZero()) + return so; + if (this.eq(An)) + return e.isOdd() ? An : so; + if (e.eq(An)) + return this.isOdd() ? An : so; + if (this.isNegative()) + return e.isNegative() ? this.neg().mul(e.neg()) : this.neg().mul(e).neg(); + if (e.isNegative()) + return this.mul(e.neg()).neg(); + if (this.lt(n1) && e.lt(n1)) + return oo(this.toNumber() * e.toNumber(), this.unsigned); + var n = this.high >>> 16, o = this.high & 65535, s = this.low >>> 16, a = this.low & 65535, i = e.high >>> 16, l = e.high & 65535, u = e.low >>> 16, c = e.low & 65535, p = 0, m = 0, f = 0, d = 0; + return d += a * c, f += d >>> 16, d &= 65535, f += s * c, m += f >>> 16, f &= 65535, f += a * u, m += f >>> 16, f &= 65535, m += o * c, p += m >>> 16, m &= 65535, m += s * u, p += m >>> 16, m &= 65535, m += a * l, p += m >>> 16, m &= 65535, p += n * c + o * u + s * l + a * i, p &= 65535, Wt(f << 16 | d, p << 16 | m, this.unsigned); + }; + be.mul = be.multiply; + be.divide = function(e) { + if (En(e) || (e = bs(e)), e.isZero()) + throw Error("division by zero"); + if (no) { + if (!this.unsigned && this.high === -2147483648 && e.low === -1 && e.high === -1) + return this; + var t = (this.unsigned ? no.div_u : no.div_s)(this.low, this.high, e.low, e.high); + return Wt(t, no.get_high(), this.unsigned); } - Long2.fromNumber = fromNumber; - function fromBits(lowBits, highBits, unsigned) { - return new Long2(lowBits, highBits, unsigned); - } - Long2.fromBits = fromBits; - var pow_dbl = Math.pow; - function fromString(str, unsigned, radix) { - if (str.length === 0) - throw Error("empty string"); - if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity") - return ZERO; - if (typeof unsigned === "number") { - radix = unsigned, unsigned = false; - } else { - unsigned = !!unsigned; - } - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw RangeError("radix"); - var p2; - if ((p2 = str.indexOf("-")) > 0) - throw Error("interior hyphen"); - else if (p2 === 0) { - return fromString(str.substring(1), unsigned, radix).neg(); - } - var radixToPower = fromNumber(pow_dbl(radix, 8)); - var result = ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = fromNumber(pow_dbl(radix, size)); - result = result.mul(power).add(fromNumber(value)); - } else { - result = result.mul(radixToPower); - result = result.add(fromNumber(value)); - } - } - result.unsigned = unsigned; - return result; - } - Long2.fromString = fromString; - function fromValue(val, unsigned) { - if (typeof val === "number") - return fromNumber(val, unsigned); - if (typeof val === "string") - return fromString(val, unsigned); - return fromBits(val.low, val.high, typeof unsigned === "boolean" ? unsigned : val.unsigned); - } - Long2.fromValue = fromValue; - var TWO_PWR_16_DBL = 1 << 16; - var TWO_PWR_24_DBL = 1 << 24; - var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; - var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; - var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; - var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL); - var ZERO = fromInt(0); - Long2.ZERO = ZERO; - var UZERO = fromInt(0, true); - Long2.UZERO = UZERO; - var ONE = fromInt(1); - Long2.ONE = ONE; - var UONE = fromInt(1, true); - Long2.UONE = UONE; - var NEG_ONE = fromInt(-1); - Long2.NEG_ONE = NEG_ONE; - var MAX_VALUE = fromBits(4294967295 | 0, 2147483647 | 0, false); - Long2.MAX_VALUE = MAX_VALUE; - var MAX_UNSIGNED_VALUE = fromBits(4294967295 | 0, 4294967295 | 0, true); - Long2.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE; - var MIN_VALUE = fromBits(0, 2147483648 | 0, false); - Long2.MIN_VALUE = MIN_VALUE; - var LongPrototype = Long2.prototype; - LongPrototype.toInt = function toInt() { - return this.unsigned ? this.low >>> 0 : this.low; - }; - LongPrototype.toNumber = function toNumber() { - if (this.unsigned) - return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); - return this.high * TWO_PWR_32_DBL + (this.low >>> 0); - }; - LongPrototype.toString = function toString(radix) { - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw RangeError("radix"); - if (this.isZero()) - return "0"; - if (this.isNegative()) { - if (this.eq(MIN_VALUE)) { - var radixLong = fromNumber(radix), div3 = this.div(radixLong), rem1 = div3.mul(radixLong).sub(this); - return div3.toString(radix) + rem1.toInt().toString(radix); - } else - return "-" + this.neg().toString(radix); - } - var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), rem = this; - var result = ""; - while (true) { - var remDiv = rem.div(radixToPower), intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, digits = intval.toString(radix); - rem = remDiv; - if (rem.isZero()) - return digits + result; - else { - while (digits.length < 6) - digits = "0" + digits; - result = "" + digits + result; - } - } - }; - LongPrototype.getHighBits = function getHighBits() { - return this.high; - }; - LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() { - return this.high >>> 0; - }; - LongPrototype.getLowBits = function getLowBits() { - return this.low; - }; - LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() { - return this.low >>> 0; - }; - LongPrototype.getNumBitsAbs = function getNumBitsAbs() { + if (this.isZero()) + return this.unsigned ? ql : so; + var n, o, s; + if (this.unsigned) { + if (e.unsigned || (e = e.toUnsigned()), e.gt(this)) + return ql; + if (e.gt(this.shru(1))) + return o1; + s = ql; + } else { + if (this.eq(An)) { + if (e.eq(Jc) || e.eq(_w)) + return An; + if (e.eq(An)) + return Jc; + var a = this.shr(1); + return n = a.div(e).shl(1), n.eq(so) ? e.isNegative() ? Jc : _w : (o = this.sub(e.mul(n)), s = n.add(o.div(e)), s); + } else if (e.eq(An)) + return this.unsigned ? ql : so; if (this.isNegative()) - return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); - var val = this.high != 0 ? this.high : this.low; - for (var bit = 31; bit > 0; bit--) - if ((val & 1 << bit) != 0) - break; - return this.high != 0 ? bit + 33 : bit + 1; - }; - LongPrototype.isZero = function isZero() { - return this.high === 0 && this.low === 0; - }; - LongPrototype.eqz = LongPrototype.isZero; - LongPrototype.isNegative = function isNegative() { - return !this.unsigned && this.high < 0; - }; - LongPrototype.isPositive = function isPositive() { - return this.unsigned || this.high >= 0; - }; - LongPrototype.isOdd = function isOdd() { - return (this.low & 1) === 1; - }; - LongPrototype.isEven = function isEven2() { - return (this.low & 1) === 0; - }; - LongPrototype.equals = function equals(other) { - if (!isLong(other)) - other = fromValue(other); - if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) - return false; - return this.high === other.high && this.low === other.low; - }; - LongPrototype.eq = LongPrototype.equals; - LongPrototype.notEquals = function notEquals(other) { - return !this.eq(other); - }; - LongPrototype.neq = LongPrototype.notEquals; - LongPrototype.ne = LongPrototype.notEquals; - LongPrototype.lessThan = function lessThan(other) { - return this.comp(other) < 0; - }; - LongPrototype.lt = LongPrototype.lessThan; - LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) { - return this.comp(other) <= 0; - }; - LongPrototype.lte = LongPrototype.lessThanOrEqual; - LongPrototype.le = LongPrototype.lessThanOrEqual; - LongPrototype.greaterThan = function greaterThan(other) { - return this.comp(other) > 0; - }; - LongPrototype.gt = LongPrototype.greaterThan; - LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) { - return this.comp(other) >= 0; - }; - LongPrototype.gte = LongPrototype.greaterThanOrEqual; - LongPrototype.ge = LongPrototype.greaterThanOrEqual; - LongPrototype.compare = function compare(other) { - if (!isLong(other)) - other = fromValue(other); - if (this.eq(other)) - return 0; - var thisNeg = this.isNegative(), otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) - return -1; - if (!thisNeg && otherNeg) - return 1; - if (!this.unsigned) - return this.sub(other).isNegative() ? -1 : 1; - return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1; - }; - LongPrototype.comp = LongPrototype.compare; - LongPrototype.negate = function negate() { - if (!this.unsigned && this.eq(MIN_VALUE)) - return MIN_VALUE; - return this.not().add(ONE); - }; - LongPrototype.neg = LongPrototype.negate; - LongPrototype.add = function add5(addend) { - if (!isLong(addend)) - addend = fromValue(addend); - var a48 = this.high >>> 16; - var a32 = this.high & 65535; - var a16 = this.low >>> 16; - var a00 = this.low & 65535; - var b48 = addend.high >>> 16; - var b32 = addend.high & 65535; - var b16 = addend.low >>> 16; - var b00 = addend.low & 65535; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 65535; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 65535; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 65535; - c48 += a48 + b48; - c48 &= 65535; - return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); - }; - LongPrototype.subtract = function subtract(subtrahend) { - if (!isLong(subtrahend)) - subtrahend = fromValue(subtrahend); - return this.add(subtrahend.neg()); - }; - LongPrototype.sub = LongPrototype.subtract; - LongPrototype.multiply = function multiply4(multiplier) { - if (this.isZero()) - return ZERO; - if (!isLong(multiplier)) - multiplier = fromValue(multiplier); - if (wasm) { - var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); - return fromBits(low, wasm.get_high(), this.unsigned); - } - if (multiplier.isZero()) - return ZERO; - if (this.eq(MIN_VALUE)) - return multiplier.isOdd() ? MIN_VALUE : ZERO; - if (multiplier.eq(MIN_VALUE)) - return this.isOdd() ? MIN_VALUE : ZERO; - if (this.isNegative()) { - if (multiplier.isNegative()) - return this.neg().mul(multiplier.neg()); - else - return this.neg().mul(multiplier).neg(); - } else if (multiplier.isNegative()) - return this.mul(multiplier.neg()).neg(); - if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) - return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); - var a48 = this.high >>> 16; - var a32 = this.high & 65535; - var a16 = this.low >>> 16; - var a00 = this.low & 65535; - var b48 = multiplier.high >>> 16; - var b32 = multiplier.high & 65535; - var b16 = multiplier.low >>> 16; - var b00 = multiplier.low & 65535; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 65535; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 65535; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 65535; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 65535; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 65535; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 65535; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 65535; - return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); - }; - LongPrototype.mul = LongPrototype.multiply; - LongPrototype.divide = function divide(divisor) { - if (!isLong(divisor)) - divisor = fromValue(divisor); - if (divisor.isZero()) - throw Error("division by zero"); - if (wasm) { - if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) { - return this; - } - var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); - return fromBits(low, wasm.get_high(), this.unsigned); - } - if (this.isZero()) - return this.unsigned ? UZERO : ZERO; - var approx, rem, res; - if (!this.unsigned) { - if (this.eq(MIN_VALUE)) { - if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) - return MIN_VALUE; - else if (divisor.eq(MIN_VALUE)) - return ONE; - else { - var halfThis = this.shr(1); - approx = halfThis.div(divisor).shl(1); - if (approx.eq(ZERO)) { - return divisor.isNegative() ? ONE : NEG_ONE; - } else { - rem = this.sub(divisor.mul(approx)); - res = approx.add(rem.div(divisor)); - return res; - } - } - } else if (divisor.eq(MIN_VALUE)) - return this.unsigned ? UZERO : ZERO; - if (this.isNegative()) { - if (divisor.isNegative()) - return this.neg().div(divisor.neg()); - return this.neg().div(divisor).neg(); - } else if (divisor.isNegative()) - return this.div(divisor.neg()).neg(); - res = ZERO; - } else { - if (!divisor.unsigned) - divisor = divisor.toUnsigned(); - if (divisor.gt(this)) - return UZERO; - if (divisor.gt(this.shru(1))) - return UONE; - res = UZERO; - } - rem = this; - while (rem.gte(divisor)) { - approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); - var log22 = Math.ceil(Math.log(approx) / Math.LN2), delta = log22 <= 48 ? 1 : pow_dbl(2, log22 - 48), approxRes = fromNumber(approx), approxRem = approxRes.mul(divisor); - while (approxRem.isNegative() || approxRem.gt(rem)) { - approx -= delta; - approxRes = fromNumber(approx, this.unsigned); - approxRem = approxRes.mul(divisor); - } - if (approxRes.isZero()) - approxRes = ONE; - res = res.add(approxRes); - rem = rem.sub(approxRem); - } - return res; - }; - LongPrototype.div = LongPrototype.divide; - LongPrototype.modulo = function modulo(divisor) { - if (!isLong(divisor)) - divisor = fromValue(divisor); - if (wasm) { - var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); - return fromBits(low, wasm.get_high(), this.unsigned); - } - return this.sub(this.div(divisor).mul(divisor)); - }; - LongPrototype.mod = LongPrototype.modulo; - LongPrototype.rem = LongPrototype.modulo; - LongPrototype.not = function not() { - return fromBits(~this.low, ~this.high, this.unsigned); - }; - LongPrototype.and = function and(other) { - if (!isLong(other)) - other = fromValue(other); - return fromBits(this.low & other.low, this.high & other.high, this.unsigned); - }; - LongPrototype.or = function or(other) { - if (!isLong(other)) - other = fromValue(other); - return fromBits(this.low | other.low, this.high | other.high, this.unsigned); - }; - LongPrototype.xor = function xor(other) { - if (!isLong(other)) - other = fromValue(other); - return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); - }; - LongPrototype.shiftLeft = function shiftLeft(numBits) { - if (isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned); - else - return fromBits(0, this.low << numBits - 32, this.unsigned); - }; - LongPrototype.shl = LongPrototype.shiftLeft; - LongPrototype.shiftRight = function shiftRight(numBits) { - if (isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned); - else - return fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned); - }; - LongPrototype.shr = LongPrototype.shiftRight; - LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) { - if (isLong(numBits)) - numBits = numBits.toInt(); - numBits &= 63; - if (numBits === 0) - return this; - else { - var high = this.high; - if (numBits < 32) { - var low = this.low; - return fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits, this.unsigned); - } else if (numBits === 32) - return fromBits(high, 0, this.unsigned); - else - return fromBits(high >>> numBits - 32, 0, this.unsigned); - } - }; - LongPrototype.shru = LongPrototype.shiftRightUnsigned; - LongPrototype.shr_u = LongPrototype.shiftRightUnsigned; - LongPrototype.toSigned = function toSigned() { - if (!this.unsigned) - return this; - return fromBits(this.low, this.high, false); - }; - LongPrototype.toUnsigned = function toUnsigned() { - if (this.unsigned) - return this; - return fromBits(this.low, this.high, true); - }; - LongPrototype.toBytes = function toBytes(le) { - return le ? this.toBytesLE() : this.toBytesBE(); - }; - LongPrototype.toBytesLE = function toBytesLE() { - var hi = this.high, lo = this.low; - return [ - lo & 255, - lo >>> 8 & 255, - lo >>> 16 & 255, - lo >>> 24, - hi & 255, - hi >>> 8 & 255, - hi >>> 16 & 255, - hi >>> 24 - ]; - }; - LongPrototype.toBytesBE = function toBytesBE() { - var hi = this.high, lo = this.low; - return [ - hi >>> 24, - hi >>> 16 & 255, - hi >>> 8 & 255, - hi & 255, - lo >>> 24, - lo >>> 16 & 255, - lo >>> 8 & 255, - lo & 255 - ]; - }; - Long2.fromBytes = function fromBytes(bytes, unsigned, le) { - return le ? Long2.fromBytesLE(bytes, unsigned) : Long2.fromBytesBE(bytes, unsigned); - }; - Long2.fromBytesLE = function fromBytesLE(bytes, unsigned) { - return new Long2(bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24, bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24, unsigned); - }; - Long2.fromBytesBE = function fromBytesBE(bytes, unsigned) { - return new Long2(bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7], bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], unsigned); - }; - } -}); -var require_browser = __commonJS({ - "(disabled):node_modules/.pnpm/node-fetch@2.6.2/node_modules/node-fetch/browser.js"() { - } -}); -var require_alea = __commonJS({ - "node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/alea.js"(exports, module) { - (function(global2, module2, define2) { - function Alea(seed) { - var me = this, mash = Mash(); - me.next = function() { - var t = 2091639 * me.s0 + me.c * 23283064365386963e-26; - me.s0 = me.s1; - me.s1 = me.s2; - return me.s2 = t - (me.c = t | 0); - }; - me.c = 1; - me.s0 = mash(" "); - me.s1 = mash(" "); - me.s2 = mash(" "); - me.s0 -= mash(seed); - if (me.s0 < 0) { - me.s0 += 1; - } - me.s1 -= mash(seed); - if (me.s1 < 0) { - me.s1 += 1; - } - me.s2 -= mash(seed); - if (me.s2 < 0) { - me.s2 += 1; - } - mash = null; - } - function copy(f, t) { - t.c = f.c; - t.s0 = f.s0; - t.s1 = f.s1; - t.s2 = f.s2; - return t; - } - function impl(seed, opts) { - var xg = new Alea(seed), state = opts && opts.state, prng = xg.next; - prng.int32 = function() { - return xg.next() * 4294967296 | 0; - }; - prng.double = function() { - return prng() + (prng() * 2097152 | 0) * 11102230246251565e-32; - }; - prng.quick = prng; - if (state) { - if (typeof state == "object") - copy(state, xg); - prng.state = function() { - return copy(xg, {}); - }; - } - return prng; - } - function Mash() { - var n = 4022871197; - var mash = function(data) { - data = data.toString(); - for (var i = 0; i < data.length; i++) { - n += data.charCodeAt(i); - var h = 0.02519603282416938 * n; - n = h >>> 0; - h -= n; - h *= n; - n = h >>> 0; - h -= n; - n += h * 4294967296; - } - return (n >>> 0) * 23283064365386963e-26; - }; - return mash; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.alea = impl; - } - })(exports, typeof module == "object" && module, typeof define == "function" && define); - } -}); -var require_xor128 = __commonJS({ - "node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xor128.js"(exports, module) { - (function(global2, module2, define2) { - function XorGen(seed) { - var me = this, strseed = ""; - me.x = 0; - me.y = 0; - me.z = 0; - me.w = 0; - me.next = function() { - var t = me.x ^ me.x << 11; - me.x = me.y; - me.y = me.z; - me.z = me.w; - return me.w ^= me.w >>> 19 ^ t ^ t >>> 8; - }; - if (seed === (seed | 0)) { - me.x = seed; - } else { - strseed += seed; - } - for (var k = 0; k < strseed.length + 64; k++) { - me.x ^= strseed.charCodeAt(k) | 0; - me.next(); - } - } - function copy(f, t) { - t.x = f.x; - t.y = f.y; - t.z = f.z; - t.w = f.w; - return t; - } - function impl(seed, opts) { - var xg = new XorGen(seed), state = opts && opts.state, prng = function() { - return (xg.next() >>> 0) / 4294967296; - }; - prng.double = function() { - do { - var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (typeof state == "object") - copy(state, xg); - prng.state = function() { - return copy(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.xor128 = impl; - } - })(exports, typeof module == "object" && module, typeof define == "function" && define); - } -}); -var require_xorwow = __commonJS({ - "node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xorwow.js"(exports, module) { - (function(global2, module2, define2) { - function XorGen(seed) { - var me = this, strseed = ""; - me.next = function() { - var t = me.x ^ me.x >>> 2; - me.x = me.y; - me.y = me.z; - me.z = me.w; - me.w = me.v; - return (me.d = me.d + 362437 | 0) + (me.v = me.v ^ me.v << 4 ^ (t ^ t << 1)) | 0; - }; - me.x = 0; - me.y = 0; - me.z = 0; - me.w = 0; - me.v = 0; - if (seed === (seed | 0)) { - me.x = seed; - } else { - strseed += seed; - } - for (var k = 0; k < strseed.length + 64; k++) { - me.x ^= strseed.charCodeAt(k) | 0; - if (k == strseed.length) { - me.d = me.x << 10 ^ me.x >>> 4; - } - me.next(); - } - } - function copy(f, t) { - t.x = f.x; - t.y = f.y; - t.z = f.z; - t.w = f.w; - t.v = f.v; - t.d = f.d; - return t; - } - function impl(seed, opts) { - var xg = new XorGen(seed), state = opts && opts.state, prng = function() { - return (xg.next() >>> 0) / 4294967296; - }; - prng.double = function() { - do { - var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (typeof state == "object") - copy(state, xg); - prng.state = function() { - return copy(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.xorwow = impl; - } - })(exports, typeof module == "object" && module, typeof define == "function" && define); - } -}); -var require_xorshift7 = __commonJS({ - "node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xorshift7.js"(exports, module) { - (function(global2, module2, define2) { - function XorGen(seed) { - var me = this; - me.next = function() { - var X = me.x, i = me.i, t, v, w; - t = X[i]; - t ^= t >>> 7; - v = t ^ t << 24; - t = X[i + 1 & 7]; - v ^= t ^ t >>> 10; - t = X[i + 3 & 7]; - v ^= t ^ t >>> 3; - t = X[i + 4 & 7]; - v ^= t ^ t << 7; - t = X[i + 7 & 7]; - t = t ^ t << 13; - v ^= t ^ t << 9; - X[i] = v; - me.i = i + 1 & 7; - return v; - }; - function init2(me2, seed2) { - var j, w, X = []; - if (seed2 === (seed2 | 0)) { - w = X[0] = seed2; - } else { - seed2 = "" + seed2; - for (j = 0; j < seed2.length; ++j) { - X[j & 7] = X[j & 7] << 15 ^ seed2.charCodeAt(j) + X[j + 1 & 7] << 13; - } - } - while (X.length < 8) - X.push(0); - for (j = 0; j < 8 && X[j] === 0; ++j) - ; - if (j == 8) - w = X[7] = -1; - else - w = X[j]; - me2.x = X; - me2.i = 0; - for (j = 256; j > 0; --j) { - me2.next(); - } - } - init2(me, seed); - } - function copy(f, t) { - t.x = f.x.slice(); - t.i = f.i; - return t; - } - function impl(seed, opts) { - if (seed == null) - seed = +new Date(); - var xg = new XorGen(seed), state = opts && opts.state, prng = function() { - return (xg.next() >>> 0) / 4294967296; - }; - prng.double = function() { - do { - var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (state.x) - copy(state, xg); - prng.state = function() { - return copy(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.xorshift7 = impl; - } - })(exports, typeof module == "object" && module, typeof define == "function" && define); - } -}); -var require_xor4096 = __commonJS({ - "node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/xor4096.js"(exports, module) { - (function(global2, module2, define2) { - function XorGen(seed) { - var me = this; - me.next = function() { - var w = me.w, X = me.X, i = me.i, t, v; - me.w = w = w + 1640531527 | 0; - v = X[i + 34 & 127]; - t = X[i = i + 1 & 127]; - v ^= v << 13; - t ^= t << 17; - v ^= v >>> 15; - t ^= t >>> 12; - v = X[i] = v ^ t; - me.i = i; - return v + (w ^ w >>> 16) | 0; - }; - function init2(me2, seed2) { - var t, v, i, j, w, X = [], limit = 128; - if (seed2 === (seed2 | 0)) { - v = seed2; - seed2 = null; - } else { - seed2 = seed2 + "\0"; - v = 0; - limit = Math.max(limit, seed2.length); - } - for (i = 0, j = -32; j < limit; ++j) { - if (seed2) - v ^= seed2.charCodeAt((j + 32) % seed2.length); - if (j === 0) - w = v; - v ^= v << 10; - v ^= v >>> 15; - v ^= v << 4; - v ^= v >>> 13; - if (j >= 0) { - w = w + 1640531527 | 0; - t = X[j & 127] ^= v + w; - i = t == 0 ? i + 1 : 0; - } - } - if (i >= 128) { - X[(seed2 && seed2.length || 0) & 127] = -1; - } - i = 127; - for (j = 4 * 128; j > 0; --j) { - v = X[i + 34 & 127]; - t = X[i = i + 1 & 127]; - v ^= v << 13; - t ^= t << 17; - v ^= v >>> 15; - t ^= t >>> 12; - X[i] = v ^ t; - } - me2.w = w; - me2.X = X; - me2.i = i; - } - init2(me, seed); - } - function copy(f, t) { - t.i = f.i; - t.w = f.w; - t.X = f.X.slice(); - return t; - } - ; - function impl(seed, opts) { - if (seed == null) - seed = +new Date(); - var xg = new XorGen(seed), state = opts && opts.state, prng = function() { - return (xg.next() >>> 0) / 4294967296; - }; - prng.double = function() { - do { - var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (state.X) - copy(state, xg); - prng.state = function() { - return copy(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.xor4096 = impl; - } - })(exports, typeof module == "object" && module, typeof define == "function" && define); - } -}); -var require_tychei = __commonJS({ - "node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/lib/tychei.js"(exports, module) { - (function(global2, module2, define2) { - function XorGen(seed) { - var me = this, strseed = ""; - me.next = function() { - var b = me.b, c = me.c, d = me.d, a = me.a; - b = b << 25 ^ b >>> 7 ^ c; - c = c - d | 0; - d = d << 24 ^ d >>> 8 ^ a; - a = a - b | 0; - me.b = b = b << 20 ^ b >>> 12 ^ c; - me.c = c = c - d | 0; - me.d = d << 16 ^ c >>> 16 ^ a; - return me.a = a - b | 0; - }; - me.a = 0; - me.b = 0; - me.c = 2654435769 | 0; - me.d = 1367130551; - if (seed === Math.floor(seed)) { - me.a = seed / 4294967296 | 0; - me.b = seed | 0; - } else { - strseed += seed; - } - for (var k = 0; k < strseed.length + 20; k++) { - me.b ^= strseed.charCodeAt(k) | 0; - me.next(); - } - } - function copy(f, t) { - t.a = f.a; - t.b = f.b; - t.c = f.c; - t.d = f.d; - return t; - } - ; - function impl(seed, opts) { - var xg = new XorGen(seed), state = opts && opts.state, prng = function() { - return (xg.next() >>> 0) / 4294967296; - }; - prng.double = function() { - do { - var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (typeof state == "object") - copy(state, xg); - prng.state = function() { - return copy(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.tychei = impl; - } - })(exports, typeof module == "object" && module, typeof define == "function" && define); - } -}); -var require_crypto = __commonJS({ - "(disabled):crypto"() { - } -}); -var require_seedrandom = __commonJS({ - "node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/seedrandom.js"(exports, module) { - (function(pool3, math) { - var global2 = this, width = 256, chunks = 6, digits = 52, rngname = "random", startdenom = math.pow(width, chunks), significance = math.pow(2, digits), overflow = significance * 2, mask = width - 1, nodecrypto; - function seedrandom5(seed, options3, callback) { - var key = []; - options3 = options3 == true ? { entropy: true } : options3 || {}; - var shortseed = mixkey(flatten4(options3.entropy ? [seed, tostring(pool3)] : seed == null ? autoseed() : seed, 3), key); - var arc4 = new ARC4(key); - var prng = function() { - var n = arc4.g(chunks), d = startdenom, x = 0; - while (n < significance) { - n = (n + x) * width; - d *= width; - x = arc4.g(1); - } - while (n >= overflow) { - n /= 2; - d /= 2; - x >>>= 1; - } - return (n + x) / d; - }; - prng.int32 = function() { - return arc4.g(4) | 0; - }; - prng.quick = function() { - return arc4.g(4) / 4294967296; - }; - prng.double = prng; - mixkey(tostring(arc4.S), pool3); - return (options3.pass || callback || function(prng2, seed2, is_math_call, state) { - if (state) { - if (state.S) { - copy(state, arc4); - } - prng2.state = function() { - return copy(arc4, {}); - }; - } - if (is_math_call) { - math[rngname] = prng2; - return seed2; - } else - return prng2; - })(prng, shortseed, "global" in options3 ? options3.global : this == math, options3.state); - } - math["seed" + rngname] = seedrandom5; - function ARC4(key) { - var t, keylen = key.length, me = this, i = 0, j = me.i = me.j = 0, s = me.S = []; - if (!keylen) { - key = [keylen++]; - } - while (i < width) { - s[i] = i++; - } - for (i = 0; i < width; i++) { - s[i] = s[j = mask & j + key[i % keylen] + (t = s[i])]; - s[j] = t; - } - (me.g = function(count22) { - var t2, r = 0, i2 = me.i, j2 = me.j, s2 = me.S; - while (count22--) { - t2 = s2[i2 = mask & i2 + 1]; - r = r * width + s2[mask & (s2[i2] = s2[j2 = mask & j2 + t2]) + (s2[j2] = t2)]; - } - me.i = i2; - me.j = j2; - return r; - })(width); - } - function copy(f, t) { - t.i = f.i; - t.j = f.j; - t.S = f.S.slice(); - return t; - } - ; - function flatten4(obj, depth) { - var result = [], typ = typeof obj, prop; - if (depth && typ == "object") { - for (prop in obj) { - try { - result.push(flatten4(obj[prop], depth - 1)); - } catch (e) { - } - } - } - return result.length ? result : typ == "string" ? obj : obj + "\0"; - } - function mixkey(seed, key) { - var stringseed = seed + "", smear, j = 0; - while (j < stringseed.length) { - key[mask & j] = mask & (smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++); - } - return tostring(key); - } - function autoseed() { - try { - var out; - if (nodecrypto && (out = nodecrypto.randomBytes)) { - out = out(width); - } else { - out = new Uint8Array(width); - (global2.crypto || global2.msCrypto).getRandomValues(out); - } - return tostring(out); - } catch (e) { - var browser = global2.navigator, plugins = browser && browser.plugins; - return [+new Date(), global2, plugins, global2.screen, tostring(pool3)]; - } - } - function tostring(a) { - return String.fromCharCode.apply(0, a); - } - mixkey(math.random(), pool3); - if (typeof module == "object" && module.exports) { - module.exports = seedrandom5; - try { - nodecrypto = require_crypto(); - } catch (ex) { - } - } else if (typeof define == "function" && define.amd) { - define(function() { - return seedrandom5; - }); - } - })([], Math); - } -}); -var require_seedrandom2 = __commonJS({ - "node_modules/.pnpm/seedrandom@2.4.3/node_modules/seedrandom/index.js"(exports, module) { - var alea5 = require_alea(); - var xor128 = require_xor128(); - var xorwow = require_xorwow(); - var xorshift7 = require_xorshift7(); - var xor4096 = require_xor4096(); - var tychei = require_tychei(); - var sr = require_seedrandom(); - sr.alea = alea5; - sr.xor128 = xor128; - sr.xorwow = xorwow; - sr.xorshift7 = xorshift7; - sr.xor4096 = xor4096; - sr.tychei = tychei; - module.exports = sr; - } -}); -var require_alea2 = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/alea.js"(exports, module) { - (function(global2, module2, define2) { - function Alea(seed) { - var me = this, mash = Mash(); - me.next = function() { - var t = 2091639 * me.s0 + me.c * 23283064365386963e-26; - me.s0 = me.s1; - me.s1 = me.s2; - return me.s2 = t - (me.c = t | 0); - }; - me.c = 1; - me.s0 = mash(" "); - me.s1 = mash(" "); - me.s2 = mash(" "); - me.s0 -= mash(seed); - if (me.s0 < 0) { - me.s0 += 1; - } - me.s1 -= mash(seed); - if (me.s1 < 0) { - me.s1 += 1; - } - me.s2 -= mash(seed); - if (me.s2 < 0) { - me.s2 += 1; - } - mash = null; - } - function copy(f, t) { - t.c = f.c; - t.s0 = f.s0; - t.s1 = f.s1; - t.s2 = f.s2; - return t; - } - function impl(seed, opts) { - var xg = new Alea(seed), state = opts && opts.state, prng = xg.next; - prng.int32 = function() { - return xg.next() * 4294967296 | 0; - }; - prng.double = function() { - return prng() + (prng() * 2097152 | 0) * 11102230246251565e-32; - }; - prng.quick = prng; - if (state) { - if (typeof state == "object") - copy(state, xg); - prng.state = function() { - return copy(xg, {}); - }; - } - return prng; - } - function Mash() { - var n = 4022871197; - var mash = function(data) { - data = String(data); - for (var i = 0; i < data.length; i++) { - n += data.charCodeAt(i); - var h = 0.02519603282416938 * n; - n = h >>> 0; - h -= n; - h *= n; - n = h >>> 0; - h -= n; - n += h * 4294967296; - } - return (n >>> 0) * 23283064365386963e-26; - }; - return mash; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.alea = impl; - } - })(exports, typeof module == "object" && module, typeof define == "function" && define); - } -}); -var require_xor1282 = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js"(exports, module) { - (function(global2, module2, define2) { - function XorGen(seed) { - var me = this, strseed = ""; - me.x = 0; - me.y = 0; - me.z = 0; - me.w = 0; - me.next = function() { - var t = me.x ^ me.x << 11; - me.x = me.y; - me.y = me.z; - me.z = me.w; - return me.w ^= me.w >>> 19 ^ t ^ t >>> 8; - }; - if (seed === (seed | 0)) { - me.x = seed; - } else { - strseed += seed; - } - for (var k = 0; k < strseed.length + 64; k++) { - me.x ^= strseed.charCodeAt(k) | 0; - me.next(); - } - } - function copy(f, t) { - t.x = f.x; - t.y = f.y; - t.z = f.z; - t.w = f.w; - return t; - } - function impl(seed, opts) { - var xg = new XorGen(seed), state = opts && opts.state, prng = function() { - return (xg.next() >>> 0) / 4294967296; - }; - prng.double = function() { - do { - var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (typeof state == "object") - copy(state, xg); - prng.state = function() { - return copy(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.xor128 = impl; - } - })(exports, typeof module == "object" && module, typeof define == "function" && define); - } -}); -var require_xorwow2 = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js"(exports, module) { - (function(global2, module2, define2) { - function XorGen(seed) { - var me = this, strseed = ""; - me.next = function() { - var t = me.x ^ me.x >>> 2; - me.x = me.y; - me.y = me.z; - me.z = me.w; - me.w = me.v; - return (me.d = me.d + 362437 | 0) + (me.v = me.v ^ me.v << 4 ^ (t ^ t << 1)) | 0; - }; - me.x = 0; - me.y = 0; - me.z = 0; - me.w = 0; - me.v = 0; - if (seed === (seed | 0)) { - me.x = seed; - } else { - strseed += seed; - } - for (var k = 0; k < strseed.length + 64; k++) { - me.x ^= strseed.charCodeAt(k) | 0; - if (k == strseed.length) { - me.d = me.x << 10 ^ me.x >>> 4; - } - me.next(); - } - } - function copy(f, t) { - t.x = f.x; - t.y = f.y; - t.z = f.z; - t.w = f.w; - t.v = f.v; - t.d = f.d; - return t; - } - function impl(seed, opts) { - var xg = new XorGen(seed), state = opts && opts.state, prng = function() { - return (xg.next() >>> 0) / 4294967296; - }; - prng.double = function() { - do { - var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (typeof state == "object") - copy(state, xg); - prng.state = function() { - return copy(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.xorwow = impl; - } - })(exports, typeof module == "object" && module, typeof define == "function" && define); - } -}); -var require_xorshift72 = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js"(exports, module) { - (function(global2, module2, define2) { - function XorGen(seed) { - var me = this; - me.next = function() { - var X = me.x, i = me.i, t, v, w; - t = X[i]; - t ^= t >>> 7; - v = t ^ t << 24; - t = X[i + 1 & 7]; - v ^= t ^ t >>> 10; - t = X[i + 3 & 7]; - v ^= t ^ t >>> 3; - t = X[i + 4 & 7]; - v ^= t ^ t << 7; - t = X[i + 7 & 7]; - t = t ^ t << 13; - v ^= t ^ t << 9; - X[i] = v; - me.i = i + 1 & 7; - return v; - }; - function init2(me2, seed2) { - var j, w, X = []; - if (seed2 === (seed2 | 0)) { - w = X[0] = seed2; - } else { - seed2 = "" + seed2; - for (j = 0; j < seed2.length; ++j) { - X[j & 7] = X[j & 7] << 15 ^ seed2.charCodeAt(j) + X[j + 1 & 7] << 13; - } - } - while (X.length < 8) - X.push(0); - for (j = 0; j < 8 && X[j] === 0; ++j) - ; - if (j == 8) - w = X[7] = -1; - else - w = X[j]; - me2.x = X; - me2.i = 0; - for (j = 256; j > 0; --j) { - me2.next(); - } - } - init2(me, seed); - } - function copy(f, t) { - t.x = f.x.slice(); - t.i = f.i; - return t; - } - function impl(seed, opts) { - if (seed == null) - seed = +new Date(); - var xg = new XorGen(seed), state = opts && opts.state, prng = function() { - return (xg.next() >>> 0) / 4294967296; - }; - prng.double = function() { - do { - var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (state.x) - copy(state, xg); - prng.state = function() { - return copy(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.xorshift7 = impl; - } - })(exports, typeof module == "object" && module, typeof define == "function" && define); - } -}); -var require_xor40962 = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js"(exports, module) { - (function(global2, module2, define2) { - function XorGen(seed) { - var me = this; - me.next = function() { - var w = me.w, X = me.X, i = me.i, t, v; - me.w = w = w + 1640531527 | 0; - v = X[i + 34 & 127]; - t = X[i = i + 1 & 127]; - v ^= v << 13; - t ^= t << 17; - v ^= v >>> 15; - t ^= t >>> 12; - v = X[i] = v ^ t; - me.i = i; - return v + (w ^ w >>> 16) | 0; - }; - function init2(me2, seed2) { - var t, v, i, j, w, X = [], limit = 128; - if (seed2 === (seed2 | 0)) { - v = seed2; - seed2 = null; - } else { - seed2 = seed2 + "\0"; - v = 0; - limit = Math.max(limit, seed2.length); - } - for (i = 0, j = -32; j < limit; ++j) { - if (seed2) - v ^= seed2.charCodeAt((j + 32) % seed2.length); - if (j === 0) - w = v; - v ^= v << 10; - v ^= v >>> 15; - v ^= v << 4; - v ^= v >>> 13; - if (j >= 0) { - w = w + 1640531527 | 0; - t = X[j & 127] ^= v + w; - i = t == 0 ? i + 1 : 0; - } - } - if (i >= 128) { - X[(seed2 && seed2.length || 0) & 127] = -1; - } - i = 127; - for (j = 4 * 128; j > 0; --j) { - v = X[i + 34 & 127]; - t = X[i = i + 1 & 127]; - v ^= v << 13; - t ^= t << 17; - v ^= v >>> 15; - t ^= t >>> 12; - X[i] = v ^ t; - } - me2.w = w; - me2.X = X; - me2.i = i; - } - init2(me, seed); - } - function copy(f, t) { - t.i = f.i; - t.w = f.w; - t.X = f.X.slice(); - return t; - } - ; - function impl(seed, opts) { - if (seed == null) - seed = +new Date(); - var xg = new XorGen(seed), state = opts && opts.state, prng = function() { - return (xg.next() >>> 0) / 4294967296; - }; - prng.double = function() { - do { - var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (state.X) - copy(state, xg); - prng.state = function() { - return copy(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.xor4096 = impl; - } - })(exports, typeof module == "object" && module, typeof define == "function" && define); - } -}); -var require_tychei2 = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js"(exports, module) { - (function(global2, module2, define2) { - function XorGen(seed) { - var me = this, strseed = ""; - me.next = function() { - var b = me.b, c = me.c, d = me.d, a = me.a; - b = b << 25 ^ b >>> 7 ^ c; - c = c - d | 0; - d = d << 24 ^ d >>> 8 ^ a; - a = a - b | 0; - me.b = b = b << 20 ^ b >>> 12 ^ c; - me.c = c = c - d | 0; - me.d = d << 16 ^ c >>> 16 ^ a; - return me.a = a - b | 0; - }; - me.a = 0; - me.b = 0; - me.c = 2654435769 | 0; - me.d = 1367130551; - if (seed === Math.floor(seed)) { - me.a = seed / 4294967296 | 0; - me.b = seed | 0; - } else { - strseed += seed; - } - for (var k = 0; k < strseed.length + 20; k++) { - me.b ^= strseed.charCodeAt(k) | 0; - me.next(); - } - } - function copy(f, t) { - t.a = f.a; - t.b = f.b; - t.c = f.c; - t.d = f.d; - return t; - } - ; - function impl(seed, opts) { - var xg = new XorGen(seed), state = opts && opts.state, prng = function() { - return (xg.next() >>> 0) / 4294967296; - }; - prng.double = function() { - do { - var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (typeof state == "object") - copy(state, xg); - prng.state = function() { - return copy(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.tychei = impl; - } - })(exports, typeof module == "object" && module, typeof define == "function" && define); - } -}); -var require_seedrandom3 = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/seedrandom.js"(exports, module) { - (function(global2, pool3, math) { - var width = 256, chunks = 6, digits = 52, rngname = "random", startdenom = math.pow(width, chunks), significance = math.pow(2, digits), overflow = significance * 2, mask = width - 1, nodecrypto; - function seedrandom5(seed, options3, callback) { - var key = []; - options3 = options3 == true ? { entropy: true } : options3 || {}; - var shortseed = mixkey(flatten4(options3.entropy ? [seed, tostring(pool3)] : seed == null ? autoseed() : seed, 3), key); - var arc4 = new ARC4(key); - var prng = function() { - var n = arc4.g(chunks), d = startdenom, x = 0; - while (n < significance) { - n = (n + x) * width; - d *= width; - x = arc4.g(1); - } - while (n >= overflow) { - n /= 2; - d /= 2; - x >>>= 1; - } - return (n + x) / d; - }; - prng.int32 = function() { - return arc4.g(4) | 0; - }; - prng.quick = function() { - return arc4.g(4) / 4294967296; - }; - prng.double = prng; - mixkey(tostring(arc4.S), pool3); - return (options3.pass || callback || function(prng2, seed2, is_math_call, state) { - if (state) { - if (state.S) { - copy(state, arc4); - } - prng2.state = function() { - return copy(arc4, {}); - }; - } - if (is_math_call) { - math[rngname] = prng2; - return seed2; - } else - return prng2; - })(prng, shortseed, "global" in options3 ? options3.global : this == math, options3.state); - } - function ARC4(key) { - var t, keylen = key.length, me = this, i = 0, j = me.i = me.j = 0, s = me.S = []; - if (!keylen) { - key = [keylen++]; - } - while (i < width) { - s[i] = i++; - } - for (i = 0; i < width; i++) { - s[i] = s[j = mask & j + key[i % keylen] + (t = s[i])]; - s[j] = t; - } - (me.g = function(count22) { - var t2, r = 0, i2 = me.i, j2 = me.j, s2 = me.S; - while (count22--) { - t2 = s2[i2 = mask & i2 + 1]; - r = r * width + s2[mask & (s2[i2] = s2[j2 = mask & j2 + t2]) + (s2[j2] = t2)]; - } - me.i = i2; - me.j = j2; - return r; - })(width); - } - function copy(f, t) { - t.i = f.i; - t.j = f.j; - t.S = f.S.slice(); - return t; - } - ; - function flatten4(obj, depth) { - var result = [], typ = typeof obj, prop; - if (depth && typ == "object") { - for (prop in obj) { - try { - result.push(flatten4(obj[prop], depth - 1)); - } catch (e) { - } - } - } - return result.length ? result : typ == "string" ? obj : obj + "\0"; - } - function mixkey(seed, key) { - var stringseed = seed + "", smear, j = 0; - while (j < stringseed.length) { - key[mask & j] = mask & (smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++); - } - return tostring(key); - } - function autoseed() { - try { - var out; - if (nodecrypto && (out = nodecrypto.randomBytes)) { - out = out(width); - } else { - out = new Uint8Array(width); - (global2.crypto || global2.msCrypto).getRandomValues(out); - } - return tostring(out); - } catch (e) { - var browser = global2.navigator, plugins = browser && browser.plugins; - return [+new Date(), global2, plugins, global2.screen, tostring(pool3)]; - } - } - function tostring(a) { - return String.fromCharCode.apply(0, a); - } - mixkey(math.random(), pool3); - if (typeof module == "object" && module.exports) { - module.exports = seedrandom5; - try { - nodecrypto = require_crypto(); - } catch (ex) { - } - } else if (typeof define == "function" && define.amd) { - define(function() { - return seedrandom5; - }); - } else { - math["seed" + rngname] = seedrandom5; - } - })(typeof self !== "undefined" ? self : exports, [], Math); - } -}); -var require_seedrandom4 = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/index.js"(exports, module) { - var alea5 = require_alea2(); - var xor128 = require_xor1282(); - var xorwow = require_xorwow2(); - var xorshift7 = require_xorshift72(); - var xor4096 = require_xor40962(); - var tychei = require_tychei2(); - var sr = require_seedrandom3(); - sr.alea = alea5; - sr.xor128 = xor128; - sr.xorwow = xorwow; - sr.xorshift7 = xorshift7; - sr.xor4096 = xor4096; - sr.tychei = tychei; - module.exports = sr; - } -}); -var require_string_decoder = __commonJS({ - "(disabled):node_modules/.pnpm/string_decoder@1.1.1/node_modules/string_decoder/lib/string_decoder.js"() { - } -}); -var require_path = __commonJS({ - "(disabled):path"() { - } -}); -var require_worker_threads = __commonJS({ - "(disabled):worker_threads"() { - } -}); -var require_perf_hooks = __commonJS({ - "(disabled):perf_hooks"() { - } -}); -var require_tfjs_backend_wasm_threaded_simd = __commonJS({ - "node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.9.0_@tensorflow+tfjs-core@3.9.0/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm-threaded-simd.js"(exports, module) { - var WasmBackendModuleThreadedSimd = function() { - var _scriptDir = typeof document !== "undefined" && document.currentScript ? document.currentScript.src : void 0; - if (typeof __filename !== "undefined") - _scriptDir = _scriptDir || __filename; - return function(WasmBackendModuleThreadedSimd2) { - WasmBackendModuleThreadedSimd2 = WasmBackendModuleThreadedSimd2 || {}; - function GROWABLE_HEAP_I8() { - if (wasmMemory.buffer != buffer2) { - updateGlobalBufferAndViews(wasmMemory.buffer); - } - return HEAP8; - } - function GROWABLE_HEAP_U8() { - if (wasmMemory.buffer != buffer2) { - updateGlobalBufferAndViews(wasmMemory.buffer); - } - return HEAPU8; - } - function GROWABLE_HEAP_I32() { - if (wasmMemory.buffer != buffer2) { - updateGlobalBufferAndViews(wasmMemory.buffer); - } - return HEAP32; - } - function GROWABLE_HEAP_U32() { - if (wasmMemory.buffer != buffer2) { - updateGlobalBufferAndViews(wasmMemory.buffer); - } - return HEAPU32; - } - function GROWABLE_HEAP_F64() { - if (wasmMemory.buffer != buffer2) { - updateGlobalBufferAndViews(wasmMemory.buffer); - } - return HEAPF64; - } - var Module = typeof WasmBackendModuleThreadedSimd2 !== "undefined" ? WasmBackendModuleThreadedSimd2 : {}; - var readyPromiseResolve, readyPromiseReject; - Module["ready"] = new Promise(function(resolve, reject) { - readyPromiseResolve = resolve; - readyPromiseReject = reject; - }); - var moduleOverrides = {}; - var key; - for (key in Module) { - if (Module.hasOwnProperty(key)) { - moduleOverrides[key] = Module[key]; - } - } - var arguments_ = []; - var thisProgram = "./this.program"; - var quit_ = function(status, toThrow) { - throw toThrow; - }; - var ENVIRONMENT_IS_WEB = false; - var ENVIRONMENT_IS_WORKER = false; - var ENVIRONMENT_IS_NODE = false; - var ENVIRONMENT_IS_SHELL = false; - ENVIRONMENT_IS_WEB = typeof window === "object"; - ENVIRONMENT_IS_WORKER = typeof importScripts === "function"; - ENVIRONMENT_IS_NODE = typeof process === "object" && typeof process.versions === "object" && typeof process.versions.node === "string"; - ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER; - var ENVIRONMENT_IS_PTHREAD = Module["ENVIRONMENT_IS_PTHREAD"] || false; - if (ENVIRONMENT_IS_PTHREAD) { - buffer2 = Module["buffer"]; - } - var scriptDirectory = ""; - function locateFile(path) { - if (Module["locateFile"]) { - return Module["locateFile"](path, scriptDirectory); - } - return scriptDirectory + path; - } - var read_, readAsync, readBinary, setWindowTitle; - var nodeFS; - var nodePath; - if (ENVIRONMENT_IS_NODE) { - if (ENVIRONMENT_IS_WORKER) { - scriptDirectory = require_path().dirname(scriptDirectory) + "/"; - } else { - scriptDirectory = __dirname + "/"; - } - read_ = function shell_read(filename, binary) { - if (!nodeFS) - nodeFS = __require2("fs"); - if (!nodePath) - nodePath = require_path(); - filename = nodePath["normalize"](filename); - return nodeFS["readFileSync"](filename, binary ? null : "utf8"); - }; - readBinary = function readBinary2(filename) { - var ret = read_(filename, true); - if (!ret.buffer) { - ret = new Uint8Array(ret); - } - assert3(ret.buffer); - return ret; - }; - if (process["argv"].length > 1) { - thisProgram = process["argv"][1].replace(/\\/g, "/"); - } - arguments_ = process["argv"].slice(2); - process["on"]("uncaughtException", function(ex) { - if (!(ex instanceof ExitStatus)) { - throw ex; - } - }); - process["on"]("unhandledRejection", abort); - quit_ = function(status) { - process["exit"](status); - }; - Module["inspect"] = function() { - return "[Emscripten Module object]"; - }; - var nodeWorkerThreads; - try { - nodeWorkerThreads = require_worker_threads(); - } catch (e) { - console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'); - throw e; - } - global.Worker = nodeWorkerThreads.Worker; - } else if (ENVIRONMENT_IS_SHELL) { - if (typeof read != "undefined") { - read_ = function shell_read(f) { - return read(f); - }; - } - readBinary = function readBinary2(f) { - var data; - if (typeof readbuffer === "function") { - return new Uint8Array(readbuffer(f)); - } - data = read(f, "binary"); - assert3(typeof data === "object"); - return data; - }; - if (typeof scriptArgs != "undefined") { - arguments_ = scriptArgs; - } else if (typeof arguments != "undefined") { - arguments_ = arguments; - } - if (typeof quit === "function") { - quit_ = function(status) { - quit(status); - }; - } - if (typeof print !== "undefined") { - if (typeof console === "undefined") - console = {}; - console.log = print; - console.warn = console.error = typeof printErr !== "undefined" ? printErr : print; - } - } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { - if (ENVIRONMENT_IS_WORKER) { - scriptDirectory = self.location.href; - } else if (typeof document !== "undefined" && document.currentScript) { - scriptDirectory = document.currentScript.src; - } - if (typeof _scriptDir !== "undefined" && _scriptDir) { - scriptDirectory = _scriptDir; - } - if (scriptDirectory.indexOf("blob:") !== 0) { - scriptDirectory = scriptDirectory.substr(0, scriptDirectory.lastIndexOf("/") + 1); - } else { - scriptDirectory = ""; - } - if (ENVIRONMENT_IS_NODE) { - read_ = function shell_read(filename, binary) { - if (!nodeFS) - nodeFS = __require2("fs"); - if (!nodePath) - nodePath = require_path(); - filename = nodePath["normalize"](filename); - return nodeFS["readFileSync"](filename, binary ? null : "utf8"); - }; - readBinary = function readBinary2(filename) { - var ret = read_(filename, true); - if (!ret.buffer) { - ret = new Uint8Array(ret); - } - assert3(ret.buffer); - return ret; - }; - } else { - read_ = function(url) { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, false); - xhr.send(null); - return xhr.responseText; - }; - if (ENVIRONMENT_IS_WORKER) { - readBinary = function(url) { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, false); - xhr.responseType = "arraybuffer"; - xhr.send(null); - return new Uint8Array(xhr.response); - }; - } - readAsync = function(url, onload, onerror) { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, true); - xhr.responseType = "arraybuffer"; - xhr.onload = function() { - if (xhr.status == 200 || xhr.status == 0 && xhr.response) { - onload(xhr.response); - return; - } - onerror(); - }; - xhr.onerror = onerror; - xhr.send(null); - }; - } - setWindowTitle = function(title) { - document.title = title; - }; - } else { - } - if (ENVIRONMENT_IS_NODE) { - if (typeof performance === "undefined") { - global.performance = require_perf_hooks().performance; - } - } - var out = Module["print"] || console.log.bind(console); - var err = Module["printErr"] || console.warn.bind(console); - for (key in moduleOverrides) { - if (moduleOverrides.hasOwnProperty(key)) { - Module[key] = moduleOverrides[key]; - } - } - moduleOverrides = null; - if (Module["arguments"]) - arguments_ = Module["arguments"]; - if (Module["thisProgram"]) - thisProgram = Module["thisProgram"]; - if (Module["quit"]) - quit_ = Module["quit"]; - var Atomics_load = Atomics.load; - var Atomics_store = Atomics.store; - var Atomics_compareExchange = Atomics.compareExchange; - var wasmBinary; - if (Module["wasmBinary"]) - wasmBinary = Module["wasmBinary"]; - var noExitRuntime = Module["noExitRuntime"] || true; - if (typeof WebAssembly !== "object") { - abort("no native wasm support detected"); - } - var wasmMemory; - var wasmModule; - var ABORT = false; - var EXITSTATUS; - function assert3(condition, text) { - if (!condition) { - abort("Assertion failed: " + text); - } - } - function getCFunc(ident) { - var func2 = Module["_" + ident]; - assert3(func2, "Cannot call unknown function " + ident + ", make sure it is exported"); - return func2; - } - function ccall(ident, returnType, argTypes, args, opts) { - var toC = { "string": function(str) { - var ret2 = 0; - if (str !== null && str !== void 0 && str !== 0) { - var len = (str.length << 2) + 1; - ret2 = stackAlloc(len); - stringToUTF8(str, ret2, len); - } - return ret2; - }, "array": function(arr) { - var ret2 = stackAlloc(arr.length); - writeArrayToMemory(arr, ret2); - return ret2; - } }; - function convertReturnValue(ret2) { - if (returnType === "string") - return UTF8ToString(ret2); - if (returnType === "boolean") - return Boolean(ret2); - return ret2; - } - var func2 = getCFunc(ident); - var cArgs = []; - var stack2 = 0; - if (args) { - for (var i = 0; i < args.length; i++) { - var converter = toC[argTypes[i]]; - if (converter) { - if (stack2 === 0) - stack2 = stackSave(); - cArgs[i] = converter(args[i]); - } else { - cArgs[i] = args[i]; - } - } - } - var ret = func2.apply(null, cArgs); - ret = convertReturnValue(ret); - if (stack2 !== 0) - stackRestore(stack2); - return ret; - } - function cwrap(ident, returnType, argTypes, opts) { - argTypes = argTypes || []; - var numericArgs = argTypes.every(function(type) { - return type === "number"; - }); - var numericRet = returnType !== "string"; - if (numericRet && numericArgs && !opts) { - return getCFunc(ident); - } - return function() { - return ccall(ident, returnType, argTypes, arguments, opts); - }; - } - function UTF8ArrayToString(heap, idx, maxBytesToRead) { - var endIdx = idx + maxBytesToRead; - var str = ""; - while (!(idx >= endIdx)) { - var u0 = heap[idx++]; - if (!u0) - return str; - if (!(u0 & 128)) { - str += String.fromCharCode(u0); - continue; - } - var u1 = heap[idx++] & 63; - if ((u0 & 224) == 192) { - str += String.fromCharCode((u0 & 31) << 6 | u1); - continue; - } - var u2 = heap[idx++] & 63; - if ((u0 & 240) == 224) { - u0 = (u0 & 15) << 12 | u1 << 6 | u2; - } else { - u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heap[idx++] & 63; - } - if (u0 < 65536) { - str += String.fromCharCode(u0); - } else { - var ch = u0 - 65536; - str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023); - } - } - return str; - } - function UTF8ToString(ptr, maxBytesToRead) { - return ptr ? UTF8ArrayToString(GROWABLE_HEAP_U8(), ptr, maxBytesToRead) : ""; - } - function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) { - if (!(maxBytesToWrite > 0)) - return 0; - var startIdx = outIdx; - var endIdx = outIdx + maxBytesToWrite - 1; - for (var i = 0; i < str.length; ++i) { - var u = str.charCodeAt(i); - if (u >= 55296 && u <= 57343) { - var u1 = str.charCodeAt(++i); - u = 65536 + ((u & 1023) << 10) | u1 & 1023; - } - if (u <= 127) { - if (outIdx >= endIdx) - break; - heap[outIdx++] = u; - } else if (u <= 2047) { - if (outIdx + 1 >= endIdx) - break; - heap[outIdx++] = 192 | u >> 6; - heap[outIdx++] = 128 | u & 63; - } else if (u <= 65535) { - if (outIdx + 2 >= endIdx) - break; - heap[outIdx++] = 224 | u >> 12; - heap[outIdx++] = 128 | u >> 6 & 63; - heap[outIdx++] = 128 | u & 63; - } else { - if (outIdx + 3 >= endIdx) - break; - heap[outIdx++] = 240 | u >> 18; - heap[outIdx++] = 128 | u >> 12 & 63; - heap[outIdx++] = 128 | u >> 6 & 63; - heap[outIdx++] = 128 | u & 63; - } - } - heap[outIdx] = 0; - return outIdx - startIdx; - } - function stringToUTF8(str, outPtr, maxBytesToWrite) { - return stringToUTF8Array(str, GROWABLE_HEAP_U8(), outPtr, maxBytesToWrite); - } - function lengthBytesUTF8(str) { - var len = 0; - for (var i = 0; i < str.length; ++i) { - var u = str.charCodeAt(i); - if (u >= 55296 && u <= 57343) - u = 65536 + ((u & 1023) << 10) | str.charCodeAt(++i) & 1023; - if (u <= 127) - ++len; - else if (u <= 2047) - len += 2; - else if (u <= 65535) - len += 3; - else - len += 4; - } - return len; - } - function writeArrayToMemory(array2, buffer3) { - GROWABLE_HEAP_I8().set(array2, buffer3); - } - function alignUp(x, multiple) { - if (x % multiple > 0) { - x += multiple - x % multiple; - } - return x; - } - var buffer2, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64; - function updateGlobalBufferAndViews(buf) { - buffer2 = buf; - Module["HEAP8"] = HEAP8 = new Int8Array(buf); - Module["HEAP16"] = HEAP16 = new Int16Array(buf); - Module["HEAP32"] = HEAP32 = new Int32Array(buf); - Module["HEAPU8"] = HEAPU8 = new Uint8Array(buf); - Module["HEAPU16"] = HEAPU16 = new Uint16Array(buf); - Module["HEAPU32"] = HEAPU32 = new Uint32Array(buf); - Module["HEAPF32"] = HEAPF32 = new Float32Array(buf); - Module["HEAPF64"] = HEAPF64 = new Float64Array(buf); - } - var INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 16777216; - if (ENVIRONMENT_IS_PTHREAD) { - wasmMemory = Module["wasmMemory"]; - buffer2 = Module["buffer"]; - } else { - if (Module["wasmMemory"]) { - wasmMemory = Module["wasmMemory"]; - } else { - wasmMemory = new WebAssembly.Memory({ "initial": INITIAL_MEMORY / 65536, "maximum": 2147483648 / 65536, "shared": true }); - if (!(wasmMemory.buffer instanceof SharedArrayBuffer)) { - err("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"); - if (ENVIRONMENT_IS_NODE) { - console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"); - } - throw Error("bad memory"); - } - } - } - if (wasmMemory) { - buffer2 = wasmMemory.buffer; - } - INITIAL_MEMORY = buffer2.byteLength; - updateGlobalBufferAndViews(buffer2); - var wasmTable; - var __ATPRERUN__ = []; - var __ATINIT__ = []; - var __ATMAIN__ = []; - var __ATEXIT__ = []; - var __ATPOSTRUN__ = []; - var runtimeInitialized = false; - var runtimeExited = false; - if (!ENVIRONMENT_IS_PTHREAD) - __ATINIT__.push({ func: function() { - ___wasm_call_ctors(); - } }); - function preRun() { - if (ENVIRONMENT_IS_PTHREAD) - return; - if (Module["preRun"]) { - if (typeof Module["preRun"] == "function") - Module["preRun"] = [Module["preRun"]]; - while (Module["preRun"].length) { - addOnPreRun(Module["preRun"].shift()); - } - } - callRuntimeCallbacks(__ATPRERUN__); - } - function initRuntime() { - runtimeInitialized = true; - if (ENVIRONMENT_IS_PTHREAD) - return; - callRuntimeCallbacks(__ATINIT__); - } - function preMain() { - if (ENVIRONMENT_IS_PTHREAD) - return; - callRuntimeCallbacks(__ATMAIN__); - } - function exitRuntime() { - if (ENVIRONMENT_IS_PTHREAD) - return; - runtimeExited = true; - } - function postRun() { - if (ENVIRONMENT_IS_PTHREAD) - return; - if (Module["postRun"]) { - if (typeof Module["postRun"] == "function") - Module["postRun"] = [Module["postRun"]]; - while (Module["postRun"].length) { - addOnPostRun(Module["postRun"].shift()); - } - } - callRuntimeCallbacks(__ATPOSTRUN__); - } - function addOnPreRun(cb) { - __ATPRERUN__.unshift(cb); - } - function addOnPostRun(cb) { - __ATPOSTRUN__.unshift(cb); - } - var runDependencies = 0; - var runDependencyWatcher = null; - var dependenciesFulfilled = null; - function addRunDependency(id) { - assert3(!ENVIRONMENT_IS_PTHREAD, "addRunDependency cannot be used in a pthread worker"); - runDependencies++; - if (Module["monitorRunDependencies"]) { - Module["monitorRunDependencies"](runDependencies); - } - } - function removeRunDependency(id) { - runDependencies--; - if (Module["monitorRunDependencies"]) { - Module["monitorRunDependencies"](runDependencies); - } - if (runDependencies == 0) { - if (runDependencyWatcher !== null) { - clearInterval(runDependencyWatcher); - runDependencyWatcher = null; - } - if (dependenciesFulfilled) { - var callback = dependenciesFulfilled; - dependenciesFulfilled = null; - callback(); - } - } - } - Module["preloadedImages"] = {}; - Module["preloadedAudios"] = {}; - function abort(what) { - if (Module["onAbort"]) { - Module["onAbort"](what); - } - if (ENVIRONMENT_IS_PTHREAD) - console.error("Pthread aborting at " + new Error().stack); - what += ""; - err(what); - ABORT = true; - EXITSTATUS = 1; - what = "abort(" + what + "). Build with -s ASSERTIONS=1 for more info."; - var e = new WebAssembly.RuntimeError(what); - readyPromiseReject(e); - throw e; - } - function hasPrefix(str, prefix) { - return String.prototype.startsWith ? str.startsWith(prefix) : str.indexOf(prefix) === 0; - } - var dataURIPrefix = "data:application/octet-stream;base64,"; - function isDataURI(filename) { - return hasPrefix(filename, dataURIPrefix); - } - var fileURIPrefix = "file://"; - function isFileURI(filename) { - return hasPrefix(filename, fileURIPrefix); - } - var wasmBinaryFile = "tfjs-backend-wasm-threaded-simd.wasm"; - if (!isDataURI(wasmBinaryFile)) { - wasmBinaryFile = locateFile(wasmBinaryFile); - } - function getBinary(file) { - try { - if (file == wasmBinaryFile && wasmBinary) { - return new Uint8Array(wasmBinary); - } - if (readBinary) { - return readBinary(file); - } else { - throw "both async and sync fetching of the wasm failed"; - } - } catch (err2) { - abort(err2); - } - } - function getBinaryPromise() { - if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) { - if (typeof fetch === "function" && !isFileURI(wasmBinaryFile)) { - return fetch(wasmBinaryFile, { credentials: "same-origin" }).then(function(response) { - if (!response["ok"]) { - throw "failed to load wasm binary file at '" + wasmBinaryFile + "'"; - } - return response["arrayBuffer"](); - }).catch(function() { - return getBinary(wasmBinaryFile); - }); - } else { - if (readAsync) { - return new Promise(function(resolve, reject) { - readAsync(wasmBinaryFile, function(response) { - resolve(new Uint8Array(response)); - }, reject); - }); - } - } - } - return Promise.resolve().then(function() { - return getBinary(wasmBinaryFile); - }); - } - function createWasm() { - var info2 = { "a": asmLibraryArg }; - function receiveInstance(instance, module2) { - var exports3 = instance.exports; - Module["asm"] = exports3; - wasmTable = Module["asm"]["F"]; - wasmModule = module2; - if (!ENVIRONMENT_IS_PTHREAD) { - var numWorkersToLoad = PThread.unusedWorkers.length; - PThread.unusedWorkers.forEach(function(w) { - PThread.loadWasmModuleToWorker(w, function() { - if (!--numWorkersToLoad) - removeRunDependency("wasm-instantiate"); - }); - }); - } - } - if (!ENVIRONMENT_IS_PTHREAD) { - addRunDependency("wasm-instantiate"); - } - function receiveInstantiatedSource(output) { - receiveInstance(output["instance"], output["module"]); - } - function instantiateArrayBuffer(receiver) { - return getBinaryPromise().then(function(binary) { - return WebAssembly.instantiate(binary, info2); - }).then(receiver, function(reason) { - err("failed to asynchronously prepare wasm: " + reason); - abort(reason); - }); - } - function instantiateAsync() { - if (!wasmBinary && typeof WebAssembly.instantiateStreaming === "function" && !isDataURI(wasmBinaryFile) && !isFileURI(wasmBinaryFile) && typeof fetch === "function") { - return fetch(wasmBinaryFile, { credentials: "same-origin" }).then(function(response) { - var result = WebAssembly.instantiateStreaming(response, info2); - return result.then(receiveInstantiatedSource, function(reason) { - err("wasm streaming compile failed: " + reason); - err("falling back to ArrayBuffer instantiation"); - return instantiateArrayBuffer(receiveInstantiatedSource); - }); - }); - } else { - return instantiateArrayBuffer(receiveInstantiatedSource); - } - } - if (Module["instantiateWasm"]) { - try { - var exports2 = Module["instantiateWasm"](info2, receiveInstance); - return exports2; - } catch (e) { - err("Module.instantiateWasm callback failed with error: " + e); - return false; - } - } - instantiateAsync().catch(readyPromiseReject); - return {}; - } - var ASM_CONSTS = { 10024: function() { - throw "Canceled!"; - }, 10042: function($0, $1) { - setTimeout(function() { - __emscripten_do_dispatch_to_thread($0, $1); - }, 0); - } }; - function initPthreadsJS() { - PThread.initRuntime(); - } - function callRuntimeCallbacks(callbacks2) { - while (callbacks2.length > 0) { - var callback = callbacks2.shift(); - if (typeof callback == "function") { - callback(Module); - continue; - } - var func2 = callback.func; - if (typeof func2 === "number") { - if (callback.arg === void 0) { - wasmTable.get(func2)(); - } else { - wasmTable.get(func2)(callback.arg); - } - } else { - func2(callback.arg === void 0 ? null : callback.arg); - } - } - } - function _emscripten_futex_wake(addr, count22) { - if (addr <= 0 || addr > GROWABLE_HEAP_I8().length || addr & true || count22 < 0) - return -28; - if (count22 == 0) - return 0; - if (count22 >= 2147483647) - count22 = Infinity; - var mainThreadWaitAddress = Atomics.load(GROWABLE_HEAP_I32(), __emscripten_main_thread_futex >> 2); - var mainThreadWoken = 0; - if (mainThreadWaitAddress == addr) { - var loadedAddr = Atomics.compareExchange(GROWABLE_HEAP_I32(), __emscripten_main_thread_futex >> 2, mainThreadWaitAddress, 0); - if (loadedAddr == mainThreadWaitAddress) { - --count22; - mainThreadWoken = 1; - if (count22 <= 0) - return 1; - } - } - var ret = Atomics.notify(GROWABLE_HEAP_I32(), addr >> 2, count22); - if (ret >= 0) - return ret + mainThreadWoken; - throw "Atomics.notify returned an unexpected value " + ret; - } - Module["_emscripten_futex_wake"] = _emscripten_futex_wake; - function killThread(pthread_ptr) { - if (ENVIRONMENT_IS_PTHREAD) - throw "Internal Error! killThread() can only ever be called from main application thread!"; - if (!pthread_ptr) - throw "Internal Error! Null pthread_ptr in killThread!"; - GROWABLE_HEAP_I32()[pthread_ptr + 12 >> 2] = 0; - var pthread = PThread.pthreads[pthread_ptr]; - pthread.worker.terminate(); - PThread.freeThreadData(pthread); - PThread.runningWorkers.splice(PThread.runningWorkers.indexOf(pthread.worker), 1); - pthread.worker.pthread = void 0; - } - function cancelThread(pthread_ptr) { - if (ENVIRONMENT_IS_PTHREAD) - throw "Internal Error! cancelThread() can only ever be called from main application thread!"; - if (!pthread_ptr) - throw "Internal Error! Null pthread_ptr in cancelThread!"; - var pthread = PThread.pthreads[pthread_ptr]; - pthread.worker.postMessage({ "cmd": "cancel" }); - } - function cleanupThread(pthread_ptr) { - if (ENVIRONMENT_IS_PTHREAD) - throw "Internal Error! cleanupThread() can only ever be called from main application thread!"; - if (!pthread_ptr) - throw "Internal Error! Null pthread_ptr in cleanupThread!"; - var pthread = PThread.pthreads[pthread_ptr]; - if (pthread) { - GROWABLE_HEAP_I32()[pthread_ptr + 12 >> 2] = 0; - var worker = pthread.worker; - PThread.returnWorkerToPool(worker); - } - } - var PThread = { unusedWorkers: [], runningWorkers: [], initMainThreadBlock: function() { - var pthreadPoolSize = Math.min(4, Math.max(1, (navigator.hardwareConcurrency || 1) / 2)); - for (var i = 0; i < pthreadPoolSize; ++i) { - PThread.allocateUnusedWorker(); - } - }, initRuntime: function() { - var tb = _malloc(228); - for (var i = 0; i < 228 / 4; ++i) - GROWABLE_HEAP_U32()[tb / 4 + i] = 0; - GROWABLE_HEAP_I32()[tb + 12 >> 2] = tb; - var headPtr = tb + 152; - GROWABLE_HEAP_I32()[headPtr >> 2] = headPtr; - var tlsMemory = _malloc(512); - for (var i = 0; i < 128; ++i) - GROWABLE_HEAP_U32()[tlsMemory / 4 + i] = 0; - Atomics.store(GROWABLE_HEAP_U32(), tb + 100 >> 2, tlsMemory); - Atomics.store(GROWABLE_HEAP_U32(), tb + 40 >> 2, tb); - __emscripten_thread_init(tb, !ENVIRONMENT_IS_WORKER, 1); - _emscripten_register_main_browser_thread_id(tb); - }, initWorker: function() { - }, pthreads: {}, threadExitHandlers: [], setThreadStatus: function() { - }, runExitHandlers: function() { - while (PThread.threadExitHandlers.length > 0) { - PThread.threadExitHandlers.pop()(); - } - if (ENVIRONMENT_IS_PTHREAD && _pthread_self()) - ___pthread_tsd_run_dtors(); - }, runExitHandlersAndDeinitThread: function(tb, exitCode) { - Atomics.store(GROWABLE_HEAP_U32(), tb + 56 >> 2, 1); - Atomics.store(GROWABLE_HEAP_U32(), tb + 60 >> 2, 0); - PThread.runExitHandlers(); - Atomics.store(GROWABLE_HEAP_U32(), tb + 4 >> 2, exitCode); - Atomics.store(GROWABLE_HEAP_U32(), tb + 0 >> 2, 1); - _emscripten_futex_wake(tb + 0, 2147483647); - __emscripten_thread_init(0, 0, 0); - }, threadExit: function(exitCode) { - var tb = _pthread_self(); - if (tb) { - PThread.runExitHandlersAndDeinitThread(tb, exitCode); - if (ENVIRONMENT_IS_PTHREAD) { - postMessage({ "cmd": "exit" }); - } - } - }, threadCancel: function() { - PThread.runExitHandlersAndDeinitThread(_pthread_self(), -1); - postMessage({ "cmd": "cancelDone" }); - }, terminateAllThreads: function() { - for (var t in PThread.pthreads) { - var pthread = PThread.pthreads[t]; - if (pthread && pthread.worker) { - PThread.returnWorkerToPool(pthread.worker); - } - } - PThread.pthreads = {}; - for (var i = 0; i < PThread.unusedWorkers.length; ++i) { - var worker = PThread.unusedWorkers[i]; - worker.terminate(); - } - PThread.unusedWorkers = []; - for (var i = 0; i < PThread.runningWorkers.length; ++i) { - var worker = PThread.runningWorkers[i]; - var pthread = worker.pthread; - PThread.freeThreadData(pthread); - worker.terminate(); - } - PThread.runningWorkers = []; - }, freeThreadData: function(pthread) { - if (!pthread) - return; - if (pthread.threadInfoStruct) { - var tlsMemory = GROWABLE_HEAP_I32()[pthread.threadInfoStruct + 100 >> 2]; - GROWABLE_HEAP_I32()[pthread.threadInfoStruct + 100 >> 2] = 0; - _free(tlsMemory); - _free(pthread.threadInfoStruct); - } - pthread.threadInfoStruct = 0; - if (pthread.allocatedOwnStack && pthread.stackBase) - _free(pthread.stackBase); - pthread.stackBase = 0; - if (pthread.worker) - pthread.worker.pthread = null; - }, returnWorkerToPool: function(worker) { - PThread.runWithoutMainThreadQueuedCalls(function() { - delete PThread.pthreads[worker.pthread.threadInfoStruct]; - PThread.unusedWorkers.push(worker); - PThread.runningWorkers.splice(PThread.runningWorkers.indexOf(worker), 1); - PThread.freeThreadData(worker.pthread); - worker.pthread = void 0; - }); - }, runWithoutMainThreadQueuedCalls: function(func2) { - GROWABLE_HEAP_I32()[__emscripten_allow_main_runtime_queued_calls >> 2] = 0; - try { - func2(); - } finally { - GROWABLE_HEAP_I32()[__emscripten_allow_main_runtime_queued_calls >> 2] = 1; - } - }, receiveObjectTransfer: function(data) { - }, loadWasmModuleToWorker: function(worker, onFinishedLoading) { - worker.onmessage = function(e) { - var d = e["data"]; - var cmd = d["cmd"]; - if (worker.pthread) - PThread.currentProxiedOperationCallerThread = worker.pthread.threadInfoStruct; - if (d["targetThread"] && d["targetThread"] != _pthread_self()) { - var thread = PThread.pthreads[d.targetThread]; - if (thread) { - thread.worker.postMessage(e.data, d["transferList"]); - } else { - console.error('Internal error! Worker sent a message "' + cmd + '" to target pthread ' + d["targetThread"] + ", but that thread no longer exists!"); - } - PThread.currentProxiedOperationCallerThread = void 0; - return; - } - if (cmd === "processQueuedMainThreadWork") { - _emscripten_main_thread_process_queued_calls(); - } else if (cmd === "spawnThread") { - spawnThread(e.data); - } else if (cmd === "cleanupThread") { - cleanupThread(d["thread"]); - } else if (cmd === "killThread") { - killThread(d["thread"]); - } else if (cmd === "cancelThread") { - cancelThread(d["thread"]); - } else if (cmd === "loaded") { - worker.loaded = true; - if (onFinishedLoading) - onFinishedLoading(worker); - if (worker.runPthread) { - worker.runPthread(); - delete worker.runPthread; - } - } else if (cmd === "print") { - out("Thread " + d["threadId"] + ": " + d["text"]); - } else if (cmd === "printErr") { - err("Thread " + d["threadId"] + ": " + d["text"]); - } else if (cmd === "alert") { - alert("Thread " + d["threadId"] + ": " + d["text"]); - } else if (cmd === "exit") { - var detached = worker.pthread && Atomics.load(GROWABLE_HEAP_U32(), worker.pthread.threadInfoStruct + 64 >> 2); - if (detached) { - PThread.returnWorkerToPool(worker); - } - } else if (cmd === "exitProcess") { - try { - exit(d["returnCode"]); - } catch (e2) { - if (e2 instanceof ExitStatus) - return; - throw e2; - } - } else if (cmd === "cancelDone") { - PThread.returnWorkerToPool(worker); - } else if (cmd === "objectTransfer") { - PThread.receiveObjectTransfer(e.data); - } else if (e.data.target === "setimmediate") { - worker.postMessage(e.data); - } else { - err("worker sent an unknown command " + cmd); - } - PThread.currentProxiedOperationCallerThread = void 0; - }; - worker.onerror = function(e) { - err("pthread sent an error! " + e.filename + ":" + e.lineno + ": " + e.message); - }; - if (ENVIRONMENT_IS_NODE) { - worker.on("message", function(data) { - worker.onmessage({ data }); - }); - worker.on("error", function(data) { - worker.onerror(data); - }); - worker.on("exit", function(data) { - }); - } - worker.postMessage({ "cmd": "load", "urlOrBlob": Module["mainScriptUrlOrBlob"] || _scriptDir, "wasmMemory": wasmMemory, "wasmModule": wasmModule }); - }, allocateUnusedWorker: function() { - var pthreadMainJs = locateFile("tfjs-backend-wasm-threaded-simd.worker.js"); - PThread.unusedWorkers.push(new Worker(pthreadMainJs)); - }, getNewWorker: function() { - if (PThread.unusedWorkers.length == 0) { - PThread.allocateUnusedWorker(); - PThread.loadWasmModuleToWorker(PThread.unusedWorkers[0]); - } - if (PThread.unusedWorkers.length > 0) - return PThread.unusedWorkers.pop(); - else - return null; - }, busySpinWait: function(msecs) { - var t = performance.now() + msecs; - while (performance.now() < t) { - } - } }; - function establishStackSpace(stackTop, stackMax) { - _emscripten_stack_set_limits(stackTop, stackMax); - stackRestore(stackTop); - } - Module["establishStackSpace"] = establishStackSpace; - function getNoExitRuntime() { - return noExitRuntime; - } - Module["getNoExitRuntime"] = getNoExitRuntime; - function invokeEntryPoint(ptr, arg) { - return wasmTable.get(ptr)(arg); - } - Module["invokeEntryPoint"] = invokeEntryPoint; - function ___assert_fail(condition, filename, line, func2) { - abort("Assertion failed: " + UTF8ToString(condition) + ", at: " + [filename ? UTF8ToString(filename) : "unknown filename", line, func2 ? UTF8ToString(func2) : "unknown function"]); - } - function ___call_main(argc, argv) { - var returnCode = _main(argc, argv); - } - var _emscripten_get_now; - if (ENVIRONMENT_IS_NODE) { - _emscripten_get_now = function() { - var t = process["hrtime"](); - return t[0] * 1e3 + t[1] / 1e6; - }; - } else if (ENVIRONMENT_IS_PTHREAD) { - _emscripten_get_now = function() { - return performance.now() - Module["__performance_now_clock_drift"]; - }; - } else if (typeof dateNow !== "undefined") { - _emscripten_get_now = dateNow; - } else - _emscripten_get_now = function() { - return performance.now(); - }; - function setErrNo(value) { - GROWABLE_HEAP_I32()[___errno_location() >> 2] = value; - return value; - } - function _atexit(func2, arg) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(1, 1, func2, arg); - } - function __emscripten_notify_thread_queue(targetThreadId, mainThreadId) { - if (targetThreadId == mainThreadId) { - postMessage({ "cmd": "processQueuedMainThreadWork" }); - } else if (ENVIRONMENT_IS_PTHREAD) { - postMessage({ "targetThread": targetThreadId, "cmd": "processThreadQueue" }); - } else { - var pthread = PThread.pthreads[targetThreadId]; - var worker = pthread && pthread.worker; - if (!worker) { - return; - } - worker.postMessage({ "cmd": "processThreadQueue" }); - } - return 1; - } - function _abort() { - abort(); - } - function _emscripten_asm_const_int(code, sigPtr, argbuf) { - var args = readAsmConstArgs(sigPtr, argbuf); - return ASM_CONSTS[code].apply(null, args); - } - function _emscripten_conditional_set_current_thread_status(expectedStatus, newStatus) { - } - function _emscripten_futex_wait(addr, val, timeout) { - if (addr <= 0 || addr > GROWABLE_HEAP_I8().length || addr & true) - return -28; - if (!ENVIRONMENT_IS_WEB) { - var ret = Atomics.wait(GROWABLE_HEAP_I32(), addr >> 2, val, timeout); - if (ret === "timed-out") - return -73; - if (ret === "not-equal") - return -6; - if (ret === "ok") - return 0; - throw "Atomics.wait returned an unexpected value " + ret; - } else { - if (Atomics.load(GROWABLE_HEAP_I32(), addr >> 2) != val) { - return -6; - } - var tNow = performance.now(); - var tEnd = tNow + timeout; - var lastAddr = Atomics.exchange(GROWABLE_HEAP_I32(), __emscripten_main_thread_futex >> 2, addr); - while (1) { - tNow = performance.now(); - if (tNow > tEnd) { - lastAddr = Atomics.exchange(GROWABLE_HEAP_I32(), __emscripten_main_thread_futex >> 2, 0); - return -73; - } - lastAddr = Atomics.exchange(GROWABLE_HEAP_I32(), __emscripten_main_thread_futex >> 2, 0); - if (lastAddr == 0) { - break; - } - _emscripten_main_thread_process_queued_calls(); - if (Atomics.load(GROWABLE_HEAP_I32(), addr >> 2) != val) { - return -6; - } - lastAddr = Atomics.exchange(GROWABLE_HEAP_I32(), __emscripten_main_thread_futex >> 2, addr); - } - return 0; - } - } - function _emscripten_memcpy_big(dest, src, num) { - GROWABLE_HEAP_U8().copyWithin(dest, src, src + num); - } - function _emscripten_num_logical_cores() { - if (ENVIRONMENT_IS_NODE) - return __require2("os").cpus().length; - return navigator["hardwareConcurrency"]; - } - function _emscripten_proxy_to_main_thread_js(index, sync) { - var numCallArgs = arguments.length - 2; - var stack2 = stackSave(); - var serializedNumCallArgs = numCallArgs; - var args = stackAlloc(serializedNumCallArgs * 8); - var b = args >> 3; - for (var i = 0; i < numCallArgs; i++) { - var arg = arguments[2 + i]; - GROWABLE_HEAP_F64()[b + i] = arg; - } - var ret = _emscripten_run_in_main_runtime_thread_js(index, serializedNumCallArgs, args, sync); - stackRestore(stack2); - return ret; - } - var _emscripten_receive_on_main_thread_js_callArgs = []; - var readAsmConstArgsArray = []; - function readAsmConstArgs(sigPtr, buf) { - readAsmConstArgsArray.length = 0; - var ch; - buf >>= 2; - while (ch = GROWABLE_HEAP_U8()[sigPtr++]) { - var double = ch < 105; - if (double && buf & 1) - buf++; - readAsmConstArgsArray.push(double ? GROWABLE_HEAP_F64()[buf++ >> 1] : GROWABLE_HEAP_I32()[buf]); - ++buf; - } - return readAsmConstArgsArray; - } - function _emscripten_receive_on_main_thread_js(index, numCallArgs, args) { - _emscripten_receive_on_main_thread_js_callArgs.length = numCallArgs; - var b = args >> 3; - for (var i = 0; i < numCallArgs; i++) { - _emscripten_receive_on_main_thread_js_callArgs[i] = GROWABLE_HEAP_F64()[b + i]; - } - var isEmAsmConst = index < 0; - var func2 = !isEmAsmConst ? proxiedFunctionTable[index] : ASM_CONSTS[-index - 1]; - return func2.apply(null, _emscripten_receive_on_main_thread_js_callArgs); - } - function _emscripten_get_heap_size() { - return GROWABLE_HEAP_U8().length; - } - function emscripten_realloc_buffer(size) { - try { - wasmMemory.grow(size - buffer2.byteLength + 65535 >>> 16); - updateGlobalBufferAndViews(wasmMemory.buffer); - return 1; - } catch (e) { - } - } - function _emscripten_resize_heap(requestedSize) { - var oldSize = _emscripten_get_heap_size(); - if (requestedSize <= oldSize) { - return false; - } - var maxHeapSize = 2147483648; - if (requestedSize > maxHeapSize) { - return false; - } - for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { - var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown); - overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296); - var newSize = Math.min(maxHeapSize, alignUp(Math.max(requestedSize, overGrownHeapSize), 65536)); - var replacement = emscripten_realloc_buffer(newSize); - if (replacement) { - return true; - } - } - return false; - } - var JSEvents = { inEventHandler: 0, removeAllEventListeners: function() { - for (var i = JSEvents.eventHandlers.length - 1; i >= 0; --i) { - JSEvents._removeHandler(i); - } - JSEvents.eventHandlers = []; - JSEvents.deferredCalls = []; - }, registerRemoveEventListeners: function() { - if (!JSEvents.removeEventListenersRegistered) { - __ATEXIT__.push(JSEvents.removeAllEventListeners); - JSEvents.removeEventListenersRegistered = true; - } - }, deferredCalls: [], deferCall: function(targetFunction, precedence, argsList) { - function arraysHaveEqualContent(arrA, arrB) { - if (arrA.length != arrB.length) - return false; - for (var i2 in arrA) { - if (arrA[i2] != arrB[i2]) - return false; - } - return true; - } - for (var i in JSEvents.deferredCalls) { - var call = JSEvents.deferredCalls[i]; - if (call.targetFunction == targetFunction && arraysHaveEqualContent(call.argsList, argsList)) { - return; - } - } - JSEvents.deferredCalls.push({ targetFunction, precedence, argsList }); - JSEvents.deferredCalls.sort(function(x, y) { - return x.precedence < y.precedence; - }); - }, removeDeferredCalls: function(targetFunction) { - for (var i = 0; i < JSEvents.deferredCalls.length; ++i) { - if (JSEvents.deferredCalls[i].targetFunction == targetFunction) { - JSEvents.deferredCalls.splice(i, 1); - --i; - } - } - }, canPerformEventHandlerRequests: function() { - return JSEvents.inEventHandler && JSEvents.currentEventHandler.allowsDeferredCalls; - }, runDeferredCalls: function() { - if (!JSEvents.canPerformEventHandlerRequests()) { - return; - } - for (var i = 0; i < JSEvents.deferredCalls.length; ++i) { - var call = JSEvents.deferredCalls[i]; - JSEvents.deferredCalls.splice(i, 1); - --i; - call.targetFunction.apply(null, call.argsList); - } - }, eventHandlers: [], removeAllHandlersOnTarget: function(target, eventTypeString) { - for (var i = 0; i < JSEvents.eventHandlers.length; ++i) { - if (JSEvents.eventHandlers[i].target == target && (!eventTypeString || eventTypeString == JSEvents.eventHandlers[i].eventTypeString)) { - JSEvents._removeHandler(i--); - } - } - }, _removeHandler: function(i) { - var h = JSEvents.eventHandlers[i]; - h.target.removeEventListener(h.eventTypeString, h.eventListenerFunc, h.useCapture); - JSEvents.eventHandlers.splice(i, 1); - }, registerOrRemoveHandler: function(eventHandler) { - var jsEventHandler = function jsEventHandler2(event) { - ++JSEvents.inEventHandler; - JSEvents.currentEventHandler = eventHandler; - JSEvents.runDeferredCalls(); - eventHandler.handlerFunc(event); - JSEvents.runDeferredCalls(); - --JSEvents.inEventHandler; - }; - if (eventHandler.callbackfunc) { - eventHandler.eventListenerFunc = jsEventHandler; - eventHandler.target.addEventListener(eventHandler.eventTypeString, jsEventHandler, eventHandler.useCapture); - JSEvents.eventHandlers.push(eventHandler); - JSEvents.registerRemoveEventListeners(); - } else { - for (var i = 0; i < JSEvents.eventHandlers.length; ++i) { - if (JSEvents.eventHandlers[i].target == eventHandler.target && JSEvents.eventHandlers[i].eventTypeString == eventHandler.eventTypeString) { - JSEvents._removeHandler(i--); - } - } - } - }, queueEventHandlerOnThread_iiii: function(targetThread, eventHandlerFunc, eventTypeId, eventData, userData) { - var stackTop = stackSave(); - var varargs = stackAlloc(12); - GROWABLE_HEAP_I32()[varargs >> 2] = eventTypeId; - GROWABLE_HEAP_I32()[varargs + 4 >> 2] = eventData; - GROWABLE_HEAP_I32()[varargs + 8 >> 2] = userData; - __emscripten_call_on_thread(0, targetThread, 637534208, eventHandlerFunc, eventData, varargs); - stackRestore(stackTop); - }, getTargetThreadForEventCallback: function(targetThread) { - switch (targetThread) { - case 1: - return 0; - case 2: - return PThread.currentProxiedOperationCallerThread; - default: - return targetThread; - } - }, getNodeNameForTarget: function(target) { - if (!target) - return ""; - if (target == window) - return "#window"; - if (target == screen) - return "#screen"; - return target && target.nodeName ? target.nodeName : ""; - }, fullscreenEnabled: function() { - return document.fullscreenEnabled || document.webkitFullscreenEnabled; - } }; - function stringToNewUTF8(jsString) { - var length = lengthBytesUTF8(jsString) + 1; - var cString = _malloc(length); - stringToUTF8(jsString, cString, length); - return cString; - } - function _emscripten_set_offscreencanvas_size_on_target_thread_js(targetThread, targetCanvas, width, height) { - var stackTop = stackSave(); - var varargs = stackAlloc(12); - var targetCanvasPtr = 0; - if (targetCanvas) { - targetCanvasPtr = stringToNewUTF8(targetCanvas); - } - GROWABLE_HEAP_I32()[varargs >> 2] = targetCanvasPtr; - GROWABLE_HEAP_I32()[varargs + 4 >> 2] = width; - GROWABLE_HEAP_I32()[varargs + 8 >> 2] = height; - __emscripten_call_on_thread(0, targetThread, 657457152, 0, targetCanvasPtr, varargs); - stackRestore(stackTop); - } - function _emscripten_set_offscreencanvas_size_on_target_thread(targetThread, targetCanvas, width, height) { - targetCanvas = targetCanvas ? UTF8ToString(targetCanvas) : ""; - _emscripten_set_offscreencanvas_size_on_target_thread_js(targetThread, targetCanvas, width, height); - } - function maybeCStringToJsString(cString) { - return cString > 2 ? UTF8ToString(cString) : cString; - } - var specialHTMLTargets = [0, typeof document !== "undefined" ? document : 0, typeof window !== "undefined" ? window : 0]; - function findEventTarget(target) { - target = maybeCStringToJsString(target); - var domElement = specialHTMLTargets[target] || (typeof document !== "undefined" ? document.querySelector(target) : void 0); - return domElement; - } - function findCanvasEventTarget(target) { - return findEventTarget(target); - } - function _emscripten_set_canvas_element_size_calling_thread(target, width, height) { - var canvas2 = findCanvasEventTarget(target); - if (!canvas2) - return -4; - if (canvas2.canvasSharedPtr) { - GROWABLE_HEAP_I32()[canvas2.canvasSharedPtr >> 2] = width; - GROWABLE_HEAP_I32()[canvas2.canvasSharedPtr + 4 >> 2] = height; - } - if (canvas2.offscreenCanvas || !canvas2.controlTransferredOffscreen) { - if (canvas2.offscreenCanvas) - canvas2 = canvas2.offscreenCanvas; - var autoResizeViewport = false; - if (canvas2.GLctxObject && canvas2.GLctxObject.GLctx) { - var prevViewport = canvas2.GLctxObject.GLctx.getParameter(2978); - autoResizeViewport = prevViewport[0] === 0 && prevViewport[1] === 0 && prevViewport[2] === canvas2.width && prevViewport[3] === canvas2.height; - } - canvas2.width = width; - canvas2.height = height; - if (autoResizeViewport) { - canvas2.GLctxObject.GLctx.viewport(0, 0, width, height); - } - } else if (canvas2.canvasSharedPtr) { - var targetThread = GROWABLE_HEAP_I32()[canvas2.canvasSharedPtr + 8 >> 2]; - _emscripten_set_offscreencanvas_size_on_target_thread(targetThread, target, width, height); - return 1; - } else { - return -4; - } - return 0; - } - function _emscripten_set_canvas_element_size_main_thread(target, width, height) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(2, 1, target, width, height); - return _emscripten_set_canvas_element_size_calling_thread(target, width, height); - } - function _emscripten_set_canvas_element_size(target, width, height) { - var canvas2 = findCanvasEventTarget(target); - if (canvas2) { - return _emscripten_set_canvas_element_size_calling_thread(target, width, height); - } else { - return _emscripten_set_canvas_element_size_main_thread(target, width, height); - } - } - function _emscripten_set_current_thread_status(newStatus) { - } - function _emscripten_set_thread_name(threadId, name) { - } - function __webgl_enable_ANGLE_instanced_arrays(ctx) { - var ext = ctx.getExtension("ANGLE_instanced_arrays"); - if (ext) { - ctx["vertexAttribDivisor"] = function(index, divisor) { - ext["vertexAttribDivisorANGLE"](index, divisor); - }; - ctx["drawArraysInstanced"] = function(mode, first, count22, primcount) { - ext["drawArraysInstancedANGLE"](mode, first, count22, primcount); - }; - ctx["drawElementsInstanced"] = function(mode, count22, type, indices, primcount) { - ext["drawElementsInstancedANGLE"](mode, count22, type, indices, primcount); - }; - return 1; - } - } - function __webgl_enable_OES_vertex_array_object(ctx) { - var ext = ctx.getExtension("OES_vertex_array_object"); - if (ext) { - ctx["createVertexArray"] = function() { - return ext["createVertexArrayOES"](); - }; - ctx["deleteVertexArray"] = function(vao) { - ext["deleteVertexArrayOES"](vao); - }; - ctx["bindVertexArray"] = function(vao) { - ext["bindVertexArrayOES"](vao); - }; - ctx["isVertexArray"] = function(vao) { - return ext["isVertexArrayOES"](vao); - }; - return 1; - } - } - function __webgl_enable_WEBGL_draw_buffers(ctx) { - var ext = ctx.getExtension("WEBGL_draw_buffers"); - if (ext) { - ctx["drawBuffers"] = function(n, bufs) { - ext["drawBuffersWEBGL"](n, bufs); - }; - return 1; - } - } - function __webgl_enable_WEBGL_multi_draw(ctx) { - return !!(ctx.multiDrawWebgl = ctx.getExtension("WEBGL_multi_draw")); - } - var GL = { counter: 1, buffers: [], programs: [], framebuffers: [], renderbuffers: [], textures: [], uniforms: [], shaders: [], vaos: [], contexts: {}, offscreenCanvases: {}, timerQueriesEXT: [], programInfos: {}, stringCache: {}, unpackAlignment: 4, recordError: function recordError(errorCode) { - if (!GL.lastError) { - GL.lastError = errorCode; - } - }, getNewId: function(table) { - var ret = GL.counter++; - for (var i = table.length; i < ret; i++) { - table[i] = null; - } - return ret; - }, getSource: function(shader, count22, string3, length) { - var source = ""; - for (var i = 0; i < count22; ++i) { - var len = length ? GROWABLE_HEAP_I32()[length + i * 4 >> 2] : -1; - source += UTF8ToString(GROWABLE_HEAP_I32()[string3 + i * 4 >> 2], len < 0 ? void 0 : len); - } - return source; - }, createContext: function(canvas2, webGLContextAttributes) { - var ctx = canvas2.getContext("webgl", webGLContextAttributes); - if (!ctx) - return 0; - var handle = GL.registerContext(ctx, webGLContextAttributes); - return handle; - }, registerContext: function(ctx, webGLContextAttributes) { - var handle = _malloc(8); - GROWABLE_HEAP_I32()[handle + 4 >> 2] = _pthread_self(); - var context = { handle, attributes: webGLContextAttributes, version: webGLContextAttributes.majorVersion, GLctx: ctx }; - if (ctx.canvas) - ctx.canvas.GLctxObject = context; - GL.contexts[handle] = context; - if (typeof webGLContextAttributes.enableExtensionsByDefault === "undefined" || webGLContextAttributes.enableExtensionsByDefault) { - GL.initExtensions(context); - } - return handle; - }, makeContextCurrent: function(contextHandle) { - GL.currentContext = GL.contexts[contextHandle]; - Module.ctx = GLctx = GL.currentContext && GL.currentContext.GLctx; - return !(contextHandle && !GLctx); - }, getContext: function(contextHandle) { - return GL.contexts[contextHandle]; - }, deleteContext: function(contextHandle) { - if (GL.currentContext === GL.contexts[contextHandle]) - GL.currentContext = null; - if (typeof JSEvents === "object") - JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas); - if (GL.contexts[contextHandle] && GL.contexts[contextHandle].GLctx.canvas) - GL.contexts[contextHandle].GLctx.canvas.GLctxObject = void 0; - _free(GL.contexts[contextHandle].handle); - GL.contexts[contextHandle] = null; - }, initExtensions: function(context) { - if (!context) - context = GL.currentContext; - if (context.initExtensionsDone) - return; - context.initExtensionsDone = true; - var GLctx2 = context.GLctx; - __webgl_enable_ANGLE_instanced_arrays(GLctx2); - __webgl_enable_OES_vertex_array_object(GLctx2); - __webgl_enable_WEBGL_draw_buffers(GLctx2); - GLctx2.disjointTimerQueryExt = GLctx2.getExtension("EXT_disjoint_timer_query"); - __webgl_enable_WEBGL_multi_draw(GLctx2); - var exts = GLctx2.getSupportedExtensions() || []; - exts.forEach(function(ext) { - if (ext.indexOf("lose_context") < 0 && ext.indexOf("debug") < 0) { - GLctx2.getExtension(ext); - } - }); - }, populateUniformTable: function(program) { - var p2 = GL.programs[program]; - var ptable = GL.programInfos[program] = { uniforms: {}, maxUniformLength: 0, maxAttributeLength: -1, maxUniformBlockNameLength: -1 }; - var utable = ptable.uniforms; - var numUniforms = GLctx.getProgramParameter(p2, 35718); - for (var i = 0; i < numUniforms; ++i) { - var u = GLctx.getActiveUniform(p2, i); - var name = u.name; - ptable.maxUniformLength = Math.max(ptable.maxUniformLength, name.length + 1); - if (name.slice(-1) == "]") { - name = name.slice(0, name.lastIndexOf("[")); - } - var loc = GLctx.getUniformLocation(p2, name); - if (loc) { - var id = GL.getNewId(GL.uniforms); - utable[name] = [u.size, id]; - GL.uniforms[id] = loc; - for (var j = 1; j < u.size; ++j) { - var n = name + "[" + j + "]"; - loc = GLctx.getUniformLocation(p2, n); - id = GL.getNewId(GL.uniforms); - GL.uniforms[id] = loc; - } - } - } - } }; - var __emscripten_webgl_power_preferences = ["default", "low-power", "high-performance"]; - function _emscripten_webgl_do_create_context(target, attributes) { - var a = attributes >> 2; - var powerPreference = GROWABLE_HEAP_I32()[a + (24 >> 2)]; - var contextAttributes = { "alpha": !!GROWABLE_HEAP_I32()[a + (0 >> 2)], "depth": !!GROWABLE_HEAP_I32()[a + (4 >> 2)], "stencil": !!GROWABLE_HEAP_I32()[a + (8 >> 2)], "antialias": !!GROWABLE_HEAP_I32()[a + (12 >> 2)], "premultipliedAlpha": !!GROWABLE_HEAP_I32()[a + (16 >> 2)], "preserveDrawingBuffer": !!GROWABLE_HEAP_I32()[a + (20 >> 2)], "powerPreference": __emscripten_webgl_power_preferences[powerPreference], "failIfMajorPerformanceCaveat": !!GROWABLE_HEAP_I32()[a + (28 >> 2)], majorVersion: GROWABLE_HEAP_I32()[a + (32 >> 2)], minorVersion: GROWABLE_HEAP_I32()[a + (36 >> 2)], enableExtensionsByDefault: GROWABLE_HEAP_I32()[a + (40 >> 2)], explicitSwapControl: GROWABLE_HEAP_I32()[a + (44 >> 2)], proxyContextToMainThread: GROWABLE_HEAP_I32()[a + (48 >> 2)], renderViaOffscreenBackBuffer: GROWABLE_HEAP_I32()[a + (52 >> 2)] }; - var canvas2 = findCanvasEventTarget(target); - if (!canvas2) { - return 0; - } - if (contextAttributes.explicitSwapControl) { - return 0; - } - var contextHandle = GL.createContext(canvas2, contextAttributes); - return contextHandle; - } - function _emscripten_webgl_create_context(a0, a12) { - return _emscripten_webgl_do_create_context(a0, a12); - } - var SYSCALLS = { mappings: {}, buffers: [null, [], []], printChar: function(stream, curr) { - var buffer3 = SYSCALLS.buffers[stream]; - if (curr === 0 || curr === 10) { - (stream === 1 ? out : err)(UTF8ArrayToString(buffer3, 0)); - buffer3.length = 0; - } else { - buffer3.push(curr); - } - }, varargs: void 0, get: function() { - SYSCALLS.varargs += 4; - var ret = GROWABLE_HEAP_I32()[SYSCALLS.varargs - 4 >> 2]; - return ret; - }, getStr: function(ptr) { - var ret = UTF8ToString(ptr); - return ret; - }, get64: function(low, high) { - return low; - } }; - function _fd_close(fd) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(3, 1, fd); - return 0; - } - function _fd_seek(fd, offset_low, offset_high, whence, newOffset) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(4, 1, fd, offset_low, offset_high, whence, newOffset); - } - function _fd_write(fd, iov, iovcnt, pnum) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(5, 1, fd, iov, iovcnt, pnum); - var num = 0; - for (var i = 0; i < iovcnt; i++) { - var ptr = GROWABLE_HEAP_I32()[iov + i * 8 >> 2]; - var len = GROWABLE_HEAP_I32()[iov + (i * 8 + 4) >> 2]; - for (var j = 0; j < len; j++) { - SYSCALLS.printChar(fd, GROWABLE_HEAP_U8()[ptr + j]); - } - num += len; - } - GROWABLE_HEAP_I32()[pnum >> 2] = num; - return 0; - } - function _pthread_cleanup_pop(execute2) { - var routine = PThread.threadExitHandlers.pop(); - if (execute2) - routine(); - } - function _pthread_cleanup_push(routine, arg) { - PThread.threadExitHandlers.push(function() { - wasmTable.get(routine)(arg); - }); - } - function spawnThread(threadParams) { - if (ENVIRONMENT_IS_PTHREAD) - throw "Internal Error! spawnThread() can only ever be called from main application thread!"; - var worker = PThread.getNewWorker(); - if (worker.pthread !== void 0) - throw "Internal error!"; - if (!threadParams.pthread_ptr) - throw "Internal error, no pthread ptr!"; - PThread.runningWorkers.push(worker); - var tlsMemory = _malloc(128 * 4); - for (var i = 0; i < 128; ++i) { - GROWABLE_HEAP_I32()[tlsMemory + i * 4 >> 2] = 0; - } - var stackHigh = threadParams.stackBase + threadParams.stackSize; - var pthread = PThread.pthreads[threadParams.pthread_ptr] = { worker, stackBase: threadParams.stackBase, stackSize: threadParams.stackSize, allocatedOwnStack: threadParams.allocatedOwnStack, threadInfoStruct: threadParams.pthread_ptr }; - var tis = pthread.threadInfoStruct >> 2; - Atomics.store(GROWABLE_HEAP_U32(), tis + (64 >> 2), threadParams.detached); - Atomics.store(GROWABLE_HEAP_U32(), tis + (100 >> 2), tlsMemory); - Atomics.store(GROWABLE_HEAP_U32(), tis + (40 >> 2), pthread.threadInfoStruct); - Atomics.store(GROWABLE_HEAP_U32(), tis + (80 >> 2), threadParams.stackSize); - Atomics.store(GROWABLE_HEAP_U32(), tis + (76 >> 2), stackHigh); - Atomics.store(GROWABLE_HEAP_U32(), tis + (104 >> 2), threadParams.stackSize); - Atomics.store(GROWABLE_HEAP_U32(), tis + (104 + 8 >> 2), stackHigh); - Atomics.store(GROWABLE_HEAP_U32(), tis + (104 + 12 >> 2), threadParams.detached); - var global_libc = _emscripten_get_global_libc(); - var global_locale = global_libc + 40; - Atomics.store(GROWABLE_HEAP_U32(), tis + (172 >> 2), global_locale); - worker.pthread = pthread; - var msg = { "cmd": "run", "start_routine": threadParams.startRoutine, "arg": threadParams.arg, "threadInfoStruct": threadParams.pthread_ptr, "stackBase": threadParams.stackBase, "stackSize": threadParams.stackSize }; - worker.runPthread = function() { - msg.time = performance.now(); - worker.postMessage(msg, threadParams.transferList); - }; - if (worker.loaded) { - worker.runPthread(); - delete worker.runPthread; - } - } - function _pthread_create(pthread_ptr, attr, start_routine, arg) { - if (typeof SharedArrayBuffer === "undefined") { - err("Current environment does not support SharedArrayBuffer, pthreads are not available!"); - return 6; - } - if (!pthread_ptr) { - err("pthread_create called with a null thread pointer!"); - return 28; - } - var transferList = []; - var error = 0; - if (ENVIRONMENT_IS_PTHREAD && (transferList.length === 0 || error)) { - return _emscripten_sync_run_in_main_thread_4(687865856, pthread_ptr, attr, start_routine, arg); - } - if (error) - return error; - var stackSize = 0; - var stackBase = 0; - var detached = 0; - if (attr && attr != -1) { - stackSize = GROWABLE_HEAP_I32()[attr >> 2]; - stackSize += 81920; - stackBase = GROWABLE_HEAP_I32()[attr + 8 >> 2]; - detached = GROWABLE_HEAP_I32()[attr + 12 >> 2] !== 0; - } else { - stackSize = 2097152; - } - var allocatedOwnStack = stackBase == 0; - if (allocatedOwnStack) { - stackBase = _memalign(16, stackSize); - } else { - stackBase -= stackSize; - assert3(stackBase > 0); - } - var threadInfoStruct = _malloc(228); - for (var i = 0; i < 228 >> 2; ++i) - GROWABLE_HEAP_U32()[(threadInfoStruct >> 2) + i] = 0; - GROWABLE_HEAP_I32()[pthread_ptr >> 2] = threadInfoStruct; - GROWABLE_HEAP_I32()[threadInfoStruct + 12 >> 2] = threadInfoStruct; - var headPtr = threadInfoStruct + 152; - GROWABLE_HEAP_I32()[headPtr >> 2] = headPtr; - var threadParams = { stackBase, stackSize, allocatedOwnStack, detached, startRoutine: start_routine, pthread_ptr: threadInfoStruct, arg, transferList }; - if (ENVIRONMENT_IS_PTHREAD) { - threadParams.cmd = "spawnThread"; - postMessage(threadParams, transferList); - } else { - spawnThread(threadParams); - } - return 0; - } - function _sysconf(name) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(6, 1, name); - switch (name) { - case 30: - return 16384; - case 85: - var maxHeapSize = 2147483648; - return maxHeapSize / 16384; - case 132: - case 133: - case 12: - case 137: - case 138: - case 15: - case 235: - case 16: - case 17: - case 18: - case 19: - case 20: - case 149: - case 13: - case 10: - case 236: - case 153: - case 9: - case 21: - case 22: - case 159: - case 154: - case 14: - case 77: - case 78: - case 139: - case 82: - case 68: - case 67: - case 164: - case 11: - case 29: - case 47: - case 48: - case 95: - case 52: - case 51: - case 46: - return 200809; - case 27: - case 246: - case 127: - case 128: - case 23: - case 24: - case 160: - case 161: - case 181: - case 182: - case 242: - case 183: - case 184: - case 243: - case 244: - case 245: - case 165: - case 178: - case 179: - case 49: - case 50: - case 168: - case 169: - case 175: - case 170: - case 171: - case 172: - case 97: - case 76: - case 32: - case 173: - case 35: - case 80: - case 81: - case 79: - return -1; - case 176: - case 177: - case 7: - case 155: - case 8: - case 157: - case 125: - case 126: - case 92: - case 93: - case 129: - case 130: - case 131: - case 94: - case 91: - return 1; - case 74: - case 60: - case 69: - case 70: - case 4: - return 1024; - case 31: - case 42: - case 72: - return 32; - case 87: - case 26: - case 33: - return 2147483647; - case 34: - case 1: - return 47839; - case 38: - case 36: - return 99; - case 43: - case 37: - return 2048; - case 0: - return 2097152; - case 3: - return 65536; - case 28: - return 32768; - case 44: - return 32767; - case 75: - return 16384; - case 39: - return 1e3; - case 89: - return 700; - case 71: - return 256; - case 40: - return 255; - case 2: - return 100; - case 180: - return 64; - case 25: - return 20; - case 5: - return 16; - case 6: - return 6; - case 73: - return 4; - case 84: { - if (typeof navigator === "object") - return navigator["hardwareConcurrency"] || 1; - return 1; - } - } - setErrNo(28); - return -1; - } - if (!ENVIRONMENT_IS_PTHREAD) - PThread.initMainThreadBlock(); - var GLctx; - var proxiedFunctionTable = [null, _atexit, _emscripten_set_canvas_element_size_main_thread, _fd_close, _fd_seek, _fd_write, _sysconf]; - var asmLibraryArg = { "e": ___assert_fail, "r": ___call_main, "x": __emscripten_notify_thread_queue, "b": _abort, "y": _emscripten_asm_const_int, "j": _emscripten_conditional_set_current_thread_status, "c": _emscripten_futex_wait, "d": _emscripten_futex_wake, "f": _emscripten_get_now, "p": _emscripten_memcpy_big, "z": _emscripten_num_logical_cores, "u": _emscripten_receive_on_main_thread_js, "q": _emscripten_resize_heap, "v": _emscripten_set_canvas_element_size, "i": _emscripten_set_current_thread_status, "t": _emscripten_set_thread_name, "w": _emscripten_webgl_create_context, "m": _fd_close, "n": _fd_seek, "g": _fd_write, "o": initPthreadsJS, "a": wasmMemory || Module["wasmMemory"], "k": _pthread_cleanup_pop, "l": _pthread_cleanup_push, "h": _pthread_create, "s": _sysconf }; - var asm = createWasm(); - var ___wasm_call_ctors = Module["___wasm_call_ctors"] = function() { - return (___wasm_call_ctors = Module["___wasm_call_ctors"] = Module["asm"]["A"]).apply(null, arguments); - }; - var _init = Module["_init"] = function() { - return (_init = Module["_init"] = Module["asm"]["B"]).apply(null, arguments); - }; - var _register_tensor = Module["_register_tensor"] = function() { - return (_register_tensor = Module["_register_tensor"] = Module["asm"]["C"]).apply(null, arguments); - }; - var _dispose_data = Module["_dispose_data"] = function() { - return (_dispose_data = Module["_dispose_data"] = Module["asm"]["D"]).apply(null, arguments); - }; - var _dispose = Module["_dispose"] = function() { - return (_dispose = Module["_dispose"] = Module["asm"]["E"]).apply(null, arguments); - }; - var _Abs = Module["_Abs"] = function() { - return (_Abs = Module["_Abs"] = Module["asm"]["G"]).apply(null, arguments); - }; - var _Add = Module["_Add"] = function() { - return (_Add = Module["_Add"] = Module["asm"]["H"]).apply(null, arguments); - }; - var _AddN = Module["_AddN"] = function() { - return (_AddN = Module["_AddN"] = Module["asm"]["I"]).apply(null, arguments); - }; - var _All = Module["_All"] = function() { - return (_All = Module["_All"] = Module["asm"]["J"]).apply(null, arguments); - }; - var _Any = Module["_Any"] = function() { - return (_Any = Module["_Any"] = Module["asm"]["K"]).apply(null, arguments); - }; - var _ArgMax = Module["_ArgMax"] = function() { - return (_ArgMax = Module["_ArgMax"] = Module["asm"]["L"]).apply(null, arguments); - }; - var _AvgPool = Module["_AvgPool"] = function() { - return (_AvgPool = Module["_AvgPool"] = Module["asm"]["M"]).apply(null, arguments); - }; - var _BatchMatMul = Module["_BatchMatMul"] = function() { - return (_BatchMatMul = Module["_BatchMatMul"] = Module["asm"]["N"]).apply(null, arguments); - }; - var _Ceil = Module["_Ceil"] = function() { - return (_Ceil = Module["_Ceil"] = Module["asm"]["O"]).apply(null, arguments); - }; - var _ClipByValue = Module["_ClipByValue"] = function() { - return (_ClipByValue = Module["_ClipByValue"] = Module["asm"]["P"]).apply(null, arguments); - }; - var _Conv2D = Module["_Conv2D"] = function() { - return (_Conv2D = Module["_Conv2D"] = Module["asm"]["Q"]).apply(null, arguments); - }; - var _Conv2DBackpropInput = Module["_Conv2DBackpropInput"] = function() { - return (_Conv2DBackpropInput = Module["_Conv2DBackpropInput"] = Module["asm"]["R"]).apply(null, arguments); - }; - var _Cos = Module["_Cos"] = function() { - return (_Cos = Module["_Cos"] = Module["asm"]["S"]).apply(null, arguments); - }; - var _Cosh = Module["_Cosh"] = function() { - return (_Cosh = Module["_Cosh"] = Module["asm"]["T"]).apply(null, arguments); - }; - var _CropAndResize = Module["_CropAndResize"] = function() { - return (_CropAndResize = Module["_CropAndResize"] = Module["asm"]["U"]).apply(null, arguments); - }; - var _Cumsum = Module["_Cumsum"] = function() { - return (_Cumsum = Module["_Cumsum"] = Module["asm"]["V"]).apply(null, arguments); - }; - var _DepthToSpace = Module["_DepthToSpace"] = function() { - return (_DepthToSpace = Module["_DepthToSpace"] = Module["asm"]["W"]).apply(null, arguments); - }; - var _DepthwiseConv2dNative = Module["_DepthwiseConv2dNative"] = function() { - return (_DepthwiseConv2dNative = Module["_DepthwiseConv2dNative"] = Module["asm"]["X"]).apply(null, arguments); - }; - var _Elu = Module["_Elu"] = function() { - return (_Elu = Module["_Elu"] = Module["asm"]["Y"]).apply(null, arguments); - }; - var _Equal = Module["_Equal"] = function() { - return (_Equal = Module["_Equal"] = Module["asm"]["Z"]).apply(null, arguments); - }; - var _Exp = Module["_Exp"] = function() { - return (_Exp = Module["_Exp"] = Module["asm"]["_"]).apply(null, arguments); - }; - var _FlipLeftRight = Module["_FlipLeftRight"] = function() { - return (_FlipLeftRight = Module["_FlipLeftRight"] = Module["asm"]["$"]).apply(null, arguments); - }; - var _Floor = Module["_Floor"] = function() { - return (_Floor = Module["_Floor"] = Module["asm"]["aa"]).apply(null, arguments); - }; - var _FloorDiv = Module["_FloorDiv"] = function() { - return (_FloorDiv = Module["_FloorDiv"] = Module["asm"]["ba"]).apply(null, arguments); - }; - var _FusedBatchNorm = Module["_FusedBatchNorm"] = function() { - return (_FusedBatchNorm = Module["_FusedBatchNorm"] = Module["asm"]["ca"]).apply(null, arguments); - }; - var _FusedConv2D = Module["_FusedConv2D"] = function() { - return (_FusedConv2D = Module["_FusedConv2D"] = Module["asm"]["da"]).apply(null, arguments); - }; - var _FusedDepthwiseConv2D = Module["_FusedDepthwiseConv2D"] = function() { - return (_FusedDepthwiseConv2D = Module["_FusedDepthwiseConv2D"] = Module["asm"]["ea"]).apply(null, arguments); - }; - var _Gather = Module["_Gather"] = function() { - return (_Gather = Module["_Gather"] = Module["asm"]["fa"]).apply(null, arguments); - }; - var _GatherNd = Module["_GatherNd"] = function() { - return (_GatherNd = Module["_GatherNd"] = Module["asm"]["ga"]).apply(null, arguments); - }; - var _Greater = Module["_Greater"] = function() { - return (_Greater = Module["_Greater"] = Module["asm"]["ha"]).apply(null, arguments); - }; - var _GreaterEqual = Module["_GreaterEqual"] = function() { - return (_GreaterEqual = Module["_GreaterEqual"] = Module["asm"]["ia"]).apply(null, arguments); - }; - var _LeakyRelu = Module["_LeakyRelu"] = function() { - return (_LeakyRelu = Module["_LeakyRelu"] = Module["asm"]["ja"]).apply(null, arguments); - }; - var _Less = Module["_Less"] = function() { - return (_Less = Module["_Less"] = Module["asm"]["ka"]).apply(null, arguments); - }; - var _LessEqual = Module["_LessEqual"] = function() { - return (_LessEqual = Module["_LessEqual"] = Module["asm"]["la"]).apply(null, arguments); - }; - var _Log = Module["_Log"] = function() { - return (_Log = Module["_Log"] = Module["asm"]["ma"]).apply(null, arguments); - }; - var _LogicalAnd = Module["_LogicalAnd"] = function() { - return (_LogicalAnd = Module["_LogicalAnd"] = Module["asm"]["na"]).apply(null, arguments); - }; - var _Max = Module["_Max"] = function() { - return (_Max = Module["_Max"] = Module["asm"]["oa"]).apply(null, arguments); - }; - var _MaxPool = Module["_MaxPool"] = function() { - return (_MaxPool = Module["_MaxPool"] = Module["asm"]["pa"]).apply(null, arguments); - }; - var _Maximum = Module["_Maximum"] = function() { - return (_Maximum = Module["_Maximum"] = Module["asm"]["qa"]).apply(null, arguments); - }; - var _Mean = Module["_Mean"] = function() { - return (_Mean = Module["_Mean"] = Module["asm"]["ra"]).apply(null, arguments); - }; - var _Min = Module["_Min"] = function() { - return (_Min = Module["_Min"] = Module["asm"]["sa"]).apply(null, arguments); - }; - var _Minimum = Module["_Minimum"] = function() { - return (_Minimum = Module["_Minimum"] = Module["asm"]["ta"]).apply(null, arguments); - }; - var _MirrorPad = Module["_MirrorPad"] = function() { - return (_MirrorPad = Module["_MirrorPad"] = Module["asm"]["ua"]).apply(null, arguments); - }; - var _Multiply = Module["_Multiply"] = function() { - return (_Multiply = Module["_Multiply"] = Module["asm"]["va"]).apply(null, arguments); - }; - var _Neg = Module["_Neg"] = function() { - return (_Neg = Module["_Neg"] = Module["asm"]["wa"]).apply(null, arguments); - }; - var _NonMaxSuppressionV3 = Module["_NonMaxSuppressionV3"] = function() { - return (_NonMaxSuppressionV3 = Module["_NonMaxSuppressionV3"] = Module["asm"]["xa"]).apply(null, arguments); - }; - var _NonMaxSuppressionV4 = Module["_NonMaxSuppressionV4"] = function() { - return (_NonMaxSuppressionV4 = Module["_NonMaxSuppressionV4"] = Module["asm"]["ya"]).apply(null, arguments); - }; - var _NonMaxSuppressionV5 = Module["_NonMaxSuppressionV5"] = function() { - return (_NonMaxSuppressionV5 = Module["_NonMaxSuppressionV5"] = Module["asm"]["za"]).apply(null, arguments); - }; - var _NotEqual = Module["_NotEqual"] = function() { - return (_NotEqual = Module["_NotEqual"] = Module["asm"]["Aa"]).apply(null, arguments); - }; - var _OneHot = Module["_OneHot"] = function() { - return (_OneHot = Module["_OneHot"] = Module["asm"]["Ba"]).apply(null, arguments); - }; - var _PadV2 = Module["_PadV2"] = function() { - return (_PadV2 = Module["_PadV2"] = Module["asm"]["Ca"]).apply(null, arguments); - }; - var _Pow = Module["_Pow"] = function() { - return (_Pow = Module["_Pow"] = Module["asm"]["Da"]).apply(null, arguments); - }; - var _Prelu = Module["_Prelu"] = function() { - return (_Prelu = Module["_Prelu"] = Module["asm"]["Ea"]).apply(null, arguments); - }; - var _Prod = Module["_Prod"] = function() { - return (_Prod = Module["_Prod"] = Module["asm"]["Fa"]).apply(null, arguments); - }; - var _RealDiv = Module["_RealDiv"] = function() { - return (_RealDiv = Module["_RealDiv"] = Module["asm"]["Ga"]).apply(null, arguments); - }; - var _Relu = Module["_Relu"] = function() { - return (_Relu = Module["_Relu"] = Module["asm"]["Ha"]).apply(null, arguments); - }; - var _Relu6 = Module["_Relu6"] = function() { - return (_Relu6 = Module["_Relu6"] = Module["asm"]["Ia"]).apply(null, arguments); - }; - var _ResizeBilinear = Module["_ResizeBilinear"] = function() { - return (_ResizeBilinear = Module["_ResizeBilinear"] = Module["asm"]["Ja"]).apply(null, arguments); - }; - var _Reverse = Module["_Reverse"] = function() { - return (_Reverse = Module["_Reverse"] = Module["asm"]["Ka"]).apply(null, arguments); - }; - var _RotateWithOffset = Module["_RotateWithOffset"] = function() { - return (_RotateWithOffset = Module["_RotateWithOffset"] = Module["asm"]["La"]).apply(null, arguments); - }; - var _Round = Module["_Round"] = function() { - return (_Round = Module["_Round"] = Module["asm"]["Ma"]).apply(null, arguments); - }; - var _Rsqrt = Module["_Rsqrt"] = function() { - return (_Rsqrt = Module["_Rsqrt"] = Module["asm"]["Na"]).apply(null, arguments); - }; - var _ScatterNd = Module["_ScatterNd"] = function() { - return (_ScatterNd = Module["_ScatterNd"] = Module["asm"]["Oa"]).apply(null, arguments); - }; - var _SelectV2 = Module["_SelectV2"] = function() { - return (_SelectV2 = Module["_SelectV2"] = Module["asm"]["Pa"]).apply(null, arguments); - }; - var _Sigmoid = Module["_Sigmoid"] = function() { - return (_Sigmoid = Module["_Sigmoid"] = Module["asm"]["Qa"]).apply(null, arguments); - }; - var _Sin = Module["_Sin"] = function() { - return (_Sin = Module["_Sin"] = Module["asm"]["Ra"]).apply(null, arguments); - }; - var _Softmax = Module["_Softmax"] = function() { - return (_Softmax = Module["_Softmax"] = Module["asm"]["Sa"]).apply(null, arguments); - }; - var _Sqrt = Module["_Sqrt"] = function() { - return (_Sqrt = Module["_Sqrt"] = Module["asm"]["Ta"]).apply(null, arguments); - }; - var _Square = Module["_Square"] = function() { - return (_Square = Module["_Square"] = Module["asm"]["Ua"]).apply(null, arguments); - }; - var _SquaredDifference = Module["_SquaredDifference"] = function() { - return (_SquaredDifference = Module["_SquaredDifference"] = Module["asm"]["Va"]).apply(null, arguments); - }; - var _Step = Module["_Step"] = function() { - return (_Step = Module["_Step"] = Module["asm"]["Wa"]).apply(null, arguments); - }; - var _StridedSlice = Module["_StridedSlice"] = function() { - return (_StridedSlice = Module["_StridedSlice"] = Module["asm"]["Xa"]).apply(null, arguments); - }; - var _Sub = Module["_Sub"] = function() { - return (_Sub = Module["_Sub"] = Module["asm"]["Ya"]).apply(null, arguments); - }; - var _Sum = Module["_Sum"] = function() { - return (_Sum = Module["_Sum"] = Module["asm"]["Za"]).apply(null, arguments); - }; - var _Tan = Module["_Tan"] = function() { - return (_Tan = Module["_Tan"] = Module["asm"]["_a"]).apply(null, arguments); - }; - var _Tanh = Module["_Tanh"] = function() { - return (_Tanh = Module["_Tanh"] = Module["asm"]["$a"]).apply(null, arguments); - }; - var _Tile = Module["_Tile"] = function() { - return (_Tile = Module["_Tile"] = Module["asm"]["ab"]).apply(null, arguments); - }; - var _TopK = Module["_TopK"] = function() { - return (_TopK = Module["_TopK"] = Module["asm"]["bb"]).apply(null, arguments); - }; - var _Transform = Module["_Transform"] = function() { - return (_Transform = Module["_Transform"] = Module["asm"]["cb"]).apply(null, arguments); - }; - var _Transpose = Module["_Transpose"] = function() { - return (_Transpose = Module["_Transpose"] = Module["asm"]["db"]).apply(null, arguments); - }; - var __FusedMatMul = Module["__FusedMatMul"] = function() { - return (__FusedMatMul = Module["__FusedMatMul"] = Module["asm"]["eb"]).apply(null, arguments); - }; - var _malloc = Module["_malloc"] = function() { - return (_malloc = Module["_malloc"] = Module["asm"]["fb"]).apply(null, arguments); - }; - var _free = Module["_free"] = function() { - return (_free = Module["_free"] = Module["asm"]["gb"]).apply(null, arguments); - }; - var ___errno_location = Module["___errno_location"] = function() { - return (___errno_location = Module["___errno_location"] = Module["asm"]["hb"]).apply(null, arguments); - }; - var _emscripten_get_global_libc = Module["_emscripten_get_global_libc"] = function() { - return (_emscripten_get_global_libc = Module["_emscripten_get_global_libc"] = Module["asm"]["ib"]).apply(null, arguments); - }; - var _pthread_self = Module["_pthread_self"] = function() { - return (_pthread_self = Module["_pthread_self"] = Module["asm"]["jb"]).apply(null, arguments); - }; - var ___pthread_tsd_run_dtors = Module["___pthread_tsd_run_dtors"] = function() { - return (___pthread_tsd_run_dtors = Module["___pthread_tsd_run_dtors"] = Module["asm"]["kb"]).apply(null, arguments); - }; - var _emscripten_main_thread_process_queued_calls = Module["_emscripten_main_thread_process_queued_calls"] = function() { - return (_emscripten_main_thread_process_queued_calls = Module["_emscripten_main_thread_process_queued_calls"] = Module["asm"]["lb"]).apply(null, arguments); - }; - var _emscripten_current_thread_process_queued_calls = Module["_emscripten_current_thread_process_queued_calls"] = function() { - return (_emscripten_current_thread_process_queued_calls = Module["_emscripten_current_thread_process_queued_calls"] = Module["asm"]["mb"]).apply(null, arguments); - }; - var _emscripten_register_main_browser_thread_id = Module["_emscripten_register_main_browser_thread_id"] = function() { - return (_emscripten_register_main_browser_thread_id = Module["_emscripten_register_main_browser_thread_id"] = Module["asm"]["nb"]).apply(null, arguments); - }; - var __emscripten_do_dispatch_to_thread = Module["__emscripten_do_dispatch_to_thread"] = function() { - return (__emscripten_do_dispatch_to_thread = Module["__emscripten_do_dispatch_to_thread"] = Module["asm"]["ob"]).apply(null, arguments); - }; - var _emscripten_sync_run_in_main_thread_4 = Module["_emscripten_sync_run_in_main_thread_4"] = function() { - return (_emscripten_sync_run_in_main_thread_4 = Module["_emscripten_sync_run_in_main_thread_4"] = Module["asm"]["pb"]).apply(null, arguments); - }; - var _emscripten_run_in_main_runtime_thread_js = Module["_emscripten_run_in_main_runtime_thread_js"] = function() { - return (_emscripten_run_in_main_runtime_thread_js = Module["_emscripten_run_in_main_runtime_thread_js"] = Module["asm"]["qb"]).apply(null, arguments); - }; - var __emscripten_call_on_thread = Module["__emscripten_call_on_thread"] = function() { - return (__emscripten_call_on_thread = Module["__emscripten_call_on_thread"] = Module["asm"]["rb"]).apply(null, arguments); - }; - var _emscripten_tls_init = Module["_emscripten_tls_init"] = function() { - return (_emscripten_tls_init = Module["_emscripten_tls_init"] = Module["asm"]["sb"]).apply(null, arguments); - }; - var __emscripten_thread_init = Module["__emscripten_thread_init"] = function() { - return (__emscripten_thread_init = Module["__emscripten_thread_init"] = Module["asm"]["tb"]).apply(null, arguments); - }; - var stackSave = Module["stackSave"] = function() { - return (stackSave = Module["stackSave"] = Module["asm"]["ub"]).apply(null, arguments); - }; - var stackRestore = Module["stackRestore"] = function() { - return (stackRestore = Module["stackRestore"] = Module["asm"]["vb"]).apply(null, arguments); - }; - var stackAlloc = Module["stackAlloc"] = function() { - return (stackAlloc = Module["stackAlloc"] = Module["asm"]["wb"]).apply(null, arguments); - }; - var _emscripten_stack_set_limits = Module["_emscripten_stack_set_limits"] = function() { - return (_emscripten_stack_set_limits = Module["_emscripten_stack_set_limits"] = Module["asm"]["xb"]).apply(null, arguments); - }; - var _memalign = Module["_memalign"] = function() { - return (_memalign = Module["_memalign"] = Module["asm"]["yb"]).apply(null, arguments); - }; - var __emscripten_allow_main_runtime_queued_calls = Module["__emscripten_allow_main_runtime_queued_calls"] = 10016; - var __emscripten_main_thread_futex = Module["__emscripten_main_thread_futex"] = 11652; - Module["cwrap"] = cwrap; - Module["PThread"] = PThread; - Module["PThread"] = PThread; - Module["wasmMemory"] = wasmMemory; - Module["ExitStatus"] = ExitStatus; - var calledRun; - function ExitStatus(status) { - this.name = "ExitStatus"; - this.message = "Program terminated with exit(" + status + ")"; - this.status = status; - } - dependenciesFulfilled = function runCaller() { - if (!calledRun) - run(); - if (!calledRun) - dependenciesFulfilled = runCaller; - }; - function run(args) { - args = args || arguments_; - if (runDependencies > 0) { - return; - } - if (ENVIRONMENT_IS_PTHREAD) { - readyPromiseResolve(Module); - initRuntime(); - postMessage({ "cmd": "loaded" }); - return; - } - preRun(); - if (runDependencies > 0) { - return; - } - function doRun() { - if (calledRun) - return; - calledRun = true; - Module["calledRun"] = true; - if (ABORT) - return; - initRuntime(); - preMain(); - readyPromiseResolve(Module); - if (Module["onRuntimeInitialized"]) - Module["onRuntimeInitialized"](); - postRun(); - } - if (Module["setStatus"]) { - Module["setStatus"]("Running..."); - setTimeout(function() { - setTimeout(function() { - Module["setStatus"](""); - }, 1); - doRun(); - }, 1); - } else { - doRun(); - } - } - Module["run"] = run; - function exit(status, implicit) { - if (implicit && noExitRuntime && status === 0) { - return; - } - if (!implicit) { - if (ENVIRONMENT_IS_PTHREAD) { - postMessage({ "cmd": "exitProcess", "returnCode": status }); - throw new ExitStatus(status); - } else { - } - } - if (noExitRuntime) { - } else { - PThread.terminateAllThreads(); - EXITSTATUS = status; - exitRuntime(); - if (Module["onExit"]) - Module["onExit"](status); - ABORT = true; - } - quit_(status, new ExitStatus(status)); - } - if (Module["preInit"]) { - if (typeof Module["preInit"] == "function") - Module["preInit"] = [Module["preInit"]]; - while (Module["preInit"].length > 0) { - Module["preInit"].pop()(); - } - } - if (ENVIRONMENT_IS_PTHREAD) { - noExitRuntime = false; - PThread.initWorker(); - } - run(); - return WasmBackendModuleThreadedSimd2.ready; - }; - }(); - if (typeof exports === "object" && typeof module === "object") - module.exports = WasmBackendModuleThreadedSimd; - else if (typeof define === "function" && define["amd"]) - define([], function() { - return WasmBackendModuleThreadedSimd; - }); - else if (typeof exports === "object") - exports["WasmBackendModuleThreadedSimd"] = WasmBackendModuleThreadedSimd; - } -}); -var require_tfjs_backend_wasm = __commonJS({ - "node_modules/.pnpm/@tensorflow+tfjs-backend-wasm@3.9.0_@tensorflow+tfjs-core@3.9.0/node_modules/@tensorflow/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm.js"(exports, module) { - var WasmBackendModule = function() { - var _scriptDir = typeof document !== "undefined" && document.currentScript ? document.currentScript.src : void 0; - if (typeof __filename !== "undefined") - _scriptDir = _scriptDir || __filename; - return function(WasmBackendModule2) { - WasmBackendModule2 = WasmBackendModule2 || {}; - var Module = typeof WasmBackendModule2 !== "undefined" ? WasmBackendModule2 : {}; - var readyPromiseResolve, readyPromiseReject; - Module["ready"] = new Promise(function(resolve, reject) { - readyPromiseResolve = resolve; - readyPromiseReject = reject; - }); - var moduleOverrides = {}; - var key; - for (key in Module) { - if (Module.hasOwnProperty(key)) { - moduleOverrides[key] = Module[key]; - } - } - var arguments_ = []; - var thisProgram = "./this.program"; - var quit_ = function(status, toThrow) { - throw toThrow; - }; - var ENVIRONMENT_IS_WEB = false; - var ENVIRONMENT_IS_WORKER = false; - var ENVIRONMENT_IS_NODE = false; - var ENVIRONMENT_IS_SHELL = false; - ENVIRONMENT_IS_WEB = typeof window === "object"; - ENVIRONMENT_IS_WORKER = typeof importScripts === "function"; - ENVIRONMENT_IS_NODE = typeof process === "object" && typeof process.versions === "object" && typeof process.versions.node === "string"; - ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER; - var scriptDirectory = ""; - function locateFile(path) { - if (Module["locateFile"]) { - return Module["locateFile"](path, scriptDirectory); - } - return scriptDirectory + path; - } - var read_, readAsync, readBinary, setWindowTitle; - var nodeFS; - var nodePath; - if (ENVIRONMENT_IS_NODE) { - if (ENVIRONMENT_IS_WORKER) { - scriptDirectory = require_path().dirname(scriptDirectory) + "/"; - } else { - scriptDirectory = __dirname + "/"; - } - read_ = function shell_read(filename, binary) { - if (!nodeFS) - nodeFS = __require2("fs"); - if (!nodePath) - nodePath = require_path(); - filename = nodePath["normalize"](filename); - return nodeFS["readFileSync"](filename, binary ? null : "utf8"); - }; - readBinary = function readBinary2(filename) { - var ret = read_(filename, true); - if (!ret.buffer) { - ret = new Uint8Array(ret); - } - assert3(ret.buffer); - return ret; - }; - if (process["argv"].length > 1) { - thisProgram = process["argv"][1].replace(/\\/g, "/"); - } - arguments_ = process["argv"].slice(2); - process["on"]("uncaughtException", function(ex) { - if (!(ex instanceof ExitStatus)) { - throw ex; - } - }); - process["on"]("unhandledRejection", abort); - quit_ = function(status) { - process["exit"](status); - }; - Module["inspect"] = function() { - return "[Emscripten Module object]"; - }; - } else if (ENVIRONMENT_IS_SHELL) { - if (typeof read != "undefined") { - read_ = function shell_read(f) { - return read(f); - }; - } - readBinary = function readBinary2(f) { - var data; - if (typeof readbuffer === "function") { - return new Uint8Array(readbuffer(f)); - } - data = read(f, "binary"); - assert3(typeof data === "object"); - return data; - }; - if (typeof scriptArgs != "undefined") { - arguments_ = scriptArgs; - } else if (typeof arguments != "undefined") { - arguments_ = arguments; - } - if (typeof quit === "function") { - quit_ = function(status) { - quit(status); - }; - } - if (typeof print !== "undefined") { - if (typeof console === "undefined") - console = {}; - console.log = print; - console.warn = console.error = typeof printErr !== "undefined" ? printErr : print; - } - } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { - if (ENVIRONMENT_IS_WORKER) { - scriptDirectory = self.location.href; - } else if (typeof document !== "undefined" && document.currentScript) { - scriptDirectory = document.currentScript.src; - } - if (_scriptDir) { - scriptDirectory = _scriptDir; - } - if (scriptDirectory.indexOf("blob:") !== 0) { - scriptDirectory = scriptDirectory.substr(0, scriptDirectory.lastIndexOf("/") + 1); - } else { - scriptDirectory = ""; - } - { - read_ = function(url) { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, false); - xhr.send(null); - return xhr.responseText; - }; - if (ENVIRONMENT_IS_WORKER) { - readBinary = function(url) { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, false); - xhr.responseType = "arraybuffer"; - xhr.send(null); - return new Uint8Array(xhr.response); - }; - } - readAsync = function(url, onload, onerror) { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, true); - xhr.responseType = "arraybuffer"; - xhr.onload = function() { - if (xhr.status == 200 || xhr.status == 0 && xhr.response) { - onload(xhr.response); - return; - } - onerror(); - }; - xhr.onerror = onerror; - xhr.send(null); - }; - } - setWindowTitle = function(title) { - document.title = title; - }; - } else { - } - var out = Module["print"] || console.log.bind(console); - var err = Module["printErr"] || console.warn.bind(console); - for (key in moduleOverrides) { - if (moduleOverrides.hasOwnProperty(key)) { - Module[key] = moduleOverrides[key]; - } - } - moduleOverrides = null; - if (Module["arguments"]) - arguments_ = Module["arguments"]; - if (Module["thisProgram"]) - thisProgram = Module["thisProgram"]; - if (Module["quit"]) - quit_ = Module["quit"]; - var wasmBinary; - if (Module["wasmBinary"]) - wasmBinary = Module["wasmBinary"]; - var noExitRuntime = Module["noExitRuntime"] || true; - if (typeof WebAssembly !== "object") { - abort("no native wasm support detected"); - } - var wasmMemory; - var ABORT = false; - var EXITSTATUS; - function assert3(condition, text) { - if (!condition) { - abort("Assertion failed: " + text); - } - } - function getCFunc(ident) { - var func2 = Module["_" + ident]; - assert3(func2, "Cannot call unknown function " + ident + ", make sure it is exported"); - return func2; - } - function ccall(ident, returnType, argTypes, args, opts) { - var toC = { "string": function(str) { - var ret2 = 0; - if (str !== null && str !== void 0 && str !== 0) { - var len = (str.length << 2) + 1; - ret2 = stackAlloc(len); - stringToUTF8(str, ret2, len); - } - return ret2; - }, "array": function(arr) { - var ret2 = stackAlloc(arr.length); - writeArrayToMemory(arr, ret2); - return ret2; - } }; - function convertReturnValue(ret2) { - if (returnType === "string") - return UTF8ToString(ret2); - if (returnType === "boolean") - return Boolean(ret2); - return ret2; - } - var func2 = getCFunc(ident); - var cArgs = []; - var stack2 = 0; - if (args) { - for (var i = 0; i < args.length; i++) { - var converter = toC[argTypes[i]]; - if (converter) { - if (stack2 === 0) - stack2 = stackSave(); - cArgs[i] = converter(args[i]); - } else { - cArgs[i] = args[i]; - } - } - } - var ret = func2.apply(null, cArgs); - ret = convertReturnValue(ret); - if (stack2 !== 0) - stackRestore(stack2); - return ret; - } - function cwrap(ident, returnType, argTypes, opts) { - argTypes = argTypes || []; - var numericArgs = argTypes.every(function(type) { - return type === "number"; - }); - var numericRet = returnType !== "string"; - if (numericRet && numericArgs && !opts) { - return getCFunc(ident); - } - return function() { - return ccall(ident, returnType, argTypes, arguments, opts); - }; - } - var UTF8Decoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf8") : void 0; - function UTF8ArrayToString(heap, idx, maxBytesToRead) { - var endIdx = idx + maxBytesToRead; - var endPtr = idx; - while (heap[endPtr] && !(endPtr >= endIdx)) - ++endPtr; - if (endPtr - idx > 16 && heap.subarray && UTF8Decoder) { - return UTF8Decoder.decode(heap.subarray(idx, endPtr)); - } else { - var str = ""; - while (idx < endPtr) { - var u0 = heap[idx++]; - if (!(u0 & 128)) { - str += String.fromCharCode(u0); - continue; - } - var u1 = heap[idx++] & 63; - if ((u0 & 224) == 192) { - str += String.fromCharCode((u0 & 31) << 6 | u1); - continue; - } - var u2 = heap[idx++] & 63; - if ((u0 & 240) == 224) { - u0 = (u0 & 15) << 12 | u1 << 6 | u2; - } else { - u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heap[idx++] & 63; - } - if (u0 < 65536) { - str += String.fromCharCode(u0); - } else { - var ch = u0 - 65536; - str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023); - } - } - } - return str; - } - function UTF8ToString(ptr, maxBytesToRead) { - return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : ""; - } - function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) { - if (!(maxBytesToWrite > 0)) - return 0; - var startIdx = outIdx; - var endIdx = outIdx + maxBytesToWrite - 1; - for (var i = 0; i < str.length; ++i) { - var u = str.charCodeAt(i); - if (u >= 55296 && u <= 57343) { - var u1 = str.charCodeAt(++i); - u = 65536 + ((u & 1023) << 10) | u1 & 1023; - } - if (u <= 127) { - if (outIdx >= endIdx) - break; - heap[outIdx++] = u; - } else if (u <= 2047) { - if (outIdx + 1 >= endIdx) - break; - heap[outIdx++] = 192 | u >> 6; - heap[outIdx++] = 128 | u & 63; - } else if (u <= 65535) { - if (outIdx + 2 >= endIdx) - break; - heap[outIdx++] = 224 | u >> 12; - heap[outIdx++] = 128 | u >> 6 & 63; - heap[outIdx++] = 128 | u & 63; - } else { - if (outIdx + 3 >= endIdx) - break; - heap[outIdx++] = 240 | u >> 18; - heap[outIdx++] = 128 | u >> 12 & 63; - heap[outIdx++] = 128 | u >> 6 & 63; - heap[outIdx++] = 128 | u & 63; - } - } - heap[outIdx] = 0; - return outIdx - startIdx; - } - function stringToUTF8(str, outPtr, maxBytesToWrite) { - return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite); - } - function writeArrayToMemory(array2, buffer3) { - HEAP8.set(array2, buffer3); - } - function alignUp(x, multiple) { - if (x % multiple > 0) { - x += multiple - x % multiple; - } - return x; - } - var buffer2, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64; - function updateGlobalBufferAndViews(buf) { - buffer2 = buf; - Module["HEAP8"] = HEAP8 = new Int8Array(buf); - Module["HEAP16"] = HEAP16 = new Int16Array(buf); - Module["HEAP32"] = HEAP32 = new Int32Array(buf); - Module["HEAPU8"] = HEAPU8 = new Uint8Array(buf); - Module["HEAPU16"] = HEAPU16 = new Uint16Array(buf); - Module["HEAPU32"] = HEAPU32 = new Uint32Array(buf); - Module["HEAPF32"] = HEAPF32 = new Float32Array(buf); - Module["HEAPF64"] = HEAPF64 = new Float64Array(buf); - } - var INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 16777216; - var wasmTable; - var __ATPRERUN__ = []; - var __ATINIT__ = []; - var __ATMAIN__ = []; - var __ATPOSTRUN__ = []; - var runtimeInitialized = false; - __ATINIT__.push({ func: function() { - ___wasm_call_ctors(); - } }); - function preRun() { - if (Module["preRun"]) { - if (typeof Module["preRun"] == "function") - Module["preRun"] = [Module["preRun"]]; - while (Module["preRun"].length) { - addOnPreRun(Module["preRun"].shift()); - } - } - callRuntimeCallbacks(__ATPRERUN__); - } - function initRuntime() { - runtimeInitialized = true; - callRuntimeCallbacks(__ATINIT__); - } - function preMain() { - callRuntimeCallbacks(__ATMAIN__); - } - function postRun() { - if (Module["postRun"]) { - if (typeof Module["postRun"] == "function") - Module["postRun"] = [Module["postRun"]]; - while (Module["postRun"].length) { - addOnPostRun(Module["postRun"].shift()); - } - } - callRuntimeCallbacks(__ATPOSTRUN__); - } - function addOnPreRun(cb) { - __ATPRERUN__.unshift(cb); - } - function addOnPostRun(cb) { - __ATPOSTRUN__.unshift(cb); - } - var runDependencies = 0; - var runDependencyWatcher = null; - var dependenciesFulfilled = null; - function addRunDependency(id) { - runDependencies++; - if (Module["monitorRunDependencies"]) { - Module["monitorRunDependencies"](runDependencies); - } - } - function removeRunDependency(id) { - runDependencies--; - if (Module["monitorRunDependencies"]) { - Module["monitorRunDependencies"](runDependencies); - } - if (runDependencies == 0) { - if (runDependencyWatcher !== null) { - clearInterval(runDependencyWatcher); - runDependencyWatcher = null; - } - if (dependenciesFulfilled) { - var callback = dependenciesFulfilled; - dependenciesFulfilled = null; - callback(); - } - } - } - Module["preloadedImages"] = {}; - Module["preloadedAudios"] = {}; - function abort(what) { - if (Module["onAbort"]) { - Module["onAbort"](what); - } - what += ""; - err(what); - ABORT = true; - EXITSTATUS = 1; - what = "abort(" + what + "). Build with -s ASSERTIONS=1 for more info."; - var e = new WebAssembly.RuntimeError(what); - readyPromiseReject(e); - throw e; - } - function hasPrefix(str, prefix) { - return String.prototype.startsWith ? str.startsWith(prefix) : str.indexOf(prefix) === 0; - } - var dataURIPrefix = "data:application/octet-stream;base64,"; - function isDataURI(filename) { - return hasPrefix(filename, dataURIPrefix); - } - var fileURIPrefix = "file://"; - function isFileURI(filename) { - return hasPrefix(filename, fileURIPrefix); - } - var wasmBinaryFile = "tfjs-backend-wasm.wasm"; - if (!isDataURI(wasmBinaryFile)) { - wasmBinaryFile = locateFile(wasmBinaryFile); - } - function getBinary(file) { - try { - if (file == wasmBinaryFile && wasmBinary) { - return new Uint8Array(wasmBinary); - } - if (readBinary) { - return readBinary(file); - } else { - throw "both async and sync fetching of the wasm failed"; - } - } catch (err2) { - abort(err2); - } - } - function getBinaryPromise() { - if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) { - if (typeof fetch === "function" && !isFileURI(wasmBinaryFile)) { - return fetch(wasmBinaryFile, { credentials: "same-origin" }).then(function(response) { - if (!response["ok"]) { - throw "failed to load wasm binary file at '" + wasmBinaryFile + "'"; - } - return response["arrayBuffer"](); - }).catch(function() { - return getBinary(wasmBinaryFile); - }); - } else { - if (readAsync) { - return new Promise(function(resolve, reject) { - readAsync(wasmBinaryFile, function(response) { - resolve(new Uint8Array(response)); - }, reject); - }); - } - } - } - return Promise.resolve().then(function() { - return getBinary(wasmBinaryFile); - }); - } - function createWasm() { - var info2 = { "a": asmLibraryArg }; - function receiveInstance(instance, module2) { - var exports3 = instance.exports; - Module["asm"] = exports3; - wasmMemory = Module["asm"]["i"]; - updateGlobalBufferAndViews(wasmMemory.buffer); - wasmTable = Module["asm"]["o"]; - removeRunDependency("wasm-instantiate"); - } - addRunDependency("wasm-instantiate"); - function receiveInstantiatedSource(output) { - receiveInstance(output["instance"]); - } - function instantiateArrayBuffer(receiver) { - return getBinaryPromise().then(function(binary) { - return WebAssembly.instantiate(binary, info2); - }).then(receiver, function(reason) { - err("failed to asynchronously prepare wasm: " + reason); - abort(reason); - }); - } - function instantiateAsync() { - if (!wasmBinary && typeof WebAssembly.instantiateStreaming === "function" && !isDataURI(wasmBinaryFile) && !isFileURI(wasmBinaryFile) && typeof fetch === "function") { - return fetch(wasmBinaryFile, { credentials: "same-origin" }).then(function(response) { - var result = WebAssembly.instantiateStreaming(response, info2); - return result.then(receiveInstantiatedSource, function(reason) { - err("wasm streaming compile failed: " + reason); - err("falling back to ArrayBuffer instantiation"); - return instantiateArrayBuffer(receiveInstantiatedSource); - }); - }); - } else { - return instantiateArrayBuffer(receiveInstantiatedSource); - } - } - if (Module["instantiateWasm"]) { - try { - var exports2 = Module["instantiateWasm"](info2, receiveInstance); - return exports2; - } catch (e) { - err("Module.instantiateWasm callback failed with error: " + e); - return false; - } - } - instantiateAsync().catch(readyPromiseReject); - return {}; - } - function callRuntimeCallbacks(callbacks2) { - while (callbacks2.length > 0) { - var callback = callbacks2.shift(); - if (typeof callback == "function") { - callback(Module); - continue; - } - var func2 = callback.func; - if (typeof func2 === "number") { - if (callback.arg === void 0) { - wasmTable.get(func2)(); - } else { - wasmTable.get(func2)(callback.arg); - } - } else { - func2(callback.arg === void 0 ? null : callback.arg); - } - } - } - function _abort() { - abort(); - } - function _emscripten_memcpy_big(dest, src, num) { - HEAPU8.copyWithin(dest, src, src + num); - } - function _emscripten_get_heap_size() { - return HEAPU8.length; - } - function emscripten_realloc_buffer(size) { - try { - wasmMemory.grow(size - buffer2.byteLength + 65535 >>> 16); - updateGlobalBufferAndViews(wasmMemory.buffer); - return 1; - } catch (e) { - } - } - function _emscripten_resize_heap(requestedSize) { - var oldSize = _emscripten_get_heap_size(); - var maxHeapSize = 2147483648; - if (requestedSize > maxHeapSize) { - return false; - } - for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { - var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown); - overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296); - var newSize = Math.min(maxHeapSize, alignUp(Math.max(requestedSize, overGrownHeapSize), 65536)); - var replacement = emscripten_realloc_buffer(newSize); - if (replacement) { - return true; - } - } - return false; - } - var SYSCALLS = { mappings: {}, buffers: [null, [], []], printChar: function(stream, curr) { - var buffer3 = SYSCALLS.buffers[stream]; - if (curr === 0 || curr === 10) { - (stream === 1 ? out : err)(UTF8ArrayToString(buffer3, 0)); - buffer3.length = 0; - } else { - buffer3.push(curr); - } - }, varargs: void 0, get: function() { - SYSCALLS.varargs += 4; - var ret = HEAP32[SYSCALLS.varargs - 4 >> 2]; - return ret; - }, getStr: function(ptr) { - var ret = UTF8ToString(ptr); - return ret; - }, get64: function(low, high) { - return low; - } }; - function _fd_close(fd) { - return 0; - } - function _fd_seek(fd, offset_low, offset_high, whence, newOffset) { - } - function _fd_write(fd, iov, iovcnt, pnum) { - var num = 0; - for (var i = 0; i < iovcnt; i++) { - var ptr = HEAP32[iov + i * 8 >> 2]; - var len = HEAP32[iov + (i * 8 + 4) >> 2]; - for (var j = 0; j < len; j++) { - SYSCALLS.printChar(fd, HEAPU8[ptr + j]); - } - num += len; - } - HEAP32[pnum >> 2] = num; - return 0; - } - function _pthread_create() { - return 6; - } - function setErrNo(value) { - HEAP32[___errno_location() >> 2] = value; - return value; - } - function _sysconf(name) { - switch (name) { - case 30: - return 16384; - case 85: - var maxHeapSize = 2147483648; - return maxHeapSize / 16384; - case 132: - case 133: - case 12: - case 137: - case 138: - case 15: - case 235: - case 16: - case 17: - case 18: - case 19: - case 20: - case 149: - case 13: - case 10: - case 236: - case 153: - case 9: - case 21: - case 22: - case 159: - case 154: - case 14: - case 77: - case 78: - case 139: - case 82: - case 68: - case 67: - case 164: - case 11: - case 29: - case 47: - case 48: - case 95: - case 52: - case 51: - case 46: - return 200809; - case 27: - case 246: - case 127: - case 128: - case 23: - case 24: - case 160: - case 161: - case 181: - case 182: - case 242: - case 183: - case 184: - case 243: - case 244: - case 245: - case 165: - case 178: - case 179: - case 49: - case 50: - case 168: - case 169: - case 175: - case 170: - case 171: - case 172: - case 97: - case 76: - case 32: - case 173: - case 35: - case 80: - case 81: - case 79: - return -1; - case 176: - case 177: - case 7: - case 155: - case 8: - case 157: - case 125: - case 126: - case 92: - case 93: - case 129: - case 130: - case 131: - case 94: - case 91: - return 1; - case 74: - case 60: - case 69: - case 70: - case 4: - return 1024; - case 31: - case 42: - case 72: - return 32; - case 87: - case 26: - case 33: - return 2147483647; - case 34: - case 1: - return 47839; - case 38: - case 36: - return 99; - case 43: - case 37: - return 2048; - case 0: - return 2097152; - case 3: - return 65536; - case 28: - return 32768; - case 44: - return 32767; - case 75: - return 16384; - case 39: - return 1e3; - case 89: - return 700; - case 71: - return 256; - case 40: - return 255; - case 2: - return 100; - case 180: - return 64; - case 25: - return 20; - case 5: - return 16; - case 6: - return 6; - case 73: - return 4; - case 84: { - if (typeof navigator === "object") - return navigator["hardwareConcurrency"] || 1; - return 1; - } - } - setErrNo(28); - return -1; - } - var asmLibraryArg = { "a": _abort, "d": _emscripten_memcpy_big, "e": _emscripten_resize_heap, "f": _fd_close, "c": _fd_seek, "b": _fd_write, "g": _pthread_create, "h": _sysconf }; - var asm = createWasm(); - var ___wasm_call_ctors = Module["___wasm_call_ctors"] = function() { - return (___wasm_call_ctors = Module["___wasm_call_ctors"] = Module["asm"]["j"]).apply(null, arguments); - }; - var _init = Module["_init"] = function() { - return (_init = Module["_init"] = Module["asm"]["k"]).apply(null, arguments); - }; - var _register_tensor = Module["_register_tensor"] = function() { - return (_register_tensor = Module["_register_tensor"] = Module["asm"]["l"]).apply(null, arguments); - }; - var _dispose_data = Module["_dispose_data"] = function() { - return (_dispose_data = Module["_dispose_data"] = Module["asm"]["m"]).apply(null, arguments); - }; - var _dispose = Module["_dispose"] = function() { - return (_dispose = Module["_dispose"] = Module["asm"]["n"]).apply(null, arguments); - }; - var _Abs = Module["_Abs"] = function() { - return (_Abs = Module["_Abs"] = Module["asm"]["p"]).apply(null, arguments); - }; - var _Add = Module["_Add"] = function() { - return (_Add = Module["_Add"] = Module["asm"]["q"]).apply(null, arguments); - }; - var _AddN = Module["_AddN"] = function() { - return (_AddN = Module["_AddN"] = Module["asm"]["r"]).apply(null, arguments); - }; - var _All = Module["_All"] = function() { - return (_All = Module["_All"] = Module["asm"]["s"]).apply(null, arguments); - }; - var _Any = Module["_Any"] = function() { - return (_Any = Module["_Any"] = Module["asm"]["t"]).apply(null, arguments); - }; - var _ArgMax = Module["_ArgMax"] = function() { - return (_ArgMax = Module["_ArgMax"] = Module["asm"]["u"]).apply(null, arguments); - }; - var _AvgPool = Module["_AvgPool"] = function() { - return (_AvgPool = Module["_AvgPool"] = Module["asm"]["v"]).apply(null, arguments); - }; - var _BatchMatMul = Module["_BatchMatMul"] = function() { - return (_BatchMatMul = Module["_BatchMatMul"] = Module["asm"]["w"]).apply(null, arguments); - }; - var _Ceil = Module["_Ceil"] = function() { - return (_Ceil = Module["_Ceil"] = Module["asm"]["x"]).apply(null, arguments); - }; - var _ClipByValue = Module["_ClipByValue"] = function() { - return (_ClipByValue = Module["_ClipByValue"] = Module["asm"]["y"]).apply(null, arguments); - }; - var _Conv2D = Module["_Conv2D"] = function() { - return (_Conv2D = Module["_Conv2D"] = Module["asm"]["z"]).apply(null, arguments); - }; - var _Conv2DBackpropInput = Module["_Conv2DBackpropInput"] = function() { - return (_Conv2DBackpropInput = Module["_Conv2DBackpropInput"] = Module["asm"]["A"]).apply(null, arguments); - }; - var _Cos = Module["_Cos"] = function() { - return (_Cos = Module["_Cos"] = Module["asm"]["B"]).apply(null, arguments); - }; - var _Cosh = Module["_Cosh"] = function() { - return (_Cosh = Module["_Cosh"] = Module["asm"]["C"]).apply(null, arguments); - }; - var _CropAndResize = Module["_CropAndResize"] = function() { - return (_CropAndResize = Module["_CropAndResize"] = Module["asm"]["D"]).apply(null, arguments); - }; - var _Cumsum = Module["_Cumsum"] = function() { - return (_Cumsum = Module["_Cumsum"] = Module["asm"]["E"]).apply(null, arguments); - }; - var _DepthToSpace = Module["_DepthToSpace"] = function() { - return (_DepthToSpace = Module["_DepthToSpace"] = Module["asm"]["F"]).apply(null, arguments); - }; - var _DepthwiseConv2dNative = Module["_DepthwiseConv2dNative"] = function() { - return (_DepthwiseConv2dNative = Module["_DepthwiseConv2dNative"] = Module["asm"]["G"]).apply(null, arguments); - }; - var _Elu = Module["_Elu"] = function() { - return (_Elu = Module["_Elu"] = Module["asm"]["H"]).apply(null, arguments); - }; - var _Equal = Module["_Equal"] = function() { - return (_Equal = Module["_Equal"] = Module["asm"]["I"]).apply(null, arguments); - }; - var _Exp = Module["_Exp"] = function() { - return (_Exp = Module["_Exp"] = Module["asm"]["J"]).apply(null, arguments); - }; - var _FlipLeftRight = Module["_FlipLeftRight"] = function() { - return (_FlipLeftRight = Module["_FlipLeftRight"] = Module["asm"]["K"]).apply(null, arguments); - }; - var _Floor = Module["_Floor"] = function() { - return (_Floor = Module["_Floor"] = Module["asm"]["L"]).apply(null, arguments); - }; - var _FloorDiv = Module["_FloorDiv"] = function() { - return (_FloorDiv = Module["_FloorDiv"] = Module["asm"]["M"]).apply(null, arguments); - }; - var _FusedBatchNorm = Module["_FusedBatchNorm"] = function() { - return (_FusedBatchNorm = Module["_FusedBatchNorm"] = Module["asm"]["N"]).apply(null, arguments); - }; - var _FusedConv2D = Module["_FusedConv2D"] = function() { - return (_FusedConv2D = Module["_FusedConv2D"] = Module["asm"]["O"]).apply(null, arguments); - }; - var _FusedDepthwiseConv2D = Module["_FusedDepthwiseConv2D"] = function() { - return (_FusedDepthwiseConv2D = Module["_FusedDepthwiseConv2D"] = Module["asm"]["P"]).apply(null, arguments); - }; - var _Gather = Module["_Gather"] = function() { - return (_Gather = Module["_Gather"] = Module["asm"]["Q"]).apply(null, arguments); - }; - var _GatherNd = Module["_GatherNd"] = function() { - return (_GatherNd = Module["_GatherNd"] = Module["asm"]["R"]).apply(null, arguments); - }; - var _Greater = Module["_Greater"] = function() { - return (_Greater = Module["_Greater"] = Module["asm"]["S"]).apply(null, arguments); - }; - var _GreaterEqual = Module["_GreaterEqual"] = function() { - return (_GreaterEqual = Module["_GreaterEqual"] = Module["asm"]["T"]).apply(null, arguments); - }; - var _LeakyRelu = Module["_LeakyRelu"] = function() { - return (_LeakyRelu = Module["_LeakyRelu"] = Module["asm"]["U"]).apply(null, arguments); - }; - var _Less = Module["_Less"] = function() { - return (_Less = Module["_Less"] = Module["asm"]["V"]).apply(null, arguments); - }; - var _LessEqual = Module["_LessEqual"] = function() { - return (_LessEqual = Module["_LessEqual"] = Module["asm"]["W"]).apply(null, arguments); - }; - var _Log = Module["_Log"] = function() { - return (_Log = Module["_Log"] = Module["asm"]["X"]).apply(null, arguments); - }; - var _LogicalAnd = Module["_LogicalAnd"] = function() { - return (_LogicalAnd = Module["_LogicalAnd"] = Module["asm"]["Y"]).apply(null, arguments); - }; - var _Max = Module["_Max"] = function() { - return (_Max = Module["_Max"] = Module["asm"]["Z"]).apply(null, arguments); - }; - var _MaxPool = Module["_MaxPool"] = function() { - return (_MaxPool = Module["_MaxPool"] = Module["asm"]["_"]).apply(null, arguments); - }; - var _Maximum = Module["_Maximum"] = function() { - return (_Maximum = Module["_Maximum"] = Module["asm"]["$"]).apply(null, arguments); - }; - var _Mean = Module["_Mean"] = function() { - return (_Mean = Module["_Mean"] = Module["asm"]["aa"]).apply(null, arguments); - }; - var _Min = Module["_Min"] = function() { - return (_Min = Module["_Min"] = Module["asm"]["ba"]).apply(null, arguments); - }; - var _Minimum = Module["_Minimum"] = function() { - return (_Minimum = Module["_Minimum"] = Module["asm"]["ca"]).apply(null, arguments); - }; - var _MirrorPad = Module["_MirrorPad"] = function() { - return (_MirrorPad = Module["_MirrorPad"] = Module["asm"]["da"]).apply(null, arguments); - }; - var _Multiply = Module["_Multiply"] = function() { - return (_Multiply = Module["_Multiply"] = Module["asm"]["ea"]).apply(null, arguments); - }; - var _Neg = Module["_Neg"] = function() { - return (_Neg = Module["_Neg"] = Module["asm"]["fa"]).apply(null, arguments); - }; - var _NonMaxSuppressionV3 = Module["_NonMaxSuppressionV3"] = function() { - return (_NonMaxSuppressionV3 = Module["_NonMaxSuppressionV3"] = Module["asm"]["ga"]).apply(null, arguments); - }; - var _NonMaxSuppressionV4 = Module["_NonMaxSuppressionV4"] = function() { - return (_NonMaxSuppressionV4 = Module["_NonMaxSuppressionV4"] = Module["asm"]["ha"]).apply(null, arguments); - }; - var _NonMaxSuppressionV5 = Module["_NonMaxSuppressionV5"] = function() { - return (_NonMaxSuppressionV5 = Module["_NonMaxSuppressionV5"] = Module["asm"]["ia"]).apply(null, arguments); - }; - var _NotEqual = Module["_NotEqual"] = function() { - return (_NotEqual = Module["_NotEqual"] = Module["asm"]["ja"]).apply(null, arguments); - }; - var _OneHot = Module["_OneHot"] = function() { - return (_OneHot = Module["_OneHot"] = Module["asm"]["ka"]).apply(null, arguments); - }; - var _PadV2 = Module["_PadV2"] = function() { - return (_PadV2 = Module["_PadV2"] = Module["asm"]["la"]).apply(null, arguments); - }; - var _Pow = Module["_Pow"] = function() { - return (_Pow = Module["_Pow"] = Module["asm"]["ma"]).apply(null, arguments); - }; - var _Prelu = Module["_Prelu"] = function() { - return (_Prelu = Module["_Prelu"] = Module["asm"]["na"]).apply(null, arguments); - }; - var _Prod = Module["_Prod"] = function() { - return (_Prod = Module["_Prod"] = Module["asm"]["oa"]).apply(null, arguments); - }; - var _RealDiv = Module["_RealDiv"] = function() { - return (_RealDiv = Module["_RealDiv"] = Module["asm"]["pa"]).apply(null, arguments); - }; - var _Relu = Module["_Relu"] = function() { - return (_Relu = Module["_Relu"] = Module["asm"]["qa"]).apply(null, arguments); - }; - var _Relu6 = Module["_Relu6"] = function() { - return (_Relu6 = Module["_Relu6"] = Module["asm"]["ra"]).apply(null, arguments); - }; - var _ResizeBilinear = Module["_ResizeBilinear"] = function() { - return (_ResizeBilinear = Module["_ResizeBilinear"] = Module["asm"]["sa"]).apply(null, arguments); - }; - var _Reverse = Module["_Reverse"] = function() { - return (_Reverse = Module["_Reverse"] = Module["asm"]["ta"]).apply(null, arguments); - }; - var _RotateWithOffset = Module["_RotateWithOffset"] = function() { - return (_RotateWithOffset = Module["_RotateWithOffset"] = Module["asm"]["ua"]).apply(null, arguments); - }; - var _Round = Module["_Round"] = function() { - return (_Round = Module["_Round"] = Module["asm"]["va"]).apply(null, arguments); - }; - var _Rsqrt = Module["_Rsqrt"] = function() { - return (_Rsqrt = Module["_Rsqrt"] = Module["asm"]["wa"]).apply(null, arguments); - }; - var _ScatterNd = Module["_ScatterNd"] = function() { - return (_ScatterNd = Module["_ScatterNd"] = Module["asm"]["xa"]).apply(null, arguments); - }; - var _SelectV2 = Module["_SelectV2"] = function() { - return (_SelectV2 = Module["_SelectV2"] = Module["asm"]["ya"]).apply(null, arguments); - }; - var _Sigmoid = Module["_Sigmoid"] = function() { - return (_Sigmoid = Module["_Sigmoid"] = Module["asm"]["za"]).apply(null, arguments); - }; - var _Sin = Module["_Sin"] = function() { - return (_Sin = Module["_Sin"] = Module["asm"]["Aa"]).apply(null, arguments); - }; - var _Softmax = Module["_Softmax"] = function() { - return (_Softmax = Module["_Softmax"] = Module["asm"]["Ba"]).apply(null, arguments); - }; - var _Sqrt = Module["_Sqrt"] = function() { - return (_Sqrt = Module["_Sqrt"] = Module["asm"]["Ca"]).apply(null, arguments); - }; - var _Square = Module["_Square"] = function() { - return (_Square = Module["_Square"] = Module["asm"]["Da"]).apply(null, arguments); - }; - var _SquaredDifference = Module["_SquaredDifference"] = function() { - return (_SquaredDifference = Module["_SquaredDifference"] = Module["asm"]["Ea"]).apply(null, arguments); - }; - var _Step = Module["_Step"] = function() { - return (_Step = Module["_Step"] = Module["asm"]["Fa"]).apply(null, arguments); - }; - var _StridedSlice = Module["_StridedSlice"] = function() { - return (_StridedSlice = Module["_StridedSlice"] = Module["asm"]["Ga"]).apply(null, arguments); - }; - var _Sub = Module["_Sub"] = function() { - return (_Sub = Module["_Sub"] = Module["asm"]["Ha"]).apply(null, arguments); - }; - var _Sum = Module["_Sum"] = function() { - return (_Sum = Module["_Sum"] = Module["asm"]["Ia"]).apply(null, arguments); - }; - var _Tan = Module["_Tan"] = function() { - return (_Tan = Module["_Tan"] = Module["asm"]["Ja"]).apply(null, arguments); - }; - var _Tanh = Module["_Tanh"] = function() { - return (_Tanh = Module["_Tanh"] = Module["asm"]["Ka"]).apply(null, arguments); - }; - var _Tile = Module["_Tile"] = function() { - return (_Tile = Module["_Tile"] = Module["asm"]["La"]).apply(null, arguments); - }; - var _TopK = Module["_TopK"] = function() { - return (_TopK = Module["_TopK"] = Module["asm"]["Ma"]).apply(null, arguments); - }; - var _Transform = Module["_Transform"] = function() { - return (_Transform = Module["_Transform"] = Module["asm"]["Na"]).apply(null, arguments); - }; - var _Transpose = Module["_Transpose"] = function() { - return (_Transpose = Module["_Transpose"] = Module["asm"]["Oa"]).apply(null, arguments); - }; - var __FusedMatMul = Module["__FusedMatMul"] = function() { - return (__FusedMatMul = Module["__FusedMatMul"] = Module["asm"]["Pa"]).apply(null, arguments); - }; - var _malloc = Module["_malloc"] = function() { - return (_malloc = Module["_malloc"] = Module["asm"]["Qa"]).apply(null, arguments); - }; - var _free = Module["_free"] = function() { - return (_free = Module["_free"] = Module["asm"]["Ra"]).apply(null, arguments); - }; - var ___errno_location = Module["___errno_location"] = function() { - return (___errno_location = Module["___errno_location"] = Module["asm"]["Sa"]).apply(null, arguments); - }; - var stackSave = Module["stackSave"] = function() { - return (stackSave = Module["stackSave"] = Module["asm"]["Ta"]).apply(null, arguments); - }; - var stackRestore = Module["stackRestore"] = function() { - return (stackRestore = Module["stackRestore"] = Module["asm"]["Ua"]).apply(null, arguments); - }; - var stackAlloc = Module["stackAlloc"] = function() { - return (stackAlloc = Module["stackAlloc"] = Module["asm"]["Va"]).apply(null, arguments); - }; - Module["cwrap"] = cwrap; - var calledRun; - function ExitStatus(status) { - this.name = "ExitStatus"; - this.message = "Program terminated with exit(" + status + ")"; - this.status = status; - } - dependenciesFulfilled = function runCaller() { - if (!calledRun) - run(); - if (!calledRun) - dependenciesFulfilled = runCaller; - }; - function run(args) { - args = args || arguments_; - if (runDependencies > 0) { - return; - } - preRun(); - if (runDependencies > 0) { - return; - } - function doRun() { - if (calledRun) - return; - calledRun = true; - Module["calledRun"] = true; - if (ABORT) - return; - initRuntime(); - preMain(); - readyPromiseResolve(Module); - if (Module["onRuntimeInitialized"]) - Module["onRuntimeInitialized"](); - postRun(); - } - if (Module["setStatus"]) { - Module["setStatus"]("Running..."); - setTimeout(function() { - setTimeout(function() { - Module["setStatus"](""); - }, 1); - doRun(); - }, 1); - } else { - doRun(); - } - } - Module["run"] = run; - if (Module["preInit"]) { - if (typeof Module["preInit"] == "function") - Module["preInit"] = [Module["preInit"]]; - while (Module["preInit"].length > 0) { - Module["preInit"].pop()(); - } - } - run(); - return WasmBackendModule2.ready; - }; - }(); - if (typeof exports === "object" && typeof module === "object") - module.exports = WasmBackendModule; - else if (typeof define === "function" && define["amd"]) - define([], function() { - return WasmBackendModule; - }); - else if (typeof exports === "object") - exports["WasmBackendModule"] = WasmBackendModule; - } -}); -var version = "3.9.0"; -var version2 = "3.9.0"; -var version3 = "3.9.0"; -var version4 = "3.9.0"; -var version5 = "3.9.0"; -var version6 = "3.9.0"; -var version7 = "3.9.0"; -var version8 = "3.9.0"; -var EPSILON_FLOAT32 = 1e-7; -var EPSILON_FLOAT16 = 1e-4; -var DataStorage = class { - constructor(backend22, dataMover) { - this.backend = backend22; - this.dataMover = dataMover; - this.data = new WeakMap(); - this.dataIdsCount = 0; - } - get(dataId) { - if (!this.data.has(dataId)) { - this.dataMover.moveData(this.backend, dataId); + return e.isNegative() ? this.neg().div(e.neg()) : this.neg().div(e).neg(); + if (e.isNegative()) + return this.div(e.neg()).neg(); + s = so; } - return this.data.get(dataId); + for (o = this; o.gte(e); ) { + n = Math.max(1, Math.floor(o.toNumber() / e.toNumber())); + for (var i = Math.ceil(Math.log(n) / Math.LN2), l = i <= 48 ? 1 : Qh(2, i - 48), u = oo(n), c = u.mul(e); c.isNegative() || c.gt(o); ) + n -= l, u = oo(n, this.unsigned), c = u.mul(e); + u.isZero() && (u = Jc), s = s.add(u), o = o.sub(c); + } + return s; + }; + be.div = be.divide; + be.modulo = function(e) { + if (En(e) || (e = bs(e)), no) { + var t = (this.unsigned ? no.rem_u : no.rem_s)(this.low, this.high, e.low, e.high); + return Wt(t, no.get_high(), this.unsigned); + } + return this.sub(this.div(e).mul(e)); + }; + be.mod = be.modulo; + be.rem = be.modulo; + be.not = function() { + return Wt(~this.low, ~this.high, this.unsigned); + }; + be.and = function(e) { + return En(e) || (e = bs(e)), Wt(this.low & e.low, this.high & e.high, this.unsigned); + }; + be.or = function(e) { + return En(e) || (e = bs(e)), Wt(this.low | e.low, this.high | e.high, this.unsigned); + }; + be.xor = function(e) { + return En(e) || (e = bs(e)), Wt(this.low ^ e.low, this.high ^ e.high, this.unsigned); + }; + be.shiftLeft = function(e) { + return En(e) && (e = e.toInt()), (e &= 63) === 0 ? this : e < 32 ? Wt(this.low << e, this.high << e | this.low >>> 32 - e, this.unsigned) : Wt(0, this.low << e - 32, this.unsigned); + }; + be.shl = be.shiftLeft; + be.shiftRight = function(e) { + return En(e) && (e = e.toInt()), (e &= 63) === 0 ? this : e < 32 ? Wt(this.low >>> e | this.high << 32 - e, this.high >> e, this.unsigned) : Wt(this.high >> e - 32, this.high >= 0 ? 0 : -1, this.unsigned); + }; + be.shr = be.shiftRight; + be.shiftRightUnsigned = function(e) { + if (En(e) && (e = e.toInt()), e &= 63, e === 0) + return this; + var t = this.high; + if (e < 32) { + var n = this.low; + return Wt(n >>> e | t << 32 - e, t >>> e, this.unsigned); + } else + return e === 32 ? Wt(t, 0, this.unsigned) : Wt(t >>> e - 32, 0, this.unsigned); + }; + be.shru = be.shiftRightUnsigned; + be.shr_u = be.shiftRightUnsigned; + be.toSigned = function() { + return this.unsigned ? Wt(this.low, this.high, false) : this; + }; + be.toUnsigned = function() { + return this.unsigned ? this : Wt(this.low, this.high, true); + }; + be.toBytes = function(e) { + return e ? this.toBytesLE() : this.toBytesBE(); + }; + be.toBytesLE = function() { + var e = this.high, t = this.low; + return [t & 255, t >>> 8 & 255, t >>> 16 & 255, t >>> 24, e & 255, e >>> 8 & 255, e >>> 16 & 255, e >>> 24]; + }; + be.toBytesBE = function() { + var e = this.high, t = this.low; + return [e >>> 24, e >>> 16 & 255, e >>> 8 & 255, e & 255, t >>> 24, t >>> 16 & 255, t >>> 8 & 255, t & 255]; + }; + Vt.fromBytes = function(e, t, n) { + return n ? Vt.fromBytesLE(e, t) : Vt.fromBytesBE(e, t); + }; + Vt.fromBytesLE = function(e, t) { + return new Vt(e[0] | e[1] << 8 | e[2] << 16 | e[3] << 24, e[4] | e[5] << 8 | e[6] << 16 | e[7] << 24, t); + }; + Vt.fromBytesBE = function(e, t) { + return new Vt(e[4] << 24 | e[5] << 16 | e[6] << 8 | e[7], e[0] << 24 | e[1] << 16 | e[2] << 8 | e[3], t); + }; +}); +var H1 = Ut(() => { +}); +var NN = Ut((IN, Vk) => { + (function(r, e, t) { + function n(i) { + var l = this, u = a(); + 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(i), l.s0 < 0 && (l.s0 += 1), l.s1 -= u(i), l.s1 < 0 && (l.s1 += 1), l.s2 -= u(i), l.s2 < 0 && (l.s2 += 1), u = null; + } + function o(i, l) { + return l.c = i.c, l.s0 = i.s0, l.s1 = i.s1, l.s2 = i.s2, l; + } + function s(i, l) { + var u = new n(i), c = l && l.state, p = u.next; + return p.int32 = function() { + return u.next() * 4294967296 | 0; + }, p.double = function() { + return p() + (p() * 2097152 | 0) * 11102230246251565e-32; + }, p.quick = p, c && (typeof c == "object" && o(c, u), p.state = function() { + return o(u, {}); + }), p; + } + function a() { + var i = 4022871197, l = function(u) { + u = u.toString(); + for (var c = 0; c < u.length; c++) { + i += u.charCodeAt(c); + var p = 0.02519603282416938 * i; + i = p >>> 0, p -= i, p *= i, i = p >>> 0, p -= i, i += p * 4294967296; + } + return (i >>> 0) * 23283064365386963e-26; + }; + return l; + } + e && e.exports ? e.exports = s : t && t.amd ? t(function() { + return s; + }) : this.alea = s; + })(IN, typeof Vk == "object" && Vk, typeof define == "function" && define); +}); +var EN = Ut((TN, Wk) => { + (function(r, e, t) { + function n(a) { + var i = this, l = ""; + i.x = 0, i.y = 0, i.z = 0, i.w = 0, i.next = function() { + var c = i.x ^ i.x << 11; + return i.x = i.y, i.y = i.z, i.z = i.w, i.w ^= i.w >>> 19 ^ c ^ c >>> 8; + }, a === (a | 0) ? i.x = a : l += a; + for (var u = 0; u < l.length + 64; u++) + i.x ^= l.charCodeAt(u) | 0, i.next(); + } + function o(a, i) { + return i.x = a.x, i.y = a.y, i.z = a.z, i.w = a.w, i; + } + function s(a, i) { + var l = new n(a), u = i && i.state, c = function() { + return (l.next() >>> 0) / 4294967296; + }; + return c.double = function() { + do + var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21); + while (f === 0); + return f; + }, c.int32 = l.next, c.quick = c, u && (typeof u == "object" && o(u, l), c.state = function() { + return o(l, {}); + }), c; + } + e && e.exports ? e.exports = s : t && t.amd ? t(function() { + return s; + }) : this.xor128 = s; + })(TN, typeof Wk == "object" && Wk, typeof define == "function" && define); +}); +var $N = Ut((AN, jk) => { + (function(r, e, t) { + function n(a) { + var i = this, l = ""; + i.next = function() { + var c = i.x ^ i.x >>> 2; + return i.x = i.y, i.y = i.z, i.z = i.w, i.w = i.v, (i.d = i.d + 362437 | 0) + (i.v = i.v ^ i.v << 4 ^ (c ^ c << 1)) | 0; + }, i.x = 0, i.y = 0, i.z = 0, i.w = 0, i.v = 0, a === (a | 0) ? i.x = a : l += a; + for (var u = 0; u < l.length + 64; u++) + i.x ^= l.charCodeAt(u) | 0, u == l.length && (i.d = i.x << 10 ^ i.x >>> 4), i.next(); + } + function o(a, i) { + return i.x = a.x, i.y = a.y, i.z = a.z, i.w = a.w, i.v = a.v, i.d = a.d, i; + } + function s(a, i) { + var l = new n(a), u = i && i.state, c = function() { + return (l.next() >>> 0) / 4294967296; + }; + return c.double = function() { + do + var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21); + while (f === 0); + return f; + }, c.int32 = l.next, c.quick = c, u && (typeof u == "object" && o(u, l), c.state = function() { + return o(l, {}); + }), c; + } + e && e.exports ? e.exports = s : t && t.amd ? t(function() { + return s; + }) : this.xorwow = s; + })(AN, typeof jk == "object" && jk, typeof define == "function" && define); +}); +var RN = Ut((DN, Gk) => { + (function(r, e, t) { + function n(a) { + var i = this; + i.next = function() { + var u = i.x, c = i.i, p, m, f; + return p = u[c], p ^= p >>> 7, m = p ^ p << 24, p = u[c + 1 & 7], m ^= p ^ p >>> 10, p = u[c + 3 & 7], m ^= p ^ p >>> 3, p = u[c + 4 & 7], m ^= p ^ p << 7, p = u[c + 7 & 7], p = p ^ p << 13, m ^= p ^ p << 9, u[c] = m, i.i = c + 1 & 7, m; + }; + function l(u, c) { + var p, m, f = []; + if (c === (c | 0)) + m = f[0] = c; + else + for (c = "" + c, p = 0; p < c.length; ++p) + f[p & 7] = f[p & 7] << 15 ^ c.charCodeAt(p) + f[p + 1 & 7] << 13; + for (; f.length < 8; ) + f.push(0); + for (p = 0; p < 8 && f[p] === 0; ++p) + ; + for (p == 8 ? m = f[7] = -1 : m = f[p], u.x = f, u.i = 0, p = 256; p > 0; --p) + u.next(); + } + l(i, a); + } + function o(a, i) { + return i.x = a.x.slice(), i.i = a.i, i; + } + function s(a, i) { + a == null && (a = +new Date()); + var l = new n(a), u = i && i.state, c = function() { + return (l.next() >>> 0) / 4294967296; + }; + return c.double = function() { + do + var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21); + while (f === 0); + return f; + }, c.int32 = l.next, c.quick = c, u && (u.x && o(u, l), c.state = function() { + return o(l, {}); + }), c; + } + e && e.exports ? e.exports = s : t && t.amd ? t(function() { + return s; + }) : this.xorshift7 = s; + })(DN, typeof Gk == "object" && Gk, typeof define == "function" && define); +}); +var ON = Ut((FN, Uk) => { + (function(r, e, t) { + function n(a) { + var i = this; + i.next = function() { + var u = i.w, c = i.X, p = i.i, m, f; + return i.w = u = u + 1640531527 | 0, f = c[p + 34 & 127], m = c[p = p + 1 & 127], f ^= f << 13, m ^= m << 17, f ^= f >>> 15, m ^= m >>> 12, f = c[p] = f ^ m, i.i = p, f + (u ^ u >>> 16) | 0; + }; + function l(u, c) { + var p, m, f, d, h, g = [], y = 128; + for (c === (c | 0) ? (m = c, c = null) : (c = c + "\0", m = 0, y = Math.max(y, c.length)), f = 0, d = -32; d < y; ++d) + c && (m ^= c.charCodeAt((d + 32) % c.length)), d === 0 && (h = m), m ^= m << 10, m ^= m >>> 15, m ^= m << 4, m ^= m >>> 13, d >= 0 && (h = h + 1640531527 | 0, p = g[d & 127] ^= m + h, f = p == 0 ? f + 1 : 0); + for (f >= 128 && (g[(c && c.length || 0) & 127] = -1), f = 127, d = 4 * 128; d > 0; --d) + m = g[f + 34 & 127], p = g[f = f + 1 & 127], m ^= m << 13, p ^= p << 17, m ^= m >>> 15, p ^= p >>> 12, g[f] = m ^ p; + u.w = h, u.X = g, u.i = f; + } + l(i, a); + } + function o(a, i) { + return i.i = a.i, i.w = a.w, i.X = a.X.slice(), i; + } + function s(a, i) { + a == null && (a = +new Date()); + var l = new n(a), u = i && i.state, c = function() { + return (l.next() >>> 0) / 4294967296; + }; + return c.double = function() { + do + var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21); + while (f === 0); + return f; + }, c.int32 = l.next, c.quick = c, u && (u.X && o(u, l), c.state = function() { + return o(l, {}); + }), c; + } + e && e.exports ? e.exports = s : t && t.amd ? t(function() { + return s; + }) : this.xor4096 = s; + })(FN, typeof Uk == "object" && Uk, typeof define == "function" && define); +}); +var MN = Ut((PN, Hk) => { + (function(r, e, t) { + function n(a) { + var i = this, l = ""; + i.next = function() { + var c = i.b, p = i.c, m = i.d, f = i.a; + return c = c << 25 ^ c >>> 7 ^ p, p = p - m | 0, m = m << 24 ^ m >>> 8 ^ f, f = f - c | 0, i.b = c = c << 20 ^ c >>> 12 ^ p, i.c = p = p - m | 0, i.d = m << 16 ^ p >>> 16 ^ f, i.a = f - c | 0; + }, i.a = 0, i.b = 0, i.c = 2654435769 | 0, i.d = 1367130551, a === Math.floor(a) ? (i.a = a / 4294967296 | 0, i.b = a | 0) : l += a; + for (var u = 0; u < l.length + 20; u++) + i.b ^= l.charCodeAt(u) | 0, i.next(); + } + function o(a, i) { + return i.a = a.a, i.b = a.b, i.c = a.c, i.d = a.d, i; + } + function s(a, i) { + var l = new n(a), u = i && i.state, c = function() { + return (l.next() >>> 0) / 4294967296; + }; + return c.double = function() { + do + var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21); + while (f === 0); + return f; + }, c.int32 = l.next, c.quick = c, u && (typeof u == "object" && o(u, l), c.state = function() { + return o(l, {}); + }), c; + } + e && e.exports ? e.exports = s : t && t.amd ? t(function() { + return s; + }) : this.tychei = s; + })(PN, typeof Hk == "object" && Hk, typeof define == "function" && define); +}); +var qk = Ut(() => { +}); +var LN = Ut((X_e, wg) => { + (function(r, e) { + var t = this, n = 256, o = 6, s = 52, a = "random", i = e.pow(n, o), l = e.pow(2, s), u = l * 2, c = n - 1, p; + function m(x, k, C) { + var A = []; + k = k == true ? { entropy: true } : k || {}; + var $ = g(h(k.entropy ? [x, w(r)] : x == null ? y() : x, 3), A), R = new f(A), P = function() { + for (var M = R.g(o), V = i, W = 0; M < l; ) + M = (M + W) * n, V *= n, W = R.g(1); + for (; M >= u; ) + M /= 2, V /= 2, W >>>= 1; + return (M + W) / V; + }; + return P.int32 = function() { + return R.g(4) | 0; + }, P.quick = function() { + return R.g(4) / 4294967296; + }, P.double = P, g(w(R.S), r), (k.pass || C || function(M, V, W, G) { + return G && (G.S && d(G, R), M.state = function() { + return d(R, {}); + }), W ? (e[a] = M, V) : M; + })(P, $, "global" in k ? k.global : this == e, k.state); + } + e["seed" + a] = m; + function f(x) { + var k, C = x.length, A = this, $ = 0, R = A.i = A.j = 0, P = A.S = []; + for (C || (x = [C++]); $ < n; ) + P[$] = $++; + for ($ = 0; $ < n; $++) + P[$] = P[R = c & R + x[$ % C] + (k = P[$])], P[R] = k; + (A.g = function(M) { + for (var V, W = 0, G = A.i, U = A.j, H = A.S; M--; ) + V = H[G = c & G + 1], W = W * n + H[c & (H[G] = H[U = c & U + V]) + (H[U] = V)]; + return A.i = G, A.j = U, W; + })(n); + } + function d(x, k) { + return k.i = x.i, k.j = x.j, k.S = x.S.slice(), k; + } + function h(x, k) { + var C = [], A = typeof x, $; + if (k && A == "object") + for ($ in x) + try { + C.push(h(x[$], k - 1)); + } catch (R) { + } + return C.length ? C : A == "string" ? x : x + "\0"; + } + function g(x, k) { + for (var C = x + "", A, $ = 0; $ < C.length; ) + k[c & $] = c & (A ^= k[c & $] * 19) + C.charCodeAt($++); + return w(k); + } + function y() { + try { + var x; + return p && (x = p.randomBytes) ? x = x(n) : (x = new Uint8Array(n), (t.crypto || t.msCrypto).getRandomValues(x)), w(x); + } catch (A) { + var k = t.navigator, C = k && k.plugins; + return [+new Date(), t, C, t.screen, w(r)]; + } + } + function w(x) { + return String.fromCharCode.apply(0, x); + } + if (g(e.random(), r), typeof wg == "object" && wg.exports) { + wg.exports = m; + try { + p = qk(); + } catch (x) { + } + } else + typeof define == "function" && define.amd && define(function() { + return m; + }); + })([], Math); +}); +var Kk = Ut((Y_e, zN) => { + var $H = NN(), DH = EN(), RH = $N(), FH = RN(), OH = ON(), PH = MN(), du = LN(); + du.alea = $H; + du.xor128 = DH; + du.xorwow = RH; + du.xorshift7 = FH; + du.xor4096 = OH; + du.tychei = PH; + zN.exports = du; +}); +var w$ = Ut((b$, Gv) => { + (function(r, e, t) { + function n(i) { + var l = this, u = a(); + 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(i), l.s0 < 0 && (l.s0 += 1), l.s1 -= u(i), l.s1 < 0 && (l.s1 += 1), l.s2 -= u(i), l.s2 < 0 && (l.s2 += 1), u = null; + } + function o(i, l) { + return l.c = i.c, l.s0 = i.s0, l.s1 = i.s1, l.s2 = i.s2, l; + } + function s(i, l) { + var u = new n(i), c = l && l.state, p = u.next; + return p.int32 = function() { + return u.next() * 4294967296 | 0; + }, p.double = function() { + return p() + (p() * 2097152 | 0) * 11102230246251565e-32; + }, p.quick = p, c && (typeof c == "object" && o(c, u), p.state = function() { + return o(u, {}); + }), p; + } + function a() { + var i = 4022871197, l = function(u) { + u = String(u); + for (var c = 0; c < u.length; c++) { + i += u.charCodeAt(c); + var p = 0.02519603282416938 * i; + i = p >>> 0, p -= i, p *= i, i = p >>> 0, p -= i, i += p * 4294967296; + } + return (i >>> 0) * 23283064365386963e-26; + }; + return l; + } + e && e.exports ? e.exports = s : t && t.amd ? t(function() { + return s; + }) : this.alea = s; + })(b$, typeof Gv == "object" && Gv, typeof define == "function" && define); +}); +var _$ = Ut((k$, Uv) => { + (function(r, e, t) { + function n(a) { + var i = this, l = ""; + i.x = 0, i.y = 0, i.z = 0, i.w = 0, i.next = function() { + var c = i.x ^ i.x << 11; + return i.x = i.y, i.y = i.z, i.z = i.w, i.w ^= i.w >>> 19 ^ c ^ c >>> 8; + }, a === (a | 0) ? i.x = a : l += a; + for (var u = 0; u < l.length + 64; u++) + i.x ^= l.charCodeAt(u) | 0, i.next(); + } + function o(a, i) { + return i.x = a.x, i.y = a.y, i.z = a.z, i.w = a.w, i; + } + function s(a, i) { + var l = new n(a), u = i && i.state, c = function() { + return (l.next() >>> 0) / 4294967296; + }; + return c.double = function() { + do + var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21); + while (f === 0); + return f; + }, c.int32 = l.next, c.quick = c, u && (typeof u == "object" && o(u, l), c.state = function() { + return o(l, {}); + }), c; + } + e && e.exports ? e.exports = s : t && t.amd ? t(function() { + return s; + }) : this.xor128 = s; + })(k$, typeof Uv == "object" && Uv, typeof define == "function" && define); +}); +var C$ = Ut((v$, Hv) => { + (function(r, e, t) { + function n(a) { + var i = this, l = ""; + i.next = function() { + var c = i.x ^ i.x >>> 2; + return i.x = i.y, i.y = i.z, i.z = i.w, i.w = i.v, (i.d = i.d + 362437 | 0) + (i.v = i.v ^ i.v << 4 ^ (c ^ c << 1)) | 0; + }, i.x = 0, i.y = 0, i.z = 0, i.w = 0, i.v = 0, a === (a | 0) ? i.x = a : l += a; + for (var u = 0; u < l.length + 64; u++) + i.x ^= l.charCodeAt(u) | 0, u == l.length && (i.d = i.x << 10 ^ i.x >>> 4), i.next(); + } + function o(a, i) { + return i.x = a.x, i.y = a.y, i.z = a.z, i.w = a.w, i.v = a.v, i.d = a.d, i; + } + function s(a, i) { + var l = new n(a), u = i && i.state, c = function() { + return (l.next() >>> 0) / 4294967296; + }; + return c.double = function() { + do + var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21); + while (f === 0); + return f; + }, c.int32 = l.next, c.quick = c, u && (typeof u == "object" && o(u, l), c.state = function() { + return o(l, {}); + }), c; + } + e && e.exports ? e.exports = s : t && t.amd ? t(function() { + return s; + }) : this.xorwow = s; + })(v$, typeof Hv == "object" && Hv, typeof define == "function" && define); +}); +var I$ = Ut((S$, qv) => { + (function(r, e, t) { + function n(a) { + var i = this; + i.next = function() { + var u = i.x, c = i.i, p, m, f; + return p = u[c], p ^= p >>> 7, m = p ^ p << 24, p = u[c + 1 & 7], m ^= p ^ p >>> 10, p = u[c + 3 & 7], m ^= p ^ p >>> 3, p = u[c + 4 & 7], m ^= p ^ p << 7, p = u[c + 7 & 7], p = p ^ p << 13, m ^= p ^ p << 9, u[c] = m, i.i = c + 1 & 7, m; + }; + function l(u, c) { + var p, m, f = []; + if (c === (c | 0)) + m = f[0] = c; + else + for (c = "" + c, p = 0; p < c.length; ++p) + f[p & 7] = f[p & 7] << 15 ^ c.charCodeAt(p) + f[p + 1 & 7] << 13; + for (; f.length < 8; ) + f.push(0); + for (p = 0; p < 8 && f[p] === 0; ++p) + ; + for (p == 8 ? m = f[7] = -1 : m = f[p], u.x = f, u.i = 0, p = 256; p > 0; --p) + u.next(); + } + l(i, a); + } + function o(a, i) { + return i.x = a.x.slice(), i.i = a.i, i; + } + function s(a, i) { + a == null && (a = +new Date()); + var l = new n(a), u = i && i.state, c = function() { + return (l.next() >>> 0) / 4294967296; + }; + return c.double = function() { + do + var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21); + while (f === 0); + return f; + }, c.int32 = l.next, c.quick = c, u && (u.x && o(u, l), c.state = function() { + return o(l, {}); + }), c; + } + e && e.exports ? e.exports = s : t && t.amd ? t(function() { + return s; + }) : this.xorshift7 = s; + })(S$, typeof qv == "object" && qv, typeof define == "function" && define); +}); +var T$ = Ut((N$, Kv) => { + (function(r, e, t) { + function n(a) { + var i = this; + i.next = function() { + var u = i.w, c = i.X, p = i.i, m, f; + return i.w = u = u + 1640531527 | 0, f = c[p + 34 & 127], m = c[p = p + 1 & 127], f ^= f << 13, m ^= m << 17, f ^= f >>> 15, m ^= m >>> 12, f = c[p] = f ^ m, i.i = p, f + (u ^ u >>> 16) | 0; + }; + function l(u, c) { + var p, m, f, d, h, g = [], y = 128; + for (c === (c | 0) ? (m = c, c = null) : (c = c + "\0", m = 0, y = Math.max(y, c.length)), f = 0, d = -32; d < y; ++d) + c && (m ^= c.charCodeAt((d + 32) % c.length)), d === 0 && (h = m), m ^= m << 10, m ^= m >>> 15, m ^= m << 4, m ^= m >>> 13, d >= 0 && (h = h + 1640531527 | 0, p = g[d & 127] ^= m + h, f = p == 0 ? f + 1 : 0); + for (f >= 128 && (g[(c && c.length || 0) & 127] = -1), f = 127, d = 4 * 128; d > 0; --d) + m = g[f + 34 & 127], p = g[f = f + 1 & 127], m ^= m << 13, p ^= p << 17, m ^= m >>> 15, p ^= p >>> 12, g[f] = m ^ p; + u.w = h, u.X = g, u.i = f; + } + l(i, a); + } + function o(a, i) { + return i.i = a.i, i.w = a.w, i.X = a.X.slice(), i; + } + function s(a, i) { + a == null && (a = +new Date()); + var l = new n(a), u = i && i.state, c = function() { + return (l.next() >>> 0) / 4294967296; + }; + return c.double = function() { + do + var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21); + while (f === 0); + return f; + }, c.int32 = l.next, c.quick = c, u && (u.X && o(u, l), c.state = function() { + return o(l, {}); + }), c; + } + e && e.exports ? e.exports = s : t && t.amd ? t(function() { + return s; + }) : this.xor4096 = s; + })(N$, typeof Kv == "object" && Kv, typeof define == "function" && define); +}); +var A$ = Ut((E$, Xv) => { + (function(r, e, t) { + function n(a) { + var i = this, l = ""; + i.next = function() { + var c = i.b, p = i.c, m = i.d, f = i.a; + return c = c << 25 ^ c >>> 7 ^ p, p = p - m | 0, m = m << 24 ^ m >>> 8 ^ f, f = f - c | 0, i.b = c = c << 20 ^ c >>> 12 ^ p, i.c = p = p - m | 0, i.d = m << 16 ^ p >>> 16 ^ f, i.a = f - c | 0; + }, i.a = 0, i.b = 0, i.c = 2654435769 | 0, i.d = 1367130551, a === Math.floor(a) ? (i.a = a / 4294967296 | 0, i.b = a | 0) : l += a; + for (var u = 0; u < l.length + 20; u++) + i.b ^= l.charCodeAt(u) | 0, i.next(); + } + function o(a, i) { + return i.a = a.a, i.b = a.b, i.c = a.c, i.d = a.d, i; + } + function s(a, i) { + var l = new n(a), u = i && i.state, c = function() { + return (l.next() >>> 0) / 4294967296; + }; + return c.double = function() { + do + var p = l.next() >>> 11, m = (l.next() >>> 0) / 4294967296, f = (p + m) / (1 << 21); + while (f === 0); + return f; + }, c.int32 = l.next, c.quick = c, u && (typeof u == "object" && o(u, l), c.state = function() { + return o(l, {}); + }), c; + } + e && e.exports ? e.exports = s : t && t.amd ? t(function() { + return s; + }) : this.tychei = s; + })(E$, typeof Xv == "object" && Xv, typeof define == "function" && define); +}); +var D$ = Ut(($$, Ex) => { + (function(r, e, t) { + var n = 256, o = 6, s = 52, a = "random", i = t.pow(n, o), l = t.pow(2, s), u = l * 2, c = n - 1, p; + function m(x, k, C) { + var A = []; + k = k == true ? { entropy: true } : k || {}; + var $ = g(h(k.entropy ? [x, w(e)] : x == null ? y() : x, 3), A), R = new f(A), P = function() { + for (var M = R.g(o), V = i, W = 0; M < l; ) + M = (M + W) * n, V *= n, W = R.g(1); + for (; M >= u; ) + M /= 2, V /= 2, W >>>= 1; + return (M + W) / V; + }; + return P.int32 = function() { + return R.g(4) | 0; + }, P.quick = function() { + return R.g(4) / 4294967296; + }, P.double = P, g(w(R.S), e), (k.pass || C || function(M, V, W, G) { + return G && (G.S && d(G, R), M.state = function() { + return d(R, {}); + }), W ? (t[a] = M, V) : M; + })(P, $, "global" in k ? k.global : this == t, k.state); + } + function f(x) { + var k, C = x.length, A = this, $ = 0, R = A.i = A.j = 0, P = A.S = []; + for (C || (x = [C++]); $ < n; ) + P[$] = $++; + for ($ = 0; $ < n; $++) + P[$] = P[R = c & R + x[$ % C] + (k = P[$])], P[R] = k; + (A.g = function(M) { + for (var V, W = 0, G = A.i, U = A.j, H = A.S; M--; ) + V = H[G = c & G + 1], W = W * n + H[c & (H[G] = H[U = c & U + V]) + (H[U] = V)]; + return A.i = G, A.j = U, W; + })(n); + } + function d(x, k) { + return k.i = x.i, k.j = x.j, k.S = x.S.slice(), k; + } + function h(x, k) { + var C = [], A = typeof x, $; + if (k && A == "object") + for ($ in x) + try { + C.push(h(x[$], k - 1)); + } catch (R) { + } + return C.length ? C : A == "string" ? x : x + "\0"; + } + function g(x, k) { + for (var C = x + "", A, $ = 0; $ < C.length; ) + k[c & $] = c & (A ^= k[c & $] * 19) + C.charCodeAt($++); + return w(k); + } + function y() { + try { + var x; + return p && (x = p.randomBytes) ? x = x(n) : (x = new Uint8Array(n), (r.crypto || r.msCrypto).getRandomValues(x)), w(x); + } catch (A) { + var k = r.navigator, C = k && k.plugins; + return [+new Date(), r, C, r.screen, w(e)]; + } + } + function w(x) { + return String.fromCharCode.apply(0, x); + } + if (g(t.random(), e), typeof Ex == "object" && Ex.exports) { + Ex.exports = m; + try { + p = qk(); + } catch (x) { + } + } else + typeof define == "function" && define.amd ? define(function() { + return m; + }) : t["seed" + a] = m; + })(typeof self != "undefined" ? self : $$, [], Math); +}); +var Yv = Ut((Pet, R$) => { + var d7 = w$(), h7 = _$(), g7 = C$(), x7 = I$(), y7 = T$(), b7 = A$(), Ou = D$(); + Ou.alea = d7; + Ou.xor128 = h7; + Ou.xorwow = g7; + Ou.xorshift7 = x7; + Ou.xor4096 = y7; + Ou.tychei = b7; + R$.exports = Ou; +}); +var Zv = Ut(() => { +}); +var hm = Ut(() => { +}); +var qV = Ut(() => { +}); +var KV = Ut(() => { +}); +var XV = Ut((Oy, xI) => { + var gI = function() { + var r = typeof document != "undefined" && document.currentScript ? document.currentScript.src : void 0; + return typeof __filename != "undefined" && (r = r || __filename), function(e) { + e = e || {}; + function t() { + return Q.buffer != Ue && ur(Q.buffer), pt; + } + function n() { + return Q.buffer != Ue && ur(Q.buffer), ft; + } + function o() { + return Q.buffer != Ue && ur(Q.buffer), Qt; + } + function s() { + return Q.buffer != Ue && ur(Q.buffer), pn; + } + function a() { + return Q.buffer != Ue && ur(Q.buffer), Zn; + } + var i = typeof e != "undefined" ? e : {}, l, u; + i.ready = new Promise(function(N, D) { + l = N, u = D; + }); + var c = {}, p; + for (p in i) + i.hasOwnProperty(p) && (c[p] = i[p]); + var m = [], f = "./this.program", d = function(N, D) { + throw D; + }, h = false, g = false, y = false, w = false; + h = typeof window == "object", g = typeof importScripts == "function", y = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string", w = !h && !y && !g; + var x = i.ENVIRONMENT_IS_PTHREAD || false; + x && (Ue = i.buffer); + var k = ""; + function C(N) { + return i.locateFile ? i.locateFile(N, k) : k + N; + } + var A, $, R, P, M, V; + if (y) { + g ? k = hm().dirname(k) + "/" : k = __dirname + "/", A = function(D, B) { + return M || (M = pc("fs")), V || (V = hm()), D = V.normalize(D), M.readFileSync(D, B ? null : "utf8"); + }, R = function(D) { + var B = A(D, true); + return B.buffer || (B = new Uint8Array(B)), fe(B.buffer), B; + }, process.argv.length > 1 && (f = process.argv[1].replace(/\\/g, "/")), m = process.argv.slice(2), process.on("uncaughtException", function(N) { + if (!(N instanceof Im)) + throw N; + }), process.on("unhandledRejection", Ci), d = function(N) { + process.exit(N); + }, i.inspect = function() { + return "[Emscripten Module object]"; + }; + var W; + try { + W = qV(); + } catch (N) { + throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'), N; + } + global.Worker = W.Worker; + } else + w ? (typeof read != "undefined" && (A = function(D) { + return read(D); + }), R = function(D) { + var B; + return typeof readbuffer == "function" ? new Uint8Array(readbuffer(D)) : (B = read(D, "binary"), fe(typeof B == "object"), B); + }, typeof scriptArgs != "undefined" ? m = scriptArgs : typeof arguments != "undefined" && (m = arguments), typeof quit == "function" && (d = function(N) { + quit(N); + }), typeof print != "undefined" && (typeof console == "undefined" && (console = {}), console.log = print, console.warn = console.error = typeof printErr != "undefined" ? printErr : print)) : (h || g) && (g ? k = self.location.href : typeof document != "undefined" && document.currentScript && (k = document.currentScript.src), typeof r != "undefined" && r && (k = r), k.indexOf("blob:") !== 0 ? k = k.substr(0, k.lastIndexOf("/") + 1) : k = "", y ? (A = function(D, B) { + return M || (M = pc("fs")), V || (V = hm()), D = V.normalize(D), M.readFileSync(D, B ? null : "utf8"); + }, R = function(D) { + var B = A(D, true); + return B.buffer || (B = new Uint8Array(B)), fe(B.buffer), B; + }) : (A = function(N) { + var D = new XMLHttpRequest(); + return D.open("GET", N, false), D.send(null), D.responseText; + }, g && (R = function(N) { + var D = new XMLHttpRequest(); + return D.open("GET", N, false), D.responseType = "arraybuffer", D.send(null), new Uint8Array(D.response); + }), $ = function(N, D, B) { + var q = new XMLHttpRequest(); + q.open("GET", N, true), q.responseType = "arraybuffer", q.onload = function() { + if (q.status == 200 || q.status == 0 && q.response) { + D(q.response); + return; + } + B(); + }, q.onerror = B, q.send(null); + }), P = function(N) { + document.title = N; + }); + y && typeof performance == "undefined" && (global.performance = KV().performance); + var G = i.print || console.log.bind(console), U = i.printErr || console.warn.bind(console); + for (p in c) + c.hasOwnProperty(p) && (i[p] = c[p]); + c = null, i.arguments && (m = i.arguments), i.thisProgram && (f = i.thisProgram), i.quit && (d = i.quit); + var H = Atomics.load, K = Atomics.store, re = Atomics.compareExchange, X; + i.wasmBinary && (X = i.wasmBinary); + var ne = i.noExitRuntime || true; + typeof WebAssembly != "object" && Ci("no native wasm support detected"); + var Q, se, pe = false, ie; + function fe(N, D) { + N || Ci("Assertion failed: " + D); + } + function de(N) { + var D = i["_" + N]; + return fe(D, "Cannot call unknown function " + N + ", make sure it is exported"), D; + } + function ge(N, D, B, q, ye) { + var he = { string: function(qr) { + var cc = 0; + if (qr != null && qr !== 0) { + var RI = (qr.length << 2) + 1; + cc = ac(RI), qe(qr, cc, RI); + } + return cc; + }, array: function(qr) { + var cc = ac(qr.length); + return It(qr, cc), cc; + } }; + function xe(qr) { + return D === "string" ? Ce(qr) : D === "boolean" ? Boolean(qr) : qr; + } + var Te = de(N), bt = [], kr = 0; + if (q) + for (var hr = 0; hr < q.length; hr++) { + var qa = he[B[hr]]; + qa ? (kr === 0 && (kr = Sm()), bt[hr] = qa(q[hr])) : bt[hr] = q[hr]; + } + var uc = Te.apply(null, bt); + return uc = xe(uc), kr !== 0 && ic(kr), uc; + } + function we(N, D, B, q) { + B = B || []; + var ye = B.every(function(xe) { + return xe === "number"; + }), he = D !== "string"; + return he && ye && !q ? de(N) : function() { + return ge(N, D, B, arguments, q); + }; + } + function $e(N, D, B) { + for (var q = D + B, ye = ""; !(D >= q); ) { + var he = N[D++]; + if (!he) + return ye; + if (!(he & 128)) { + ye += String.fromCharCode(he); + continue; + } + var xe = N[D++] & 63; + if ((he & 224) == 192) { + ye += String.fromCharCode((he & 31) << 6 | xe); + continue; + } + var Te = N[D++] & 63; + if ((he & 240) == 224 ? he = (he & 15) << 12 | xe << 6 | Te : he = (he & 7) << 18 | xe << 12 | Te << 6 | N[D++] & 63, he < 65536) + ye += String.fromCharCode(he); + else { + var bt = he - 65536; + ye += String.fromCharCode(55296 | bt >> 10, 56320 | bt & 1023); + } + } + return ye; + } + function Ce(N, D) { + return N ? $e(n(), N, D) : ""; + } + function Be(N, D, B, q) { + if (!(q > 0)) + return 0; + for (var ye = B, he = B + q - 1, xe = 0; xe < N.length; ++xe) { + var Te = N.charCodeAt(xe); + if (Te >= 55296 && Te <= 57343) { + var bt = N.charCodeAt(++xe); + Te = 65536 + ((Te & 1023) << 10) | bt & 1023; + } + if (Te <= 127) { + if (B >= he) + break; + D[B++] = Te; + } else if (Te <= 2047) { + if (B + 1 >= he) + break; + D[B++] = 192 | Te >> 6, D[B++] = 128 | Te & 63; + } else if (Te <= 65535) { + if (B + 2 >= he) + break; + D[B++] = 224 | Te >> 12, D[B++] = 128 | Te >> 6 & 63, D[B++] = 128 | Te & 63; + } else { + if (B + 3 >= he) + break; + D[B++] = 240 | Te >> 18, D[B++] = 128 | Te >> 12 & 63, D[B++] = 128 | Te >> 6 & 63, D[B++] = 128 | Te & 63; + } + } + return D[B] = 0, B - ye; + } + function qe(N, D, B) { + return Be(N, n(), D, B); + } + function lt(N) { + for (var D = 0, B = 0; B < N.length; ++B) { + var q = N.charCodeAt(B); + q >= 55296 && q <= 57343 && (q = 65536 + ((q & 1023) << 10) | N.charCodeAt(++B) & 1023), q <= 127 ? ++D : q <= 2047 ? D += 2 : q <= 65535 ? D += 3 : D += 4; + } + return D; + } + function It(N, D) { + t().set(N, D); + } + function Nt(N, D) { + return N % D > 0 && (N += D - N % D), N; + } + var Ue, pt, ft, Bt, In, Qt, pn, Br, Zn; + function ur(N) { + Ue = N, i.HEAP8 = pt = new Int8Array(N), i.HEAP16 = Bt = new Int16Array(N), i.HEAP32 = Qt = new Int32Array(N), i.HEAPU8 = ft = new Uint8Array(N), i.HEAPU16 = In = new Uint16Array(N), i.HEAPU32 = pn = new Uint32Array(N), i.HEAPF32 = Br = new Float32Array(N), i.HEAPF64 = Zn = new Float64Array(N); + } + var Nn = i.INITIAL_MEMORY || 16777216; + if (x) + Q = i.wasmMemory, Ue = i.buffer; + else if (i.wasmMemory) + Q = i.wasmMemory; + else if (Q = new WebAssembly.Memory({ initial: Nn / 65536, maximum: 2147483648 / 65536, shared: true }), !(Q.buffer instanceof SharedArrayBuffer)) + throw U("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"), y && console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"), Error("bad memory"); + Q && (Ue = Q.buffer), Nn = Ue.byteLength, ur(Ue); + var Hr, wr = [], mn = [], zn = [], Ol = [], Wa = [], Ms = false, _i = false; + x || mn.push({ func: function() { + Bh(); + } }); + function gm() { + if (!x) { + if (i.preRun) + for (typeof i.preRun == "function" && (i.preRun = [i.preRun]); i.preRun.length; ) + Nh(i.preRun.shift()); + rc(wr); + } + } + function Pl() { + Ms = true, !x && rc(mn); + } + function zy() { + x || rc(zn); + } + function Ih() { + x || (_i = true); + } + function fn() { + if (!x) { + if (i.postRun) + for (typeof i.postRun == "function" && (i.postRun = [i.postRun]); i.postRun.length; ) + By(i.postRun.shift()); + rc(Wa); + } + } + function Nh(N) { + wr.unshift(N); + } + function By(N) { + Wa.unshift(N); + } + var vi = 0, ja = null, Ml = null; + function Vy(N) { + fe(!x, "addRunDependency cannot be used in a pthread worker"), vi++, i.monitorRunDependencies && i.monitorRunDependencies(vi); + } + function Wy(N) { + if (vi--, i.monitorRunDependencies && i.monitorRunDependencies(vi), vi == 0 && (ja !== null && (clearInterval(ja), ja = null), Ml)) { + var D = Ml; + Ml = null, D(); + } + } + i.preloadedImages = {}, i.preloadedAudios = {}; + function Ci(N) { + i.onAbort && i.onAbort(N), x && console.error("Pthread aborting at " + new Error().stack), N += "", U(N), pe = true, ie = 1, N = "abort(" + N + "). Build with -s ASSERTIONS=1 for more info."; + var D = new WebAssembly.RuntimeError(N); + throw u(D), D; + } + function Th(N, D) { + return String.prototype.startsWith ? N.startsWith(D) : N.indexOf(D) === 0; + } + var tc = "data:application/octet-stream;base64,"; + function Eh(N) { + return Th(N, tc); + } + var jy = "file://"; + function Ah(N) { + return Th(N, jy); + } + var dn = "tfjs-backend-wasm-threaded-simd.wasm"; + Eh(dn) || (dn = C(dn)); + function $h(N) { + try { + if (N == dn && X) + return new Uint8Array(X); + if (R) + return R(N); + throw "both async and sync fetching of the wasm failed"; + } catch (D) { + Ci(D); + } + } + function Gy() { + if (!X && (h || g)) { + if (typeof fetch == "function" && !Ah(dn)) + return fetch(dn, { credentials: "same-origin" }).then(function(N) { + if (!N.ok) + throw "failed to load wasm binary file at '" + dn + "'"; + return N.arrayBuffer(); + }).catch(function() { + return $h(dn); + }); + if ($) + return new Promise(function(N, D) { + $(dn, function(B) { + N(new Uint8Array(B)); + }, D); + }); + } + return Promise.resolve().then(function() { + return $h(dn); + }); + } + function Uy() { + var N = { a: Ob }; + function D(xe, Te) { + var bt = xe.exports; + if (i.asm = bt, Hr = i.asm.F, se = Te, !x) { + var kr = Ee.unusedWorkers.length; + Ee.unusedWorkers.forEach(function(hr) { + Ee.loadWasmModuleToWorker(hr, function() { + --kr || Wy("wasm-instantiate"); + }); + }); + } + } + x || Vy("wasm-instantiate"); + function B(xe) { + D(xe.instance, xe.module); + } + function q(xe) { + return Gy().then(function(Te) { + return WebAssembly.instantiate(Te, N); + }).then(xe, function(Te) { + U("failed to asynchronously prepare wasm: " + Te), Ci(Te); + }); + } + function ye() { + return !X && typeof WebAssembly.instantiateStreaming == "function" && !Eh(dn) && !Ah(dn) && typeof fetch == "function" ? fetch(dn, { credentials: "same-origin" }).then(function(xe) { + var Te = WebAssembly.instantiateStreaming(xe, N); + return Te.then(B, function(bt) { + return U("wasm streaming compile failed: " + bt), U("falling back to ArrayBuffer instantiation"), q(B); + }); + }) : q(B); + } + if (i.instantiateWasm) + try { + var he = i.instantiateWasm(N, D); + return he; + } catch (xe) { + return U("Module.instantiateWasm callback failed with error: " + xe), false; + } + return ye().catch(u), {}; + } + var Hy = { 10024: function() { + throw "Canceled!"; + }, 10042: function(N, D) { + setTimeout(function() { + NI(N, D); + }, 0); + } }; + function Dh() { + Ee.initRuntime(); + } + function rc(N) { + for (; N.length > 0; ) { + var D = N.shift(); + if (typeof D == "function") { + D(i); + continue; + } + var B = D.func; + typeof B == "number" ? D.arg === void 0 ? Hr.get(B)() : Hr.get(B)(D.arg) : B(D.arg === void 0 ? null : D.arg); + } + } + function xm(N, D) { + if (N <= 0 || N > t().length || N & true || D < 0) + return -28; + if (D == 0) + return 0; + D >= 2147483647 && (D = 1 / 0); + var B = Atomics.load(o(), lc >> 2), q = 0; + if (B == N) { + var ye = Atomics.compareExchange(o(), lc >> 2, B, 0); + if (ye == B && (--D, q = 1, D <= 0)) + return 1; + } + var he = Atomics.notify(o(), N >> 2, D); + if (he >= 0) + return he + q; + throw "Atomics.notify returned an unexpected value " + he; + } + i._emscripten_futex_wake = xm; + function qy(N) { + if (x) + throw "Internal Error! killThread() can only ever be called from main application thread!"; + if (!N) + throw "Internal Error! Null pthread_ptr in killThread!"; + o()[N + 12 >> 2] = 0; + var D = Ee.pthreads[N]; + D.worker.terminate(), Ee.freeThreadData(D), Ee.runningWorkers.splice(Ee.runningWorkers.indexOf(D.worker), 1), D.worker.pthread = void 0; + } + function Ky(N) { + if (x) + throw "Internal Error! cancelThread() can only ever be called from main application thread!"; + if (!N) + throw "Internal Error! Null pthread_ptr in cancelThread!"; + var D = Ee.pthreads[N]; + D.worker.postMessage({ cmd: "cancel" }); + } + function Xy(N) { + if (x) + throw "Internal Error! cleanupThread() can only ever be called from main application thread!"; + if (!N) + throw "Internal Error! Null pthread_ptr in cleanupThread!"; + var D = Ee.pthreads[N]; + if (D) { + o()[N + 12 >> 2] = 0; + var B = D.worker; + Ee.returnWorkerToPool(B); + } + } + var Ee = { unusedWorkers: [], runningWorkers: [], initMainThreadBlock: function() { + for (var N = Math.min(4, Math.max(1, (navigator.hardwareConcurrency || 1) / 2)), D = 0; D < N; ++D) + Ee.allocateUnusedWorker(); + }, initRuntime: function() { + for (var N = zl(228), D = 0; D < 228 / 4; ++D) + s()[N / 4 + D] = 0; + o()[N + 12 >> 2] = N; + var B = N + 152; + o()[B >> 2] = B; + for (var q = zl(512), D = 0; D < 128; ++D) + s()[q / 4 + D] = 0; + Atomics.store(s(), N + 100 >> 2, q), Atomics.store(s(), N + 40 >> 2, N), lw(N, !g, 1), II(N); + }, initWorker: function() { + }, pthreads: {}, threadExitHandlers: [], setThreadStatus: function() { + }, runExitHandlers: function() { + for (; Ee.threadExitHandlers.length > 0; ) + Ee.threadExitHandlers.pop()(); + x && sc() && SI(); + }, runExitHandlersAndDeinitThread: function(N, D) { + Atomics.store(s(), N + 56 >> 2, 1), Atomics.store(s(), N + 60 >> 2, 0), Ee.runExitHandlers(), Atomics.store(s(), N + 4 >> 2, D), Atomics.store(s(), N + 0 >> 2, 1), xm(N + 0, 2147483647), lw(0, 0, 0); + }, threadExit: function(N) { + var D = sc(); + D && (Ee.runExitHandlersAndDeinitThread(D, N), x && postMessage({ cmd: "exit" })); + }, threadCancel: function() { + Ee.runExitHandlersAndDeinitThread(sc(), -1), postMessage({ cmd: "cancelDone" }); + }, terminateAllThreads: function() { + for (var N in Ee.pthreads) { + var D = Ee.pthreads[N]; + D && D.worker && Ee.returnWorkerToPool(D.worker); + } + Ee.pthreads = {}; + for (var B = 0; B < Ee.unusedWorkers.length; ++B) { + var q = Ee.unusedWorkers[B]; + q.terminate(); + } + Ee.unusedWorkers = []; + for (var B = 0; B < Ee.runningWorkers.length; ++B) { + var q = Ee.runningWorkers[B], D = q.pthread; + Ee.freeThreadData(D), q.terminate(); + } + Ee.runningWorkers = []; + }, freeThreadData: function(N) { + if (!!N) { + if (N.threadInfoStruct) { + var D = o()[N.threadInfoStruct + 100 >> 2]; + o()[N.threadInfoStruct + 100 >> 2] = 0, Cm(D), Cm(N.threadInfoStruct); + } + N.threadInfoStruct = 0, N.allocatedOwnStack && N.stackBase && Cm(N.stackBase), N.stackBase = 0, N.worker && (N.worker.pthread = null); + } + }, returnWorkerToPool: function(N) { + Ee.runWithoutMainThreadQueuedCalls(function() { + delete Ee.pthreads[N.pthread.threadInfoStruct], Ee.unusedWorkers.push(N), Ee.runningWorkers.splice(Ee.runningWorkers.indexOf(N), 1), Ee.freeThreadData(N.pthread), N.pthread = void 0; + }); + }, runWithoutMainThreadQueuedCalls: function(N) { + o()[DI >> 2] = 0; + try { + N(); + } finally { + o()[DI >> 2] = 1; + } + }, receiveObjectTransfer: function(N) { + }, loadWasmModuleToWorker: function(N, D) { + N.onmessage = function(B) { + var q = B.data, ye = q.cmd; + if (N.pthread && (Ee.currentProxiedOperationCallerThread = N.pthread.threadInfoStruct), q.targetThread && q.targetThread != sc()) { + var he = Ee.pthreads[q.targetThread]; + he ? he.worker.postMessage(B.data, q.transferList) : console.error('Internal error! Worker sent a message "' + ye + '" to target pthread ' + q.targetThread + ", but that thread no longer exists!"), Ee.currentProxiedOperationCallerThread = void 0; + return; + } + if (ye === "processQueuedMainThreadWork") + iw(); + else if (ye === "spawnThread") + Lh(B.data); + else if (ye === "cleanupThread") + Xy(q.thread); + else if (ye === "killThread") + qy(q.thread); + else if (ye === "cancelThread") + Ky(q.thread); + else if (ye === "loaded") + N.loaded = true, D && D(N), N.runPthread && (N.runPthread(), delete N.runPthread); + else if (ye === "print") + G("Thread " + q.threadId + ": " + q.text); + else if (ye === "printErr") + U("Thread " + q.threadId + ": " + q.text); + else if (ye === "alert") + alert("Thread " + q.threadId + ": " + q.text); + else if (ye === "exit") { + var xe = N.pthread && Atomics.load(s(), N.pthread.threadInfoStruct + 64 >> 2); + xe && Ee.returnWorkerToPool(N); + } else if (ye === "exitProcess") + try { + WW(q.returnCode); + } catch (Te) { + if (Te instanceof Im) + return; + throw Te; + } + else + ye === "cancelDone" ? Ee.returnWorkerToPool(N) : ye === "objectTransfer" ? Ee.receiveObjectTransfer(B.data) : B.data.target === "setimmediate" ? N.postMessage(B.data) : U("worker sent an unknown command " + ye); + Ee.currentProxiedOperationCallerThread = void 0; + }, N.onerror = function(B) { + U("pthread sent an error! " + B.filename + ":" + B.lineno + ": " + B.message); + }, y && (N.on("message", function(B) { + N.onmessage({ data: B }); + }), N.on("error", function(B) { + N.onerror(B); + }), N.on("exit", function(B) { + })), N.postMessage({ cmd: "load", urlOrBlob: i.mainScriptUrlOrBlob || r, wasmMemory: Q, wasmModule: se }); + }, allocateUnusedWorker: function() { + var N = C("tfjs-backend-wasm-threaded-simd.worker.js"); + Ee.unusedWorkers.push(new Worker(N)); + }, getNewWorker: function() { + return Ee.unusedWorkers.length == 0 && (Ee.allocateUnusedWorker(), Ee.loadWasmModuleToWorker(Ee.unusedWorkers[0])), Ee.unusedWorkers.length > 0 ? Ee.unusedWorkers.pop() : null; + }, busySpinWait: function(N) { + for (var D = performance.now() + N; performance.now() < D; ) + ; + } }; + function Yy(N, D) { + AI(N, D), ic(N); + } + i.establishStackSpace = Yy; + function Zy() { + return ne; + } + i.getNoExitRuntime = Zy; + function Jy(N, D) { + return Hr.get(N)(D); + } + i.invokeEntryPoint = Jy; + function Qy(N, D, B, q) { + Ci("Assertion failed: " + Ce(N) + ", at: " + [D ? Ce(D) : "unknown filename", B, q ? Ce(q) : "unknown function"]); + } + function eb(N, D) { + var B = _main(N, D); + } + var Ll; + y ? Ll = function() { + var N = process.hrtime(); + return N[0] * 1e3 + N[1] / 1e6; + } : x ? Ll = function() { + return performance.now() - i.__performance_now_clock_drift; + } : typeof dateNow != "undefined" ? Ll = dateNow : Ll = function() { + return performance.now(); + }; + function tb(N) { + return o()[vI() >> 2] = N, N; + } + function rb(N, D) { + if (x) + return Ga(1, 1, N, D); + } + function nb(N, D) { + if (N == D) + postMessage({ cmd: "processQueuedMainThreadWork" }); + else if (x) + postMessage({ targetThread: N, cmd: "processThreadQueue" }); + else { + var B = Ee.pthreads[N], q = B && B.worker; + if (!q) + return; + q.postMessage({ cmd: "processThreadQueue" }); + } + return 1; + } + function ob() { + Ci(); + } + function sb(N, D, B) { + var q = cb(D, B); + return Hy[N].apply(null, q); + } + function ib(N, D) { + } + function ab(N, D, B) { + if (N <= 0 || N > t().length || N & true) + return -28; + if (h) { + if (Atomics.load(o(), N >> 2) != D) + return -6; + for (var ye = performance.now(), he = ye + B, xe = Atomics.exchange(o(), lc >> 2, N); ; ) { + if (ye = performance.now(), ye > he) + return xe = Atomics.exchange(o(), lc >> 2, 0), -73; + if (xe = Atomics.exchange(o(), lc >> 2, 0), xe == 0) + break; + if (iw(), Atomics.load(o(), N >> 2) != D) + return -6; + xe = Atomics.exchange(o(), lc >> 2, N); + } + return 0; + } else { + var q = Atomics.wait(o(), N >> 2, D, B); + if (q === "timed-out") + return -73; + if (q === "not-equal") + return -6; + if (q === "ok") + return 0; + throw "Atomics.wait returned an unexpected value " + q; + } + } + function lb(N, D, B) { + n().copyWithin(N, D, D + B); + } + function ub() { + return y ? pc("os").cpus().length : navigator.hardwareConcurrency; + } + function Ga(N, D) { + for (var B = arguments.length - 2, q = Sm(), ye = B, he = ac(ye * 8), xe = he >> 3, Te = 0; Te < B; Te++) { + var bt = arguments[2 + Te]; + a()[xe + Te] = bt; + } + var kr = EI(N, ye, he, D); + return ic(q), kr; + } + var ym = [], bm = []; + function cb(N, D) { + bm.length = 0; + var B; + for (D >>= 2; B = n()[N++]; ) { + var q = B < 105; + q && D & 1 && D++, bm.push(q ? a()[D++ >> 1] : o()[D]), ++D; + } + return bm; + } + function pb(N, D, B) { + ym.length = D; + for (var q = B >> 3, ye = 0; ye < D; ye++) + ym[ye] = a()[q + ye]; + var he = N < 0, xe = he ? Hy[-N - 1] : Fb[N]; + return xe.apply(null, ym); + } + function mb() { + return n().length; + } + function fb(N) { + try { + return Q.grow(N - Ue.byteLength + 65535 >>> 16), ur(Q.buffer), 1; + } catch (D) { + } + } + function db(N) { + var D = mb(); + if (N <= D) + return false; + var B = 2147483648; + if (N > B) + return false; + for (var q = 1; q <= 4; q *= 2) { + var ye = D * (1 + 0.2 / q); + ye = Math.min(ye, N + 100663296); + var he = Math.min(B, Nt(Math.max(N, ye), 65536)), xe = fb(he); + if (xe) + return true; + } + return false; + } + var Je = { inEventHandler: 0, removeAllEventListeners: function() { + for (var N = Je.eventHandlers.length - 1; N >= 0; --N) + Je._removeHandler(N); + Je.eventHandlers = [], Je.deferredCalls = []; + }, registerRemoveEventListeners: function() { + Je.removeEventListenersRegistered || (Ol.push(Je.removeAllEventListeners), Je.removeEventListenersRegistered = true); + }, deferredCalls: [], deferCall: function(N, D, B) { + function q(xe, Te) { + if (xe.length != Te.length) + return false; + for (var bt in xe) + if (xe[bt] != Te[bt]) + return false; + return true; + } + for (var ye in Je.deferredCalls) { + var he = Je.deferredCalls[ye]; + if (he.targetFunction == N && q(he.argsList, B)) + return; + } + Je.deferredCalls.push({ targetFunction: N, precedence: D, argsList: B }), Je.deferredCalls.sort(function(xe, Te) { + return xe.precedence < Te.precedence; + }); + }, removeDeferredCalls: function(N) { + for (var D = 0; D < Je.deferredCalls.length; ++D) + Je.deferredCalls[D].targetFunction == N && (Je.deferredCalls.splice(D, 1), --D); + }, canPerformEventHandlerRequests: function() { + return Je.inEventHandler && Je.currentEventHandler.allowsDeferredCalls; + }, runDeferredCalls: function() { + if (!!Je.canPerformEventHandlerRequests()) + for (var N = 0; N < Je.deferredCalls.length; ++N) { + var D = Je.deferredCalls[N]; + Je.deferredCalls.splice(N, 1), --N, D.targetFunction.apply(null, D.argsList); + } + }, eventHandlers: [], removeAllHandlersOnTarget: function(N, D) { + for (var B = 0; B < Je.eventHandlers.length; ++B) + Je.eventHandlers[B].target == N && (!D || D == Je.eventHandlers[B].eventTypeString) && Je._removeHandler(B--); + }, _removeHandler: function(N) { + var D = Je.eventHandlers[N]; + D.target.removeEventListener(D.eventTypeString, D.eventListenerFunc, D.useCapture), Je.eventHandlers.splice(N, 1); + }, registerOrRemoveHandler: function(N) { + var D = function(ye) { + ++Je.inEventHandler, Je.currentEventHandler = N, Je.runDeferredCalls(), N.handlerFunc(ye), Je.runDeferredCalls(), --Je.inEventHandler; + }; + if (N.callbackfunc) + N.eventListenerFunc = D, N.target.addEventListener(N.eventTypeString, D, N.useCapture), Je.eventHandlers.push(N), Je.registerRemoveEventListeners(); + else + for (var B = 0; B < Je.eventHandlers.length; ++B) + Je.eventHandlers[B].target == N.target && Je.eventHandlers[B].eventTypeString == N.eventTypeString && Je._removeHandler(B--); + }, queueEventHandlerOnThread_iiii: function(N, D, B, q, ye) { + var he = Sm(), xe = ac(12); + o()[xe >> 2] = B, o()[xe + 4 >> 2] = q, o()[xe + 8 >> 2] = ye, aw(0, N, 637534208, D, q, xe), ic(he); + }, getTargetThreadForEventCallback: function(N) { + switch (N) { + case 1: + return 0; + case 2: + return Ee.currentProxiedOperationCallerThread; + default: + return N; + } + }, getNodeNameForTarget: function(N) { + return N ? N == window ? "#window" : N == screen ? "#screen" : N && N.nodeName ? N.nodeName : "" : ""; + }, fullscreenEnabled: function() { + return document.fullscreenEnabled || document.webkitFullscreenEnabled; + } }; + function hb(N) { + var D = lt(N) + 1, B = zl(D); + return qe(N, B, D), B; + } + function gb(N, D, B, q) { + var ye = Sm(), he = ac(12), xe = 0; + D && (xe = hb(D)), o()[he >> 2] = xe, o()[he + 4 >> 2] = B, o()[he + 8 >> 2] = q, aw(0, N, 657457152, 0, xe, he), ic(ye); + } + function xb(N, D, B, q) { + D = D ? Ce(D) : "", gb(N, D, B, q); + } + function yb(N) { + return N > 2 ? Ce(N) : N; + } + var bb = [0, typeof document != "undefined" ? document : 0, typeof window != "undefined" ? window : 0]; + function wb(N) { + N = yb(N); + var D = bb[N] || (typeof document != "undefined" ? document.querySelector(N) : void 0); + return D; + } + function wm(N) { + return wb(N); + } + function Rh(N, D, B) { + var q = wm(N); + if (!q) + return -4; + if (q.canvasSharedPtr && (o()[q.canvasSharedPtr >> 2] = D, o()[q.canvasSharedPtr + 4 >> 2] = B), q.offscreenCanvas || !q.controlTransferredOffscreen) { + q.offscreenCanvas && (q = q.offscreenCanvas); + var ye = false; + if (q.GLctxObject && q.GLctxObject.GLctx) { + var he = q.GLctxObject.GLctx.getParameter(2978); + ye = he[0] === 0 && he[1] === 0 && he[2] === q.width && he[3] === q.height; + } + q.width = D, q.height = B, ye && q.GLctxObject.GLctx.viewport(0, 0, D, B); + } else if (q.canvasSharedPtr) { + var xe = o()[q.canvasSharedPtr + 8 >> 2]; + return xb(xe, N, D, B), 1; + } else + return -4; + return 0; + } + function Fh(N, D, B) { + return x ? Ga(2, 1, N, D, B) : Rh(N, D, B); + } + function kb(N, D, B) { + var q = wm(N); + return q ? Rh(N, D, B) : Fh(N, D, B); + } + function _b(N) { + } + function vb(N, D) { + } + function Cb(N) { + var D = N.getExtension("ANGLE_instanced_arrays"); + if (D) + return N.vertexAttribDivisor = function(B, q) { + D.vertexAttribDivisorANGLE(B, q); + }, N.drawArraysInstanced = function(B, q, ye, he) { + D.drawArraysInstancedANGLE(B, q, ye, he); + }, N.drawElementsInstanced = function(B, q, ye, he, xe) { + D.drawElementsInstancedANGLE(B, q, ye, he, xe); + }, 1; + } + function Sb(N) { + var D = N.getExtension("OES_vertex_array_object"); + if (D) + return N.createVertexArray = function() { + return D.createVertexArrayOES(); + }, N.deleteVertexArray = function(B) { + D.deleteVertexArrayOES(B); + }, N.bindVertexArray = function(B) { + D.bindVertexArrayOES(B); + }, N.isVertexArray = function(B) { + return D.isVertexArrayOES(B); + }, 1; + } + function Ib(N) { + var D = N.getExtension("WEBGL_draw_buffers"); + if (D) + return N.drawBuffers = function(B, q) { + D.drawBuffersWEBGL(B, q); + }, 1; + } + function Nb(N) { + return !!(N.multiDrawWebgl = N.getExtension("WEBGL_multi_draw")); + } + var dt = { counter: 1, buffers: [], programs: [], framebuffers: [], renderbuffers: [], textures: [], uniforms: [], shaders: [], vaos: [], contexts: {}, offscreenCanvases: {}, timerQueriesEXT: [], programInfos: {}, stringCache: {}, unpackAlignment: 4, recordError: function(D) { + dt.lastError || (dt.lastError = D); + }, getNewId: function(N) { + for (var D = dt.counter++, B = N.length; B < D; B++) + N[B] = null; + return D; + }, getSource: function(N, D, B, q) { + for (var ye = "", he = 0; he < D; ++he) { + var xe = q ? o()[q + he * 4 >> 2] : -1; + ye += Ce(o()[B + he * 4 >> 2], xe < 0 ? void 0 : xe); + } + return ye; + }, createContext: function(N, D) { + var B = N.getContext("webgl", D); + if (!B) + return 0; + var q = dt.registerContext(B, D); + return q; + }, registerContext: function(N, D) { + var B = zl(8); + o()[B + 4 >> 2] = sc(); + var q = { handle: B, attributes: D, version: D.majorVersion, GLctx: N }; + return N.canvas && (N.canvas.GLctxObject = q), dt.contexts[B] = q, (typeof D.enableExtensionsByDefault == "undefined" || D.enableExtensionsByDefault) && dt.initExtensions(q), B; + }, makeContextCurrent: function(N) { + return dt.currentContext = dt.contexts[N], i.ctx = Ua = dt.currentContext && dt.currentContext.GLctx, !(N && !Ua); + }, getContext: function(N) { + return dt.contexts[N]; + }, deleteContext: function(N) { + dt.currentContext === dt.contexts[N] && (dt.currentContext = null), typeof Je == "object" && Je.removeAllHandlersOnTarget(dt.contexts[N].GLctx.canvas), dt.contexts[N] && dt.contexts[N].GLctx.canvas && (dt.contexts[N].GLctx.canvas.GLctxObject = void 0), Cm(dt.contexts[N].handle), dt.contexts[N] = null; + }, initExtensions: function(N) { + if (N || (N = dt.currentContext), !N.initExtensionsDone) { + N.initExtensionsDone = true; + var D = N.GLctx; + Cb(D), Sb(D), Ib(D), D.disjointTimerQueryExt = D.getExtension("EXT_disjoint_timer_query"), Nb(D); + var B = D.getSupportedExtensions() || []; + B.forEach(function(q) { + q.indexOf("lose_context") < 0 && q.indexOf("debug") < 0 && D.getExtension(q); + }); + } + }, populateUniformTable: function(N) { + for (var D = dt.programs[N], B = dt.programInfos[N] = { uniforms: {}, maxUniformLength: 0, maxAttributeLength: -1, maxUniformBlockNameLength: -1 }, q = B.uniforms, ye = Ua.getProgramParameter(D, 35718), he = 0; he < ye; ++he) { + var xe = Ua.getActiveUniform(D, he), Te = xe.name; + B.maxUniformLength = Math.max(B.maxUniformLength, Te.length + 1), Te.slice(-1) == "]" && (Te = Te.slice(0, Te.lastIndexOf("["))); + var bt = Ua.getUniformLocation(D, Te); + if (bt) { + var kr = dt.getNewId(dt.uniforms); + q[Te] = [xe.size, kr], dt.uniforms[kr] = bt; + for (var hr = 1; hr < xe.size; ++hr) { + var qa = Te + "[" + hr + "]"; + bt = Ua.getUniformLocation(D, qa), kr = dt.getNewId(dt.uniforms), dt.uniforms[kr] = bt; + } + } + } + } }, Tb = ["default", "low-power", "high-performance"]; + function Eb(N, D) { + var B = D >> 2, q = o()[B + (24 >> 2)], ye = { alpha: !!o()[B + (0 >> 2)], depth: !!o()[B + (4 >> 2)], stencil: !!o()[B + (8 >> 2)], antialias: !!o()[B + (12 >> 2)], premultipliedAlpha: !!o()[B + (16 >> 2)], preserveDrawingBuffer: !!o()[B + (20 >> 2)], powerPreference: Tb[q], failIfMajorPerformanceCaveat: !!o()[B + (28 >> 2)], majorVersion: o()[B + (32 >> 2)], minorVersion: o()[B + (36 >> 2)], enableExtensionsByDefault: o()[B + (40 >> 2)], explicitSwapControl: o()[B + (44 >> 2)], proxyContextToMainThread: o()[B + (48 >> 2)], renderViaOffscreenBackBuffer: o()[B + (52 >> 2)] }, he = wm(N); + if (!he || ye.explicitSwapControl) + return 0; + var xe = dt.createContext(he, ye); + return xe; + } + function Ab(N, D) { + return Eb(N, D); + } + var nc = { mappings: {}, buffers: [null, [], []], printChar: function(N, D) { + var B = nc.buffers[N]; + D === 0 || D === 10 ? ((N === 1 ? G : U)($e(B, 0)), B.length = 0) : B.push(D); + }, varargs: void 0, get: function() { + nc.varargs += 4; + var N = o()[nc.varargs - 4 >> 2]; + return N; + }, getStr: function(N) { + var D = Ce(N); + return D; + }, get64: function(N, D) { + return N; + } }; + function Oh(N) { + return x ? Ga(3, 1, N) : 0; + } + function Ph(N, D, B, q, ye) { + if (x) + return Ga(4, 1, N, D, B, q, ye); + } + function Mh(N, D, B, q) { + if (x) + return Ga(5, 1, N, D, B, q); + for (var ye = 0, he = 0; he < B; he++) { + for (var xe = o()[D + he * 8 >> 2], Te = o()[D + (he * 8 + 4) >> 2], bt = 0; bt < Te; bt++) + nc.printChar(N, n()[xe + bt]); + ye += Te; + } + return o()[q >> 2] = ye, 0; + } + function $b(N) { + var D = Ee.threadExitHandlers.pop(); + N && D(); + } + function Db(N, D) { + Ee.threadExitHandlers.push(function() { + Hr.get(N)(D); + }); + } + function Lh(N) { + if (x) + throw "Internal Error! spawnThread() can only ever be called from main application thread!"; + var D = Ee.getNewWorker(); + if (D.pthread !== void 0) + throw "Internal error!"; + if (!N.pthread_ptr) + throw "Internal error, no pthread ptr!"; + Ee.runningWorkers.push(D); + for (var B = zl(128 * 4), q = 0; q < 128; ++q) + o()[B + q * 4 >> 2] = 0; + var ye = N.stackBase + N.stackSize, he = Ee.pthreads[N.pthread_ptr] = { worker: D, stackBase: N.stackBase, stackSize: N.stackSize, allocatedOwnStack: N.allocatedOwnStack, threadInfoStruct: N.pthread_ptr }, xe = he.threadInfoStruct >> 2; + Atomics.store(s(), xe + (64 >> 2), N.detached), Atomics.store(s(), xe + (100 >> 2), B), Atomics.store(s(), xe + (40 >> 2), he.threadInfoStruct), Atomics.store(s(), xe + (80 >> 2), N.stackSize), Atomics.store(s(), xe + (76 >> 2), ye), Atomics.store(s(), xe + (104 >> 2), N.stackSize), Atomics.store(s(), xe + (104 + 8 >> 2), ye), Atomics.store(s(), xe + (104 + 12 >> 2), N.detached); + var Te = CI(), bt = Te + 40; + Atomics.store(s(), xe + (172 >> 2), bt), D.pthread = he; + var kr = { cmd: "run", start_routine: N.startRoutine, arg: N.arg, threadInfoStruct: N.pthread_ptr, stackBase: N.stackBase, stackSize: N.stackSize }; + D.runPthread = function() { + kr.time = performance.now(), D.postMessage(kr, N.transferList); + }, D.loaded && (D.runPthread(), delete D.runPthread); + } + function Rb(N, D, B, q) { + if (typeof SharedArrayBuffer == "undefined") + return U("Current environment does not support SharedArrayBuffer, pthreads are not available!"), 6; + if (!N) + return U("pthread_create called with a null thread pointer!"), 28; + var ye = [], he = 0; + if (x && (ye.length === 0 || he)) + return TI(687865856, N, D, B, q); + if (he) + return he; + var xe = 0, Te = 0, bt = 0; + D && D != -1 ? (xe = o()[D >> 2], xe += 81920, Te = o()[D + 8 >> 2], bt = o()[D + 12 >> 2] !== 0) : xe = 2097152; + var kr = Te == 0; + kr ? Te = $I(16, xe) : (Te -= xe, fe(Te > 0)); + for (var hr = zl(228), qa = 0; qa < 228 >> 2; ++qa) + s()[(hr >> 2) + qa] = 0; + o()[N >> 2] = hr, o()[hr + 12 >> 2] = hr; + var uc = hr + 152; + o()[uc >> 2] = uc; + var qr = { stackBase: Te, stackSize: xe, allocatedOwnStack: kr, detached: bt, startRoutine: B, pthread_ptr: hr, arg: q, transferList: ye }; + return x ? (qr.cmd = "spawnThread", postMessage(qr, ye)) : Lh(qr), 0; + } + function zh(N) { + if (x) + return Ga(6, 1, N); + switch (N) { + case 30: + return 16384; + case 85: + var D = 2147483648; + return D / 16384; + case 132: + case 133: + case 12: + case 137: + case 138: + case 15: + case 235: + case 16: + case 17: + case 18: + case 19: + case 20: + case 149: + case 13: + case 10: + case 236: + case 153: + case 9: + case 21: + case 22: + case 159: + case 154: + case 14: + case 77: + case 78: + case 139: + case 82: + case 68: + case 67: + case 164: + case 11: + case 29: + case 47: + case 48: + case 95: + case 52: + case 51: + case 46: + return 200809; + case 27: + case 246: + case 127: + case 128: + case 23: + case 24: + case 160: + case 161: + case 181: + case 182: + case 242: + case 183: + case 184: + case 243: + case 244: + case 245: + case 165: + case 178: + case 179: + case 49: + case 50: + case 168: + case 169: + case 175: + case 170: + case 171: + case 172: + case 97: + case 76: + case 32: + case 173: + case 35: + case 80: + case 81: + case 79: + return -1; + case 176: + case 177: + case 7: + case 155: + case 8: + case 157: + case 125: + case 126: + case 92: + case 93: + case 129: + case 130: + case 131: + case 94: + case 91: + return 1; + case 74: + case 60: + case 69: + case 70: + case 4: + return 1024; + case 31: + case 42: + case 72: + return 32; + case 87: + case 26: + case 33: + return 2147483647; + case 34: + case 1: + return 47839; + case 38: + case 36: + return 99; + case 43: + case 37: + return 2048; + case 0: + return 2097152; + case 3: + return 65536; + case 28: + return 32768; + case 44: + return 32767; + case 75: + return 16384; + case 39: + return 1e3; + case 89: + return 700; + case 71: + return 256; + case 40: + return 255; + case 2: + return 100; + case 180: + return 64; + case 25: + return 20; + case 5: + return 16; + case 6: + return 6; + case 73: + return 4; + case 84: + return typeof navigator == "object" && navigator.hardwareConcurrency || 1; + } + return tb(28), -1; + } + x || Ee.initMainThreadBlock(); + var Ua, Fb = [null, rb, Fh, Oh, Ph, Mh, zh], Ob = { e: Qy, r: eb, x: nb, b: ob, y: sb, j: ib, c: ab, d: xm, f: Ll, p: lb, z: ub, u: pb, q: db, v: kb, i: _b, t: vb, w: Ab, m: Oh, n: Ph, g: Mh, o: Dh, a: Q || i.wasmMemory, k: $b, l: Db, h: Rb, s: zh }, _I = Uy(), Bh = i.___wasm_call_ctors = function() { + return (Bh = i.___wasm_call_ctors = i.asm.A).apply(null, arguments); + }, Pb = i._init = function() { + return (Pb = i._init = i.asm.B).apply(null, arguments); + }, Mb = i._register_tensor = function() { + return (Mb = i._register_tensor = i.asm.C).apply(null, arguments); + }, Lb = i._dispose_data = function() { + return (Lb = i._dispose_data = i.asm.D).apply(null, arguments); + }, zb = i._dispose = function() { + return (zb = i._dispose = i.asm.E).apply(null, arguments); + }, Bb = i._Abs = function() { + return (Bb = i._Abs = i.asm.G).apply(null, arguments); + }, Vb = i._Add = function() { + return (Vb = i._Add = i.asm.H).apply(null, arguments); + }, Wb = i._AddN = function() { + return (Wb = i._AddN = i.asm.I).apply(null, arguments); + }, jb = i._All = function() { + return (jb = i._All = i.asm.J).apply(null, arguments); + }, Gb = i._Any = function() { + return (Gb = i._Any = i.asm.K).apply(null, arguments); + }, Ub = i._ArgMax = function() { + return (Ub = i._ArgMax = i.asm.L).apply(null, arguments); + }, Hb = i._AvgPool = function() { + return (Hb = i._AvgPool = i.asm.M).apply(null, arguments); + }, qb = i._BatchMatMul = function() { + return (qb = i._BatchMatMul = i.asm.N).apply(null, arguments); + }, Kb = i._Ceil = function() { + return (Kb = i._Ceil = i.asm.O).apply(null, arguments); + }, Xb = i._ClipByValue = function() { + return (Xb = i._ClipByValue = i.asm.P).apply(null, arguments); + }, Yb = i._Conv2D = function() { + return (Yb = i._Conv2D = i.asm.Q).apply(null, arguments); + }, Zb = i._Conv2DBackpropInput = function() { + return (Zb = i._Conv2DBackpropInput = i.asm.R).apply(null, arguments); + }, Jb = i._Cos = function() { + return (Jb = i._Cos = i.asm.S).apply(null, arguments); + }, Qb = i._Cosh = function() { + return (Qb = i._Cosh = i.asm.T).apply(null, arguments); + }, ew = i._CropAndResize = function() { + return (ew = i._CropAndResize = i.asm.U).apply(null, arguments); + }, tw = i._Cumsum = function() { + return (tw = i._Cumsum = i.asm.V).apply(null, arguments); + }, rw = i._DepthToSpace = function() { + return (rw = i._DepthToSpace = i.asm.W).apply(null, arguments); + }, nw = i._DepthwiseConv2dNative = function() { + return (nw = i._DepthwiseConv2dNative = i.asm.X).apply(null, arguments); + }, ow = i._Elu = function() { + return (ow = i._Elu = i.asm.Y).apply(null, arguments); + }, Vh = i._Equal = function() { + return (Vh = i._Equal = i.asm.Z).apply(null, arguments); + }, Wh = i._Exp = function() { + return (Wh = i._Exp = i.asm._).apply(null, arguments); + }, jh = i._FlipLeftRight = function() { + return (jh = i._FlipLeftRight = i.asm.$).apply(null, arguments); + }, km = i._Floor = function() { + return (km = i._Floor = i.asm.aa).apply(null, arguments); + }, oc = i._FloorDiv = function() { + return (oc = i._FloorDiv = i.asm.ba).apply(null, arguments); + }, sw = i._FusedBatchNorm = function() { + return (sw = i._FusedBatchNorm = i.asm.ca).apply(null, arguments); + }, _m = i._FusedConv2D = function() { + return (_m = i._FusedConv2D = i.asm.da).apply(null, arguments); + }, Z = i._FusedDepthwiseConv2D = function() { + return (Z = i._FusedDepthwiseConv2D = i.asm.ea).apply(null, arguments); + }, oe = i._Gather = function() { + return (oe = i._Gather = i.asm.fa).apply(null, arguments); + }, ve = i._GatherNd = function() { + return (ve = i._GatherNd = i.asm.ga).apply(null, arguments); + }, ut = i._Greater = function() { + return (ut = i._Greater = i.asm.ha).apply(null, arguments); + }, er = i._GreaterEqual = function() { + return (er = i._GreaterEqual = i.asm.ia).apply(null, arguments); + }, Gt = i._LeakyRelu = function() { + return (Gt = i._LeakyRelu = i.asm.ja).apply(null, arguments); + }, et = i._Less = function() { + return (et = i._Less = i.asm.ka).apply(null, arguments); + }, rt = i._LessEqual = function() { + return (rt = i._LessEqual = i.asm.la).apply(null, arguments); + }, Er = i._Log = function() { + return (Er = i._Log = i.asm.ma).apply(null, arguments); + }, Si = i._LogicalAnd = function() { + return (Si = i._LogicalAnd = i.asm.na).apply(null, arguments); + }, Ii = i._Max = function() { + return (Ii = i._Max = i.asm.oa).apply(null, arguments); + }, Gh = i._MaxPool = function() { + return (Gh = i._MaxPool = i.asm.pa).apply(null, arguments); + }, vm = i._Maximum = function() { + return (vm = i._Maximum = i.asm.qa).apply(null, arguments); + }, Tn = i._Mean = function() { + return (Tn = i._Mean = i.asm.ra).apply(null, arguments); + }, Ha = i._Min = function() { + return (Ha = i._Min = i.asm.sa).apply(null, arguments); + }, Uh = i._Minimum = function() { + return (Uh = i._Minimum = i.asm.ta).apply(null, arguments); + }, tW = i._MirrorPad = function() { + return (tW = i._MirrorPad = i.asm.ua).apply(null, arguments); + }, rW = i._Multiply = function() { + return (rW = i._Multiply = i.asm.va).apply(null, arguments); + }, nW = i._Neg = function() { + return (nW = i._Neg = i.asm.wa).apply(null, arguments); + }, oW = i._NonMaxSuppressionV3 = function() { + return (oW = i._NonMaxSuppressionV3 = i.asm.xa).apply(null, arguments); + }, sW = i._NonMaxSuppressionV4 = function() { + return (sW = i._NonMaxSuppressionV4 = i.asm.ya).apply(null, arguments); + }, iW = i._NonMaxSuppressionV5 = function() { + return (iW = i._NonMaxSuppressionV5 = i.asm.za).apply(null, arguments); + }, aW = i._NotEqual = function() { + return (aW = i._NotEqual = i.asm.Aa).apply(null, arguments); + }, lW = i._OneHot = function() { + return (lW = i._OneHot = i.asm.Ba).apply(null, arguments); + }, uW = i._PadV2 = function() { + return (uW = i._PadV2 = i.asm.Ca).apply(null, arguments); + }, cW = i._Pow = function() { + return (cW = i._Pow = i.asm.Da).apply(null, arguments); + }, pW = i._Prelu = function() { + return (pW = i._Prelu = i.asm.Ea).apply(null, arguments); + }, mW = i._Prod = function() { + return (mW = i._Prod = i.asm.Fa).apply(null, arguments); + }, fW = i._RealDiv = function() { + return (fW = i._RealDiv = i.asm.Ga).apply(null, arguments); + }, dW = i._Relu = function() { + return (dW = i._Relu = i.asm.Ha).apply(null, arguments); + }, hW = i._Relu6 = function() { + return (hW = i._Relu6 = i.asm.Ia).apply(null, arguments); + }, gW = i._ResizeBilinear = function() { + return (gW = i._ResizeBilinear = i.asm.Ja).apply(null, arguments); + }, xW = i._Reverse = function() { + return (xW = i._Reverse = i.asm.Ka).apply(null, arguments); + }, yW = i._RotateWithOffset = function() { + return (yW = i._RotateWithOffset = i.asm.La).apply(null, arguments); + }, bW = i._Round = function() { + return (bW = i._Round = i.asm.Ma).apply(null, arguments); + }, wW = i._Rsqrt = function() { + return (wW = i._Rsqrt = i.asm.Na).apply(null, arguments); + }, kW = i._ScatterNd = function() { + return (kW = i._ScatterNd = i.asm.Oa).apply(null, arguments); + }, _W = i._SelectV2 = function() { + return (_W = i._SelectV2 = i.asm.Pa).apply(null, arguments); + }, vW = i._Sigmoid = function() { + return (vW = i._Sigmoid = i.asm.Qa).apply(null, arguments); + }, CW = i._Sin = function() { + return (CW = i._Sin = i.asm.Ra).apply(null, arguments); + }, SW = i._Softmax = function() { + return (SW = i._Softmax = i.asm.Sa).apply(null, arguments); + }, IW = i._Sqrt = function() { + return (IW = i._Sqrt = i.asm.Ta).apply(null, arguments); + }, NW = i._Square = function() { + return (NW = i._Square = i.asm.Ua).apply(null, arguments); + }, TW = i._SquaredDifference = function() { + return (TW = i._SquaredDifference = i.asm.Va).apply(null, arguments); + }, EW = i._Step = function() { + return (EW = i._Step = i.asm.Wa).apply(null, arguments); + }, AW = i._StridedSlice = function() { + return (AW = i._StridedSlice = i.asm.Xa).apply(null, arguments); + }, $W = i._Sub = function() { + return ($W = i._Sub = i.asm.Ya).apply(null, arguments); + }, DW = i._Sum = function() { + return (DW = i._Sum = i.asm.Za).apply(null, arguments); + }, RW = i._Tan = function() { + return (RW = i._Tan = i.asm._a).apply(null, arguments); + }, FW = i._Tanh = function() { + return (FW = i._Tanh = i.asm.$a).apply(null, arguments); + }, OW = i._Tile = function() { + return (OW = i._Tile = i.asm.ab).apply(null, arguments); + }, PW = i._TopK = function() { + return (PW = i._TopK = i.asm.bb).apply(null, arguments); + }, MW = i._Transform = function() { + return (MW = i._Transform = i.asm.cb).apply(null, arguments); + }, LW = i._Transpose = function() { + return (LW = i._Transpose = i.asm.db).apply(null, arguments); + }, zW = i.__FusedMatMul = function() { + return (zW = i.__FusedMatMul = i.asm.eb).apply(null, arguments); + }, zl = i._malloc = function() { + return (zl = i._malloc = i.asm.fb).apply(null, arguments); + }, Cm = i._free = function() { + return (Cm = i._free = i.asm.gb).apply(null, arguments); + }, vI = i.___errno_location = function() { + return (vI = i.___errno_location = i.asm.hb).apply(null, arguments); + }, CI = i._emscripten_get_global_libc = function() { + return (CI = i._emscripten_get_global_libc = i.asm.ib).apply(null, arguments); + }, sc = i._pthread_self = function() { + return (sc = i._pthread_self = i.asm.jb).apply(null, arguments); + }, SI = i.___pthread_tsd_run_dtors = function() { + return (SI = i.___pthread_tsd_run_dtors = i.asm.kb).apply(null, arguments); + }, iw = i._emscripten_main_thread_process_queued_calls = function() { + return (iw = i._emscripten_main_thread_process_queued_calls = i.asm.lb).apply(null, arguments); + }, BW = i._emscripten_current_thread_process_queued_calls = function() { + return (BW = i._emscripten_current_thread_process_queued_calls = i.asm.mb).apply(null, arguments); + }, II = i._emscripten_register_main_browser_thread_id = function() { + return (II = i._emscripten_register_main_browser_thread_id = i.asm.nb).apply(null, arguments); + }, NI = i.__emscripten_do_dispatch_to_thread = function() { + return (NI = i.__emscripten_do_dispatch_to_thread = i.asm.ob).apply(null, arguments); + }, TI = i._emscripten_sync_run_in_main_thread_4 = function() { + return (TI = i._emscripten_sync_run_in_main_thread_4 = i.asm.pb).apply(null, arguments); + }, EI = i._emscripten_run_in_main_runtime_thread_js = function() { + return (EI = i._emscripten_run_in_main_runtime_thread_js = i.asm.qb).apply(null, arguments); + }, aw = i.__emscripten_call_on_thread = function() { + return (aw = i.__emscripten_call_on_thread = i.asm.rb).apply(null, arguments); + }, VW = i._emscripten_tls_init = function() { + return (VW = i._emscripten_tls_init = i.asm.sb).apply(null, arguments); + }, lw = i.__emscripten_thread_init = function() { + return (lw = i.__emscripten_thread_init = i.asm.tb).apply(null, arguments); + }, Sm = i.stackSave = function() { + return (Sm = i.stackSave = i.asm.ub).apply(null, arguments); + }, ic = i.stackRestore = function() { + return (ic = i.stackRestore = i.asm.vb).apply(null, arguments); + }, ac = i.stackAlloc = function() { + return (ac = i.stackAlloc = i.asm.wb).apply(null, arguments); + }, AI = i._emscripten_stack_set_limits = function() { + return (AI = i._emscripten_stack_set_limits = i.asm.xb).apply(null, arguments); + }, $I = i._memalign = function() { + return ($I = i._memalign = i.asm.yb).apply(null, arguments); + }, DI = i.__emscripten_allow_main_runtime_queued_calls = 10016, lc = i.__emscripten_main_thread_futex = 11652; + i.cwrap = we, i.PThread = Ee, i.PThread = Ee, i.wasmMemory = Q, i.ExitStatus = Im; + var Hh; + function Im(N) { + this.name = "ExitStatus", this.message = "Program terminated with exit(" + N + ")", this.status = N; + } + Ml = function N() { + Hh || uw(), Hh || (Ml = N); + }; + function uw(N) { + if (N = N || m, vi > 0) + return; + if (x) { + l(i), Pl(), postMessage({ cmd: "loaded" }); + return; + } + if (gm(), vi > 0) + return; + function D() { + Hh || (Hh = true, i.calledRun = true, !pe && (Pl(), zy(), l(i), i.onRuntimeInitialized && i.onRuntimeInitialized(), fn())); + } + i.setStatus ? (i.setStatus("Running..."), setTimeout(function() { + setTimeout(function() { + i.setStatus(""); + }, 1), D(); + }, 1)) : D(); + } + i.run = uw; + function WW(N, D) { + if (!(D && ne && N === 0)) { + if (!D && x) + throw postMessage({ cmd: "exitProcess", returnCode: N }), new Im(N); + ne || (Ee.terminateAllThreads(), ie = N, Ih(), i.onExit && i.onExit(N), pe = true), d(N, new Im(N)); + } + } + if (i.preInit) + for (typeof i.preInit == "function" && (i.preInit = [i.preInit]); i.preInit.length > 0; ) + i.preInit.pop()(); + return x && (ne = false, Ee.initWorker()), uw(), e.ready; + }; + }(); + typeof Oy == "object" && typeof xI == "object" ? xI.exports = gI : typeof define == "function" && define.amd ? define([], function() { + return gI; + }) : typeof Oy == "object" && (Oy.WasmBackendModuleThreadedSimd = gI); +}); +var ZV = Ut((Py, bI) => { + var yI = function() { + var r = typeof document != "undefined" && document.currentScript ? document.currentScript.src : void 0; + return typeof __filename != "undefined" && (r = r || __filename), function(e) { + e = e || {}; + var t = typeof e != "undefined" ? e : {}, n, o; + t.ready = new Promise(function(Z, oe) { + n = Z, o = oe; + }); + var s = {}, a; + for (a in t) + t.hasOwnProperty(a) && (s[a] = t[a]); + var i = [], l = "./this.program", u = function(Z, oe) { + throw oe; + }, c = false, p = false, m = false, f = false; + c = typeof window == "object", p = typeof importScripts == "function", m = typeof process == "object" && typeof process.versions == "object" && typeof process.versions.node == "string", f = !c && !m && !p; + var d = ""; + function h(Z) { + return t.locateFile ? t.locateFile(Z, d) : d + Z; + } + var g, y, w, x, k, C; + m ? (p ? d = hm().dirname(d) + "/" : d = __dirname + "/", g = function(oe, ve) { + return k || (k = pc("fs")), C || (C = hm()), oe = C.normalize(oe), k.readFileSync(oe, ve ? null : "utf8"); + }, w = function(oe) { + var ve = g(oe, true); + return ve.buffer || (ve = new Uint8Array(ve)), G(ve.buffer), ve; + }, process.argv.length > 1 && (l = process.argv[1].replace(/\\/g, "/")), i = process.argv.slice(2), process.on("uncaughtException", function(Z) { + if (!(Z instanceof sw)) + throw Z; + }), process.on("unhandledRejection", Ms), u = function(Z) { + process.exit(Z); + }, t.inspect = function() { + return "[Emscripten Module object]"; + }) : f ? (typeof read != "undefined" && (g = function(oe) { + return read(oe); + }), w = function(oe) { + var ve; + return typeof readbuffer == "function" ? new Uint8Array(readbuffer(oe)) : (ve = read(oe, "binary"), G(typeof ve == "object"), ve); + }, typeof scriptArgs != "undefined" ? i = scriptArgs : typeof arguments != "undefined" && (i = arguments), typeof quit == "function" && (u = function(Z) { + quit(Z); + }), typeof print != "undefined" && (typeof console == "undefined" && (console = {}), console.log = print, console.warn = console.error = typeof printErr != "undefined" ? printErr : print)) : (c || p) && (p ? d = self.location.href : typeof document != "undefined" && document.currentScript && (d = document.currentScript.src), r && (d = r), d.indexOf("blob:") !== 0 ? d = d.substr(0, d.lastIndexOf("/") + 1) : d = "", g = function(Z) { + var oe = new XMLHttpRequest(); + return oe.open("GET", Z, false), oe.send(null), oe.responseText; + }, p && (w = function(Z) { + var oe = new XMLHttpRequest(); + return oe.open("GET", Z, false), oe.responseType = "arraybuffer", oe.send(null), new Uint8Array(oe.response); + }), y = function(Z, oe, ve) { + var ut = new XMLHttpRequest(); + ut.open("GET", Z, true), ut.responseType = "arraybuffer", ut.onload = function() { + if (ut.status == 200 || ut.status == 0 && ut.response) { + oe(ut.response); + return; + } + ve(); + }, ut.onerror = ve, ut.send(null); + }, x = function(Z) { + document.title = Z; + }); + var A = t.print || console.log.bind(console), $ = t.printErr || console.warn.bind(console); + for (a in s) + s.hasOwnProperty(a) && (t[a] = s[a]); + s = null, t.arguments && (i = t.arguments), t.thisProgram && (l = t.thisProgram), t.quit && (u = t.quit); + var R; + t.wasmBinary && (R = t.wasmBinary); + var P = t.noExitRuntime || true; + typeof WebAssembly != "object" && Ms("no native wasm support detected"); + var M, V = false, W; + function G(Z, oe) { + Z || Ms("Assertion failed: " + oe); + } + function U(Z) { + var oe = t["_" + Z]; + return G(oe, "Cannot call unknown function " + Z + ", make sure it is exported"), oe; + } + function H(Z, oe, ve, ut, er) { + var Gt = { string: function(Tn) { + var Ha = 0; + if (Tn != null && Tn !== 0) { + var Uh = (Tn.length << 2) + 1; + Ha = km(Uh), se(Tn, Ha, Uh); + } + return Ha; + }, array: function(Tn) { + var Ha = km(Tn.length); + return pe(Tn, Ha), Ha; + } }; + function et(Tn) { + return oe === "string" ? ne(Tn) : oe === "boolean" ? Boolean(Tn) : Tn; + } + var rt = U(Z), Er = [], Si = 0; + if (ut) + for (var Ii = 0; Ii < ut.length; Ii++) { + var Gh = Gt[ve[Ii]]; + Gh ? (Si === 0 && (Si = Wh()), Er[Ii] = Gh(ut[Ii])) : Er[Ii] = ut[Ii]; + } + var vm = rt.apply(null, Er); + return vm = et(vm), Si !== 0 && jh(Si), vm; + } + function K(Z, oe, ve, ut) { + ve = ve || []; + var er = ve.every(function(et) { + return et === "number"; + }), Gt = oe !== "string"; + return Gt && er && !ut ? U(Z) : function() { + return H(Z, oe, ve, arguments, ut); + }; + } + var re = typeof TextDecoder != "undefined" ? new TextDecoder("utf8") : void 0; + function X(Z, oe, ve) { + for (var ut = oe + ve, er = oe; Z[er] && !(er >= ut); ) + ++er; + if (er - oe > 16 && Z.subarray && re) + return re.decode(Z.subarray(oe, er)); + for (var Gt = ""; oe < er; ) { + var et = Z[oe++]; + if (!(et & 128)) { + Gt += String.fromCharCode(et); + continue; + } + var rt = Z[oe++] & 63; + if ((et & 224) == 192) { + Gt += String.fromCharCode((et & 31) << 6 | rt); + continue; + } + var Er = Z[oe++] & 63; + if ((et & 240) == 224 ? et = (et & 15) << 12 | rt << 6 | Er : et = (et & 7) << 18 | rt << 12 | Er << 6 | Z[oe++] & 63, et < 65536) + Gt += String.fromCharCode(et); + else { + var Si = et - 65536; + Gt += String.fromCharCode(55296 | Si >> 10, 56320 | Si & 1023); + } + } + return Gt; + } + function ne(Z, oe) { + return Z ? X(ge, Z, oe) : ""; + } + function Q(Z, oe, ve, ut) { + if (!(ut > 0)) + return 0; + for (var er = ve, Gt = ve + ut - 1, et = 0; et < Z.length; ++et) { + var rt = Z.charCodeAt(et); + if (rt >= 55296 && rt <= 57343) { + var Er = Z.charCodeAt(++et); + rt = 65536 + ((rt & 1023) << 10) | Er & 1023; + } + if (rt <= 127) { + if (ve >= Gt) + break; + oe[ve++] = rt; + } else if (rt <= 2047) { + if (ve + 1 >= Gt) + break; + oe[ve++] = 192 | rt >> 6, oe[ve++] = 128 | rt & 63; + } else if (rt <= 65535) { + if (ve + 2 >= Gt) + break; + oe[ve++] = 224 | rt >> 12, oe[ve++] = 128 | rt >> 6 & 63, oe[ve++] = 128 | rt & 63; + } else { + if (ve + 3 >= Gt) + break; + oe[ve++] = 240 | rt >> 18, oe[ve++] = 128 | rt >> 12 & 63, oe[ve++] = 128 | rt >> 6 & 63, oe[ve++] = 128 | rt & 63; + } + } + return oe[ve] = 0, ve - er; + } + function se(Z, oe, ve) { + return Q(Z, ge, oe, ve); + } + function pe(Z, oe) { + de.set(Z, oe); + } + function ie(Z, oe) { + return Z % oe > 0 && (Z += oe - Z % oe), Z; + } + var fe, de, ge, we, $e, Ce, Be, qe, lt; + function It(Z) { + fe = Z, t.HEAP8 = de = new Int8Array(Z), t.HEAP16 = we = new Int16Array(Z), t.HEAP32 = Ce = new Int32Array(Z), t.HEAPU8 = ge = new Uint8Array(Z), t.HEAPU16 = $e = new Uint16Array(Z), t.HEAPU32 = Be = new Uint32Array(Z), t.HEAPF32 = qe = new Float32Array(Z), t.HEAPF64 = lt = new Float64Array(Z); + } + var Nt = t.INITIAL_MEMORY || 16777216, Ue, pt = [], ft = [], Bt = [], In = [], Qt = false; + ft.push({ func: function() { + Dh(); + } }); + function pn() { + if (t.preRun) + for (typeof t.preRun == "function" && (t.preRun = [t.preRun]); t.preRun.length; ) + Nn(t.preRun.shift()); + ja(pt); + } + function Br() { + Qt = true, ja(ft); + } + function Zn() { + ja(Bt); + } + function ur() { + if (t.postRun) + for (typeof t.postRun == "function" && (t.postRun = [t.postRun]); t.postRun.length; ) + Hr(t.postRun.shift()); + ja(In); + } + function Nn(Z) { + pt.unshift(Z); + } + function Hr(Z) { + In.unshift(Z); + } + var wr = 0, mn = null, zn = null; + function Ol(Z) { + wr++, t.monitorRunDependencies && t.monitorRunDependencies(wr); + } + function Wa(Z) { + if (wr--, t.monitorRunDependencies && t.monitorRunDependencies(wr), wr == 0 && (mn !== null && (clearInterval(mn), mn = null), zn)) { + var oe = zn; + zn = null, oe(); + } + } + t.preloadedImages = {}, t.preloadedAudios = {}; + function Ms(Z) { + t.onAbort && t.onAbort(Z), Z += "", $(Z), V = true, W = 1, Z = "abort(" + Z + "). Build with -s ASSERTIONS=1 for more info."; + var oe = new WebAssembly.RuntimeError(Z); + throw o(oe), oe; + } + function _i(Z, oe) { + return String.prototype.startsWith ? Z.startsWith(oe) : Z.indexOf(oe) === 0; + } + var gm = "data:application/octet-stream;base64,"; + function Pl(Z) { + return _i(Z, gm); + } + var zy = "file://"; + function Ih(Z) { + return _i(Z, zy); + } + var fn = "tfjs-backend-wasm.wasm"; + Pl(fn) || (fn = h(fn)); + function Nh(Z) { + try { + if (Z == fn && R) + return new Uint8Array(R); + if (w) + return w(Z); + throw "both async and sync fetching of the wasm failed"; + } catch (oe) { + Ms(oe); + } + } + function By() { + if (!R && (c || p)) { + if (typeof fetch == "function" && !Ih(fn)) + return fetch(fn, { credentials: "same-origin" }).then(function(Z) { + if (!Z.ok) + throw "failed to load wasm binary file at '" + fn + "'"; + return Z.arrayBuffer(); + }).catch(function() { + return Nh(fn); + }); + if (y) + return new Promise(function(Z, oe) { + y(fn, function(ve) { + Z(new Uint8Array(ve)); + }, oe); + }); + } + return Promise.resolve().then(function() { + return Nh(fn); + }); + } + function vi() { + var Z = { a: Uy }; + function oe(et, rt) { + var Er = et.exports; + t.asm = Er, M = t.asm.i, It(M.buffer), Ue = t.asm.o, Wa("wasm-instantiate"); + } + Ol("wasm-instantiate"); + function ve(et) { + oe(et.instance); + } + function ut(et) { + return By().then(function(rt) { + return WebAssembly.instantiate(rt, Z); + }).then(et, function(rt) { + $("failed to asynchronously prepare wasm: " + rt), Ms(rt); + }); + } + function er() { + return !R && typeof WebAssembly.instantiateStreaming == "function" && !Pl(fn) && !Ih(fn) && typeof fetch == "function" ? fetch(fn, { credentials: "same-origin" }).then(function(et) { + var rt = WebAssembly.instantiateStreaming(et, Z); + return rt.then(ve, function(Er) { + return $("wasm streaming compile failed: " + Er), $("falling back to ArrayBuffer instantiation"), ut(ve); + }); + }) : ut(ve); + } + if (t.instantiateWasm) + try { + var Gt = t.instantiateWasm(Z, oe); + return Gt; + } catch (et) { + return $("Module.instantiateWasm callback failed with error: " + et), false; + } + return er().catch(o), {}; + } + function ja(Z) { + for (; Z.length > 0; ) { + var oe = Z.shift(); + if (typeof oe == "function") { + oe(t); + continue; + } + var ve = oe.func; + typeof ve == "number" ? oe.arg === void 0 ? Ue.get(ve)() : Ue.get(ve)(oe.arg) : ve(oe.arg === void 0 ? null : oe.arg); + } + } + function Ml() { + Ms(); + } + function Vy(Z, oe, ve) { + ge.copyWithin(Z, oe, oe + ve); + } + function Wy() { + return ge.length; + } + function Ci(Z) { + try { + return M.grow(Z - fe.byteLength + 65535 >>> 16), It(M.buffer), 1; + } catch (oe) { + } + } + function Th(Z) { + var oe = Wy(), ve = 2147483648; + if (Z > ve) + return false; + for (var ut = 1; ut <= 4; ut *= 2) { + var er = oe * (1 + 0.2 / ut); + er = Math.min(er, Z + 100663296); + var Gt = Math.min(ve, ie(Math.max(Z, er), 65536)), et = Ci(Gt); + if (et) + return true; + } + return false; + } + var tc = { mappings: {}, buffers: [null, [], []], printChar: function(Z, oe) { + var ve = tc.buffers[Z]; + oe === 0 || oe === 10 ? ((Z === 1 ? A : $)(X(ve, 0)), ve.length = 0) : ve.push(oe); + }, varargs: void 0, get: function() { + tc.varargs += 4; + var Z = Ce[tc.varargs - 4 >> 2]; + return Z; + }, getStr: function(Z) { + var oe = ne(Z); + return oe; + }, get64: function(Z, oe) { + return Z; + } }; + function Eh(Z) { + return 0; + } + function jy(Z, oe, ve, ut, er) { + } + function Ah(Z, oe, ve, ut) { + for (var er = 0, Gt = 0; Gt < ve; Gt++) { + for (var et = Ce[oe + Gt * 8 >> 2], rt = Ce[oe + (Gt * 8 + 4) >> 2], Er = 0; Er < rt; Er++) + tc.printChar(Z, ge[et + Er]); + er += rt; + } + return Ce[ut >> 2] = er, 0; + } + function dn() { + return 6; + } + function $h(Z) { + return Ce[Vh() >> 2] = Z, Z; + } + function Gy(Z) { + switch (Z) { + case 30: + return 16384; + case 85: + var oe = 2147483648; + return oe / 16384; + case 132: + case 133: + case 12: + case 137: + case 138: + case 15: + case 235: + case 16: + case 17: + case 18: + case 19: + case 20: + case 149: + case 13: + case 10: + case 236: + case 153: + case 9: + case 21: + case 22: + case 159: + case 154: + case 14: + case 77: + case 78: + case 139: + case 82: + case 68: + case 67: + case 164: + case 11: + case 29: + case 47: + case 48: + case 95: + case 52: + case 51: + case 46: + return 200809; + case 27: + case 246: + case 127: + case 128: + case 23: + case 24: + case 160: + case 161: + case 181: + case 182: + case 242: + case 183: + case 184: + case 243: + case 244: + case 245: + case 165: + case 178: + case 179: + case 49: + case 50: + case 168: + case 169: + case 175: + case 170: + case 171: + case 172: + case 97: + case 76: + case 32: + case 173: + case 35: + case 80: + case 81: + case 79: + return -1; + case 176: + case 177: + case 7: + case 155: + case 8: + case 157: + case 125: + case 126: + case 92: + case 93: + case 129: + case 130: + case 131: + case 94: + case 91: + return 1; + case 74: + case 60: + case 69: + case 70: + case 4: + return 1024; + case 31: + case 42: + case 72: + return 32; + case 87: + case 26: + case 33: + return 2147483647; + case 34: + case 1: + return 47839; + case 38: + case 36: + return 99; + case 43: + case 37: + return 2048; + case 0: + return 2097152; + case 3: + return 65536; + case 28: + return 32768; + case 44: + return 32767; + case 75: + return 16384; + case 39: + return 1e3; + case 89: + return 700; + case 71: + return 256; + case 40: + return 255; + case 2: + return 100; + case 180: + return 64; + case 25: + return 20; + case 5: + return 16; + case 6: + return 6; + case 73: + return 4; + case 84: + return typeof navigator == "object" && navigator.hardwareConcurrency || 1; + } + return $h(28), -1; + } + var Uy = { a: Ml, d: Vy, e: Th, f: Eh, c: jy, b: Ah, g: dn, h: Gy }, Hy = vi(), Dh = t.___wasm_call_ctors = function() { + return (Dh = t.___wasm_call_ctors = t.asm.j).apply(null, arguments); + }, rc = t._init = function() { + return (rc = t._init = t.asm.k).apply(null, arguments); + }, xm = t._register_tensor = function() { + return (xm = t._register_tensor = t.asm.l).apply(null, arguments); + }, qy = t._dispose_data = function() { + return (qy = t._dispose_data = t.asm.m).apply(null, arguments); + }, Ky = t._dispose = function() { + return (Ky = t._dispose = t.asm.n).apply(null, arguments); + }, Xy = t._Abs = function() { + return (Xy = t._Abs = t.asm.p).apply(null, arguments); + }, Ee = t._Add = function() { + return (Ee = t._Add = t.asm.q).apply(null, arguments); + }, Yy = t._AddN = function() { + return (Yy = t._AddN = t.asm.r).apply(null, arguments); + }, Zy = t._All = function() { + return (Zy = t._All = t.asm.s).apply(null, arguments); + }, Jy = t._Any = function() { + return (Jy = t._Any = t.asm.t).apply(null, arguments); + }, Qy = t._ArgMax = function() { + return (Qy = t._ArgMax = t.asm.u).apply(null, arguments); + }, eb = t._AvgPool = function() { + return (eb = t._AvgPool = t.asm.v).apply(null, arguments); + }, Ll = t._BatchMatMul = function() { + return (Ll = t._BatchMatMul = t.asm.w).apply(null, arguments); + }, tb = t._Ceil = function() { + return (tb = t._Ceil = t.asm.x).apply(null, arguments); + }, rb = t._ClipByValue = function() { + return (rb = t._ClipByValue = t.asm.y).apply(null, arguments); + }, nb = t._Conv2D = function() { + return (nb = t._Conv2D = t.asm.z).apply(null, arguments); + }, ob = t._Conv2DBackpropInput = function() { + return (ob = t._Conv2DBackpropInput = t.asm.A).apply(null, arguments); + }, sb = t._Cos = function() { + return (sb = t._Cos = t.asm.B).apply(null, arguments); + }, ib = t._Cosh = function() { + return (ib = t._Cosh = t.asm.C).apply(null, arguments); + }, ab = t._CropAndResize = function() { + return (ab = t._CropAndResize = t.asm.D).apply(null, arguments); + }, lb = t._Cumsum = function() { + return (lb = t._Cumsum = t.asm.E).apply(null, arguments); + }, ub = t._DepthToSpace = function() { + return (ub = t._DepthToSpace = t.asm.F).apply(null, arguments); + }, Ga = t._DepthwiseConv2dNative = function() { + return (Ga = t._DepthwiseConv2dNative = t.asm.G).apply(null, arguments); + }, ym = t._Elu = function() { + return (ym = t._Elu = t.asm.H).apply(null, arguments); + }, bm = t._Equal = function() { + return (bm = t._Equal = t.asm.I).apply(null, arguments); + }, cb = t._Exp = function() { + return (cb = t._Exp = t.asm.J).apply(null, arguments); + }, pb = t._FlipLeftRight = function() { + return (pb = t._FlipLeftRight = t.asm.K).apply(null, arguments); + }, mb = t._Floor = function() { + return (mb = t._Floor = t.asm.L).apply(null, arguments); + }, fb = t._FloorDiv = function() { + return (fb = t._FloorDiv = t.asm.M).apply(null, arguments); + }, db = t._FusedBatchNorm = function() { + return (db = t._FusedBatchNorm = t.asm.N).apply(null, arguments); + }, Je = t._FusedConv2D = function() { + return (Je = t._FusedConv2D = t.asm.O).apply(null, arguments); + }, hb = t._FusedDepthwiseConv2D = function() { + return (hb = t._FusedDepthwiseConv2D = t.asm.P).apply(null, arguments); + }, gb = t._Gather = function() { + return (gb = t._Gather = t.asm.Q).apply(null, arguments); + }, xb = t._GatherNd = function() { + return (xb = t._GatherNd = t.asm.R).apply(null, arguments); + }, yb = t._Greater = function() { + return (yb = t._Greater = t.asm.S).apply(null, arguments); + }, bb = t._GreaterEqual = function() { + return (bb = t._GreaterEqual = t.asm.T).apply(null, arguments); + }, wb = t._LeakyRelu = function() { + return (wb = t._LeakyRelu = t.asm.U).apply(null, arguments); + }, wm = t._Less = function() { + return (wm = t._Less = t.asm.V).apply(null, arguments); + }, Rh = t._LessEqual = function() { + return (Rh = t._LessEqual = t.asm.W).apply(null, arguments); + }, Fh = t._Log = function() { + return (Fh = t._Log = t.asm.X).apply(null, arguments); + }, kb = t._LogicalAnd = function() { + return (kb = t._LogicalAnd = t.asm.Y).apply(null, arguments); + }, _b = t._Max = function() { + return (_b = t._Max = t.asm.Z).apply(null, arguments); + }, vb = t._MaxPool = function() { + return (vb = t._MaxPool = t.asm._).apply(null, arguments); + }, Cb = t._Maximum = function() { + return (Cb = t._Maximum = t.asm.$).apply(null, arguments); + }, Sb = t._Mean = function() { + return (Sb = t._Mean = t.asm.aa).apply(null, arguments); + }, Ib = t._Min = function() { + return (Ib = t._Min = t.asm.ba).apply(null, arguments); + }, Nb = t._Minimum = function() { + return (Nb = t._Minimum = t.asm.ca).apply(null, arguments); + }, dt = t._MirrorPad = function() { + return (dt = t._MirrorPad = t.asm.da).apply(null, arguments); + }, Tb = t._Multiply = function() { + return (Tb = t._Multiply = t.asm.ea).apply(null, arguments); + }, Eb = t._Neg = function() { + return (Eb = t._Neg = t.asm.fa).apply(null, arguments); + }, Ab = t._NonMaxSuppressionV3 = function() { + return (Ab = t._NonMaxSuppressionV3 = t.asm.ga).apply(null, arguments); + }, nc = t._NonMaxSuppressionV4 = function() { + return (nc = t._NonMaxSuppressionV4 = t.asm.ha).apply(null, arguments); + }, Oh = t._NonMaxSuppressionV5 = function() { + return (Oh = t._NonMaxSuppressionV5 = t.asm.ia).apply(null, arguments); + }, Ph = t._NotEqual = function() { + return (Ph = t._NotEqual = t.asm.ja).apply(null, arguments); + }, Mh = t._OneHot = function() { + return (Mh = t._OneHot = t.asm.ka).apply(null, arguments); + }, $b = t._PadV2 = function() { + return ($b = t._PadV2 = t.asm.la).apply(null, arguments); + }, Db = t._Pow = function() { + return (Db = t._Pow = t.asm.ma).apply(null, arguments); + }, Lh = t._Prelu = function() { + return (Lh = t._Prelu = t.asm.na).apply(null, arguments); + }, Rb = t._Prod = function() { + return (Rb = t._Prod = t.asm.oa).apply(null, arguments); + }, zh = t._RealDiv = function() { + return (zh = t._RealDiv = t.asm.pa).apply(null, arguments); + }, Ua = t._Relu = function() { + return (Ua = t._Relu = t.asm.qa).apply(null, arguments); + }, Fb = t._Relu6 = function() { + return (Fb = t._Relu6 = t.asm.ra).apply(null, arguments); + }, Ob = t._ResizeBilinear = function() { + return (Ob = t._ResizeBilinear = t.asm.sa).apply(null, arguments); + }, _I = t._Reverse = function() { + return (_I = t._Reverse = t.asm.ta).apply(null, arguments); + }, Bh = t._RotateWithOffset = function() { + return (Bh = t._RotateWithOffset = t.asm.ua).apply(null, arguments); + }, Pb = t._Round = function() { + return (Pb = t._Round = t.asm.va).apply(null, arguments); + }, Mb = t._Rsqrt = function() { + return (Mb = t._Rsqrt = t.asm.wa).apply(null, arguments); + }, Lb = t._ScatterNd = function() { + return (Lb = t._ScatterNd = t.asm.xa).apply(null, arguments); + }, zb = t._SelectV2 = function() { + return (zb = t._SelectV2 = t.asm.ya).apply(null, arguments); + }, Bb = t._Sigmoid = function() { + return (Bb = t._Sigmoid = t.asm.za).apply(null, arguments); + }, Vb = t._Sin = function() { + return (Vb = t._Sin = t.asm.Aa).apply(null, arguments); + }, Wb = t._Softmax = function() { + return (Wb = t._Softmax = t.asm.Ba).apply(null, arguments); + }, jb = t._Sqrt = function() { + return (jb = t._Sqrt = t.asm.Ca).apply(null, arguments); + }, Gb = t._Square = function() { + return (Gb = t._Square = t.asm.Da).apply(null, arguments); + }, Ub = t._SquaredDifference = function() { + return (Ub = t._SquaredDifference = t.asm.Ea).apply(null, arguments); + }, Hb = t._Step = function() { + return (Hb = t._Step = t.asm.Fa).apply(null, arguments); + }, qb = t._StridedSlice = function() { + return (qb = t._StridedSlice = t.asm.Ga).apply(null, arguments); + }, Kb = t._Sub = function() { + return (Kb = t._Sub = t.asm.Ha).apply(null, arguments); + }, Xb = t._Sum = function() { + return (Xb = t._Sum = t.asm.Ia).apply(null, arguments); + }, Yb = t._Tan = function() { + return (Yb = t._Tan = t.asm.Ja).apply(null, arguments); + }, Zb = t._Tanh = function() { + return (Zb = t._Tanh = t.asm.Ka).apply(null, arguments); + }, Jb = t._Tile = function() { + return (Jb = t._Tile = t.asm.La).apply(null, arguments); + }, Qb = t._TopK = function() { + return (Qb = t._TopK = t.asm.Ma).apply(null, arguments); + }, ew = t._Transform = function() { + return (ew = t._Transform = t.asm.Na).apply(null, arguments); + }, tw = t._Transpose = function() { + return (tw = t._Transpose = t.asm.Oa).apply(null, arguments); + }, rw = t.__FusedMatMul = function() { + return (rw = t.__FusedMatMul = t.asm.Pa).apply(null, arguments); + }, nw = t._malloc = function() { + return (nw = t._malloc = t.asm.Qa).apply(null, arguments); + }, ow = t._free = function() { + return (ow = t._free = t.asm.Ra).apply(null, arguments); + }, Vh = t.___errno_location = function() { + return (Vh = t.___errno_location = t.asm.Sa).apply(null, arguments); + }, Wh = t.stackSave = function() { + return (Wh = t.stackSave = t.asm.Ta).apply(null, arguments); + }, jh = t.stackRestore = function() { + return (jh = t.stackRestore = t.asm.Ua).apply(null, arguments); + }, km = t.stackAlloc = function() { + return (km = t.stackAlloc = t.asm.Va).apply(null, arguments); + }; + t.cwrap = K; + var oc; + function sw(Z) { + this.name = "ExitStatus", this.message = "Program terminated with exit(" + Z + ")", this.status = Z; + } + zn = function Z() { + oc || _m(), oc || (zn = Z); + }; + function _m(Z) { + if (Z = Z || i, wr > 0 || (pn(), wr > 0)) + return; + function oe() { + oc || (oc = true, t.calledRun = true, !V && (Br(), Zn(), n(t), t.onRuntimeInitialized && t.onRuntimeInitialized(), ur())); + } + t.setStatus ? (t.setStatus("Running..."), setTimeout(function() { + setTimeout(function() { + t.setStatus(""); + }, 1), oe(); + }, 1)) : oe(); + } + if (t.run = _m, t.preInit) + for (typeof t.preInit == "function" && (t.preInit = [t.preInit]); t.preInit.length > 0; ) + t.preInit.pop()(); + return _m(), e.ready; + }; + }(); + typeof Py == "object" && typeof bI == "object" ? bI.exports = yI : typeof define == "function" && define.amd ? define([], function() { + return yI; + }) : typeof Py == "object" && (Py.WasmBackendModule = yI); +}); +var OI = "3.9.0"; +var PI = "3.9.0"; +var MI = "3.9.0"; +var LI = "3.9.0"; +var zI = "3.9.0"; +var BI = "3.9.0"; +var VI = "3.9.0"; +var WI = "3.9.0"; +var nj = 1e-7; +var oj = 1e-4; +var Ka = class { + constructor(e, t) { + this.backend = e, this.dataMover = t, this.data = new WeakMap(), this.dataIdsCount = 0; } - set(dataId, value) { - this.dataIdsCount++; - this.data.set(dataId, value); + get(e) { + return this.data.has(e) || this.dataMover.moveData(this.backend, e), this.data.get(e); } - has(dataId) { - return this.data.has(dataId); + set(e, t) { + this.dataIdsCount++, this.data.set(e, t); } - delete(dataId) { - this.dataIdsCount--; - return this.data.delete(dataId); + has(e) { + return this.data.has(e); + } + delete(e) { + return this.dataIdsCount--, this.data.delete(e); } numDataIds() { return this.dataIdsCount; } }; -var KernelBackend = class { - refCount(dataId) { - return notYetImplemented("refCount"); +var Ls = class { + refCount(e) { + return Jn("refCount"); } - incRef(dataId) { - return notYetImplemented("incRef"); + incRef(e) { + return Jn("incRef"); } timerAvailable() { return true; } - time(f) { - return notYetImplemented("time"); + time(e) { + return Jn("time"); } - read(dataId) { - return notYetImplemented("read"); + read(e) { + return Jn("read"); } - readSync(dataId) { - return notYetImplemented("readSync"); + readSync(e) { + return Jn("readSync"); } numDataIds() { - return notYetImplemented("numDataIds"); + return Jn("numDataIds"); } - disposeData(dataId, force) { - return notYetImplemented("disposeData"); + disposeData(e, t) { + return Jn("disposeData"); } - write(values, shape, dtype) { - return notYetImplemented("write"); + write(e, t, n) { + return Jn("write"); } - move(dataId, values, shape, dtype, refCount) { - return notYetImplemented("move"); + move(e, t, n, o, s) { + return Jn("move"); } memory() { - return notYetImplemented("memory"); + return Jn("memory"); } floatPrecision() { - return notYetImplemented("floatPrecision"); + return Jn("floatPrecision"); } epsilon() { - return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16; + return this.floatPrecision() === 32 ? nj : oj; } dispose() { - return notYetImplemented("dispose"); + return Jn("dispose"); } }; -function notYetImplemented(kernelName) { - throw new Error(`'${kernelName}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`); +function Jn(r) { + throw new Error(`'${r}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`); } -function shuffle(array2) { - let counter = array2.length; - let index = 0; - while (counter > 0) { - index = Math.random() * counter | 0; - counter--; - swap(array2, counter, index); +function jI(r) { + let e = r.length, t = 0; + for (; e > 0; ) + t = Math.random() * e | 0, e--, Kh(r, e, t); +} +function sj(r, e) { + if (r.length !== e.length) + throw new Error(`Array sizes must match to be shuffled together First array length was ${r.length}Second array length was ${e.length}`); + let t = r.length, n = 0; + for (; t > 0; ) + n = Math.random() * t | 0, t--, Kh(r, t, n), Kh(e, t, n); +} +function mc(r, e, t) { + return Math.max(r, Math.min(e, t)); +} +function ij(r) { + return r % 2 == 0 ? r : r + 1; +} +function Kh(r, e, t) { + let n = r[e]; + r[e] = r[t], r[t] = n; +} +function aj(r) { + let e = 0; + for (let t = 0; t < r.length; t++) + e += r[t]; + return e; +} +function lj(r, e) { + let t = Math.random(); + return e * t + (1 - t) * r; +} +function uj(r, e) { + let t = 0; + for (let n = 0; n < r.length; n++) { + let o = Number(r[n]) - Number(e[n]); + t += o * o; } + return t; } -function shuffleCombo(array2, array22) { - if (array2.length !== array22.length) { - throw new Error(`Array sizes must match to be shuffled together First array length was ${array2.length}Second array length was ${array22.length}`); - } - let counter = array2.length; - let index = 0; - while (counter > 0) { - index = Math.random() * counter | 0; - counter--; - swap(array2, counter, index); - swap(array22, counter, index); - } +function E(r, e) { + if (!r) + throw new Error(typeof e == "string" ? e : e()); } -function clamp(min6, x, max6) { - return Math.max(min6, Math.min(x, max6)); +function $t(r, e, t = "") { + E(Kr(r, e), () => t + ` Shapes ${r} and ${e} must match`); } -function nearestLargerEven(val) { - return val % 2 === 0 ? val : val + 1; +function Bn(r) { + E(r != null, () => "The input to the tensor constructor must be a non-null value."); } -function swap(object2, left, right) { - const temp = object2[left]; - object2[left] = object2[right]; - object2[right] = temp; +function vo(r, e = [], t = false) { + if (e == null && (e = []), Array.isArray(r) || cr(r) && !t) + for (let n = 0; n < r.length; ++n) + vo(r[n], e, t); + else + e.push(r); + return e; } -function sum(arr) { - let sum6 = 0; - for (let i = 0; i < arr.length; i++) { - sum6 += arr[i]; - } - return sum6; -} -function randUniform(a, b) { - const r = Math.random(); - return b * r + (1 - r) * a; -} -function distSquared(a, b) { - let result = 0; - for (let i = 0; i < a.length; i++) { - const diff = Number(a[i]) - Number(b[i]); - result += diff * diff; - } - return result; -} -function assert(expr, msg) { - if (!expr) { - throw new Error(typeof msg === "string" ? msg : msg()); - } -} -function assertShapesMatch(shapeA, shapeB, errorMessagePrefix = "") { - assert(arraysEqual(shapeA, shapeB), () => errorMessagePrefix + ` Shapes ${shapeA} and ${shapeB} must match`); -} -function assertNonNull(a) { - assert(a != null, () => `The input to the tensor constructor must be a non-null value.`); -} -function flatten(arr, result = [], skipTypedArray = false) { - if (result == null) { - result = []; - } - if (Array.isArray(arr) || isTypedArray(arr) && !skipTypedArray) { - for (let i = 0; i < arr.length; ++i) { - flatten(arr[i], result, skipTypedArray); - } - } else { - result.push(arr); - } - return result; -} -function sizeFromShape(shape) { - if (shape.length === 0) { +function nt(r) { + if (r.length === 0) return 1; - } - let size = shape[0]; - for (let i = 1; i < shape.length; i++) { - size *= shape[i]; - } - return size; + let e = r[0]; + for (let t = 1; t < r.length; t++) + e *= r[t]; + return e; } -function isScalarShape(shape) { - return shape.length === 0; +function cj(r) { + return r.length === 0; } -function arraysEqual(n1, n2) { - if (n1 === n2) { +function Kr(r, e) { + if (r === e) return true; - } - if (n1 == null || n2 == null) { + if (r == null || e == null || r.length !== e.length) return false; - } - if (n1.length !== n2.length) { - return false; - } - for (let i = 0; i < n1.length; i++) { - if (n1[i] !== n2[i]) { + for (let t = 0; t < r.length; t++) + if (r[t] !== e[t]) return false; - } - } return true; } -function isInt(a) { - return a % 1 === 0; +function ot(r) { + return r % 1 == 0; } -function tanh(x) { - if (Math.tanh != null) { - return Math.tanh(x); - } - if (x === Infinity) { +function pj(r) { + if (Math.tanh != null) + return Math.tanh(r); + if (r === 1 / 0) return 1; - } else if (x === -Infinity) { + if (r === -1 / 0) return -1; - } else { - const e2x = Math.exp(2 * x); - return (e2x - 1) / (e2x + 1); + { + let e = Math.exp(2 * r); + return (e - 1) / (e + 1); } } -function sizeToSquarishShape(size) { - const width = Math.ceil(Math.sqrt(size)); - return [width, Math.ceil(size / width)]; +function mj(r) { + let e = Math.ceil(Math.sqrt(r)); + return [e, Math.ceil(r / e)]; } -function createShuffledIndices(n) { - const shuffledIndices = new Uint32Array(n); - for (let i = 0; i < n; ++i) { - shuffledIndices[i] = i; - } - shuffle(shuffledIndices); - return shuffledIndices; +function fj(r) { + let e = new Uint32Array(r); + for (let t = 0; t < r; ++t) + e[t] = t; + return jI(e), e; } -function rightPad(a, size) { - if (size <= a.length) { - return a; - } - return a + " ".repeat(size - a.length); +function Vl(r, e) { + return e <= r.length ? r : r + " ".repeat(e - r.length); } -function repeatedTry(checkFn, delayFn = (counter) => 0, maxCounter) { - return new Promise((resolve, reject) => { - let tryCount = 0; - const tryFn = () => { - if (checkFn()) { - resolve(); +function dj(r, e = (n) => 0, t) { + return new Promise((n, o) => { + let s = 0, a = () => { + if (r()) { + n(); return; } - tryCount++; - const nextBackoff = delayFn(tryCount); - if (maxCounter != null && tryCount >= maxCounter) { - reject(); + s++; + let i = e(s); + if (t != null && s >= t) { + o(); return; } - setTimeout(tryFn, nextBackoff); + setTimeout(a, i); }; - tryFn(); + a(); }); } -function inferFromImplicitShape(shape, size) { - let shapeProd = 1; - let implicitIdx = -1; - for (let i = 0; i < shape.length; ++i) { - if (shape[i] >= 0) { - shapeProd *= shape[i]; - } else if (shape[i] === -1) { - if (implicitIdx !== -1) { - throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${implicitIdx} and dim ${i}`); - } - implicitIdx = i; - } else if (shape[i] < 0) { - throw Error(`Shapes can not be < 0. Found ${shape[i]} at dim ${i}`); +function hj(r, e) { + let t = 1, n = -1; + for (let s = 0; s < r.length; ++s) + if (r[s] >= 0) + t *= r[s]; + else if (r[s] === -1) { + if (n !== -1) + throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${n} and dim ${s}`); + n = s; + } else if (r[s] < 0) + throw Error(`Shapes can not be < 0. Found ${r[s]} at dim ${s}`); + if (n === -1) { + if (e > 0 && e !== t) + throw Error(`Size(${e}) must match the product of shape ${r}`); + return r; + } + if (t === 0) + throw Error(`Cannot infer the missing size in [${r}] when there are 0 elements`); + if (e % t != 0) + throw Error(`The implicit shape can't be a fractional number. Got ${e} / ${t}`); + let o = r.slice(); + return o[n] = e / t, o; +} +function ir(r, e) { + let t = e.length; + return r = r == null ? e.map((n, o) => o) : [].concat(r), E(r.every((n) => n >= -t && n < t), () => `All values in axis param must be in range [-${t}, ${t}) but got axis ${r}`), E(r.every((n) => ot(n)), () => `All values in axis param must be integers but got axis ${r}`), r.map((n) => n < 0 ? t + n : n); +} +function cw(r, e) { + let t = [], n = [], o = e != null && Array.isArray(e) && e.length === 0, s = e == null || o ? null : ir(e, r).sort(), a = 0; + for (let i = 0; i < r.length; ++i) { + if (s != null) { + if (s[a] === i && r[i] !== 1) + throw new Error(`Can't squeeze axis ${i} since its dim '${r[i]}' is not 1`); + (s[a] == null || s[a] > i) && r[i] === 1 && (t.push(r[i]), n.push(i)), s[a] <= i && a++; } + r[i] !== 1 && (t.push(r[i]), n.push(i)); } - if (implicitIdx === -1) { - if (size > 0 && size !== shapeProd) { - throw Error(`Size(${size}) must match the product of shape ${shape}`); - } - return shape; - } - if (shapeProd === 0) { - throw Error(`Cannot infer the missing size in [${shape}] when there are 0 elements`); - } - if (size % shapeProd !== 0) { - throw Error(`The implicit shape can't be a fractional number. Got ${size} / ${shapeProd}`); - } - const newShape = shape.slice(); - newShape[implicitIdx] = size / shapeProd; - return newShape; + return { newShape: t, keptDims: n }; } -function parseAxisParam(axis, shape) { - const rank = shape.length; - axis = axis == null ? shape.map((s, i) => i) : [].concat(axis); - assert(axis.every((ax) => ax >= -rank && ax < rank), () => `All values in axis param must be in range [-${rank}, ${rank}) but got axis ${axis}`); - assert(axis.every((ax) => isInt(ax)), () => `All values in axis param must be integers but got axis ${axis}`); - return axis.map((a) => a < 0 ? rank + a : a); +function pw(r, e) { + let t = null; + if (r == null || r === "float32") + t = new Float32Array(e); + else if (r === "int32") + t = new Int32Array(e); + else if (r === "bool") + t = new Uint8Array(e); + else + throw new Error(`Unknown data type ${r}`); + return t; } -function squeezeShape(shape, axis) { - const newShape = []; - const keptDims = []; - const isEmptyArray = axis != null && Array.isArray(axis) && axis.length === 0; - const axes = axis == null || isEmptyArray ? null : parseAxisParam(axis, shape).sort(); - let j = 0; - for (let i = 0; i < shape.length; ++i) { - if (axes != null) { - if (axes[j] === i && shape[i] !== 1) { - throw new Error(`Can't squeeze axis ${i} since its dim '${shape[i]}' is not 1`); - } - if ((axes[j] == null || axes[j] > i) && shape[i] === 1) { - newShape.push(shape[i]); - keptDims.push(i); - } - if (axes[j] <= i) { - j++; - } - } - if (shape[i] !== 1) { - newShape.push(shape[i]); - keptDims.push(i); - } - } - return { newShape, keptDims }; +function mw(r, e) { + let t = null; + if (r == null || r === "float32") + t = new Float32Array(e); + else if (r === "int32") + t = new Int32Array(e); + else if (r === "bool") + t = new Uint8Array(e); + else if (r === "string") + t = new Array(e); + else + throw new Error(`Unknown data type ${r}`); + return t; } -function getTypedArrayFromDType(dtype, size) { - let values = null; - if (dtype == null || dtype === "float32") { - values = new Float32Array(size); - } else if (dtype === "int32") { - values = new Int32Array(size); - } else if (dtype === "bool") { - values = new Uint8Array(size); - } else { - throw new Error(`Unknown data type ${dtype}`); - } - return values; -} -function getArrayFromDType(dtype, size) { - let values = null; - if (dtype == null || dtype === "float32") { - values = new Float32Array(size); - } else if (dtype === "int32") { - values = new Int32Array(size); - } else if (dtype === "bool") { - values = new Uint8Array(size); - } else if (dtype === "string") { - values = new Array(size); - } else { - throw new Error(`Unknown data type ${dtype}`); - } - return values; -} -function checkConversionForErrors(vals, dtype) { - for (let i = 0; i < vals.length; i++) { - const num = vals[i]; - if (isNaN(num) || !isFinite(num)) { - throw Error(`A tensor of type ${dtype} being uploaded contains ${num}.`); - } +function fw(r, e) { + for (let t = 0; t < r.length; t++) { + let n = r[t]; + if (isNaN(n) || !isFinite(n)) + throw Error(`A tensor of type ${e} being uploaded contains ${n}.`); } } -function isValidDtype(dtype) { - return dtype === "bool" || dtype === "complex64" || dtype === "float32" || dtype === "int32" || dtype === "string"; +function dw(r) { + return r === "bool" || r === "complex64" || r === "float32" || r === "int32" || r === "string"; } -function hasEncodingLoss(oldType, newType) { - if (newType === "complex64") { - return false; - } - if (newType === "float32" && oldType !== "complex64") { - return false; - } - if (newType === "int32" && oldType !== "float32" && oldType !== "complex64") { - return false; - } - if (newType === "bool" && oldType === "bool") { - return false; - } - return true; +function gj(r, e) { + return !(e === "complex64" || e === "float32" && r !== "complex64" || e === "int32" && r !== "float32" && r !== "complex64" || e === "bool" && r === "bool"); } -function isTypedArray(a) { - return a instanceof Float32Array || a instanceof Int32Array || a instanceof Uint8Array; +function cr(r) { + return r instanceof Float32Array || r instanceof Int32Array || r instanceof Uint8Array; } -function bytesPerElement(dtype) { - if (dtype === "float32" || dtype === "int32") { +function Xh(r) { + if (r === "float32" || r === "int32") return 4; - } else if (dtype === "complex64") { + if (r === "complex64") return 8; - } else if (dtype === "bool") { + if (r === "bool") return 1; - } else { - throw new Error(`Unknown dtype ${dtype}`); - } + throw new Error(`Unknown dtype ${r}`); } -function bytesFromStringArray(arr) { - if (arr == null) { +function hw(r) { + if (r == null) return 0; - } - let bytes = 0; - arr.forEach((x) => bytes += x.length); - return bytes; + let e = 0; + return r.forEach((t) => e += t.length), e; } -function isString(value) { - return typeof value === "string" || value instanceof String; +function Co(r) { + return typeof r == "string" || r instanceof String; } -function isBoolean(value) { - return typeof value === "boolean"; +function GI(r) { + return typeof r == "boolean"; } -function isNumber(value) { - return typeof value === "number"; +function UI(r) { + return typeof r == "number"; } -function inferDtype(values) { - if (Array.isArray(values)) { - return inferDtype(values[0]); - } - if (values instanceof Float32Array) { - return "float32"; - } else if (values instanceof Int32Array || values instanceof Uint8Array) { - return "int32"; - } else if (isNumber(values)) { - return "float32"; - } else if (isString(values)) { - return "string"; - } else if (isBoolean(values)) { - return "bool"; - } - return "float32"; +function fc(r) { + return Array.isArray(r) ? fc(r[0]) : r instanceof Float32Array ? "float32" : r instanceof Int32Array || r instanceof Uint8Array ? "int32" : UI(r) ? "float32" : Co(r) ? "string" : GI(r) ? "bool" : "float32"; } -function isFunction(f) { - return !!(f && f.constructor && f.call && f.apply); +function zs(r) { + return !!(r && r.constructor && r.call && r.apply); } -function nearestDivisor(size, start) { - for (let i = start; i < size; ++i) { - if (size % i === 0) { - return i; - } - } - return size; +function dc(r, e) { + for (let t = e; t < r; ++t) + if (r % t == 0) + return t; + return r; } -function computeStrides(shape) { - const rank = shape.length; - if (rank < 2) { +function Bs(r) { + let e = r.length; + if (e < 2) return []; - } - const strides = new Array(rank - 1); - strides[rank - 2] = shape[rank - 1]; - for (let i = rank - 3; i >= 0; --i) { - strides[i] = strides[i + 1] * shape[i + 1]; - } - return strides; + let t = new Array(e - 1); + t[e - 2] = r[e - 1]; + for (let n = e - 3; n >= 0; --n) + t[n] = t[n + 1] * r[n + 1]; + return t; } -function createNestedArray(offset, shape, a, isComplex = false) { - const ret = new Array(); - if (shape.length === 1) { - const d = shape[0] * (isComplex ? 2 : 1); - for (let i = 0; i < d; i++) { - ret[i] = a[offset + i]; - } +function HI(r, e, t, n = false) { + let o = new Array(); + if (e.length === 1) { + let s = e[0] * (n ? 2 : 1); + for (let a = 0; a < s; a++) + o[a] = t[r + a]; } else { - const d = shape[0]; - const rest = shape.slice(1); - const len = rest.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1); - for (let i = 0; i < d; i++) { - ret[i] = createNestedArray(offset + i * len, rest, a, isComplex); - } + let s = e[0], a = e.slice(1), i = a.reduce((l, u) => l * u) * (n ? 2 : 1); + for (let l = 0; l < s; l++) + o[l] = HI(r + l * i, a, t, n); } - return ret; + return o; } -function toNestedArray(shape, a, isComplex = false) { - if (shape.length === 0) { - return a[0]; - } - const size = shape.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1); - if (size === 0) { +function Wl(r, e, t = false) { + if (r.length === 0) + return e[0]; + let n = r.reduce((o, s) => o * s) * (t ? 2 : 1); + if (n === 0) return []; - } - if (size !== a.length) { - throw new Error(`[${shape}] does not match the input size ${a.length}${isComplex ? " for a complex tensor" : ""}.`); - } - return createNestedArray(0, shape, a, isComplex); + if (n !== e.length) + throw new Error(`[${r}] does not match the input size ${e.length}${t ? " for a complex tensor" : ""}.`); + return HI(0, r, e, t); } -function makeOnesTypedArray(size, dtype) { - const array2 = makeZerosTypedArray(size, dtype); - for (let i = 0; i < array2.length; i++) { - array2[i] = 1; - } - return array2; +function Nm(r, e) { + let t = hc(r, e); + for (let n = 0; n < t.length; n++) + t[n] = 1; + return t; } -function makeZerosTypedArray(size, dtype) { - if (dtype == null || dtype === "float32" || dtype === "complex64") { - return new Float32Array(size); - } else if (dtype === "int32") { - return new Int32Array(size); - } else if (dtype === "bool") { - return new Uint8Array(size); - } else { - throw new Error(`Unknown data type ${dtype}`); - } +function hc(r, e) { + if (e == null || e === "float32" || e === "complex64") + return new Float32Array(r); + if (e === "int32") + return new Int32Array(r); + if (e === "bool") + return new Uint8Array(r); + throw new Error(`Unknown data type ${e}`); } -function makeZerosNestedTypedArray(shape, dtype) { - const size = shape.reduce((prev, curr) => prev * curr, 1); - if (dtype == null || dtype === "float32") { - return toNestedArray(shape, new Float32Array(size)); - } else if (dtype === "int32") { - return toNestedArray(shape, new Int32Array(size)); - } else if (dtype === "bool") { - return toNestedArray(shape, new Uint8Array(size)); - } else { - throw new Error(`Unknown data type ${dtype}`); - } +function xj(r, e) { + let t = r.reduce((n, o) => n * o, 1); + if (e == null || e === "float32") + return Wl(r, new Float32Array(t)); + if (e === "int32") + return Wl(r, new Int32Array(t)); + if (e === "bool") + return Wl(r, new Uint8Array(t)); + throw new Error(`Unknown data type ${e}`); } -function assertNonNegativeIntegerDimensions(shape) { - shape.forEach((dimSize) => { - assert(Number.isInteger(dimSize) && dimSize >= 0, () => `Tensor must have a shape comprised of positive integers but got shape [${shape}].`); +function Tm(r) { + r.forEach((e) => { + E(Number.isInteger(e) && e >= 0, () => `Tensor must have a shape comprised of positive integers but got shape [${r}].`); }); } -function locToIndex(locs, rank, strides) { - if (rank === 0) { +function yj(r, e, t) { + if (e === 0) return 0; - } else if (rank === 1) { - return locs[0]; - } - let index = locs[locs.length - 1]; - for (let i = 0; i < locs.length - 1; ++i) { - index += strides[i] * locs[i]; - } - return index; + if (e === 1) + return r[0]; + let n = r[r.length - 1]; + for (let o = 0; o < r.length - 1; ++o) + n += t[o] * r[o]; + return n; } -function indexToLoc(index, rank, strides) { - if (rank === 0) { +function bj(r, e, t) { + if (e === 0) return []; - } else if (rank === 1) { - return [index]; - } - const locs = new Array(rank); - for (let i = 0; i < locs.length - 1; ++i) { - locs[i] = Math.floor(index / strides[i]); - index -= locs[i] * strides[i]; - } - locs[locs.length - 1] = index; - return locs; + if (e === 1) + return [r]; + let n = new Array(e); + for (let o = 0; o < n.length - 1; ++o) + n[o] = Math.floor(r / t[o]), r -= n[o] * t[o]; + return n[n.length - 1] = r, n; } -function isPromise(object2) { - return object2 && object2.then && typeof object2.then === "function"; +function Em(r) { + return r && r.then && typeof r.then == "function"; } -function warn(...msg) { - if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) { - console.warn(...msg); - } +function Vn(...r) { + j().getBool("IS_TEST") || j().getBool("PROD") || console.warn(...r); } -function log2(...msg) { - if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) { - console.log(...msg); - } +function wj(...r) { + j().getBool("IS_TEST") || j().getBool("PROD") || console.log(...r); } -var TENSORFLOWJS_FLAGS_PREFIX = "tfjsflags"; -var Environment = class { - constructor(global2) { - this.global = global2; - this.flags = {}; - this.flagRegistry = {}; - this.urlFlags = {}; - this.getQueryParams = getQueryParams; - this.populateURLFlags(); +var qI = "tfjsflags"; +var Yh = class { + constructor(e) { + this.global = e, this.flags = {}, this.flagRegistry = {}, this.urlFlags = {}, this.getQueryParams = kj, this.populateURLFlags(); } - setPlatform(platformName, platform) { - if (this.platform != null) { - warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${platform}.`); - } - this.platformName = platformName; - this.platform = platform; + setPlatform(e, t) { + this.platform != null && Vn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`), this.platformName = e, this.platform = t; } - registerFlag(flagName, evaluationFn, setHook) { - this.flagRegistry[flagName] = { evaluationFn, setHook }; - if (this.urlFlags[flagName] != null) { - const flagValue = this.urlFlags[flagName]; - warn(`Setting feature override from URL ${flagName}: ${flagValue}.`); - this.set(flagName, flagValue); + registerFlag(e, t, n) { + if (this.flagRegistry[e] = { evaluationFn: t, setHook: n }, this.urlFlags[e] != null) { + let o = this.urlFlags[e]; + Vn(`Setting feature override from URL ${e}: ${o}.`), this.set(e, o); } } - async getAsync(flagName) { - if (flagName in this.flags) { - return this.flags[flagName]; - } - this.flags[flagName] = await this.evaluateFlag(flagName); - return this.flags[flagName]; + async getAsync(e) { + return e in this.flags ? this.flags[e] : (this.flags[e] = await this.evaluateFlag(e), this.flags[e]); } - get(flagName) { - if (flagName in this.flags) { - return this.flags[flagName]; - } - const flagValue = this.evaluateFlag(flagName); - if (isPromise(flagValue)) { - throw new Error(`Flag ${flagName} cannot be synchronously evaluated. Please use getAsync() instead.`); - } - this.flags[flagName] = flagValue; - return this.flags[flagName]; + get(e) { + if (e in this.flags) + return this.flags[e]; + let t = this.evaluateFlag(e); + if (Em(t)) + throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`); + return this.flags[e] = t, this.flags[e]; } - getNumber(flagName) { - return this.get(flagName); + getNumber(e) { + return this.get(e); } - getBool(flagName) { - return this.get(flagName); + getBool(e) { + return this.get(e); } getFlags() { return this.flags; @@ -6779,9050 +4258,5359 @@ var Environment = class { get features() { return this.flags; } - set(flagName, value) { - if (this.flagRegistry[flagName] == null) { - throw new Error(`Cannot set flag ${flagName} as it has not been registered.`); - } - this.flags[flagName] = value; - if (this.flagRegistry[flagName].setHook != null) { - this.flagRegistry[flagName].setHook(value); - } + set(e, t) { + if (this.flagRegistry[e] == null) + throw new Error(`Cannot set flag ${e} as it has not been registered.`); + this.flags[e] = t, this.flagRegistry[e].setHook != null && this.flagRegistry[e].setHook(t); } - evaluateFlag(flagName) { - if (this.flagRegistry[flagName] == null) { - throw new Error(`Cannot evaluate flag '${flagName}': no evaluation function found.`); - } - return this.flagRegistry[flagName].evaluationFn(); + evaluateFlag(e) { + if (this.flagRegistry[e] == null) + throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`); + return this.flagRegistry[e].evaluationFn(); } - setFlags(flags) { - this.flags = Object.assign({}, flags); + setFlags(e) { + this.flags = Object.assign({}, e); } reset() { - this.flags = {}; - this.urlFlags = {}; - this.populateURLFlags(); + this.flags = {}, this.urlFlags = {}, this.populateURLFlags(); } populateURLFlags() { - if (typeof this.global === "undefined" || typeof this.global.location === "undefined" || typeof this.global.location.search === "undefined") { + if (typeof this.global == "undefined" || typeof this.global.location == "undefined" || typeof this.global.location.search == "undefined") return; - } - const urlParams = this.getQueryParams(this.global.location.search); - if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) { - const keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(","); - keyValues.forEach((keyValue) => { - const [key, value] = keyValue.split(":"); - this.urlFlags[key] = parseValue(key, value); - }); - } + let e = this.getQueryParams(this.global.location.search); + qI in e && e[qI].split(",").forEach((n) => { + let [o, s] = n.split(":"); + this.urlFlags[o] = vj(o, s); + }); } }; -function getQueryParams(queryString) { - const params = {}; - queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (s, ...t) => { - decodeParam(params, t[0], t[1]); - return t.join("="); - }); - return params; +function kj(r) { + let e = {}; + return r.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (t, ...n) => (_j(e, n[0], n[1]), n.join("="))), e; } -function decodeParam(params, name, value) { - params[decodeURIComponent(name)] = decodeURIComponent(value || ""); +function _j(r, e, t) { + r[decodeURIComponent(e)] = decodeURIComponent(t || ""); } -function parseValue(flagName, value) { - value = value.toLowerCase(); - if (value === "true" || value === "false") { - return value === "true"; - } else if (`${+value}` === value) { - return +value; - } - throw new Error(`Could not parse value flag value ${value} for flag ${flagName}.`); +function vj(r, e) { + if (e = e.toLowerCase(), e === "true" || e === "false") + return e === "true"; + if (`${+e}` === e) + return +e; + throw new Error(`Could not parse value flag value ${e} for flag ${r}.`); } -function env() { - return ENV; +function j() { + return gw; } -var ENV = null; -function setEnvironmentGlobal(environment) { - ENV = environment; +var gw = null; +function KI(r) { + gw = r; } -var globalNameSpace; -function getGlobalNamespace() { - if (globalNameSpace == null) { - let ns; - if (typeof window !== "undefined") { - ns = window; - } else if (typeof global !== "undefined") { - ns = global; - } else if (typeof process !== "undefined") { - ns = process; - } else if (typeof self !== "undefined") { - ns = self; - } else { +var xw; +function yw() { + if (xw == null) { + let r; + if (typeof window != "undefined") + r = window; + else if (typeof global != "undefined") + r = global; + else if (typeof process != "undefined") + r = process; + else if (typeof self != "undefined") + r = self; + else throw new Error("Could not find a global object"); - } - globalNameSpace = ns; + xw = r; } - return globalNameSpace; + return xw; } -function getGlobalMap() { - const ns = getGlobalNamespace(); - if (ns._tfGlobals == null) { - ns._tfGlobals = new Map(); - } - return ns._tfGlobals; +function Cj() { + let r = yw(); + return r._tfGlobals == null && (r._tfGlobals = new Map()), r._tfGlobals; } -function getGlobal(key, init2) { - const globalMap = getGlobalMap(); - if (globalMap.has(key)) { - return globalMap.get(key); - } else { - const singleton = init2(); - globalMap.set(key, singleton); - return globalMap.get(key); +function Am(r, e) { + let t = Cj(); + if (t.has(r)) + return t.get(r); + { + let n = e(); + return t.set(r, n), t.get(r); } } -var Abs = "Abs"; -var Acos = "Acos"; -var Acosh = "Acosh"; -var Add = "Add"; -var AddN = "AddN"; -var All = "All"; -var Any = "Any"; -var ArgMax = "ArgMax"; -var ArgMin = "ArgMin"; -var Asin = "Asin"; -var Asinh = "Asinh"; -var Atan = "Atan"; -var Atanh = "Atanh"; -var Atan2 = "Atan2"; -var AvgPool = "AvgPool"; -var AvgPoolGrad = "AvgPoolGrad"; -var AvgPool3D = "AvgPool3D"; -var AvgPool3DGrad = "AvgPool3DGrad"; -var BatchMatMul = "BatchMatMul"; -var BatchToSpaceND = "BatchToSpaceND"; -var Bincount = "Bincount"; -var BroadcastTo = "BroadcastTo"; -var BroadcastArgs = "BroadcastArgs"; -var Cast = "Cast"; -var Ceil = "Ceil"; -var ClipByValue = "ClipByValue"; -var Complex = "Complex"; -var ComplexAbs = "ComplexAbs"; -var Concat = "Concat"; -var Conv2D = "Conv2D"; -var Conv2DBackpropFilter = "Conv2DBackpropFilter"; -var Conv2DBackpropInput = "Conv2DBackpropInput"; -var Conv3D = "Conv3D"; -var Conv3DBackpropFilterV2 = "Conv3DBackpropFilterV2"; -var Conv3DBackpropInputV2 = "Conv3DBackpropInputV2"; -var Cos = "Cos"; -var Cosh = "Cosh"; -var Cumsum = "Cumsum"; -var CropAndResize = "CropAndResize"; -var DenseBincount = "DenseBincount"; -var DepthToSpace = "DepthToSpace"; -var DepthwiseConv2dNative = "DepthwiseConv2dNative"; -var DepthwiseConv2dNativeBackpropFilter = "DepthwiseConv2dNativeBackpropFilter"; -var DepthwiseConv2dNativeBackpropInput = "DepthwiseConv2dNativeBackpropInput"; -var Diag = "Diag"; -var Dilation2D = "Dilation2D"; -var Dilation2DBackpropInput = "Dilation2DBackpropInput"; -var Dilation2DBackpropFilter = "Dilation2DBackpropFilter"; -var RealDiv = "RealDiv"; -var Einsum = "Einsum"; -var Elu = "Elu"; -var EluGrad = "EluGrad"; -var Erf = "Erf"; -var Equal = "Equal"; -var Exp = "Exp"; -var ExpandDims = "ExpandDims"; -var Expm1 = "Expm1"; -var FFT = "FFT"; -var Fill = "Fill"; -var FlipLeftRight = "FlipLeftRight"; -var Floor = "Floor"; -var FloorDiv = "FloorDiv"; -var FusedBatchNorm = "FusedBatchNorm"; -var GatherV2 = "GatherV2"; -var GatherNd = "GatherNd"; -var Greater = "Greater"; -var GreaterEqual = "GreaterEqual"; -var Identity = "Identity"; -var IFFT = "IFFT"; -var Imag = "Imag"; -var IsFinite = "IsFinite"; -var IsInf = "IsInf"; -var IsNan = "IsNan"; -var LeakyRelu = "LeakyRelu"; -var Less = "Less"; -var LessEqual = "LessEqual"; -var LinSpace = "LinSpace"; -var Log = "Log"; -var Log1p = "Log1p"; -var LogicalAnd = "LogicalAnd"; -var LogicalNot = "LogicalNot"; -var LogicalOr = "LogicalOr"; -var LogSoftmax = "LogSoftmax"; -var LRN = "LRN"; -var LRNGrad = "LRNGrad"; -var Max = "Max"; -var Maximum = "Maximum"; -var MaxPool = "MaxPool"; -var MaxPoolGrad = "MaxPoolGrad"; -var MaxPool3D = "MaxPool3D"; -var MaxPool3DGrad = "MaxPool3DGrad"; -var MaxPoolWithArgmax = "MaxPoolWithArgmax"; -var Mean = "Mean"; -var Min = "Min"; -var Minimum = "Minimum"; -var MirrorPad = "MirrorPad"; -var Mod = "Mod"; -var Multinomial = "Multinomial"; -var Multiply = "Multiply"; -var Neg = "Neg"; -var NotEqual = "NotEqual"; -var NonMaxSuppressionV3 = "NonMaxSuppressionV3"; -var NonMaxSuppressionV4 = "NonMaxSuppressionV4"; -var NonMaxSuppressionV5 = "NonMaxSuppressionV5"; -var OnesLike = "OnesLike"; -var OneHot = "OneHot"; -var Pack = "Pack"; -var PadV2 = "PadV2"; -var Pool = "Pool"; -var Pow = "Pow"; -var Prelu = "Prelu"; -var Prod = "Prod"; -var Range = "Range"; -var Real = "Real"; -var Reciprocal = "Reciprocal"; -var Relu = "Relu"; -var Reshape = "Reshape"; -var ResizeNearestNeighbor = "ResizeNearestNeighbor"; -var ResizeNearestNeighborGrad = "ResizeNearestNeighborGrad"; -var ResizeBilinear = "ResizeBilinear"; -var ResizeBilinearGrad = "ResizeBilinearGrad"; -var Relu6 = "Relu6"; -var Reverse = "Reverse"; -var Round = "Round"; -var Rsqrt = "Rsqrt"; -var ScatterNd = "ScatterNd"; -var Select = "Select"; -var Selu = "Selu"; -var Slice = "Slice"; -var Sin = "Sin"; -var Sinh = "Sinh"; -var Sign = "Sign"; -var Sigmoid = "Sigmoid"; -var Softplus = "Softplus"; -var Sqrt = "Sqrt"; -var Sum = "Sum"; -var SpaceToBatchND = "SpaceToBatchND"; -var SplitV = "SplitV"; -var Softmax = "Softmax"; -var SparseFillEmptyRows = "SparseFillEmptyRows"; -var SparseReshape = "SparseReshape"; -var SparseSegmentMean = "SparseSegmentMean"; -var SparseSegmentSum = "SparseSegmentSum"; -var SparseToDense = "SparseToDense"; -var SquaredDifference = "SquaredDifference"; -var Square = "Square"; -var StridedSlice = "StridedSlice"; -var StringNGrams = "StringNGrams"; -var StringSplit = "StringSplit"; -var StringToHashBucketFast = "StringToHashBucketFast"; -var Sub = "Sub"; -var Tan = "Tan"; -var Tanh = "Tanh"; -var Tile = "Tile"; -var TopK = "TopK"; -var Transform = "Transform"; -var Transpose = "Transpose"; -var Unique = "Unique"; -var Unpack = "Unpack"; -var UnsortedSegmentSum = "UnsortedSegmentSum"; -var ZerosLike = "ZerosLike"; -var Step = "Step"; -var FromPixels = "FromPixels"; -var RotateWithOffset = "RotateWithOffset"; -var _FusedMatMul = "_FusedMatMul"; -var FusedConv2D = "FusedConv2D"; -var FusedDepthwiseConv2D = "FusedDepthwiseConv2D"; -var kernelRegistry = getGlobal("kernelRegistry", () => new Map()); -var gradRegistry = getGlobal("gradRegistry", () => new Map()); -function getKernel(kernelName, backendName) { - const key = makeKey(kernelName, backendName); - return kernelRegistry.get(key); +var Vs = "Abs"; +var Ni = "Acos"; +var Ti = "Acosh"; +var Wn = "Add"; +var So = "AddN"; +var Ei = "All"; +var Ai = "Any"; +var Io = "ArgMax"; +var Xa = "ArgMin"; +var $i = "Asin"; +var Di = "Asinh"; +var Ri = "Atan"; +var Fi = "Atanh"; +var Oi = "Atan2"; +var No = "AvgPool"; +var gc = "AvgPoolGrad"; +var Ya = "AvgPool3D"; +var xc = "AvgPool3DGrad"; +var To = "BatchMatMul"; +var Ws = "BatchToSpaceND"; +var yc = "Bincount"; +var XI = "BroadcastTo"; +var Zh = "BroadcastArgs"; +var Qn = "Cast"; +var Eo = "Ceil"; +var eo = "ClipByValue"; +var bc = "Complex"; +var Za = "ComplexAbs"; +var js = "Concat"; +var Ao = "Conv2D"; +var wc = "Conv2DBackpropFilter"; +var $o = "Conv2DBackpropInput"; +var Ja = "Conv3D"; +var kc = "Conv3DBackpropFilterV2"; +var _c = "Conv3DBackpropInputV2"; +var Do = "Cos"; +var Ro = "Cosh"; +var Fo = "Cumsum"; +var Pi = "CropAndResize"; +var vc = "DenseBincount"; +var Mi = "DepthToSpace"; +var Oo = "DepthwiseConv2dNative"; +var Cc = "DepthwiseConv2dNativeBackpropFilter"; +var Sc = "DepthwiseConv2dNativeBackpropInput"; +var Ic = "Diag"; +var Qa = "Dilation2D"; +var $m = "Dilation2DBackpropInput"; +var Dm = "Dilation2DBackpropFilter"; +var Po = "RealDiv"; +var Nc = "Einsum"; +var Mo = "Elu"; +var Tc = "EluGrad"; +var Li = "Erf"; +var zi = "Equal"; +var Lo = "Exp"; +var Gs = "ExpandDims"; +var Bi = "Expm1"; +var Ec = "FFT"; +var el = "Fill"; +var Vi = "FlipLeftRight"; +var zo = "Floor"; +var Bo = "FloorDiv"; +var Vo = "FusedBatchNorm"; +var Us = "GatherV2"; +var Wi = "GatherNd"; +var ji = "Greater"; +var Wo = "GreaterEqual"; +var to = "Identity"; +var Ac = "IFFT"; +var $c = "Imag"; +var Gi = "IsFinite"; +var Ui = "IsInf"; +var Hi = "IsNan"; +var jo = "LeakyRelu"; +var qi = "Less"; +var Ki = "LessEqual"; +var Dc = "LinSpace"; +var Go = "Log"; +var Xi = "Log1p"; +var Yi = "LogicalAnd"; +var jl = "LogicalNot"; +var Gl = "LogicalOr"; +var YI = "LogSoftmax"; +var tl = "LRN"; +var Rc = "LRNGrad"; +var Uo = "Max"; +var Ho = "Maximum"; +var qo = "MaxPool"; +var Fc = "MaxPoolGrad"; +var rl = "MaxPool3D"; +var Oc = "MaxPool3DGrad"; +var Pc = "MaxPoolWithArgmax"; +var Ko = "Mean"; +var Xo = "Min"; +var Yo = "Minimum"; +var Zo = "MirrorPad"; +var Zi = "Mod"; +var Mc = "Multinomial"; +var Jo = "Multiply"; +var Hs = "Neg"; +var Ji = "NotEqual"; +var Qi = "NonMaxSuppressionV3"; +var ea = "NonMaxSuppressionV4"; +var ta = "NonMaxSuppressionV5"; +var qs = "OnesLike"; +var Qo = "OneHot"; +var Ks = "Pack"; +var es = "PadV2"; +var fse = "Pool"; +var ts = "Pow"; +var rs = "Prelu"; +var ra = "Prod"; +var nl = "Range"; +var Lc = "Real"; +var na = "Reciprocal"; +var ns = "Relu"; +var Xs = "Reshape"; +var ol = "ResizeNearestNeighbor"; +var zc = "ResizeNearestNeighborGrad"; +var os = "ResizeBilinear"; +var Bc = "ResizeBilinearGrad"; +var ss = "Relu6"; +var is = "Reverse"; +var as = "Round"; +var ls = "Rsqrt"; +var oa = "ScatterNd"; +var Ys = "Select"; +var sa = "Selu"; +var Zs = "Slice"; +var us = "Sin"; +var ia = "Sinh"; +var aa = "Sign"; +var cs = "Sigmoid"; +var la = "Softplus"; +var ps = "Sqrt"; +var ms = "Sum"; +var Js = "SpaceToBatchND"; +var Qs = "SplitV"; +var fs = "Softmax"; +var Vc = "SparseFillEmptyRows"; +var Wc = "SparseReshape"; +var jc = "SparseSegmentMean"; +var Gc = "SparseSegmentSum"; +var Uc = "SparseToDense"; +var ds = "SquaredDifference"; +var sl = "Square"; +var ua = "StridedSlice"; +var Hc = "StringNGrams"; +var qc = "StringSplit"; +var Kc = "StringToHashBucketFast"; +var hs = "Sub"; +var gs = "Tan"; +var xs = "Tanh"; +var jn = "Tile"; +var ca = "TopK"; +var pa = "Transform"; +var ys = "Transpose"; +var Xc = "Unique"; +var ei = "Unpack"; +var il = "UnsortedSegmentSum"; +var ti = "ZerosLike"; +var ro = "Step"; +var Rm = "FromPixels"; +var ma = "RotateWithOffset"; +var ri = "_FusedMatMul"; +var ni = "FusedConv2D"; +var oi = "FusedDepthwiseConv2D"; +var Yc = Am("kernelRegistry", () => new Map()); +var Fm = Am("gradRegistry", () => new Map()); +function Om(r, e) { + let t = ww(r, e); + return Yc.get(t); } -function getGradient(kernelName) { - return gradRegistry.get(kernelName); +function bw(r) { + return Fm.get(r); } -function getKernelsForBackend(backendName) { - const it = kernelRegistry.entries(); - const result = []; - while (true) { - const { done, value } = it.next(); - if (done) { +function Jh(r) { + let e = Yc.entries(), t = []; + for (; ; ) { + let { done: n, value: o } = e.next(); + if (n) break; - } - const [key, config3] = value; - const [backend22] = key.split("_"); - if (backend22 === backendName) { - result.push(config3); - } + let [s, a] = o, [i] = s.split("_"); + i === r && t.push(a); } - return result; + return t; } -function registerKernel(config3) { - const { kernelName, backendName } = config3; - const key = makeKey(kernelName, backendName); - if (kernelRegistry.has(key)) { - warn(`The kernel '${kernelName}' for backend '${backendName}' is already registered`); - } - kernelRegistry.set(key, config3); +function Ul(r) { + let { kernelName: e, backendName: t } = r, n = ww(e, t); + Yc.has(n) && Vn(`The kernel '${e}' for backend '${t}' is already registered`), Yc.set(n, r); } -function registerGradient(config3) { - const { kernelName } = config3; - if (gradRegistry.has(kernelName)) { - if (env().getBool("DEBUG")) { - warn(`Overriding the gradient for '${kernelName}'`); - } - } - gradRegistry.set(kernelName, config3); +function ZI(r) { + let { kernelName: e } = r; + Fm.has(e) && j().getBool("DEBUG") && Vn(`Overriding the gradient for '${e}'`), Fm.set(e, r); } -function unregisterKernel(kernelName, backendName) { - const key = makeKey(kernelName, backendName); - if (!kernelRegistry.has(key)) { - throw new Error(`The kernel '${kernelName}' for backend '${backendName}' is not registered`); - } - kernelRegistry.delete(key); +function yse(r, e) { + let t = ww(r, e); + if (!Yc.has(t)) + throw new Error(`The kernel '${r}' for backend '${e}' is not registered`); + Yc.delete(t); } -function unregisterGradient(kernelName) { - if (!gradRegistry.has(kernelName)) { - throw new Error(`The gradient '${kernelName}' for backend is not registered`); - } - gradRegistry.delete(kernelName); +function bse(r) { + if (!Fm.has(r)) + throw new Error(`The gradient '${r}' for backend is not registered`); + Fm.delete(r); } -function copyRegisteredKernels(registeredBackendName, newBackendName) { - const kernels = getKernelsForBackend(registeredBackendName); - kernels.forEach((kernelConfig) => { - const newKernelConfig = Object.assign({}, kernelConfig, { backendName: newBackendName }); - registerKernel(newKernelConfig); +function wse(r, e) { + Jh(r).forEach((n) => { + let o = Object.assign({}, n, { backendName: e }); + Ul(o); }); } -function makeKey(kernelName, backendName) { - return `${backendName}_${kernelName}`; +function ww(r, e) { + return `${e}_${r}`; } -var util_exports = {}; -__export2(util_exports, { - arraysEqual: () => arraysEqual, - assert: () => assert, - assertNonNegativeIntegerDimensions: () => assertNonNegativeIntegerDimensions, - assertNonNull: () => assertNonNull, - assertShapesMatch: () => assertShapesMatch, - bytesFromStringArray: () => bytesFromStringArray, - bytesPerElement: () => bytesPerElement, - checkConversionForErrors: () => checkConversionForErrors, - clamp: () => clamp, - computeStrides: () => computeStrides, - createScalarValue: () => createScalarValue, - createShuffledIndices: () => createShuffledIndices, - decodeString: () => decodeString, - distSquared: () => distSquared, - encodeString: () => encodeString, - fetch: () => fetch3, - fingerPrint64: () => fingerPrint64, - flatten: () => flatten, - getArrayFromDType: () => getArrayFromDType, - getTypedArrayFromDType: () => getTypedArrayFromDType, - hasEncodingLoss: () => hasEncodingLoss, - hexToLong: () => hexToLong, - indexToLoc: () => indexToLoc, - inferDtype: () => inferDtype, - inferFromImplicitShape: () => inferFromImplicitShape, - isBoolean: () => isBoolean, - isFunction: () => isFunction, - isInt: () => isInt, - isNumber: () => isNumber, - isPromise: () => isPromise, - isScalarShape: () => isScalarShape, - isString: () => isString, - isTypedArray: () => isTypedArray, - isValidDtype: () => isValidDtype, - locToIndex: () => locToIndex, - makeOnesTypedArray: () => makeOnesTypedArray, - makeZerosNestedTypedArray: () => makeZerosNestedTypedArray, - makeZerosTypedArray: () => makeZerosTypedArray, - nearestDivisor: () => nearestDivisor, - nearestLargerEven: () => nearestLargerEven, - now: () => now2, - parseAxisParam: () => parseAxisParam, - randUniform: () => randUniform, - repeatedTry: () => repeatedTry, - rightPad: () => rightPad, - shuffle: () => shuffle, - shuffleCombo: () => shuffleCombo, - sizeFromShape: () => sizeFromShape, - sizeToSquarishShape: () => sizeToSquarishShape, - squeezeShape: () => squeezeShape, - sum: () => sum, - swap: () => swap, - tanh: () => tanh, - toNestedArray: () => toNestedArray, - toTypedArray: () => toTypedArray -}); -var LongExports = __toModule(require_long()); -var Long = LongExports.default || LongExports; -function hexToLong(hex) { - return Long.fromString(hex, true, 16); +var b = {}; +He(b, { arraysEqual: () => Kr, assert: () => E, assertNonNegativeIntegerDimensions: () => Tm, assertNonNull: () => Bn, assertShapesMatch: () => $t, bytesFromStringArray: () => hw, bytesPerElement: () => Xh, checkConversionForErrors: () => fw, clamp: () => mc, computeStrides: () => Bs, createScalarValue: () => $j, createShuffledIndices: () => fj, decodeString: () => ep, distSquared: () => uj, encodeString: () => ll, fetch: () => Rj, fingerPrint64: () => Aj, flatten: () => vo, getArrayFromDType: () => mw, getTypedArrayFromDType: () => pw, hasEncodingLoss: () => gj, hexToLong: () => Pm, indexToLoc: () => bj, inferDtype: () => fc, inferFromImplicitShape: () => hj, isBoolean: () => GI, isFunction: () => zs, isInt: () => ot, isNumber: () => UI, isPromise: () => Em, isScalarShape: () => cj, isString: () => Co, isTypedArray: () => cr, isValidDtype: () => dw, locToIndex: () => yj, makeOnesTypedArray: () => Nm, makeZerosNestedTypedArray: () => xj, makeZerosTypedArray: () => hc, nearestDivisor: () => dc, nearestLargerEven: () => ij, now: () => Yl, parseAxisParam: () => ir, randUniform: () => lj, repeatedTry: () => dj, rightPad: () => Vl, shuffle: () => jI, shuffleCombo: () => sj, sizeFromShape: () => nt, sizeToSquarishShape: () => mj, squeezeShape: () => cw, sum: () => aj, swap: () => Kh, tanh: () => pj, toNestedArray: () => Wl, toTypedArray: () => Qc }); +var u1 = Bl(l1()); +var Kl = u1.default || u1; +function Pm(r) { + return Kl.fromString(r, true, 16); } -var k0 = hexToLong("c3a5c85c97cb3127"); -var k1 = hexToLong("b492b66fbe98f273"); -var k2 = hexToLong("9ae16a3b2f90404f"); -function shiftMix(val) { - return val.xor(val.shru(47)); +var c1 = Pm("c3a5c85c97cb3127"); +var Xl = Pm("b492b66fbe98f273"); +var Xr = Pm("9ae16a3b2f90404f"); +function vw(r) { + return r.xor(r.shru(47)); } -function fetch2(s, offset, numBytes) { - const bytes = s.slice(offset, offset + numBytes); - return Long.fromBytes(Array.from(bytes), true, true); +function p1(r, e, t) { + let n = r.slice(e, e + t); + return Kl.fromBytes(Array.from(n), true, true); } -function fetch64(s, offset) { - return fetch2(s, offset, 8); +function Pt(r, e) { + return p1(r, e, 8); } -function fetch32(s, offset) { - return fetch2(s, offset, 4); +function m1(r, e) { + return p1(r, e, 4); } -function rotate64(val, shift) { - return shift === 0 ? val : val.shru(shift).or(val.shl(64 - shift)); +function _r(r, e) { + return e === 0 ? r : r.shru(e).or(r.shl(64 - e)); } -function hashLen16(u, v, mul2 = hexToLong("9ddfea08eb382d69")) { - let a = u.xor(v).mul(mul2); - a = a.xor(a.shru(47)); - let b = v.xor(a).mul(mul2); - b = b.xor(b.shru(47)); - b = b.mul(mul2); - return b; +function al(r, e, t = Pm("9ddfea08eb382d69")) { + let n = r.xor(e).mul(t); + n = n.xor(n.shru(47)); + let o = e.xor(n).mul(t); + return o = o.xor(o.shru(47)), o = o.mul(t), o; } -function weakHashLen32WithSeeds(w, x, y, z, a, b) { - a = a.add(w); - b = rotate64(b.add(a).add(z), 21); - const c = a; - a = a.add(x); - a = a.add(y); - b = b.add(rotate64(a, 44)); - return [a.add(z), b.add(c)]; +function Ij(r, e, t, n, o, s) { + o = o.add(r), s = _r(s.add(o).add(n), 21); + let a = o; + return o = o.add(e), o = o.add(t), s = s.add(_r(o, 44)), [o.add(n), s.add(a)]; } -function weakHashLen32WithSeedsStr(s, offset, a, b) { - return weakHashLen32WithSeeds(fetch64(s, offset), fetch64(s, offset + 8), fetch64(s, offset + 16), fetch64(s, offset + 24), a, b); +function eg(r, e, t, n) { + return Ij(Pt(r, e), Pt(r, e + 8), Pt(r, e + 16), Pt(r, e + 24), t, n); } -function hashLen0to16(s, len = s.length) { - if (len >= 8) { - const mul2 = k2.add(len * 2); - const a = fetch64(s, 0).add(k2); - const b = fetch64(s, len - 8); - const c = rotate64(b, 37).mul(mul2).add(a); - const d = rotate64(a, 25).add(b).mul(mul2); - return hashLen16(c, d, mul2); +function Nj(r, e = r.length) { + if (e >= 8) { + let t = Xr.add(e * 2), n = Pt(r, 0).add(Xr), o = Pt(r, e - 8), s = _r(o, 37).mul(t).add(n), a = _r(n, 25).add(o).mul(t); + return al(s, a, t); } - if (len >= 4) { - const mul2 = k2.add(len * 2); - const a = fetch32(s, 0); - return hashLen16(a.shl(3).add(len), fetch32(s, len - 4), mul2); + if (e >= 4) { + let t = Xr.add(e * 2), n = m1(r, 0); + return al(n.shl(3).add(e), m1(r, e - 4), t); } - if (len > 0) { - const a = s[0]; - const b = s[len >> 1]; - const c = s[len - 1]; - const y = a + (b << 8); - const z = len + (c << 2); - return shiftMix(k2.mul(y).xor(k0.mul(z))).mul(k2); + if (e > 0) { + let t = r[0], n = r[e >> 1], o = r[e - 1], s = t + (n << 8), a = e + (o << 2); + return vw(Xr.mul(s).xor(c1.mul(a))).mul(Xr); } - return k2; + return Xr; } -function hashLen17to32(s, len = s.length) { - const mul2 = k2.add(len * 2); - const a = fetch64(s, 0).mul(k1); - const b = fetch64(s, 8); - const c = fetch64(s, len - 8).mul(mul2); - const d = fetch64(s, len - 16).mul(k2); - return hashLen16(rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d), a.add(rotate64(b.add(k2), 18)).add(c), mul2); +function Tj(r, e = r.length) { + let t = Xr.add(e * 2), n = Pt(r, 0).mul(Xl), o = Pt(r, 8), s = Pt(r, e - 8).mul(t), a = Pt(r, e - 16).mul(Xr); + return al(_r(n.add(o), 43).add(_r(s, 30)).add(a), n.add(_r(o.add(Xr), 18)).add(s), t); } -function hashLen33to64(s, len = s.length) { - const mul2 = k2.add(len * 2); - const a = fetch64(s, 0).mul(k2); - const b = fetch64(s, 8); - const c = fetch64(s, len - 8).mul(mul2); - const d = fetch64(s, len - 16).mul(k2); - const y = rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d); - const z = hashLen16(y, a.add(rotate64(b.add(k2), 18)).add(c), mul2); - const e = fetch64(s, 16).mul(mul2); - const f = fetch64(s, 24); - const g = y.add(fetch64(s, len - 32)).mul(mul2); - const h = z.add(fetch64(s, len - 24)).mul(mul2); - return hashLen16(rotate64(e.add(f), 43).add(rotate64(g, 30)).add(h), e.add(rotate64(f.add(a), 18)).add(g), mul2); +function Ej(r, e = r.length) { + let t = Xr.add(e * 2), n = Pt(r, 0).mul(Xr), o = Pt(r, 8), s = Pt(r, e - 8).mul(t), a = Pt(r, e - 16).mul(Xr), i = _r(n.add(o), 43).add(_r(s, 30)).add(a), l = al(i, n.add(_r(o.add(Xr), 18)).add(s), t), u = Pt(r, 16).mul(t), c = Pt(r, 24), p = i.add(Pt(r, e - 32)).mul(t), m = l.add(Pt(r, e - 24)).mul(t); + return al(_r(u.add(c), 43).add(_r(p, 30)).add(m), u.add(_r(c.add(n), 18)).add(p), t); } -function fingerPrint64(s, len = s.length) { - const seed = Long.fromNumber(81, true); - if (len <= 32) { - if (len <= 16) { - return hashLen0to16(s, len); - } else { - return hashLen17to32(s, len); - } - } else if (len <= 64) { - return hashLen33to64(s, len); - } - let x = seed; - let y = seed.mul(k1).add(113); - let z = shiftMix(y.mul(k2).add(113)).mul(k2); - let v = [Long.UZERO, Long.UZERO]; - let w = [Long.UZERO, Long.UZERO]; - x = x.mul(k2).add(fetch64(s, 0)); - let offset = 0; - const end = (len - 1 >> 6) * 64; - const last64 = end + (len - 1 & 63) - 63; - do { - x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(k1); - y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(k1); - x = x.xor(w[1]); - y = y.add(v[0]).add(fetch64(s, offset + 40)); - z = rotate64(z.add(w[0]), 33).mul(k1); - v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(k1), x.add(w[0])); - w = weakHashLen32WithSeedsStr(s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16))); - [z, x] = [x, z]; - offset += 64; - } while (offset !== end); - const mul2 = k1.add(z.and(255).shl(1)); - offset = last64; - w[0] = w[0].add(len - 1 & 63); - v[0] = v[0].add(w[0]); - w[0] = w[0].add(v[0]); - x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(mul2); - y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(mul2); - x = x.xor(w[1].mul(9)); - y = y.add(v[0].mul(9).add(fetch64(s, offset + 40))); - z = rotate64(z.add(w[0]), 33).mul(mul2); - v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(mul2), x.add(w[0])); - w = weakHashLen32WithSeedsStr(s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16))); - [z, x] = [x, z]; - return hashLen16(hashLen16(v[0], w[0], mul2).add(shiftMix(y).mul(k0)).add(z), hashLen16(v[1], w[1], mul2).add(x), mul2); +function Aj(r, e = r.length) { + let t = Kl.fromNumber(81, true); + if (e <= 32) + return e <= 16 ? Nj(r, e) : Tj(r, e); + if (e <= 64) + return Ej(r, e); + let n = t, o = t.mul(Xl).add(113), s = vw(o.mul(Xr).add(113)).mul(Xr), a = [Kl.UZERO, Kl.UZERO], i = [Kl.UZERO, Kl.UZERO]; + n = n.mul(Xr).add(Pt(r, 0)); + let l = 0, u = (e - 1 >> 6) * 64, c = u + (e - 1 & 63) - 63; + do + n = _r(n.add(o).add(a[0]).add(Pt(r, l + 8)), 37).mul(Xl), o = _r(o.add(a[1]).add(Pt(r, l + 48)), 42).mul(Xl), n = n.xor(i[1]), o = o.add(a[0]).add(Pt(r, l + 40)), s = _r(s.add(i[0]), 33).mul(Xl), a = eg(r, l, a[1].mul(Xl), n.add(i[0])), i = eg(r, l + 32, s.add(i[1]), o.add(Pt(r, l + 16))), [s, n] = [n, s], l += 64; + while (l !== u); + let p = Xl.add(s.and(255).shl(1)); + return l = c, i[0] = i[0].add(e - 1 & 63), a[0] = a[0].add(i[0]), i[0] = i[0].add(a[0]), n = _r(n.add(o).add(a[0]).add(Pt(r, l + 8)), 37).mul(p), o = _r(o.add(a[1]).add(Pt(r, l + 48)), 42).mul(p), n = n.xor(i[1].mul(9)), o = o.add(a[0].mul(9).add(Pt(r, l + 40))), s = _r(s.add(i[0]), 33).mul(p), a = eg(r, l, a[1].mul(p), n.add(i[0])), i = eg(r, l + 32, s.add(i[1]), o.add(Pt(r, l + 16))), [s, n] = [n, s], al(al(a[0], i[0], p).add(vw(o).mul(c1)).add(s), al(a[1], i[1], p).add(n), p); } -function createScalarValue(value, dtype) { - if (dtype === "string") { - return encodeString(value); - } - return toTypedArray([value], dtype); +function $j(r, e) { + return e === "string" ? ll(r) : Qc([r], e); } -function noConversionNeeded(a, dtype) { - return a instanceof Float32Array && dtype === "float32" || a instanceof Int32Array && dtype === "int32" || a instanceof Uint8Array && dtype === "bool"; +function Dj(r, e) { + return r instanceof Float32Array && e === "float32" || r instanceof Int32Array && e === "int32" || r instanceof Uint8Array && e === "bool"; } -function toTypedArray(a, dtype) { - if (dtype === "string") { +function Qc(r, e) { + if (e === "string") throw new Error("Cannot convert a string[] to a TypedArray"); + if (Array.isArray(r) && (r = vo(r)), j().getBool("DEBUG") && fw(r, e), Dj(r, e)) + return r; + if (e == null || e === "float32" || e === "complex64") + return new Float32Array(r); + if (e === "int32") + return new Int32Array(r); + if (e === "bool") { + let t = new Uint8Array(r.length); + for (let n = 0; n < t.length; ++n) + Math.round(r[n]) !== 0 && (t[n] = 1); + return t; + } else + throw new Error(`Unknown data type ${e}`); +} +function Yl() { + return j().platform.now(); +} +function Rj(r, e) { + return j().platform.fetch(r, e); +} +function ll(r, e = "utf-8") { + return e = e || "utf-8", j().platform.encode(r, e); +} +function ep(r, e = "utf-8") { + return e = e || "utf-8", j().platform.decode(r, e); +} +var Cw = class { + constructor(e, t) { + this.backendTimer = e, this.logger = t, t == null && (this.logger = new f1()); } - if (Array.isArray(a)) { - a = flatten(a); - } - if (env().getBool("DEBUG")) { - checkConversionForErrors(a, dtype); - } - if (noConversionNeeded(a, dtype)) { - return a; - } - if (dtype == null || dtype === "float32" || dtype === "complex64") { - return new Float32Array(a); - } else if (dtype === "int32") { - return new Int32Array(a); - } else if (dtype === "bool") { - const bool = new Uint8Array(a.length); - for (let i = 0; i < bool.length; ++i) { - if (Math.round(a[i]) !== 0) { - bool[i] = 1; - } + profileKernel(e, t, n) { + let o, s = () => { + o = n(); + }, a, i = Yl(); + if (this.backendTimer.timerAvailable()) + a = this.backendTimer.time(s); + else { + s(); + for (let u of o) + u.dataSync(); + a = Promise.resolve({ kernelMs: Yl() - i }); } - return bool; - } else { - throw new Error(`Unknown data type ${dtype}`); - } -} -function now2() { - return env().platform.now(); -} -function fetch3(path, requestInits) { - return env().platform.fetch(path, requestInits); -} -function encodeString(s, encoding = "utf-8") { - encoding = encoding || "utf-8"; - return env().platform.encode(s, encoding); -} -function decodeString(bytes, encoding = "utf-8") { - encoding = encoding || "utf-8"; - return env().platform.decode(bytes, encoding); -} -var Profiler = class { - constructor(backendTimer, logger) { - this.backendTimer = backendTimer; - this.logger = logger; - if (logger == null) { - this.logger = new Logger(); - } - } - profileKernel(kernelName, inputs, f) { - let outputs; - const holdResultWrapperFn = () => { - outputs = f(); - }; - let timer; - const start = now2(); - if (this.backendTimer.timerAvailable()) { - timer = this.backendTimer.time(holdResultWrapperFn); - } else { - holdResultWrapperFn(); - for (const output of outputs) { - output.dataSync(); - } - timer = Promise.resolve({ kernelMs: now2() - start }); - } - if (env().getBool("CHECK_COMPUTATION_FOR_ERRORS")) { - for (let i = 0; i < outputs.length; i++) { - const output = outputs[i]; - output.data().then((tensorVals) => { - checkComputationForErrors(tensorVals, output.dtype, kernelName); + if (j().getBool("CHECK_COMPUTATION_FOR_ERRORS")) + for (let u = 0; u < o.length; u++) { + let c = o[u]; + c.data().then((p) => { + Fj(p, c.dtype, e); }); } - } - const kernelProfile = { - kernelName, - outputs, - inputs, - timeMs: timer.then((timing) => timing.kernelMs), - extraInfo: timer.then((timing) => timing.getExtraProfileInfo != null ? timing.getExtraProfileInfo() : "") - }; - return kernelProfile; + return { kernelName: e, outputs: o, inputs: t, timeMs: a.then((u) => u.kernelMs), extraInfo: a.then((u) => u.getExtraProfileInfo != null ? u.getExtraProfileInfo() : "") }; } - logKernelProfile(kernelProfile) { - const { kernelName, outputs, timeMs, inputs, extraInfo } = kernelProfile; - outputs.forEach((result) => { - Promise.all([result.data(), timeMs, extraInfo]).then((valueContainer) => { - this.logger.logKernelProfile(kernelName, result, valueContainer[0], valueContainer[1], inputs, valueContainer[2]); + logKernelProfile(e) { + let { kernelName: t, outputs: n, timeMs: o, inputs: s, extraInfo: a } = e; + n.forEach((i) => { + Promise.all([i.data(), o, a]).then((l) => { + this.logger.logKernelProfile(t, i, l[0], l[1], s, l[2]); }); }); } }; -function checkComputationForErrors(vals, dtype, kernelName) { - if (dtype !== "float32") { +function Fj(r, e, t) { + if (e !== "float32") return false; - } - for (let i = 0; i < vals.length; i++) { - const num = vals[i]; - if (isNaN(num) || !isFinite(num)) { - console.warn(`Found ${num} in the result of '${kernelName}'`); - return true; - } + for (let n = 0; n < r.length; n++) { + let o = r[n]; + if (isNaN(o) || !isFinite(o)) + return console.warn(`Found ${o} in the result of '${t}'`), true; } return false; } -var Logger = class { - logKernelProfile(name, result, vals, timeMs, inputs, extraInfo) { - const time2 = typeof timeMs === "number" ? rightPad(`${timeMs}ms`, 9) : timeMs["error"]; - const paddedName = rightPad(name, 25); - const rank = result.rank; - const size = result.size; - const shape = rightPad(result.shape.toString(), 14); - let inputShapesDescription = ""; - for (const name2 in inputs) { - const input2 = inputs[name2]; - if (input2 != null) { - const inputShape = input2.shape || result.shape; - const inputRank = inputShape.length; - inputShapesDescription += `${name2}: ${inputRank}D ${inputRank > 0 ? inputShape : ""} `; +var f1 = class { + logKernelProfile(e, t, n, o, s, a) { + let i = typeof o == "number" ? Vl(`${o}ms`, 9) : o.error, l = Vl(e, 25), u = t.rank, c = t.size, p = Vl(t.shape.toString(), 14), m = ""; + for (let f in s) { + let d = s[f]; + if (d != null) { + let h = d.shape || t.shape, g = h.length; + m += `${f}: ${g}D ${g > 0 ? h : ""} `; } } - console.log(`%c${paddedName} %c${time2} %c${rank}D ${shape} %c${size} %c${inputShapesDescription} %c${extraInfo}`, "font-weight:bold", "color:red", "color:blue", "color: orange", "color: green", "color: steelblue"); + console.log(`%c${l} %c${i} %c${u}D ${p} %c${c} %c${m} %c${a}`, "font-weight:bold", "color:red", "color:blue", "color: orange", "color: green", "color: steelblue"); } }; -function getFilteredNodesXToY(tape, xs, y) { - const tensorsFromX = {}; - const nodesFromX = {}; - for (let i = 0; i < xs.length; i++) { - tensorsFromX[xs[i].id] = true; - } - for (let i = 0; i < tape.length; i++) { - const node = tape[i]; - const nodeInputs = node.inputs; - for (const inputName in nodeInputs) { - const input2 = nodeInputs[inputName]; - let anyInputFromX = false; - for (let j = 0; j < xs.length; j++) { - if (tensorsFromX[input2.id]) { - node.outputs.forEach((output) => tensorsFromX[output.id] = true); - anyInputFromX = true; - nodesFromX[node.id] = true; +function d1(r, e, t) { + let n = {}, o = {}; + for (let l = 0; l < e.length; l++) + n[e[l].id] = true; + for (let l = 0; l < r.length; l++) { + let u = r[l], c = u.inputs; + for (let p in c) { + let m = c[p], f = false; + for (let d = 0; d < e.length; d++) + if (n[m.id]) { + u.outputs.forEach((h) => n[h.id] = true), f = true, o[u.id] = true; break; } - } - if (anyInputFromX) { + if (f) + break; + } + } + let s = {}; + s[t.id] = true; + let a = {}; + for (let l = r.length - 1; l >= 0; l--) { + let u = r[l], c = u.inputs; + for (let p = 0; p < u.outputs.length; p++) + if (s[u.outputs[p].id]) { + for (let m in c) + s[c[m].id] = true, a[u.id] = true; break; } - } } - const tensorsLeadToY = {}; - tensorsLeadToY[y.id] = true; - const nodesToY = {}; - for (let i = tape.length - 1; i >= 0; i--) { - const node = tape[i]; - const nodeInputs = node.inputs; - for (let j = 0; j < node.outputs.length; j++) { - if (tensorsLeadToY[node.outputs[j].id]) { - for (const inputName in nodeInputs) { - tensorsLeadToY[nodeInputs[inputName].id] = true; - nodesToY[node.id] = true; - } - break; + let i = []; + for (let l = 0; l < r.length; l++) { + let u = r[l]; + if (o[u.id] && a[u.id]) { + let c = {}; + for (let m in u.inputs) { + let f = u.inputs[m]; + n[f.id] && (c[m] = f); } + let p = Object.assign({}, u); + p.inputs = c, p.outputs = u.outputs, i.push(p); } } - const filteredTape = []; - for (let i = 0; i < tape.length; i++) { - const node = tape[i]; - if (nodesFromX[node.id] && nodesToY[node.id]) { - const prunedInputs = {}; - for (const inputName in node.inputs) { - const nodeInput = node.inputs[inputName]; - if (tensorsFromX[nodeInput.id]) { - prunedInputs[inputName] = nodeInput; - } - } - const prunedNode = Object.assign({}, node); - prunedNode.inputs = prunedInputs; - prunedNode.outputs = node.outputs; - filteredTape.push(prunedNode); - } - } - return filteredTape; + return i; } -function backpropagateGradients(tensorAccumulatedGradientMap, filteredTape, tidy2, add5) { - for (let i = filteredTape.length - 1; i >= 0; i--) { - const node = filteredTape[i]; - const dys = []; - node.outputs.forEach((o) => { - const gradTensor = tensorAccumulatedGradientMap[o.id]; - if (gradTensor != null) { - dys.push(gradTensor); - } else { - dys.push(null); - } - }); - if (node.gradient == null) { - throw new Error(`Cannot compute gradient: gradient function not found for ${node.kernelName}.`); - } - const inputGradients = node.gradient(dys); - for (const inputName in node.inputs) { - if (!(inputName in inputGradients)) { - throw new Error(`Cannot backprop through input ${inputName}. Available gradients found: ${Object.keys(inputGradients)}.`); - } - const dx = tidy2(() => inputGradients[inputName]()); - if (dx.dtype !== "float32") { - throw new Error(`Error in gradient for op ${node.kernelName}. The gradient of input ${inputName} must have 'float32' dtype, but has '${dx.dtype}'`); - } - const x = node.inputs[inputName]; - if (!arraysEqual(dx.shape, x.shape)) { - throw new Error(`Error in gradient for op ${node.kernelName}. The gradient of input '${inputName}' has shape '${dx.shape}', which does not match the shape of the input '${x.shape}'`); - } - if (tensorAccumulatedGradientMap[x.id] == null) { - tensorAccumulatedGradientMap[x.id] = dx; - } else { - const curGradient = tensorAccumulatedGradientMap[x.id]; - tensorAccumulatedGradientMap[x.id] = add5(curGradient, dx); - curGradient.dispose(); +function h1(r, e, t, n) { + for (let o = e.length - 1; o >= 0; o--) { + let s = e[o], a = []; + if (s.outputs.forEach((l) => { + let u = r[l.id]; + u != null ? a.push(u) : a.push(null); + }), s.gradient == null) + throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`); + let i = s.gradient(a); + for (let l in s.inputs) { + if (!(l in i)) + throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(i)}.`); + let u = t(() => i[l]()); + if (u.dtype !== "float32") + throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`); + let c = s.inputs[l]; + if (!Kr(u.shape, c.shape)) + throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${l}' has shape '${u.shape}', which does not match the shape of the input '${c.shape}'`); + if (r[c.id] == null) + r[c.id] = u; + else { + let p = r[c.id]; + r[c.id] = n(p, u), p.dispose(); } } } } -var FORMAT_LIMIT_NUM_VALS = 20; -var FORMAT_NUM_FIRST_LAST_VALS = 3; -var FORMAT_NUM_SIG_DIGITS = 7; -function tensorToString(vals, shape, dtype, verbose) { - const strides = computeStrides(shape); - const padPerCol = computeMaxSizePerColumn(vals, shape, dtype, strides); - const rank = shape.length; - const valsLines = subTensorToString(vals, shape, dtype, strides, padPerCol); - const lines2 = ["Tensor"]; - if (verbose) { - lines2.push(` dtype: ${dtype}`); - lines2.push(` rank: ${rank}`); - lines2.push(` shape: [${shape}]`); - lines2.push(` values:`); - } - lines2.push(valsLines.map((l) => " " + l).join("\n")); - return lines2.join("\n"); +var g1 = 20; +var Mm = 3; +var Sw = 7; +function x1(r, e, t, n) { + let o = Bs(e), s = Oj(r, e, t, o), a = e.length, i = tg(r, e, t, o, s), l = ["Tensor"]; + return n && (l.push(` dtype: ${t}`), l.push(` rank: ${a}`), l.push(` shape: [${e}]`), l.push(" values:")), l.push(i.map((u) => " " + u).join(` +`)), l.join(` +`); } -function computeMaxSizePerColumn(vals, shape, dtype, strides) { - const n = sizeFromShape(shape); - const numCols = strides[strides.length - 1]; - const padPerCol = new Array(numCols).fill(0); - const rank = shape.length; - const valuesOrTuples = dtype === "complex64" ? createComplexTuples(vals) : vals; - if (rank > 1) { - for (let row = 0; row < n / numCols; row++) { - const offset = row * numCols; - for (let j = 0; j < numCols; j++) { - padPerCol[j] = Math.max(padPerCol[j], valToString(valuesOrTuples[offset + j], 0, dtype).length); +function Oj(r, e, t, n) { + let o = nt(e), s = n[n.length - 1], a = new Array(s).fill(0), i = e.length, l = t === "complex64" ? zm(r) : r; + if (i > 1) + for (let u = 0; u < o / s; u++) { + let c = u * s; + for (let p = 0; p < s; p++) + a[p] = Math.max(a[p], Lm(l[c + p], 0, t).length); + } + return a; +} +function Lm(r, e, t) { + let n; + return Array.isArray(r) ? n = `${parseFloat(r[0].toFixed(Sw))} + ${parseFloat(r[1].toFixed(Sw))}j` : Co(r) ? n = `'${r}'` : t === "bool" ? n = y1(r) : n = parseFloat(r.toFixed(Sw)).toString(), Vl(n, e); +} +function y1(r) { + return r === 0 ? "false" : "true"; +} +function tg(r, e, t, n, o, s = true) { + let a = t === "complex64" ? 2 : 1, i = e[0], l = e.length; + if (l === 0) { + if (t === "complex64") { + let h = zm(r); + return [Lm(h[0], 0, t)]; + } + return t === "bool" ? [y1(r[0])] : [r[0].toString()]; + } + if (l === 1) { + if (i > g1) { + let g = Mm * a, y = Array.from(r.slice(0, g)), w = Array.from(r.slice((i - Mm) * a, i * a)); + return t === "complex64" && (y = zm(y), w = zm(w)), ["[" + y.map((x, k) => Lm(x, o[k], t)).join(", ") + ", ..., " + w.map((x, k) => Lm(x, o[i - Mm + k], t)).join(", ") + "]"]; + } + let h = t === "complex64" ? zm(r) : Array.from(r); + return ["[" + h.map((g, y) => Lm(g, o[y], t)).join(", ") + "]"]; + } + let u = e.slice(1), c = n.slice(1), p = n[0] * a, m = []; + if (i > g1) { + for (let h = 0; h < Mm; h++) { + let g = h * p, y = g + p; + m.push(...tg(r.slice(g, y), u, t, c, o, false)); + } + m.push("..."); + for (let h = i - Mm; h < i; h++) { + let g = h * p, y = g + p; + m.push(...tg(r.slice(g, y), u, t, c, o, h === i - 1)); + } + } else + for (let h = 0; h < i; h++) { + let g = h * p, y = g + p; + m.push(...tg(r.slice(g, y), u, t, c, o, h === i - 1)); + } + let f = l === 2 ? "," : ""; + m[0] = "[" + m[0] + f; + for (let h = 1; h < m.length - 1; h++) + m[h] = " " + m[h] + f; + let d = `, +`; + for (let h = 2; h < l; h++) + d += ` +`; + return m[m.length - 1] = " " + m[m.length - 1] + "]" + (s ? "" : d), m; +} +function zm(r) { + let e = []; + for (let t = 0; t < r.length; t += 2) + e.push([r[t], r[t + 1]]); + return e; +} +var ct = class { + constructor(e, t, n) { + if (this.dtype = t, this.shape = e.slice(), this.size = nt(e), n != null) { + let o = n.length; + E(o === this.size, () => `Length of values '${o}' does not match the size inferred by the shape '${this.size}'.`); + } + if (t === "complex64") + throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag)."); + this.values = n || mw(t, this.size), this.strides = Bs(e); + } + set(e, ...t) { + t.length === 0 && (t = [0]), E(t.length === this.rank, () => `The number of provided coordinates (${t.length}) must match the rank (${this.rank})`); + let n = this.locToIndex(t); + this.values[n] = e; + } + get(...e) { + e.length === 0 && (e = [0]); + let t = 0; + for (let o of e) { + if (o < 0 || o >= this.shape[t]) { + let s = `Requested out of range element at ${e}. Buffer shape=${this.shape}`; + throw new Error(s); } + t++; } + let n = e[e.length - 1]; + for (let o = 0; o < e.length - 1; ++o) + n += this.strides[o] * e[o]; + return this.values[n]; } - return padPerCol; -} -function valToString(val, pad3, dtype) { - let valStr; - if (Array.isArray(val)) { - valStr = `${parseFloat(val[0].toFixed(FORMAT_NUM_SIG_DIGITS))} + ${parseFloat(val[1].toFixed(FORMAT_NUM_SIG_DIGITS))}j`; - } else if (isString(val)) { - valStr = `'${val}'`; - } else if (dtype === "bool") { - valStr = boolNumToString(val); - } else { - valStr = parseFloat(val.toFixed(FORMAT_NUM_SIG_DIGITS)).toString(); - } - return rightPad(valStr, pad3); -} -function boolNumToString(v) { - return v === 0 ? "false" : "true"; -} -function subTensorToString(vals, shape, dtype, strides, padPerCol, isLast = true) { - const storagePerElement = dtype === "complex64" ? 2 : 1; - const size = shape[0]; - const rank = shape.length; - if (rank === 0) { - if (dtype === "complex64") { - const complexTuple = createComplexTuples(vals); - return [valToString(complexTuple[0], 0, dtype)]; - } - if (dtype === "bool") { - return [boolNumToString(vals[0])]; - } - return [vals[0].toString()]; - } - if (rank === 1) { - if (size > FORMAT_LIMIT_NUM_VALS) { - const firstValsSize = FORMAT_NUM_FIRST_LAST_VALS * storagePerElement; - let firstVals = Array.from(vals.slice(0, firstValsSize)); - let lastVals = Array.from(vals.slice((size - FORMAT_NUM_FIRST_LAST_VALS) * storagePerElement, size * storagePerElement)); - if (dtype === "complex64") { - firstVals = createComplexTuples(firstVals); - lastVals = createComplexTuples(lastVals); - } - return [ - "[" + firstVals.map((x, i) => valToString(x, padPerCol[i], dtype)).join(", ") + ", ..., " + lastVals.map((x, i) => valToString(x, padPerCol[size - FORMAT_NUM_FIRST_LAST_VALS + i], dtype)).join(", ") + "]" - ]; - } - const displayVals = dtype === "complex64" ? createComplexTuples(vals) : Array.from(vals); - return [ - "[" + displayVals.map((x, i) => valToString(x, padPerCol[i], dtype)).join(", ") + "]" - ]; - } - const subshape = shape.slice(1); - const substrides = strides.slice(1); - const stride = strides[0] * storagePerElement; - const lines2 = []; - if (size > FORMAT_LIMIT_NUM_VALS) { - for (let i = 0; i < FORMAT_NUM_FIRST_LAST_VALS; i++) { - const start = i * stride; - const end = start + stride; - lines2.push(...subTensorToString(vals.slice(start, end), subshape, dtype, substrides, padPerCol, false)); - } - lines2.push("..."); - for (let i = size - FORMAT_NUM_FIRST_LAST_VALS; i < size; i++) { - const start = i * stride; - const end = start + stride; - lines2.push(...subTensorToString(vals.slice(start, end), subshape, dtype, substrides, padPerCol, i === size - 1)); - } - } else { - for (let i = 0; i < size; i++) { - const start = i * stride; - const end = start + stride; - lines2.push(...subTensorToString(vals.slice(start, end), subshape, dtype, substrides, padPerCol, i === size - 1)); - } - } - const sep = rank === 2 ? "," : ""; - lines2[0] = "[" + lines2[0] + sep; - for (let i = 1; i < lines2.length - 1; i++) { - lines2[i] = " " + lines2[i] + sep; - } - let newLineSep = ",\n"; - for (let i = 2; i < rank; i++) { - newLineSep += "\n"; - } - lines2[lines2.length - 1] = " " + lines2[lines2.length - 1] + "]" + (isLast ? "" : newLineSep); - return lines2; -} -function createComplexTuples(vals) { - const complexTuples = []; - for (let i = 0; i < vals.length; i += 2) { - complexTuples.push([vals[i], vals[i + 1]]); - } - return complexTuples; -} -var TensorBuffer = class { - constructor(shape, dtype, values) { - this.dtype = dtype; - this.shape = shape.slice(); - this.size = sizeFromShape(shape); - if (values != null) { - const n = values.length; - assert(n === this.size, () => `Length of values '${n}' does not match the size inferred by the shape '${this.size}'.`); - } - if (dtype === "complex64") { - throw new Error(`complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).`); - } - this.values = values || getArrayFromDType(dtype, this.size); - this.strides = computeStrides(shape); - } - set(value, ...locs) { - if (locs.length === 0) { - locs = [0]; - } - assert(locs.length === this.rank, () => `The number of provided coordinates (${locs.length}) must match the rank (${this.rank})`); - const index = this.locToIndex(locs); - this.values[index] = value; - } - get(...locs) { - if (locs.length === 0) { - locs = [0]; - } - let i = 0; - for (const loc of locs) { - if (loc < 0 || loc >= this.shape[i]) { - const msg = `Requested out of range element at ${locs}. Buffer shape=${this.shape}`; - throw new Error(msg); - } - i++; - } - let index = locs[locs.length - 1]; - for (let i2 = 0; i2 < locs.length - 1; ++i2) { - index += this.strides[i2] * locs[i2]; - } - return this.values[index]; - } - locToIndex(locs) { - if (this.rank === 0) { + locToIndex(e) { + if (this.rank === 0) return 0; - } else if (this.rank === 1) { - return locs[0]; - } - let index = locs[locs.length - 1]; - for (let i = 0; i < locs.length - 1; ++i) { - index += this.strides[i] * locs[i]; - } - return index; + if (this.rank === 1) + return e[0]; + let t = e[e.length - 1]; + for (let n = 0; n < e.length - 1; ++n) + t += this.strides[n] * e[n]; + return t; } - indexToLoc(index) { - if (this.rank === 0) { + indexToLoc(e) { + if (this.rank === 0) return []; - } else if (this.rank === 1) { - return [index]; - } - const locs = new Array(this.shape.length); - for (let i = 0; i < locs.length - 1; ++i) { - locs[i] = Math.floor(index / this.strides[i]); - index -= locs[i] * this.strides[i]; - } - locs[locs.length - 1] = index; - return locs; + if (this.rank === 1) + return [e]; + let t = new Array(this.shape.length); + for (let n = 0; n < t.length - 1; ++n) + t[n] = Math.floor(e / this.strides[n]), e -= t[n] * this.strides[n]; + return t[t.length - 1] = e, t; } get rank() { return this.shape.length; } toTensor() { - return trackerFn().makeTensor(this.values, this.shape, this.dtype); + return si().makeTensor(this.values, this.shape, this.dtype); } }; -var trackerFn = null; -var opHandler = null; -var deprecationWarningFn = null; -function setTensorTracker(fn) { - trackerFn = fn; +var si = null; +var tp = null; +var Pj = null; +function b1(r) { + si = r; } -function setOpHandler(handler) { - opHandler = handler; +function w1(r) { + tp = r; } -function setDeprecationWarningFn(fn) { - deprecationWarningFn = fn; +function k1(r) { + Pj = r; } -var Tensor = class { - constructor(shape, dtype, dataId, id) { - this.kept = false; - this.isDisposedInternal = false; - this.shape = shape.slice(); - this.dtype = dtype || "float32"; - this.size = sizeFromShape(shape); - this.strides = computeStrides(shape); - this.dataId = dataId; - this.id = id; - this.rankType = this.rank < 5 ? this.rank.toString() : "higher"; +var je = class { + constructor(e, t, n, o) { + this.kept = false, this.isDisposedInternal = false, this.shape = e.slice(), this.dtype = t || "float32", this.size = nt(e), this.strides = Bs(e), this.dataId = n, this.id = o, this.rankType = this.rank < 5 ? this.rank.toString() : "higher"; } get rank() { return this.shape.length; } async buffer() { - const vals = await this.data(); - return opHandler.buffer(this.shape, this.dtype, vals); + let e = await this.data(); + return tp.buffer(this.shape, this.dtype, e); } bufferSync() { - return opHandler.buffer(this.shape, this.dtype, this.dataSync()); + return tp.buffer(this.shape, this.dtype, this.dataSync()); } async array() { - const vals = await this.data(); - return toNestedArray(this.shape, vals, this.dtype === "complex64"); + let e = await this.data(); + return Wl(this.shape, e, this.dtype === "complex64"); } arraySync() { - return toNestedArray(this.shape, this.dataSync(), this.dtype === "complex64"); + return Wl(this.shape, this.dataSync(), this.dtype === "complex64"); } async data() { this.throwIfDisposed(); - const data = trackerFn().read(this.dataId); + let e = si().read(this.dataId); if (this.dtype === "string") { - const bytes = await data; + let t = await e; try { - return bytes.map((b) => decodeString(b)); - } catch (_a) { + return t.map((n) => ep(n)); + } catch (n) { throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes()."); } } - return data; + return e; } dataSync() { this.throwIfDisposed(); - const data = trackerFn().readSync(this.dataId); - if (this.dtype === "string") { + let e = si().readSync(this.dataId); + if (this.dtype === "string") try { - return data.map((b) => decodeString(b)); - } catch (_a) { + return e.map((t) => ep(t)); + } catch (t) { throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes()."); } - } - return data; + return e; } async bytes() { this.throwIfDisposed(); - const data = await trackerFn().read(this.dataId); - if (this.dtype === "string") { - return data; - } else { - return new Uint8Array(data.buffer); - } + let e = await si().read(this.dataId); + return this.dtype === "string" ? e : new Uint8Array(e.buffer); } dispose() { - if (this.isDisposed) { - return; - } - trackerFn().disposeTensor(this); - this.isDisposedInternal = true; + this.isDisposed || (si().disposeTensor(this), this.isDisposedInternal = true); } get isDisposed() { return this.isDisposedInternal; } throwIfDisposed() { - if (this.isDisposed) { - throw new Error(`Tensor is disposed.`); - } + if (this.isDisposed) + throw new Error("Tensor is disposed."); } - print(verbose = false) { - return opHandler.print(this, verbose); + print(e = false) { + return tp.print(this, e); } clone() { - this.throwIfDisposed(); - return opHandler.clone(this); + return this.throwIfDisposed(), tp.clone(this); } - toString(verbose = false) { - const vals = this.dataSync(); - return tensorToString(vals, this.shape, this.dtype, verbose); + toString(e = false) { + let t = this.dataSync(); + return x1(t, this.shape, this.dtype, e); } - cast(dtype) { - this.throwIfDisposed(); - return opHandler.cast(this, dtype); + cast(e) { + return this.throwIfDisposed(), tp.cast(this, e); } - variable(trainable = true, name, dtype) { - this.throwIfDisposed(); - return trackerFn().makeVariable(this, trainable, name, dtype); + variable(e = true, t, n) { + return this.throwIfDisposed(), si().makeVariable(this, e, t, n); } }; -Object.defineProperty(Tensor, Symbol.hasInstance, { - value: (instance) => { - return !!instance && instance.data != null && instance.dataSync != null && instance.throwIfDisposed != null; - } -}); -function getGlobalTensorClass() { - return getGlobal("Tensor", () => { - return Tensor; - }); +Object.defineProperty(je, Symbol.hasInstance, { value: (r) => !!r && r.data != null && r.dataSync != null && r.throwIfDisposed != null }); +function Mj() { + return Am("Tensor", () => je); } -getGlobalTensorClass(); -var Variable = class extends Tensor { - constructor(initialValue, trainable, name, tensorId) { - super(initialValue.shape, initialValue.dtype, initialValue.dataId, tensorId); - this.trainable = trainable; - this.name = name; +Mj(); +var ul = class extends je { + constructor(e, t, n, o) { + super(e.shape, e.dtype, e.dataId, o); + this.trainable = t, this.name = n; } - assign(newValue) { - if (newValue.dtype !== this.dtype) { - throw new Error(`dtype of the new value (${newValue.dtype}) and previous value (${this.dtype}) must match`); - } - if (!arraysEqual(newValue.shape, this.shape)) { - throw new Error(`shape of the new value (${newValue.shape}) and previous value (${this.shape}) must match`); - } - trackerFn().disposeTensor(this); - this.dataId = newValue.dataId; - trackerFn().incRef(this, null); + assign(e) { + if (e.dtype !== this.dtype) + throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`); + if (!Kr(e.shape, this.shape)) + throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`); + si().disposeTensor(this), this.dataId = e.dataId, si().incRef(this, null); } dispose() { - trackerFn().disposeVariable(this); - this.isDisposedInternal = true; + si().disposeVariable(this), this.isDisposedInternal = true; } }; -Object.defineProperty(Variable, Symbol.hasInstance, { - value: (instance) => { - return instance instanceof Tensor && instance.assign != null && instance.assign instanceof Function; - } -}); -var tensor_util_exports = {}; -__export2(tensor_util_exports, { - assertTypesMatch: () => assertTypesMatch, - getTensorsInContainer: () => getTensorsInContainer, - isTensorInList: () => isTensorInList, - makeTypesMatch: () => makeTypesMatch -}); -var Rank; -(function(Rank2) { - Rank2["R0"] = "R0"; - Rank2["R1"] = "R1"; - Rank2["R2"] = "R2"; - Rank2["R3"] = "R3"; - Rank2["R4"] = "R4"; - Rank2["R5"] = "R5"; - Rank2["R6"] = "R6"; -})(Rank || (Rank = {})); -var UpcastInt32AndMap; -(function(UpcastInt32AndMap2) { - UpcastInt32AndMap2["float32"] = "float32"; - UpcastInt32AndMap2["int32"] = "int32"; - UpcastInt32AndMap2["bool"] = "int32"; - UpcastInt32AndMap2["complex64"] = "complex64"; -})(UpcastInt32AndMap || (UpcastInt32AndMap = {})); -var UpcastBoolAndMap; -(function(UpcastBoolAndMap2) { - UpcastBoolAndMap2["float32"] = "float32"; - UpcastBoolAndMap2["int32"] = "int32"; - UpcastBoolAndMap2["bool"] = "bool"; - UpcastBoolAndMap2["complex64"] = "complex64"; -})(UpcastBoolAndMap || (UpcastBoolAndMap = {})); -var UpcastFloat32AndMap; -(function(UpcastFloat32AndMap2) { - UpcastFloat32AndMap2["float32"] = "float32"; - UpcastFloat32AndMap2["int32"] = "float32"; - UpcastFloat32AndMap2["bool"] = "float32"; - UpcastFloat32AndMap2["complex64"] = "complex64"; -})(UpcastFloat32AndMap || (UpcastFloat32AndMap = {})); -var UpcastComplex64AndMap; -(function(UpcastComplex64AndMap2) { - UpcastComplex64AndMap2["float32"] = "complex64"; - UpcastComplex64AndMap2["int32"] = "complex64"; - UpcastComplex64AndMap2["bool"] = "complex64"; - UpcastComplex64AndMap2["complex64"] = "complex64"; -})(UpcastComplex64AndMap || (UpcastComplex64AndMap = {})); -var upcastTypeMap = { - "float32": UpcastFloat32AndMap, - "int32": UpcastInt32AndMap, - "bool": UpcastBoolAndMap, - "complex64": UpcastComplex64AndMap -}; -function upcastType(typeA, typeB) { - if (typeA === "string" || typeB === "string") { - if (typeA === "string" && typeB === "string") { +Object.defineProperty(ul, Symbol.hasInstance, { value: (r) => r instanceof je && r.assign != null && r.assign instanceof Function }); +var io = {}; +He(io, { assertTypesMatch: () => $w, getTensorsInContainer: () => Bm, isTensorInList: () => zj, makeTypesMatch: () => Ge }); +var Iw; +(function(r) { + r.R0 = "R0", r.R1 = "R1", r.R2 = "R2", r.R3 = "R3", r.R4 = "R4", r.R5 = "R5", r.R6 = "R6"; +})(Iw || (Iw = {})); +var Nw; +(function(r) { + r.float32 = "float32", r.int32 = "int32", r.bool = "int32", r.complex64 = "complex64"; +})(Nw || (Nw = {})); +var Tw; +(function(r) { + r.float32 = "float32", r.int32 = "int32", r.bool = "bool", r.complex64 = "complex64"; +})(Tw || (Tw = {})); +var Ew; +(function(r) { + r.float32 = "float32", r.int32 = "float32", r.bool = "float32", r.complex64 = "complex64"; +})(Ew || (Ew = {})); +var Aw; +(function(r) { + r.float32 = "complex64", r.int32 = "complex64", r.bool = "complex64", r.complex64 = "complex64"; +})(Aw || (Aw = {})); +var Lj = { float32: Ew, int32: Nw, bool: Tw, complex64: Aw }; +function pr(r, e) { + if (r === "string" || e === "string") { + if (r === "string" && e === "string") return "string"; - } - throw new Error(`Can not upcast ${typeA} with ${typeB}`); + throw new Error(`Can not upcast ${r} with ${e}`); } - return upcastTypeMap[typeA][typeB]; + return Lj[r][e]; } -function sumOutType(type) { - return upcastType(type, "int32"); +function Zl(r) { + return pr(r, "int32"); } -function makeTypesMatch(a, b) { - if (a.dtype === b.dtype) { - return [a, b]; - } - const dtype = upcastType(a.dtype, b.dtype); - return [a.cast(dtype), b.cast(dtype)]; +function Ge(r, e) { + if (r.dtype === e.dtype) + return [r, e]; + let t = pr(r.dtype, e.dtype); + return [r.cast(t), e.cast(t)]; } -function assertTypesMatch(a, b) { - assert(a.dtype === b.dtype, () => `The dtypes of the first(${a.dtype}) and second(${b.dtype}) input must match`); +function $w(r, e) { + E(r.dtype === e.dtype, () => `The dtypes of the first(${r.dtype}) and second(${e.dtype}) input must match`); } -function isTensorInList(tensor2, tensorList) { - return tensorList.some((x) => x.id === tensor2.id); +function zj(r, e) { + return e.some((t) => t.id === r.id); } -function getTensorsInContainer(result) { - const list = []; - const seen = new Set(); - walkTensorContainer(result, list, seen); - return list; +function Bm(r) { + let e = [], t = new Set(); + return _1(r, e, t), e; } -function walkTensorContainer(container, list, seen) { - if (container == null) { +function _1(r, e, t) { + if (r == null) + return; + if (r instanceof je) { + e.push(r); return; } - if (container instanceof Tensor) { - list.push(container); + if (!Bj(r)) return; - } - if (!isIterable(container)) { - return; - } - const iterable = container; - for (const k in iterable) { - const val = iterable[k]; - if (!seen.has(val)) { - seen.add(val); - walkTensorContainer(val, list, seen); - } + let n = r; + for (let o in n) { + let s = n[o]; + t.has(s) || (t.add(s), _1(s, e, t)); } } -function isIterable(obj) { - return Array.isArray(obj) || typeof obj === "object"; +function Bj(r) { + return Array.isArray(r) || typeof r == "object"; } -function isRegisteredKernelInvocation(kernelInvocation) { - return kernelInvocation.kernelName != null; +function Dw(r) { + return r.kernelName != null; } -var EngineState = class { +var Rw = class { constructor() { - this.registeredVariables = {}; - this.nextTapeNodeId = 0; - this.numBytes = 0; - this.numTensors = 0; - this.numStringTensors = 0; - this.numDataBuffers = 0; - this.gradientDepth = 0; - this.kernelDepth = 0; - this.scopeStack = []; - this.numDataMovesStack = []; - this.nextScopeId = 0; - this.tensorInfo = new WeakMap(); - this.profiling = false; - this.activeProfile = { - newBytes: 0, - newTensors: 0, - peakBytes: 0, - kernels: [], - result: null, - get kernelNames() { - return Array.from(new Set(this.kernels.map((k) => k.name))); - } - }; + this.registeredVariables = {}, this.nextTapeNodeId = 0, this.numBytes = 0, this.numTensors = 0, this.numStringTensors = 0, this.numDataBuffers = 0, this.gradientDepth = 0, this.kernelDepth = 0, this.scopeStack = [], this.numDataMovesStack = [], this.nextScopeId = 0, this.tensorInfo = new WeakMap(), this.profiling = false, this.activeProfile = { newBytes: 0, newTensors: 0, peakBytes: 0, kernels: [], result: null, get kernelNames() { + return Array.from(new Set(this.kernels.map((e) => e.name))); + } }; } dispose() { - for (const variableName in this.registeredVariables) { - this.registeredVariables[variableName].dispose(); - } + for (let e in this.registeredVariables) + this.registeredVariables[e].dispose(); } }; -var Engine = class { - constructor(ENV5) { - this.ENV = ENV5; - this.registry = {}; - this.registryFactory = {}; - this.pendingBackendInitId = 0; - this.state = new EngineState(); +var Jl = class { + constructor(e) { + this.ENV = e, this.registry = {}, this.registryFactory = {}, this.pendingBackendInitId = 0, this.state = new Rw(); } async ready() { - if (this.pendingBackendInit != null) { + if (this.pendingBackendInit != null) return this.pendingBackendInit.then(() => { }); - } - if (this.backendInstance != null) { + if (this.backendInstance != null) return; - } - const sortedBackends = this.getSortedBackends(); - for (let i = 0; i < sortedBackends.length; i++) { - const backendName = sortedBackends[i]; - const success = await this.initializeBackend(backendName).success; - if (success) { - await this.setBackend(backendName); + let e = this.getSortedBackends(); + for (let t = 0; t < e.length; t++) { + let n = e[t]; + if (await this.initializeBackend(n).success) { + await this.setBackend(n); return; } } - throw new Error(`Could not initialize any backends, all backend initializations failed.`); + throw new Error("Could not initialize any backends, all backend initializations failed."); } get backend() { - if (this.pendingBackendInit != null) { + if (this.pendingBackendInit != null) throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`); - } if (this.backendInstance == null) { - const { name, asyncInit } = this.initializeBackendsAndReturnBest(); - if (asyncInit) { - throw new Error(`The highest priority backend '${name}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`); - } - this.setBackend(name); + let { name: e, asyncInit: t } = this.initializeBackendsAndReturnBest(); + if (t) + throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`); + this.setBackend(e); } return this.backendInstance; } backendNames() { return Object.keys(this.registryFactory); } - findBackend(backendName) { - if (!(backendName in this.registry)) { - if (backendName in this.registryFactory) { - const { asyncInit } = this.initializeBackend(backendName); - if (asyncInit) { + findBackend(e) { + if (!(e in this.registry)) + if (e in this.registryFactory) { + let { asyncInit: t } = this.initializeBackend(e); + if (t) return null; - } - } else { + } else return null; - } - } - return this.registry[backendName]; + return this.registry[e]; } - findBackendFactory(backendName) { - if (!(backendName in this.registryFactory)) { - return null; - } - return this.registryFactory[backendName].factory; + findBackendFactory(e) { + return e in this.registryFactory ? this.registryFactory[e].factory : null; } - registerBackend(backendName, factory, priority = 1) { - if (backendName in this.registryFactory) { - warn(`${backendName} backend was already registered. Reusing existing backend factory.`); - return false; - } - this.registryFactory[backendName] = { factory, priority }; - return true; + registerBackend(e, t, n = 1) { + return e in this.registryFactory ? (Vn(`${e} backend was already registered. Reusing existing backend factory.`), false) : (this.registryFactory[e] = { factory: t, priority: n }, true); } - async setBackend(backendName) { - if (this.registryFactory[backendName] == null) { - throw new Error(`Backend name '${backendName}' not found in registry`); - } - this.backendName = backendName; - if (this.registry[backendName] == null) { + async setBackend(e) { + if (this.registryFactory[e] == null) + throw new Error(`Backend name '${e}' not found in registry`); + if (this.backendName = e, this.registry[e] == null) { this.backendInstance = null; - const { success, asyncInit } = this.initializeBackend(backendName); - const result = asyncInit ? await success : success; - if (!result) { + let { success: t, asyncInit: n } = this.initializeBackend(e); + if (!(n ? await t : t)) return false; - } } - this.backendInstance = this.registry[backendName]; - this.setupRegisteredKernels(); - this.profiler = new Profiler(this.backendInstance); - return true; + return this.backendInstance = this.registry[e], this.setupRegisteredKernels(), this.profiler = new Cw(this.backendInstance), true; } setupRegisteredKernels() { - const kernels = getKernelsForBackend(this.backendName); - kernels.forEach((kernel) => { - if (kernel.setupFunc != null) { - kernel.setupFunc(this.backendInstance); - } + Jh(this.backendName).forEach((t) => { + t.setupFunc != null && t.setupFunc(this.backendInstance); }); } - disposeRegisteredKernels(backendName) { - const kernels = getKernelsForBackend(backendName); - kernels.forEach((kernel) => { - if (kernel.disposeFunc != null) { - kernel.disposeFunc(this.registry[backendName]); - } + disposeRegisteredKernels(e) { + Jh(e).forEach((n) => { + n.disposeFunc != null && n.disposeFunc(this.registry[e]); }); } - initializeBackend(backendName) { - const registryFactoryEntry = this.registryFactory[backendName]; - if (registryFactoryEntry == null) { - throw new Error(`Cannot initialize backend ${backendName}, no registration found.`); - } + initializeBackend(e) { + let t = this.registryFactory[e]; + if (t == null) + throw new Error(`Cannot initialize backend ${e}, no registration found.`); try { - const backend22 = registryFactoryEntry.factory(); - if (backend22 && !(backend22 instanceof KernelBackend) && typeof backend22.then === "function") { - const promiseId = ++this.pendingBackendInitId; - const success = backend22.then((backendInstance) => { - if (promiseId < this.pendingBackendInitId) { - return false; - } - this.registry[backendName] = backendInstance; - this.pendingBackendInit = null; - return true; - }).catch((err) => { - if (promiseId < this.pendingBackendInitId) { - return false; - } - this.pendingBackendInit = null; - warn(`Initialization of backend ${backendName} failed`); - warn(err.stack || err.message); - return false; - }); - this.pendingBackendInit = success; - return { success, asyncInit: true }; - } else { - this.registry[backendName] = backend22; - return { success: true, asyncInit: false }; - } - } catch (err) { - warn(`Initialization of backend ${backendName} failed`); - warn(err.stack || err.message); - return { success: false, asyncInit: false }; + let n = t.factory(); + if (n && !(n instanceof Ls) && typeof n.then == "function") { + let o = ++this.pendingBackendInitId, s = n.then((a) => o < this.pendingBackendInitId ? false : (this.registry[e] = a, this.pendingBackendInit = null, true)).catch((a) => (o < this.pendingBackendInitId || (this.pendingBackendInit = null, Vn(`Initialization of backend ${e} failed`), Vn(a.stack || a.message)), false)); + return this.pendingBackendInit = s, { success: s, asyncInit: true }; + } else + return this.registry[e] = n, { success: true, asyncInit: false }; + } catch (n) { + return Vn(`Initialization of backend ${e} failed`), Vn(n.stack || n.message), { success: false, asyncInit: false }; } } - removeBackend(backendName) { - if (!(backendName in this.registryFactory)) { - throw new Error(`${backendName} backend not found in registry`); - } - if (this.backendName === backendName && this.pendingBackendInit != null) { - this.pendingBackendInitId++; - } - if (backendName in this.registry) { - this.disposeRegisteredKernels(backendName); - this.registry[backendName].dispose(); - delete this.registry[backendName]; - } - delete this.registryFactory[backendName]; - if (this.backendName === backendName) { - this.pendingBackendInit = null; - this.backendName = null; - this.backendInstance = null; - } + removeBackend(e) { + if (!(e in this.registryFactory)) + throw new Error(`${e} backend not found in registry`); + this.backendName === e && this.pendingBackendInit != null && this.pendingBackendInitId++, e in this.registry && (this.disposeRegisteredKernels(e), this.registry[e].dispose(), delete this.registry[e]), delete this.registryFactory[e], this.backendName === e && (this.pendingBackendInit = null, this.backendName = null, this.backendInstance = null); } getSortedBackends() { - if (Object.keys(this.registryFactory).length === 0) { + if (Object.keys(this.registryFactory).length === 0) throw new Error("No backend found in registry."); - } - return Object.keys(this.registryFactory).sort((a, b) => { - return this.registryFactory[b].priority - this.registryFactory[a].priority; - }); + return Object.keys(this.registryFactory).sort((e, t) => this.registryFactory[t].priority - this.registryFactory[e].priority); } initializeBackendsAndReturnBest() { - const sortedBackends = this.getSortedBackends(); - for (let i = 0; i < sortedBackends.length; i++) { - const backendName = sortedBackends[i]; - const { success, asyncInit } = this.initializeBackend(backendName); - if (asyncInit || success) { - return { name: backendName, asyncInit }; - } + let e = this.getSortedBackends(); + for (let t = 0; t < e.length; t++) { + let n = e[t], { success: o, asyncInit: s } = this.initializeBackend(n); + if (s || o) + return { name: n, asyncInit: s }; } - throw new Error(`Could not initialize any backends, all backend initializations failed.`); + throw new Error("Could not initialize any backends, all backend initializations failed."); } - moveData(backend22, dataId) { - const info2 = this.state.tensorInfo.get(dataId); - const srcBackend = info2.backend; - const values = this.readSync(dataId); - const refCount = srcBackend.refCount(dataId); - srcBackend.disposeData(dataId, true); - info2.backend = backend22; - backend22.move(dataId, values, info2.shape, info2.dtype, refCount); - if (this.shouldCheckForMemLeaks()) { - this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++; - } + moveData(e, t) { + let n = this.state.tensorInfo.get(t), o = n.backend, s = this.readSync(t), a = o.refCount(t); + o.disposeData(t, true), n.backend = e, e.move(t, s, n.shape, n.dtype, a), this.shouldCheckForMemLeaks() && this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]++; } - tidy(nameOrFn, fn) { - let name = null; - if (fn == null) { - if (typeof nameOrFn !== "function") { + tidy(e, t) { + let n = null; + if (t == null) { + if (typeof e != "function") throw new Error("Please provide a function to tidy()"); - } - fn = nameOrFn; + t = e; } else { - if (typeof nameOrFn !== "string" && !(nameOrFn instanceof String)) { + if (typeof e != "string" && !(e instanceof String)) throw new Error("When calling with two arguments, the first argument to tidy() must be a string"); - } - if (typeof fn !== "function") { + if (typeof t != "function") throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function"); - } - name = nameOrFn; + n = e; } - let result; - return this.scopedRun(() => this.startScope(name), () => this.endScope(result), () => { - result = fn(); - if (result instanceof Promise) { - console.error("Cannot return a Promise inside of tidy."); - } - return result; - }); + let o; + return this.scopedRun(() => this.startScope(n), () => this.endScope(o), () => (o = t(), o instanceof Promise && console.error("Cannot return a Promise inside of tidy."), o)); } - scopedRun(start, end, f) { - start(); + scopedRun(e, t, n) { + e(); try { - const res = f(); - end(); - return res; - } catch (ex) { - end(); - throw ex; + let o = n(); + return t(), o; + } catch (o) { + throw t(), o; } } nextTensorId() { - return Engine.nextTensorId++; + return Jl.nextTensorId++; } nextVariableId() { - return Engine.nextVariableId++; + return Jl.nextVariableId++; } - clone(x) { - const y = ENGINE.runKernel(Identity, { x }); - const inputs = { x }; - const grad2 = (dy) => ({ - x: () => { - const dtype = "float32"; - const gradInputs = { x: dy }; - const attrs = { dtype }; - return ENGINE.runKernel(Cast, gradInputs, attrs); - } - }); - const saved = []; - this.addTapeNode(this.state.activeScope.name, inputs, [y], grad2, saved, {}); - return y; + clone(e) { + let t = T.runKernel(to, { x: e }), n = { x: e }, o = (a) => ({ x: () => { + let i = "float32", l = { x: a }, u = { dtype: i }; + return T.runKernel(Qn, l, u); + } }), s = []; + return this.addTapeNode(this.state.activeScope.name, n, [t], o, s, {}), t; } - runKernel(kernelName, inputs, attrs) { - if (this.backendName == null) { - this.backend; - } - const hasKernel = getKernel(kernelName, this.backendName) != null; - if (!hasKernel) { - throw new Error(`Kernel '${kernelName}' not registered for backend '${this.backendName}'`); - } - return this.runKernelFunc({ kernelName, inputs, attrs }); + runKernel(e, t, n) { + if (this.backendName == null && this.backend, !(Om(e, this.backendName) != null)) + throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`); + return this.runKernelFunc({ kernelName: e, inputs: t, attrs: n }); } shouldCheckForMemLeaks() { return this.ENV.getBool("IS_TEST"); } - checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos) { - const numDataIdsAfter = this.backend.numDataIds(); - let numOutputDataIds = 0; - outInfos.forEach((info2) => { - numOutputDataIds += info2.dtype === "complex64" ? 3 : 1; + checkKernelForMemLeak(e, t, n) { + let o = this.backend.numDataIds(), s = 0; + n.forEach((l) => { + s += l.dtype === "complex64" ? 3 : 1; }); - const numMoves = this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1]; - const dataIdsLeaked = numDataIdsAfter - numDataIdsBefore - numOutputDataIds - numMoves; - if (dataIdsLeaked > 0) { - throw new Error(`Backend '${this.backendName}' has an internal memory leak (${dataIdsLeaked} data ids) after running '${kernelName}'`); - } + let a = this.state.numDataMovesStack[this.state.numDataMovesStack.length - 1], i = o - t - s - a; + if (i > 0) + throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`); } - runKernelFunc(kernelParams) { - let outputs; - let saved = []; - const isTapeOn = this.isTapeOn(); - const startingBytecount = this.state.numBytes; - const startingNumTensors = this.state.numTensors; - if (this.shouldCheckForMemLeaks()) { - this.state.numDataMovesStack.push(0); - } - let kernelFunc3; - if (this.backendName == null) { - this.backend; - } - let out; - const kernelOrScopeName = isRegisteredKernelInvocation(kernelParams) ? kernelParams.kernelName : this.state.activeScope != null ? this.state.activeScope.name : ""; - if (isRegisteredKernelInvocation(kernelParams)) { - const { kernelName, inputs: inputs2, attrs: attrs2 } = kernelParams; - if (this.backendName == null) { - this.backend; - } - const kernel = getKernel(kernelName, this.backendName); - assert(kernel != null, () => `Cannot find registered kernel '${kernelName}' for backend '${this.backendName}'`); - kernelFunc3 = () => { - const numDataIdsBefore = this.backend.numDataIds(); - out = kernel.kernelFunc({ inputs: inputs2, attrs: attrs2, backend: this.backend }); - const outInfos = Array.isArray(out) ? out : [out]; - if (this.shouldCheckForMemLeaks()) { - this.checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos); - } - const outTensors = outInfos.map((outInfo) => { - if (outInfo.rank != null) { - return outInfo; - } - const { dataId, shape, dtype } = outInfo; - return this.makeTensorFromDataId(dataId, shape, dtype); + runKernelFunc(e) { + let t, n = [], o = this.isTapeOn(), s = this.state.numBytes, a = this.state.numTensors; + this.shouldCheckForMemLeaks() && this.state.numDataMovesStack.push(0); + let i; + this.backendName == null && this.backend; + let l, u = Dw(e) ? e.kernelName : this.state.activeScope != null ? this.state.activeScope.name : ""; + if (Dw(e)) { + let { kernelName: d, inputs: h, attrs: g } = e; + this.backendName == null && this.backend; + let y = Om(d, this.backendName); + E(y != null, () => `Cannot find registered kernel '${d}' for backend '${this.backendName}'`), i = () => { + let w = this.backend.numDataIds(); + l = y.kernelFunc({ inputs: h, attrs: g, backend: this.backend }); + let x = Array.isArray(l) ? l : [l]; + this.shouldCheckForMemLeaks() && this.checkKernelForMemLeak(d, w, x); + let k = x.map((C) => { + if (C.rank != null) + return C; + let { dataId: A, shape: $, dtype: R } = C; + return this.makeTensorFromDataId(A, $, R); }); - if (isTapeOn) { - const tensorsToSave = this.getTensorsForGradient(kernelName, inputs2, outTensors); - saved = this.saveTensorsForBackwardMode(tensorsToSave); + if (o) { + let C = this.getTensorsForGradient(d, h, k); + n = this.saveTensorsForBackwardMode(C); } - return outTensors; + return k; }; } else { - const { forwardFunc } = kernelParams; - const saveFunc = (tensors) => { - if (!isTapeOn) { - return; - } - saved = tensors.map((tensor2) => this.keep(this.clone(tensor2))); + let { forwardFunc: d } = e, h = (g) => { + !o || (n = g.map((y) => this.keep(this.clone(y)))); }; - kernelFunc3 = () => { - const numDataIdsBefore = this.backend.numDataIds(); - out = this.tidy(() => forwardFunc(this.backend, saveFunc)); - const outs = Array.isArray(out) ? out : [out]; - if (this.shouldCheckForMemLeaks()) { - this.checkKernelForMemLeak(kernelOrScopeName, numDataIdsBefore, outs); - } - return outs; + i = () => { + let g = this.backend.numDataIds(); + l = this.tidy(() => d(this.backend, h)); + let y = Array.isArray(l) ? l : [l]; + return this.shouldCheckForMemLeaks() && this.checkKernelForMemLeak(u, g, y), y; }; } - const { inputs, attrs } = kernelParams; - const backwardsFunc = isRegisteredKernelInvocation(kernelParams) ? null : kernelParams.backwardsFunc; - let kernelProfile; - this.scopedRun(() => this.state.kernelDepth++, () => this.state.kernelDepth--, () => { - if (!this.ENV.getBool("DEBUG") && !this.state.profiling) { - outputs = kernelFunc3(); - } else { - kernelProfile = this.profiler.profileKernel(kernelOrScopeName, inputs, () => kernelFunc3()); - if (this.ENV.getBool("DEBUG")) { - this.profiler.logKernelProfile(kernelProfile); - } - outputs = kernelProfile.outputs; - } - }); - if (isTapeOn) { - this.addTapeNode(kernelOrScopeName, inputs, outputs, backwardsFunc, saved, attrs); - } - if (this.state.profiling) { - this.state.activeProfile.kernels.push({ - name: kernelOrScopeName, - bytesAdded: this.state.numBytes - startingBytecount, - totalBytesSnapshot: this.state.numBytes, - tensorsAdded: this.state.numTensors - startingNumTensors, - totalTensorsSnapshot: this.state.numTensors, - inputShapes: Object.keys(inputs).map((key) => inputs[key] != null ? inputs[key].shape : null), - outputShapes: outputs.map((item) => item.shape), - kernelTimeMs: kernelProfile.timeMs, - extraInfo: kernelProfile.extraInfo - }); - } - return Array.isArray(out) ? outputs : outputs[0]; + let { inputs: c, attrs: p } = e, m = Dw(e) ? null : e.backwardsFunc, f; + return this.scopedRun(() => this.state.kernelDepth++, () => this.state.kernelDepth--, () => { + !this.ENV.getBool("DEBUG") && !this.state.profiling ? t = i() : (f = this.profiler.profileKernel(u, c, () => i()), this.ENV.getBool("DEBUG") && this.profiler.logKernelProfile(f), t = f.outputs); + }), o && this.addTapeNode(u, c, t, m, n, p), this.state.profiling && this.state.activeProfile.kernels.push({ name: u, bytesAdded: this.state.numBytes - s, totalBytesSnapshot: this.state.numBytes, tensorsAdded: this.state.numTensors - a, totalTensorsSnapshot: this.state.numTensors, inputShapes: Object.keys(c).map((d) => c[d] != null ? c[d].shape : null), outputShapes: t.map((d) => d.shape), kernelTimeMs: f.timeMs, extraInfo: f.extraInfo }), Array.isArray(l) ? t : t[0]; } - saveTensorsForBackwardMode(tensors) { - const saved = tensors.map((tensor2) => this.keep(this.clone(tensor2))); - return saved; + saveTensorsForBackwardMode(e) { + return e.map((n) => this.keep(this.clone(n))); } - getTensorsForGradient(kernelName, inputs, outputs) { - const gradConfig = getGradient(kernelName); - if (gradConfig != null) { - const inputsToSave = gradConfig.inputsToSave || []; - const outputsToSave = gradConfig.outputsToSave || []; - let inputTensorsToSave; - if (gradConfig.saveAllInputs) { - assert(Array.isArray(inputs), () => "saveAllInputs is true, expected inputs to be an array."); - inputTensorsToSave = Object.keys(inputs).map((key) => inputs[key]); - } else { - inputTensorsToSave = inputsToSave.map((inputName) => inputs[inputName]); - } - const outputTensorsToSave = outputs.filter((_, i) => outputsToSave[i]); - return inputTensorsToSave.concat(outputTensorsToSave); + getTensorsForGradient(e, t, n) { + let o = bw(e); + if (o != null) { + let s = o.inputsToSave || [], a = o.outputsToSave || [], i; + o.saveAllInputs ? (E(Array.isArray(t), () => "saveAllInputs is true, expected inputs to be an array."), i = Object.keys(t).map((u) => t[u])) : i = s.map((u) => t[u]); + let l = n.filter((u, c) => a[c]); + return i.concat(l); } return []; } - makeTensor(values, shape, dtype, backend22) { - if (values == null) { + makeTensor(e, t, n, o) { + if (e == null) throw new Error("Values passed to engine.makeTensor() are null"); + n = n || "float32", o = o || this.backend; + let s = e; + n === "string" && Co(e[0]) && (s = e.map((l) => ll(l))); + let a = o.write(s, t, n), i = new je(t, n, a, this.nextTensorId()); + if (this.trackTensor(i, o), n === "string") { + let l = this.state.tensorInfo.get(a), u = hw(s); + this.state.numBytes += u - l.bytes, l.bytes = u; } - dtype = dtype || "float32"; - backend22 = backend22 || this.backend; - let backendVals = values; - if (dtype === "string" && isString(values[0])) { - backendVals = values.map((d) => encodeString(d)); - } - const dataId = backend22.write(backendVals, shape, dtype); - const t = new Tensor(shape, dtype, dataId, this.nextTensorId()); - this.trackTensor(t, backend22); - if (dtype === "string") { - const info2 = this.state.tensorInfo.get(dataId); - const newBytes = bytesFromStringArray(backendVals); - this.state.numBytes += newBytes - info2.bytes; - info2.bytes = newBytes; - } - return t; + return i; } - makeTensorFromDataId(dataId, shape, dtype, backend22) { - dtype = dtype || "float32"; - const t = new Tensor(shape, dtype, dataId, this.nextTensorId()); - this.trackTensor(t, backend22); - return t; + makeTensorFromDataId(e, t, n, o) { + n = n || "float32"; + let s = new je(t, n, e, this.nextTensorId()); + return this.trackTensor(s, o), s; } - makeVariable(initialValue, trainable = true, name, dtype) { - name = name || this.nextVariableId().toString(); - if (dtype != null && dtype !== initialValue.dtype) { - initialValue = initialValue.cast(dtype); - } - const v = new Variable(initialValue, trainable, name, this.nextTensorId()); - if (this.state.registeredVariables[v.name] != null) { - throw new Error(`Variable with name ${v.name} was already registered`); - } - this.state.registeredVariables[v.name] = v; - this.incRef(v, this.backend); - return v; + makeVariable(e, t = true, n, o) { + n = n || this.nextVariableId().toString(), o != null && o !== e.dtype && (e = e.cast(o)); + let s = new ul(e, t, n, this.nextTensorId()); + if (this.state.registeredVariables[s.name] != null) + throw new Error(`Variable with name ${s.name} was already registered`); + return this.state.registeredVariables[s.name] = s, this.incRef(s, this.backend), s; } - trackTensor(a, backend22) { - this.state.numTensors++; - if (a.dtype === "string") { - this.state.numStringTensors++; - } - let bytes = 0; - if (a.dtype !== "complex64" && a.dtype !== "string") { - bytes = a.size * bytesPerElement(a.dtype); - } - this.state.numBytes += bytes; - if (!this.state.tensorInfo.has(a.dataId)) { - this.state.numDataBuffers++; - this.state.tensorInfo.set(a.dataId, { - backend: backend22 || this.backend, - dtype: a.dtype, - shape: a.shape, - bytes - }); - } - if (!(a instanceof Variable)) { - this.track(a); - } + trackTensor(e, t) { + this.state.numTensors++, e.dtype === "string" && this.state.numStringTensors++; + let n = 0; + e.dtype !== "complex64" && e.dtype !== "string" && (n = e.size * Xh(e.dtype)), this.state.numBytes += n, this.state.tensorInfo.has(e.dataId) || (this.state.numDataBuffers++, this.state.tensorInfo.set(e.dataId, { backend: t || this.backend, dtype: e.dtype, shape: e.shape, bytes: n })), e instanceof ul || this.track(e); } - incRef(a, backend22) { - this.trackTensor(a, backend22); - this.backend.incRef(a.dataId); + incRef(e, t) { + this.trackTensor(e, t), this.backend.incRef(e.dataId); } - removeDataId(dataId, backend22) { - if (this.state.tensorInfo.has(dataId) && this.state.tensorInfo.get(dataId).backend === backend22) { - this.state.tensorInfo.delete(dataId); - this.state.numDataBuffers--; - } + removeDataId(e, t) { + this.state.tensorInfo.has(e) && this.state.tensorInfo.get(e).backend === t && (this.state.tensorInfo.delete(e), this.state.numDataBuffers--); } - disposeTensor(a) { - if (!this.state.tensorInfo.has(a.dataId)) { + disposeTensor(e) { + if (!this.state.tensorInfo.has(e.dataId)) return; + let t = this.state.tensorInfo.get(e.dataId); + if (this.state.numTensors--, e.dtype === "string" && (this.state.numStringTensors--, this.state.numBytes -= t.bytes), e.dtype !== "complex64" && e.dtype !== "string") { + let n = e.size * Xh(e.dtype); + this.state.numBytes -= n; } - const info2 = this.state.tensorInfo.get(a.dataId); - this.state.numTensors--; - if (a.dtype === "string") { - this.state.numStringTensors--; - this.state.numBytes -= info2.bytes; - } - if (a.dtype !== "complex64" && a.dtype !== "string") { - const bytes = a.size * bytesPerElement(a.dtype); - this.state.numBytes -= bytes; - } - if (info2.backend.disposeData(a.dataId)) { - this.removeDataId(a.dataId, info2.backend); - } + t.backend.disposeData(e.dataId) && this.removeDataId(e.dataId, t.backend); } disposeVariables() { - for (const varName in this.state.registeredVariables) { - const v = this.state.registeredVariables[varName]; - this.disposeVariable(v); + for (let e in this.state.registeredVariables) { + let t = this.state.registeredVariables[e]; + this.disposeVariable(t); } } - disposeVariable(v) { - this.disposeTensor(v); - if (this.state.registeredVariables[v.name] != null) { - delete this.state.registeredVariables[v.name]; - } + disposeVariable(e) { + this.disposeTensor(e), this.state.registeredVariables[e.name] != null && delete this.state.registeredVariables[e.name]; } memory() { - const info2 = this.backend.memory(); - info2.numTensors = this.state.numTensors; - info2.numDataBuffers = this.state.numDataBuffers; - info2.numBytes = this.state.numBytes; - if (this.state.numStringTensors > 0) { - info2.unreliable = true; - if (info2.reasons == null) { - info2.reasons = []; - } - info2.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)"); - } - return info2; + let e = this.backend.memory(); + return e.numTensors = this.state.numTensors, e.numDataBuffers = this.state.numDataBuffers, e.numBytes = this.state.numBytes, this.state.numStringTensors > 0 && (e.unreliable = true, e.reasons == null && (e.reasons = []), e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")), e; } - async profile(query) { + async profile(e) { this.state.profiling = true; - const startBytes = this.state.numBytes; - const startNumTensors = this.state.numTensors; - this.state.activeProfile.kernels = []; - this.state.activeProfile.result = await query(); - this.state.profiling = false; - this.state.activeProfile.peakBytes = Math.max(...this.state.activeProfile.kernels.map((d) => d.totalBytesSnapshot)); - this.state.activeProfile.newBytes = this.state.numBytes - startBytes; - this.state.activeProfile.newTensors = this.state.numTensors - startNumTensors; - for (const kernel of this.state.activeProfile.kernels) { - kernel.kernelTimeMs = await kernel.kernelTimeMs; - kernel.extraInfo = await kernel.extraInfo; - } + let t = this.state.numBytes, n = this.state.numTensors; + this.state.activeProfile.kernels = [], this.state.activeProfile.result = await e(), this.state.profiling = false, this.state.activeProfile.peakBytes = Math.max(...this.state.activeProfile.kernels.map((o) => o.totalBytesSnapshot)), this.state.activeProfile.newBytes = this.state.numBytes - t, this.state.activeProfile.newTensors = this.state.numTensors - n; + for (let o of this.state.activeProfile.kernels) + o.kernelTimeMs = await o.kernelTimeMs, o.extraInfo = await o.extraInfo; return this.state.activeProfile; } isTapeOn() { return this.state.gradientDepth > 0 && this.state.kernelDepth === 0; } - addTapeNode(kernelName, inputs, outputs, gradientsFunc, saved, attrs) { - const tapeNode = { id: this.state.nextTapeNodeId++, kernelName, inputs, outputs, saved }; - const gradConfig = getGradient(kernelName); - if (gradConfig != null) { - gradientsFunc = gradConfig.gradFunc; - } - if (gradientsFunc != null) { - tapeNode.gradient = (dys) => { - dys = dys.map((dy, i) => { - if (dy == null) { - const output = outputs[i]; - const vals = makeZerosTypedArray(output.size, output.dtype); - return this.makeTensor(vals, output.shape, output.dtype); - } - return dy; - }); - return gradientsFunc(dys.length > 1 ? dys : dys[0], saved, attrs); - }; - } - this.state.activeTape.push(tapeNode); + addTapeNode(e, t, n, o, s, a) { + let i = { id: this.state.nextTapeNodeId++, kernelName: e, inputs: t, outputs: n, saved: s }, l = bw(e); + l != null && (o = l.gradFunc), o != null && (i.gradient = (u) => (u = u.map((c, p) => { + if (c == null) { + let m = n[p], f = hc(m.size, m.dtype); + return this.makeTensor(f, m.shape, m.dtype); + } + return c; + }), o(u.length > 1 ? u : u[0], s, a))), this.state.activeTape.push(i); } - keep(result) { - result.kept = true; - return result; + keep(e) { + return e.kept = true, e; } startTape() { - if (this.state.gradientDepth === 0) { - this.state.activeTape = []; - } - this.state.gradientDepth++; + this.state.gradientDepth === 0 && (this.state.activeTape = []), this.state.gradientDepth++; } endTape() { this.state.gradientDepth--; } - startScope(name) { - const scopeInfo = { - track: [], - name: "unnamed scope", - id: this.state.nextScopeId++ - }; - if (name) { - scopeInfo.name = name; - } - this.state.scopeStack.push(scopeInfo); - this.state.activeScope = scopeInfo; + startScope(e) { + let t = { track: [], name: "unnamed scope", id: this.state.nextScopeId++ }; + e && (t.name = e), this.state.scopeStack.push(t), this.state.activeScope = t; } - endScope(result) { - const tensorsToTrackInParent = getTensorsInContainer(result); - const tensorsToTrackInParentSet = new Set(tensorsToTrackInParent.map((t) => t.id)); - for (let i = 0; i < this.state.activeScope.track.length; i++) { - const tensor2 = this.state.activeScope.track[i]; - if (!tensor2.kept && !tensorsToTrackInParentSet.has(tensor2.id)) { - tensor2.dispose(); - } + endScope(e) { + let t = Bm(e), n = new Set(t.map((s) => s.id)); + for (let s = 0; s < this.state.activeScope.track.length; s++) { + let a = this.state.activeScope.track[s]; + !a.kept && !n.has(a.id) && a.dispose(); } - const oldScope = this.state.scopeStack.pop(); - this.state.activeScope = this.state.scopeStack.length === 0 ? null : this.state.scopeStack[this.state.scopeStack.length - 1]; - tensorsToTrackInParent.forEach((tensor2) => { - if (!tensor2.kept && tensor2.scopeId === oldScope.id) { - this.track(tensor2); - } + let o = this.state.scopeStack.pop(); + this.state.activeScope = this.state.scopeStack.length === 0 ? null : this.state.scopeStack[this.state.scopeStack.length - 1], t.forEach((s) => { + !s.kept && s.scopeId === o.id && this.track(s); }); } - gradients(f, xs, dy, allowNoGradients = false) { - assert(xs.length > 0, () => "gradients() received an empty list of xs."); - if (dy != null && dy.dtype !== "float32") { - throw new Error(`dy must have 'float32' dtype, but has '${dy.dtype}'`); - } - const y = this.scopedRun(() => this.startTape(), () => this.endTape(), () => this.tidy("forward", f)); - assert(y instanceof Tensor, () => "The result y returned by f() must be a tensor."); - const filteredTape = getFilteredNodesXToY(this.state.activeTape, xs, y); - if (!allowNoGradients && filteredTape.length === 0 && xs.length > 0) { + gradients(e, t, n, o = false) { + if (E(t.length > 0, () => "gradients() received an empty list of xs."), n != null && n.dtype !== "float32") + throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`); + let s = this.scopedRun(() => this.startTape(), () => this.endTape(), () => this.tidy("forward", e)); + E(s instanceof je, () => "The result y returned by f() must be a tensor."); + let a = d1(this.state.activeTape, t, s); + if (!o && a.length === 0 && t.length > 0) throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y."); - } return this.tidy("backward", () => { - const accumulatedGradientMap = {}; - accumulatedGradientMap[y.id] = dy == null ? ones(y.shape) : dy; - backpropagateGradients(accumulatedGradientMap, filteredTape, (f2) => this.tidy(f2), add); - const grads2 = xs.map((x) => accumulatedGradientMap[x.id]); - if (this.state.gradientDepth === 0) { - this.state.activeTape.forEach((node) => { - for (const tensor2 of node.saved) { - tensor2.dispose(); - } - }); - this.state.activeTape = null; - } - return { value: y, grads: grads2 }; + let i = {}; + i[s.id] = n == null ? Vj(s.shape) : n, h1(i, a, (u) => this.tidy(u), Wj); + let l = t.map((u) => i[u.id]); + return this.state.gradientDepth === 0 && (this.state.activeTape.forEach((u) => { + for (let c of u.saved) + c.dispose(); + }), this.state.activeTape = null), { value: s, grads: l }; }); } - customGrad(f) { - assert(isFunction(f), () => "The f passed in customGrad(f) must be a function."); - return (...inputs) => { - assert(inputs.every((t) => t instanceof Tensor), () => "The args passed in customGrad(f)(x1, x2,...) must all be tensors"); - let res; - const inputMap = {}; - inputs.forEach((input2, i) => { - inputMap[i] = input2; + customGrad(e) { + return E(zs(e), () => "The f passed in customGrad(f) must be a function."), (...t) => { + E(t.every((i) => i instanceof je), () => "The args passed in customGrad(f)(x1, x2,...) must all be tensors"); + let n, o = {}; + t.forEach((i, l) => { + o[l] = i; }); - const forwardFunc = (_, save) => { - res = f(...[...inputs, save]); - assert(res.value instanceof Tensor, () => "The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"); - assert(isFunction(res.gradFunc), () => "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."); - return res.value; + let s = (i, l) => (n = e(...t, l), E(n.value instanceof je, () => "The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"), E(zs(n.gradFunc), () => "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."), n.value), a = (i, l) => { + let u = n.gradFunc(i, l), c = Array.isArray(u) ? u : [u]; + E(c.length === t.length, () => "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."), E(c.every((m) => m instanceof je), () => "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."); + let p = {}; + return c.forEach((m, f) => { + p[f] = () => m; + }), p; }; - const backwardsFunc = (dy, saved) => { - const gradRes = res.gradFunc(dy, saved); - const grads2 = Array.isArray(gradRes) ? gradRes : [gradRes]; - assert(grads2.length === inputs.length, () => "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."); - assert(grads2.every((t) => t instanceof Tensor), () => "The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."); - const gradMap = {}; - grads2.forEach((grad2, i) => { - gradMap[i] = () => grad2; - }); - return gradMap; - }; - return this.runKernelFunc({ - forwardFunc, - backwardsFunc, - inputs: inputMap - }); + return this.runKernelFunc({ forwardFunc: s, backwardsFunc: a, inputs: o }); }; } - readSync(dataId) { - const info2 = this.state.tensorInfo.get(dataId); - return info2.backend.readSync(dataId); + readSync(e) { + return this.state.tensorInfo.get(e).backend.readSync(e); } - read(dataId) { - const info2 = this.state.tensorInfo.get(dataId); - return info2.backend.read(dataId); + read(e) { + return this.state.tensorInfo.get(e).backend.read(e); } - async time(query) { - const start = now2(); - const timingInfo = await this.backend.time(query); - timingInfo.wallMs = now2() - start; - return timingInfo; + async time(e) { + let t = Yl(), n = await this.backend.time(e); + return n.wallMs = Yl() - t, n; } - track(result) { - if (this.state.activeScope != null) { - result.scopeId = this.state.activeScope.id; - this.state.activeScope.track.push(result); - } - return result; + track(e) { + return this.state.activeScope != null && (e.scopeId = this.state.activeScope.id, this.state.activeScope.track.push(e)), e; } get registeredVariables() { return this.state.registeredVariables; } reset() { - this.pendingBackendInitId++; - this.state.dispose(); - this.ENV.reset(); - this.state = new EngineState(); - for (const backendName in this.registry) { - this.disposeRegisteredKernels(backendName); - this.registry[backendName].dispose(); - delete this.registry[backendName]; - } - this.backendName = null; - this.backendInstance = null; - this.pendingBackendInit = null; + this.pendingBackendInitId++, this.state.dispose(), this.ENV.reset(), this.state = new Rw(); + for (let e in this.registry) + this.disposeRegisteredKernels(e), this.registry[e].dispose(), delete this.registry[e]; + this.backendName = null, this.backendInstance = null, this.pendingBackendInit = null; } }; -Engine.nextTensorId = 0; -Engine.nextVariableId = 0; -function ones(shape) { - const values = makeOnesTypedArray(sizeFromShape(shape), "float32"); - return ENGINE.makeTensor(values, shape, "float32"); +Jl.nextTensorId = 0; +Jl.nextVariableId = 0; +function Vj(r) { + let e = Nm(nt(r), "float32"); + return T.makeTensor(e, r, "float32"); } -function getOrMakeEngine() { - const ns = getGlobalNamespace(); - if (ns._tfengine == null) { - const environment = new Environment(ns); - ns._tfengine = new Engine(environment); +function Fw() { + let r = yw(); + if (r._tfengine == null) { + let e = new Yh(r); + r._tfengine = new Jl(e); } - setEnvironmentGlobal(ns._tfengine.ENV); - setTensorTracker(() => ns._tfengine); - return ns._tfengine; + return KI(r._tfengine.ENV), b1(() => r._tfengine), r._tfengine; } -var ENGINE = getOrMakeEngine(); -function add(a, b) { - const inputs = { a, b }; - return ENGINE.runKernel(Add, inputs); +var T = Fw(); +function Wj(r, e) { + let t = { a: r, b: e }; + return T.runKernel(Wn, t); } -var device_util_exports = {}; -__export2(device_util_exports, { - isBrowser: () => isBrowser, - isMobile: () => isMobile -}); -function _isNavigatorDefined() { - return typeof navigator !== "undefined" && navigator != null; +var Ql = {}; +He(Ql, { isBrowser: () => Ow, isMobile: () => Gj }); +function jj() { + return typeof navigator != "undefined" && navigator != null; } -function isMobile(nav) { - if (nav || _isNavigatorDefined()) { - if (!nav) { - nav = navigator; - } - if (nav.product === "ReactNative") { +function Gj(r) { + if (r || jj()) { + if (r || (r = navigator), r.product === "ReactNative") return true; + let e = r.userAgent || r.vendor || (typeof window != "undefined" ? window.opera : ""); + if (!e) { + let t = r; + return t.userAgentData && t.userAgentData.mobile; } - const a = nav.userAgent || nav.vendor || (typeof window !== "undefined" ? window.opera : ""); - if (!a) { - const navAny = nav; - return navAny.userAgentData && navAny.userAgentData.mobile; - } - return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4)); + return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0, 4)); } return false; } -function isBrowser() { - return typeof window !== "undefined" && window.document != null || typeof WorkerGlobalScope !== "undefined"; +function Ow() { + return typeof window != "undefined" && window.document != null || typeof WorkerGlobalScope != "undefined"; } -var ENV2 = env(); -ENV2.registerFlag("DEBUG", () => false, (debugValue) => { - if (debugValue) { - console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance."); - } +var ws = j(); +ws.registerFlag("DEBUG", () => false, (r) => { + r && console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance."); }); -ENV2.registerFlag("IS_BROWSER", () => isBrowser()); -ENV2.registerFlag("IS_NODE", () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined"); -ENV2.registerFlag("IS_CHROME", () => typeof navigator !== "undefined" && navigator != null && navigator.userAgent != null && /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor)); -ENV2.registerFlag("PROD", () => false); -ENV2.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY", () => ENV2.getBool("DEBUG")); -ENV2.registerFlag("DEPRECATION_WARNINGS_ENABLED", () => true); -ENV2.registerFlag("IS_TEST", () => false); -ENV2.registerFlag("CHECK_COMPUTATION_FOR_ERRORS", () => true); -ENV2.registerFlag("WRAP_TO_IMAGEBITMAP", () => false); -function inferShape(val, dtype) { - let firstElem = val; - if (isTypedArray(val)) { - return dtype === "string" ? [] : [val.length]; - } - if (!Array.isArray(val)) { +ws.registerFlag("IS_BROWSER", () => Ow()); +ws.registerFlag("IS_NODE", () => typeof process != "undefined" && typeof process.versions != "undefined" && typeof process.versions.node != "undefined"); +ws.registerFlag("IS_CHROME", () => typeof navigator != "undefined" && navigator != null && navigator.userAgent != null && /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor)); +ws.registerFlag("PROD", () => false); +ws.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY", () => ws.getBool("DEBUG")); +ws.registerFlag("DEPRECATION_WARNINGS_ENABLED", () => true); +ws.registerFlag("IS_TEST", () => false); +ws.registerFlag("CHECK_COMPUTATION_FOR_ERRORS", () => true); +ws.registerFlag("WRAP_TO_IMAGEBITMAP", () => false); +function Ar(r, e) { + let t = r; + if (cr(r)) + return e === "string" ? [] : [r.length]; + if (!Array.isArray(r)) return []; - } - const shape = []; - while (Array.isArray(firstElem) || isTypedArray(firstElem) && dtype !== "string") { - shape.push(firstElem.length); - firstElem = firstElem[0]; - } - if (Array.isArray(val) && env().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")) { - deepAssertShapeConsistency(val, shape, []); - } - return shape; + let n = []; + for (; Array.isArray(t) || cr(t) && e !== "string"; ) + n.push(t.length), t = t[0]; + return Array.isArray(r) && j().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY") && v1(r, n, []), n; } -function deepAssertShapeConsistency(val, shape, indices) { - indices = indices || []; - if (!Array.isArray(val) && !isTypedArray(val)) { - assert(shape.length === 0, () => `Element arr[${indices.join("][")}] is a primitive, but should be an array/TypedArray of ${shape[0]} elements`); +function v1(r, e, t) { + if (t = t || [], !Array.isArray(r) && !cr(r)) { + E(e.length === 0, () => `Element arr[${t.join("][")}] is a primitive, but should be an array/TypedArray of ${e[0]} elements`); return; } - assert(shape.length > 0, () => `Element arr[${indices.join("][")}] should be a primitive, but is an array of ${val.length} elements`); - assert(val.length === shape[0], () => `Element arr[${indices.join("][")}] should have ${shape[0]} elements, but has ${val.length} elements`); - const subShape = shape.slice(1); - for (let i = 0; i < val.length; ++i) { - deepAssertShapeConsistency(val[i], subShape, indices.concat(i)); + E(e.length > 0, () => `Element arr[${t.join("][")}] should be a primitive, but is an array of ${r.length} elements`), E(r.length === e[0], () => `Element arr[${t.join("][")}] should have ${e[0]} elements, but has ${r.length} elements`); + let n = e.slice(1); + for (let o = 0; o < r.length; ++o) + v1(r[o], n, t.concat(o)); +} +function C1(r, e, t, n) { + if (r !== "string_or_numeric") { + if (r == null) + throw new Error("Expected dtype cannot be null."); + if (r !== "numeric" && r !== e || r === "numeric" && e === "string") + throw new Error(`Argument '${t}' passed to '${n}' must be ${r} tensor, but got ${e} tensor`); } } -function assertDtype(expectedDtype, actualDType, argName, functionName) { - if (expectedDtype === "string_or_numeric") { - return; - } - if (expectedDtype == null) { - throw new Error(`Expected dtype cannot be null.`); - } - if (expectedDtype !== "numeric" && expectedDtype !== actualDType || expectedDtype === "numeric" && actualDType === "string") { - throw new Error(`Argument '${argName}' passed to '${functionName}' must be ${expectedDtype} tensor, but got ${actualDType} tensor`); +function _(r, e, t, n = "numeric") { + if (r instanceof je) + return C1(n, r.dtype, e, t), r; + let o = fc(r); + if (o !== "string" && ["bool", "int32", "float32"].indexOf(n) >= 0 && (o = n), C1(n, o, e, t), r == null || !cr(r) && !Array.isArray(r) && typeof r != "number" && typeof r != "boolean" && typeof r != "string") { + let l = r == null ? "null" : r.constructor.name; + throw new Error(`Argument '${e}' passed to '${t}' must be a Tensor or TensorLike, but got '${l}'`); } + let s = Ar(r, o); + !cr(r) && !Array.isArray(r) && (r = [r]); + let i = o !== "string" ? Qc(r, o) : vo(r, [], true); + return T.makeTensor(i, s, o); } -function convertToTensor(x, argName, functionName, parseAsDtype = "numeric") { - if (x instanceof Tensor) { - assertDtype(parseAsDtype, x.dtype, argName, functionName); - return x; - } - let inferredDtype = inferDtype(x); - if (inferredDtype !== "string" && ["bool", "int32", "float32"].indexOf(parseAsDtype) >= 0) { - inferredDtype = parseAsDtype; - } - assertDtype(parseAsDtype, inferredDtype, argName, functionName); - if (x == null || !isTypedArray(x) && !Array.isArray(x) && typeof x !== "number" && typeof x !== "boolean" && typeof x !== "string") { - const type = x == null ? "null" : x.constructor.name; - throw new Error(`Argument '${argName}' passed to '${functionName}' must be a Tensor or TensorLike, but got '${type}'`); - } - const inferredShape = inferShape(x, inferredDtype); - if (!isTypedArray(x) && !Array.isArray(x)) { - x = [x]; - } - const skipTypedArray = true; - const values = inferredDtype !== "string" ? toTypedArray(x, inferredDtype) : flatten(x, [], skipTypedArray); - return ENGINE.makeTensor(values, inferredShape, inferredDtype); +function fa(r, e, t, n = "numeric") { + if (!Array.isArray(r)) + throw new Error(`Argument ${e} passed to ${t} must be a \`Tensor[]\` or \`TensorLike[]\``); + return r.map((s, a) => _(s, `${e}[${a}]`, t, n)); } -function convertToTensorArray(arg, argName, functionName, parseAsDtype = "numeric") { - if (!Array.isArray(arg)) { - throw new Error(`Argument ${argName} passed to ${functionName} must be a \`Tensor[]\` or \`TensorLike[]\``); - } - const tensors = arg; - return tensors.map((t, i) => convertToTensor(t, `${argName}[${i}]`, functionName, parseAsDtype)); -} -var OP_SCOPE_SUFFIX = "__op"; -function op(f) { - const keys = Object.keys(f); - if (keys.length !== 1) { - throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${keys.length} keys.`); - } - let opName = keys[0]; - const fn = f[opName]; - if (opName.endsWith("_")) { - opName = opName.substring(0, opName.length - 1); - } - opName = opName + OP_SCOPE_SUFFIX; - const f2 = (...args) => { - ENGINE.startScope(opName); +var S1 = "__op"; +function I(r) { + let e = Object.keys(r); + if (e.length !== 1) + throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${e.length} keys.`); + let t = e[0], n = r[t]; + t.endsWith("_") && (t = t.substring(0, t.length - 1)), t = t + S1; + let o = (...s) => { + T.startScope(t); try { - const result = fn(...args); - if (isPromise(result)) { - console.error("Cannot return a Promise inside of tidy."); - } - ENGINE.endScope(result); - return result; - } catch (ex) { - ENGINE.endScope(null); - throw ex; + let a = n(...s); + return Em(a) && console.error("Cannot return a Promise inside of tidy."), T.endScope(a), a; + } catch (a) { + throw T.endScope(null), a; } }; - Object.defineProperty(f2, "name", { value: opName, configurable: true }); - return f2; + return Object.defineProperty(o, "name", { value: t, configurable: true }), o; } -function complex_(real4, imag4) { - const $real = convertToTensor(real4, "real", "complex"); - const $imag = convertToTensor(imag4, "imag", "complex"); - assertShapesMatch($real.shape, $imag.shape, `real and imag shapes, ${$real.shape} and ${$imag.shape}, must match in call to tf.complex().`); - const inputs = { real: $real, imag: $imag }; - return ENGINE.runKernel(Complex, inputs); +function Uj(r, e) { + let t = _(r, "real", "complex"), n = _(e, "imag", "complex"); + $t(t.shape, n.shape, `real and imag shapes, ${t.shape} and ${n.shape}, must match in call to tf.complex().`); + let o = { real: t, imag: n }; + return T.runKernel(bc, o); } -var complex = op({ complex_ }); -function makeTensor(values, shape, inferredShape, dtype) { - if (dtype == null) { - dtype = inferDtype(values); - } - if (dtype === "complex64") { - throw new Error(`Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).`); - } - if (!isTypedArray(values) && !Array.isArray(values) && typeof values !== "number" && typeof values !== "boolean" && typeof values !== "string") { +var $n = I({ complex_: Uj }); +function Yr(r, e, t, n) { + if (n == null && (n = fc(r)), n === "complex64") + throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag)."); + if (!cr(r) && !Array.isArray(r) && typeof r != "number" && typeof r != "boolean" && typeof r != "string") throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray"); - } - if (shape != null) { - assertNonNegativeIntegerDimensions(shape); - const providedSize = sizeFromShape(shape); - const inferredSize = sizeFromShape(inferredShape); - assert(providedSize === inferredSize, () => `Based on the provided shape, [${shape}], the tensor should have ${providedSize} values but has ${inferredSize}`); - for (let i = 0; i < inferredShape.length; ++i) { - const inferred = inferredShape[i]; - const flatDimsDontMatch = i === inferredShape.length - 1 ? inferred !== sizeFromShape(shape.slice(i)) : true; - assert(inferredShape[i] === shape[i] || !flatDimsDontMatch, () => `Error creating a new Tensor. Inferred shape (${inferredShape}) does not match the provided shape (${shape}). `); + if (e != null) { + Tm(e); + let o = nt(e), s = nt(t); + E(o === s, () => `Based on the provided shape, [${e}], the tensor should have ${o} values but has ${s}`); + for (let a = 0; a < t.length; ++a) { + let i = t[a], l = a === t.length - 1 ? i !== nt(e.slice(a)) : true; + E(t[a] === e[a] || !l, () => `Error creating a new Tensor. Inferred shape (${t}) does not match the provided shape (${e}). `); } } - if (!isTypedArray(values) && !Array.isArray(values)) { - values = [values]; - } - shape = shape || inferredShape; - values = dtype !== "string" ? toTypedArray(values, dtype) : flatten(values, [], true); - return ENGINE.makeTensor(values, shape, dtype); + return !cr(r) && !Array.isArray(r) && (r = [r]), e = e || t, r = n !== "string" ? Qc(r, n) : vo(r, [], true), T.makeTensor(r, e, n); } -function tensor(values, shape, dtype) { - const inferredShape = inferShape(values, dtype); - return makeTensor(values, shape, inferredShape, dtype); +function vr(r, e, t) { + let n = Ar(r, t); + return Yr(r, e, n, t); } -var DTYPE_VALUE_SIZE_MAP = { - "float32": 4, - "float16": 2, - "int32": 4, - "uint16": 2, - "uint8": 1, - "bool": 1, - "complex64": 8 -}; -var NUM_BYTES_STRING_LENGTH = 4; -async function encodeWeights(tensors, group) { - const specs = []; - const dataPromises = []; - const names = Array.isArray(tensors) ? tensors.map((tensor2) => tensor2.name) : Object.keys(tensors); - for (let i = 0; i < names.length; ++i) { - const name = names[i]; - const t = Array.isArray(tensors) ? tensors[i].tensor : tensors[name]; - if (t.dtype !== "float32" && t.dtype !== "int32" && t.dtype !== "bool" && t.dtype !== "string" && t.dtype !== "complex64") { - throw new Error(`Unsupported dtype in weight '${name}': ${t.dtype}`); - } - const spec = { name, shape: t.shape, dtype: t.dtype }; - if (t.dtype === "string") { - const utf8bytes = new Promise(async (resolve) => { - const vals = await t.bytes(); - const totalNumBytes = vals.reduce((p2, c) => p2 + c.length, 0) + NUM_BYTES_STRING_LENGTH * vals.length; - const bytes = new Uint8Array(totalNumBytes); - let offset = 0; - for (let i2 = 0; i2 < vals.length; i2++) { - const val = vals[i2]; - const bytesOfLength = new Uint8Array(new Uint32Array([val.length]).buffer); - bytes.set(bytesOfLength, offset); - offset += NUM_BYTES_STRING_LENGTH; - bytes.set(val, offset); - offset += val.length; +var Vm = { float32: 4, float16: 2, int32: 4, uint16: 2, uint8: 1, bool: 1, complex64: 8 }; +var rg = 4; +async function I1(r, e) { + let t = [], n = [], o = Array.isArray(r) ? r.map((a) => a.name) : Object.keys(r); + for (let a = 0; a < o.length; ++a) { + let i = o[a], l = Array.isArray(r) ? r[a].tensor : r[i]; + if (l.dtype !== "float32" && l.dtype !== "int32" && l.dtype !== "bool" && l.dtype !== "string" && l.dtype !== "complex64") + throw new Error(`Unsupported dtype in weight '${i}': ${l.dtype}`); + let u = { name: i, shape: l.shape, dtype: l.dtype }; + if (l.dtype === "string") { + let c = new Promise(async (p) => { + let m = await l.bytes(), f = m.reduce((g, y) => g + y.length, 0) + rg * m.length, d = new Uint8Array(f), h = 0; + for (let g = 0; g < m.length; g++) { + let y = m[g], w = new Uint8Array(new Uint32Array([y.length]).buffer); + d.set(w, h), h += rg, d.set(y, h), h += y.length; } - resolve(bytes); + p(d); }); - dataPromises.push(utf8bytes); - } else { - dataPromises.push(t.data()); - } - if (group != null) { - spec.group = group; - } - specs.push(spec); + n.push(c); + } else + n.push(l.data()); + e != null && (u.group = e), t.push(u); } - const tensorValues = await Promise.all(dataPromises); - return { data: concatenateTypedArrays(tensorValues), specs }; + let s = await Promise.all(n); + return { data: Hj(s), specs: t }; } -function decodeWeights(buffer2, specs) { - const out = {}; - let float16Decode; - let offset = 0; - for (const spec of specs) { - const name = spec.name; - const dtype = spec.dtype; - const shape = spec.shape; - const size = sizeFromShape(shape); - let values; - if ("quantization" in spec) { - const quantization = spec.quantization; - if (quantization.dtype === "uint8" || quantization.dtype === "uint16") { - if (!("min" in quantization && "scale" in quantization)) { - throw new Error(`Weight ${spec.name} with quantization ${quantization.dtype} doesn't have corresponding metadata min and scale.`); - } - } else if (quantization.dtype === "float16") { - if (dtype !== "float32") { - throw new Error(`Weight ${spec.name} is quantized with ${quantization.dtype} which only supports weights of type float32 not ${dtype}.`); - } - } else { - throw new Error(`Weight ${spec.name} has unknown quantization dtype ${quantization.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`); - } - const quantizationSizeFactor = DTYPE_VALUE_SIZE_MAP[quantization.dtype]; - const byteBuffer = buffer2.slice(offset, offset + size * quantizationSizeFactor); - const quantizedArray = quantization.dtype === "uint8" ? new Uint8Array(byteBuffer) : new Uint16Array(byteBuffer); - if (dtype === "float32") { - if (quantization.dtype === "uint8" || quantization.dtype === "uint16") { - values = new Float32Array(quantizedArray.length); - for (let i = 0; i < quantizedArray.length; i++) { - const v = quantizedArray[i]; - values[i] = v * quantization.scale + quantization.min; +function ng(r, e) { + let t = {}, n, o = 0; + for (let s of e) { + let a = s.name, i = s.dtype, l = s.shape, u = nt(l), c; + if ("quantization" in s) { + let p = s.quantization; + if (p.dtype === "uint8" || p.dtype === "uint16") { + if (!("min" in p && "scale" in p)) + throw new Error(`Weight ${s.name} with quantization ${p.dtype} doesn't have corresponding metadata min and scale.`); + } else if (p.dtype === "float16") { + if (i !== "float32") + throw new Error(`Weight ${s.name} is quantized with ${p.dtype} which only supports weights of type float32 not ${i}.`); + } else + throw new Error(`Weight ${s.name} has unknown quantization dtype ${p.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`); + let m = Vm[p.dtype], f = r.slice(o, o + u * m), d = p.dtype === "uint8" ? new Uint8Array(f) : new Uint16Array(f); + if (i === "float32") + if (p.dtype === "uint8" || p.dtype === "uint16") { + c = new Float32Array(d.length); + for (let h = 0; h < d.length; h++) { + let g = d[h]; + c[h] = g * p.scale + p.min; } - } else if (quantization.dtype === "float16") { - if (float16Decode === void 0) { - float16Decode = getFloat16Decoder(); - } - values = float16Decode(quantizedArray); - } else { - throw new Error(`Unsupported quantization type ${quantization.dtype} for weight type float32.`); + } else if (p.dtype === "float16") + n === void 0 && (n = Yj()), c = n(d); + else + throw new Error(`Unsupported quantization type ${p.dtype} for weight type float32.`); + else if (i === "int32") { + if (p.dtype !== "uint8" && p.dtype !== "uint16") + throw new Error(`Unsupported quantization type ${p.dtype} for weight type int32.`); + c = new Int32Array(d.length); + for (let h = 0; h < d.length; h++) { + let g = d[h]; + c[h] = Math.round(g * p.scale + p.min); } - } else if (dtype === "int32") { - if (quantization.dtype !== "uint8" && quantization.dtype !== "uint16") { - throw new Error(`Unsupported quantization type ${quantization.dtype} for weight type int32.`); - } - values = new Int32Array(quantizedArray.length); - for (let i = 0; i < quantizedArray.length; i++) { - const v = quantizedArray[i]; - values[i] = Math.round(v * quantization.scale + quantization.min); - } - } else { - throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`); - } - offset += size * quantizationSizeFactor; - } else if (dtype === "string") { - const size2 = sizeFromShape(spec.shape); - values = []; - for (let i = 0; i < size2; i++) { - const byteLength = new Uint32Array(buffer2.slice(offset, offset + NUM_BYTES_STRING_LENGTH))[0]; - offset += NUM_BYTES_STRING_LENGTH; - const bytes = new Uint8Array(buffer2.slice(offset, offset + byteLength)); - values.push(bytes); - offset += byteLength; + } else + throw new Error(`Unsupported dtype in weight '${a}': ${i}`); + o += u * m; + } else if (i === "string") { + let p = nt(s.shape); + c = []; + for (let m = 0; m < p; m++) { + let f = new Uint32Array(r.slice(o, o + rg))[0]; + o += rg; + let d = new Uint8Array(r.slice(o, o + f)); + c.push(d), o += f; } } else { - const dtypeFactor = DTYPE_VALUE_SIZE_MAP[dtype]; - const byteBuffer = buffer2.slice(offset, offset + size * dtypeFactor); - if (dtype === "float32") { - values = new Float32Array(byteBuffer); - } else if (dtype === "int32") { - values = new Int32Array(byteBuffer); - } else if (dtype === "bool") { - values = new Uint8Array(byteBuffer); - } else if (dtype === "complex64") { - values = new Float32Array(byteBuffer); - const real4 = new Float32Array(values.length / 2); - const image32 = new Float32Array(values.length / 2); - for (let i = 0; i < real4.length; i++) { - real4[i] = values[i * 2]; - image32[i] = values[i * 2 + 1]; - } - const realTensor = tensor(real4, shape, "float32"); - const imageTensor = tensor(image32, shape, "float32"); - out[name] = complex(realTensor, imageTensor); - realTensor.dispose(); - imageTensor.dispose(); - } else { - throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`); - } - offset += size * dtypeFactor; - } - if (dtype !== "complex64") { - out[name] = tensor(values, shape, dtype); + let p = Vm[i], m = r.slice(o, o + u * p); + if (i === "float32") + c = new Float32Array(m); + else if (i === "int32") + c = new Int32Array(m); + else if (i === "bool") + c = new Uint8Array(m); + else if (i === "complex64") { + c = new Float32Array(m); + let f = new Float32Array(c.length / 2), d = new Float32Array(c.length / 2); + for (let y = 0; y < f.length; y++) + f[y] = c[y * 2], d[y] = c[y * 2 + 1]; + let h = vr(f, l, "float32"), g = vr(d, l, "float32"); + t[a] = $n(h, g), h.dispose(), g.dispose(); + } else + throw new Error(`Unsupported dtype in weight '${a}': ${i}`); + o += u * p; } + i !== "complex64" && (t[a] = vr(c, l, i)); } - return out; + return t; } -function concatenateTypedArrays(xs) { - if (xs === null) { - throw new Error(`Invalid input value: ${JSON.stringify(xs)}`); - } - let totalByteLength = 0; - const normalizedXs = []; - xs.forEach((x) => { - totalByteLength += x.byteLength; - normalizedXs.push(x.byteLength === x.buffer.byteLength ? x : new x.constructor(x)); - if (!(x instanceof Float32Array || x instanceof Int32Array || x instanceof Uint8Array)) { - throw new Error(`Unsupported TypedArray subtype: ${x.constructor.name}`); - } +function Hj(r) { + if (r === null) + throw new Error(`Invalid input value: ${JSON.stringify(r)}`); + let e = 0, t = []; + r.forEach((s) => { + if (e += s.byteLength, t.push(s.byteLength === s.buffer.byteLength ? s : new s.constructor(s)), !(s instanceof Float32Array || s instanceof Int32Array || s instanceof Uint8Array)) + throw new Error(`Unsupported TypedArray subtype: ${s.constructor.name}`); }); - const y = new Uint8Array(totalByteLength); - let offset = 0; - normalizedXs.forEach((x) => { - y.set(new Uint8Array(x.buffer), offset); - offset += x.byteLength; + let n = new Uint8Array(e), o = 0; + return t.forEach((s) => { + n.set(new Uint8Array(s.buffer), o), o += s.byteLength; + }), n.buffer; +} +var Pw = typeof Buffer != "undefined" && (typeof Blob == "undefined" || typeof atob == "undefined" || typeof btoa == "undefined"); +function N1(r) { + return Pw ? Buffer.byteLength(r) : new Blob([r]).size; +} +function T1(r) { + if (Pw) + return Buffer.from(r).toString("base64"); + let e = new Uint8Array(r), t = ""; + for (let n = 0, o = e.length; n < o; n++) + t += String.fromCharCode(e[n]); + return btoa(t); +} +function E1(r) { + if (Pw) { + let n = Buffer.from(r, "base64"); + return n.buffer.slice(n.byteOffset, n.byteOffset + n.byteLength); + } + let e = atob(r), t = new Uint8Array(e.length); + for (let n = 0; n < e.length; ++n) + t.set([e.charCodeAt(n)], n); + return t.buffer; +} +function rp(r) { + if (r.length === 1) + return r[0]; + let e = 0; + r.forEach((o) => { + e += o.byteLength; }); - return y.buffer; + let t = new Uint8Array(e), n = 0; + return r.forEach((o) => { + t.set(new Uint8Array(o), n), n += o.byteLength; + }), t.buffer; } -var useNodeBuffer = typeof Buffer !== "undefined" && (typeof Blob === "undefined" || typeof atob === "undefined" || typeof btoa === "undefined"); -function stringByteLength(str) { - if (useNodeBuffer) { - return Buffer.byteLength(str); - } - return new Blob([str]).size; +function Mw(r) { + let e = "/"; + for (r = r.trim(); r.endsWith(e); ) + r = r.slice(0, r.length - 1); + let t = r.split(e); + return t[t.length - 1]; } -function arrayBufferToBase64String(buffer2) { - if (useNodeBuffer) { - return Buffer.from(buffer2).toString("base64"); - } - const buf = new Uint8Array(buffer2); - let s = ""; - for (let i = 0, l = buf.length; i < l; i++) { - s += String.fromCharCode(buf[i]); - } - return btoa(s); +function og(r, e) { + let t = { modelTopology: r.modelTopology, format: r.format, generatedBy: r.generatedBy, convertedBy: r.convertedBy, weightsManifest: e }; + return r.signature != null && (t.signature = r.signature), r.userDefinedMetadata != null && (t.userDefinedMetadata = r.userDefinedMetadata), r.modelInitializer != null && (t.modelInitializer = r.modelInitializer), r.trainingConfig != null && (t.trainingConfig = r.trainingConfig), t; } -function base64StringToArrayBuffer(str) { - if (useNodeBuffer) { - const buf = Buffer.from(str, "base64"); - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); +async function np(r, e) { + let t = { modelTopology: r.modelTopology, format: r.format, generatedBy: r.generatedBy, convertedBy: r.convertedBy }; + if (r.trainingConfig != null && (t.trainingConfig = r.trainingConfig), r.weightsManifest != null) { + let [n, o] = await e(r.weightsManifest); + t.weightSpecs = n, t.weightData = o; } - const s = atob(str); - const buffer2 = new Uint8Array(s.length); - for (let i = 0; i < s.length; ++i) { - buffer2.set([s.charCodeAt(i)], i); - } - return buffer2.buffer; + return r.signature != null && (t.signature = r.signature), r.userDefinedMetadata != null && (t.userDefinedMetadata = r.userDefinedMetadata), r.modelInitializer != null && (t.modelInitializer = r.modelInitializer), t; } -function concatenateArrayBuffers(buffers) { - if (buffers.length === 1) { - return buffers[0]; - } - let totalByteLength = 0; - buffers.forEach((buffer2) => { - totalByteLength += buffer2.byteLength; - }); - const temp = new Uint8Array(totalByteLength); - let offset = 0; - buffers.forEach((buffer2) => { - temp.set(new Uint8Array(buffer2), offset); - offset += buffer2.byteLength; - }); - return temp.buffer; -} -function basename(path) { - const SEPARATOR = "/"; - path = path.trim(); - while (path.endsWith(SEPARATOR)) { - path = path.slice(0, path.length - 1); - } - const items = path.split(SEPARATOR); - return items[items.length - 1]; -} -function getModelJSONForModelArtifacts(artifacts, manifest) { - const result = { - modelTopology: artifacts.modelTopology, - format: artifacts.format, - generatedBy: artifacts.generatedBy, - convertedBy: artifacts.convertedBy, - weightsManifest: manifest - }; - if (artifacts.signature != null) { - result.signature = artifacts.signature; - } - if (artifacts.userDefinedMetadata != null) { - result.userDefinedMetadata = artifacts.userDefinedMetadata; - } - if (artifacts.modelInitializer != null) { - result.modelInitializer = artifacts.modelInitializer; - } - if (artifacts.trainingConfig != null) { - result.trainingConfig = artifacts.trainingConfig; - } - return result; -} -async function getModelArtifactsForJSON(modelJSON, loadWeights2) { - const modelArtifacts = { - modelTopology: modelJSON.modelTopology, - format: modelJSON.format, - generatedBy: modelJSON.generatedBy, - convertedBy: modelJSON.convertedBy - }; - if (modelJSON.trainingConfig != null) { - modelArtifacts.trainingConfig = modelJSON.trainingConfig; - } - if (modelJSON.weightsManifest != null) { - const [weightSpecs, weightData] = await loadWeights2(modelJSON.weightsManifest); - modelArtifacts.weightSpecs = weightSpecs; - modelArtifacts.weightData = weightData; - } - if (modelJSON.signature != null) { - modelArtifacts.signature = modelJSON.signature; - } - if (modelJSON.userDefinedMetadata != null) { - modelArtifacts.userDefinedMetadata = modelJSON.userDefinedMetadata; - } - if (modelJSON.modelInitializer != null) { - modelArtifacts.modelInitializer = modelJSON.modelInitializer; - } - return modelArtifacts; -} -function getModelArtifactsInfoForJSON(modelArtifacts) { - if (modelArtifacts.modelTopology instanceof ArrayBuffer) { +function ii(r) { + if (r.modelTopology instanceof ArrayBuffer) throw new Error("Expected JSON model topology, received ArrayBuffer."); - } - return { - dateSaved: new Date(), - modelTopologyType: "JSON", - modelTopologyBytes: modelArtifacts.modelTopology == null ? 0 : stringByteLength(JSON.stringify(modelArtifacts.modelTopology)), - weightSpecsBytes: modelArtifacts.weightSpecs == null ? 0 : stringByteLength(JSON.stringify(modelArtifacts.weightSpecs)), - weightDataBytes: modelArtifacts.weightData == null ? 0 : modelArtifacts.weightData.byteLength - }; + return { dateSaved: new Date(), modelTopologyType: "JSON", modelTopologyBytes: r.modelTopology == null ? 0 : N1(JSON.stringify(r.modelTopology)), weightSpecsBytes: r.weightSpecs == null ? 0 : N1(JSON.stringify(r.weightSpecs)), weightDataBytes: r.weightData == null ? 0 : r.weightData.byteLength }; } -function computeFloat16MantisaTable() { - const convertMantissa = (i) => { - let m = i << 13; - let e = 0; - while ((m & 8388608) === 0) { - e -= 8388608; - m <<= 1; +function qj() { + let r = (t) => { + let n = t << 13, o = 0; + for (; (n & 8388608) == 0; ) + o -= 8388608, n <<= 1; + return n &= ~8388608, o += 947912704, n | o; + }, e = new Uint32Array(2048); + e[0] = 0; + for (let t = 1; t < 1024; t++) + e[t] = r(t); + for (let t = 1024; t < 2048; t++) + e[t] = 939524096 + (t - 1024 << 13); + return e; +} +function Kj() { + let r = new Uint32Array(64); + r[0] = 0, r[31] = 1199570944, r[32] = 2147483648, r[63] = 3347054592; + for (let e = 1; e < 31; e++) + r[e] = e << 23; + for (let e = 33; e < 63; e++) + r[e] = 2147483648 + (e - 32 << 23); + return r; +} +function Xj() { + let r = new Uint32Array(64); + for (let e = 0; e < 64; e++) + r[e] = 1024; + return r[0] = r[32] = 0, r; +} +function Yj() { + let r = qj(), e = Kj(), t = Xj(); + return (n) => { + let o = new ArrayBuffer(4 * n.length), s = new Uint32Array(o); + for (let a = 0; a < n.length; a++) { + let i = n[a], l = r[t[i >> 10] + (i & 1023)] + e[i >> 10]; + s[a] = l; } - m &= ~8388608; - e += 947912704; - return m | e; - }; - const mantisaTable = new Uint32Array(2048); - mantisaTable[0] = 0; - for (let i = 1; i < 1024; i++) { - mantisaTable[i] = convertMantissa(i); - } - for (let i = 1024; i < 2048; i++) { - mantisaTable[i] = 939524096 + (i - 1024 << 13); - } - return mantisaTable; -} -function computeFloat16ExponentTable() { - const exponentTable = new Uint32Array(64); - exponentTable[0] = 0; - exponentTable[31] = 1199570944; - exponentTable[32] = 2147483648; - exponentTable[63] = 3347054592; - for (let i = 1; i < 31; i++) { - exponentTable[i] = i << 23; - } - for (let i = 33; i < 63; i++) { - exponentTable[i] = 2147483648 + (i - 32 << 23); - } - return exponentTable; -} -function computeFloat16OffsetTable() { - const offsetTable = new Uint32Array(64); - for (let i = 0; i < 64; i++) { - offsetTable[i] = 1024; - } - offsetTable[0] = offsetTable[32] = 0; - return offsetTable; -} -function getFloat16Decoder() { - const mantisaTable = computeFloat16MantisaTable(); - const exponentTable = computeFloat16ExponentTable(); - const offsetTable = computeFloat16OffsetTable(); - return (quantizedArray) => { - const buffer2 = new ArrayBuffer(4 * quantizedArray.length); - const bufferUint32View = new Uint32Array(buffer2); - for (let index = 0; index < quantizedArray.length; index++) { - const float16Bits = quantizedArray[index]; - const float32Bits = mantisaTable[offsetTable[float16Bits >> 10] + (float16Bits & 1023)] + exponentTable[float16Bits >> 10]; - bufferUint32View[index] = float32Bits; - } - return new Float32Array(buffer2); + return new Float32Array(o); }; } -var IORouterRegistry = class { +var vt = class { constructor() { - this.saveRouters = []; - this.loadRouters = []; + this.saveRouters = [], this.loadRouters = []; } static getInstance() { - if (IORouterRegistry.instance == null) { - IORouterRegistry.instance = new IORouterRegistry(); - } - return IORouterRegistry.instance; + return vt.instance == null && (vt.instance = new vt()), vt.instance; } - static registerSaveRouter(saveRouter) { - IORouterRegistry.getInstance().saveRouters.push(saveRouter); + static registerSaveRouter(e) { + vt.getInstance().saveRouters.push(e); } - static registerLoadRouter(loadRouter) { - IORouterRegistry.getInstance().loadRouters.push(loadRouter); + static registerLoadRouter(e) { + vt.getInstance().loadRouters.push(e); } - static getSaveHandlers(url) { - return IORouterRegistry.getHandlers(url, "save"); + static getSaveHandlers(e) { + return vt.getHandlers(e, "save"); } - static getLoadHandlers(url, loadOptions) { - return IORouterRegistry.getHandlers(url, "load", loadOptions); + static getLoadHandlers(e, t) { + return vt.getHandlers(e, "load", t); } - static getHandlers(url, handlerType, loadOptions) { - const validHandlers = []; - const routers = handlerType === "load" ? IORouterRegistry.getInstance().loadRouters : IORouterRegistry.getInstance().saveRouters; - routers.forEach((router) => { - const handler = router(url, loadOptions); - if (handler !== null) { - validHandlers.push(handler); - } - }); - return validHandlers; + static getHandlers(e, t, n) { + let o = []; + return (t === "load" ? vt.getInstance().loadRouters : vt.getInstance().saveRouters).forEach((a) => { + let i = a(e, n); + i !== null && o.push(i); + }), o; } }; -var registerSaveRouter = (loudRouter) => IORouterRegistry.registerSaveRouter(loudRouter); -var registerLoadRouter = (loudRouter) => IORouterRegistry.registerLoadRouter(loudRouter); -var getSaveHandlers = (url) => IORouterRegistry.getSaveHandlers(url); -var getLoadHandlers = (url, loadOptions) => IORouterRegistry.getLoadHandlers(url, loadOptions); -var DATABASE_NAME = "tensorflowjs"; -var DATABASE_VERSION = 1; -var MODEL_STORE_NAME = "models_store"; -var INFO_STORE_NAME = "model_info_store"; -function getIndexedDBFactory() { - if (!env().getBool("IS_BROWSER")) { +var A1 = (r) => vt.registerSaveRouter(r); +var $1 = (r) => vt.registerLoadRouter(r); +var D1 = (r) => vt.getSaveHandlers(r); +var R1 = (r, e) => vt.getLoadHandlers(r, e); +var Lw = "tensorflowjs"; +var zw = 1; +var eu = "models_store"; +var cl = "model_info_store"; +function F1() { + if (!j().getBool("IS_BROWSER")) throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser."); - } - const theWindow = typeof window === "undefined" ? self : window; - const factory = theWindow.indexedDB || theWindow.mozIndexedDB || theWindow.webkitIndexedDB || theWindow.msIndexedDB || theWindow.shimIndexedDB; - if (factory == null) { + let r = typeof window == "undefined" ? self : window, e = r.indexedDB || r.mozIndexedDB || r.webkitIndexedDB || r.msIndexedDB || r.shimIndexedDB; + if (e == null) throw new Error("The current browser does not appear to support IndexedDB."); - } - return factory; + return e; } -function setUpDatabase(openRequest) { - const db = openRequest.result; - db.createObjectStore(MODEL_STORE_NAME, { keyPath: "modelPath" }); - db.createObjectStore(INFO_STORE_NAME, { keyPath: "modelPath" }); +function Bw(r) { + let e = r.result; + e.createObjectStore(eu, { keyPath: "modelPath" }), e.createObjectStore(cl, { keyPath: "modelPath" }); } -var BrowserIndexedDB = class { - constructor(modelPath) { - this.indexedDB = getIndexedDBFactory(); - if (modelPath == null || !modelPath) { +var da = class { + constructor(e) { + if (this.indexedDB = F1(), e == null || !e) throw new Error("For IndexedDB, modelPath must not be null, undefined or empty."); - } - this.modelPath = modelPath; + this.modelPath = e; } - async save(modelArtifacts) { - if (modelArtifacts.modelTopology instanceof ArrayBuffer) { + async save(e) { + if (e.modelTopology instanceof ArrayBuffer) throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet."); - } - return this.databaseAction(this.modelPath, modelArtifacts); + return this.databaseAction(this.modelPath, e); } async load() { return this.databaseAction(this.modelPath); } - databaseAction(modelPath, modelArtifacts) { - return new Promise((resolve, reject) => { - const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION); - openRequest.onupgradeneeded = () => setUpDatabase(openRequest); - openRequest.onsuccess = () => { - const db = openRequest.result; - if (modelArtifacts == null) { - const modelTx = db.transaction(MODEL_STORE_NAME, "readonly"); - const modelStore = modelTx.objectStore(MODEL_STORE_NAME); - const getRequest = modelStore.get(this.modelPath); - getRequest.onsuccess = () => { - if (getRequest.result == null) { - db.close(); - return reject(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`)); - } else { - resolve(getRequest.result.modelArtifacts); - } - }; - getRequest.onerror = (error) => { - db.close(); - return reject(getRequest.error); - }; - modelTx.oncomplete = () => db.close(); + databaseAction(e, t) { + return new Promise((n, o) => { + let s = this.indexedDB.open(Lw, zw); + s.onupgradeneeded = () => Bw(s), s.onsuccess = () => { + let a = s.result; + if (t == null) { + let i = a.transaction(eu, "readonly"), u = i.objectStore(eu).get(this.modelPath); + u.onsuccess = () => { + if (u.result == null) + return a.close(), o(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`)); + n(u.result.modelArtifacts); + }, u.onerror = (c) => (a.close(), o(u.error)), i.oncomplete = () => a.close(); } else { - const modelArtifactsInfo = getModelArtifactsInfoForJSON(modelArtifacts); - const infoTx = db.transaction(INFO_STORE_NAME, "readwrite"); - let infoStore = infoTx.objectStore(INFO_STORE_NAME); - const putInfoRequest = infoStore.put({ modelPath: this.modelPath, modelArtifactsInfo }); - let modelTx; - putInfoRequest.onsuccess = () => { - modelTx = db.transaction(MODEL_STORE_NAME, "readwrite"); - const modelStore = modelTx.objectStore(MODEL_STORE_NAME); - const putModelRequest = modelStore.put({ - modelPath: this.modelPath, - modelArtifacts, - modelArtifactsInfo - }); - putModelRequest.onsuccess = () => resolve({ modelArtifactsInfo }); - putModelRequest.onerror = (error) => { - infoStore = infoTx.objectStore(INFO_STORE_NAME); - const deleteInfoRequest = infoStore.delete(this.modelPath); - deleteInfoRequest.onsuccess = () => { - db.close(); - return reject(putModelRequest.error); - }; - deleteInfoRequest.onerror = (error2) => { - db.close(); - return reject(putModelRequest.error); - }; + let i = ii(t), l = a.transaction(cl, "readwrite"), u = l.objectStore(cl), c = u.put({ modelPath: this.modelPath, modelArtifactsInfo: i }), p; + c.onsuccess = () => { + p = a.transaction(eu, "readwrite"); + let f = p.objectStore(eu).put({ modelPath: this.modelPath, modelArtifacts: t, modelArtifactsInfo: i }); + f.onsuccess = () => n({ modelArtifactsInfo: i }), f.onerror = (d) => { + u = l.objectStore(cl); + let h = u.delete(this.modelPath); + h.onsuccess = () => (a.close(), o(f.error)), h.onerror = (g) => (a.close(), o(f.error)); }; - }; - putInfoRequest.onerror = (error) => { - db.close(); - return reject(putInfoRequest.error); - }; - infoTx.oncomplete = () => { - if (modelTx == null) { - db.close(); - } else { - modelTx.oncomplete = () => db.close(); - } + }, c.onerror = (m) => (a.close(), o(c.error)), l.oncomplete = () => { + p == null ? a.close() : p.oncomplete = () => a.close(); }; } - }; - openRequest.onerror = (error) => reject(openRequest.error); + }, s.onerror = (a) => o(s.error); }); } }; -BrowserIndexedDB.URL_SCHEME = "indexeddb://"; -var indexedDBRouter = (url) => { - if (!env().getBool("IS_BROWSER")) { - return null; - } else { - if (!Array.isArray(url) && url.startsWith(BrowserIndexedDB.URL_SCHEME)) { - return browserIndexedDB(url.slice(BrowserIndexedDB.URL_SCHEME.length)); - } else { - return null; - } - } -}; -IORouterRegistry.registerSaveRouter(indexedDBRouter); -IORouterRegistry.registerLoadRouter(indexedDBRouter); -function browserIndexedDB(modelPath) { - return new BrowserIndexedDB(modelPath); +da.URL_SCHEME = "indexeddb://"; +var O1 = (r) => j().getBool("IS_BROWSER") && !Array.isArray(r) && r.startsWith(da.URL_SCHEME) ? Zj(r.slice(da.URL_SCHEME.length)) : null; +vt.registerSaveRouter(O1); +vt.registerLoadRouter(O1); +function Zj(r) { + return new da(r); } -function maybeStripScheme(key) { - return key.startsWith(BrowserIndexedDB.URL_SCHEME) ? key.slice(BrowserIndexedDB.URL_SCHEME.length) : key; +function Jj(r) { + return r.startsWith(da.URL_SCHEME) ? r.slice(da.URL_SCHEME.length) : r; } -var BrowserIndexedDBManager = class { +var Vw = class { constructor() { - this.indexedDB = getIndexedDBFactory(); + this.indexedDB = F1(); } async listModels() { - return new Promise((resolve, reject) => { - const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION); - openRequest.onupgradeneeded = () => setUpDatabase(openRequest); - openRequest.onsuccess = () => { - const db = openRequest.result; - const tx = db.transaction(INFO_STORE_NAME, "readonly"); - const store = tx.objectStore(INFO_STORE_NAME); - const getAllInfoRequest = store.getAll(); - getAllInfoRequest.onsuccess = () => { - const out = {}; - for (const item of getAllInfoRequest.result) { - out[item.modelPath] = item.modelArtifactsInfo; - } - resolve(out); - }; - getAllInfoRequest.onerror = (error) => { - db.close(); - return reject(getAllInfoRequest.error); - }; - tx.oncomplete = () => db.close(); - }; - openRequest.onerror = (error) => reject(openRequest.error); + return new Promise((e, t) => { + let n = this.indexedDB.open(Lw, zw); + n.onupgradeneeded = () => Bw(n), n.onsuccess = () => { + let o = n.result, s = o.transaction(cl, "readonly"), i = s.objectStore(cl).getAll(); + i.onsuccess = () => { + let l = {}; + for (let u of i.result) + l[u.modelPath] = u.modelArtifactsInfo; + e(l); + }, i.onerror = (l) => (o.close(), t(i.error)), s.oncomplete = () => o.close(); + }, n.onerror = (o) => t(n.error); }); } - async removeModel(path) { - path = maybeStripScheme(path); - return new Promise((resolve, reject) => { - const openRequest = this.indexedDB.open(DATABASE_NAME, DATABASE_VERSION); - openRequest.onupgradeneeded = () => setUpDatabase(openRequest); - openRequest.onsuccess = () => { - const db = openRequest.result; - const infoTx = db.transaction(INFO_STORE_NAME, "readwrite"); - const infoStore = infoTx.objectStore(INFO_STORE_NAME); - const getInfoRequest = infoStore.get(path); - let modelTx; - getInfoRequest.onsuccess = () => { - if (getInfoRequest.result == null) { - db.close(); - return reject(new Error(`Cannot find model with path '${path}' in IndexedDB.`)); - } else { - const deleteInfoRequest = infoStore.delete(path); - const deleteModelData = () => { - modelTx = db.transaction(MODEL_STORE_NAME, "readwrite"); - const modelStore = modelTx.objectStore(MODEL_STORE_NAME); - const deleteModelRequest = modelStore.delete(path); - deleteModelRequest.onsuccess = () => resolve(getInfoRequest.result.modelArtifactsInfo); - deleteModelRequest.onerror = (error) => reject(getInfoRequest.error); - }; - deleteInfoRequest.onsuccess = deleteModelData; - deleteInfoRequest.onerror = (error) => { - deleteModelData(); - db.close(); - return reject(getInfoRequest.error); + async removeModel(e) { + return e = Jj(e), new Promise((t, n) => { + let o = this.indexedDB.open(Lw, zw); + o.onupgradeneeded = () => Bw(o), o.onsuccess = () => { + let s = o.result, a = s.transaction(cl, "readwrite"), i = a.objectStore(cl), l = i.get(e), u; + l.onsuccess = () => { + if (l.result == null) + return s.close(), n(new Error(`Cannot find model with path '${e}' in IndexedDB.`)); + { + let c = i.delete(e), p = () => { + u = s.transaction(eu, "readwrite"); + let f = u.objectStore(eu).delete(e); + f.onsuccess = () => t(l.result.modelArtifactsInfo), f.onerror = (d) => n(l.error); }; + c.onsuccess = p, c.onerror = (m) => (p(), s.close(), n(l.error)); } + }, l.onerror = (c) => (s.close(), n(l.error)), a.oncomplete = () => { + u == null ? s.close() : u.oncomplete = () => s.close(); }; - getInfoRequest.onerror = (error) => { - db.close(); - return reject(getInfoRequest.error); - }; - infoTx.oncomplete = () => { - if (modelTx == null) { - db.close(); - } else { - modelTx.oncomplete = () => db.close(); - } - }; - }; - openRequest.onerror = (error) => reject(openRequest.error); + }, o.onerror = (s) => n(o.error); }); } }; -var PATH_SEPARATOR = "/"; -var PATH_PREFIX = "tensorflowjs_models"; -var INFO_SUFFIX = "info"; -var MODEL_TOPOLOGY_SUFFIX = "model_topology"; -var WEIGHT_SPECS_SUFFIX = "weight_specs"; -var WEIGHT_DATA_SUFFIX = "weight_data"; -var MODEL_METADATA_SUFFIX = "model_metadata"; -function getModelKeys(path) { - return { - info: [PATH_PREFIX, path, INFO_SUFFIX].join(PATH_SEPARATOR), - topology: [PATH_PREFIX, path, MODEL_TOPOLOGY_SUFFIX].join(PATH_SEPARATOR), - weightSpecs: [PATH_PREFIX, path, WEIGHT_SPECS_SUFFIX].join(PATH_SEPARATOR), - weightData: [PATH_PREFIX, path, WEIGHT_DATA_SUFFIX].join(PATH_SEPARATOR), - modelMetadata: [PATH_PREFIX, path, MODEL_METADATA_SUFFIX].join(PATH_SEPARATOR) - }; +var ha = "/"; +var op = "tensorflowjs_models"; +var P1 = "info"; +var Qj = "model_topology"; +var eG = "weight_specs"; +var tG = "weight_data"; +var rG = "model_metadata"; +function M1(r) { + return { info: [op, r, P1].join(ha), topology: [op, r, Qj].join(ha), weightSpecs: [op, r, eG].join(ha), weightData: [op, r, tG].join(ha), modelMetadata: [op, r, rG].join(ha) }; } -function removeItems(keys) { - for (const key of Object.values(keys)) { - window.localStorage.removeItem(key); - } +function L1(r) { + for (let e of Object.values(r)) + window.localStorage.removeItem(e); } -function getModelPathFromKey(key) { - const items = key.split(PATH_SEPARATOR); - if (items.length < 3) { - throw new Error(`Invalid key format: ${key}`); - } - return items.slice(1, items.length - 1).join(PATH_SEPARATOR); +function nG(r) { + let e = r.split(ha); + if (e.length < 3) + throw new Error(`Invalid key format: ${r}`); + return e.slice(1, e.length - 1).join(ha); } -function maybeStripScheme2(key) { - return key.startsWith(BrowserLocalStorage.URL_SCHEME) ? key.slice(BrowserLocalStorage.URL_SCHEME.length) : key; +function oG(r) { + return r.startsWith(ga.URL_SCHEME) ? r.slice(ga.URL_SCHEME.length) : r; } -var BrowserLocalStorage = class { - constructor(modelPath) { - if (!env().getBool("IS_BROWSER") || typeof window === "undefined" || typeof window.localStorage === "undefined") { +var ga = class { + constructor(e) { + if (!j().getBool("IS_BROWSER") || typeof window == "undefined" || typeof window.localStorage == "undefined") throw new Error("The current environment does not support local storage."); - } - this.LS = window.localStorage; - if (modelPath == null || !modelPath) { + if (this.LS = window.localStorage, e == null || !e) throw new Error("For local storage, modelPath must not be null, undefined or empty."); - } - this.modelPath = modelPath; - this.keys = getModelKeys(this.modelPath); + this.modelPath = e, this.keys = M1(this.modelPath); } - async save(modelArtifacts) { - if (modelArtifacts.modelTopology instanceof ArrayBuffer) { + async save(e) { + if (e.modelTopology instanceof ArrayBuffer) throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet."); - } else { - const topology = JSON.stringify(modelArtifacts.modelTopology); - const weightSpecs = JSON.stringify(modelArtifacts.weightSpecs); - const modelArtifactsInfo = getModelArtifactsInfoForJSON(modelArtifacts); + { + let t = JSON.stringify(e.modelTopology), n = JSON.stringify(e.weightSpecs), o = ii(e); try { - this.LS.setItem(this.keys.info, JSON.stringify(modelArtifactsInfo)); - this.LS.setItem(this.keys.topology, topology); - this.LS.setItem(this.keys.weightSpecs, weightSpecs); - this.LS.setItem(this.keys.weightData, arrayBufferToBase64String(modelArtifacts.weightData)); - const metadata = { - format: modelArtifacts.format, - generatedBy: modelArtifacts.generatedBy, - convertedBy: modelArtifacts.convertedBy, - signature: modelArtifacts.signature != null ? modelArtifacts.signature : void 0, - userDefinedMetadata: modelArtifacts.userDefinedMetadata != null ? modelArtifacts.userDefinedMetadata : void 0, - modelInitializer: modelArtifacts.modelInitializer != null ? modelArtifacts.modelInitializer : void 0, - trainingConfig: modelArtifacts.trainingConfig != null ? modelArtifacts.trainingConfig : void 0 - }; - this.LS.setItem(this.keys.modelMetadata, JSON.stringify(metadata)); - return { modelArtifactsInfo }; - } catch (err) { - removeItems(this.keys); - throw new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${modelArtifactsInfo.modelTopologyBytes}, weightSpecsBytes=${modelArtifactsInfo.weightSpecsBytes}, weightDataBytes=${modelArtifactsInfo.weightDataBytes}.`); + this.LS.setItem(this.keys.info, JSON.stringify(o)), this.LS.setItem(this.keys.topology, t), this.LS.setItem(this.keys.weightSpecs, n), this.LS.setItem(this.keys.weightData, T1(e.weightData)); + let s = { format: e.format, generatedBy: e.generatedBy, convertedBy: e.convertedBy, signature: e.signature != null ? e.signature : void 0, userDefinedMetadata: e.userDefinedMetadata != null ? e.userDefinedMetadata : void 0, modelInitializer: e.modelInitializer != null ? e.modelInitializer : void 0, trainingConfig: e.trainingConfig != null ? e.trainingConfig : void 0 }; + return this.LS.setItem(this.keys.modelMetadata, JSON.stringify(s)), { modelArtifactsInfo: o }; + } catch (s) { + throw L1(this.keys), new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${o.modelTopologyBytes}, weightSpecsBytes=${o.weightSpecsBytes}, weightDataBytes=${o.weightDataBytes}.`); } } } async load() { - const info2 = JSON.parse(this.LS.getItem(this.keys.info)); - if (info2 == null) { + let e = JSON.parse(this.LS.getItem(this.keys.info)); + if (e == null) throw new Error(`In local storage, there is no model with name '${this.modelPath}'`); - } - if (info2.modelTopologyType !== "JSON") { + if (e.modelTopologyType !== "JSON") throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet."); - } - const out = {}; - const topology = JSON.parse(this.LS.getItem(this.keys.topology)); - if (topology == null) { + let t = {}, n = JSON.parse(this.LS.getItem(this.keys.topology)); + if (n == null) throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`); - } - out.modelTopology = topology; - const weightSpecs = JSON.parse(this.LS.getItem(this.keys.weightSpecs)); - if (weightSpecs == null) { + t.modelTopology = n; + let o = JSON.parse(this.LS.getItem(this.keys.weightSpecs)); + if (o == null) throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`); + t.weightSpecs = o; + let s = this.LS.getItem(this.keys.modelMetadata); + if (s != null) { + let i = JSON.parse(s); + t.format = i.format, t.generatedBy = i.generatedBy, t.convertedBy = i.convertedBy, i.signature != null && (t.signature = i.signature), i.userDefinedMetadata != null && (t.userDefinedMetadata = i.userDefinedMetadata), i.modelInitializer != null && (t.modelInitializer = i.modelInitializer), i.trainingConfig != null && (t.trainingConfig = i.trainingConfig); } - out.weightSpecs = weightSpecs; - const metadataString = this.LS.getItem(this.keys.modelMetadata); - if (metadataString != null) { - const metadata = JSON.parse(metadataString); - out.format = metadata.format; - out.generatedBy = metadata.generatedBy; - out.convertedBy = metadata.convertedBy; - if (metadata.signature != null) { - out.signature = metadata.signature; - } - if (metadata.userDefinedMetadata != null) { - out.userDefinedMetadata = metadata.userDefinedMetadata; - } - if (metadata.modelInitializer != null) { - out.modelInitializer = metadata.modelInitializer; - } - if (metadata.trainingConfig != null) { - out.trainingConfig = metadata.trainingConfig; - } - } - const weightDataBase64 = this.LS.getItem(this.keys.weightData); - if (weightDataBase64 == null) { + let a = this.LS.getItem(this.keys.weightData); + if (a == null) throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`); - } - out.weightData = base64StringToArrayBuffer(weightDataBase64); - return out; + return t.weightData = E1(a), t; } }; -BrowserLocalStorage.URL_SCHEME = "localstorage://"; -var localStorageRouter = (url) => { - if (!env().getBool("IS_BROWSER")) { - return null; - } else { - if (!Array.isArray(url) && url.startsWith(BrowserLocalStorage.URL_SCHEME)) { - return browserLocalStorage(url.slice(BrowserLocalStorage.URL_SCHEME.length)); - } else { - return null; - } - } -}; -IORouterRegistry.registerSaveRouter(localStorageRouter); -IORouterRegistry.registerLoadRouter(localStorageRouter); -function browserLocalStorage(modelPath) { - return new BrowserLocalStorage(modelPath); +ga.URL_SCHEME = "localstorage://"; +var z1 = (r) => j().getBool("IS_BROWSER") && !Array.isArray(r) && r.startsWith(ga.URL_SCHEME) ? sG(r.slice(ga.URL_SCHEME.length)) : null; +vt.registerSaveRouter(z1); +vt.registerLoadRouter(z1); +function sG(r) { + return new ga(r); } -var BrowserLocalStorageManager = class { +var Ww = class { constructor() { - assert(env().getBool("IS_BROWSER"), () => "Current environment is not a web browser"); - assert(typeof window === "undefined" || typeof window.localStorage !== "undefined", () => "Current browser does not appear to support localStorage"); - this.LS = window.localStorage; + E(j().getBool("IS_BROWSER"), () => "Current environment is not a web browser"), E(typeof window == "undefined" || typeof window.localStorage != "undefined", () => "Current browser does not appear to support localStorage"), this.LS = window.localStorage; } async listModels() { - const out = {}; - const prefix = PATH_PREFIX + PATH_SEPARATOR; - const suffix = PATH_SEPARATOR + INFO_SUFFIX; - for (let i = 0; i < this.LS.length; ++i) { - const key = this.LS.key(i); - if (key.startsWith(prefix) && key.endsWith(suffix)) { - const modelPath = getModelPathFromKey(key); - out[modelPath] = JSON.parse(this.LS.getItem(key)); + let e = {}, t = op + ha, n = ha + P1; + for (let o = 0; o < this.LS.length; ++o) { + let s = this.LS.key(o); + if (s.startsWith(t) && s.endsWith(n)) { + let a = nG(s); + e[a] = JSON.parse(this.LS.getItem(s)); } } - return out; + return e; } - async removeModel(path) { - path = maybeStripScheme2(path); - const keys = getModelKeys(path); - if (this.LS.getItem(keys.info) == null) { - throw new Error(`Cannot find model at path '${path}'`); - } - const info2 = JSON.parse(this.LS.getItem(keys.info)); - removeItems(keys); - return info2; + async removeModel(e) { + e = oG(e); + let t = M1(e); + if (this.LS.getItem(t.info) == null) + throw new Error(`Cannot find model at path '${e}'`); + let n = JSON.parse(this.LS.getItem(t.info)); + return L1(t), n; } }; -var URL_SCHEME_SUFFIX = "://"; -var ModelStoreManagerRegistry = class { +var sp = "://"; +var Zr = class { constructor() { this.managers = {}; } static getInstance() { - if (ModelStoreManagerRegistry.instance == null) { - ModelStoreManagerRegistry.instance = new ModelStoreManagerRegistry(); - } - return ModelStoreManagerRegistry.instance; + return Zr.instance == null && (Zr.instance = new Zr()), Zr.instance; } - static registerManager(scheme, manager) { - assert(scheme != null, () => "scheme must not be undefined or null."); - if (scheme.endsWith(URL_SCHEME_SUFFIX)) { - scheme = scheme.slice(0, scheme.indexOf(URL_SCHEME_SUFFIX)); - } - assert(scheme.length > 0, () => "scheme must not be an empty string."); - const registry = ModelStoreManagerRegistry.getInstance(); - assert(registry.managers[scheme] == null, () => `A model store manager is already registered for scheme '${scheme}'.`); - registry.managers[scheme] = manager; + static registerManager(e, t) { + E(e != null, () => "scheme must not be undefined or null."), e.endsWith(sp) && (e = e.slice(0, e.indexOf(sp))), E(e.length > 0, () => "scheme must not be an empty string."); + let n = Zr.getInstance(); + E(n.managers[e] == null, () => `A model store manager is already registered for scheme '${e}'.`), n.managers[e] = t; } - static getManager(scheme) { - const manager = this.getInstance().managers[scheme]; - if (manager == null) { - throw new Error(`Cannot find model manager for scheme '${scheme}'`); - } - return manager; + static getManager(e) { + let t = this.getInstance().managers[e]; + if (t == null) + throw new Error(`Cannot find model manager for scheme '${e}'`); + return t; } static getSchemes() { return Object.keys(this.getInstance().managers); } }; -function parseURL(url) { - if (url.indexOf(URL_SCHEME_SUFFIX) === -1) { - throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${ModelStoreManagerRegistry.getSchemes().join(",")}`); - } - return { - scheme: url.split(URL_SCHEME_SUFFIX)[0], - path: url.split(URL_SCHEME_SUFFIX)[1] - }; +function sg(r) { + if (r.indexOf(sp) === -1) + throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Zr.getSchemes().join(",")}`); + return { scheme: r.split(sp)[0], path: r.split(sp)[1] }; } -async function cloneModelInternal(sourceURL, destURL, deleteSource = false) { - assert(sourceURL !== destURL, () => `Old path and new path are the same: '${sourceURL}'`); - const loadHandlers = IORouterRegistry.getLoadHandlers(sourceURL); - assert(loadHandlers.length > 0, () => `Copying failed because no load handler is found for source URL ${sourceURL}.`); - assert(loadHandlers.length < 2, () => `Copying failed because more than one (${loadHandlers.length}) load handlers for source URL ${sourceURL}.`); - const loadHandler = loadHandlers[0]; - const saveHandlers = IORouterRegistry.getSaveHandlers(destURL); - assert(saveHandlers.length > 0, () => `Copying failed because no save handler is found for destination URL ${destURL}.`); - assert(saveHandlers.length < 2, () => `Copying failed because more than one (${loadHandlers.length}) save handlers for destination URL ${destURL}.`); - const saveHandler = saveHandlers[0]; - const sourceScheme = parseURL(sourceURL).scheme; - const sourcePath = parseURL(sourceURL).path; - const sameMedium = sourceScheme === parseURL(sourceURL).scheme; - const modelArtifacts = await loadHandler.load(); - if (deleteSource && sameMedium) { - await ModelStoreManagerRegistry.getManager(sourceScheme).removeModel(sourcePath); - } - const saveResult = await saveHandler.save(modelArtifacts); - if (deleteSource && !sameMedium) { - await ModelStoreManagerRegistry.getManager(sourceScheme).removeModel(sourcePath); - } - return saveResult.modelArtifactsInfo; +async function B1(r, e, t = false) { + E(r !== e, () => `Old path and new path are the same: '${r}'`); + let n = vt.getLoadHandlers(r); + E(n.length > 0, () => `Copying failed because no load handler is found for source URL ${r}.`), E(n.length < 2, () => `Copying failed because more than one (${n.length}) load handlers for source URL ${r}.`); + let o = n[0], s = vt.getSaveHandlers(e); + E(s.length > 0, () => `Copying failed because no save handler is found for destination URL ${e}.`), E(s.length < 2, () => `Copying failed because more than one (${n.length}) save handlers for destination URL ${e}.`); + let a = s[0], i = sg(r).scheme, l = sg(r).path, u = i === sg(r).scheme, c = await o.load(); + t && u && await Zr.getManager(i).removeModel(l); + let p = await a.save(c); + return t && !u && await Zr.getManager(i).removeModel(l), p.modelArtifactsInfo; } -async function listModels() { - const schemes = ModelStoreManagerRegistry.getSchemes(); - const out = {}; - for (const scheme of schemes) { - const schemeOut = await ModelStoreManagerRegistry.getManager(scheme).listModels(); - for (const path in schemeOut) { - const url = scheme + URL_SCHEME_SUFFIX + path; - out[url] = schemeOut[path]; +async function V1() { + let r = Zr.getSchemes(), e = {}; + for (let t of r) { + let n = await Zr.getManager(t).listModels(); + for (let o in n) { + let s = t + sp + o; + e[s] = n[o]; } } - return out; + return e; } -async function removeModel(url) { - const schemeAndPath = parseURL(url); - const manager = ModelStoreManagerRegistry.getManager(schemeAndPath.scheme); - return manager.removeModel(schemeAndPath.path); +async function W1(r) { + let e = sg(r); + return Zr.getManager(e.scheme).removeModel(e.path); } -async function copyModel(sourceURL, destURL) { - const deleteSource = false; - return cloneModelInternal(sourceURL, destURL, deleteSource); +async function j1(r, e) { + return B1(r, e, false); } -async function moveModel(sourceURL, destURL) { - const deleteSource = true; - return cloneModelInternal(sourceURL, destURL, deleteSource); +async function G1(r, e) { + return B1(r, e, true); } -var PlatformBrowser = class { - fetch(path, init2) { - return fetch(path, init2); +var U1 = class { + fetch(e, t) { + return fetch(e, t); } now() { return performance.now(); } - encode(text, encoding) { - if (encoding !== "utf-8" && encoding !== "utf8") { - throw new Error(`Browser's encoder only supports utf-8, but got ${encoding}`); - } - if (this.textEncoder == null) { - this.textEncoder = new TextEncoder(); - } - return this.textEncoder.encode(text); + encode(e, t) { + if (t !== "utf-8" && t !== "utf8") + throw new Error(`Browser's encoder only supports utf-8, but got ${t}`); + return this.textEncoder == null && (this.textEncoder = new TextEncoder()), this.textEncoder.encode(e); } - decode(bytes, encoding) { - return new TextDecoder(encoding).decode(bytes); + decode(e, t) { + return new TextDecoder(t).decode(e); } }; -if (env().get("IS_BROWSER")) { - env().setPlatform("browser", new PlatformBrowser()); +if (j().get("IS_BROWSER")) { + j().setPlatform("browser", new U1()); try { - ModelStoreManagerRegistry.registerManager(BrowserLocalStorage.URL_SCHEME, new BrowserLocalStorageManager()); - } catch (err) { + Zr.registerManager(ga.URL_SCHEME, new Ww()); + } catch (r) { } try { - ModelStoreManagerRegistry.registerManager(BrowserIndexedDB.URL_SCHEME, new BrowserIndexedDBManager()); - } catch (err) { + Zr.registerManager(da.URL_SCHEME, new Vw()); + } catch (r) { } } -var getNodeFetch = { - importFetch: () => require_browser() -}; -var systemFetch; -var PlatformNode = class { +var iG = { importFetch: () => H1() }; +var jw; +var q1 = class { constructor() { - this.util = __require2("util"); - this.textEncoder = new this.util.TextEncoder(); + this.util = pc("util"), this.textEncoder = new this.util.TextEncoder(); } - fetch(path, requestInits) { - if (env().global.fetch != null) { - return env().global.fetch(path, requestInits); - } - if (systemFetch == null) { - systemFetch = getNodeFetch.importFetch(); - } - return systemFetch(path, requestInits); + fetch(e, t) { + return j().global.fetch != null ? j().global.fetch(e, t) : (jw == null && (jw = iG.importFetch()), jw(e, t)); } now() { - const time2 = process.hrtime(); - return time2[0] * 1e3 + time2[1] / 1e6; + let e = process.hrtime(); + return e[0] * 1e3 + e[1] / 1e6; } - encode(text, encoding) { - if (encoding !== "utf-8" && encoding !== "utf8") { - throw new Error(`Node built-in encoder only supports utf-8, but got ${encoding}`); - } - return this.textEncoder.encode(text); + encode(e, t) { + if (t !== "utf-8" && t !== "utf8") + throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`); + return this.textEncoder.encode(e); } - decode(bytes, encoding) { - if (bytes.length === 0) { - return ""; - } - return new this.util.TextDecoder(encoding).decode(bytes); + decode(e, t) { + return e.length === 0 ? "" : new this.util.TextDecoder(t).decode(e); } }; -if (env().get("IS_NODE")) { - env().setPlatform("node", new PlatformNode()); +j().get("IS_NODE") && j().setPlatform("node", new q1()); +function Se(r, e = "float32", t) { + return e = e || "float32", Tm(r), new ct(r, e, t); } -function buffer(shape, dtype = "float32", values) { - dtype = dtype || "float32"; - assertNonNegativeIntegerDimensions(shape); - return new TensorBuffer(shape, dtype, values); -} -function cast_(x, dtype) { - const $x = convertToTensor(x, "x", "cast"); - if (!isValidDtype(dtype)) { - throw new Error(`Failed to cast to unknown dtype ${dtype}`); - } - if (dtype === "string" && $x.dtype !== "string" || dtype !== "string" && $x.dtype === "string") { +function aG(r, e) { + let t = _(r, "x", "cast"); + if (!dw(e)) + throw new Error(`Failed to cast to unknown dtype ${e}`); + if (e === "string" && t.dtype !== "string" || e !== "string" && t.dtype === "string") throw new Error("Only strings can be casted to strings"); - } - const inputs = { x: $x }; - const attrs = { dtype }; - return ENGINE.runKernel(Cast, inputs, attrs); + let n = { x: t }, o = { dtype: e }; + return T.runKernel(Qn, n, o); } -var cast = op({ cast_ }); -function clone_(x) { - const $x = convertToTensor(x, "x", "clone", "string_or_numeric"); - const inputs = { x: $x }; - return ENGINE.runKernel(Identity, inputs); +var J = I({ cast_: aG }); +function lG(r) { + let t = { x: _(r, "x", "clone", "string_or_numeric") }; + return T.runKernel(to, t); } -var clone = op({ clone_ }); -function print2(x, verbose = false) { - console.log(x.toString(verbose)); +var hn = I({ clone_: lG }); +function Gw(r, e = false) { + console.log(r.toString(e)); } -getOrMakeEngine(); -var opHandler2 = { - buffer, - cast, - clone, - print: print2 -}; -setOpHandler(opHandler2); -var io_exports = {}; -__export2(io_exports, { - browserFiles: () => browserFiles, - browserHTTPRequest: () => browserHTTPRequest, - concatenateArrayBuffers: () => concatenateArrayBuffers, - copyModel: () => copyModel, - decodeWeights: () => decodeWeights, - encodeWeights: () => encodeWeights, - fromMemory: () => fromMemory, - getLoadHandlers: () => getLoadHandlers, - getModelArtifactsForJSON: () => getModelArtifactsForJSON, - getModelArtifactsInfoForJSON: () => getModelArtifactsInfoForJSON, - getSaveHandlers: () => getSaveHandlers, - http: () => http, - isHTTPScheme: () => isHTTPScheme, - listModels: () => listModels, - loadWeights: () => loadWeights, - moveModel: () => moveModel, - registerLoadRouter: () => registerLoadRouter, - registerSaveRouter: () => registerSaveRouter, - removeModel: () => removeModel, - weightsLoaderFactory: () => weightsLoaderFactory, - withSaveHandler: () => withSaveHandler -}); -var DEFAULT_FILE_NAME_PREFIX = "model"; -var DEFAULT_JSON_EXTENSION_NAME = ".json"; -var DEFAULT_WEIGHT_DATA_EXTENSION_NAME = ".weights.bin"; -function defer(f) { - return new Promise((resolve) => setTimeout(resolve)).then(f); +Fw(); +var uG = { buffer: Se, cast: J, clone: hn, print: Gw }; +w1(uG); +var $r = {}; +He($r, { browserFiles: () => Y1, browserHTTPRequest: () => Q1, concatenateArrayBuffers: () => rp, copyModel: () => j1, decodeWeights: () => ng, encodeWeights: () => I1, fromMemory: () => tN, getLoadHandlers: () => R1, getModelArtifactsForJSON: () => np, getModelArtifactsInfoForJSON: () => ii, getSaveHandlers: () => D1, http: () => lg, isHTTPScheme: () => ag, listModels: () => V1, loadWeights: () => Z1, moveModel: () => G1, registerLoadRouter: () => $1, registerSaveRouter: () => A1, removeModel: () => W1, weightsLoaderFactory: () => qw, withSaveHandler: () => rN }); +var cG = "model"; +var pG = ".json"; +var mG = ".weights.bin"; +function K1(r) { + return new Promise((e) => setTimeout(e)).then(r); } -var BrowserDownloads = class { - constructor(fileNamePrefix) { - if (!env().getBool("IS_BROWSER")) { +var pl = class { + constructor(e) { + if (!j().getBool("IS_BROWSER")) throw new Error("browserDownloads() cannot proceed because the current environment is not a browser."); - } - if (fileNamePrefix.startsWith(BrowserDownloads.URL_SCHEME)) { - fileNamePrefix = fileNamePrefix.slice(BrowserDownloads.URL_SCHEME.length); - } - if (fileNamePrefix == null || fileNamePrefix.length === 0) { - fileNamePrefix = DEFAULT_FILE_NAME_PREFIX; - } - this.modelJsonFileName = fileNamePrefix + DEFAULT_JSON_EXTENSION_NAME; - this.weightDataFileName = fileNamePrefix + DEFAULT_WEIGHT_DATA_EXTENSION_NAME; + e.startsWith(pl.URL_SCHEME) && (e = e.slice(pl.URL_SCHEME.length)), (e == null || e.length === 0) && (e = cG), this.modelJsonFileName = e + pG, this.weightDataFileName = e + mG; } - async save(modelArtifacts) { - if (typeof document === "undefined") { + async save(e) { + if (typeof document == "undefined") throw new Error("Browser downloads are not supported in this environment since `document` is not present"); - } - const weightsURL = window.URL.createObjectURL(new Blob([modelArtifacts.weightData], { type: "application/octet-stream" })); - if (modelArtifacts.modelTopology instanceof ArrayBuffer) { + let t = window.URL.createObjectURL(new Blob([e.weightData], { type: "application/octet-stream" })); + if (e.modelTopology instanceof ArrayBuffer) throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet."); - } else { - const weightsManifest = [{ - paths: ["./" + this.weightDataFileName], - weights: modelArtifacts.weightSpecs - }]; - const modelJSON = getModelJSONForModelArtifacts(modelArtifacts, weightsManifest); - const modelJsonURL = window.URL.createObjectURL(new Blob([JSON.stringify(modelJSON)], { type: "application/json" })); - const jsonAnchor = this.modelJsonAnchor == null ? document.createElement("a") : this.modelJsonAnchor; - jsonAnchor.download = this.modelJsonFileName; - jsonAnchor.href = modelJsonURL; - await defer(() => jsonAnchor.dispatchEvent(new MouseEvent("click"))); - if (modelArtifacts.weightData != null) { - const weightDataAnchor = this.weightDataAnchor == null ? document.createElement("a") : this.weightDataAnchor; - weightDataAnchor.download = this.weightDataFileName; - weightDataAnchor.href = weightsURL; - await defer(() => weightDataAnchor.dispatchEvent(new MouseEvent("click"))); + { + let n = [{ paths: ["./" + this.weightDataFileName], weights: e.weightSpecs }], o = og(e, n), s = window.URL.createObjectURL(new Blob([JSON.stringify(o)], { type: "application/json" })), a = this.modelJsonAnchor == null ? document.createElement("a") : this.modelJsonAnchor; + if (a.download = this.modelJsonFileName, a.href = s, await K1(() => a.dispatchEvent(new MouseEvent("click"))), e.weightData != null) { + let i = this.weightDataAnchor == null ? document.createElement("a") : this.weightDataAnchor; + i.download = this.weightDataFileName, i.href = t, await K1(() => i.dispatchEvent(new MouseEvent("click"))); } - return { modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts) }; + return { modelArtifactsInfo: ii(e) }; } } }; -BrowserDownloads.URL_SCHEME = "downloads://"; -var BrowserFiles = class { - constructor(files) { - if (files == null || files.length < 1) { - throw new Error(`When calling browserFiles, at least 1 file is required, but received ${files}`); - } - this.jsonFile = files[0]; - this.weightsFiles = files.slice(1); +pl.URL_SCHEME = "downloads://"; +var X1 = class { + constructor(e) { + if (e == null || e.length < 1) + throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`); + this.jsonFile = e[0], this.weightsFiles = e.slice(1); } async load() { - return new Promise((resolve, reject) => { - const jsonReader = new FileReader(); - jsonReader.onload = (event) => { - const modelJSON = JSON.parse(event.target.result); - const modelTopology = modelJSON.modelTopology; - if (modelTopology == null) { - reject(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`)); + return new Promise((e, t) => { + let n = new FileReader(); + n.onload = (o) => { + let s = JSON.parse(o.target.result), a = s.modelTopology; + if (a == null) { + t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`)); return; } - const weightsManifest = modelJSON.weightsManifest; - if (weightsManifest == null) { - reject(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`)); + if (s.weightsManifest == null) { + t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`)); return; } if (this.weightsFiles.length === 0) { - resolve({ modelTopology }); + e({ modelTopology: a }); return; } - const modelArtifactsPromise = getModelArtifactsForJSON(modelJSON, (weightsManifest2) => this.loadWeights(weightsManifest2)); - resolve(modelArtifactsPromise); - }; - jsonReader.onerror = (error) => reject(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`); - jsonReader.readAsText(this.jsonFile); + let l = np(s, (u) => this.loadWeights(u)); + e(l); + }, n.onerror = (o) => t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`), n.readAsText(this.jsonFile); }); } - loadWeights(weightsManifest) { - const weightSpecs = []; - const paths = []; - for (const entry of weightsManifest) { - weightSpecs.push(...entry.weights); - paths.push(...entry.paths); - } - const pathToFile = this.checkManifestAndWeightFiles(weightsManifest); - const promises = paths.map((path) => this.loadWeightsFile(path, pathToFile[path])); - return Promise.all(promises).then((buffers) => [weightSpecs, concatenateArrayBuffers(buffers)]); + loadWeights(e) { + let t = [], n = []; + for (let a of e) + t.push(...a.weights), n.push(...a.paths); + let o = this.checkManifestAndWeightFiles(e), s = n.map((a) => this.loadWeightsFile(a, o[a])); + return Promise.all(s).then((a) => [t, rp(a)]); } - loadWeightsFile(path, file) { - return new Promise((resolve, reject) => { - const weightFileReader = new FileReader(); - weightFileReader.onload = (event) => { - const weightData = event.target.result; - resolve(weightData); - }; - weightFileReader.onerror = (error) => reject(`Failed to weights data from file of path '${path}'.`); - weightFileReader.readAsArrayBuffer(file); + loadWeightsFile(e, t) { + return new Promise((n, o) => { + let s = new FileReader(); + s.onload = (a) => { + let i = a.target.result; + n(i); + }, s.onerror = (a) => o(`Failed to weights data from file of path '${e}'.`), s.readAsArrayBuffer(t); }); } - checkManifestAndWeightFiles(manifest) { - const basenames = []; - const fileNames = this.weightsFiles.map((file) => basename(file.name)); - const pathToFile = {}; - for (const group of manifest) { - group.paths.forEach((path) => { - const pathBasename = basename(path); - if (basenames.indexOf(pathBasename) !== -1) { - throw new Error(`Duplicate file basename found in weights manifest: '${pathBasename}'`); - } - basenames.push(pathBasename); - if (fileNames.indexOf(pathBasename) === -1) { - throw new Error(`Weight file with basename '${pathBasename}' is not provided.`); - } else { - pathToFile[path] = this.weightsFiles[fileNames.indexOf(pathBasename)]; - } + checkManifestAndWeightFiles(e) { + let t = [], n = this.weightsFiles.map((s) => Mw(s.name)), o = {}; + for (let s of e) + s.paths.forEach((a) => { + let i = Mw(a); + if (t.indexOf(i) !== -1) + throw new Error(`Duplicate file basename found in weights manifest: '${i}'`); + if (t.push(i), n.indexOf(i) === -1) + throw new Error(`Weight file with basename '${i}' is not provided.`); + o[a] = this.weightsFiles[n.indexOf(i)]; }); - } - if (basenames.length !== this.weightsFiles.length) { - throw new Error(`Mismatch in the number of files in weights manifest (${basenames.length}) and the number of weight files provided (${this.weightsFiles.length}).`); - } - return pathToFile; + if (t.length !== this.weightsFiles.length) + throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`); + return o; } }; -var browserDownloadsRouter = (url) => { - if (!env().getBool("IS_BROWSER")) { - return null; - } else { - if (!Array.isArray(url) && url.startsWith(BrowserDownloads.URL_SCHEME)) { - return browserDownloads(url.slice(BrowserDownloads.URL_SCHEME.length)); - } else { - return null; - } +var fG = (r) => j().getBool("IS_BROWSER") && !Array.isArray(r) && r.startsWith(pl.URL_SCHEME) ? dG(r.slice(pl.URL_SCHEME.length)) : null; +vt.registerSaveRouter(fG); +function dG(r = "model") { + return new pl(r); +} +function Y1(r) { + return new X1(r); +} +function Uw(r, e, t, n) { + a(r), t = t == null ? 0 : t, n = n == null ? 1 : n, i(t, n); + let o = 0, s = (l) => (l.then((u) => { + let c = t + ++o / r.length * (n - t); + return e(c), u; + }), l); + function a(l) { + E(l != null && Array.isArray(l) && l.length > 0, () => "promises must be a none empty array"); } -}; -IORouterRegistry.registerSaveRouter(browserDownloadsRouter); -function browserDownloads(fileNamePrefix = "model") { - return new BrowserDownloads(fileNamePrefix); -} -function browserFiles(files) { - return new BrowserFiles(files); -} -function monitorPromisesProgress(promises, onProgress, startFraction, endFraction) { - checkPromises(promises); - startFraction = startFraction == null ? 0 : startFraction; - endFraction = endFraction == null ? 1 : endFraction; - checkFraction(startFraction, endFraction); - let resolvedPromise = 0; - const registerMonitor = (promise) => { - promise.then((value) => { - const fraction = startFraction + ++resolvedPromise / promises.length * (endFraction - startFraction); - onProgress(fraction); - return value; - }); - return promise; - }; - function checkPromises(promises2) { - assert(promises2 != null && Array.isArray(promises2) && promises2.length > 0, () => "promises must be a none empty array"); + function i(l, u) { + E(l >= 0 && l <= 1, () => `Progress fraction must be in range [0, 1], but got startFraction ${l}`), E(u >= 0 && u <= 1, () => `Progress fraction must be in range [0, 1], but got endFraction ${u}`), E(u >= l, () => `startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`); } - function checkFraction(startFraction2, endFraction2) { - assert(startFraction2 >= 0 && startFraction2 <= 1, () => `Progress fraction must be in range [0, 1], but got startFraction ${startFraction2}`); - assert(endFraction2 >= 0 && endFraction2 <= 1, () => `Progress fraction must be in range [0, 1], but got endFraction ${endFraction2}`); - assert(endFraction2 >= startFraction2, () => `startFraction must be no more than endFraction, but got startFraction ${startFraction2} and endFraction ${endFraction2}`); - } - return Promise.all(promises.map(registerMonitor)); + return Promise.all(r.map(s)); } -async function loadWeightsAsArrayBuffer(fetchURLs, loadOptions) { - if (loadOptions == null) { - loadOptions = {}; - } - const fetchFunc = loadOptions.fetchFunc == null ? env().platform.fetch : loadOptions.fetchFunc; - const requests = fetchURLs.map((fetchURL) => fetchFunc(fetchURL, loadOptions.requestInit, { isBinary: true })); - const fetchStartFraction = 0; - const fetchEndFraction = 0.5; - const responses = loadOptions.onProgress == null ? await Promise.all(requests) : await monitorPromisesProgress(requests, loadOptions.onProgress, fetchStartFraction, fetchEndFraction); - const bufferPromises = responses.map((response) => response.arrayBuffer()); - const bufferStartFraction = 0.5; - const bufferEndFraction = 1; - const buffers = loadOptions.onProgress == null ? await Promise.all(bufferPromises) : await monitorPromisesProgress(bufferPromises, loadOptions.onProgress, bufferStartFraction, bufferEndFraction); - return buffers; +async function Hw(r, e) { + e == null && (e = {}); + let t = e.fetchFunc == null ? j().platform.fetch : e.fetchFunc, n = r.map((p) => t(p, e.requestInit, { isBinary: true })), o = 0, s = 0.5, i = (e.onProgress == null ? await Promise.all(n) : await Uw(n, e.onProgress, o, s)).map((p) => p.arrayBuffer()), l = 0.5, u = 1; + return e.onProgress == null ? await Promise.all(i) : await Uw(i, e.onProgress, l, u); } -async function loadWeights(manifest, filePathPrefix = "", weightNames, requestInit) { - const fetchWeights = (fetchUrls) => loadWeightsAsArrayBuffer(fetchUrls, { requestInit }); - const loadWeights2 = weightsLoaderFactory(fetchWeights); - return loadWeights2(manifest, filePathPrefix, weightNames); +async function Z1(r, e = "", t, n) { + return qw((a) => Hw(a, { requestInit: n }))(r, e, t); } -function weightsLoaderFactory(fetchWeightsFunction) { - return async (manifest, filePathPrefix = "", weightNames) => { - const groupIndicesToFetchMap = manifest.map(() => false); - const groupWeightsToFetch = {}; - const weightsFound = weightNames != null ? weightNames.map(() => false) : []; - const allManifestWeightNames = []; - manifest.forEach((manifestGroupConfig, groupIndex) => { - let groupOffset = 0; - manifestGroupConfig.weights.forEach((weightsEntry) => { - const rawDtype = "quantization" in weightsEntry ? weightsEntry.quantization.dtype : weightsEntry.dtype; - const weightsBytes = DTYPE_VALUE_SIZE_MAP[rawDtype] * sizeFromShape(weightsEntry.shape); - const enqueueWeightsForFetchingFn = () => { - groupIndicesToFetchMap[groupIndex] = true; - if (groupWeightsToFetch[groupIndex] == null) { - groupWeightsToFetch[groupIndex] = []; - } - groupWeightsToFetch[groupIndex].push({ - manifestEntry: weightsEntry, - groupOffset, - sizeBytes: weightsBytes - }); +function qw(r) { + return async (e, t = "", n) => { + let o = e.map(() => false), s = {}, a = n != null ? n.map(() => false) : [], i = []; + if (e.forEach((f, d) => { + let h = 0; + f.weights.forEach((g) => { + let y = "quantization" in g ? g.quantization.dtype : g.dtype, w = Vm[y] * nt(g.shape), x = () => { + o[d] = true, s[d] == null && (s[d] = []), s[d].push({ manifestEntry: g, groupOffset: h, sizeBytes: w }); }; - if (weightNames != null) { - weightNames.forEach((weightName, weightIndex) => { - if (weightName === weightsEntry.name) { - enqueueWeightsForFetchingFn(); - weightsFound[weightIndex] = true; - } - }); - } else { - enqueueWeightsForFetchingFn(); - } - allManifestWeightNames.push(weightsEntry.name); - groupOffset += weightsBytes; + n != null ? n.forEach((k, C) => { + k === g.name && (x(), a[C] = true); + }) : x(), i.push(g.name), h += w; }); - }); - if (!weightsFound.every((found) => found)) { - const weightsNotFound = weightNames.filter((_, i) => !weightsFound[i]); - throw new Error(`Could not find weights in manifest with names: ${weightsNotFound.join(", ")}. -Manifest JSON has weights with names: ${allManifestWeightNames.join(", ")}.`); + }), !a.every((f) => f)) { + let f = n.filter((d, h) => !a[h]); + throw new Error(`Could not find weights in manifest with names: ${f.join(", ")}. +Manifest JSON has weights with names: ${i.join(", ")}.`); } - const groupIndicesToFetch = groupIndicesToFetchMap.reduce((accumulator, shouldFetch, i) => { - if (shouldFetch) { - accumulator.push(i); - } - return accumulator; - }, []); - const fetchUrls = []; - groupIndicesToFetch.forEach((i) => { - manifest[i].paths.forEach((filepath) => { - const fetchUrl = filePathPrefix + (!filePathPrefix.endsWith("/") ? "/" : "") + filepath; - fetchUrls.push(fetchUrl); + let l = o.reduce((f, d, h) => (d && f.push(h), f), []), u = []; + l.forEach((f) => { + e[f].paths.forEach((d) => { + let h = t + (t.endsWith("/") ? "" : "/") + d; + u.push(h); }); }); - const buffers = await fetchWeightsFunction(fetchUrls); - const weightsTensorMap = {}; - let bufferIndexOffset = 0; - groupIndicesToFetch.forEach((i) => { - const numBuffers = manifest[i].paths.length; - let groupBytes = 0; - for (let i2 = 0; i2 < numBuffers; i2++) { - groupBytes += buffers[bufferIndexOffset + i2].byteLength; + let c = await r(u), p = {}, m = 0; + return l.forEach((f) => { + let d = e[f].paths.length, h = 0; + for (let k = 0; k < d; k++) + h += c[m + k].byteLength; + let g = new ArrayBuffer(h), y = new Uint8Array(g), w = 0; + for (let k = 0; k < d; k++) { + let C = new Uint8Array(c[m + k]); + y.set(C, w), w += C.byteLength; } - const groupBuffer = new ArrayBuffer(groupBytes); - const groupByteBuffer = new Uint8Array(groupBuffer); - let groupBufferOffset = 0; - for (let i2 = 0; i2 < numBuffers; i2++) { - const buffer2 = new Uint8Array(buffers[bufferIndexOffset + i2]); - groupByteBuffer.set(buffer2, groupBufferOffset); - groupBufferOffset += buffer2.byteLength; - } - const weightsEntries = groupWeightsToFetch[i]; - weightsEntries.forEach((weightsEntry) => { - const byteBuffer = groupBuffer.slice(weightsEntry.groupOffset, weightsEntry.groupOffset + weightsEntry.sizeBytes); - const nameToTensorMap = decodeWeights(byteBuffer, [weightsEntry.manifestEntry]); - for (const name in nameToTensorMap) { - weightsTensorMap[name] = nameToTensorMap[name]; - } - }); - bufferIndexOffset += numBuffers; - }); - return weightsTensorMap; + s[f].forEach((k) => { + let C = g.slice(k.groupOffset, k.groupOffset + k.sizeBytes), A = ng(C, [k.manifestEntry]); + for (let $ in A) + p[$] = A[$]; + }), m += d; + }), p; }; } -var OCTET_STREAM_MIME_TYPE = "application/octet-stream"; -var JSON_TYPE = "application/json"; -var HTTPRequest = class { - constructor(path, loadOptions) { - this.DEFAULT_METHOD = "POST"; - if (loadOptions == null) { - loadOptions = {}; - } - this.weightPathPrefix = loadOptions.weightPathPrefix; - this.onProgress = loadOptions.onProgress; - this.weightUrlConverter = loadOptions.weightUrlConverter; - if (loadOptions.fetchFunc != null) { - assert(typeof loadOptions.fetchFunc === "function", () => "Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"); - this.fetch = loadOptions.fetchFunc; - } else { - this.fetch = env().platform.fetch; - } - assert(path != null && path.length > 0, () => "URL path for http must not be null, undefined or empty."); - if (Array.isArray(path)) { - assert(path.length === 2, () => `URL paths for http must have a length of 2, (actual length is ${path.length}).`); - } - this.path = path; - if (loadOptions.requestInit != null && loadOptions.requestInit.body != null) { +var hG = "application/octet-stream"; +var gG = "application/json"; +var ig = class { + constructor(e, t) { + if (this.DEFAULT_METHOD = "POST", t == null && (t = {}), this.weightPathPrefix = t.weightPathPrefix, this.onProgress = t.onProgress, this.weightUrlConverter = t.weightUrlConverter, t.fetchFunc != null ? (E(typeof t.fetchFunc == "function", () => "Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"), this.fetch = t.fetchFunc) : this.fetch = j().platform.fetch, E(e != null && e.length > 0, () => "URL path for http must not be null, undefined or empty."), Array.isArray(e) && E(e.length === 2, () => `URL paths for http must have a length of 2, (actual length is ${e.length}).`), this.path = e, t.requestInit != null && t.requestInit.body != null) throw new Error("requestInit is expected to have no pre-existing body, but has one."); - } - this.requestInit = loadOptions.requestInit || {}; + this.requestInit = t.requestInit || {}; } - async save(modelArtifacts) { - if (modelArtifacts.modelTopology instanceof ArrayBuffer) { + async save(e) { + if (e.modelTopology instanceof ArrayBuffer) throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet."); - } - const init2 = Object.assign({ method: this.DEFAULT_METHOD }, this.requestInit); - init2.body = new FormData(); - const weightsManifest = [{ - paths: ["./model.weights.bin"], - weights: modelArtifacts.weightSpecs - }]; - const modelTopologyAndWeightManifest = getModelJSONForModelArtifacts(modelArtifacts, weightsManifest); - init2.body.append("model.json", new Blob([JSON.stringify(modelTopologyAndWeightManifest)], { type: JSON_TYPE }), "model.json"); - if (modelArtifacts.weightData != null) { - init2.body.append("model.weights.bin", new Blob([modelArtifacts.weightData], { type: OCTET_STREAM_MIME_TYPE }), "model.weights.bin"); - } - const response = await this.fetch(this.path, init2); - if (response.ok) { - return { - modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts), - responses: [response] - }; - } else { - throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${response.status}.`); - } + let t = Object.assign({ method: this.DEFAULT_METHOD }, this.requestInit); + t.body = new FormData(); + let n = [{ paths: ["./model.weights.bin"], weights: e.weightSpecs }], o = og(e, n); + t.body.append("model.json", new Blob([JSON.stringify(o)], { type: gG }), "model.json"), e.weightData != null && t.body.append("model.weights.bin", new Blob([e.weightData], { type: hG }), "model.weights.bin"); + let s = await this.fetch(this.path, t); + if (s.ok) + return { modelArtifactsInfo: ii(e), responses: [s] }; + throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${s.status}.`); } async load() { - const modelConfigRequest = await this.fetch(this.path, this.requestInit); - if (!modelConfigRequest.ok) { - throw new Error(`Request to ${this.path} failed with status code ${modelConfigRequest.status}. Please verify this URL points to the model JSON of the model to load.`); - } - let modelJSON; + let e = await this.fetch(this.path, this.requestInit); + if (!e.ok) + throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`); + let t; try { - modelJSON = await modelConfigRequest.json(); - } catch (e) { - let message = `Failed to parse model JSON of response from ${this.path}.`; - if (this.path.endsWith(".pb")) { - message += " 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."; - } else { - message += " Please make sure the server is serving valid JSON for this request."; - } - throw new Error(message); + t = await e.json(); + } catch (s) { + let a = `Failed to parse model JSON of response from ${this.path}.`; + throw this.path.endsWith(".pb") ? a += " 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." : a += " Please make sure the server is serving valid JSON for this request.", new Error(a); } - const modelTopology = modelJSON.modelTopology; - const weightsManifest = modelJSON.weightsManifest; - if (modelTopology == null && weightsManifest == null) { + let n = t.modelTopology, o = t.weightsManifest; + if (n == null && o == null) throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`); - } - return getModelArtifactsForJSON(modelJSON, (weightsManifest2) => this.loadWeights(weightsManifest2)); + return np(t, (s) => this.loadWeights(s)); } - async loadWeights(weightsManifest) { - const weightPath = Array.isArray(this.path) ? this.path[1] : this.path; - const [prefix, suffix] = parseUrl(weightPath); - const pathPrefix = this.weightPathPrefix || prefix; - const weightSpecs = []; - for (const entry of weightsManifest) { - weightSpecs.push(...entry.weights); - } - const fetchURLs = []; - const urlPromises = []; - for (const weightsGroup of weightsManifest) { - for (const path of weightsGroup.paths) { - if (this.weightUrlConverter != null) { - urlPromises.push(this.weightUrlConverter(path)); - } else { - fetchURLs.push(pathPrefix + path + suffix); - } - } - } - if (this.weightUrlConverter) { - fetchURLs.push(...await Promise.all(urlPromises)); - } - const buffers = await loadWeightsAsArrayBuffer(fetchURLs, { - requestInit: this.requestInit, - fetchFunc: this.fetch, - onProgress: this.onProgress - }); - return [weightSpecs, concatenateArrayBuffers(buffers)]; + async loadWeights(e) { + let t = Array.isArray(this.path) ? this.path[1] : this.path, [n, o] = xG(t), s = this.weightPathPrefix || n, a = []; + for (let c of e) + a.push(...c.weights); + let i = [], l = []; + for (let c of e) + for (let p of c.paths) + this.weightUrlConverter != null ? l.push(this.weightUrlConverter(p)) : i.push(s + p + o); + this.weightUrlConverter && i.push(...await Promise.all(l)); + let u = await Hw(i, { requestInit: this.requestInit, fetchFunc: this.fetch, onProgress: this.onProgress }); + return [a, rp(u)]; } }; -HTTPRequest.URL_SCHEME_REGEX = /^https?:\/\//; -function parseUrl(url) { - const lastSlash = url.lastIndexOf("/"); - const lastSearchParam = url.lastIndexOf("?"); - const prefix = url.substring(0, lastSlash); - const suffix = lastSearchParam > lastSlash ? url.substring(lastSearchParam) : ""; - return [prefix + "/", suffix]; +ig.URL_SCHEME_REGEX = /^https?:\/\//; +function xG(r) { + let e = r.lastIndexOf("/"), t = r.lastIndexOf("?"), n = r.substring(0, e), o = t > e ? r.substring(t) : ""; + return [n + "/", o]; } -function isHTTPScheme(url) { - return url.match(HTTPRequest.URL_SCHEME_REGEX) != null; +function ag(r) { + return r.match(ig.URL_SCHEME_REGEX) != null; } -var httpRouter = (url, loadOptions) => { - if (typeof fetch === "undefined" && (loadOptions == null || loadOptions.fetchFunc == null)) { +var J1 = (r, e) => { + if (typeof fetch == "undefined" && (e == null || e.fetchFunc == null)) return null; - } else { - let isHTTP = true; - if (Array.isArray(url)) { - isHTTP = url.every((urlItem) => isHTTPScheme(urlItem)); - } else { - isHTTP = isHTTPScheme(url); - } - if (isHTTP) { - return http(url, loadOptions); - } + { + let t = true; + if (Array.isArray(r) ? t = r.every((n) => ag(n)) : t = ag(r), t) + return lg(r, e); } return null; }; -IORouterRegistry.registerSaveRouter(httpRouter); -IORouterRegistry.registerLoadRouter(httpRouter); -function http(path, loadOptions) { - return new HTTPRequest(path, loadOptions); +vt.registerSaveRouter(J1); +vt.registerLoadRouter(J1); +function lg(r, e) { + return new ig(r, e); } -function browserHTTPRequest(path, loadOptions) { - return http(path, loadOptions); +function Q1(r, e) { + return lg(r, e); } -var PassthroughLoader = class { - constructor(modelArtifacts) { - this.modelArtifacts = modelArtifacts; +var ug = class { + constructor(e) { + this.modelArtifacts = e; } async load() { return this.modelArtifacts; } }; -var PassthroughSaver = class { - constructor(saveHandler) { - this.saveHandler = saveHandler; +var eN = class { + constructor(e) { + this.saveHandler = e; } - async save(modelArtifacts) { - return this.saveHandler(modelArtifacts); + async save(e) { + return this.saveHandler(e); } }; -function fromMemory(modelArtifacts, weightSpecs, weightData, trainingConfig) { - if (arguments.length === 1) { - const isModelArtifacts = modelArtifacts.modelTopology != null || modelArtifacts.weightSpecs != null; - if (isModelArtifacts) { - return new PassthroughLoader(modelArtifacts); - } else { - 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."); - return new PassthroughLoader({ modelTopology: modelArtifacts }); - } - } else { - 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."); - return new PassthroughLoader({ - modelTopology: modelArtifacts, - weightSpecs, - weightData, - trainingConfig - }); - } +function tN(r, e, t, n) { + return arguments.length === 1 ? r.modelTopology != null || r.weightSpecs != null ? new ug(r) : (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 ug({ modelTopology: r })) : (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 ug({ modelTopology: r, weightSpecs: e, weightData: t, trainingConfig: n })); } -function withSaveHandler(saveHandler) { - return new PassthroughSaver(saveHandler); +function rN(r) { + return new eN(r); } -var math_exports = {}; -__export2(math_exports, { - confusionMatrix: () => confusionMatrix -}); -function matMul_(a, b, transposeA = false, transposeB = false) { - let $a = convertToTensor(a, "a", "matMul"); - let $b = convertToTensor(b, "b", "matMul"); - [$a, $b] = makeTypesMatch($a, $b); - const inputs = { a: $a, b: $b }; - const attrs = { transposeA, transposeB }; - return ENGINE.runKernel(BatchMatMul, inputs, attrs); +var oN = {}; +He(oN, { confusionMatrix: () => nN }); +function yG(r, e, t = false, n = false) { + let o = _(r, "a", "matMul"), s = _(e, "b", "matMul"); + [o, s] = Ge(o, s); + let a = { a: o, b: s }, i = { transposeA: t, transposeB: n }; + return T.runKernel(To, a, i); } -var matMul = op({ matMul_ }); -function oneHot_(indices, depth, onValue = 1, offValue = 0) { - if (depth < 2) { - throw new Error(`Error in oneHot: depth must be >=2, but it is ${depth}`); - } - const $indices = convertToTensor(indices, "indices", "oneHot", "int32"); - const inputs = { indices: $indices }; - const attrs = { depth, onValue, offValue }; - return ENGINE.runKernel(OneHot, inputs, attrs); +var Me = I({ matMul_: yG }); +function bG(r, e, t = 1, n = 0) { + if (e < 2) + throw new Error(`Error in oneHot: depth must be >=2, but it is ${e}`); + let s = { indices: _(r, "indices", "oneHot", "int32") }, a = { depth: e, onValue: t, offValue: n }; + return T.runKernel(Qo, s, a); } -var oneHot = op({ oneHot_ }); -function transpose_(x, perm) { - const $x = convertToTensor(x, "x", "transpose"); - if (perm == null) { - perm = $x.shape.map((s, i) => i).reverse(); - } - assert($x.rank === perm.length, () => `Error in transpose: rank of input ${$x.rank} must match length of perm ${perm}.`); - perm.forEach((axis) => { - assert(axis >= 0 && axis < $x.rank, () => `All entries in 'perm' must be between 0 and ${$x.rank - 1} but got ${perm}`); - }); - if ($x.rank <= 1) { - return $x.clone(); - } - const inputs = { x: $x }; - const attrs = { perm }; - return ENGINE.runKernel(Transpose, inputs, attrs); +var xa = I({ oneHot_: bG }); +function wG(r, e) { + let t = _(r, "x", "transpose"); + if (e == null && (e = t.shape.map((s, a) => a).reverse()), E(t.rank === e.length, () => `Error in transpose: rank of input ${t.rank} must match length of perm ${e}.`), e.forEach((s) => { + E(s >= 0 && s < t.rank, () => `All entries in 'perm' must be between 0 and ${t.rank - 1} but got ${e}`); + }), t.rank <= 1) + return t.clone(); + let n = { x: t }, o = { perm: e }; + return T.runKernel(ys, n, o); } -var transpose = op({ transpose_ }); -function confusionMatrix_(labels2, predictions, numClasses) { - const $labels = convertToTensor(labels2, "labels", "confusionMatrix"); - const $predictions = convertToTensor(predictions, "predictions", "confusionMatrix"); - assert(numClasses == null || numClasses > 0 && Number.isInteger(numClasses), () => `If provided, numClasses must be a positive integer, but got ${numClasses}`); - assert($labels.rank === 1, () => `Expected the rank of labels to be 1, but got ${$labels.rank}`); - assert($predictions.rank === 1, () => `Expected the rank of predictions to be 1, but got ${$predictions.rank}`); - assert($labels.shape[0] === $predictions.shape[0], () => `Mismatch in the number of examples: ${$labels.shape[0]} vs. ${$predictions.shape[0]}. Labels and predictions should have the same number of elements.`); - assert(numClasses > 0 && Number.isInteger(numClasses), () => `numClasses is required to be a positive integer, but got ${numClasses}`); - const oneHotLabels = oneHot(cast($labels, "int32"), numClasses); - const oneHotPredictions = oneHot(cast($predictions, "int32"), numClasses); - const oneHotLabelsT = transpose(oneHotLabels); - const product = matMul(oneHotLabelsT, oneHotPredictions); - return cast(product, "int32"); +var Ve = I({ transpose_: wG }); +function kG(r, e, t) { + let n = _(r, "labels", "confusionMatrix"), o = _(e, "predictions", "confusionMatrix"); + E(t == null || t > 0 && Number.isInteger(t), () => `If provided, numClasses must be a positive integer, but got ${t}`), E(n.rank === 1, () => `Expected the rank of labels to be 1, but got ${n.rank}`), E(o.rank === 1, () => `Expected the rank of predictions to be 1, but got ${o.rank}`), E(n.shape[0] === o.shape[0], () => `Mismatch in the number of examples: ${n.shape[0]} vs. ${o.shape[0]}. Labels and predictions should have the same number of elements.`), E(t > 0 && Number.isInteger(t), () => `numClasses is required to be a positive integer, but got ${t}`); + let s = xa(J(n, "int32"), t), a = xa(J(o, "int32"), t), i = Ve(s), l = Me(i, a); + return J(l, "int32"); } -var confusionMatrix = op({ confusionMatrix_ }); -var browser_exports = {}; -__export2(browser_exports, { - fromPixels: () => fromPixels, - fromPixelsAsync: () => fromPixelsAsync, - toPixels: () => toPixels -}); -function tensor3d(values, shape, dtype) { - assertNonNull(values); - if (shape != null && shape.length !== 3) { +var nN = I({ confusionMatrix_: kG }); +var cg = {}; +He(cg, { fromPixels: () => TG, fromPixelsAsync: () => IG, toPixels: () => NG }); +function Kw(r, e, t) { + if (Bn(r), e != null && e.length !== 3) throw new Error("tensor3d() requires shape to have three numbers"); - } - const inferredShape = inferShape(values, dtype); - if (inferredShape.length !== 3 && inferredShape.length !== 1) { + let n = Ar(r, t); + if (n.length !== 3 && n.length !== 1) throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray"); - } - if (inferredShape.length === 1 && shape == null) { + if (n.length === 1 && e == null) throw new Error("tensor3d() requires shape to be provided when `values` are a flat array"); - } - return makeTensor(values, shape, inferredShape, dtype); + return Yr(r, e, n, t); } -var fromPixels2DContext; -function fromPixels_(pixels, numChannels = 3) { - if (numChannels > 4) { +var ip; +function sN(r, e = 3) { + if (e > 4) throw new Error("Cannot construct Tensor with more than 4 channels from pixels."); - } - if (pixels == null) { + if (r == null) throw new Error("pixels passed to tf.browser.fromPixels() can not be null"); - } - let isPixelData2 = false; - let isImageData = false; - let isVideo = false; - let isImage = false; - let isCanvasLike = false; - let isImageBitmap = false; - if (pixels.data instanceof Uint8Array) { - isPixelData2 = true; - } else if (typeof ImageData !== "undefined" && pixels instanceof ImageData) { - isImageData = true; - } else if (typeof HTMLVideoElement !== "undefined" && pixels instanceof HTMLVideoElement) { - isVideo = true; - } else if (typeof HTMLImageElement !== "undefined" && pixels instanceof HTMLImageElement) { - isImage = true; - } else if (pixels.getContext != null) { - isCanvasLike = true; - } else if (typeof ImageBitmap !== "undefined" && pixels instanceof ImageBitmap) { - isImageBitmap = true; - } 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 ${pixels.constructor.name}`); - } - if (isVideo) { - const HAVE_CURRENT_DATA_READY_STATE = 2; - if (isVideo && pixels.readyState < HAVE_CURRENT_DATA_READY_STATE) { + let t = false, n = false, o = false, s = false, a = false, i = false; + if (r.data instanceof Uint8Array) + t = true; + else if (typeof ImageData != "undefined" && r instanceof ImageData) + n = true; + else if (typeof HTMLVideoElement != "undefined" && r instanceof HTMLVideoElement) + o = true; + else if (typeof HTMLImageElement != "undefined" && r instanceof HTMLImageElement) + s = true; + else if (r.getContext != null) + a = true; + else if (typeof ImageBitmap != "undefined" && r instanceof ImageBitmap) + i = true; + 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 ${r.constructor.name}`); + if (o) { + let d = 2; + if (o && r.readyState < d) throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the