From 2a52cff72cc031d2fd44d63a1f2265c649628ad9 Mon Sep 17 00:00:00 2001 From: Vladimir Mandic Date: Sat, 27 Mar 2021 15:45:37 -0400 Subject: [PATCH] update --- CHANGELOG.md | 3 + dist/demo-browser-index.js | 99748 +------------------------------ dist/demo-browser-index.js.map | 2 +- dist/human.esm-nobundle.js | 25451 +------- dist/human.esm-nobundle.js.map | 2 +- dist/human.esm.js | 98735 +----------------------------- dist/human.esm.js.map | 2 +- dist/human.js | 98741 +----------------------------- dist/human.js.map | 2 +- dist/human.node-gpu.js | 25473 +------- dist/human.node-gpu.js.map | 2 +- dist/human.node.js | 25473 +------- dist/human.node.js.map | 2 +- dist/tfjs.esm.js | 75665 +---------------------- dist/tfjs.esm.js.map | 2 +- 15 files changed, 6284 insertions(+), 443019 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a8a7968..30c86fd5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,9 @@ Repository: **** ### **HEAD -> main** 2021/03/27 mandic00@live.com + +### **origin/main** 2021/03/27 mandic00@live.com + - start working on efficientpose ### **1.2.5** 2021/03/25 mandic00@live.com diff --git a/dist/demo-browser-index.js b/dist/demo-browser-index.js index 79482c95..55876b0e 100644 --- a/dist/demo-browser-index.js +++ b/dist/demo-browser-index.js @@ -5,28354 +5,31 @@ author: ' */ -var __defProp = Object.defineProperty; -var __export = (target, all5) => { - for (var name in all5) - __defProp(target, name, {get: all5[name], enumerable: true}); -}; -var __accessCheck = (obj, member, msg) => { - if (!member.has(obj)) - throw TypeError("Cannot " + msg); -}; -var __privateGet = (obj, member, getter) => { - __accessCheck(obj, member, "read from private field"); - return getter ? getter.call(obj) : member.get(obj); -}; -var __privateSet = (obj, member, value, setter) => { - __accessCheck(obj, member, "write to private field"); - setter ? setter.call(obj, value) : member.set(obj, value); - return value; -}; - -// src/helpers.ts -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")}`; - if (msg) - console.log(ts, "Human:", ...msg); -} -var now = () => { - if (typeof performance !== "undefined") - return performance.now(); - return parseInt((Number(process.hrtime.bigint()) / 1e3 / 1e3).toString()); -}; -function mergeDeep(...objects) { - const isObject = (obj) => obj && typeof obj === "object"; - return objects.reduce((prev, obj) => { - Object.keys(obj || {}).forEach((key) => { - const pVal = prev[key]; - const oVal = obj[key]; - if (Array.isArray(pVal) && Array.isArray(oVal)) - prev[key] = pVal.concat(...oVal); - else if (isObject(pVal) && isObject(oVal)) - prev[key] = mergeDeep(pVal, oVal); - else - prev[key] = oVal; - }); - return prev; - }, {}); -} - -// src/sysinfo.ts -function info() { - let platform; - let agent; - if (typeof navigator !== "undefined") { - const raw = navigator.userAgent.match(/\(([^()]+)\)/g); - if (raw && raw[0]) { - platform = raw[0].match(/\(([^()]+)\)/g)[0].replace(/\(|\)/g, ""); - agent = navigator.userAgent.replace(raw[0], ""); - if (platform[1]) - agent = agent.replace(raw[1], ""); - agent = agent.replace(/ /g, " "); - } - } else if (typeof process !== "undefined") { - platform = `${process.platform} ${process.arch}`; - agent = `NodeJS ${process.version}`; - } - return {platform, agent}; -} - -// 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, - 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, - 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, - SparseToDense: () => SparseToDense, - SplitV: () => SplitV, - Sqrt: () => Sqrt, - Square: () => Square, - SquaredDifference: () => SquaredDifference, - Step: () => Step, - StridedSlice: () => StridedSlice, - 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, - 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, - 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: () => log2, - 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, - 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, - sparseToDense: () => sparseToDense, - spectral: () => spectral, - split: () => split, - sqrt: () => sqrt, - square: () => square, - squaredDifference: () => squaredDifference, - squeeze: () => squeeze, - stack: () => stack, - step: () => step, - stridedSlice: () => stridedSlice, - 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: () => version13, - version_converter: () => version11, - version_core: () => version6, - version_cpu: () => version7, - version_layers: () => version10, - version_wasm: () => version9, - version_webgl: () => version8, - webgl: () => webgl, - webgl_util: () => webgl_util_exports, - where: () => where, - whereAsync: () => whereAsync, - zeros: () => zeros, - zerosLike: () => zerosLike -}); -var __create = Object.create; -var __defProp2 = Object.defineProperty; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __markAsModule = (target) => __defProp2(target, "__esModule", {value: true}); -var __commonJS = (cb, mod42) => () => (mod42 || cb((mod42 = {exports: {}}).exports, mod42), mod42.exports); -var __export2 = (target, all42) => { - for (var name in all42) - __defProp2(target, name, {get: all42[name], enumerable: true}); -}; -var __exportStar = (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}); - } - return target; -}; -var __toModule = (module) => { - return __exportStar(__markAsModule(__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_browser = __commonJS(() => { -}); -var require_alea = __commonJS((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(data2) { - data2 = data2.toString(); - for (var i = 0; i < data2.length; i++) { - n += data2.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((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((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((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((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((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(() => { -}); -var require_seedrandom = __commonJS((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, options, callback) { - var key = []; - options = options == true ? {entropy: true} : options || {}; - var shortseed = mixkey(flatten4(options.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 (options.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 options ? options.global : this == math, options.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(count2) { - var t2, r = 0, i2 = me.i, j2 = me.j, s2 = me.S; - while (count2--) { - 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((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_path = __commonJS(() => { -}); -var require_worker_threads = __commonJS(() => { -}); -var require_perf_hooks = __commonJS(() => { -}); -var require_tfjs_backend_wasm_threaded_simd = __commonJS((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(status2, 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 = require("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(status2) { - process["exit"](status2); - }; - 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 data2; - if (typeof readbuffer === "function") { - return new Uint8Array(readbuffer(f)); - } - data2 = read(f, "binary"); - assert3(typeof data2 === "object"); - return data2; - }; - if (typeof scriptArgs != "undefined") { - arguments_ = scriptArgs; - } else if (typeof arguments != "undefined") { - arguments_ = arguments; - } - if (typeof quit === "function") { - quit_ = function(status2) { - quit(status2); - }; - } - 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 = require("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(str2) { - var ret2 = 0; - if (str2 !== null && str2 !== void 0 && str2 !== 0) { - var len = (str2.length << 2) + 1; - ret2 = stackAlloc(len); - stringToUTF8(str2, 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 str2 = ""; - while (!(idx >= endIdx)) { - var u0 = heap[idx++]; - if (!u0) - return str2; - if (!(u0 & 128)) { - str2 += String.fromCharCode(u0); - continue; - } - var u1 = heap[idx++] & 63; - if ((u0 & 224) == 192) { - str2 += 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) { - str2 += String.fromCharCode(u0); - } else { - var ch = u0 - 65536; - str2 += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023); - } - } - return str2; - } - function UTF8ToString(ptr, maxBytesToRead) { - return ptr ? UTF8ArrayToString(GROWABLE_HEAP_U8(), ptr, maxBytesToRead) : ""; - } - function stringToUTF8Array(str2, heap, outIdx, maxBytesToWrite) { - if (!(maxBytesToWrite > 0)) - return 0; - var startIdx = outIdx; - var endIdx = outIdx + maxBytesToWrite - 1; - for (var i = 0; i < str2.length; ++i) { - var u = str2.charCodeAt(i); - if (u >= 55296 && u <= 57343) { - var u1 = str2.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(str2, outPtr, maxBytesToWrite) { - return stringToUTF8Array(str2, GROWABLE_HEAP_U8(), outPtr, maxBytesToWrite); - } - function lengthBytesUTF8(str2) { - var len = 0; - for (var i = 0; i < str2.length; ++i) { - var u = str2.charCodeAt(i); - if (u >= 55296 && u <= 57343) - u = 65536 + ((u & 1023) << 10) | str2.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(); - }}); - if (ENVIRONMENT_IS_PTHREAD) - runtimeInitialized = true; - 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; - 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(str2, prefix) { - return String.prototype.startsWith ? str2.startsWith(prefix) : str2.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(instance2, module2) { - var exports3 = instance2.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 = {8991: 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, count2) { - if (addr <= 0 || addr > GROWABLE_HEAP_I8().length || addr & true || count2 < 0) - return -28; - if (count2 == 0) - return 0; - if (count2 >= 2147483647) - count2 = 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) { - --count2; - mainThreadWoken = 1; - if (count2 <= 0) - return 1; - } - } - var ret = Atomics.notify(GROWABLE_HEAP_I32(), addr >> 2, count2); - 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!"; - GROWABLE_HEAP_I32()[pthread_ptr + 12 >> 2] = 0; - var pthread = PThread.pthreads[pthread_ptr]; - if (pthread) { - var worker2 = pthread.worker; - PThread.returnWorkerToPool(worker2); - } - } - var PThread = {unusedWorkers: [], runningWorkers: [], initMainThreadBlock: function() { - var pthreadPoolSize = 8; - 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(); - }, threadExit: function(exitCode) { - var tb = _pthread_self(); - if (tb) { - Atomics.store(GROWABLE_HEAP_U32(), tb + 4 >> 2, exitCode); - Atomics.store(GROWABLE_HEAP_U32(), tb + 0 >> 2, 1); - Atomics.store(GROWABLE_HEAP_U32(), tb + 56 >> 2, 1); - Atomics.store(GROWABLE_HEAP_U32(), tb + 60 >> 2, 0); - PThread.runExitHandlers(); - _emscripten_futex_wake(tb + 0, 2147483647); - __emscripten_thread_init(0, 0, 0); - if (ENVIRONMENT_IS_PTHREAD) { - postMessage({cmd: "exit"}); - } - } - }, threadCancel: function() { - PThread.runExitHandlers(); - var tb = _pthread_self(); - Atomics.store(GROWABLE_HEAP_U32(), tb + 4 >> 2, -1); - Atomics.store(GROWABLE_HEAP_U32(), tb + 0 >> 2, 1); - _emscripten_futex_wake(tb + 0, 2147483647); - __emscripten_thread_init(0, 0, 0); - 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 worker2 = PThread.unusedWorkers[i]; - worker2.terminate(); - } - PThread.unusedWorkers = []; - for (var i = 0; i < PThread.runningWorkers.length; ++i) { - var worker2 = PThread.runningWorkers[i]; - var pthread = worker2.pthread; - PThread.freeThreadData(pthread); - worker2.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(worker2) { - PThread.runWithoutMainThreadQueuedCalls(function() { - delete PThread.pthreads[worker2.pthread.threadInfoStruct]; - PThread.unusedWorkers.push(worker2); - PThread.runningWorkers.splice(PThread.runningWorkers.indexOf(worker2), 1); - PThread.freeThreadData(worker2.pthread); - worker2.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(data2) { - }, loadWasmModuleToWorker: function(worker2, onFinishedLoading) { - worker2.onmessage = function(e) { - var d = e["data"]; - var cmd = d["cmd"]; - if (worker2.pthread) - PThread.currentProxiedOperationCallerThread = worker2.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") { - worker2.loaded = true; - if (onFinishedLoading) - onFinishedLoading(worker2); - if (worker2.runPthread) { - worker2.runPthread(); - delete worker2.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 = worker2.pthread && Atomics.load(GROWABLE_HEAP_U32(), worker2.pthread.threadInfoStruct + 64 >> 2); - if (detached) { - PThread.returnWorkerToPool(worker2); - } - } else if (cmd === "exitProcess") { - try { - exit(d["returnCode"]); - } catch (e2) { - if (e2 instanceof ExitStatus) - return; - throw e2; - } - } else if (cmd === "cancelDone") { - PThread.returnWorkerToPool(worker2); - } else if (cmd === "objectTransfer") { - PThread.receiveObjectTransfer(e.data); - } else if (e.data.target === "setimmediate") { - worker2.postMessage(e.data); - } else { - err("worker sent an unknown command " + cmd); - } - PThread.currentProxiedOperationCallerThread = void 0; - }; - worker2.onerror = function(e) { - err("pthread sent an error! " + e.filename + ":" + e.lineno + ": " + e.message); - }; - if (ENVIRONMENT_IS_NODE) { - worker2.on("message", function(data2) { - worker2.onmessage({data: data2}); - }); - worker2.on("error", function(data2) { - worker2.onerror(data2); - }); - worker2.on("exit", function(data2) { - }); - } - worker2.postMessage({cmd: "load", urlOrBlob: Module["mainScriptUrlOrBlob"] || _scriptDir, wasmMemory, 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 worker2 = pthread && pthread.worker; - if (!worker2) { - return; - } - worker2.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 require("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, count2, primcount) { - ext["drawArraysInstancedANGLE"](mode, first, count2, primcount); - }; - ctx["drawElementsInstanced"] = function(mode, count2, type, indices, primcount) { - ext["drawElementsInstancedANGLE"](mode, count2, 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, count2, string, length) { - var source = ""; - for (var i = 0; i < count2; ++i) { - var len = length ? GROWABLE_HEAP_I32()[length + i * 4 >> 2] : -1; - source += UTF8ToString(GROWABLE_HEAP_I32()[string + 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 worker2 = PThread.getNewWorker(); - if (worker2.pthread !== void 0) - throw "Internal error!"; - if (!threadParams.pthread_ptr) - throw "Internal error, no pthread ptr!"; - PThread.runningWorkers.push(worker2); - 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: worker2, 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); - worker2.pthread = pthread; - var msg = {cmd: "run", start_routine: threadParams.startRoutine, arg: threadParams.arg, threadInfoStruct: threadParams.pthread_ptr, stackBase: threadParams.stackBase, stackSize: threadParams.stackSize}; - worker2.runPthread = function() { - msg.time = performance.now(); - worker2.postMessage(msg, threadParams.transferList); - }; - if (worker2.loaded) { - worker2.runPthread(); - delete worker2.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 _ArgMax = Module["_ArgMax"] = function() { - return (_ArgMax = Module["_ArgMax"] = Module["asm"]["J"]).apply(null, arguments); - }; - var _AvgPool = Module["_AvgPool"] = function() { - return (_AvgPool = Module["_AvgPool"] = Module["asm"]["K"]).apply(null, arguments); - }; - var _BatchMatMul = Module["_BatchMatMul"] = function() { - return (_BatchMatMul = Module["_BatchMatMul"] = Module["asm"]["L"]).apply(null, arguments); - }; - var _Ceil = Module["_Ceil"] = function() { - return (_Ceil = Module["_Ceil"] = Module["asm"]["M"]).apply(null, arguments); - }; - var _ClipByValue = Module["_ClipByValue"] = function() { - return (_ClipByValue = Module["_ClipByValue"] = Module["asm"]["N"]).apply(null, arguments); - }; - var _Conv2D = Module["_Conv2D"] = function() { - return (_Conv2D = Module["_Conv2D"] = Module["asm"]["O"]).apply(null, arguments); - }; - var _Conv2DBackpropInput = Module["_Conv2DBackpropInput"] = function() { - return (_Conv2DBackpropInput = Module["_Conv2DBackpropInput"] = Module["asm"]["P"]).apply(null, arguments); - }; - var _Cos = Module["_Cos"] = function() { - return (_Cos = Module["_Cos"] = Module["asm"]["Q"]).apply(null, arguments); - }; - var _CropAndResize = Module["_CropAndResize"] = function() { - return (_CropAndResize = Module["_CropAndResize"] = Module["asm"]["R"]).apply(null, arguments); - }; - var _Cumsum = Module["_Cumsum"] = function() { - return (_Cumsum = Module["_Cumsum"] = Module["asm"]["S"]).apply(null, arguments); - }; - var _DepthToSpace = Module["_DepthToSpace"] = function() { - return (_DepthToSpace = Module["_DepthToSpace"] = Module["asm"]["T"]).apply(null, arguments); - }; - var _DepthwiseConv2dNative = Module["_DepthwiseConv2dNative"] = function() { - return (_DepthwiseConv2dNative = Module["_DepthwiseConv2dNative"] = Module["asm"]["U"]).apply(null, arguments); - }; - var _Equal = Module["_Equal"] = function() { - return (_Equal = Module["_Equal"] = Module["asm"]["V"]).apply(null, arguments); - }; - var _Exp = Module["_Exp"] = function() { - return (_Exp = Module["_Exp"] = Module["asm"]["W"]).apply(null, arguments); - }; - var _FlipLeftRight = Module["_FlipLeftRight"] = function() { - return (_FlipLeftRight = Module["_FlipLeftRight"] = Module["asm"]["X"]).apply(null, arguments); - }; - var _Floor = Module["_Floor"] = function() { - return (_Floor = Module["_Floor"] = Module["asm"]["Y"]).apply(null, arguments); - }; - var _FloorDiv = Module["_FloorDiv"] = function() { - return (_FloorDiv = Module["_FloorDiv"] = Module["asm"]["Z"]).apply(null, arguments); - }; - var _FusedBatchNorm = Module["_FusedBatchNorm"] = function() { - return (_FusedBatchNorm = Module["_FusedBatchNorm"] = Module["asm"]["_"]).apply(null, arguments); - }; - var _FusedConv2D = Module["_FusedConv2D"] = function() { - return (_FusedConv2D = Module["_FusedConv2D"] = Module["asm"]["$"]).apply(null, arguments); - }; - var _FusedDepthwiseConv2D = Module["_FusedDepthwiseConv2D"] = function() { - return (_FusedDepthwiseConv2D = Module["_FusedDepthwiseConv2D"] = Module["asm"]["aa"]).apply(null, arguments); - }; - var _Gather = Module["_Gather"] = function() { - return (_Gather = Module["_Gather"] = Module["asm"]["ba"]).apply(null, arguments); - }; - var _GatherNd = Module["_GatherNd"] = function() { - return (_GatherNd = Module["_GatherNd"] = Module["asm"]["ca"]).apply(null, arguments); - }; - var _Greater = Module["_Greater"] = function() { - return (_Greater = Module["_Greater"] = Module["asm"]["da"]).apply(null, arguments); - }; - var _GreaterEqual = Module["_GreaterEqual"] = function() { - return (_GreaterEqual = Module["_GreaterEqual"] = Module["asm"]["ea"]).apply(null, arguments); - }; - var _LeakyRelu = Module["_LeakyRelu"] = function() { - return (_LeakyRelu = Module["_LeakyRelu"] = Module["asm"]["fa"]).apply(null, arguments); - }; - var _Less = Module["_Less"] = function() { - return (_Less = Module["_Less"] = Module["asm"]["ga"]).apply(null, arguments); - }; - var _LessEqual = Module["_LessEqual"] = function() { - return (_LessEqual = Module["_LessEqual"] = Module["asm"]["ha"]).apply(null, arguments); - }; - var _Log = Module["_Log"] = function() { - return (_Log = Module["_Log"] = Module["asm"]["ia"]).apply(null, arguments); - }; - var _LogicalAnd = Module["_LogicalAnd"] = function() { - return (_LogicalAnd = Module["_LogicalAnd"] = Module["asm"]["ja"]).apply(null, arguments); - }; - var _Max = Module["_Max"] = function() { - return (_Max = Module["_Max"] = Module["asm"]["ka"]).apply(null, arguments); - }; - var _MaxPool = Module["_MaxPool"] = function() { - return (_MaxPool = Module["_MaxPool"] = Module["asm"]["la"]).apply(null, arguments); - }; - var _Maximum = Module["_Maximum"] = function() { - return (_Maximum = Module["_Maximum"] = Module["asm"]["ma"]).apply(null, arguments); - }; - var _Mean = Module["_Mean"] = function() { - return (_Mean = Module["_Mean"] = Module["asm"]["na"]).apply(null, arguments); - }; - var _Min = Module["_Min"] = function() { - return (_Min = Module["_Min"] = Module["asm"]["oa"]).apply(null, arguments); - }; - var _Minimum = Module["_Minimum"] = function() { - return (_Minimum = Module["_Minimum"] = Module["asm"]["pa"]).apply(null, arguments); - }; - var _Multiply = Module["_Multiply"] = function() { - return (_Multiply = Module["_Multiply"] = Module["asm"]["qa"]).apply(null, arguments); - }; - var _Neg = Module["_Neg"] = function() { - return (_Neg = Module["_Neg"] = Module["asm"]["ra"]).apply(null, arguments); - }; - var _NonMaxSuppressionV3 = Module["_NonMaxSuppressionV3"] = function() { - return (_NonMaxSuppressionV3 = Module["_NonMaxSuppressionV3"] = Module["asm"]["sa"]).apply(null, arguments); - }; - var _NonMaxSuppressionV4 = Module["_NonMaxSuppressionV4"] = function() { - return (_NonMaxSuppressionV4 = Module["_NonMaxSuppressionV4"] = Module["asm"]["ta"]).apply(null, arguments); - }; - var _NonMaxSuppressionV5 = Module["_NonMaxSuppressionV5"] = function() { - return (_NonMaxSuppressionV5 = Module["_NonMaxSuppressionV5"] = Module["asm"]["ua"]).apply(null, arguments); - }; - var _NotEqual = Module["_NotEqual"] = function() { - return (_NotEqual = Module["_NotEqual"] = Module["asm"]["va"]).apply(null, arguments); - }; - var _OneHot = Module["_OneHot"] = function() { - return (_OneHot = Module["_OneHot"] = Module["asm"]["wa"]).apply(null, arguments); - }; - var _PadV2 = Module["_PadV2"] = function() { - return (_PadV2 = Module["_PadV2"] = Module["asm"]["xa"]).apply(null, arguments); - }; - var _Pow = Module["_Pow"] = function() { - return (_Pow = Module["_Pow"] = Module["asm"]["ya"]).apply(null, arguments); - }; - var _Prelu = Module["_Prelu"] = function() { - return (_Prelu = Module["_Prelu"] = Module["asm"]["za"]).apply(null, arguments); - }; - var _Prod = Module["_Prod"] = function() { - return (_Prod = Module["_Prod"] = Module["asm"]["Aa"]).apply(null, arguments); - }; - var _RealDiv = Module["_RealDiv"] = function() { - return (_RealDiv = Module["_RealDiv"] = Module["asm"]["Ba"]).apply(null, arguments); - }; - var _Relu = Module["_Relu"] = function() { - return (_Relu = Module["_Relu"] = Module["asm"]["Ca"]).apply(null, arguments); - }; - var _Relu6 = Module["_Relu6"] = function() { - return (_Relu6 = Module["_Relu6"] = Module["asm"]["Da"]).apply(null, arguments); - }; - var _ResizeBilinear = Module["_ResizeBilinear"] = function() { - return (_ResizeBilinear = Module["_ResizeBilinear"] = Module["asm"]["Ea"]).apply(null, arguments); - }; - var _Reverse = Module["_Reverse"] = function() { - return (_Reverse = Module["_Reverse"] = Module["asm"]["Fa"]).apply(null, arguments); - }; - var _RotateWithOffset = Module["_RotateWithOffset"] = function() { - return (_RotateWithOffset = Module["_RotateWithOffset"] = Module["asm"]["Ga"]).apply(null, arguments); - }; - var _Round = Module["_Round"] = function() { - return (_Round = Module["_Round"] = Module["asm"]["Ha"]).apply(null, arguments); - }; - var _Rsqrt = Module["_Rsqrt"] = function() { - return (_Rsqrt = Module["_Rsqrt"] = Module["asm"]["Ia"]).apply(null, arguments); - }; - var _ScatterNd = Module["_ScatterNd"] = function() { - return (_ScatterNd = Module["_ScatterNd"] = Module["asm"]["Ja"]).apply(null, arguments); - }; - var _SelectV2 = Module["_SelectV2"] = function() { - return (_SelectV2 = Module["_SelectV2"] = Module["asm"]["Ka"]).apply(null, arguments); - }; - var _Sigmoid = Module["_Sigmoid"] = function() { - return (_Sigmoid = Module["_Sigmoid"] = Module["asm"]["La"]).apply(null, arguments); - }; - var _Sin = Module["_Sin"] = function() { - return (_Sin = Module["_Sin"] = Module["asm"]["Ma"]).apply(null, arguments); - }; - var _Softmax = Module["_Softmax"] = function() { - return (_Softmax = Module["_Softmax"] = Module["asm"]["Na"]).apply(null, arguments); - }; - var _Sqrt = Module["_Sqrt"] = function() { - return (_Sqrt = Module["_Sqrt"] = Module["asm"]["Oa"]).apply(null, arguments); - }; - var _Square = Module["_Square"] = function() { - return (_Square = Module["_Square"] = Module["asm"]["Pa"]).apply(null, arguments); - }; - var _SquaredDifference = Module["_SquaredDifference"] = function() { - return (_SquaredDifference = Module["_SquaredDifference"] = Module["asm"]["Qa"]).apply(null, arguments); - }; - var _Step = Module["_Step"] = function() { - return (_Step = Module["_Step"] = Module["asm"]["Ra"]).apply(null, arguments); - }; - var _StridedSlice = Module["_StridedSlice"] = function() { - return (_StridedSlice = Module["_StridedSlice"] = Module["asm"]["Sa"]).apply(null, arguments); - }; - var _Sub = Module["_Sub"] = function() { - return (_Sub = Module["_Sub"] = Module["asm"]["Ta"]).apply(null, arguments); - }; - var _Sum = Module["_Sum"] = function() { - return (_Sum = Module["_Sum"] = Module["asm"]["Ua"]).apply(null, arguments); - }; - var _Tanh = Module["_Tanh"] = function() { - return (_Tanh = Module["_Tanh"] = Module["asm"]["Va"]).apply(null, arguments); - }; - var _Tile = Module["_Tile"] = function() { - return (_Tile = Module["_Tile"] = Module["asm"]["Wa"]).apply(null, arguments); - }; - var _TopK = Module["_TopK"] = function() { - return (_TopK = Module["_TopK"] = Module["asm"]["Xa"]).apply(null, arguments); - }; - var _Transpose = Module["_Transpose"] = function() { - return (_Transpose = Module["_Transpose"] = Module["asm"]["Ya"]).apply(null, arguments); - }; - var __FusedMatMul = Module["__FusedMatMul"] = function() { - return (__FusedMatMul = Module["__FusedMatMul"] = Module["asm"]["Za"]).apply(null, arguments); - }; - var _malloc = Module["_malloc"] = function() { - return (_malloc = Module["_malloc"] = Module["asm"]["_a"]).apply(null, arguments); - }; - var _free = Module["_free"] = function() { - return (_free = Module["_free"] = Module["asm"]["$a"]).apply(null, arguments); - }; - var ___errno_location = Module["___errno_location"] = function() { - return (___errno_location = Module["___errno_location"] = Module["asm"]["ab"]).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"]["bb"]).apply(null, arguments); - }; - var _pthread_self = Module["_pthread_self"] = function() { - return (_pthread_self = Module["_pthread_self"] = Module["asm"]["cb"]).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"]["db"]).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"]["eb"]).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"]["fb"]).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"]["gb"]).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"]["hb"]).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"]["ib"]).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"]["jb"]).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"]["kb"]).apply(null, arguments); - }; - var _emscripten_tls_init = Module["_emscripten_tls_init"] = function() { - return (_emscripten_tls_init = Module["_emscripten_tls_init"] = Module["asm"]["lb"]).apply(null, arguments); - }; - var __emscripten_thread_init = Module["__emscripten_thread_init"] = function() { - return (__emscripten_thread_init = Module["__emscripten_thread_init"] = Module["asm"]["mb"]).apply(null, arguments); - }; - var stackSave = Module["stackSave"] = function() { - return (stackSave = Module["stackSave"] = Module["asm"]["nb"]).apply(null, arguments); - }; - var stackRestore = Module["stackRestore"] = function() { - return (stackRestore = Module["stackRestore"] = Module["asm"]["ob"]).apply(null, arguments); - }; - var stackAlloc = Module["stackAlloc"] = function() { - return (stackAlloc = Module["stackAlloc"] = Module["asm"]["pb"]).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"]["qb"]).apply(null, arguments); - }; - var _memalign = Module["_memalign"] = function() { - return (_memalign = Module["_memalign"] = Module["asm"]["rb"]).apply(null, arguments); - }; - var __emscripten_allow_main_runtime_queued_calls = Module["__emscripten_allow_main_runtime_queued_calls"] = 9880; - var __emscripten_main_thread_futex = Module["__emscripten_main_thread_futex"] = 11368; - Module["cwrap"] = cwrap; - Module["PThread"] = PThread; - Module["PThread"] = PThread; - Module["wasmMemory"] = wasmMemory; - Module["ExitStatus"] = ExitStatus; - var calledRun; - function ExitStatus(status2) { - this.name = "ExitStatus"; - this.message = "Program terminated with exit(" + status2 + ")"; - this.status = status2; - } - dependenciesFulfilled = function runCaller() { - if (!calledRun) - run2(); - if (!calledRun) - dependenciesFulfilled = runCaller; - }; - function run2(args) { - args = args || arguments_; - if (runDependencies > 0) { - return; - } - if (ENVIRONMENT_IS_PTHREAD) { - readyPromiseResolve(Module); - 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"] = run2; - function exit(status2, implicit) { - if (implicit && noExitRuntime && status2 === 0) { - return; - } - if (!implicit) { - if (ENVIRONMENT_IS_PTHREAD) { - postMessage({cmd: "exitProcess", returnCode: status2}); - throw new ExitStatus(status2); - } else { - } - } - if (noExitRuntime) { - } else { - PThread.terminateAllThreads(); - EXITSTATUS = status2; - exitRuntime(); - if (Module["onExit"]) - Module["onExit"](status2); - ABORT = true; - } - quit_(status2, new ExitStatus(status2)); - } - 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(); - } - run2(); - 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((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(status2, 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 = require("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(status2) { - process["exit"](status2); - }; - 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 data2; - if (typeof readbuffer === "function") { - return new Uint8Array(readbuffer(f)); - } - data2 = read(f, "binary"); - assert3(typeof data2 === "object"); - return data2; - }; - if (typeof scriptArgs != "undefined") { - arguments_ = scriptArgs; - } else if (typeof arguments != "undefined") { - arguments_ = arguments; - } - if (typeof quit === "function") { - quit_ = function(status2) { - quit(status2); - }; - } - 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(str2) { - var ret2 = 0; - if (str2 !== null && str2 !== void 0 && str2 !== 0) { - var len = (str2.length << 2) + 1; - ret2 = stackAlloc(len); - stringToUTF8(str2, 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 str2 = ""; - while (idx < endPtr) { - var u0 = heap[idx++]; - if (!(u0 & 128)) { - str2 += String.fromCharCode(u0); - continue; - } - var u1 = heap[idx++] & 63; - if ((u0 & 224) == 192) { - str2 += 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) { - str2 += String.fromCharCode(u0); - } else { - var ch = u0 - 65536; - str2 += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023); - } - } - } - return str2; - } - function UTF8ToString(ptr, maxBytesToRead) { - return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : ""; - } - function stringToUTF8Array(str2, heap, outIdx, maxBytesToWrite) { - if (!(maxBytesToWrite > 0)) - return 0; - var startIdx = outIdx; - var endIdx = outIdx + maxBytesToWrite - 1; - for (var i = 0; i < str2.length; ++i) { - var u = str2.charCodeAt(i); - if (u >= 55296 && u <= 57343) { - var u1 = str2.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(str2, outPtr, maxBytesToWrite) { - return stringToUTF8Array(str2, 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(str2, prefix) { - return String.prototype.startsWith ? str2.startsWith(prefix) : str2.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(instance2, module2) { - var exports3 = instance2.exports; - Module["asm"] = exports3; - wasmMemory = Module["asm"]["g"]; - updateGlobalBufferAndViews(wasmMemory.buffer); - wasmTable = Module["asm"]["m"]; - 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; - } - var asmLibraryArg = {a: _abort, d: _emscripten_memcpy_big, e: _emscripten_resize_heap, f: _fd_close, c: _fd_seek, b: _fd_write}; - var asm = createWasm(); - var ___wasm_call_ctors = Module["___wasm_call_ctors"] = function() { - return (___wasm_call_ctors = Module["___wasm_call_ctors"] = Module["asm"]["h"]).apply(null, arguments); - }; - var _init = Module["_init"] = function() { - return (_init = Module["_init"] = Module["asm"]["i"]).apply(null, arguments); - }; - var _register_tensor = Module["_register_tensor"] = function() { - return (_register_tensor = Module["_register_tensor"] = Module["asm"]["j"]).apply(null, arguments); - }; - var _dispose_data = Module["_dispose_data"] = function() { - return (_dispose_data = Module["_dispose_data"] = Module["asm"]["k"]).apply(null, arguments); - }; - var _dispose = Module["_dispose"] = function() { - return (_dispose = Module["_dispose"] = Module["asm"]["l"]).apply(null, arguments); - }; - var _Abs = Module["_Abs"] = function() { - return (_Abs = Module["_Abs"] = Module["asm"]["n"]).apply(null, arguments); - }; - var _Add = Module["_Add"] = function() { - return (_Add = Module["_Add"] = Module["asm"]["o"]).apply(null, arguments); - }; - var _AddN = Module["_AddN"] = function() { - return (_AddN = Module["_AddN"] = Module["asm"]["p"]).apply(null, arguments); - }; - var _ArgMax = Module["_ArgMax"] = function() { - return (_ArgMax = Module["_ArgMax"] = Module["asm"]["q"]).apply(null, arguments); - }; - var _AvgPool = Module["_AvgPool"] = function() { - return (_AvgPool = Module["_AvgPool"] = Module["asm"]["r"]).apply(null, arguments); - }; - var _BatchMatMul = Module["_BatchMatMul"] = function() { - return (_BatchMatMul = Module["_BatchMatMul"] = Module["asm"]["s"]).apply(null, arguments); - }; - var _Ceil = Module["_Ceil"] = function() { - return (_Ceil = Module["_Ceil"] = Module["asm"]["t"]).apply(null, arguments); - }; - var _ClipByValue = Module["_ClipByValue"] = function() { - return (_ClipByValue = Module["_ClipByValue"] = Module["asm"]["u"]).apply(null, arguments); - }; - var _Conv2D = Module["_Conv2D"] = function() { - return (_Conv2D = Module["_Conv2D"] = Module["asm"]["v"]).apply(null, arguments); - }; - var _Conv2DBackpropInput = Module["_Conv2DBackpropInput"] = function() { - return (_Conv2DBackpropInput = Module["_Conv2DBackpropInput"] = Module["asm"]["w"]).apply(null, arguments); - }; - var _Cos = Module["_Cos"] = function() { - return (_Cos = Module["_Cos"] = Module["asm"]["x"]).apply(null, arguments); - }; - var _CropAndResize = Module["_CropAndResize"] = function() { - return (_CropAndResize = Module["_CropAndResize"] = Module["asm"]["y"]).apply(null, arguments); - }; - var _Cumsum = Module["_Cumsum"] = function() { - return (_Cumsum = Module["_Cumsum"] = Module["asm"]["z"]).apply(null, arguments); - }; - var _DepthToSpace = Module["_DepthToSpace"] = function() { - return (_DepthToSpace = Module["_DepthToSpace"] = Module["asm"]["A"]).apply(null, arguments); - }; - var _DepthwiseConv2dNative = Module["_DepthwiseConv2dNative"] = function() { - return (_DepthwiseConv2dNative = Module["_DepthwiseConv2dNative"] = Module["asm"]["B"]).apply(null, arguments); - }; - var _Equal = Module["_Equal"] = function() { - return (_Equal = Module["_Equal"] = Module["asm"]["C"]).apply(null, arguments); - }; - var _Exp = Module["_Exp"] = function() { - return (_Exp = Module["_Exp"] = Module["asm"]["D"]).apply(null, arguments); - }; - var _FlipLeftRight = Module["_FlipLeftRight"] = function() { - return (_FlipLeftRight = Module["_FlipLeftRight"] = Module["asm"]["E"]).apply(null, arguments); - }; - var _Floor = Module["_Floor"] = function() { - return (_Floor = Module["_Floor"] = Module["asm"]["F"]).apply(null, arguments); - }; - var _FloorDiv = Module["_FloorDiv"] = function() { - return (_FloorDiv = Module["_FloorDiv"] = Module["asm"]["G"]).apply(null, arguments); - }; - var _FusedBatchNorm = Module["_FusedBatchNorm"] = function() { - return (_FusedBatchNorm = Module["_FusedBatchNorm"] = Module["asm"]["H"]).apply(null, arguments); - }; - var _FusedConv2D = Module["_FusedConv2D"] = function() { - return (_FusedConv2D = Module["_FusedConv2D"] = Module["asm"]["I"]).apply(null, arguments); - }; - var _FusedDepthwiseConv2D = Module["_FusedDepthwiseConv2D"] = function() { - return (_FusedDepthwiseConv2D = Module["_FusedDepthwiseConv2D"] = Module["asm"]["J"]).apply(null, arguments); - }; - var _Gather = Module["_Gather"] = function() { - return (_Gather = Module["_Gather"] = Module["asm"]["K"]).apply(null, arguments); - }; - var _GatherNd = Module["_GatherNd"] = function() { - return (_GatherNd = Module["_GatherNd"] = Module["asm"]["L"]).apply(null, arguments); - }; - var _Greater = Module["_Greater"] = function() { - return (_Greater = Module["_Greater"] = Module["asm"]["M"]).apply(null, arguments); - }; - var _GreaterEqual = Module["_GreaterEqual"] = function() { - return (_GreaterEqual = Module["_GreaterEqual"] = Module["asm"]["N"]).apply(null, arguments); - }; - var _LeakyRelu = Module["_LeakyRelu"] = function() { - return (_LeakyRelu = Module["_LeakyRelu"] = Module["asm"]["O"]).apply(null, arguments); - }; - var _Less = Module["_Less"] = function() { - return (_Less = Module["_Less"] = Module["asm"]["P"]).apply(null, arguments); - }; - var _LessEqual = Module["_LessEqual"] = function() { - return (_LessEqual = Module["_LessEqual"] = Module["asm"]["Q"]).apply(null, arguments); - }; - var _Log = Module["_Log"] = function() { - return (_Log = Module["_Log"] = Module["asm"]["R"]).apply(null, arguments); - }; - var _LogicalAnd = Module["_LogicalAnd"] = function() { - return (_LogicalAnd = Module["_LogicalAnd"] = Module["asm"]["S"]).apply(null, arguments); - }; - var _Max = Module["_Max"] = function() { - return (_Max = Module["_Max"] = Module["asm"]["T"]).apply(null, arguments); - }; - var _MaxPool = Module["_MaxPool"] = function() { - return (_MaxPool = Module["_MaxPool"] = Module["asm"]["U"]).apply(null, arguments); - }; - var _Maximum = Module["_Maximum"] = function() { - return (_Maximum = Module["_Maximum"] = Module["asm"]["V"]).apply(null, arguments); - }; - var _Mean = Module["_Mean"] = function() { - return (_Mean = Module["_Mean"] = Module["asm"]["W"]).apply(null, arguments); - }; - var _Min = Module["_Min"] = function() { - return (_Min = Module["_Min"] = Module["asm"]["X"]).apply(null, arguments); - }; - var _Minimum = Module["_Minimum"] = function() { - return (_Minimum = Module["_Minimum"] = Module["asm"]["Y"]).apply(null, arguments); - }; - var _Multiply = Module["_Multiply"] = function() { - return (_Multiply = Module["_Multiply"] = Module["asm"]["Z"]).apply(null, arguments); - }; - var _Neg = Module["_Neg"] = function() { - return (_Neg = Module["_Neg"] = Module["asm"]["_"]).apply(null, arguments); - }; - var _NonMaxSuppressionV3 = Module["_NonMaxSuppressionV3"] = function() { - return (_NonMaxSuppressionV3 = Module["_NonMaxSuppressionV3"] = Module["asm"]["$"]).apply(null, arguments); - }; - var _NonMaxSuppressionV4 = Module["_NonMaxSuppressionV4"] = function() { - return (_NonMaxSuppressionV4 = Module["_NonMaxSuppressionV4"] = Module["asm"]["aa"]).apply(null, arguments); - }; - var _NonMaxSuppressionV5 = Module["_NonMaxSuppressionV5"] = function() { - return (_NonMaxSuppressionV5 = Module["_NonMaxSuppressionV5"] = Module["asm"]["ba"]).apply(null, arguments); - }; - var _NotEqual = Module["_NotEqual"] = function() { - return (_NotEqual = Module["_NotEqual"] = Module["asm"]["ca"]).apply(null, arguments); - }; - var _OneHot = Module["_OneHot"] = function() { - return (_OneHot = Module["_OneHot"] = Module["asm"]["da"]).apply(null, arguments); - }; - var _PadV2 = Module["_PadV2"] = function() { - return (_PadV2 = Module["_PadV2"] = Module["asm"]["ea"]).apply(null, arguments); - }; - var _Pow = Module["_Pow"] = function() { - return (_Pow = Module["_Pow"] = Module["asm"]["fa"]).apply(null, arguments); - }; - var _Prelu = Module["_Prelu"] = function() { - return (_Prelu = Module["_Prelu"] = Module["asm"]["ga"]).apply(null, arguments); - }; - var _Prod = Module["_Prod"] = function() { - return (_Prod = Module["_Prod"] = Module["asm"]["ha"]).apply(null, arguments); - }; - var _RealDiv = Module["_RealDiv"] = function() { - return (_RealDiv = Module["_RealDiv"] = Module["asm"]["ia"]).apply(null, arguments); - }; - var _Relu = Module["_Relu"] = function() { - return (_Relu = Module["_Relu"] = Module["asm"]["ja"]).apply(null, arguments); - }; - var _Relu6 = Module["_Relu6"] = function() { - return (_Relu6 = Module["_Relu6"] = Module["asm"]["ka"]).apply(null, arguments); - }; - var _ResizeBilinear = Module["_ResizeBilinear"] = function() { - return (_ResizeBilinear = Module["_ResizeBilinear"] = Module["asm"]["la"]).apply(null, arguments); - }; - var _Reverse = Module["_Reverse"] = function() { - return (_Reverse = Module["_Reverse"] = Module["asm"]["ma"]).apply(null, arguments); - }; - var _RotateWithOffset = Module["_RotateWithOffset"] = function() { - return (_RotateWithOffset = Module["_RotateWithOffset"] = Module["asm"]["na"]).apply(null, arguments); - }; - var _Round = Module["_Round"] = function() { - return (_Round = Module["_Round"] = Module["asm"]["oa"]).apply(null, arguments); - }; - var _Rsqrt = Module["_Rsqrt"] = function() { - return (_Rsqrt = Module["_Rsqrt"] = Module["asm"]["pa"]).apply(null, arguments); - }; - var _ScatterNd = Module["_ScatterNd"] = function() { - return (_ScatterNd = Module["_ScatterNd"] = Module["asm"]["qa"]).apply(null, arguments); - }; - var _SelectV2 = Module["_SelectV2"] = function() { - return (_SelectV2 = Module["_SelectV2"] = Module["asm"]["ra"]).apply(null, arguments); - }; - var _Sigmoid = Module["_Sigmoid"] = function() { - return (_Sigmoid = Module["_Sigmoid"] = Module["asm"]["sa"]).apply(null, arguments); - }; - var _Sin = Module["_Sin"] = function() { - return (_Sin = Module["_Sin"] = Module["asm"]["ta"]).apply(null, arguments); - }; - var _Softmax = Module["_Softmax"] = function() { - return (_Softmax = Module["_Softmax"] = Module["asm"]["ua"]).apply(null, arguments); - }; - var _Sqrt = Module["_Sqrt"] = function() { - return (_Sqrt = Module["_Sqrt"] = Module["asm"]["va"]).apply(null, arguments); - }; - var _Square = Module["_Square"] = function() { - return (_Square = Module["_Square"] = Module["asm"]["wa"]).apply(null, arguments); - }; - var _SquaredDifference = Module["_SquaredDifference"] = function() { - return (_SquaredDifference = Module["_SquaredDifference"] = Module["asm"]["xa"]).apply(null, arguments); - }; - var _Step = Module["_Step"] = function() { - return (_Step = Module["_Step"] = Module["asm"]["ya"]).apply(null, arguments); - }; - var _StridedSlice = Module["_StridedSlice"] = function() { - return (_StridedSlice = Module["_StridedSlice"] = Module["asm"]["za"]).apply(null, arguments); - }; - var _Sub = Module["_Sub"] = function() { - return (_Sub = Module["_Sub"] = Module["asm"]["Aa"]).apply(null, arguments); - }; - var _Sum = Module["_Sum"] = function() { - return (_Sum = Module["_Sum"] = Module["asm"]["Ba"]).apply(null, arguments); - }; - var _Tanh = Module["_Tanh"] = function() { - return (_Tanh = Module["_Tanh"] = Module["asm"]["Ca"]).apply(null, arguments); - }; - var _Tile = Module["_Tile"] = function() { - return (_Tile = Module["_Tile"] = Module["asm"]["Da"]).apply(null, arguments); - }; - var _TopK = Module["_TopK"] = function() { - return (_TopK = Module["_TopK"] = Module["asm"]["Ea"]).apply(null, arguments); - }; - var _Transpose = Module["_Transpose"] = function() { - return (_Transpose = Module["_Transpose"] = Module["asm"]["Fa"]).apply(null, arguments); - }; - var __FusedMatMul = Module["__FusedMatMul"] = function() { - return (__FusedMatMul = Module["__FusedMatMul"] = Module["asm"]["Ga"]).apply(null, arguments); - }; - var _malloc = Module["_malloc"] = function() { - return (_malloc = Module["_malloc"] = Module["asm"]["Ha"]).apply(null, arguments); - }; - var _free = Module["_free"] = function() { - return (_free = Module["_free"] = Module["asm"]["Ia"]).apply(null, arguments); - }; - var stackSave = Module["stackSave"] = function() { - return (stackSave = Module["stackSave"] = Module["asm"]["Ja"]).apply(null, arguments); - }; - var stackRestore = Module["stackRestore"] = function() { - return (stackRestore = Module["stackRestore"] = Module["asm"]["Ka"]).apply(null, arguments); - }; - var stackAlloc = Module["stackAlloc"] = function() { - return (stackAlloc = Module["stackAlloc"] = Module["asm"]["La"]).apply(null, arguments); - }; - Module["cwrap"] = cwrap; - var calledRun; - function ExitStatus(status2) { - this.name = "ExitStatus"; - this.message = "Program terminated with exit(" + status2 + ")"; - this.status = status2; - } - dependenciesFulfilled = function runCaller() { - if (!calledRun) - run2(); - if (!calledRun) - dependenciesFulfilled = runCaller; - }; - function run2(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"] = run2; - if (Module["preInit"]) { - if (typeof Module["preInit"] == "function") - Module["preInit"] = [Module["preInit"]]; - while (Module["preInit"].length > 0) { - Module["preInit"].pop()(); - } - } - run2(); - 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 require_alea2 = __commonJS((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(data2) { - data2 = String(data2); - for (var i = 0; i < data2.length; i++) { - n += data2.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((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((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((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((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((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((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, options, callback) { - var key = []; - options = options == true ? {entropy: true} : options || {}; - var shortseed = mixkey(flatten4(options.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 (options.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 options ? options.global : this == math, options.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(count2) { - var t2, r = 0, i2 = me.i, j2 = me.j, s2 = me.S; - while (count2--) { - 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((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(() => { -}); -var version = "3.3.0"; -var version2 = "3.3.0"; -var version3 = "3.3.0"; -var version4 = "3.3.0"; -var version5 = "3.3.0"; -/** - * @license - * Copyright 2020 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var 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 this.data.get(dataId); - } - set(dataId, value) { - this.dataIdsCount++; - this.data.set(dataId, value); - } - has(dataId) { - return this.data.has(dataId); - } - delete(dataId) { - this.dataIdsCount--; - return this.data.delete(dataId); - } - numDataIds() { - return this.dataIdsCount; - } -}; -var KernelBackend = class { - refCount(dataId) { - return notYetImplemented("refCount"); - } - incRef(dataId) { - return notYetImplemented("incRef"); - } - timerAvailable() { - return true; - } - time(f) { - return notYetImplemented("time"); - } - read(dataId) { - return notYetImplemented("read"); - } - readSync(dataId) { - return notYetImplemented("readSync"); - } - numDataIds() { - return notYetImplemented("numDataIds"); - } - disposeData(dataId, force) { - return notYetImplemented("disposeData"); - } - write(values, shape, dtype) { - return notYetImplemented("write"); - } - move(dataId, values, shape, dtype, refCount) { - return notYetImplemented("move"); - } - memory() { - return notYetImplemented("memory"); - } - floatPrecision() { - return notYetImplemented("floatPrecision"); - } - epsilon() { - return this.floatPrecision() === 32 ? EPSILON_FLOAT32 : EPSILON_FLOAT16; - } - dispose() { - return notYetImplemented("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`); -} -/** - * @license - * Copyright 2020 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -function shuffle(array2) { - let counter = array2.length; - let temp = 0; - let index = 0; - while (counter > 0) { - index = Math.random() * counter | 0; - counter--; - temp = array2[counter]; - array2[counter] = array2[index]; - array2[index] = temp; - } -} -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 temp, temp2; - let index = 0; - while (counter > 0) { - index = Math.random() * counter | 0; - counter--; - temp = array2[counter]; - temp2 = array22[counter]; - array2[counter] = array2[index]; - array22[counter] = array22[index]; - array2[index] = temp; - array22[index] = temp2; - } -} -function clamp(min6, x, max6) { - return Math.max(min6, Math.min(x, max6)); -} -function nearestLargerEven(val) { - return val % 2 === 0 ? val : val + 1; -} -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) { - return 1; - } - let size = shape[0]; - for (let i = 1; i < shape.length; i++) { - size *= shape[i]; - } - return size; -} -function isScalarShape(shape) { - return shape.length === 0; -} -function arraysEqual(n1, n2) { - if (n1 === n2) { - return true; - } - if (n1 == null || n2 == null) { - return false; - } - if (n1.length !== n2.length) { - return false; - } - for (let i = 0; i < n1.length; i++) { - if (n1[i] !== n2[i]) { - return false; - } - } - return true; -} -function isInt(a) { - return a % 1 === 0; -} -function tanh(x) { - if (Math.tanh != null) { - return Math.tanh(x); - } - if (x === Infinity) { - return 1; - } else if (x === -Infinity) { - return -1; - } else { - const e2x = Math.exp(2 * x); - return (e2x - 1) / (e2x + 1); - } -} -function sizeToSquarishShape(size) { - const width = Math.ceil(Math.sqrt(size)); - return [width, Math.ceil(size / width)]; -} -function createShuffledIndices(n) { - const shuffledIndices = new Uint32Array(n); - for (let i = 0; i < n; ++i) { - shuffledIndices[i] = i; - } - shuffle(shuffledIndices); - return shuffledIndices; -} -function rightPad(a, size) { - if (size <= a.length) { - return a; - } - return a + " ".repeat(size - a.length); -} -function repeatedTry(checkFn, delayFn = (counter) => 0, maxCounter) { - return new Promise((resolve, reject) => { - let tryCount = 0; - const tryFn = () => { - if (checkFn()) { - resolve(); - return; - } - tryCount++; - const nextBackoff = delayFn(tryCount); - if (maxCounter != null && tryCount >= maxCounter) { - reject(); - return; - } - setTimeout(tryFn, nextBackoff); - }; - tryFn(); - }); -} -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}`); - } - } - 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; -} -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 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 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 isValidDtype(dtype) { - return dtype === "bool" || dtype === "complex64" || dtype === "float32" || dtype === "int32" || dtype === "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 isTypedArray(a) { - return a instanceof Float32Array || a instanceof Int32Array || a instanceof Uint8Array; -} -function bytesPerElement(dtype) { - if (dtype === "float32" || dtype === "int32") { - return 4; - } else if (dtype === "complex64") { - return 8; - } else if (dtype === "bool") { - return 1; - } else { - throw new Error(`Unknown dtype ${dtype}`); - } -} -function bytesFromStringArray(arr) { - if (arr == null) { - return 0; - } - let bytes = 0; - arr.forEach((x) => bytes += x.length); - return bytes; -} -function isString(value) { - return typeof value === "string" || value instanceof String; -} -function isBoolean(value) { - return typeof value === "boolean"; -} -function isNumber(value) { - return typeof value === "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 isFunction(f) { - return !!(f && f.constructor && f.call && f.apply); -} -function nearestDivisor(size, start) { - for (let i = start; i < size; ++i) { - if (size % i === 0) { - return i; - } - } - return size; -} -function computeStrides(shape) { - const rank = shape.length; - if (rank < 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; -} -function createNestedArray(offset, shape, a) { - const ret = new Array(); - if (shape.length === 1) { - const d = shape[0]; - for (let i = 0; i < d; i++) { - ret[i] = a[offset + i]; - } - } else { - const d = shape[0]; - const rest = shape.slice(1); - const len = rest.reduce((acc, c) => acc * c); - for (let i = 0; i < d; i++) { - ret[i] = createNestedArray(offset + i * len, rest, a); - } - } - return ret; -} -function toNestedArray(shape, a) { - if (shape.length === 0) { - return a[0]; - } - const size = shape.reduce((acc, c) => acc * c); - if (size === 0) { - return []; - } - if (size !== a.length) { - throw new Error(`[${shape}] does not match the input size ${a.length}.`); - } - return createNestedArray(0, shape, a); -} -function makeOnesTypedArray(size, dtype) { - const array2 = makeZerosTypedArray(size, dtype); - for (let i = 0; i < array2.length; i++) { - array2[i] = 1; - } - return array2; -} -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 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 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 locToIndex(locs, rank, strides) { - if (rank === 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; -} -function indexToLoc(index, rank, strides) { - if (rank === 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; -} -function isPromise(object2) { - return object2 && object2.then && typeof object2.then === "function"; -} -/** - * @license - * Copyright 2017 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var TENSORFLOWJS_FLAGS_PREFIX = "tfjsflags"; -var Environment = class { - constructor(global2) { - this.global = global2; - this.flags = {}; - this.flagRegistry = {}; - this.urlFlags = {}; - this.populateURLFlags(); - } - setPlatform(platformName, platform) { - if (this.platform != null) { - console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${platform}.`); - } - this.platformName = platformName; - this.platform = platform; - } - registerFlag(flagName, evaluationFn, setHook) { - this.flagRegistry[flagName] = {evaluationFn, setHook}; - if (this.urlFlags[flagName] != null) { - const flagValue = this.urlFlags[flagName]; - console.warn(`Setting feature override from URL ${flagName}: ${flagValue}.`); - this.set(flagName, flagValue); - } - } - async getAsync(flagName) { - if (flagName in this.flags) { - return this.flags[flagName]; - } - this.flags[flagName] = await this.evaluateFlag(flagName); - return this.flags[flagName]; - } - 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]; - } - getNumber(flagName) { - return this.get(flagName); - } - getBool(flagName) { - return this.get(flagName); - } - getFlags() { - return this.flags; - } - 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); - } - } - evaluateFlag(flagName) { - if (this.flagRegistry[flagName] == null) { - throw new Error(`Cannot evaluate flag '${flagName}': no evaluation function found.`); - } - return this.flagRegistry[flagName].evaluationFn(); - } - setFlags(flags) { - this.flags = Object.assign({}, flags); - } - reset() { - this.flags = {}; - this.urlFlags = {}; - this.populateURLFlags(); - } - populateURLFlags() { - if (typeof this.global === "undefined" || typeof this.global.location === "undefined" || typeof this.global.location.search === "undefined") { - return; - } - const urlParams = 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); - }); - } - } -}; -function getQueryParams(queryString) { - const params = {}; - queryString.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g, (s, ...t) => { - decodeParam(params, t[0], t[1]); - return t.join("="); - }); - return params; -} -function decodeParam(params, name, value) { - params[decodeURIComponent(name)] = decodeURIComponent(value || ""); -} -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 env() { - return ENV; -} -var ENV = null; -function setEnvironmentGlobal(environment) { - ENV = environment; -} -/** - * @license - * Copyright 2020 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var 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 { - throw new Error("Could not find a global object"); - } - globalNameSpace = ns; - } - return globalNameSpace; -} -function getGlobalMap() { - const ns = getGlobalNamespace(); - if (ns._tfGlobals == null) { - ns._tfGlobals = new Map(); - } - return ns._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); - } -} -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 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 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 SquaredDifference = "SquaredDifference"; -var Square = "Square"; -var Sub = "Sub"; -var SparseToDense = "SparseToDense"; -var StridedSlice = "StridedSlice"; -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"; -/** - * @license - * Copyright 2019 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var kernelRegistry = getGlobal("kernelRegistry", () => new Map()); -var gradRegistry = getGlobal("gradRegistry", () => new Map()); -function getKernel(kernelName, backendName) { - const key = makeKey(kernelName, backendName); - return kernelRegistry.get(key); -} -function getGradient(kernelName) { - return gradRegistry.get(kernelName); -} -function getKernelsForBackend(backendName) { - const it = kernelRegistry.entries(); - const result = []; - while (true) { - const {done, value} = it.next(); - if (done) { - break; - } - const [key, config3] = value; - const [backend22] = key.split("_"); - if (backend22 === backendName) { - result.push(config3); - } - } - return result; -} -function registerKernel(config3) { - const {kernelName, backendName} = config3; - const key = makeKey(kernelName, backendName); - if (kernelRegistry.has(key)) { - console.warn(`The kernel '${kernelName}' for backend '${backendName}' is already registered`); - } - kernelRegistry.set(key, config3); -} -function registerGradient(config3) { - const {kernelName} = config3; - if (gradRegistry.has(kernelName)) { - if (env().getBool("DEBUG")) { - console.warn(`Overriding the gradient for '${kernelName}'`); - } - } - gradRegistry.set(kernelName, config3); -} -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 unregisterGradient(kernelName) { - if (!gradRegistry.has(kernelName)) { - throw new Error(`The gradient '${kernelName}' for backend is not registered`); - } - gradRegistry.delete(kernelName); -} -function copyRegisteredKernels(registeredBackendName, newBackendName) { - const kernels = getKernelsForBackend(registeredBackendName); - kernels.forEach((kernelConfig) => { - const newKernelConfig = Object.assign({}, kernelConfig, {backendName: newBackendName}); - registerKernel(newKernelConfig); - }); -} -function makeKey(kernelName, backendName) { - return `${backendName}_${kernelName}`; -} -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: () => fetch2, - flatten: () => flatten, - getArrayFromDType: () => getArrayFromDType, - getTypedArrayFromDType: () => getTypedArrayFromDType, - hasEncodingLoss: () => hasEncodingLoss, - 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, - tanh: () => tanh, - toNestedArray: () => toNestedArray, - toTypedArray: () => toTypedArray -}); -/** - * @license - * Copyright 2017 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -function createScalarValue(value, dtype) { - if (dtype === "string") { - return encodeString(value); - } - return toTypedArray([value], dtype); -} -function noConversionNeeded(a, dtype) { - return a instanceof Float32Array && dtype === "float32" || a instanceof Int32Array && dtype === "int32" || a instanceof Uint8Array && dtype === "bool"; -} -function toTypedArray(a, dtype) { - if (dtype === "string") { - throw new Error("Cannot convert a string[] to a TypedArray"); - } - 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; - } - } - return bool; - } else { - throw new Error(`Unknown data type ${dtype}`); - } -} -function now2() { - return env().platform.now(); -} -function fetch2(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); -} -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var 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); - }); - } - } - const kernelProfile = { - kernelName, - outputs, - inputs, - timeMs: timer.then((timing) => timing.kernelMs), - extraInfo: timer.then((timing) => timing.getExtraProfileInfo != null ? timing.getExtraProfileInfo() : "") - }; - return kernelProfile; - } - 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]); - }); - }); - } -}; -function checkComputationForErrors(vals, dtype, kernelName) { - if (dtype !== "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; - } - } - 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 : ""} `; - } - } - 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"); - } -}; -/** - * @license - * Copyright 2017 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -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; - break; - } - } - if (anyInputFromX) { - 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; - } - } - } - 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; -} -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(); - } - } - } -} -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var 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"); -} -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); - } - } - } - 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; -} -/** - * @license - * Copyright 2017 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var 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) { - 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; - } - indexToLoc(index) { - 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; - } - get rank() { - return this.shape.length; - } - toTensor() { - return trackerFn().makeTensor(this.values, this.shape, this.dtype); - } -}; -var trackerFn = null; -var opHandler = null; -var deprecationWarningFn = null; -function setTensorTracker(fn) { - trackerFn = fn; -} -function setOpHandler(handler) { - opHandler = handler; -} -function setDeprecationWarningFn(fn) { - deprecationWarningFn = fn; -} -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"; - } - get rank() { - return this.shape.length; - } - async buffer() { - const vals = await this.data(); - return opHandler.buffer(this.shape, this.dtype, vals); - } - bufferSync() { - return opHandler.buffer(this.shape, this.dtype, this.dataSync()); - } - async array() { - const vals = await this.data(); - return toNestedArray(this.shape, vals); - } - arraySync() { - return toNestedArray(this.shape, this.dataSync()); - } - async data() { - this.throwIfDisposed(); - const data2 = trackerFn().read(this.dataId); - if (this.dtype === "string") { - const bytes = await data2; - try { - return bytes.map((b) => decodeString(b)); - } catch (_a) { - throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes()."); - } - } - return data2; - } - dataSync() { - this.throwIfDisposed(); - const data2 = trackerFn().readSync(this.dataId); - if (this.dtype === "string") { - try { - return data2.map((b) => decodeString(b)); - } catch (_a) { - throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes()."); - } - } - return data2; - } - async bytes() { - this.throwIfDisposed(); - const data2 = await trackerFn().read(this.dataId); - if (this.dtype === "string") { - return data2; - } else { - return new Uint8Array(data2.buffer); - } - } - dispose() { - if (this.isDisposed) { - return; - } - trackerFn().disposeTensor(this); - this.isDisposedInternal = true; - } - get isDisposed() { - return this.isDisposedInternal; - } - throwIfDisposed() { - if (this.isDisposed) { - throw new Error(`Tensor is disposed.`); - } - } - print(verbose = false) { - return opHandler.print(this, verbose); - } - clone() { - this.throwIfDisposed(); - return opHandler.clone(this); - } - toString(verbose = false) { - const vals = this.dataSync(); - return tensorToString(vals, this.shape, this.dtype, verbose); - } - cast(dtype) { - this.throwIfDisposed(); - return opHandler.cast(this, dtype); - } - variable(trainable = true, name, dtype) { - this.throwIfDisposed(); - return trackerFn().makeVariable(this, trainable, name, dtype); - } -}; -Object.defineProperty(Tensor, Symbol.hasInstance, { - value: (instance2) => { - return !!instance2 && instance2.data != null && instance2.dataSync != null && instance2.throwIfDisposed != null; - } -}); -function getGlobalTensorClass() { - return getGlobal("Tensor", () => { - return Tensor; - }); -} -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; - } - 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); - } - dispose() { - trackerFn().disposeVariable(this); - this.isDisposedInternal = true; - } -}; -Object.defineProperty(Variable, Symbol.hasInstance, { - value: (instance2) => { - return instance2 instanceof Tensor && instance2.assign != null && instance2.assign instanceof Function; - } -}); -var tensor_util_exports = {}; -__export2(tensor_util_exports, { - assertTypesMatch: () => assertTypesMatch, - getTensorsInContainer: () => getTensorsInContainer, - isTensorInList: () => isTensorInList, - makeTypesMatch: () => makeTypesMatch -}); -/** - * @license - * Copyright 2017 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var 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") { - return "string"; - } - throw new Error(`Can not upcast ${typeA} with ${typeB}`); - } - return upcastTypeMap[typeA][typeB]; -} -function sumOutType(type) { - return upcastType(type, "int32"); -} -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -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 assertTypesMatch(a, b) { - assert(a.dtype === b.dtype, () => `The dtypes of the first(${a.dtype}) and second(${b.dtype}) input must match`); -} -function isTensorInList(tensor2, tensorList) { - return tensorList.some((x) => x.id === tensor2.id); -} -function getTensorsInContainer(result) { - const list = []; - const seen = new Set(); - walkTensorContainer(result, list, seen); - return list; -} -function walkTensorContainer(container, list, seen) { - if (container == null) { - return; - } - if (container instanceof Tensor) { - list.push(container); - 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); - } - } -} -function isIterable(obj) { - return Array.isArray(obj) || typeof obj === "object"; -} -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -function isRegisteredKernelInvocation(kernelInvocation) { - return kernelInvocation.kernelName != null; -} -var EngineState = 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))); - } - }; - } - dispose() { - for (const variableName in this.registeredVariables) { - this.registeredVariables[variableName].dispose(); - } - } -}; -var Engine = class { - constructor(ENV5) { - this.ENV = ENV5; - this.registry = {}; - this.registryFactory = {}; - this.pendingBackendInitId = 0; - this.state = new EngineState(); - } - async ready() { - if (this.pendingBackendInit != null) { - return this.pendingBackendInit.then(() => { - }); - } - 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); - return; - } - } - throw new Error(`Could not initialize any backends, all backend initializations failed.`); - } - get backend() { - 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); - } - 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) { - return null; - } - } else { - return null; - } - } - return this.registry[backendName]; - } - findBackendFactory(backendName) { - if (!(backendName in this.registryFactory)) { - return null; - } - return this.registryFactory[backendName].factory; - } - registerBackend(backendName, factory, priority = 1) { - if (backendName in this.registryFactory) { - console.warn(`${backendName} backend was already registered. Reusing existing backend factory.`); - return false; - } - this.registryFactory[backendName] = {factory, priority}; - return 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) { - this.backendInstance = null; - const {success, asyncInit} = this.initializeBackend(backendName); - const result = asyncInit ? await success : success; - if (!result) { - return false; - } - } - this.backendInstance = this.registry[backendName]; - this.setupRegisteredKernels(); - this.profiler = new Profiler(this.backendInstance); - return true; - } - setupRegisteredKernels() { - const kernels = getKernelsForBackend(this.backendName); - kernels.forEach((kernel) => { - if (kernel.setupFunc != null) { - kernel.setupFunc(this.backendInstance); - } - }); - } - disposeRegisteredKernels(backendName) { - const kernels = getKernelsForBackend(backendName); - kernels.forEach((kernel) => { - if (kernel.disposeFunc != null) { - kernel.disposeFunc(this.registry[backendName]); - } - }); - } - initializeBackend(backendName) { - const registryFactoryEntry = this.registryFactory[backendName]; - if (registryFactoryEntry == null) { - throw new Error(`Cannot initialize backend ${backendName}, 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; - console.warn(`Initialization of backend ${backendName} failed`); - console.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) { - console.warn(`Initialization of backend ${backendName} failed`); - console.warn(err.stack || err.message); - return {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; - } - } - getSortedBackends() { - 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; - }); - } - 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}; - } - } - 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]++; - } - } - tidy(nameOrFn, fn) { - let name = null; - if (fn == null) { - if (typeof nameOrFn !== "function") { - throw new Error("Please provide a function to tidy()"); - } - fn = nameOrFn; - } else { - if (typeof nameOrFn !== "string" && !(nameOrFn instanceof String)) { - throw new Error("When calling with two arguments, the first argument to tidy() must be a string"); - } - if (typeof fn !== "function") { - throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function"); - } - name = nameOrFn; - } - 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; - }); - } - scopedRun(start, end, f) { - start(); - try { - const res = f(); - end(); - return res; - } catch (ex) { - end(); - throw ex; - } - } - nextTensorId() { - return Engine.nextTensorId++; - } - nextVariableId() { - return Engine.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; - } - runKernel(kernelName, inputs, attrs) { - 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}); - } - 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; - }); - 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}'`); - } - } - 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); - }); - if (isTapeOn) { - const tensorsToSave = this.getTensorsForGradient(kernelName, inputs2, outTensors); - saved = this.saveTensorsForBackwardMode(tensorsToSave); - } - return outTensors; - }; - } else { - const {forwardFunc} = kernelParams; - const saveFunc = (tensors) => { - if (!isTapeOn) { - return; - } - saved = tensors.map((tensor2) => this.keep(this.clone(tensor2))); - }; - 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; - }; - } - 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]; - } - saveTensorsForBackwardMode(tensors) { - const saved = tensors.map((tensor2) => this.keep(this.clone(tensor2))); - return saved; - } - 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); - } - return []; - } - makeTensor(values, shape, dtype, backend22) { - if (values == null) { - throw new Error("Values passed to engine.makeTensor() are null"); - } - 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; - } - makeTensorFromDataId(dataId, shape, dtype, backend22) { - dtype = dtype || "float32"; - const t = new Tensor(shape, dtype, dataId, this.nextTensorId()); - this.trackTensor(t, backend22); - return t; - } - 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; - } - 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); - } - } - incRef(a, backend22) { - this.trackTensor(a, backend22); - this.backend.incRef(a.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--; - } - } - disposeTensor(a) { - if (!this.state.tensorInfo.has(a.dataId)) { - return; - } - 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); - } - } - disposeVariables() { - for (const varName in this.state.registeredVariables) { - const v = this.state.registeredVariables[varName]; - this.disposeVariable(v); - } - } - disposeVariable(v) { - this.disposeTensor(v); - if (this.state.registeredVariables[v.name] != null) { - delete this.state.registeredVariables[v.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; - } - async profile(query) { - 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; - } - 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); - } - keep(result) { - result.kept = true; - return result; - } - startTape() { - if (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; - } - 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(); - } - } - 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); - } - }); - } - 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) { - 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}; - }); - } - 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; - }); - 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; - }; - 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 - }); - }; - } - readSync(dataId) { - const info2 = this.state.tensorInfo.get(dataId); - return info2.backend.readSync(dataId); - } - read(dataId) { - const info2 = this.state.tensorInfo.get(dataId); - return info2.backend.read(dataId); - } - async time(query) { - const start = now2(); - const timingInfo = await this.backend.time(query); - timingInfo.wallMs = now2() - start; - return timingInfo; - } - track(result) { - if (this.state.activeScope != null) { - result.scopeId = this.state.activeScope.id; - this.state.activeScope.track.push(result); - } - return result; - } - 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; - } -}; -Engine.nextTensorId = 0; -Engine.nextVariableId = 0; -function ones(shape) { - const values = makeOnesTypedArray(sizeFromShape(shape), "float32"); - return ENGINE.makeTensor(values, shape, "float32"); -} -function getOrMakeEngine() { - const ns = getGlobalNamespace(); - if (ns._tfengine == null) { - const environment = new Environment(ns); - ns._tfengine = new Engine(environment); - } - setEnvironmentGlobal(ns._tfengine.ENV); - setTensorTracker(() => ns._tfengine); - return ns._tfengine; -} -var ENGINE = getOrMakeEngine(); -function add(a, b) { - const inputs = {a, b}; - return ENGINE.runKernel(Add, inputs); -} -var device_util_exports = {}; -__export2(device_util_exports, { - isBrowser: () => isBrowser, - isMobile: () => isMobile -}); -/** - * @license - * Copyright 2017 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -function _isNavigatorDefined() { - return typeof navigator !== "undefined" && navigator != null; -} -function isMobile() { - if (_isNavigatorDefined()) { - const a = navigator.userAgent || navigator.vendor || window.opera; - 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 false; -} -function isBrowser() { - return typeof window !== "undefined" && window.document != null || typeof WorkerGlobalScope !== "undefined"; -} -/** - * @license - * Copyright 2019 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var 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."); - } -}); -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); -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -function inferShape(val, dtype) { - let firstElem = val; - if (isTypedArray(val)) { - return dtype === "string" ? [] : [val.length]; - } - if (!Array.isArray(val)) { - 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; -} -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`); - 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)); - } -} -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 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 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)); -} -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var 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); - 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; - } - }; - Object.defineProperty(f2, "name", {value: opName, configurable: true}); - return f2; -} -/** - * @license - * Copyright 2020 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -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); -} -var complex = op({complex_}); -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -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") { - 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 (!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); -} -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -function tensor(values, shape, dtype) { - const inferredShape = inferShape(values, dtype); - return makeTensor(values, shape, inferredShape, dtype); -} -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var DTYPE_VALUE_SIZE_MAP = { - float32: 4, - float16: 2, - int32: 4, - uint16: 2, - uint8: 1, - bool: 1, - complex64: 8 -}; -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var 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; - } - resolve(bytes); - }); - dataPromises.push(utf8bytes); - } else { - dataPromises.push(t.data()); - } - if (group != null) { - spec.group = group; - } - specs.push(spec); - } - const tensorValues = await Promise.all(dataPromises); - return {data: concatenateTypedArrays(tensorValues), specs}; -} -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; - } - } 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 (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 { - 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 image3 = new Float32Array(values.length / 2); - for (let i = 0; i < real4.length; i++) { - real4[i] = values[i * 2]; - image3[i] = values[i * 2 + 1]; - } - const realTensor = tensor(real4, shape, "float32"); - const imageTensor = tensor(image3, 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); - } - } - return out; -} -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}`); - } - }); - const y = new Uint8Array(totalByteLength); - let offset = 0; - normalizedXs.forEach((x) => { - y.set(new Uint8Array(x.buffer), offset); - offset += x.byteLength; - }); - return y.buffer; -} -var useNodeBuffer = typeof Buffer !== "undefined" && (typeof Blob === "undefined" || typeof atob === "undefined" || typeof btoa === "undefined"); -function stringByteLength(str2) { - if (useNodeBuffer) { - return Buffer.byteLength(str2); - } - return new Blob([str2]).size; -} -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 base64StringToArrayBuffer(str2) { - if (useNodeBuffer) { - const buf = Buffer.from(str2, "base64"); - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - } - const s = atob(str2); - const buffer2 = new Uint8Array(s.length); - for (let i = 0; i < s.length; ++i) { - buffer2.set([s.charCodeAt(i)], i); - } - return buffer2.buffer; -} -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 getModelArtifactsInfoForJSON(modelArtifacts) { - if (modelArtifacts.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 - }; -} -function computeFloat16MantisaTable() { - const convertMantissa = (i) => { - let m = i << 13; - let e = 0; - while ((m & 8388608) === 0) { - e -= 8388608; - m <<= 1; - } - 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); - }; -} -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var IORouterRegistry = class { - constructor() { - this.saveRouters = []; - this.loadRouters = []; - } - static getInstance() { - if (IORouterRegistry.instance == null) { - IORouterRegistry.instance = new IORouterRegistry(); - } - return IORouterRegistry.instance; - } - static registerSaveRouter(saveRouter) { - IORouterRegistry.getInstance().saveRouters.push(saveRouter); - } - static registerLoadRouter(loadRouter) { - IORouterRegistry.getInstance().loadRouters.push(loadRouter); - } - static getSaveHandlers(url) { - return IORouterRegistry.getHandlers(url, "save"); - } - static getLoadHandlers(url, loadOptions) { - return IORouterRegistry.getHandlers(url, "load", loadOptions); - } - 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; - } -}; -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); -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var 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")) { - 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) { - throw new Error("The current browser does not appear to support IndexedDB."); - } - return factory; -} -function setUpDatabase(openRequest) { - const db = openRequest.result; - db.createObjectStore(MODEL_STORE_NAME, {keyPath: "modelPath"}); - db.createObjectStore(INFO_STORE_NAME, {keyPath: "modelPath"}); -} -var BrowserIndexedDB = class { - constructor(modelPath) { - this.indexedDB = getIndexedDBFactory(); - if (modelPath == null || !modelPath) { - throw new Error("For IndexedDB, modelPath must not be null, undefined or empty."); - } - this.modelPath = modelPath; - } - async save(modelArtifacts) { - if (modelArtifacts.modelTopology instanceof ArrayBuffer) { - throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet."); - } - return this.databaseAction(this.modelPath, modelArtifacts); - } - 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(); - } 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); - }; - }; - }; - putInfoRequest.onerror = (error) => { - db.close(); - return reject(putInfoRequest.error); - }; - infoTx.oncomplete = () => { - if (modelTx == null) { - db.close(); - } else { - modelTx.oncomplete = () => db.close(); - } - }; - } - }; - openRequest.onerror = (error) => reject(openRequest.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); -} -function maybeStripScheme(key) { - return key.startsWith(BrowserIndexedDB.URL_SCHEME) ? key.slice(BrowserIndexedDB.URL_SCHEME.length) : key; -} -var BrowserIndexedDBManager = class { - constructor() { - this.indexedDB = getIndexedDBFactory(); - } - 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); - }); - } - 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); - }; - } - }; - 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); - }); - } -}; -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var 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) - }; -} -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 maybeStripScheme2(key) { - return key.startsWith(BrowserLocalStorage.URL_SCHEME) ? key.slice(BrowserLocalStorage.URL_SCHEME.length) : key; -} -var BrowserLocalStorage = class { - constructor(modelPath) { - if (!env().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) { - throw new Error("For local storage, modelPath must not be null, undefined or empty."); - } - this.modelPath = modelPath; - this.keys = getModelKeys(this.modelPath); - } - async save(modelArtifacts) { - if (modelArtifacts.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); - 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 result = { - format: modelArtifacts.format, - generatedBy: modelArtifacts.generatedBy, - convertedBy: modelArtifacts.convertedBy - }; - if (modelArtifacts.signature != null) { - result.signature = modelArtifacts.signature; - } - if (modelArtifacts.userDefinedMetadata != null) { - result.userDefinedMetadata = modelArtifacts.userDefinedMetadata; - } - if (modelArtifacts.modelInitializer != null) { - result.modelInitializer = modelArtifacts.modelInitializer; - } - this.LS.setItem(this.keys.modelMetadata, JSON.stringify(result)); - return {modelArtifactsInfo}; - } catch (err) { - this.LS.removeItem(this.keys.info); - this.LS.removeItem(this.keys.topology); - this.LS.removeItem(this.keys.weightSpecs); - this.LS.removeItem(this.keys.weightData); - this.LS.removeItem(this.keys.modelMetadata); - 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}.`); - } - } - } - async load() { - const info2 = JSON.parse(this.LS.getItem(this.keys.info)); - if (info2 == null) { - throw new Error(`In local storage, there is no model with name '${this.modelPath}'`); - } - if (info2.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) { - 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) { - throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`); - } - 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"]; - } - } - const weightDataBase64 = this.LS.getItem(this.keys.weightData); - if (weightDataBase64 == null) { - throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`); - } - out.weightData = base64StringToArrayBuffer(weightDataBase64); - return out; - } -}; -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); -} -var BrowserLocalStorageManager = 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; - } - 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)); - } - } - return out; - } - 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)); - this.LS.removeItem(keys.info); - this.LS.removeItem(keys.topology); - this.LS.removeItem(keys.weightSpecs); - this.LS.removeItem(keys.weightData); - return info2; - } -}; -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var URL_SCHEME_SUFFIX = "://"; -var ModelStoreManagerRegistry = class { - constructor() { - this.managers = {}; - } - static getInstance() { - if (ModelStoreManagerRegistry.instance == null) { - ModelStoreManagerRegistry.instance = new ModelStoreManagerRegistry(); - } - return ModelStoreManagerRegistry.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 getManager(scheme) { - const manager = this.getInstance().managers[scheme]; - if (manager == null) { - throw new Error(`Cannot find model manager for scheme '${scheme}'`); - } - return manager; - } - 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] - }; -} -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 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]; - } - } - return out; -} -async function removeModel(url) { - const schemeAndPath = parseURL(url); - const manager = ModelStoreManagerRegistry.getManager(schemeAndPath.scheme); - return manager.removeModel(schemeAndPath.path); -} -async function copyModel(sourceURL, destURL) { - const deleteSource = false; - return cloneModelInternal(sourceURL, destURL, deleteSource); -} -async function moveModel(sourceURL, destURL) { - const deleteSource = true; - return cloneModelInternal(sourceURL, destURL, deleteSource); -} -/** - * @license - * Copyright 2019 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var PlatformBrowser = class { - fetch(path, init2) { - return fetch(path, init2); - } - 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); - } - decode(bytes, encoding) { - return new TextDecoder(encoding).decode(bytes); - } -}; -if (env().get("IS_BROWSER")) { - env().setPlatform("browser", new PlatformBrowser()); - try { - ModelStoreManagerRegistry.registerManager(BrowserLocalStorage.URL_SCHEME, new BrowserLocalStorageManager()); - } catch (err) { - } - try { - ModelStoreManagerRegistry.registerManager(BrowserIndexedDB.URL_SCHEME, new BrowserIndexedDBManager()); - } catch (err) { - } -} -/** - * @license - * Copyright 2019 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var getNodeFetch = { - importFetch: () => require_browser() -}; -var systemFetch; -var PlatformNode = class { - constructor() { - this.util = require("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); - } - now() { - const time2 = process.hrtime(); - return time2[0] * 1e3 + time2[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); - } - decode(bytes, encoding) { - if (bytes.length === 0) { - return ""; - } - return new this.util.TextDecoder(encoding).decode(bytes); - } -}; -if (env().get("IS_NODE")) { - env().setPlatform("node", new PlatformNode()); -} -/** - * @license - * Copyright 2020 Google Inc. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -function buffer(shape, dtype = "float32", values) { - dtype = dtype || "float32"; - assertNonNegativeIntegerDimensions(shape); - return new TensorBuffer(shape, dtype, values); -} -/** - * @license - * Copyright 2020 Google Inc. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -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") { - throw new Error("Only strings can be casted to strings"); - } - const inputs = {x: $x}; - const attrs = {dtype}; - return ENGINE.runKernel(Cast, inputs, attrs); -} -var cast = op({cast_}); -/** - * @license - * Copyright 2020 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -function clone_(x) { - const $x = convertToTensor(x, "x", "clone", "string_or_numeric"); - const inputs = {x: $x}; - return ENGINE.runKernel(Identity, inputs); -} -var clone = op({clone_}); -/** - * @license - * Copyright 2020 Google Inc. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -function print2(x, verbose = false) { - console.log(x.toString(verbose)); -} -/** - * @license - * Copyright 2020 Google Inc. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -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, - getModelArtifactsInfoForJSON: () => getModelArtifactsInfoForJSON, - getSaveHandlers: () => getSaveHandlers, - http: () => http, - isHTTPScheme: () => isHTTPScheme, - listModels: () => listModels, - loadWeights: () => loadWeights, - moveModel: () => moveModel, - registerLoadRouter: () => registerLoadRouter, - registerSaveRouter: () => registerSaveRouter, - removeModel: () => removeModel, - weightsLoaderFactory: () => weightsLoaderFactory, - withSaveHandler: () => withSaveHandler -}); -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var 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); -} -var BrowserDownloads = class { - constructor(fileNamePrefix) { - if (!env().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.modelTopologyFileName = fileNamePrefix + DEFAULT_JSON_EXTENSION_NAME; - this.weightDataFileName = fileNamePrefix + DEFAULT_WEIGHT_DATA_EXTENSION_NAME; - } - async save(modelArtifacts) { - 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) { - 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 modelTopologyAndWeightManifest = { - modelTopology: modelArtifacts.modelTopology, - format: modelArtifacts.format, - generatedBy: modelArtifacts.generatedBy, - convertedBy: modelArtifacts.convertedBy, - weightsManifest - }; - if (modelArtifacts.signature != null) { - modelTopologyAndWeightManifest.signature = modelArtifacts.signature; - } - if (modelArtifacts.userDefinedMetadata != null) { - modelTopologyAndWeightManifest.userDefinedMetadata = modelArtifacts.userDefinedMetadata; - } - if (modelArtifacts.modelInitializer != null) { - modelTopologyAndWeightManifest.modelInitializer = modelArtifacts.modelInitializer; - } - const modelTopologyAndWeightManifestURL = window.URL.createObjectURL(new Blob([JSON.stringify(modelTopologyAndWeightManifest)], {type: "application/json"})); - const jsonAnchor = this.jsonAnchor == null ? document.createElement("a") : this.jsonAnchor; - jsonAnchor.download = this.modelTopologyFileName; - jsonAnchor.href = modelTopologyAndWeightManifestURL; - 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"))); - } - return {modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts)}; - } - } -}; -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.files = files; - } - async load() { - const jsonFile = this.files[0]; - const weightFiles = this.files.slice(1); - 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 ${jsonFile.name}`)); - return; - } - if (weightFiles.length === 0) { - resolve({modelTopology}); - } - const weightsManifest = modelJSON.weightsManifest; - if (weightsManifest == null) { - reject(new Error(`weightManifest field is missing from file ${jsonFile.name}`)); - return; - } - let pathToFile; - try { - pathToFile = this.checkManifestAndWeightFiles(weightsManifest, weightFiles); - } catch (err) { - reject(err); - return; - } - const weightSpecs = []; - const paths = []; - const perFileBuffers = []; - weightsManifest.forEach((weightsGroup) => { - weightsGroup.paths.forEach((path) => { - paths.push(path); - perFileBuffers.push(null); - }); - weightSpecs.push(...weightsGroup.weights); - }); - weightsManifest.forEach((weightsGroup) => { - weightsGroup.paths.forEach((path) => { - const weightFileReader = new FileReader(); - weightFileReader.onload = (event2) => { - const weightData = event2.target.result; - const index = paths.indexOf(path); - perFileBuffers[index] = weightData; - if (perFileBuffers.indexOf(null) === -1) { - const result = { - modelTopology, - weightSpecs, - weightData: concatenateArrayBuffers(perFileBuffers), - format: modelJSON.format, - generatedBy: modelJSON.generatedBy, - convertedBy: modelJSON.convertedBy - }; - if (modelJSON.signature != null) { - result.signature = modelJSON.signature; - } - if (modelJSON.userDefinedMetadata != null) { - result.userDefinedMetadata = modelJSON.userDefinedMetadata; - } - if (modelJSON.modelInitializer != null) { - result.modelInitializer = modelJSON.modelInitializer; - } - resolve(result); - } - }; - weightFileReader.onerror = (error) => reject(`Failed to weights data from file of path '${path}'.`); - weightFileReader.readAsArrayBuffer(pathToFile[path]); - }); - }); - }; - jsonReader.onerror = (error) => reject(`Failed to read model topology and weights manifest JSON from file '${jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`); - jsonReader.readAsText(jsonFile); - }); - } - checkManifestAndWeightFiles(manifest, files) { - const basenames = []; - const fileNames = files.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] = files[fileNames.indexOf(pathBasename)]; - } - }); - } - if (basenames.length !== files.length) { - throw new Error(`Mismatch in the number of files in weights manifest (${basenames.length}) and the number of weight files provided (${files.length}).`); - } - return pathToFile; - } -}; -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; - } - } -}; -IORouterRegistry.registerSaveRouter(browserDownloadsRouter); -function browserDownloads(fileNamePrefix = "model") { - return new BrowserDownloads(fileNamePrefix); -} -function browserFiles(files) { - return new BrowserFiles(files); -} -/** - * @license - * Copyright 2019 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -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 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)); -} -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -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 loadWeights(manifest, filePathPrefix = "", weightNames, requestInit) { - const fetchWeights = (fetchUrls) => loadWeightsAsArrayBuffer(fetchUrls, {requestInit}); - const loadWeights2 = weightsLoaderFactory(fetchWeights); - return loadWeights2(manifest, filePathPrefix, weightNames); -} -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 - }); - }; - if (weightNames != null) { - weightNames.forEach((weightName, weightIndex) => { - if (weightName === weightsEntry.name) { - enqueueWeightsForFetchingFn(); - weightsFound[weightIndex] = true; - } - }); - } else { - enqueueWeightsForFetchingFn(); - } - allManifestWeightNames.push(weightsEntry.name); - groupOffset += weightsBytes; - }); - }); - 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(", ")}.`); - } - 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); - }); - }); - 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; - } - 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; - }; -} -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var 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) { - throw new Error("requestInit is expected to have no pre-existing body, but has one."); - } - this.requestInit = loadOptions.requestInit || {}; - } - async save(modelArtifacts) { - if (modelArtifacts.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 = { - modelTopology: modelArtifacts.modelTopology, - format: modelArtifacts.format, - generatedBy: modelArtifacts.generatedBy, - convertedBy: modelArtifacts.convertedBy, - weightsManifest - }; - if (modelArtifacts.signature != null) { - modelTopologyAndWeightManifest.signature = modelArtifacts.signature; - } - if (modelArtifacts.userDefinedMetadata != null) { - modelTopologyAndWeightManifest.userDefinedMetadata = modelArtifacts.userDefinedMetadata; - } - if (modelArtifacts.modelInitializer != null) { - modelTopologyAndWeightManifest.modelInitializer = modelArtifacts.modelInitializer; - } - 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}.`); - } - } - 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 modelConfig; - try { - modelConfig = 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); - } - const modelTopology = modelConfig.modelTopology; - const weightsManifest = modelConfig.weightsManifest; - const generatedBy = modelConfig.generatedBy; - const convertedBy = modelConfig.convertedBy; - const format = modelConfig.format; - const signature = modelConfig.signature; - const userDefinedMetadata = modelConfig.userDefinedMetadata; - if (modelTopology == null && weightsManifest == null) { - throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`); - } - let weightSpecs; - let weightData; - if (weightsManifest != null) { - const results = await this.loadWeights(weightsManifest); - [weightSpecs, weightData] = results; - } - const artifacts = { - modelTopology, - weightSpecs, - weightData, - generatedBy, - convertedBy, - format - }; - if (signature != null) { - artifacts.signature = signature; - } - if (userDefinedMetadata != null) { - artifacts.userDefinedMetadata = userDefinedMetadata; - } - const initializer = modelConfig.modelInitializer; - if (initializer) { - artifacts.modelInitializer = initializer; - } - return artifacts; - } - 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)]; - } -}; -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]; -} -function isHTTPScheme(url) { - return url.match(HTTPRequest.URL_SCHEME_REGEX) != null; -} -var httpRouter = (url, loadOptions) => { - if (typeof fetch === "undefined" && (loadOptions == null || loadOptions.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); - } - } - return null; -}; -IORouterRegistry.registerSaveRouter(httpRouter); -IORouterRegistry.registerLoadRouter(httpRouter); -function http(path, loadOptions) { - return new HTTPRequest(path, loadOptions); -} -function browserHTTPRequest(path, loadOptions) { - return http(path, loadOptions); -} -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var PassthroughLoader = class { - constructor(modelArtifacts) { - this.modelArtifacts = modelArtifacts; - } - async load() { - return this.modelArtifacts; - } -}; -var PassthroughSaver = class { - constructor(saveHandler) { - this.saveHandler = saveHandler; - } - async save(modelArtifacts) { - return this.saveHandler(modelArtifacts); - } -}; -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 withSaveHandler(saveHandler) { - return new PassthroughSaver(saveHandler); -} -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var math_exports = {}; -__export2(math_exports, { - confusionMatrix: () => confusionMatrix -}); -/** - * @license - * Copyright 2020 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -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 matMul = op({matMul_}); -/** - * @license - * Copyright 2020 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -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 oneHot = op({oneHot_}); -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -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 transpose = op({transpose_}); -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -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 confusionMatrix = op({confusionMatrix_}); -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var browser_exports = {}; -__export2(browser_exports, { - fromPixels: () => fromPixels, - fromPixelsAsync: () => fromPixelsAsync, - toPixels: () => toPixels -}); -/** - * @license - * Copyright 2018 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -function tensor3d(values, shape, dtype) { - assertNonNull(values); - if (shape != null && shape.length !== 3) { - throw new Error("tensor3d() requires shape to have three numbers"); - } - const inferredShape = inferShape(values, dtype); - if (inferredShape.length !== 3 && inferredShape.length !== 1) { - throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray"); - } - if (inferredShape.length === 1 && shape == null) { - throw new Error("tensor3d() requires shape to be provided when `values` are a flat array"); - } - return makeTensor(values, shape, inferredShape, dtype); -} -/** - * @license - * Copyright 2019 Google LLC. All Rights Reserved. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============================================================================= - */ -var fromPixels2DContext; -function fromPixels_(pixels, numChannels = 3) { - if (numChannels > 4) { - throw new Error("Cannot construct Tensor with more than 4 channels from pixels."); - } - if (pixels == 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) { - throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the