diff --git a/build.json b/.build.json similarity index 99% rename from build.json rename to .build.json index 8665acea..01eb0702 100644 --- a/build.json +++ b/.build.json @@ -128,6 +128,7 @@ "input": "src/human.ts", "output": "dist/human.custom.esm.js", "sourcemap": true, + "minify": true, "external": ["fs", "os", "buffer", "util"] }, diff --git a/CHANGELOG.md b/CHANGELOG.md index 68b9e9fc..cb26bfc9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,9 +11,9 @@ ### **HEAD -> main** 2021/10/22 mandic00@live.com - -### **origin/main** 2021/10/22 mandic00@live.com - +- initial work on skiptime +- added generic types +- enhanced typing exports - add optional autodetected custom wasm path ### **2.3.6** 2021/10/21 mandic00@live.com diff --git a/dist/human.custom.esm.js b/dist/human.custom.esm.js index 0dee07f5..4f068824 100644 --- a/dist/human.custom.esm.js +++ b/dist/human.custom.esm.js @@ -4,46194 +4,61 @@ author: ' */ -var __defProp = Object.defineProperty; -var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __markAsModule = (target) => __defProp(target, "__esModule", { value: true }); -var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { - get: (a, b) => (typeof require !== "undefined" ? require : a)[b] -}) : x)(function(x) { - if (typeof require !== "undefined") - return require.apply(this, arguments); - throw new Error('Dynamic require of "' + x + '" is not supported'); -}); -var __export = (target, all6) => { - __markAsModule(target); - for (var name in all6) - __defProp(target, name, { get: all6[name], enumerable: true }); -}; -var __publicField = (obj, key, value) => { - __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); - return value; -}; -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 __privateAdd = (obj, member, value) => { - if (member.has(obj)) - throw TypeError("Cannot add the same private member more than once"); - member instanceof WeakSet ? member.add(obj) : member.set(obj, value); -}; -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/util/util.ts -function join(folder, file) { - const separator = folder.endsWith("/") ? "" : "/"; - const skipJoin = file.startsWith(".") || file.startsWith("/") || file.startsWith("http:") || file.startsWith("https:") || file.startsWith("file:"); - const path = skipJoin ? `${file}` : `${folder}${separator}${file}`; - if (!path.toLocaleLowerCase().includes(".json")) - throw new Error(`modelpath error: ${path} expecting json file`); - return path; -} -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 validate(defaults, config3, parent = "config", msgs = []) { - for (const key of Object.keys(config3)) { - if (typeof config3[key] === "object") { - validate(defaults[key], config3[key], key, msgs); - } else { - const defined = defaults && typeof defaults[key] !== "undefined"; - if (!defined) - msgs.push({ reason: "unknown property", where: `${parent}.${key} = ${config3[key]}` }); - const same = defaults && typeof defaults[key] === typeof config3[key]; - if (defined && !same) - msgs.push({ reason: "property type mismatch", where: `${parent}.${key} = ${config3[key]}`, expected: typeof defaults[key] }); - } - } - if (config3.debug && parent === "config" && msgs.length > 0) - log("invalid configuration", msgs); - return msgs; -} -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/config.ts -var config = { - backend: "", - modelBasePath: "", - wasmPath: "", - debug: true, - async: true, - warmup: "full", - cacheSensitivity: 0.75, - skipFrame: false, - filter: { - enabled: true, - width: 0, - height: 0, - flip: false, - return: true, - brightness: 0, - contrast: 0, - sharpness: 0, - blur: 0, - saturation: 0, - hue: 0, - negative: false, - sepia: false, - vintage: false, - kodachrome: false, - technicolor: false, - polaroid: false, - pixelate: 0 - }, - gesture: { - enabled: true - }, - face: { - enabled: true, - detector: { - modelPath: "blazeface.json", - rotation: true, - maxDetected: 1, - skipFrames: 11, - skipTime: 2e3, - minConfidence: 0.2, - iouThreshold: 0.1, - return: false - }, - mesh: { - enabled: true, - modelPath: "facemesh.json" - }, - iris: { - enabled: true, - modelPath: "iris.json" - }, - emotion: { - enabled: true, - minConfidence: 0.1, - skipFrames: 12, - skipTime: 2e3, - modelPath: "emotion.json" - }, - description: { - enabled: true, - modelPath: "faceres.json", - skipFrames: 13, - skipTime: 2e3, - minConfidence: 0.1 - }, - antispoof: { - enabled: false, - skipFrames: 14, - skipTime: 2e3, - modelPath: "antispoof.json" - } - }, - body: { - enabled: true, - modelPath: "movenet-lightning.json", - detector: { - modelPath: "" - }, - maxDetected: -1, - minConfidence: 0.3, - skipFrames: 1, - skipTime: 2e3 - }, - hand: { - enabled: true, - rotation: true, - skipFrames: 2, - skipTime: 2e3, - minConfidence: 0.5, - iouThreshold: 0.2, - maxDetected: -1, - landmarks: true, - detector: { - modelPath: "handtrack.json" - }, - skeleton: { - modelPath: "handskeleton.json" - } - }, - object: { - enabled: false, - modelPath: "mb3-centernet.json", - minConfidence: 0.2, - iouThreshold: 0.4, - maxDetected: 10, - skipFrames: 15, - skipTime: 2e3 - }, - segmentation: { - enabled: false, - modelPath: "selfie.json", - blur: 8 - } -}; - -// 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: () => BackendWasm67, - BatchMatMul: () => BatchMatMul, - BatchToSpaceND: () => BatchToSpaceND, - Bincount: () => Bincount, - BroadcastArgs: () => BroadcastArgs, - BroadcastTo: () => BroadcastTo, - Callback: () => Callback, - CallbackList: () => CallbackList, - Cast: () => Cast, - Ceil: () => Ceil, - ClipByValue: () => ClipByValue, - Complex: () => Complex, - ComplexAbs: () => ComplexAbs, - Concat: () => Concat, - Conv2D: () => Conv2D, - Conv2DBackpropFilter: () => Conv2DBackpropFilter, - Conv2DBackpropInput: () => Conv2DBackpropInput, - Conv3D: () => Conv3D, - Conv3DBackpropFilterV2: () => Conv3DBackpropFilterV2, - Conv3DBackpropInputV2: () => Conv3DBackpropInputV2, - Cos: () => Cos, - Cosh: () => Cosh, - CropAndResize: () => CropAndResize, - Cumsum: () => Cumsum, - CustomCallback: () => CustomCallback, - DataStorage: () => DataStorage, - DenseBincount: () => DenseBincount, - DepthToSpace: () => DepthToSpace, - DepthwiseConv2dNative: () => DepthwiseConv2dNative, - DepthwiseConv2dNativeBackpropFilter: () => DepthwiseConv2dNativeBackpropFilter, - DepthwiseConv2dNativeBackpropInput: () => DepthwiseConv2dNativeBackpropInput, - Diag: () => Diag, - Dilation2D: () => Dilation2D, - Dilation2DBackpropFilter: () => Dilation2DBackpropFilter, - Dilation2DBackpropInput: () => Dilation2DBackpropInput, - ENV: () => ENV, - EarlyStopping: () => EarlyStopping, - Einsum: () => Einsum, - Elu: () => Elu, - EluGrad: () => EluGrad, - Environment: () => Environment, - Equal: () => Equal, - Erf: () => Erf, - Exp: () => Exp, - ExpandDims: () => ExpandDims, - Expm1: () => Expm1, - FFT: () => FFT, - Fill: () => Fill, - FlipLeftRight: () => FlipLeftRight, - Floor: () => Floor, - FloorDiv: () => FloorDiv, - FromPixels: () => FromPixels, - FusedBatchNorm: () => FusedBatchNorm, - FusedConv2D: () => FusedConv2D, - FusedDepthwiseConv2D: () => FusedDepthwiseConv2D, - GPGPUContext: () => GPGPUContext2, - 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: () => LayerVariable2, - 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: () => Rank2, - Real: () => Real, - RealDiv: () => RealDiv, - Reciprocal: () => Reciprocal, - Reduction: () => Reduction, - Relu: () => Relu, - Relu6: () => Relu6, - Reshape: () => Reshape, - ResizeBilinear: () => ResizeBilinear, - ResizeBilinearGrad: () => ResizeBilinearGrad, - ResizeNearestNeighbor: () => ResizeNearestNeighbor, - ResizeNearestNeighborGrad: () => ResizeNearestNeighborGrad, - Reverse: () => Reverse, - RotateWithOffset: () => RotateWithOffset, - Round: () => Round, - Rsqrt: () => Rsqrt, - SGDOptimizer: () => SGDOptimizer, - ScatterNd: () => ScatterNd, - Select: () => Select, - Selu: () => Selu, - Sequential: () => Sequential, - Sigmoid: () => Sigmoid, - Sign: () => Sign, - Sin: () => Sin, - Sinh: () => Sinh, - Slice: () => Slice, - Softmax: () => Softmax, - Softplus: () => Softplus, - SpaceToBatchND: () => SpaceToBatchND, - SparseFillEmptyRows: () => SparseFillEmptyRows, - SparseReshape: () => SparseReshape, - SparseSegmentMean: () => SparseSegmentMean, - SparseSegmentSum: () => SparseSegmentSum, - SparseToDense: () => SparseToDense, - SplitV: () => SplitV, - Sqrt: () => Sqrt, - Square: () => Square, - SquaredDifference: () => SquaredDifference, - Step: () => Step, - StridedSlice: () => StridedSlice, - StringNGrams: () => StringNGrams, - StringSplit: () => StringSplit, - StringToHashBucketFast: () => StringToHashBucketFast, - Sub: () => Sub, - Sum: () => Sum, - SymbolicTensor: () => SymbolicTensor, - Tan: () => Tan, - Tanh: () => Tanh, - Tensor: () => Tensor4, - TensorBuffer: () => TensorBuffer, - Tile: () => Tile, - TopK: () => TopK, - Transform: () => Transform, - Transpose: () => Transpose, - Unique: () => Unique, - Unpack: () => Unpack, - UnsortedSegmentSum: () => UnsortedSegmentSum, - Variable: () => Variable, - ZerosLike: () => ZerosLike, - _FusedMatMul: () => _FusedMatMul, - abs: () => abs, - acos: () => acos, - acosh: () => acosh, - add: () => add2, - addN: () => addN, - all: () => all, - any: () => any, - argMax: () => argMax, - argMin: () => argMin, - asin: () => asin, - asinh: () => asinh, - atan: () => atan, - atan2: () => atan2, - atanh: () => atanh, - avgPool: () => avgPool, - avgPool3d: () => avgPool3d, - backend: () => backend, - backend_util: () => backend_util_exports, - basicLSTMCell: () => basicLSTMCell, - batchNorm: () => batchNorm, - batchNorm2d: () => batchNorm2d, - batchNorm3d: () => batchNorm3d, - batchNorm4d: () => batchNorm4d, - batchToSpaceND: () => batchToSpaceND, - bincount: () => bincount, - booleanMaskAsync: () => booleanMaskAsync, - broadcastArgs: () => broadcastArgs, - broadcastTo: () => broadcastTo, - browser: () => browser_exports, - buffer: () => buffer, - callbacks: () => callbacks, - cast: () => cast, - ceil: () => ceil, - clipByValue: () => clipByValue, - clone: () => clone, - complex: () => complex, - concat: () => concat, - concat1d: () => concat1d, - concat2d: () => concat2d, - concat3d: () => concat3d, - concat4d: () => concat4d, - constraints: () => exports_constraints_exports, - conv1d: () => conv1d, - conv2d: () => conv2d, - conv2dTranspose: () => conv2dTranspose, - conv3d: () => conv3d, - conv3dTranspose: () => conv3dTranspose, - copyRegisteredKernels: () => copyRegisteredKernels, - cos: () => cos, - cosh: () => cosh, - cosineWindow: () => cosineWindow, - cumsum: () => cumsum, - customGrad: () => customGrad, - data: () => src_exports, - denseBincount: () => denseBincount, - deprecationWarn: () => deprecationWarn, - depthToSpace: () => depthToSpace, - depthwiseConv2d: () => depthwiseConv2d, - deregisterOp: () => deregisterOp, - device_util: () => device_util_exports, - diag: () => diag, - dilation2d: () => dilation2d, - disableDeprecationWarnings: () => disableDeprecationWarnings, - dispose: () => dispose, - disposeVariables: () => disposeVariables, - div: () => div, - divNoNan: () => divNoNan, - dot: () => dot, - dropout: () => dropout, - einsum: () => einsum, - elu: () => elu, - enableDebugMode: () => enableDebugMode, - enableProdMode: () => enableProdMode, - enclosingPowerOfTwo: () => enclosingPowerOfTwo, - engine: () => engine, - env: () => env, - equal: () => equal, - erf: () => erf, - exp: () => exp, - expandDims: () => expandDims, - expm1: () => expm1, - eye: () => eye, - fft: () => fft, - fill: () => fill, - findBackend: () => findBackend, - findBackendFactory: () => findBackendFactory, - floor: () => floor, - floorDiv: () => floorDiv, - forceHalfFloat: () => forceHalfFloat, - fused: () => fused_ops_exports, - gather: () => gather, - gatherND: () => gatherND, - gather_util: () => gather_nd_util_exports, - getBackend: () => getBackend, - getGradient: () => getGradient, - getKernel: () => getKernel, - getKernelsForBackend: () => getKernelsForBackend, - getThreadsCount: () => getThreadsCount, - gpgpu_util: () => gpgpu_util_exports, - grad: () => grad, - grads: () => grads, - greater: () => greater, - greaterEqual: () => greaterEqual, - ifft: () => ifft, - imag: () => imag, - image: () => image, - inTopKAsync: () => inTopKAsync, - initializers: () => exports_initializers_exports, - input: () => input, - io: () => io_exports, - irfft: () => irfft, - isFinite: () => isFinite2, - isInf: () => isInf, - isNaN: () => isNaN2, - keep: () => keep, - kernel_impls: () => kernel_impls_exports, - layers: () => exports_layers_exports, - leakyRelu: () => leakyRelu, - less: () => less, - lessEqual: () => lessEqual, - linalg: () => linalg, - linspace: () => linspace, - loadGraphModel: () => loadGraphModel, - loadLayersModel: () => loadLayersModel, - localResponseNormalization: () => localResponseNormalization, - log: () => log5, - log1p: () => log1p, - logSigmoid: () => logSigmoid, - logSoftmax: () => logSoftmax, - logSumExp: () => logSumExp, - logicalAnd: () => logicalAnd, - logicalNot: () => logicalNot, - logicalOr: () => logicalOr, - logicalXor: () => logicalXor, - losses: () => losses, - matMul: () => matMul, - math: () => math_exports, - max: () => max, - maxPool: () => maxPool, - maxPool3d: () => maxPool3d, - maxPoolWithArgmax: () => maxPoolWithArgmax, - maximum: () => maximum, - mean: () => mean, - memory: () => memory, - meshgrid: () => meshgrid, - metrics: () => exports_metrics_exports, - min: () => min, - minimum: () => minimum, - mirrorPad: () => mirrorPad, - mod: () => mod, - model: () => model, - models: () => exports_models_exports, - moments: () => moments, - movingAverage: () => movingAverage, - mul: () => mul, - multiRNNCell: () => multiRNNCell, - multinomial: () => multinomial, - neg: () => neg, - nextFrame: () => nextFrame, - norm: () => norm, - notEqual: () => notEqual, - oneHot: () => oneHot, - ones: () => ones2, - onesLike: () => onesLike, - op: () => op, - outerProduct: () => outerProduct, - pad: () => pad, - pad1d: () => pad1d, - pad2d: () => pad2d, - pad3d: () => pad3d, - pad4d: () => pad4d, - pool: () => pool, - pow: () => pow, - prelu: () => prelu, - print: () => print2, - prod: () => prod, - profile: () => profile, - rand: () => rand, - randomGamma: () => randomGamma, - randomNormal: () => randomNormal, - randomUniform: () => randomUniform, - range: () => range, - ready: () => ready, - real: () => real, - reciprocal: () => reciprocal, - registerBackend: () => registerBackend, - registerCallbackConstructor: () => registerCallbackConstructor, - registerGradient: () => registerGradient, - registerKernel: () => registerKernel, - registerOp: () => registerOp, - regularizers: () => exports_regularizers_exports, - relu: () => relu, - relu6: () => relu6, - removeBackend: () => removeBackend, - reshape: () => reshape, - reverse: () => reverse, - reverse1d: () => reverse1d, - reverse2d: () => reverse2d, - reverse3d: () => reverse3d, - reverse4d: () => reverse4d, - rfft: () => rfft, - round: () => round2, - rsqrt: () => rsqrt, - scalar: () => scalar, - scatterND: () => scatterND, - scatter_util: () => scatter_nd_util_exports, - selu: () => selu, - separableConv2d: () => separableConv2d, - sequential: () => sequential, - serialization: () => serialization_exports, - setBackend: () => setBackend, - setPlatform: () => setPlatform, - setThreadsCount: () => setThreadsCount, - setWasmPath: () => setWasmPath, - setWasmPaths: () => setWasmPaths, - setWebGLContext: () => setWebGLContext, - setdiff1dAsync: () => setdiff1dAsync, - shared: () => shared_exports, - sigmoid: () => sigmoid, - sign: () => sign, - signal: () => signal, - sin: () => sin, - sinh: () => sinh, - slice: () => slice, - slice1d: () => slice1d, - slice2d: () => slice2d, - slice3d: () => slice3d, - slice4d: () => slice4d, - slice_util: () => slice_util_exports, - softmax: () => softmax, - softplus: () => softplus, - spaceToBatchND: () => spaceToBatchND, - sparse: () => sparse, - sparseToDense: () => sparseToDense, - spectral: () => spectral, - split: () => split, - sqrt: () => sqrt, - square: () => square, - squaredDifference: () => squaredDifference, - squeeze: () => squeeze, - stack: () => stack, - step: () => step, - stridedSlice: () => stridedSlice, - string: () => string, - sub: () => sub, - sum: () => sum2, - sumOutType: () => sumOutType, - tan: () => tan, - tanh: () => tanh2, - tensor: () => tensor, - tensor1d: () => tensor1d, - tensor2d: () => tensor2d, - tensor3d: () => tensor3d, - tensor4d: () => tensor4d, - tensor5d: () => tensor5d, - tensor6d: () => tensor6d, - tensor_util: () => tensor_util_exports, - test_util: () => test_util_exports, - tidy: () => tidy, - tile: () => tile, - time: () => time, - topk: () => topk, - train: () => train, - transpose: () => transpose, - truncatedNormal: () => truncatedNormal, - unique: () => unique, - unregisterGradient: () => unregisterGradient, - unregisterKernel: () => unregisterKernel, - unsortedSegmentSum: () => unsortedSegmentSum, - unstack: () => unstack, - upcastType: () => upcastType, - util: () => util_exports, - valueAndGrad: () => valueAndGrad, - valueAndGrads: () => valueAndGrads, - variable: () => variable, - variableGrads: () => variableGrads, - version: () => version8, - version_converter: () => version3, - version_core: () => version_core, - version_cpu: () => version5, - version_layers: () => version2, - version_wasm: () => version7, - version_webgl: () => version6, - webgl: () => webgl, - webgl_util: () => webgl_util_exports, - webgpu: () => webgpu_exports, - where: () => where, - whereAsync: () => whereAsync, - zeros: () => zeros, - zerosLike: () => zerosLike -}); -var __require2 = ((x) => typeof __require !== "undefined" ? __require : typeof Proxy !== "undefined" ? new Proxy(x, { - get: (a, b) => (typeof __require !== "undefined" ? __require : a)[b] -}) : x)(function(x) { - if (typeof __require !== "undefined") - return __require.apply(this, arguments); - throw new Error('Dynamic require of "' + x + '" is not supported'); -}); -var __create = Object.create; -var __defProp2 = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __markAsModule2 = (target) => __defProp2(target, "__esModule", { value: true }); -var __require22 = ((x) => typeof __require2 !== "undefined" ? __require2 : typeof Proxy !== "undefined" ? new Proxy(x, { - get: (a, b) => (typeof __require2 !== "undefined" ? __require2 : a)[b] -}) : x)(function(x) { - if (typeof __require2 !== "undefined") - return __require2.apply(this, arguments); - throw new Error('Dynamic require of "' + x + '" is not supported'); -}); -var __commonJS = (cb, mod4) => function __require222() { - return mod4 || (0, cb[Object.keys(cb)[0]])((mod4 = { exports: {} }).exports, mod4), mod4.exports; -}; -var __export2 = (target, all52) => { - __markAsModule2(target); - for (var name in all52) - __defProp2(target, name, { get: all52[name], enumerable: true }); -}; -var __reExport = (target, module, desc) => { - if (module && typeof module === "object" || typeof module === "function") { - for (let key of __getOwnPropNames(module)) - if (!__hasOwnProp.call(target, key) && key !== "default") - __defProp2(target, key, { get: () => module[key], enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable }); - } - return target; -}; -var __toModule = (module) => { - return __reExport(__markAsModule2(__defProp2(module != null ? __create(__getProtoOf(module)) : {}, "default", module && module.__esModule && "default" in module ? { get: () => module.default, enumerable: true } : { value: module, enumerable: true })), module); -}; -var require_long = __commonJS({ - "node_modules/.pnpm/long@4.0.0/node_modules/long/src/long.js"(exports, module) { - module.exports = Long2; - var wasm = null; - try { - wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([ - 0, - 97, - 115, - 109, - 1, - 0, - 0, - 0, - 1, - 13, - 2, - 96, - 0, - 1, - 127, - 96, - 4, - 127, - 127, - 127, - 127, - 1, - 127, - 3, - 7, - 6, - 0, - 1, - 1, - 1, - 1, - 1, - 6, - 6, - 1, - 127, - 1, - 65, - 0, - 11, - 7, - 50, - 6, - 3, - 109, - 117, - 108, - 0, - 1, - 5, - 100, - 105, - 118, - 95, - 115, - 0, - 2, - 5, - 100, - 105, - 118, - 95, - 117, - 0, - 3, - 5, - 114, - 101, - 109, - 95, - 115, - 0, - 4, - 5, - 114, - 101, - 109, - 95, - 117, - 0, - 5, - 8, - 103, - 101, - 116, - 95, - 104, - 105, - 103, - 104, - 0, - 0, - 10, - 191, - 1, - 6, - 4, - 0, - 35, - 0, - 11, - 36, - 1, - 1, - 126, - 32, - 0, - 173, - 32, - 1, - 173, - 66, - 32, - 134, - 132, - 32, - 2, - 173, - 32, - 3, - 173, - 66, - 32, - 134, - 132, - 126, - 34, - 4, - 66, - 32, - 135, - 167, - 36, - 0, - 32, - 4, - 167, - 11, - 36, - 1, - 1, - 126, - 32, - 0, - 173, - 32, - 1, - 173, - 66, - 32, - 134, - 132, - 32, - 2, - 173, - 32, - 3, - 173, - 66, - 32, - 134, - 132, - 127, - 34, - 4, - 66, - 32, - 135, - 167, - 36, - 0, - 32, - 4, - 167, - 11, - 36, - 1, - 1, - 126, - 32, - 0, - 173, - 32, - 1, - 173, - 66, - 32, - 134, - 132, - 32, - 2, - 173, - 32, - 3, - 173, - 66, - 32, - 134, - 132, - 128, - 34, - 4, - 66, - 32, - 135, - 167, - 36, - 0, - 32, - 4, - 167, - 11, - 36, - 1, - 1, - 126, - 32, - 0, - 173, - 32, - 1, - 173, - 66, - 32, - 134, - 132, - 32, - 2, - 173, - 32, - 3, - 173, - 66, - 32, - 134, - 132, - 129, - 34, - 4, - 66, - 32, - 135, - 167, - 36, - 0, - 32, - 4, - 167, - 11, - 36, - 1, - 1, - 126, - 32, - 0, - 173, - 32, - 1, - 173, - 66, - 32, - 134, - 132, - 32, - 2, - 173, - 32, - 3, - 173, - 66, - 32, - 134, - 132, - 130, - 34, - 4, - 66, - 32, - 135, - 167, - 36, - 0, - 32, - 4, - 167, - 11 - ])), {}).exports; - } catch (e) { - } - function Long2(low, high, unsigned) { - this.low = low | 0; - this.high = high | 0; - this.unsigned = !!unsigned; - } - Long2.prototype.__isLong__; - Object.defineProperty(Long2.prototype, "__isLong__", { value: true }); - function isLong(obj) { - return (obj && obj["__isLong__"]) === true; - } - Long2.isLong = isLong; - var INT_CACHE = {}; - var UINT_CACHE = {}; - function fromInt(value, unsigned) { - var obj, cachedObj, cache6; - if (unsigned) { - value >>>= 0; - if (cache6 = 0 <= value && value < 256) { - cachedObj = UINT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true); - if (cache6) - UINT_CACHE[value] = obj; - return obj; - } else { - value |= 0; - if (cache6 = -128 <= value && value < 128) { - cachedObj = INT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = fromBits(value, value < 0 ? -1 : 0, false); - if (cache6) - INT_CACHE[value] = obj; - return obj; - } - } - Long2.fromInt = fromInt; - function fromNumber(value, unsigned) { - if (isNaN(value)) - return unsigned ? UZERO : ZERO; - if (unsigned) { - if (value < 0) - return UZERO; - if (value >= TWO_PWR_64_DBL) - return MAX_UNSIGNED_VALUE; - } else { - if (value <= -TWO_PWR_63_DBL) - return MIN_VALUE; - if (value + 1 >= TWO_PWR_63_DBL) - return MAX_VALUE; - } - if (value < 0) - return fromNumber(-value, unsigned).neg(); - return fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned); - } - Long2.fromNumber = fromNumber; - function fromBits(lowBits, highBits, unsigned) { - return new Long2(lowBits, highBits, unsigned); - } - Long2.fromBits = fromBits; - var pow_dbl = Math.pow; - function fromString(str, unsigned, radix) { - if (str.length === 0) - throw Error("empty string"); - if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity") - return ZERO; - if (typeof unsigned === "number") { - radix = unsigned, unsigned = false; - } else { - unsigned = !!unsigned; - } - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw RangeError("radix"); - var p2; - if ((p2 = str.indexOf("-")) > 0) - throw Error("interior hyphen"); - else if (p2 === 0) { - return fromString(str.substring(1), unsigned, radix).neg(); - } - var radixToPower = fromNumber(pow_dbl(radix, 8)); - var result = ZERO; - for (var i = 0; i < str.length; i += 8) { - var size2 = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size2), radix); - if (size2 < 8) { - var power = fromNumber(pow_dbl(radix, size2)); - result = result.mul(power).add(fromNumber(value)); - } else { - result = result.mul(radixToPower); - result = result.add(fromNumber(value)); - } - } - result.unsigned = unsigned; - return result; - } - Long2.fromString = fromString; - function fromValue(val, unsigned) { - if (typeof val === "number") - return fromNumber(val, unsigned); - if (typeof val === "string") - return fromString(val, unsigned); - return fromBits(val.low, val.high, typeof unsigned === "boolean" ? unsigned : val.unsigned); - } - Long2.fromValue = fromValue; - var TWO_PWR_16_DBL = 1 << 16; - var TWO_PWR_24_DBL = 1 << 24; - var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; - var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; - var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; - var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL); - var ZERO = fromInt(0); - Long2.ZERO = ZERO; - var UZERO = fromInt(0, true); - Long2.UZERO = UZERO; - var ONE = fromInt(1); - Long2.ONE = ONE; - var UONE = fromInt(1, true); - Long2.UONE = UONE; - var NEG_ONE = fromInt(-1); - Long2.NEG_ONE = NEG_ONE; - var MAX_VALUE = fromBits(4294967295 | 0, 2147483647 | 0, false); - Long2.MAX_VALUE = MAX_VALUE; - var MAX_UNSIGNED_VALUE = fromBits(4294967295 | 0, 4294967295 | 0, true); - Long2.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE; - var MIN_VALUE = fromBits(0, 2147483648 | 0, false); - Long2.MIN_VALUE = MIN_VALUE; - var LongPrototype = Long2.prototype; - LongPrototype.toInt = function toInt() { - return this.unsigned ? this.low >>> 0 : this.low; - }; - LongPrototype.toNumber = function toNumber() { - if (this.unsigned) - return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); - return this.high * TWO_PWR_32_DBL + (this.low >>> 0); - }; - LongPrototype.toString = function toString(radix) { - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw RangeError("radix"); - if (this.isZero()) - return "0"; - if (this.isNegative()) { - if (this.eq(MIN_VALUE)) { - var radixLong = fromNumber(radix), div3 = this.div(radixLong), rem1 = div3.mul(radixLong).sub(this); - return div3.toString(radix) + rem1.toInt().toString(radix); - } else - return "-" + this.neg().toString(radix); - } - var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), rem = this; - var result = ""; - while (true) { - var remDiv = rem.div(radixToPower), intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, digits = intval.toString(radix); - rem = remDiv; - if (rem.isZero()) - return digits + result; - else { - while (digits.length < 6) - digits = "0" + digits; - result = "" + digits + result; - } - } - }; - LongPrototype.getHighBits = function getHighBits() { - return this.high; - }; - LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() { - return this.high >>> 0; - }; - LongPrototype.getLowBits = function getLowBits() { - return this.low; - }; - LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() { - return this.low >>> 0; - }; - LongPrototype.getNumBitsAbs = function getNumBitsAbs() { - if (this.isNegative()) - return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); - var val = this.high != 0 ? this.high : this.low; - for (var bit = 31; bit > 0; bit--) - if ((val & 1 << bit) != 0) - break; - return this.high != 0 ? bit + 33 : bit + 1; - }; - LongPrototype.isZero = function isZero() { - return this.high === 0 && this.low === 0; - }; - LongPrototype.eqz = LongPrototype.isZero; - LongPrototype.isNegative = function isNegative() { - return !this.unsigned && this.high < 0; - }; - LongPrototype.isPositive = function isPositive() { - return this.unsigned || this.high >= 0; - }; - LongPrototype.isOdd = function isOdd() { - return (this.low & 1) === 1; - }; - LongPrototype.isEven = function isEven2() { - return (this.low & 1) === 0; - }; - LongPrototype.equals = function equals(other) { - if (!isLong(other)) - other = fromValue(other); - if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) - return false; - return this.high === other.high && this.low === other.low; - }; - LongPrototype.eq = LongPrototype.equals; - LongPrototype.notEquals = function notEquals(other) { - return !this.eq(other); - }; - LongPrototype.neq = LongPrototype.notEquals; - LongPrototype.ne = LongPrototype.notEquals; - LongPrototype.lessThan = function lessThan(other) { - return this.comp(other) < 0; - }; - LongPrototype.lt = LongPrototype.lessThan; - LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) { - return this.comp(other) <= 0; - }; - LongPrototype.lte = LongPrototype.lessThanOrEqual; - LongPrototype.le = LongPrototype.lessThanOrEqual; - LongPrototype.greaterThan = function greaterThan(other) { - return this.comp(other) > 0; - }; - LongPrototype.gt = LongPrototype.greaterThan; - LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) { - return this.comp(other) >= 0; - }; - LongPrototype.gte = LongPrototype.greaterThanOrEqual; - LongPrototype.ge = LongPrototype.greaterThanOrEqual; - LongPrototype.compare = function compare(other) { - if (!isLong(other)) - other = fromValue(other); - if (this.eq(other)) - return 0; - var thisNeg = this.isNegative(), otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) - return -1; - if (!thisNeg && otherNeg) - return 1; - if (!this.unsigned) - return this.sub(other).isNegative() ? -1 : 1; - return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1; - }; - LongPrototype.comp = LongPrototype.compare; - LongPrototype.negate = function negate() { - if (!this.unsigned && this.eq(MIN_VALUE)) - return MIN_VALUE; - return this.not().add(ONE); - }; - LongPrototype.neg = LongPrototype.negate; - LongPrototype.add = function add6(addend) { - if (!isLong(addend)) - addend = fromValue(addend); - var a48 = this.high >>> 16; - var a32 = this.high & 65535; - var a16 = this.low >>> 16; - var a00 = this.low & 65535; - var b48 = addend.high >>> 16; - var b32 = addend.high & 65535; - var b16 = addend.low >>> 16; - var b00 = addend.low & 65535; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 65535; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 65535; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 65535; - c48 += a48 + b48; - c48 &= 65535; - return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); - }; - LongPrototype.subtract = function subtract(subtrahend) { - if (!isLong(subtrahend)) - subtrahend = fromValue(subtrahend); - return this.add(subtrahend.neg()); - }; - LongPrototype.sub = LongPrototype.subtract; - LongPrototype.multiply = function multiply5(multiplier) { - if (this.isZero()) - return ZERO; - if (!isLong(multiplier)) - multiplier = fromValue(multiplier); - if (wasm) { - var low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high); - return fromBits(low, wasm.get_high(), this.unsigned); - } - if (multiplier.isZero()) - return ZERO; - if (this.eq(MIN_VALUE)) - return multiplier.isOdd() ? MIN_VALUE : ZERO; - if (multiplier.eq(MIN_VALUE)) - return this.isOdd() ? MIN_VALUE : ZERO; - if (this.isNegative()) { - if (multiplier.isNegative()) - return this.neg().mul(multiplier.neg()); - else - return this.neg().mul(multiplier).neg(); - } else if (multiplier.isNegative()) - return this.mul(multiplier.neg()).neg(); - if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) - return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); - var a48 = this.high >>> 16; - var a32 = this.high & 65535; - var a16 = this.low >>> 16; - var a00 = this.low & 65535; - var b48 = multiplier.high >>> 16; - var b32 = multiplier.high & 65535; - var b16 = multiplier.low >>> 16; - var b00 = multiplier.low & 65535; - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 65535; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 65535; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 65535; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 65535; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 65535; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 65535; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 65535; - return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); - }; - LongPrototype.mul = LongPrototype.multiply; - LongPrototype.divide = function divide(divisor) { - if (!isLong(divisor)) - divisor = fromValue(divisor); - if (divisor.isZero()) - throw Error("division by zero"); - if (wasm) { - if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) { - return this; - } - var low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high); - return fromBits(low, wasm.get_high(), this.unsigned); - } - if (this.isZero()) - return this.unsigned ? UZERO : ZERO; - var approx, rem, res; - if (!this.unsigned) { - if (this.eq(MIN_VALUE)) { - if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) - return MIN_VALUE; - else if (divisor.eq(MIN_VALUE)) - return ONE; - else { - var halfThis = this.shr(1); - approx = halfThis.div(divisor).shl(1); - if (approx.eq(ZERO)) { - return divisor.isNegative() ? ONE : NEG_ONE; - } else { - rem = this.sub(divisor.mul(approx)); - res = approx.add(rem.div(divisor)); - return res; - } - } - } else if (divisor.eq(MIN_VALUE)) - return this.unsigned ? UZERO : ZERO; - if (this.isNegative()) { - if (divisor.isNegative()) - return this.neg().div(divisor.neg()); - return this.neg().div(divisor).neg(); - } else if (divisor.isNegative()) - return this.div(divisor.neg()).neg(); - res = ZERO; - } else { - if (!divisor.unsigned) - divisor = divisor.toUnsigned(); - if (divisor.gt(this)) - return UZERO; - if (divisor.gt(this.shru(1))) - return UONE; - res = UZERO; - } - rem = this; - while (rem.gte(divisor)) { - approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); - var log22 = Math.ceil(Math.log(approx) / Math.LN2), delta = log22 <= 48 ? 1 : pow_dbl(2, log22 - 48), approxRes = fromNumber(approx), approxRem = approxRes.mul(divisor); - while (approxRem.isNegative() || approxRem.gt(rem)) { - approx -= delta; - approxRes = fromNumber(approx, this.unsigned); - approxRem = approxRes.mul(divisor); - } - if (approxRes.isZero()) - approxRes = ONE; - res = res.add(approxRes); - rem = rem.sub(approxRem); - } - return res; - }; - LongPrototype.div = LongPrototype.divide; - LongPrototype.modulo = function modulo(divisor) { - if (!isLong(divisor)) - divisor = fromValue(divisor); - if (wasm) { - var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high); - return fromBits(low, wasm.get_high(), this.unsigned); - } - return this.sub(this.div(divisor).mul(divisor)); - }; - LongPrototype.mod = LongPrototype.modulo; - LongPrototype.rem = LongPrototype.modulo; - LongPrototype.not = function not() { - return fromBits(~this.low, ~this.high, this.unsigned); - }; - LongPrototype.and = function and(other) { - if (!isLong(other)) - other = fromValue(other); - return fromBits(this.low & other.low, this.high & other.high, this.unsigned); - }; - LongPrototype.or = function or(other) { - if (!isLong(other)) - other = fromValue(other); - return fromBits(this.low | other.low, this.high | other.high, this.unsigned); - }; - LongPrototype.xor = function xor(other) { - if (!isLong(other)) - other = fromValue(other); - return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); - }; - LongPrototype.shiftLeft = function shiftLeft(numBits) { - if (isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned); - else - return fromBits(0, this.low << numBits - 32, this.unsigned); - }; - LongPrototype.shl = LongPrototype.shiftLeft; - LongPrototype.shiftRight = function shiftRight(numBits) { - if (isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned); - else - return fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned); - }; - LongPrototype.shr = LongPrototype.shiftRight; - LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) { - if (isLong(numBits)) - numBits = numBits.toInt(); - numBits &= 63; - if (numBits === 0) - return this; - else { - var high = this.high; - if (numBits < 32) { - var low = this.low; - return fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits, this.unsigned); - } else if (numBits === 32) - return fromBits(high, 0, this.unsigned); - else - return fromBits(high >>> numBits - 32, 0, this.unsigned); - } - }; - LongPrototype.shru = LongPrototype.shiftRightUnsigned; - LongPrototype.shr_u = LongPrototype.shiftRightUnsigned; - LongPrototype.toSigned = function toSigned() { - if (!this.unsigned) - return this; - return fromBits(this.low, this.high, false); - }; - LongPrototype.toUnsigned = function toUnsigned() { - if (this.unsigned) - return this; - return fromBits(this.low, this.high, true); - }; - LongPrototype.toBytes = function toBytes(le) { - return le ? this.toBytesLE() : this.toBytesBE(); - }; - LongPrototype.toBytesLE = function toBytesLE() { - var hi = this.high, lo = this.low; - return [ - lo & 255, - lo >>> 8 & 255, - lo >>> 16 & 255, - lo >>> 24, - hi & 255, - hi >>> 8 & 255, - hi >>> 16 & 255, - hi >>> 24 - ]; - }; - LongPrototype.toBytesBE = function toBytesBE() { - var hi = this.high, lo = this.low; - return [ - hi >>> 24, - hi >>> 16 & 255, - hi >>> 8 & 255, - hi & 255, - lo >>> 24, - lo >>> 16 & 255, - lo >>> 8 & 255, - lo & 255 - ]; - }; - Long2.fromBytes = function fromBytes(bytes, unsigned, le) { - return le ? Long2.fromBytesLE(bytes, unsigned) : Long2.fromBytesBE(bytes, unsigned); - }; - Long2.fromBytesLE = function fromBytesLE(bytes, unsigned) { - return new Long2(bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24, bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24, unsigned); - }; - Long2.fromBytesBE = function fromBytesBE(bytes, unsigned) { - return new Long2(bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7], bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], unsigned); - }; - } -}); -var require_node_fetch = __commonJS({ - "(disabled):node-fetch"() { - } -}); -var require_util = __commonJS({ - "(disabled):util"() { - } -}); -var require_alea = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/alea.js"(exports, module) { - (function(global2, module2, define2) { - function Alea(seed) { - var me = this, mash = Mash(); - me.next = function() { - var t = 2091639 * me.s0 + me.c * 23283064365386963e-26; - me.s0 = me.s1; - me.s1 = me.s2; - return me.s2 = t - (me.c = t | 0); - }; - me.c = 1; - me.s0 = mash(" "); - me.s1 = mash(" "); - me.s2 = mash(" "); - me.s0 -= mash(seed); - if (me.s0 < 0) { - me.s0 += 1; - } - me.s1 -= mash(seed); - if (me.s1 < 0) { - me.s1 += 1; - } - me.s2 -= mash(seed); - if (me.s2 < 0) { - me.s2 += 1; - } - mash = null; - } - function copy2(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") - copy2(state, xg); - prng.state = function() { - return copy2(xg, {}); - }; - } - return prng; - } - function Mash() { - var n = 4022871197; - var mash = function(data) { - data = String(data); - for (var i = 0; i < data.length; i++) { - n += data.charCodeAt(i); - var h = 0.02519603282416938 * n; - n = h >>> 0; - h -= n; - h *= n; - n = h >>> 0; - h -= n; - n += h * 4294967296; - } - return (n >>> 0) * 23283064365386963e-26; - }; - return mash; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.alea = impl; - } - })(exports, typeof module == "object" && module, typeof define == "function" && define); - } -}); -var require_xor128 = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js"(exports, module) { - (function(global2, module2, define2) { - function XorGen(seed) { - var me = this, strseed = ""; - me.x = 0; - me.y = 0; - me.z = 0; - me.w = 0; - me.next = function() { - var t = me.x ^ me.x << 11; - me.x = me.y; - me.y = me.z; - me.z = me.w; - return me.w ^= me.w >>> 19 ^ t ^ t >>> 8; - }; - if (seed === (seed | 0)) { - me.x = seed; - } else { - strseed += seed; - } - for (var k = 0; k < strseed.length + 64; k++) { - me.x ^= strseed.charCodeAt(k) | 0; - me.next(); - } - } - function copy2(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") - copy2(state, xg); - prng.state = function() { - return copy2(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.xor128 = impl; - } - })(exports, typeof module == "object" && module, typeof define == "function" && define); - } -}); -var require_xorwow = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js"(exports, module) { - (function(global2, module2, define2) { - function XorGen(seed) { - var me = this, strseed = ""; - me.next = function() { - var t = me.x ^ me.x >>> 2; - me.x = me.y; - me.y = me.z; - me.z = me.w; - me.w = me.v; - return (me.d = me.d + 362437 | 0) + (me.v = me.v ^ me.v << 4 ^ (t ^ t << 1)) | 0; - }; - me.x = 0; - me.y = 0; - me.z = 0; - me.w = 0; - me.v = 0; - if (seed === (seed | 0)) { - me.x = seed; - } else { - strseed += seed; - } - for (var k = 0; k < strseed.length + 64; k++) { - me.x ^= strseed.charCodeAt(k) | 0; - if (k == strseed.length) { - me.d = me.x << 10 ^ me.x >>> 4; - } - me.next(); - } - } - function copy2(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") - copy2(state, xg); - prng.state = function() { - return copy2(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.xorwow = impl; - } - })(exports, typeof module == "object" && module, typeof define == "function" && define); - } -}); -var require_xorshift7 = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js"(exports, module) { - (function(global2, module2, define2) { - function XorGen(seed) { - var me = this; - me.next = function() { - var X = me.x, i = me.i, t, v, w; - t = X[i]; - t ^= t >>> 7; - v = t ^ t << 24; - t = X[i + 1 & 7]; - v ^= t ^ t >>> 10; - t = X[i + 3 & 7]; - v ^= t ^ t >>> 3; - t = X[i + 4 & 7]; - v ^= t ^ t << 7; - t = X[i + 7 & 7]; - t = t ^ t << 13; - v ^= t ^ t << 9; - X[i] = v; - me.i = i + 1 & 7; - return v; - }; - function init2(me2, seed2) { - var j, w, X = []; - if (seed2 === (seed2 | 0)) { - w = X[0] = seed2; - } else { - seed2 = "" + seed2; - for (j = 0; j < seed2.length; ++j) { - X[j & 7] = X[j & 7] << 15 ^ seed2.charCodeAt(j) + X[j + 1 & 7] << 13; - } - } - while (X.length < 8) - X.push(0); - for (j = 0; j < 8 && X[j] === 0; ++j) - ; - if (j == 8) - w = X[7] = -1; - else - w = X[j]; - me2.x = X; - me2.i = 0; - for (j = 256; j > 0; --j) { - me2.next(); - } - } - init2(me, seed); - } - function copy2(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) - copy2(state, xg); - prng.state = function() { - return copy2(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.xorshift7 = impl; - } - })(exports, typeof module == "object" && module, typeof define == "function" && define); - } -}); -var require_xor4096 = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js"(exports, module) { - (function(global2, module2, define2) { - function XorGen(seed) { - var me = this; - me.next = function() { - var w = me.w, X = me.X, i = me.i, t, v; - me.w = w = w + 1640531527 | 0; - v = X[i + 34 & 127]; - t = X[i = i + 1 & 127]; - v ^= v << 13; - t ^= t << 17; - v ^= v >>> 15; - t ^= t >>> 12; - v = X[i] = v ^ t; - me.i = i; - return v + (w ^ w >>> 16) | 0; - }; - function init2(me2, seed2) { - var t, v, i, j, w, X = [], limit = 128; - if (seed2 === (seed2 | 0)) { - v = seed2; - seed2 = null; - } else { - seed2 = seed2 + "\0"; - v = 0; - limit = Math.max(limit, seed2.length); - } - for (i = 0, j = -32; j < limit; ++j) { - if (seed2) - v ^= seed2.charCodeAt((j + 32) % seed2.length); - if (j === 0) - w = v; - v ^= v << 10; - v ^= v >>> 15; - v ^= v << 4; - v ^= v >>> 13; - if (j >= 0) { - w = w + 1640531527 | 0; - t = X[j & 127] ^= v + w; - i = t == 0 ? i + 1 : 0; - } - } - if (i >= 128) { - X[(seed2 && seed2.length || 0) & 127] = -1; - } - i = 127; - for (j = 4 * 128; j > 0; --j) { - v = X[i + 34 & 127]; - t = X[i = i + 1 & 127]; - v ^= v << 13; - t ^= t << 17; - v ^= v >>> 15; - t ^= t >>> 12; - X[i] = v ^ t; - } - me2.w = w; - me2.X = X; - me2.i = i; - } - init2(me, seed); - } - function copy2(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) - copy2(state, xg); - prng.state = function() { - return copy2(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.xor4096 = impl; - } - })(exports, typeof module == "object" && module, typeof define == "function" && define); - } -}); -var require_tychei = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js"(exports, module) { - (function(global2, module2, define2) { - function XorGen(seed) { - var me = this, strseed = ""; - me.next = function() { - var b = me.b, c = me.c, d = me.d, a = me.a; - b = b << 25 ^ b >>> 7 ^ c; - c = c - d | 0; - d = d << 24 ^ d >>> 8 ^ a; - a = a - b | 0; - me.b = b = b << 20 ^ b >>> 12 ^ c; - me.c = c = c - d | 0; - me.d = d << 16 ^ c >>> 16 ^ a; - return me.a = a - b | 0; - }; - me.a = 0; - me.b = 0; - me.c = 2654435769 | 0; - me.d = 1367130551; - if (seed === Math.floor(seed)) { - me.a = seed / 4294967296 | 0; - me.b = seed | 0; - } else { - strseed += seed; - } - for (var k = 0; k < strseed.length + 20; k++) { - me.b ^= strseed.charCodeAt(k) | 0; - me.next(); - } - } - function copy2(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") - copy2(state, xg); - prng.state = function() { - return copy2(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.tychei = impl; - } - })(exports, typeof module == "object" && module, typeof define == "function" && define); - } -}); -var require_crypto = __commonJS({ - "(disabled):crypto"() { - } -}); -var require_seedrandom = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/seedrandom.js"(exports, module) { - (function(global2, pool3, math) { - var width = 256, chunks = 6, digits = 52, rngname = "random", startdenom = math.pow(width, chunks), significance = math.pow(2, digits), overflow = significance * 2, mask = width - 1, nodecrypto; - function seedrandom5(seed, options3, callback) { - var key = []; - options3 = options3 == true ? { entropy: true } : options3 || {}; - var shortseed = mixkey(flatten4(options3.entropy ? [seed, tostring(pool3)] : seed == null ? autoseed() : seed, 3), key); - var arc4 = new ARC4(key); - var prng = function() { - var n = arc4.g(chunks), d = startdenom, x = 0; - while (n < significance) { - n = (n + x) * width; - d *= width; - x = arc4.g(1); - } - while (n >= overflow) { - n /= 2; - d /= 2; - x >>>= 1; - } - return (n + x) / d; - }; - prng.int32 = function() { - return arc4.g(4) | 0; - }; - prng.quick = function() { - return arc4.g(4) / 4294967296; - }; - prng.double = prng; - mixkey(tostring(arc4.S), pool3); - return (options3.pass || callback || function(prng2, seed2, is_math_call, state) { - if (state) { - if (state.S) { - copy2(state, arc4); - } - prng2.state = function() { - return copy2(arc4, {}); - }; - } - if (is_math_call) { - math[rngname] = prng2; - return seed2; - } else - return prng2; - })(prng, shortseed, "global" in options3 ? options3.global : this == math, options3.state); - } - function ARC4(key) { - var t, keylen = key.length, me = this, i = 0, j = me.i = me.j = 0, s = me.S = []; - if (!keylen) { - key = [keylen++]; - } - while (i < width) { - s[i] = i++; - } - for (i = 0; i < width; i++) { - s[i] = s[j = mask & j + key[i % keylen] + (t = s[i])]; - s[j] = t; - } - (me.g = function(count22) { - var t2, r = 0, i2 = me.i, j2 = me.j, s2 = me.S; - while (count22--) { - t2 = s2[i2 = mask & i2 + 1]; - r = r * width + s2[mask & (s2[i2] = s2[j2 = mask & j2 + t2]) + (s2[j2] = t2)]; - } - me.i = i2; - me.j = j2; - return r; - })(width); - } - function copy2(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_seedrandom2 = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/index.js"(exports, module) { - var alea5 = require_alea(); - var xor128 = require_xor128(); - var xorwow = require_xorwow(); - var xorshift7 = require_xorshift7(); - var xor4096 = require_xor4096(); - var tychei = require_tychei(); - var sr = require_seedrandom(); - sr.alea = alea5; - sr.xor128 = xor128; - sr.xorwow = xorwow; - sr.xorshift7 = xorshift7; - sr.xor4096 = xor4096; - sr.tychei = tychei; - module.exports = sr; - } -}); -var require_string_decoder = __commonJS({ - "(disabled):src/node_modules/string_decoder/index.js"() { - } -}); -var require_tfjs_backend_wasm_threaded_simd = __commonJS({ - "src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm-threaded-simd.js"(exports, module) { - var WasmBackendModuleThreadedSimd = function() { - var _scriptDir = typeof document !== "undefined" && document.currentScript ? document.currentScript.src : void 0; - if (typeof __filename !== "undefined") - _scriptDir = _scriptDir || __filename; - return function(WasmBackendModuleThreadedSimd2) { - WasmBackendModuleThreadedSimd2 = WasmBackendModuleThreadedSimd2 || {}; - function GROWABLE_HEAP_I8() { - if (wasmMemory.buffer != buffer2) { - updateGlobalBufferAndViews(wasmMemory.buffer); - } - return HEAP8; - } - function GROWABLE_HEAP_U8() { - if (wasmMemory.buffer != buffer2) { - updateGlobalBufferAndViews(wasmMemory.buffer); - } - return HEAPU8; - } - function GROWABLE_HEAP_I32() { - if (wasmMemory.buffer != buffer2) { - updateGlobalBufferAndViews(wasmMemory.buffer); - } - return HEAP32; - } - function GROWABLE_HEAP_U32() { - if (wasmMemory.buffer != buffer2) { - updateGlobalBufferAndViews(wasmMemory.buffer); - } - return HEAPU32; - } - function GROWABLE_HEAP_F64() { - if (wasmMemory.buffer != buffer2) { - updateGlobalBufferAndViews(wasmMemory.buffer); - } - return HEAPF64; - } - var Module = typeof WasmBackendModuleThreadedSimd2 !== "undefined" ? WasmBackendModuleThreadedSimd2 : {}; - var readyPromiseResolve, readyPromiseReject; - Module["ready"] = new Promise(function(resolve, reject) { - readyPromiseResolve = resolve; - readyPromiseReject = reject; - }); - var moduleOverrides = {}; - var key; - for (key in Module) { - if (Module.hasOwnProperty(key)) { - moduleOverrides[key] = Module[key]; - } - } - var arguments_ = []; - var thisProgram = "./this.program"; - var quit_ = function(status, toThrow) { - throw toThrow; - }; - var ENVIRONMENT_IS_WEB = false; - var ENVIRONMENT_IS_WORKER = false; - var ENVIRONMENT_IS_NODE = false; - var ENVIRONMENT_IS_SHELL = false; - ENVIRONMENT_IS_WEB = typeof window === "object"; - ENVIRONMENT_IS_WORKER = typeof importScripts === "function"; - ENVIRONMENT_IS_NODE = typeof process === "object" && typeof process.versions === "object" && typeof process.versions.node === "string"; - ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER; - var ENVIRONMENT_IS_PTHREAD = Module["ENVIRONMENT_IS_PTHREAD"] || false; - if (ENVIRONMENT_IS_PTHREAD) { - buffer2 = Module["buffer"]; - } - var scriptDirectory = ""; - function locateFile(path) { - if (Module["locateFile"]) { - return Module["locateFile"](path, scriptDirectory); - } - return scriptDirectory + path; - } - var read_, readAsync, readBinary, setWindowTitle; - var nodeFS; - var nodePath; - if (ENVIRONMENT_IS_NODE) { - if (ENVIRONMENT_IS_WORKER) { - scriptDirectory = __require22("path").dirname(scriptDirectory) + "/"; - } else { - scriptDirectory = __dirname + "/"; - } - read_ = function shell_read(filename, binary) { - if (!nodeFS) - nodeFS = __require22("fs"); - if (!nodePath) - nodePath = __require22("path"); - filename = nodePath["normalize"](filename); - return nodeFS["readFileSync"](filename, binary ? null : "utf8"); - }; - readBinary = function readBinary2(filename) { - var ret = read_(filename, true); - if (!ret.buffer) { - ret = new Uint8Array(ret); - } - assert3(ret.buffer); - return ret; - }; - if (process["argv"].length > 1) { - thisProgram = process["argv"][1].replace(/\\/g, "/"); - } - arguments_ = process["argv"].slice(2); - process["on"]("uncaughtException", function(ex) { - if (!(ex instanceof ExitStatus)) { - throw ex; - } - }); - process["on"]("unhandledRejection", abort); - quit_ = function(status) { - process["exit"](status); - }; - Module["inspect"] = function() { - return "[Emscripten Module object]"; - }; - var nodeWorkerThreads; - try { - nodeWorkerThreads = __require22("worker_threads"); - } catch (e) { - console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'); - throw e; - } - global.Worker = nodeWorkerThreads.Worker; - } else if (ENVIRONMENT_IS_SHELL) { - if (typeof read != "undefined") { - read_ = function shell_read(f) { - return read(f); - }; - } - readBinary = function readBinary2(f) { - var data; - if (typeof readbuffer === "function") { - return new Uint8Array(readbuffer(f)); - } - data = read(f, "binary"); - assert3(typeof data === "object"); - return data; - }; - if (typeof scriptArgs != "undefined") { - arguments_ = scriptArgs; - } else if (typeof arguments != "undefined") { - arguments_ = arguments; - } - if (typeof quit === "function") { - quit_ = function(status) { - quit(status); - }; - } - if (typeof print !== "undefined") { - if (typeof console === "undefined") - console = {}; - console.log = print; - console.warn = console.error = typeof printErr !== "undefined" ? printErr : print; - } - } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { - if (ENVIRONMENT_IS_WORKER) { - scriptDirectory = self.location.href; - } else if (typeof document !== "undefined" && document.currentScript) { - scriptDirectory = document.currentScript.src; - } - if (typeof _scriptDir !== "undefined" && _scriptDir) { - scriptDirectory = _scriptDir; - } - if (scriptDirectory.indexOf("blob:") !== 0) { - scriptDirectory = scriptDirectory.substr(0, scriptDirectory.lastIndexOf("/") + 1); - } else { - scriptDirectory = ""; - } - if (ENVIRONMENT_IS_NODE) { - read_ = function shell_read(filename, binary) { - if (!nodeFS) - nodeFS = __require22("fs"); - if (!nodePath) - nodePath = __require22("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 = __require22("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"]; - function warnOnce(text) { - if (!warnOnce.shown) - warnOnce.shown = {}; - if (!warnOnce.shown[text]) { - warnOnce.shown[text] = 1; - err(text); - } - } - var Atomics_load = Atomics.load; - var Atomics_store = Atomics.store; - var Atomics_compareExchange = Atomics.compareExchange; - var wasmBinary; - if (Module["wasmBinary"]) - wasmBinary = Module["wasmBinary"]; - var noExitRuntime = Module["noExitRuntime"] || true; - if (typeof WebAssembly !== "object") { - abort("no native wasm support detected"); - } - var wasmMemory; - var wasmModule; - var ABORT = false; - var EXITSTATUS; - function assert3(condition, text) { - if (!condition) { - abort("Assertion failed: " + text); - } - } - function getCFunc(ident) { - var func2 = Module["_" + ident]; - assert3(func2, "Cannot call unknown function " + ident + ", make sure it is exported"); - return func2; - } - function ccall(ident, returnType, argTypes, args, opts) { - var toC = { "string": function(str) { - var ret2 = 0; - if (str !== null && str !== void 0 && str !== 0) { - var len = (str.length << 2) + 1; - ret2 = stackAlloc(len); - stringToUTF8(str, ret2, len); - } - return ret2; - }, "array": function(arr) { - var ret2 = stackAlloc(arr.length); - writeArrayToMemory(arr, ret2); - return ret2; - } }; - function convertReturnValue(ret2) { - if (returnType === "string") - return UTF8ToString(ret2); - if (returnType === "boolean") - return Boolean(ret2); - return ret2; - } - var func2 = getCFunc(ident); - var cArgs = []; - var stack2 = 0; - if (args) { - for (var i = 0; i < args.length; i++) { - var converter = toC[argTypes[i]]; - if (converter) { - if (stack2 === 0) - stack2 = stackSave(); - cArgs[i] = converter(args[i]); - } else { - cArgs[i] = args[i]; - } - } - } - var ret = func2.apply(null, cArgs); - ret = convertReturnValue(ret); - if (stack2 !== 0) - stackRestore(stack2); - return ret; - } - function cwrap(ident, returnType, argTypes, opts) { - argTypes = argTypes || []; - var numericArgs = argTypes.every(function(type) { - return type === "number"; - }); - var numericRet = returnType !== "string"; - if (numericRet && numericArgs && !opts) { - return getCFunc(ident); - } - return function() { - return ccall(ident, returnType, argTypes, arguments, opts); - }; - } - function UTF8ArrayToString(heap, idx, maxBytesToRead) { - var endIdx = idx + maxBytesToRead; - var str = ""; - while (!(idx >= endIdx)) { - var u0 = heap[idx++]; - if (!u0) - return str; - if (!(u0 & 128)) { - str += String.fromCharCode(u0); - continue; - } - var u1 = heap[idx++] & 63; - if ((u0 & 224) == 192) { - str += String.fromCharCode((u0 & 31) << 6 | u1); - continue; - } - var u2 = heap[idx++] & 63; - if ((u0 & 240) == 224) { - u0 = (u0 & 15) << 12 | u1 << 6 | u2; - } else { - u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heap[idx++] & 63; - } - if (u0 < 65536) { - str += String.fromCharCode(u0); - } else { - var ch = u0 - 65536; - str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023); - } - } - return str; - } - function UTF8ToString(ptr, maxBytesToRead) { - return ptr ? UTF8ArrayToString(GROWABLE_HEAP_U8(), ptr, maxBytesToRead) : ""; - } - function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) { - if (!(maxBytesToWrite > 0)) - return 0; - var startIdx = outIdx; - var endIdx = outIdx + maxBytesToWrite - 1; - for (var i = 0; i < str.length; ++i) { - var u = str.charCodeAt(i); - if (u >= 55296 && u <= 57343) { - var u1 = str.charCodeAt(++i); - u = 65536 + ((u & 1023) << 10) | u1 & 1023; - } - if (u <= 127) { - if (outIdx >= endIdx) - break; - heap[outIdx++] = u; - } else if (u <= 2047) { - if (outIdx + 1 >= endIdx) - break; - heap[outIdx++] = 192 | u >> 6; - heap[outIdx++] = 128 | u & 63; - } else if (u <= 65535) { - if (outIdx + 2 >= endIdx) - break; - heap[outIdx++] = 224 | u >> 12; - heap[outIdx++] = 128 | u >> 6 & 63; - heap[outIdx++] = 128 | u & 63; - } else { - if (outIdx + 3 >= endIdx) - break; - heap[outIdx++] = 240 | u >> 18; - heap[outIdx++] = 128 | u >> 12 & 63; - heap[outIdx++] = 128 | u >> 6 & 63; - heap[outIdx++] = 128 | u & 63; - } - } - heap[outIdx] = 0; - return outIdx - startIdx; - } - function stringToUTF8(str, outPtr, maxBytesToWrite) { - return stringToUTF8Array(str, GROWABLE_HEAP_U8(), outPtr, maxBytesToWrite); - } - function lengthBytesUTF8(str) { - var len = 0; - for (var i = 0; i < str.length; ++i) { - var u = str.charCodeAt(i); - if (u >= 55296 && u <= 57343) - u = 65536 + ((u & 1023) << 10) | str.charCodeAt(++i) & 1023; - if (u <= 127) - ++len; - else if (u <= 2047) - len += 2; - else if (u <= 65535) - len += 3; - else - len += 4; - } - return len; - } - function writeArrayToMemory(array2, buffer3) { - GROWABLE_HEAP_I8().set(array2, buffer3); - } - function alignUp(x, multiple) { - if (x % multiple > 0) { - x += multiple - x % multiple; - } - return x; - } - var buffer2, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64; - function updateGlobalBufferAndViews(buf) { - buffer2 = buf; - Module["HEAP8"] = HEAP8 = new Int8Array(buf); - Module["HEAP16"] = HEAP16 = new Int16Array(buf); - Module["HEAP32"] = HEAP32 = new Int32Array(buf); - Module["HEAPU8"] = HEAPU8 = new Uint8Array(buf); - Module["HEAPU16"] = HEAPU16 = new Uint16Array(buf); - Module["HEAPU32"] = HEAPU32 = new Uint32Array(buf); - Module["HEAPF32"] = HEAPF32 = new Float32Array(buf); - Module["HEAPF64"] = HEAPF64 = new Float64Array(buf); - } - var INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 16777216; - if (ENVIRONMENT_IS_PTHREAD) { - wasmMemory = Module["wasmMemory"]; - buffer2 = Module["buffer"]; - } else { - if (Module["wasmMemory"]) { - wasmMemory = Module["wasmMemory"]; - } else { - wasmMemory = new WebAssembly.Memory({ "initial": INITIAL_MEMORY / 65536, "maximum": 2147483648 / 65536, "shared": true }); - if (!(wasmMemory.buffer instanceof SharedArrayBuffer)) { - err("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"); - if (ENVIRONMENT_IS_NODE) { - console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"); - } - throw Error("bad memory"); - } - } - } - if (wasmMemory) { - buffer2 = wasmMemory.buffer; - } - INITIAL_MEMORY = buffer2.byteLength; - updateGlobalBufferAndViews(buffer2); - var wasmTable; - var __ATPRERUN__ = []; - var __ATINIT__ = []; - var __ATMAIN__ = []; - var __ATEXIT__ = []; - var __ATPOSTRUN__ = []; - var runtimeInitialized = false; - var runtimeExited = false; - if (!ENVIRONMENT_IS_PTHREAD) - __ATINIT__.push({ func: function() { - ___wasm_call_ctors(); - } }); - function preRun() { - if (ENVIRONMENT_IS_PTHREAD) - return; - if (Module["preRun"]) { - if (typeof Module["preRun"] == "function") - Module["preRun"] = [Module["preRun"]]; - while (Module["preRun"].length) { - addOnPreRun(Module["preRun"].shift()); - } - } - callRuntimeCallbacks(__ATPRERUN__); - } - function initRuntime() { - runtimeInitialized = true; - if (ENVIRONMENT_IS_PTHREAD) - return; - callRuntimeCallbacks(__ATINIT__); - } - function preMain() { - if (ENVIRONMENT_IS_PTHREAD) - return; - callRuntimeCallbacks(__ATMAIN__); - } - function exitRuntime() { - if (ENVIRONMENT_IS_PTHREAD) - return; - runtimeExited = true; - } - function postRun() { - if (ENVIRONMENT_IS_PTHREAD) - return; - if (Module["postRun"]) { - if (typeof Module["postRun"] == "function") - Module["postRun"] = [Module["postRun"]]; - while (Module["postRun"].length) { - addOnPostRun(Module["postRun"].shift()); - } - } - callRuntimeCallbacks(__ATPOSTRUN__); - } - function addOnPreRun(cb) { - __ATPRERUN__.unshift(cb); - } - function addOnPostRun(cb) { - __ATPOSTRUN__.unshift(cb); - } - var runDependencies = 0; - var runDependencyWatcher = null; - var dependenciesFulfilled = null; - function addRunDependency(id) { - assert3(!ENVIRONMENT_IS_PTHREAD, "addRunDependency cannot be used in a pthread worker"); - runDependencies++; - if (Module["monitorRunDependencies"]) { - Module["monitorRunDependencies"](runDependencies); - } - } - function removeRunDependency(id) { - runDependencies--; - if (Module["monitorRunDependencies"]) { - Module["monitorRunDependencies"](runDependencies); - } - if (runDependencies == 0) { - if (runDependencyWatcher !== null) { - clearInterval(runDependencyWatcher); - runDependencyWatcher = null; - } - if (dependenciesFulfilled) { - var callback = dependenciesFulfilled; - dependenciesFulfilled = null; - callback(); - } - } - } - Module["preloadedImages"] = {}; - Module["preloadedAudios"] = {}; - function abort(what) { - if (Module["onAbort"]) { - Module["onAbort"](what); - } - if (ENVIRONMENT_IS_PTHREAD) - console.error("Pthread aborting at " + new Error().stack); - what += ""; - err(what); - ABORT = true; - EXITSTATUS = 1; - what = "abort(" + what + "). Build with -s ASSERTIONS=1 for more info."; - var e = new WebAssembly.RuntimeError(what); - readyPromiseReject(e); - throw e; - } - function hasPrefix(str, prefix) { - return String.prototype.startsWith ? str.startsWith(prefix) : str.indexOf(prefix) === 0; - } - var dataURIPrefix = "data:application/octet-stream;base64,"; - function isDataURI(filename) { - return hasPrefix(filename, dataURIPrefix); - } - var fileURIPrefix = "file://"; - function isFileURI(filename) { - return hasPrefix(filename, fileURIPrefix); - } - var wasmBinaryFile = "tfjs-backend-wasm-threaded-simd.wasm"; - if (!isDataURI(wasmBinaryFile)) { - wasmBinaryFile = locateFile(wasmBinaryFile); - } - function getBinary(file) { - try { - if (file == wasmBinaryFile && wasmBinary) { - return new Uint8Array(wasmBinary); - } - if (readBinary) { - return readBinary(file); - } else { - throw "both async and sync fetching of the wasm failed"; - } - } catch (err2) { - abort(err2); - } - } - function getBinaryPromise() { - if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) { - if (typeof fetch === "function" && !isFileURI(wasmBinaryFile)) { - return fetch(wasmBinaryFile, { credentials: "same-origin" }).then(function(response) { - if (!response["ok"]) { - throw "failed to load wasm binary file at '" + wasmBinaryFile + "'"; - } - return response["arrayBuffer"](); - }).catch(function() { - return getBinary(wasmBinaryFile); - }); - } else { - if (readAsync) { - return new Promise(function(resolve, reject) { - readAsync(wasmBinaryFile, function(response) { - resolve(new Uint8Array(response)); - }, reject); - }); - } - } - } - return Promise.resolve().then(function() { - return getBinary(wasmBinaryFile); - }); - } - function createWasm() { - var info = { "a": asmLibraryArg }; - function receiveInstance(instance, module2) { - var exports3 = instance.exports; - Module["asm"] = exports3; - wasmTable = Module["asm"]["kb"]; - 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, info); - }).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, info); - 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"](info, receiveInstance); - return exports2; - } catch (e) { - err("Module.instantiateWasm callback failed with error: " + e); - return false; - } - } - instantiateAsync().catch(readyPromiseReject); - return {}; - } - var ASM_CONSTS = { 10072: function() { - throw "Canceled!"; - }, 10090: 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); - } - } - } - var ERRNO_CODES = { EPERM: 63, ENOENT: 44, ESRCH: 71, EINTR: 27, EIO: 29, ENXIO: 60, E2BIG: 1, ENOEXEC: 45, EBADF: 8, ECHILD: 12, EAGAIN: 6, EWOULDBLOCK: 6, ENOMEM: 48, EACCES: 2, EFAULT: 21, ENOTBLK: 105, EBUSY: 10, EEXIST: 20, EXDEV: 75, ENODEV: 43, ENOTDIR: 54, EISDIR: 31, EINVAL: 28, ENFILE: 41, EMFILE: 33, ENOTTY: 59, ETXTBSY: 74, EFBIG: 22, ENOSPC: 51, ESPIPE: 70, EROFS: 69, EMLINK: 34, EPIPE: 64, EDOM: 18, ERANGE: 68, ENOMSG: 49, EIDRM: 24, ECHRNG: 106, EL2NSYNC: 156, EL3HLT: 107, EL3RST: 108, ELNRNG: 109, EUNATCH: 110, ENOCSI: 111, EL2HLT: 112, EDEADLK: 16, ENOLCK: 46, EBADE: 113, EBADR: 114, EXFULL: 115, ENOANO: 104, EBADRQC: 103, EBADSLT: 102, EDEADLOCK: 16, EBFONT: 101, ENOSTR: 100, ENODATA: 116, ETIME: 117, ENOSR: 118, ENONET: 119, ENOPKG: 120, EREMOTE: 121, ENOLINK: 47, EADV: 122, ESRMNT: 123, ECOMM: 124, EPROTO: 65, EMULTIHOP: 36, EDOTDOT: 125, EBADMSG: 9, ENOTUNIQ: 126, EBADFD: 127, EREMCHG: 128, ELIBACC: 129, ELIBBAD: 130, ELIBSCN: 131, ELIBMAX: 132, ELIBEXEC: 133, ENOSYS: 52, ENOTEMPTY: 55, ENAMETOOLONG: 37, ELOOP: 32, EOPNOTSUPP: 138, EPFNOSUPPORT: 139, ECONNRESET: 15, ENOBUFS: 42, EAFNOSUPPORT: 5, EPROTOTYPE: 67, ENOTSOCK: 57, ENOPROTOOPT: 50, ESHUTDOWN: 140, ECONNREFUSED: 14, EADDRINUSE: 3, ECONNABORTED: 13, ENETUNREACH: 40, ENETDOWN: 38, ETIMEDOUT: 73, EHOSTDOWN: 142, EHOSTUNREACH: 23, EINPROGRESS: 26, EALREADY: 7, EDESTADDRREQ: 17, EMSGSIZE: 35, EPROTONOSUPPORT: 66, ESOCKTNOSUPPORT: 137, EADDRNOTAVAIL: 4, ENETRESET: 39, EISCONN: 30, ENOTCONN: 53, ETOOMANYREFS: 141, EUSERS: 136, EDQUOT: 19, ESTALE: 72, ENOTSUP: 138, ENOMEDIUM: 148, EILSEQ: 25, EOVERFLOW: 61, ECANCELED: 11, ENOTRECOVERABLE: 56, EOWNERDEAD: 62, ESTRPIPE: 135 }; - function _emscripten_futex_wake(addr, count22) { - if (addr <= 0 || addr > GROWABLE_HEAP_I8().length || addr & true || count22 < 0) - return -28; - if (count22 == 0) - return 0; - if (count22 >= 2147483647) - count22 = Infinity; - var mainThreadWaitAddress = Atomics.load(GROWABLE_HEAP_I32(), __emscripten_main_thread_futex >> 2); - var mainThreadWoken = 0; - if (mainThreadWaitAddress == addr) { - var loadedAddr = Atomics.compareExchange(GROWABLE_HEAP_I32(), __emscripten_main_thread_futex >> 2, mainThreadWaitAddress, 0); - if (loadedAddr == mainThreadWaitAddress) { - --count22; - mainThreadWoken = 1; - if (count22 <= 0) - return 1; - } - } - var ret = Atomics.notify(GROWABLE_HEAP_I32(), addr >> 2, count22); - if (ret >= 0) - return ret + mainThreadWoken; - throw "Atomics.notify returned an unexpected value " + ret; - } - Module["_emscripten_futex_wake"] = _emscripten_futex_wake; - function killThread(pthread_ptr) { - if (ENVIRONMENT_IS_PTHREAD) - throw "Internal Error! killThread() can only ever be called from main application thread!"; - if (!pthread_ptr) - throw "Internal Error! Null pthread_ptr in killThread!"; - GROWABLE_HEAP_I32()[pthread_ptr + 12 >> 2] = 0; - var pthread = PThread.pthreads[pthread_ptr]; - pthread.worker.terminate(); - PThread.freeThreadData(pthread); - PThread.runningWorkers.splice(PThread.runningWorkers.indexOf(pthread.worker), 1); - pthread.worker.pthread = void 0; - } - function cancelThread(pthread_ptr) { - if (ENVIRONMENT_IS_PTHREAD) - throw "Internal Error! cancelThread() can only ever be called from main application thread!"; - if (!pthread_ptr) - throw "Internal Error! Null pthread_ptr in cancelThread!"; - var pthread = PThread.pthreads[pthread_ptr]; - pthread.worker.postMessage({ "cmd": "cancel" }); - } - function cleanupThread(pthread_ptr) { - if (ENVIRONMENT_IS_PTHREAD) - throw "Internal Error! cleanupThread() can only ever be called from main application thread!"; - if (!pthread_ptr) - throw "Internal Error! Null pthread_ptr in cleanupThread!"; - var pthread = PThread.pthreads[pthread_ptr]; - if (pthread) { - GROWABLE_HEAP_I32()[pthread_ptr + 12 >> 2] = 0; - var worker = pthread.worker; - PThread.returnWorkerToPool(worker); - } - } - var PThread = { unusedWorkers: [], runningWorkers: [], initMainThreadBlock: function() { - var pthreadPoolSize = 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(); - }, runExitHandlersAndDeinitThread: function(tb, exitCode) { - Atomics.store(GROWABLE_HEAP_U32(), tb + 56 >> 2, 1); - Atomics.store(GROWABLE_HEAP_U32(), tb + 60 >> 2, 0); - PThread.runExitHandlers(); - Atomics.store(GROWABLE_HEAP_U32(), tb + 4 >> 2, exitCode); - Atomics.store(GROWABLE_HEAP_U32(), tb + 0 >> 2, 1); - _emscripten_futex_wake(tb + 0, 2147483647); - __emscripten_thread_init(0, 0, 0); - }, threadExit: function(exitCode) { - var tb = _pthread_self(); - if (tb) { - PThread.runExitHandlersAndDeinitThread(tb, exitCode); - if (ENVIRONMENT_IS_PTHREAD) { - postMessage({ "cmd": "exit" }); - } - } - }, threadCancel: function() { - PThread.runExitHandlersAndDeinitThread(_pthread_self(), -1); - postMessage({ "cmd": "cancelDone" }); - }, terminateAllThreads: function() { - for (var t in PThread.pthreads) { - var pthread = PThread.pthreads[t]; - if (pthread && pthread.worker) { - PThread.returnWorkerToPool(pthread.worker); - } - } - PThread.pthreads = {}; - for (var i = 0; i < PThread.unusedWorkers.length; ++i) { - var worker = PThread.unusedWorkers[i]; - worker.terminate(); - } - PThread.unusedWorkers = []; - for (var i = 0; i < PThread.runningWorkers.length; ++i) { - var worker = PThread.runningWorkers[i]; - var pthread = worker.pthread; - PThread.freeThreadData(pthread); - worker.terminate(); - } - PThread.runningWorkers = []; - }, freeThreadData: function(pthread) { - if (!pthread) - return; - if (pthread.threadInfoStruct) { - var tlsMemory = GROWABLE_HEAP_I32()[pthread.threadInfoStruct + 100 >> 2]; - GROWABLE_HEAP_I32()[pthread.threadInfoStruct + 100 >> 2] = 0; - _free(tlsMemory); - _free(pthread.threadInfoStruct); - } - pthread.threadInfoStruct = 0; - if (pthread.allocatedOwnStack && pthread.stackBase) - _free(pthread.stackBase); - pthread.stackBase = 0; - if (pthread.worker) - pthread.worker.pthread = null; - }, returnWorkerToPool: function(worker) { - PThread.runWithoutMainThreadQueuedCalls(function() { - delete PThread.pthreads[worker.pthread.threadInfoStruct]; - PThread.unusedWorkers.push(worker); - PThread.runningWorkers.splice(PThread.runningWorkers.indexOf(worker), 1); - PThread.freeThreadData(worker.pthread); - worker.pthread = void 0; - }); - }, runWithoutMainThreadQueuedCalls: function(func2) { - GROWABLE_HEAP_I32()[__emscripten_allow_main_runtime_queued_calls >> 2] = 0; - try { - func2(); - } finally { - GROWABLE_HEAP_I32()[__emscripten_allow_main_runtime_queued_calls >> 2] = 1; - } - }, receiveObjectTransfer: function(data) { - }, loadWasmModuleToWorker: function(worker, onFinishedLoading) { - worker.onmessage = function(e) { - var d = e["data"]; - var cmd = d["cmd"]; - if (worker.pthread) - PThread.currentProxiedOperationCallerThread = worker.pthread.threadInfoStruct; - if (d["targetThread"] && d["targetThread"] != _pthread_self()) { - var thread = PThread.pthreads[d.targetThread]; - if (thread) { - thread.worker.postMessage(e.data, d["transferList"]); - } else { - console.error('Internal error! Worker sent a message "' + cmd + '" to target pthread ' + d["targetThread"] + ", but that thread no longer exists!"); - } - PThread.currentProxiedOperationCallerThread = void 0; - return; - } - if (cmd === "processQueuedMainThreadWork") { - _emscripten_main_thread_process_queued_calls(); - } else if (cmd === "spawnThread") { - spawnThread(e.data); - } else if (cmd === "cleanupThread") { - cleanupThread(d["thread"]); - } else if (cmd === "killThread") { - killThread(d["thread"]); - } else if (cmd === "cancelThread") { - cancelThread(d["thread"]); - } else if (cmd === "loaded") { - worker.loaded = true; - if (onFinishedLoading) - onFinishedLoading(worker); - if (worker.runPthread) { - worker.runPthread(); - delete worker.runPthread; - } - } else if (cmd === "print") { - out("Thread " + d["threadId"] + ": " + d["text"]); - } else if (cmd === "printErr") { - err("Thread " + d["threadId"] + ": " + d["text"]); - } else if (cmd === "alert") { - alert("Thread " + d["threadId"] + ": " + d["text"]); - } else if (cmd === "exit") { - var detached = worker.pthread && Atomics.load(GROWABLE_HEAP_U32(), worker.pthread.threadInfoStruct + 64 >> 2); - if (detached) { - PThread.returnWorkerToPool(worker); - } - } else if (cmd === "exitProcess") { - try { - exit(d["returnCode"]); - } catch (e2) { - if (e2 instanceof ExitStatus) - return; - throw e2; - } - } else if (cmd === "cancelDone") { - PThread.returnWorkerToPool(worker); - } else if (cmd === "objectTransfer") { - PThread.receiveObjectTransfer(e.data); - } else if (e.data.target === "setimmediate") { - worker.postMessage(e.data); - } else { - err("worker sent an unknown command " + cmd); - } - PThread.currentProxiedOperationCallerThread = void 0; - }; - worker.onerror = function(e) { - err("pthread sent an error! " + e.filename + ":" + e.lineno + ": " + e.message); - }; - if (ENVIRONMENT_IS_NODE) { - worker.on("message", function(data) { - worker.onmessage({ data }); - }); - worker.on("error", function(data) { - worker.onerror(data); - }); - worker.on("exit", function(data) { - }); - } - worker.postMessage({ "cmd": "load", "urlOrBlob": Module["mainScriptUrlOrBlob"] || _scriptDir, "wasmMemory": wasmMemory, "wasmModule": wasmModule }); - }, allocateUnusedWorker: function() { - var pthreadMainJs = locateFile("tfjs-backend-wasm-threaded-simd.worker.js"); - PThread.unusedWorkers.push(new Worker(pthreadMainJs)); - }, getNewWorker: function() { - if (PThread.unusedWorkers.length == 0) { - PThread.allocateUnusedWorker(); - PThread.loadWasmModuleToWorker(PThread.unusedWorkers[0]); - } - if (PThread.unusedWorkers.length > 0) - return PThread.unusedWorkers.pop(); - else - return null; - }, busySpinWait: function(msecs) { - var t = performance.now() + msecs; - while (performance.now() < t) { - } - } }; - function establishStackSpace(stackTop, stackMax) { - _emscripten_stack_set_limits(stackTop, stackMax); - stackRestore(stackTop); - } - Module["establishStackSpace"] = establishStackSpace; - function getNoExitRuntime() { - return noExitRuntime; - } - Module["getNoExitRuntime"] = getNoExitRuntime; - function invokeEntryPoint(ptr, arg) { - return wasmTable.get(ptr)(arg); - } - Module["invokeEntryPoint"] = invokeEntryPoint; - function ___assert_fail(condition, filename, line, func2) { - abort("Assertion failed: " + UTF8ToString(condition) + ", at: " + [filename ? UTF8ToString(filename) : "unknown filename", line, func2 ? UTF8ToString(func2) : "unknown function"]); - } - function ___call_main(argc, argv) { - var returnCode = _main(argc, argv); - } - var _emscripten_get_now; - if (ENVIRONMENT_IS_NODE) { - _emscripten_get_now = function() { - var t = process["hrtime"](); - return t[0] * 1e3 + t[1] / 1e6; - }; - } else if (ENVIRONMENT_IS_PTHREAD) { - _emscripten_get_now = function() { - return performance.now() - Module["__performance_now_clock_drift"]; - }; - } else if (typeof dateNow !== "undefined") { - _emscripten_get_now = dateNow; - } else - _emscripten_get_now = function() { - return performance.now(); - }; - function setErrNo(value) { - GROWABLE_HEAP_I32()[___errno_location() >> 2] = value; - return value; - } - function _atexit(func2, arg) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(1, 1, func2, arg); - } - function __emscripten_notify_thread_queue(targetThreadId, mainThreadId) { - if (targetThreadId == mainThreadId) { - postMessage({ "cmd": "processQueuedMainThreadWork" }); - } else if (ENVIRONMENT_IS_PTHREAD) { - postMessage({ "targetThread": targetThreadId, "cmd": "processThreadQueue" }); - } else { - var pthread = PThread.pthreads[targetThreadId]; - var worker = pthread && pthread.worker; - if (!worker) { - return; - } - worker.postMessage({ "cmd": "processThreadQueue" }); - } - return 1; - } - function _abort() { - abort(); - } - function _emscripten_asm_const_int(code, sigPtr, argbuf) { - var args = readAsmConstArgs(sigPtr, argbuf); - return ASM_CONSTS[code].apply(null, args); - } - function _emscripten_conditional_set_current_thread_status(expectedStatus, newStatus) { - } - function _emscripten_futex_wait(addr, val, timeout) { - if (addr <= 0 || addr > GROWABLE_HEAP_I8().length || addr & true) - return -28; - if (!ENVIRONMENT_IS_WEB) { - var ret = Atomics.wait(GROWABLE_HEAP_I32(), addr >> 2, val, timeout); - if (ret === "timed-out") - return -73; - if (ret === "not-equal") - return -6; - if (ret === "ok") - return 0; - throw "Atomics.wait returned an unexpected value " + ret; - } else { - if (Atomics.load(GROWABLE_HEAP_I32(), addr >> 2) != val) { - return -6; - } - var tNow = performance.now(); - var tEnd = tNow + timeout; - var lastAddr = Atomics.exchange(GROWABLE_HEAP_I32(), __emscripten_main_thread_futex >> 2, addr); - while (1) { - tNow = performance.now(); - if (tNow > tEnd) { - lastAddr = Atomics.exchange(GROWABLE_HEAP_I32(), __emscripten_main_thread_futex >> 2, 0); - return -73; - } - lastAddr = Atomics.exchange(GROWABLE_HEAP_I32(), __emscripten_main_thread_futex >> 2, 0); - if (lastAddr == 0) { - break; - } - _emscripten_main_thread_process_queued_calls(); - if (Atomics.load(GROWABLE_HEAP_I32(), addr >> 2) != val) { - return -6; - } - lastAddr = Atomics.exchange(GROWABLE_HEAP_I32(), __emscripten_main_thread_futex >> 2, addr); - } - return 0; - } - } - function _emscripten_memcpy_big(dest, src, num) { - GROWABLE_HEAP_U8().copyWithin(dest, src, src + num); - } - function _emscripten_num_logical_cores() { - if (ENVIRONMENT_IS_NODE) - return __require22("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(size2) { - try { - wasmMemory.grow(size2 - 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 canvas3 = findCanvasEventTarget(target); - if (!canvas3) - return -4; - if (canvas3.canvasSharedPtr) { - GROWABLE_HEAP_I32()[canvas3.canvasSharedPtr >> 2] = width; - GROWABLE_HEAP_I32()[canvas3.canvasSharedPtr + 4 >> 2] = height; - } - if (canvas3.offscreenCanvas || !canvas3.controlTransferredOffscreen) { - if (canvas3.offscreenCanvas) - canvas3 = canvas3.offscreenCanvas; - var autoResizeViewport = false; - if (canvas3.GLctxObject && canvas3.GLctxObject.GLctx) { - var prevViewport = canvas3.GLctxObject.GLctx.getParameter(2978); - autoResizeViewport = prevViewport[0] === 0 && prevViewport[1] === 0 && prevViewport[2] === canvas3.width && prevViewport[3] === canvas3.height; - } - canvas3.width = width; - canvas3.height = height; - if (autoResizeViewport) { - canvas3.GLctxObject.GLctx.viewport(0, 0, width, height); - } - } else if (canvas3.canvasSharedPtr) { - var targetThread = GROWABLE_HEAP_I32()[canvas3.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 canvas3 = findCanvasEventTarget(target); - if (canvas3) { - return _emscripten_set_canvas_element_size_calling_thread(target, width, height); - } else { - return _emscripten_set_canvas_element_size_main_thread(target, width, height); - } - } - function _emscripten_set_current_thread_status(newStatus) { - } - function _emscripten_set_thread_name(threadId, name) { - } - function __webgl_enable_ANGLE_instanced_arrays(ctx) { - var ext = ctx.getExtension("ANGLE_instanced_arrays"); - if (ext) { - ctx["vertexAttribDivisor"] = function(index, divisor) { - ext["vertexAttribDivisorANGLE"](index, divisor); - }; - ctx["drawArraysInstanced"] = function(mode, first, count22, primcount) { - ext["drawArraysInstancedANGLE"](mode, first, count22, primcount); - }; - ctx["drawElementsInstanced"] = function(mode, count22, type, indices, primcount) { - ext["drawElementsInstancedANGLE"](mode, count22, type, indices, primcount); - }; - return 1; - } - } - function __webgl_enable_OES_vertex_array_object(ctx) { - var ext = ctx.getExtension("OES_vertex_array_object"); - if (ext) { - ctx["createVertexArray"] = function() { - return ext["createVertexArrayOES"](); - }; - ctx["deleteVertexArray"] = function(vao) { - ext["deleteVertexArrayOES"](vao); - }; - ctx["bindVertexArray"] = function(vao) { - ext["bindVertexArrayOES"](vao); - }; - ctx["isVertexArray"] = function(vao) { - return ext["isVertexArrayOES"](vao); - }; - return 1; - } - } - function __webgl_enable_WEBGL_draw_buffers(ctx) { - var ext = ctx.getExtension("WEBGL_draw_buffers"); - if (ext) { - ctx["drawBuffers"] = function(n, bufs) { - ext["drawBuffersWEBGL"](n, bufs); - }; - return 1; - } - } - function __webgl_enable_WEBGL_multi_draw(ctx) { - return !!(ctx.multiDrawWebgl = ctx.getExtension("WEBGL_multi_draw")); - } - var GL = { counter: 1, buffers: [], programs: [], framebuffers: [], renderbuffers: [], textures: [], uniforms: [], shaders: [], vaos: [], contexts: {}, offscreenCanvases: {}, timerQueriesEXT: [], programInfos: {}, stringCache: {}, unpackAlignment: 4, recordError: function recordError(errorCode) { - if (!GL.lastError) { - GL.lastError = errorCode; - } - }, getNewId: function(table) { - var ret = GL.counter++; - for (var i = table.length; i < ret; i++) { - table[i] = null; - } - return ret; - }, getSource: function(shader, count22, string3, length) { - var source = ""; - for (var i = 0; i < count22; ++i) { - var len = length ? GROWABLE_HEAP_I32()[length + i * 4 >> 2] : -1; - source += UTF8ToString(GROWABLE_HEAP_I32()[string3 + i * 4 >> 2], len < 0 ? void 0 : len); - } - return source; - }, createContext: function(canvas3, webGLContextAttributes) { - var ctx = canvas3.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 canvas3 = findCanvasEventTarget(target); - if (!canvas3) { - return 0; - } - if (contextAttributes.explicitSwapControl) { - return 0; - } - var contextHandle = GL.createContext(canvas3, contextAttributes); - return contextHandle; - } - function _emscripten_webgl_create_context(a0, a12) { - return _emscripten_webgl_do_create_context(a0, a12); - } - var SYSCALLS = { mappings: {}, buffers: [null, [], []], printChar: function(stream, curr) { - var buffer3 = SYSCALLS.buffers[stream]; - if (curr === 0 || curr === 10) { - (stream === 1 ? out : err)(UTF8ArrayToString(buffer3, 0)); - buffer3.length = 0; - } else { - buffer3.push(curr); - } - }, varargs: void 0, get: function() { - SYSCALLS.varargs += 4; - var ret = GROWABLE_HEAP_I32()[SYSCALLS.varargs - 4 >> 2]; - return ret; - }, getStr: function(ptr) { - var ret = UTF8ToString(ptr); - return ret; - }, get64: function(low, high) { - return low; - } }; - function _fd_close(fd) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(3, 1, fd); - return 0; - } - function _fd_seek(fd, offset_low, offset_high, whence, newOffset) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(4, 1, fd, offset_low, offset_high, whence, newOffset); - } - function _fd_write(fd, iov, iovcnt, pnum) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(5, 1, fd, iov, iovcnt, pnum); - var num = 0; - for (var i = 0; i < iovcnt; i++) { - var ptr = GROWABLE_HEAP_I32()[iov + i * 8 >> 2]; - var len = GROWABLE_HEAP_I32()[iov + (i * 8 + 4) >> 2]; - for (var j = 0; j < len; j++) { - SYSCALLS.printChar(fd, GROWABLE_HEAP_U8()[ptr + j]); - } - num += len; - } - GROWABLE_HEAP_I32()[pnum >> 2] = num; - return 0; - } - function _pthread_cleanup_pop(execute2) { - var routine = PThread.threadExitHandlers.pop(); - if (execute2) - routine(); - } - function _pthread_cleanup_push(routine, arg) { - PThread.threadExitHandlers.push(function() { - wasmTable.get(routine)(arg); - }); - } - function spawnThread(threadParams) { - if (ENVIRONMENT_IS_PTHREAD) - throw "Internal Error! spawnThread() can only ever be called from main application thread!"; - var worker = PThread.getNewWorker(); - if (worker.pthread !== void 0) - throw "Internal error!"; - if (!threadParams.pthread_ptr) - throw "Internal error, no pthread ptr!"; - PThread.runningWorkers.push(worker); - var tlsMemory = _malloc(128 * 4); - for (var i = 0; i < 128; ++i) { - GROWABLE_HEAP_I32()[tlsMemory + i * 4 >> 2] = 0; - } - var stackHigh = threadParams.stackBase + threadParams.stackSize; - var pthread = PThread.pthreads[threadParams.pthread_ptr] = { worker, stackBase: threadParams.stackBase, stackSize: threadParams.stackSize, allocatedOwnStack: threadParams.allocatedOwnStack, threadInfoStruct: threadParams.pthread_ptr }; - var tis = pthread.threadInfoStruct >> 2; - Atomics.store(GROWABLE_HEAP_U32(), tis + (64 >> 2), threadParams.detached); - Atomics.store(GROWABLE_HEAP_U32(), tis + (100 >> 2), tlsMemory); - Atomics.store(GROWABLE_HEAP_U32(), tis + (40 >> 2), pthread.threadInfoStruct); - Atomics.store(GROWABLE_HEAP_U32(), tis + (80 >> 2), threadParams.stackSize); - Atomics.store(GROWABLE_HEAP_U32(), tis + (76 >> 2), stackHigh); - Atomics.store(GROWABLE_HEAP_U32(), tis + (104 >> 2), threadParams.stackSize); - Atomics.store(GROWABLE_HEAP_U32(), tis + (104 + 8 >> 2), stackHigh); - Atomics.store(GROWABLE_HEAP_U32(), tis + (104 + 12 >> 2), threadParams.detached); - var global_libc = _emscripten_get_global_libc(); - var global_locale = global_libc + 40; - Atomics.store(GROWABLE_HEAP_U32(), tis + (172 >> 2), global_locale); - worker.pthread = pthread; - var msg = { "cmd": "run", "start_routine": threadParams.startRoutine, "arg": threadParams.arg, "threadInfoStruct": threadParams.pthread_ptr, "stackBase": threadParams.stackBase, "stackSize": threadParams.stackSize }; - worker.runPthread = function() { - msg.time = performance.now(); - worker.postMessage(msg, threadParams.transferList); - }; - if (worker.loaded) { - worker.runPthread(); - delete worker.runPthread; - } - } - function _pthread_create(pthread_ptr, attr, start_routine, arg) { - if (typeof SharedArrayBuffer === "undefined") { - err("Current environment does not support SharedArrayBuffer, pthreads are not available!"); - return 6; - } - if (!pthread_ptr) { - err("pthread_create called with a null thread pointer!"); - return 28; - } - var transferList = []; - var error = 0; - if (ENVIRONMENT_IS_PTHREAD && (transferList.length === 0 || error)) { - return _emscripten_sync_run_in_main_thread_4(687865856, pthread_ptr, attr, start_routine, arg); - } - if (error) - return error; - var stackSize = 0; - var stackBase = 0; - var detached = 0; - if (attr && attr != -1) { - stackSize = GROWABLE_HEAP_I32()[attr >> 2]; - stackSize += 81920; - stackBase = GROWABLE_HEAP_I32()[attr + 8 >> 2]; - detached = GROWABLE_HEAP_I32()[attr + 12 >> 2] !== 0; - } else { - stackSize = 2097152; - } - var allocatedOwnStack = stackBase == 0; - if (allocatedOwnStack) { - stackBase = _memalign(16, stackSize); - } else { - stackBase -= stackSize; - assert3(stackBase > 0); - } - var threadInfoStruct = _malloc(228); - for (var i = 0; i < 228 >> 2; ++i) - GROWABLE_HEAP_U32()[(threadInfoStruct >> 2) + i] = 0; - GROWABLE_HEAP_I32()[pthread_ptr >> 2] = threadInfoStruct; - GROWABLE_HEAP_I32()[threadInfoStruct + 12 >> 2] = threadInfoStruct; - var headPtr = threadInfoStruct + 152; - GROWABLE_HEAP_I32()[headPtr >> 2] = headPtr; - var threadParams = { stackBase, stackSize, allocatedOwnStack, detached, startRoutine: start_routine, pthread_ptr: threadInfoStruct, arg, transferList }; - if (ENVIRONMENT_IS_PTHREAD) { - threadParams.cmd = "spawnThread"; - postMessage(threadParams, transferList); - } else { - spawnThread(threadParams); - } - return 0; - } - function __pthread_testcancel_js() { - if (!ENVIRONMENT_IS_PTHREAD) - return; - var tb = _pthread_self(); - if (!tb) - return; - var cancelDisabled = Atomics.load(GROWABLE_HEAP_U32(), tb + 56 >> 2); - if (cancelDisabled) - return; - var canceled = Atomics.load(GROWABLE_HEAP_U32(), tb + 0 >> 2); - if (canceled == 2) - throw "Canceled!"; - } - function _emscripten_check_blocking_allowed() { - if (ENVIRONMENT_IS_NODE) - return; - if (ENVIRONMENT_IS_WORKER) - return; - warnOnce("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread"); - } - function __emscripten_do_pthread_join(thread, status, block) { - if (!thread) { - err("pthread_join attempted on a null thread pointer!"); - return ERRNO_CODES.ESRCH; - } - if (ENVIRONMENT_IS_PTHREAD && _pthread_self() == thread) { - err("PThread " + thread + " is attempting to join to itself!"); - return ERRNO_CODES.EDEADLK; - } else if (!ENVIRONMENT_IS_PTHREAD && _emscripten_main_browser_thread_id() == thread) { - err("Main thread " + thread + " is attempting to join to itself!"); - return ERRNO_CODES.EDEADLK; - } - var self2 = GROWABLE_HEAP_I32()[thread + 12 >> 2]; - if (self2 !== thread) { - err("pthread_join attempted on thread " + thread + ", which does not point to a valid thread, or does not exist anymore!"); - return ERRNO_CODES.ESRCH; - } - var detached = Atomics.load(GROWABLE_HEAP_U32(), thread + 64 >> 2); - if (detached) { - err("Attempted to join thread " + thread + ", which was already detached!"); - return ERRNO_CODES.EINVAL; - } - if (block) { - _emscripten_check_blocking_allowed(); - } - for (; ; ) { - var threadStatus = Atomics.load(GROWABLE_HEAP_U32(), thread + 0 >> 2); - if (threadStatus == 1) { - var threadExitCode = Atomics.load(GROWABLE_HEAP_U32(), thread + 4 >> 2); - if (status) - GROWABLE_HEAP_I32()[status >> 2] = threadExitCode; - Atomics.store(GROWABLE_HEAP_U32(), thread + 64 >> 2, 1); - if (!ENVIRONMENT_IS_PTHREAD) - cleanupThread(thread); - else - postMessage({ "cmd": "cleanupThread", "thread": thread }); - return 0; - } - if (!block) { - return ERRNO_CODES.EBUSY; - } - __pthread_testcancel_js(); - if (!ENVIRONMENT_IS_PTHREAD) - _emscripten_main_thread_process_queued_calls(); - _emscripten_futex_wait(thread + 0, threadStatus, ENVIRONMENT_IS_PTHREAD ? 100 : 1); - } - } - function _pthread_join(thread, status) { - return __emscripten_do_pthread_join(thread, status, true); - } - 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, "d": _emscripten_futex_wait, "c": _emscripten_futex_wake, "f": _emscripten_get_now, "p": _emscripten_memcpy_big, "A": _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, "s": _emscripten_set_thread_name, "w": _emscripten_webgl_create_context, "l": _fd_close, "n": _fd_seek, "g": _fd_write, "o": initPthreadsJS, "a": wasmMemory || Module["wasmMemory"], "z": _pthread_cleanup_pop, "k": _pthread_cleanup_push, "h": _pthread_create, "m": _pthread_join, "t": _sysconf }; - var asm = createWasm(); - var ___wasm_call_ctors = Module["___wasm_call_ctors"] = function() { - return (___wasm_call_ctors = Module["___wasm_call_ctors"] = Module["asm"]["B"]).apply(null, arguments); - }; - var _init = Module["_init"] = function() { - return (_init = Module["_init"] = Module["asm"]["C"]).apply(null, arguments); - }; - var _init_with_threads_count = Module["_init_with_threads_count"] = function() { - return (_init_with_threads_count = Module["_init_with_threads_count"] = Module["asm"]["D"]).apply(null, arguments); - }; - var _get_threads_count = Module["_get_threads_count"] = function() { - return (_get_threads_count = Module["_get_threads_count"] = Module["asm"]["E"]).apply(null, arguments); - }; - var _register_tensor = Module["_register_tensor"] = function() { - return (_register_tensor = Module["_register_tensor"] = Module["asm"]["F"]).apply(null, arguments); - }; - var _dispose_data = Module["_dispose_data"] = function() { - return (_dispose_data = Module["_dispose_data"] = Module["asm"]["G"]).apply(null, arguments); - }; - var _dispose = Module["_dispose"] = function() { - return (_dispose = Module["_dispose"] = Module["asm"]["H"]).apply(null, arguments); - }; - var _Abs = Module["_Abs"] = function() { - return (_Abs = Module["_Abs"] = Module["asm"]["I"]).apply(null, arguments); - }; - var _Add = Module["_Add"] = function() { - return (_Add = Module["_Add"] = Module["asm"]["J"]).apply(null, arguments); - }; - var _AddN = Module["_AddN"] = function() { - return (_AddN = Module["_AddN"] = Module["asm"]["K"]).apply(null, arguments); - }; - var _All = Module["_All"] = function() { - return (_All = Module["_All"] = Module["asm"]["L"]).apply(null, arguments); - }; - var _Any = Module["_Any"] = function() { - return (_Any = Module["_Any"] = Module["asm"]["M"]).apply(null, arguments); - }; - var _ArgMax = Module["_ArgMax"] = function() { - return (_ArgMax = Module["_ArgMax"] = Module["asm"]["N"]).apply(null, arguments); - }; - var _AvgPool = Module["_AvgPool"] = function() { - return (_AvgPool = Module["_AvgPool"] = Module["asm"]["O"]).apply(null, arguments); - }; - var _BatchMatMul = Module["_BatchMatMul"] = function() { - return (_BatchMatMul = Module["_BatchMatMul"] = Module["asm"]["P"]).apply(null, arguments); - }; - var _Ceil = Module["_Ceil"] = function() { - return (_Ceil = Module["_Ceil"] = Module["asm"]["Q"]).apply(null, arguments); - }; - var _ClipByValue = Module["_ClipByValue"] = function() { - return (_ClipByValue = Module["_ClipByValue"] = Module["asm"]["R"]).apply(null, arguments); - }; - var _Conv2D2 = Module["_Conv2D"] = function() { - return (_Conv2D2 = Module["_Conv2D"] = Module["asm"]["S"]).apply(null, arguments); - }; - var _Conv2DBackpropInput = Module["_Conv2DBackpropInput"] = function() { - return (_Conv2DBackpropInput = Module["_Conv2DBackpropInput"] = Module["asm"]["T"]).apply(null, arguments); - }; - var _Cos = Module["_Cos"] = function() { - return (_Cos = Module["_Cos"] = Module["asm"]["U"]).apply(null, arguments); - }; - var _Cosh = Module["_Cosh"] = function() { - return (_Cosh = Module["_Cosh"] = Module["asm"]["V"]).apply(null, arguments); - }; - var _CropAndResize = Module["_CropAndResize"] = function() { - return (_CropAndResize = Module["_CropAndResize"] = Module["asm"]["W"]).apply(null, arguments); - }; - var _Cumsum = Module["_Cumsum"] = function() { - return (_Cumsum = Module["_Cumsum"] = Module["asm"]["X"]).apply(null, arguments); - }; - var _DepthToSpace = Module["_DepthToSpace"] = function() { - return (_DepthToSpace = Module["_DepthToSpace"] = Module["asm"]["Y"]).apply(null, arguments); - }; - var _DepthwiseConv2dNative = Module["_DepthwiseConv2dNative"] = function() { - return (_DepthwiseConv2dNative = Module["_DepthwiseConv2dNative"] = Module["asm"]["Z"]).apply(null, arguments); - }; - var _Elu = Module["_Elu"] = function() { - return (_Elu = Module["_Elu"] = Module["asm"]["_"]).apply(null, arguments); - }; - var _Equal = Module["_Equal"] = function() { - return (_Equal = Module["_Equal"] = Module["asm"]["$"]).apply(null, arguments); - }; - var _Exp = Module["_Exp"] = function() { - return (_Exp = Module["_Exp"] = Module["asm"]["aa"]).apply(null, arguments); - }; - var _FlipLeftRight = Module["_FlipLeftRight"] = function() { - return (_FlipLeftRight = Module["_FlipLeftRight"] = Module["asm"]["ba"]).apply(null, arguments); - }; - var _Floor = Module["_Floor"] = function() { - return (_Floor = Module["_Floor"] = Module["asm"]["ca"]).apply(null, arguments); - }; - var _FloorDiv = Module["_FloorDiv"] = function() { - return (_FloorDiv = Module["_FloorDiv"] = Module["asm"]["da"]).apply(null, arguments); - }; - var _FusedBatchNorm = Module["_FusedBatchNorm"] = function() { - return (_FusedBatchNorm = Module["_FusedBatchNorm"] = Module["asm"]["ea"]).apply(null, arguments); - }; - var _FusedConv2D = Module["_FusedConv2D"] = function() { - return (_FusedConv2D = Module["_FusedConv2D"] = Module["asm"]["fa"]).apply(null, arguments); - }; - var _FusedDepthwiseConv2D = Module["_FusedDepthwiseConv2D"] = function() { - return (_FusedDepthwiseConv2D = Module["_FusedDepthwiseConv2D"] = Module["asm"]["ga"]).apply(null, arguments); - }; - var _Gather = Module["_Gather"] = function() { - return (_Gather = Module["_Gather"] = Module["asm"]["ha"]).apply(null, arguments); - }; - var _GatherNd = Module["_GatherNd"] = function() { - return (_GatherNd = Module["_GatherNd"] = Module["asm"]["ia"]).apply(null, arguments); - }; - var _Greater = Module["_Greater"] = function() { - return (_Greater = Module["_Greater"] = Module["asm"]["ja"]).apply(null, arguments); - }; - var _GreaterEqual = Module["_GreaterEqual"] = function() { - return (_GreaterEqual = Module["_GreaterEqual"] = Module["asm"]["ka"]).apply(null, arguments); - }; - var _LeakyRelu = Module["_LeakyRelu"] = function() { - return (_LeakyRelu = Module["_LeakyRelu"] = Module["asm"]["la"]).apply(null, arguments); - }; - var _Less = Module["_Less"] = function() { - return (_Less = Module["_Less"] = Module["asm"]["ma"]).apply(null, arguments); - }; - var _LessEqual = Module["_LessEqual"] = function() { - return (_LessEqual = Module["_LessEqual"] = Module["asm"]["na"]).apply(null, arguments); - }; - var _Log = Module["_Log"] = function() { - return (_Log = Module["_Log"] = Module["asm"]["oa"]).apply(null, arguments); - }; - var _LogicalAnd = Module["_LogicalAnd"] = function() { - return (_LogicalAnd = Module["_LogicalAnd"] = Module["asm"]["pa"]).apply(null, arguments); - }; - var _Max = Module["_Max"] = function() { - return (_Max = Module["_Max"] = Module["asm"]["qa"]).apply(null, arguments); - }; - var _MaxPool = Module["_MaxPool"] = function() { - return (_MaxPool = Module["_MaxPool"] = Module["asm"]["ra"]).apply(null, arguments); - }; - var _Maximum = Module["_Maximum"] = function() { - return (_Maximum = Module["_Maximum"] = Module["asm"]["sa"]).apply(null, arguments); - }; - var _Mean = Module["_Mean"] = function() { - return (_Mean = Module["_Mean"] = Module["asm"]["ta"]).apply(null, arguments); - }; - var _Min = Module["_Min"] = function() { - return (_Min = Module["_Min"] = Module["asm"]["ua"]).apply(null, arguments); - }; - var _Minimum = Module["_Minimum"] = function() { - return (_Minimum = Module["_Minimum"] = Module["asm"]["va"]).apply(null, arguments); - }; - var _MirrorPad = Module["_MirrorPad"] = function() { - return (_MirrorPad = Module["_MirrorPad"] = Module["asm"]["wa"]).apply(null, arguments); - }; - var _Multiply = Module["_Multiply"] = function() { - return (_Multiply = Module["_Multiply"] = Module["asm"]["xa"]).apply(null, arguments); - }; - var _Neg = Module["_Neg"] = function() { - return (_Neg = Module["_Neg"] = Module["asm"]["ya"]).apply(null, arguments); - }; - var _NonMaxSuppressionV3 = Module["_NonMaxSuppressionV3"] = function() { - return (_NonMaxSuppressionV3 = Module["_NonMaxSuppressionV3"] = Module["asm"]["za"]).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"]["_a"]).apply(null, arguments); - }; - var _Sum = Module["_Sum"] = function() { - return (_Sum = Module["_Sum"] = Module["asm"]["$a"]).apply(null, arguments); - }; - var _Tan = Module["_Tan"] = function() { - return (_Tan = Module["_Tan"] = Module["asm"]["ab"]).apply(null, arguments); - }; - var _Tanh = Module["_Tanh"] = function() { - return (_Tanh = Module["_Tanh"] = Module["asm"]["bb"]).apply(null, arguments); - }; - var _Tile = Module["_Tile"] = function() { - return (_Tile = Module["_Tile"] = Module["asm"]["cb"]).apply(null, arguments); - }; - var _TopK = Module["_TopK"] = function() { - return (_TopK = Module["_TopK"] = Module["asm"]["db"]).apply(null, arguments); - }; - var _Transform = Module["_Transform"] = function() { - return (_Transform = Module["_Transform"] = Module["asm"]["eb"]).apply(null, arguments); - }; - var _Transpose = Module["_Transpose"] = function() { - return (_Transpose = Module["_Transpose"] = Module["asm"]["fb"]).apply(null, arguments); - }; - var __FusedMatMul = Module["__FusedMatMul"] = function() { - return (__FusedMatMul = Module["__FusedMatMul"] = Module["asm"]["gb"]).apply(null, arguments); - }; - var _malloc = Module["_malloc"] = function() { - return (_malloc = Module["_malloc"] = Module["asm"]["hb"]).apply(null, arguments); - }; - var _free = Module["_free"] = function() { - return (_free = Module["_free"] = Module["asm"]["ib"]).apply(null, arguments); - }; - var ___errno_location = Module["___errno_location"] = function() { - return (___errno_location = Module["___errno_location"] = Module["asm"]["jb"]).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"]["lb"]).apply(null, arguments); - }; - var _pthread_self = Module["_pthread_self"] = function() { - return (_pthread_self = Module["_pthread_self"] = Module["asm"]["mb"]).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"]["nb"]).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"]["ob"]).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"]["pb"]).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"]["qb"]).apply(null, arguments); - }; - var _emscripten_main_browser_thread_id = Module["_emscripten_main_browser_thread_id"] = function() { - return (_emscripten_main_browser_thread_id = Module["_emscripten_main_browser_thread_id"] = Module["asm"]["rb"]).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"]["sb"]).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"]["tb"]).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"]["ub"]).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"]["vb"]).apply(null, arguments); - }; - var _emscripten_tls_init = Module["_emscripten_tls_init"] = function() { - return (_emscripten_tls_init = Module["_emscripten_tls_init"] = Module["asm"]["wb"]).apply(null, arguments); - }; - var __emscripten_thread_init = Module["__emscripten_thread_init"] = function() { - return (__emscripten_thread_init = Module["__emscripten_thread_init"] = Module["asm"]["xb"]).apply(null, arguments); - }; - var stackSave = Module["stackSave"] = function() { - return (stackSave = Module["stackSave"] = Module["asm"]["yb"]).apply(null, arguments); - }; - var stackRestore = Module["stackRestore"] = function() { - return (stackRestore = Module["stackRestore"] = Module["asm"]["zb"]).apply(null, arguments); - }; - var stackAlloc = Module["stackAlloc"] = function() { - return (stackAlloc = Module["stackAlloc"] = Module["asm"]["Ab"]).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"]["Bb"]).apply(null, arguments); - }; - var _memalign = Module["_memalign"] = function() { - return (_memalign = Module["_memalign"] = Module["asm"]["Cb"]).apply(null, arguments); - }; - var __emscripten_allow_main_runtime_queued_calls = Module["__emscripten_allow_main_runtime_queued_calls"] = 10064; - var __emscripten_main_thread_futex = Module["__emscripten_main_thread_futex"] = 10268; - Module["cwrap"] = cwrap; - Module["PThread"] = PThread; - Module["PThread"] = PThread; - Module["wasmMemory"] = wasmMemory; - Module["ExitStatus"] = ExitStatus; - var calledRun; - function ExitStatus(status) { - this.name = "ExitStatus"; - this.message = "Program terminated with exit(" + status + ")"; - this.status = status; - } - dependenciesFulfilled = function runCaller() { - if (!calledRun) - run(); - if (!calledRun) - dependenciesFulfilled = runCaller; - }; - function run(args) { - args = args || arguments_; - if (runDependencies > 0) { - return; - } - if (ENVIRONMENT_IS_PTHREAD) { - readyPromiseResolve(Module); - initRuntime(); - postMessage({ "cmd": "loaded" }); - return; - } - preRun(); - if (runDependencies > 0) { - return; - } - function doRun() { - if (calledRun) - return; - calledRun = true; - Module["calledRun"] = true; - if (ABORT) - return; - initRuntime(); - preMain(); - readyPromiseResolve(Module); - if (Module["onRuntimeInitialized"]) - Module["onRuntimeInitialized"](); - postRun(); - } - if (Module["setStatus"]) { - Module["setStatus"]("Running..."); - setTimeout(function() { - setTimeout(function() { - Module["setStatus"](""); - }, 1); - doRun(); - }, 1); - } else { - doRun(); - } - } - Module["run"] = run; - function exit(status, implicit) { - if (implicit && noExitRuntime && status === 0) { - return; - } - if (!implicit) { - if (ENVIRONMENT_IS_PTHREAD) { - postMessage({ "cmd": "exitProcess", "returnCode": status }); - throw new ExitStatus(status); - } else { - } - } - if (noExitRuntime) { - } else { - PThread.terminateAllThreads(); - EXITSTATUS = status; - exitRuntime(); - if (Module["onExit"]) - Module["onExit"](status); - ABORT = true; - } - quit_(status, new ExitStatus(status)); - } - if (Module["preInit"]) { - if (typeof Module["preInit"] == "function") - Module["preInit"] = [Module["preInit"]]; - while (Module["preInit"].length > 0) { - Module["preInit"].pop()(); - } - } - if (ENVIRONMENT_IS_PTHREAD) { - noExitRuntime = false; - PThread.initWorker(); - } - run(); - return WasmBackendModuleThreadedSimd2.ready; - }; - }(); - if (typeof exports === "object" && typeof module === "object") - module.exports = WasmBackendModuleThreadedSimd; - else if (typeof define === "function" && define["amd"]) - define([], function() { - return WasmBackendModuleThreadedSimd; - }); - else if (typeof exports === "object") - exports["WasmBackendModuleThreadedSimd"] = WasmBackendModuleThreadedSimd; - } -}); -var require_tfjs_backend_wasm = __commonJS({ - "src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm.js"(exports, module) { - var WasmBackendModule = function() { - var _scriptDir = typeof document !== "undefined" && document.currentScript ? document.currentScript.src : void 0; - if (typeof __filename !== "undefined") - _scriptDir = _scriptDir || __filename; - return function(WasmBackendModule2) { - WasmBackendModule2 = WasmBackendModule2 || {}; - var Module = typeof WasmBackendModule2 !== "undefined" ? WasmBackendModule2 : {}; - var readyPromiseResolve, readyPromiseReject; - Module["ready"] = new Promise(function(resolve, reject) { - readyPromiseResolve = resolve; - readyPromiseReject = reject; - }); - var moduleOverrides = {}; - var key; - for (key in Module) { - if (Module.hasOwnProperty(key)) { - moduleOverrides[key] = Module[key]; - } - } - var arguments_ = []; - var thisProgram = "./this.program"; - var quit_ = function(status, toThrow) { - throw toThrow; - }; - var ENVIRONMENT_IS_WEB = false; - var ENVIRONMENT_IS_WORKER = false; - var ENVIRONMENT_IS_NODE = false; - var ENVIRONMENT_IS_SHELL = false; - ENVIRONMENT_IS_WEB = typeof window === "object"; - ENVIRONMENT_IS_WORKER = typeof importScripts === "function"; - ENVIRONMENT_IS_NODE = typeof process === "object" && typeof process.versions === "object" && typeof process.versions.node === "string"; - ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER; - var scriptDirectory = ""; - function locateFile(path) { - if (Module["locateFile"]) { - return Module["locateFile"](path, scriptDirectory); - } - return scriptDirectory + path; - } - var read_, readAsync, readBinary, setWindowTitle; - var nodeFS; - var nodePath; - if (ENVIRONMENT_IS_NODE) { - if (ENVIRONMENT_IS_WORKER) { - scriptDirectory = __require22("path").dirname(scriptDirectory) + "/"; - } else { - scriptDirectory = __dirname + "/"; - } - read_ = function shell_read(filename, binary) { - if (!nodeFS) - nodeFS = __require22("fs"); - if (!nodePath) - nodePath = __require22("path"); - filename = nodePath["normalize"](filename); - return nodeFS["readFileSync"](filename, binary ? null : "utf8"); - }; - readBinary = function readBinary2(filename) { - var ret = read_(filename, true); - if (!ret.buffer) { - ret = new Uint8Array(ret); - } - assert3(ret.buffer); - return ret; - }; - if (process["argv"].length > 1) { - thisProgram = process["argv"][1].replace(/\\/g, "/"); - } - arguments_ = process["argv"].slice(2); - process["on"]("uncaughtException", function(ex) { - if (!(ex instanceof ExitStatus)) { - throw ex; - } - }); - process["on"]("unhandledRejection", abort); - quit_ = function(status) { - process["exit"](status); - }; - Module["inspect"] = function() { - return "[Emscripten Module object]"; - }; - } else if (ENVIRONMENT_IS_SHELL) { - if (typeof read != "undefined") { - read_ = function shell_read(f) { - return read(f); - }; - } - readBinary = function readBinary2(f) { - var data; - if (typeof readbuffer === "function") { - return new Uint8Array(readbuffer(f)); - } - data = read(f, "binary"); - assert3(typeof data === "object"); - return data; - }; - if (typeof scriptArgs != "undefined") { - arguments_ = scriptArgs; - } else if (typeof arguments != "undefined") { - arguments_ = arguments; - } - if (typeof quit === "function") { - quit_ = function(status) { - quit(status); - }; - } - if (typeof print !== "undefined") { - if (typeof console === "undefined") - console = {}; - console.log = print; - console.warn = console.error = typeof printErr !== "undefined" ? printErr : print; - } - } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { - if (ENVIRONMENT_IS_WORKER) { - scriptDirectory = self.location.href; - } else if (typeof document !== "undefined" && document.currentScript) { - scriptDirectory = document.currentScript.src; - } - if (_scriptDir) { - scriptDirectory = _scriptDir; - } - if (scriptDirectory.indexOf("blob:") !== 0) { - scriptDirectory = scriptDirectory.substr(0, scriptDirectory.lastIndexOf("/") + 1); - } else { - scriptDirectory = ""; - } - { - read_ = function(url) { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, false); - xhr.send(null); - return xhr.responseText; - }; - if (ENVIRONMENT_IS_WORKER) { - readBinary = function(url) { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, false); - xhr.responseType = "arraybuffer"; - xhr.send(null); - return new Uint8Array(xhr.response); - }; - } - readAsync = function(url, onload, onerror) { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, true); - xhr.responseType = "arraybuffer"; - xhr.onload = function() { - if (xhr.status == 200 || xhr.status == 0 && xhr.response) { - onload(xhr.response); - return; - } - onerror(); - }; - xhr.onerror = onerror; - xhr.send(null); - }; - } - setWindowTitle = function(title) { - document.title = title; - }; - } else { - } - var out = Module["print"] || console.log.bind(console); - var err = Module["printErr"] || console.warn.bind(console); - for (key in moduleOverrides) { - if (moduleOverrides.hasOwnProperty(key)) { - Module[key] = moduleOverrides[key]; - } - } - moduleOverrides = null; - if (Module["arguments"]) - arguments_ = Module["arguments"]; - if (Module["thisProgram"]) - thisProgram = Module["thisProgram"]; - if (Module["quit"]) - quit_ = Module["quit"]; - var wasmBinary; - if (Module["wasmBinary"]) - wasmBinary = Module["wasmBinary"]; - var noExitRuntime = Module["noExitRuntime"] || true; - if (typeof WebAssembly !== "object") { - abort("no native wasm support detected"); - } - var wasmMemory; - var ABORT = false; - var EXITSTATUS; - function assert3(condition, text) { - if (!condition) { - abort("Assertion failed: " + text); - } - } - function getCFunc(ident) { - var func2 = Module["_" + ident]; - assert3(func2, "Cannot call unknown function " + ident + ", make sure it is exported"); - return func2; - } - function ccall(ident, returnType, argTypes, args, opts) { - var toC = { "string": function(str) { - var ret2 = 0; - if (str !== null && str !== void 0 && str !== 0) { - var len = (str.length << 2) + 1; - ret2 = stackAlloc(len); - stringToUTF8(str, ret2, len); - } - return ret2; - }, "array": function(arr) { - var ret2 = stackAlloc(arr.length); - writeArrayToMemory(arr, ret2); - return ret2; - } }; - function convertReturnValue(ret2) { - if (returnType === "string") - return UTF8ToString(ret2); - if (returnType === "boolean") - return Boolean(ret2); - return ret2; - } - var func2 = getCFunc(ident); - var cArgs = []; - var stack2 = 0; - if (args) { - for (var i = 0; i < args.length; i++) { - var converter = toC[argTypes[i]]; - if (converter) { - if (stack2 === 0) - stack2 = stackSave(); - cArgs[i] = converter(args[i]); - } else { - cArgs[i] = args[i]; - } - } - } - var ret = func2.apply(null, cArgs); - ret = convertReturnValue(ret); - if (stack2 !== 0) - stackRestore(stack2); - return ret; - } - function cwrap(ident, returnType, argTypes, opts) { - argTypes = argTypes || []; - var numericArgs = argTypes.every(function(type) { - return type === "number"; - }); - var numericRet = returnType !== "string"; - if (numericRet && numericArgs && !opts) { - return getCFunc(ident); - } - return function() { - return ccall(ident, returnType, argTypes, arguments, opts); - }; - } - var UTF8Decoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf8") : void 0; - function UTF8ArrayToString(heap, idx, maxBytesToRead) { - var endIdx = idx + maxBytesToRead; - var endPtr = idx; - while (heap[endPtr] && !(endPtr >= endIdx)) - ++endPtr; - if (endPtr - idx > 16 && heap.subarray && UTF8Decoder) { - return UTF8Decoder.decode(heap.subarray(idx, endPtr)); - } else { - var str = ""; - while (idx < endPtr) { - var u0 = heap[idx++]; - if (!(u0 & 128)) { - str += String.fromCharCode(u0); - continue; - } - var u1 = heap[idx++] & 63; - if ((u0 & 224) == 192) { - str += String.fromCharCode((u0 & 31) << 6 | u1); - continue; - } - var u2 = heap[idx++] & 63; - if ((u0 & 240) == 224) { - u0 = (u0 & 15) << 12 | u1 << 6 | u2; - } else { - u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heap[idx++] & 63; - } - if (u0 < 65536) { - str += String.fromCharCode(u0); - } else { - var ch = u0 - 65536; - str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023); - } - } - } - return str; - } - function UTF8ToString(ptr, maxBytesToRead) { - return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : ""; - } - function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) { - if (!(maxBytesToWrite > 0)) - return 0; - var startIdx = outIdx; - var endIdx = outIdx + maxBytesToWrite - 1; - for (var i = 0; i < str.length; ++i) { - var u = str.charCodeAt(i); - if (u >= 55296 && u <= 57343) { - var u1 = str.charCodeAt(++i); - u = 65536 + ((u & 1023) << 10) | u1 & 1023; - } - if (u <= 127) { - if (outIdx >= endIdx) - break; - heap[outIdx++] = u; - } else if (u <= 2047) { - if (outIdx + 1 >= endIdx) - break; - heap[outIdx++] = 192 | u >> 6; - heap[outIdx++] = 128 | u & 63; - } else if (u <= 65535) { - if (outIdx + 2 >= endIdx) - break; - heap[outIdx++] = 224 | u >> 12; - heap[outIdx++] = 128 | u >> 6 & 63; - heap[outIdx++] = 128 | u & 63; - } else { - if (outIdx + 3 >= endIdx) - break; - heap[outIdx++] = 240 | u >> 18; - heap[outIdx++] = 128 | u >> 12 & 63; - heap[outIdx++] = 128 | u >> 6 & 63; - heap[outIdx++] = 128 | u & 63; - } - } - heap[outIdx] = 0; - return outIdx - startIdx; - } - function stringToUTF8(str, outPtr, maxBytesToWrite) { - return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite); - } - function writeArrayToMemory(array2, buffer3) { - HEAP8.set(array2, buffer3); - } - function alignUp(x, multiple) { - if (x % multiple > 0) { - x += multiple - x % multiple; - } - return x; - } - var buffer2, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64; - function updateGlobalBufferAndViews(buf) { - buffer2 = buf; - Module["HEAP8"] = HEAP8 = new Int8Array(buf); - Module["HEAP16"] = HEAP16 = new Int16Array(buf); - Module["HEAP32"] = HEAP32 = new Int32Array(buf); - Module["HEAPU8"] = HEAPU8 = new Uint8Array(buf); - Module["HEAPU16"] = HEAPU16 = new Uint16Array(buf); - Module["HEAPU32"] = HEAPU32 = new Uint32Array(buf); - Module["HEAPF32"] = HEAPF32 = new Float32Array(buf); - Module["HEAPF64"] = HEAPF64 = new Float64Array(buf); - } - var INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 16777216; - var wasmTable; - var __ATPRERUN__ = []; - var __ATINIT__ = []; - var __ATMAIN__ = []; - var __ATPOSTRUN__ = []; - var runtimeInitialized = false; - __ATINIT__.push({ func: function() { - ___wasm_call_ctors(); - } }); - function preRun() { - if (Module["preRun"]) { - if (typeof Module["preRun"] == "function") - Module["preRun"] = [Module["preRun"]]; - while (Module["preRun"].length) { - addOnPreRun(Module["preRun"].shift()); - } - } - callRuntimeCallbacks(__ATPRERUN__); - } - function initRuntime() { - runtimeInitialized = true; - callRuntimeCallbacks(__ATINIT__); - } - function preMain() { - callRuntimeCallbacks(__ATMAIN__); - } - function postRun() { - if (Module["postRun"]) { - if (typeof Module["postRun"] == "function") - Module["postRun"] = [Module["postRun"]]; - while (Module["postRun"].length) { - addOnPostRun(Module["postRun"].shift()); - } - } - callRuntimeCallbacks(__ATPOSTRUN__); - } - function addOnPreRun(cb) { - __ATPRERUN__.unshift(cb); - } - function addOnPostRun(cb) { - __ATPOSTRUN__.unshift(cb); - } - var runDependencies = 0; - var runDependencyWatcher = null; - var dependenciesFulfilled = null; - function addRunDependency(id) { - runDependencies++; - if (Module["monitorRunDependencies"]) { - Module["monitorRunDependencies"](runDependencies); - } - } - function removeRunDependency(id) { - runDependencies--; - if (Module["monitorRunDependencies"]) { - Module["monitorRunDependencies"](runDependencies); - } - if (runDependencies == 0) { - if (runDependencyWatcher !== null) { - clearInterval(runDependencyWatcher); - runDependencyWatcher = null; - } - if (dependenciesFulfilled) { - var callback = dependenciesFulfilled; - dependenciesFulfilled = null; - callback(); - } - } - } - Module["preloadedImages"] = {}; - Module["preloadedAudios"] = {}; - function abort(what) { - if (Module["onAbort"]) { - Module["onAbort"](what); - } - what += ""; - err(what); - ABORT = true; - EXITSTATUS = 1; - what = "abort(" + what + "). Build with -s ASSERTIONS=1 for more info."; - var e = new WebAssembly.RuntimeError(what); - readyPromiseReject(e); - throw e; - } - function hasPrefix(str, prefix) { - return String.prototype.startsWith ? str.startsWith(prefix) : str.indexOf(prefix) === 0; - } - var dataURIPrefix = "data:application/octet-stream;base64,"; - function isDataURI(filename) { - return hasPrefix(filename, dataURIPrefix); - } - var fileURIPrefix = "file://"; - function isFileURI(filename) { - return hasPrefix(filename, fileURIPrefix); - } - var wasmBinaryFile = "tfjs-backend-wasm.wasm"; - if (!isDataURI(wasmBinaryFile)) { - wasmBinaryFile = locateFile(wasmBinaryFile); - } - function getBinary(file) { - try { - if (file == wasmBinaryFile && wasmBinary) { - return new Uint8Array(wasmBinary); - } - if (readBinary) { - return readBinary(file); - } else { - throw "both async and sync fetching of the wasm failed"; - } - } catch (err2) { - abort(err2); - } - } - function getBinaryPromise() { - if (!wasmBinary && (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER)) { - if (typeof fetch === "function" && !isFileURI(wasmBinaryFile)) { - return fetch(wasmBinaryFile, { credentials: "same-origin" }).then(function(response) { - if (!response["ok"]) { - throw "failed to load wasm binary file at '" + wasmBinaryFile + "'"; - } - return response["arrayBuffer"](); - }).catch(function() { - return getBinary(wasmBinaryFile); - }); - } else { - if (readAsync) { - return new Promise(function(resolve, reject) { - readAsync(wasmBinaryFile, function(response) { - resolve(new Uint8Array(response)); - }, reject); - }); - } - } - } - return Promise.resolve().then(function() { - return getBinary(wasmBinaryFile); - }); - } - function createWasm() { - var info = { "a": asmLibraryArg }; - function receiveInstance(instance, module2) { - var exports3 = instance.exports; - Module["asm"] = exports3; - wasmMemory = Module["asm"]["h"]; - updateGlobalBufferAndViews(wasmMemory.buffer); - wasmTable = Module["asm"]["Sa"]; - removeRunDependency("wasm-instantiate"); - } - addRunDependency("wasm-instantiate"); - function receiveInstantiatedSource(output) { - receiveInstance(output["instance"]); - } - function instantiateArrayBuffer(receiver) { - return getBinaryPromise().then(function(binary) { - return WebAssembly.instantiate(binary, info); - }).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, info); - 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"](info, 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(size2) { - try { - wasmMemory.grow(size2 - buffer2.byteLength + 65535 >>> 16); - updateGlobalBufferAndViews(wasmMemory.buffer); - return 1; - } catch (e) { - } - } - function _emscripten_resize_heap(requestedSize) { - var oldSize = _emscripten_get_heap_size(); - var maxHeapSize = 2147483648; - if (requestedSize > maxHeapSize) { - return false; - } - for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { - var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown); - overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296); - var newSize = Math.min(maxHeapSize, alignUp(Math.max(requestedSize, overGrownHeapSize), 65536)); - var replacement = emscripten_realloc_buffer(newSize); - if (replacement) { - return true; - } - } - return false; - } - var SYSCALLS = { mappings: {}, buffers: [null, [], []], printChar: function(stream, curr) { - var buffer3 = SYSCALLS.buffers[stream]; - if (curr === 0 || curr === 10) { - (stream === 1 ? out : err)(UTF8ArrayToString(buffer3, 0)); - buffer3.length = 0; - } else { - buffer3.push(curr); - } - }, varargs: void 0, get: function() { - SYSCALLS.varargs += 4; - var ret = HEAP32[SYSCALLS.varargs - 4 >> 2]; - return ret; - }, getStr: function(ptr) { - var ret = UTF8ToString(ptr); - return ret; - }, get64: function(low, high) { - return low; - } }; - function _fd_close(fd) { - return 0; - } - function _fd_seek(fd, offset_low, offset_high, whence, newOffset) { - } - function _fd_write(fd, iov, iovcnt, pnum) { - var num = 0; - for (var i = 0; i < iovcnt; i++) { - var ptr = HEAP32[iov + i * 8 >> 2]; - var len = HEAP32[iov + (i * 8 + 4) >> 2]; - for (var j = 0; j < len; j++) { - SYSCALLS.printChar(fd, HEAPU8[ptr + j]); - } - num += len; - } - HEAP32[pnum >> 2] = num; - return 0; - } - function _pthread_join() { - return 28; - } - var asmLibraryArg = { "a": _abort, "d": _emscripten_memcpy_big, "e": _emscripten_resize_heap, "f": _fd_close, "c": _fd_seek, "b": _fd_write, "g": _pthread_join }; - var asm = createWasm(); - var ___wasm_call_ctors = Module["___wasm_call_ctors"] = function() { - return (___wasm_call_ctors = Module["___wasm_call_ctors"] = Module["asm"]["i"]).apply(null, arguments); - }; - var _init = Module["_init"] = function() { - return (_init = Module["_init"] = Module["asm"]["j"]).apply(null, arguments); - }; - var _init_with_threads_count = Module["_init_with_threads_count"] = function() { - return (_init_with_threads_count = Module["_init_with_threads_count"] = Module["asm"]["k"]).apply(null, arguments); - }; - var _get_threads_count = Module["_get_threads_count"] = function() { - return (_get_threads_count = Module["_get_threads_count"] = Module["asm"]["l"]).apply(null, arguments); - }; - var _register_tensor = Module["_register_tensor"] = function() { - return (_register_tensor = Module["_register_tensor"] = Module["asm"]["m"]).apply(null, arguments); - }; - var _dispose_data = Module["_dispose_data"] = function() { - return (_dispose_data = Module["_dispose_data"] = Module["asm"]["n"]).apply(null, arguments); - }; - var _dispose = Module["_dispose"] = function() { - return (_dispose = Module["_dispose"] = Module["asm"]["o"]).apply(null, arguments); - }; - var _Abs = Module["_Abs"] = function() { - return (_Abs = Module["_Abs"] = Module["asm"]["p"]).apply(null, arguments); - }; - var _Add = Module["_Add"] = function() { - return (_Add = Module["_Add"] = Module["asm"]["q"]).apply(null, arguments); - }; - var _AddN = Module["_AddN"] = function() { - return (_AddN = Module["_AddN"] = Module["asm"]["r"]).apply(null, arguments); - }; - var _All = Module["_All"] = function() { - return (_All = Module["_All"] = Module["asm"]["s"]).apply(null, arguments); - }; - var _Any = Module["_Any"] = function() { - return (_Any = Module["_Any"] = Module["asm"]["t"]).apply(null, arguments); - }; - var _ArgMax = Module["_ArgMax"] = function() { - return (_ArgMax = Module["_ArgMax"] = Module["asm"]["u"]).apply(null, arguments); - }; - var _AvgPool = Module["_AvgPool"] = function() { - return (_AvgPool = Module["_AvgPool"] = Module["asm"]["v"]).apply(null, arguments); - }; - var _BatchMatMul = Module["_BatchMatMul"] = function() { - return (_BatchMatMul = Module["_BatchMatMul"] = Module["asm"]["w"]).apply(null, arguments); - }; - var _Ceil = Module["_Ceil"] = function() { - return (_Ceil = Module["_Ceil"] = Module["asm"]["x"]).apply(null, arguments); - }; - var _ClipByValue = Module["_ClipByValue"] = function() { - return (_ClipByValue = Module["_ClipByValue"] = Module["asm"]["y"]).apply(null, arguments); - }; - var _Conv2D2 = Module["_Conv2D"] = function() { - return (_Conv2D2 = Module["_Conv2D"] = Module["asm"]["z"]).apply(null, arguments); - }; - var _Conv2DBackpropInput = Module["_Conv2DBackpropInput"] = function() { - return (_Conv2DBackpropInput = Module["_Conv2DBackpropInput"] = Module["asm"]["A"]).apply(null, arguments); - }; - var _Cos = Module["_Cos"] = function() { - return (_Cos = Module["_Cos"] = Module["asm"]["B"]).apply(null, arguments); - }; - var _Cosh = Module["_Cosh"] = function() { - return (_Cosh = Module["_Cosh"] = Module["asm"]["C"]).apply(null, arguments); - }; - var _CropAndResize = Module["_CropAndResize"] = function() { - return (_CropAndResize = Module["_CropAndResize"] = Module["asm"]["D"]).apply(null, arguments); - }; - var _Cumsum = Module["_Cumsum"] = function() { - return (_Cumsum = Module["_Cumsum"] = Module["asm"]["E"]).apply(null, arguments); - }; - var _DepthToSpace = Module["_DepthToSpace"] = function() { - return (_DepthToSpace = Module["_DepthToSpace"] = Module["asm"]["F"]).apply(null, arguments); - }; - var _DepthwiseConv2dNative = Module["_DepthwiseConv2dNative"] = function() { - return (_DepthwiseConv2dNative = Module["_DepthwiseConv2dNative"] = Module["asm"]["G"]).apply(null, arguments); - }; - var _Elu = Module["_Elu"] = function() { - return (_Elu = Module["_Elu"] = Module["asm"]["H"]).apply(null, arguments); - }; - var _Equal = Module["_Equal"] = function() { - return (_Equal = Module["_Equal"] = Module["asm"]["I"]).apply(null, arguments); - }; - var _Exp = Module["_Exp"] = function() { - return (_Exp = Module["_Exp"] = Module["asm"]["J"]).apply(null, arguments); - }; - var _FlipLeftRight = Module["_FlipLeftRight"] = function() { - return (_FlipLeftRight = Module["_FlipLeftRight"] = Module["asm"]["K"]).apply(null, arguments); - }; - var _Floor = Module["_Floor"] = function() { - return (_Floor = Module["_Floor"] = Module["asm"]["L"]).apply(null, arguments); - }; - var _FloorDiv = Module["_FloorDiv"] = function() { - return (_FloorDiv = Module["_FloorDiv"] = Module["asm"]["M"]).apply(null, arguments); - }; - var _FusedBatchNorm = Module["_FusedBatchNorm"] = function() { - return (_FusedBatchNorm = Module["_FusedBatchNorm"] = Module["asm"]["N"]).apply(null, arguments); - }; - var _FusedConv2D = Module["_FusedConv2D"] = function() { - return (_FusedConv2D = Module["_FusedConv2D"] = Module["asm"]["O"]).apply(null, arguments); - }; - var _FusedDepthwiseConv2D = Module["_FusedDepthwiseConv2D"] = function() { - return (_FusedDepthwiseConv2D = Module["_FusedDepthwiseConv2D"] = Module["asm"]["P"]).apply(null, arguments); - }; - var _Gather = Module["_Gather"] = function() { - return (_Gather = Module["_Gather"] = Module["asm"]["Q"]).apply(null, arguments); - }; - var _GatherNd = Module["_GatherNd"] = function() { - return (_GatherNd = Module["_GatherNd"] = Module["asm"]["R"]).apply(null, arguments); - }; - var _Greater = Module["_Greater"] = function() { - return (_Greater = Module["_Greater"] = Module["asm"]["S"]).apply(null, arguments); - }; - var _GreaterEqual = Module["_GreaterEqual"] = function() { - return (_GreaterEqual = Module["_GreaterEqual"] = Module["asm"]["T"]).apply(null, arguments); - }; - var _LeakyRelu = Module["_LeakyRelu"] = function() { - return (_LeakyRelu = Module["_LeakyRelu"] = Module["asm"]["U"]).apply(null, arguments); - }; - var _Less = Module["_Less"] = function() { - return (_Less = Module["_Less"] = Module["asm"]["V"]).apply(null, arguments); - }; - var _LessEqual = Module["_LessEqual"] = function() { - return (_LessEqual = Module["_LessEqual"] = Module["asm"]["W"]).apply(null, arguments); - }; - var _Log = Module["_Log"] = function() { - return (_Log = Module["_Log"] = Module["asm"]["X"]).apply(null, arguments); - }; - var _LogicalAnd = Module["_LogicalAnd"] = function() { - return (_LogicalAnd = Module["_LogicalAnd"] = Module["asm"]["Y"]).apply(null, arguments); - }; - var _Max = Module["_Max"] = function() { - return (_Max = Module["_Max"] = Module["asm"]["Z"]).apply(null, arguments); - }; - var _MaxPool = Module["_MaxPool"] = function() { - return (_MaxPool = Module["_MaxPool"] = Module["asm"]["_"]).apply(null, arguments); - }; - var _Maximum = Module["_Maximum"] = function() { - return (_Maximum = Module["_Maximum"] = Module["asm"]["$"]).apply(null, arguments); - }; - var _Mean = Module["_Mean"] = function() { - return (_Mean = Module["_Mean"] = Module["asm"]["aa"]).apply(null, arguments); - }; - var _Min = Module["_Min"] = function() { - return (_Min = Module["_Min"] = Module["asm"]["ba"]).apply(null, arguments); - }; - var _Minimum = Module["_Minimum"] = function() { - return (_Minimum = Module["_Minimum"] = Module["asm"]["ca"]).apply(null, arguments); - }; - var _MirrorPad = Module["_MirrorPad"] = function() { - return (_MirrorPad = Module["_MirrorPad"] = Module["asm"]["da"]).apply(null, arguments); - }; - var _Multiply = Module["_Multiply"] = function() { - return (_Multiply = Module["_Multiply"] = Module["asm"]["ea"]).apply(null, arguments); - }; - var _Neg = Module["_Neg"] = function() { - return (_Neg = Module["_Neg"] = Module["asm"]["fa"]).apply(null, arguments); - }; - var _NonMaxSuppressionV3 = Module["_NonMaxSuppressionV3"] = function() { - return (_NonMaxSuppressionV3 = Module["_NonMaxSuppressionV3"] = Module["asm"]["ga"]).apply(null, arguments); - }; - var _NonMaxSuppressionV4 = Module["_NonMaxSuppressionV4"] = function() { - return (_NonMaxSuppressionV4 = Module["_NonMaxSuppressionV4"] = Module["asm"]["ha"]).apply(null, arguments); - }; - var _NonMaxSuppressionV5 = Module["_NonMaxSuppressionV5"] = function() { - return (_NonMaxSuppressionV5 = Module["_NonMaxSuppressionV5"] = Module["asm"]["ia"]).apply(null, arguments); - }; - var _NotEqual = Module["_NotEqual"] = function() { - return (_NotEqual = Module["_NotEqual"] = Module["asm"]["ja"]).apply(null, arguments); - }; - var _OneHot = Module["_OneHot"] = function() { - return (_OneHot = Module["_OneHot"] = Module["asm"]["ka"]).apply(null, arguments); - }; - var _PadV2 = Module["_PadV2"] = function() { - return (_PadV2 = Module["_PadV2"] = Module["asm"]["la"]).apply(null, arguments); - }; - var _Pow = Module["_Pow"] = function() { - return (_Pow = Module["_Pow"] = Module["asm"]["ma"]).apply(null, arguments); - }; - var _Prelu = Module["_Prelu"] = function() { - return (_Prelu = Module["_Prelu"] = Module["asm"]["na"]).apply(null, arguments); - }; - var _Prod = Module["_Prod"] = function() { - return (_Prod = Module["_Prod"] = Module["asm"]["oa"]).apply(null, arguments); - }; - var _RealDiv = Module["_RealDiv"] = function() { - return (_RealDiv = Module["_RealDiv"] = Module["asm"]["pa"]).apply(null, arguments); - }; - var _Relu = Module["_Relu"] = function() { - return (_Relu = Module["_Relu"] = Module["asm"]["qa"]).apply(null, arguments); - }; - var _Relu6 = Module["_Relu6"] = function() { - return (_Relu6 = Module["_Relu6"] = Module["asm"]["ra"]).apply(null, arguments); - }; - var _ResizeBilinear = Module["_ResizeBilinear"] = function() { - return (_ResizeBilinear = Module["_ResizeBilinear"] = Module["asm"]["sa"]).apply(null, arguments); - }; - var _Reverse = Module["_Reverse"] = function() { - return (_Reverse = Module["_Reverse"] = Module["asm"]["ta"]).apply(null, arguments); - }; - var _RotateWithOffset = Module["_RotateWithOffset"] = function() { - return (_RotateWithOffset = Module["_RotateWithOffset"] = Module["asm"]["ua"]).apply(null, arguments); - }; - var _Round = Module["_Round"] = function() { - return (_Round = Module["_Round"] = Module["asm"]["va"]).apply(null, arguments); - }; - var _Rsqrt = Module["_Rsqrt"] = function() { - return (_Rsqrt = Module["_Rsqrt"] = Module["asm"]["wa"]).apply(null, arguments); - }; - var _ScatterNd = Module["_ScatterNd"] = function() { - return (_ScatterNd = Module["_ScatterNd"] = Module["asm"]["xa"]).apply(null, arguments); - }; - var _SelectV2 = Module["_SelectV2"] = function() { - return (_SelectV2 = Module["_SelectV2"] = Module["asm"]["ya"]).apply(null, arguments); - }; - var _Sigmoid = Module["_Sigmoid"] = function() { - return (_Sigmoid = Module["_Sigmoid"] = Module["asm"]["za"]).apply(null, arguments); - }; - var _Sin = Module["_Sin"] = function() { - return (_Sin = Module["_Sin"] = Module["asm"]["Aa"]).apply(null, arguments); - }; - var _Softmax = Module["_Softmax"] = function() { - return (_Softmax = Module["_Softmax"] = Module["asm"]["Ba"]).apply(null, arguments); - }; - var _Sqrt = Module["_Sqrt"] = function() { - return (_Sqrt = Module["_Sqrt"] = Module["asm"]["Ca"]).apply(null, arguments); - }; - var _Square = Module["_Square"] = function() { - return (_Square = Module["_Square"] = Module["asm"]["Da"]).apply(null, arguments); - }; - var _SquaredDifference = Module["_SquaredDifference"] = function() { - return (_SquaredDifference = Module["_SquaredDifference"] = Module["asm"]["Ea"]).apply(null, arguments); - }; - var _Step = Module["_Step"] = function() { - return (_Step = Module["_Step"] = Module["asm"]["Fa"]).apply(null, arguments); - }; - var _StridedSlice = Module["_StridedSlice"] = function() { - return (_StridedSlice = Module["_StridedSlice"] = Module["asm"]["Ga"]).apply(null, arguments); - }; - var _Sub = Module["_Sub"] = function() { - return (_Sub = Module["_Sub"] = Module["asm"]["Ha"]).apply(null, arguments); - }; - var _Sum = Module["_Sum"] = function() { - return (_Sum = Module["_Sum"] = Module["asm"]["Ia"]).apply(null, arguments); - }; - var _Tan = Module["_Tan"] = function() { - return (_Tan = Module["_Tan"] = Module["asm"]["Ja"]).apply(null, arguments); - }; - var _Tanh = Module["_Tanh"] = function() { - return (_Tanh = Module["_Tanh"] = Module["asm"]["Ka"]).apply(null, arguments); - }; - var _Tile = Module["_Tile"] = function() { - return (_Tile = Module["_Tile"] = Module["asm"]["La"]).apply(null, arguments); - }; - var _TopK = Module["_TopK"] = function() { - return (_TopK = Module["_TopK"] = Module["asm"]["Ma"]).apply(null, arguments); - }; - var _Transform = Module["_Transform"] = function() { - return (_Transform = Module["_Transform"] = Module["asm"]["Na"]).apply(null, arguments); - }; - var _Transpose = Module["_Transpose"] = function() { - return (_Transpose = Module["_Transpose"] = Module["asm"]["Oa"]).apply(null, arguments); - }; - var __FusedMatMul = Module["__FusedMatMul"] = function() { - return (__FusedMatMul = Module["__FusedMatMul"] = Module["asm"]["Pa"]).apply(null, arguments); - }; - var _malloc = Module["_malloc"] = function() { - return (_malloc = Module["_malloc"] = Module["asm"]["Qa"]).apply(null, arguments); - }; - var _free = Module["_free"] = function() { - return (_free = Module["_free"] = Module["asm"]["Ra"]).apply(null, arguments); - }; - var stackSave = Module["stackSave"] = function() { - return (stackSave = Module["stackSave"] = Module["asm"]["Ta"]).apply(null, arguments); - }; - var stackRestore = Module["stackRestore"] = function() { - return (stackRestore = Module["stackRestore"] = Module["asm"]["Ua"]).apply(null, arguments); - }; - var stackAlloc = Module["stackAlloc"] = function() { - return (stackAlloc = Module["stackAlloc"] = Module["asm"]["Va"]).apply(null, arguments); - }; - Module["cwrap"] = cwrap; - var calledRun; - function ExitStatus(status) { - this.name = "ExitStatus"; - this.message = "Program terminated with exit(" + status + ")"; - this.status = status; - } - dependenciesFulfilled = function runCaller() { - if (!calledRun) - run(); - if (!calledRun) - dependenciesFulfilled = runCaller; - }; - function run(args) { - args = args || arguments_; - if (runDependencies > 0) { - return; - } - preRun(); - if (runDependencies > 0) { - return; - } - function doRun() { - if (calledRun) - return; - calledRun = true; - Module["calledRun"] = true; - if (ABORT) - return; - initRuntime(); - preMain(); - readyPromiseResolve(Module); - if (Module["onRuntimeInitialized"]) - Module["onRuntimeInitialized"](); - postRun(); - } - if (Module["setStatus"]) { - Module["setStatus"]("Running..."); - setTimeout(function() { - setTimeout(function() { - Module["setStatus"](""); - }, 1); - doRun(); - }, 1); - } else { - doRun(); - } - } - Module["run"] = run; - if (Module["preInit"]) { - if (typeof Module["preInit"] == "function") - Module["preInit"] = [Module["preInit"]]; - while (Module["preInit"].length > 0) { - Module["preInit"].pop()(); - } - } - run(); - return WasmBackendModule2.ready; - }; - }(); - if (typeof exports === "object" && typeof module === "object") - module.exports = WasmBackendModule; - else if (typeof define === "function" && define["amd"]) - define([], function() { - return WasmBackendModule; - }); - else if (typeof exports === "object") - exports["WasmBackendModule"] = WasmBackendModule; - } -}); -var EPSILON_FLOAT32 = 1e-7; -var EPSILON_FLOAT16 = 1e-4; -var DataStorage = class { - constructor(backend3, dataMover) { - this.backend = backend3; - 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`); -} -function shuffle(array2) { - let counter = array2.length; - let index = 0; - while (counter > 0) { - index = Math.random() * counter | 0; - counter--; - swap(array2, counter, index); - } -} -function shuffleCombo(array2, array22) { - if (array2.length !== array22.length) { - throw new Error(`Array sizes must match to be shuffled together First array length was ${array2.length}Second array length was ${array22.length}`); - } - let counter = array2.length; - let index = 0; - while (counter > 0) { - index = Math.random() * counter | 0; - counter--; - swap(array2, counter, index); - swap(array22, counter, index); - } -} -function clamp(min7, x, max7) { - return Math.max(min7, Math.min(x, max7)); -} -function nearestLargerEven(val) { - return val % 2 === 0 ? val : val + 1; -} -function swap(object2, left, right) { - const temp = object2[left]; - object2[left] = object2[right]; - object2[right] = temp; -} -function sum(arr) { - let sum8 = 0; - for (let i = 0; i < arr.length; i++) { - sum8 += arr[i]; - } - return sum8; -} -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 size2 = shape[0]; - for (let i = 1; i < shape.length; i++) { - size2 *= shape[i]; - } - return size2; -} -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(size2) { - const width = Math.ceil(Math.sqrt(size2)); - return [width, Math.ceil(size2 / 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, size2) { - if (size2 <= a.length) { - return a; - } - return a + " ".repeat(size2 - 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, size2) { - 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 (size2 > 0 && size2 !== shapeProd) { - throw Error(`Size(${size2}) 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 (size2 % shapeProd !== 0) { - throw Error(`The implicit shape can't be a fractional number. Got ${size2} / ${shapeProd}`); - } - const newShape = shape.slice(); - newShape[implicitIdx] = size2 / 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, size2) { - let values = null; - if (dtype == null || dtype === "float32") { - values = new Float32Array(size2); - } else if (dtype === "int32") { - values = new Int32Array(size2); - } else if (dtype === "bool") { - values = new Uint8Array(size2); - } else { - throw new Error(`Unknown data type ${dtype}`); - } - return values; -} -function getArrayFromDType(dtype, size2) { - let values = null; - if (dtype == null || dtype === "float32") { - values = new Float32Array(size2); - } else if (dtype === "int32") { - values = new Int32Array(size2); - } else if (dtype === "bool") { - values = new Uint8Array(size2); - } else if (dtype === "string") { - values = new Array(size2); - } 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 || a instanceof Uint8ClampedArray; -} -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 || values instanceof Uint8ClampedArray) { - 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(size2, start) { - for (let i = start; i < size2; ++i) { - if (size2 % i === 0) { - return i; - } - } - return size2; -} -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, isComplex = false) { - const ret = new Array(); - if (shape.length === 1) { - const d = shape[0] * (isComplex ? 2 : 1); - for (let i = 0; i < d; i++) { - ret[i] = a[offset + i]; - } - } else { - const d = shape[0]; - const rest = shape.slice(1); - const len = rest.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1); - for (let i = 0; i < d; i++) { - ret[i] = createNestedArray(offset + i * len, rest, a, isComplex); - } - } - return ret; -} -function toNestedArray(shape, a, isComplex = false) { - if (shape.length === 0) { - return a[0]; - } - const size2 = shape.reduce((acc, c) => acc * c) * (isComplex ? 2 : 1); - if (size2 === 0) { - return []; - } - if (size2 !== a.length) { - throw new Error(`[${shape}] does not match the input size ${a.length}${isComplex ? " for a complex tensor" : ""}.`); - } - return createNestedArray(0, shape, a, isComplex); -} -function makeOnesTypedArray(size2, dtype) { - const array2 = makeZerosTypedArray(size2, dtype); - for (let i = 0; i < array2.length; i++) { - array2[i] = 1; - } - return array2; -} -function makeZerosTypedArray(size2, dtype) { - if (dtype == null || dtype === "float32" || dtype === "complex64") { - return new Float32Array(size2); - } else if (dtype === "int32") { - return new Int32Array(size2); - } else if (dtype === "bool") { - return new Uint8Array(size2); - } else { - throw new Error(`Unknown data type ${dtype}`); - } -} -function makeZerosNestedTypedArray(shape, dtype) { - const size2 = shape.reduce((prev, curr) => prev * curr, 1); - if (dtype == null || dtype === "float32") { - return toNestedArray(shape, new Float32Array(size2)); - } else if (dtype === "int32") { - return toNestedArray(shape, new Int32Array(size2)); - } else if (dtype === "bool") { - return toNestedArray(shape, new Uint8Array(size2)); - } 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"; -} -function warn(...msg) { - if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) { - console.warn(...msg); - } -} -function log2(...msg) { - if (!(env().getBool("IS_TEST") || env().getBool("PROD"))) { - console.log(...msg); - } -} -var TENSORFLOWJS_FLAGS_PREFIX = "tfjsflags"; -var Environment = class { - constructor(global2) { - this.global = global2; - this.flags = {}; - this.flagRegistry = {}; - this.urlFlags = {}; - this.getQueryParams = getQueryParams; - this.populateURLFlags(); - } - setPlatform(platformName, platform) { - if (this.platform != null) { - warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${platform}.`); - } - this.platformName = platformName; - this.platform = platform; - } - registerFlag(flagName, evaluationFn, setHook) { - this.flagRegistry[flagName] = { evaluationFn, setHook }; - if (this.urlFlags[flagName] != null) { - const flagValue = this.urlFlags[flagName]; - warn(`Setting feature override from URL ${flagName}: ${flagValue}.`); - this.set(flagName, flagValue); - } - } - 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 = this.getQueryParams(this.global.location.search); - if (TENSORFLOWJS_FLAGS_PREFIX in urlParams) { - const keyValues = urlParams[TENSORFLOWJS_FLAGS_PREFIX].split(","); - keyValues.forEach((keyValue) => { - const [key, value] = keyValue.split(":"); - this.urlFlags[key] = parseValue(key, value); - }); - } - } -}; -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; -} -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 BroadcastArgs = "BroadcastArgs"; -var Cast = "Cast"; -var Ceil = "Ceil"; -var ClipByValue = "ClipByValue"; -var Complex = "Complex"; -var ComplexAbs = "ComplexAbs"; -var Concat = "Concat"; -var Conv2D = "Conv2D"; -var Conv2DBackpropFilter = "Conv2DBackpropFilter"; -var Conv2DBackpropInput = "Conv2DBackpropInput"; -var Conv3D = "Conv3D"; -var Conv3DBackpropFilterV2 = "Conv3DBackpropFilterV2"; -var Conv3DBackpropInputV2 = "Conv3DBackpropInputV2"; -var Cos = "Cos"; -var Cosh = "Cosh"; -var Cumsum = "Cumsum"; -var CropAndResize = "CropAndResize"; -var DenseBincount = "DenseBincount"; -var DepthToSpace = "DepthToSpace"; -var DepthwiseConv2dNative = "DepthwiseConv2dNative"; -var DepthwiseConv2dNativeBackpropFilter = "DepthwiseConv2dNativeBackpropFilter"; -var DepthwiseConv2dNativeBackpropInput = "DepthwiseConv2dNativeBackpropInput"; -var Diag = "Diag"; -var Dilation2D = "Dilation2D"; -var Dilation2DBackpropInput = "Dilation2DBackpropInput"; -var Dilation2DBackpropFilter = "Dilation2DBackpropFilter"; -var RealDiv = "RealDiv"; -var Einsum = "Einsum"; -var Elu = "Elu"; -var EluGrad = "EluGrad"; -var Erf = "Erf"; -var Equal = "Equal"; -var Exp = "Exp"; -var ExpandDims = "ExpandDims"; -var Expm1 = "Expm1"; -var FFT = "FFT"; -var Fill = "Fill"; -var FlipLeftRight = "FlipLeftRight"; -var Floor = "Floor"; -var FloorDiv = "FloorDiv"; -var FusedBatchNorm = "FusedBatchNorm"; -var GatherV2 = "GatherV2"; -var GatherNd = "GatherNd"; -var Greater = "Greater"; -var GreaterEqual = "GreaterEqual"; -var Identity = "Identity"; -var IFFT = "IFFT"; -var Imag = "Imag"; -var IsFinite = "IsFinite"; -var IsInf = "IsInf"; -var IsNan = "IsNan"; -var LeakyRelu = "LeakyRelu"; -var Less = "Less"; -var LessEqual = "LessEqual"; -var LinSpace = "LinSpace"; -var Log = "Log"; -var Log1p = "Log1p"; -var LogicalAnd = "LogicalAnd"; -var LogicalNot = "LogicalNot"; -var LogicalOr = "LogicalOr"; -var LogSoftmax = "LogSoftmax"; -var LRN = "LRN"; -var LRNGrad = "LRNGrad"; -var Max = "Max"; -var Maximum = "Maximum"; -var MaxPool = "MaxPool"; -var MaxPoolGrad = "MaxPoolGrad"; -var MaxPool3D = "MaxPool3D"; -var MaxPool3DGrad = "MaxPool3DGrad"; -var MaxPoolWithArgmax = "MaxPoolWithArgmax"; -var Mean = "Mean"; -var Min = "Min"; -var Minimum = "Minimum"; -var MirrorPad = "MirrorPad"; -var Mod = "Mod"; -var Multinomial = "Multinomial"; -var Multiply = "Multiply"; -var Neg = "Neg"; -var NotEqual = "NotEqual"; -var NonMaxSuppressionV3 = "NonMaxSuppressionV3"; -var NonMaxSuppressionV4 = "NonMaxSuppressionV4"; -var NonMaxSuppressionV5 = "NonMaxSuppressionV5"; -var OnesLike = "OnesLike"; -var OneHot = "OneHot"; -var Pack = "Pack"; -var PadV2 = "PadV2"; -var Pool = "Pool"; -var Pow = "Pow"; -var Prelu = "Prelu"; -var Prod = "Prod"; -var Range = "Range"; -var Real = "Real"; -var Reciprocal = "Reciprocal"; -var Relu = "Relu"; -var Reshape = "Reshape"; -var ResizeNearestNeighbor = "ResizeNearestNeighbor"; -var ResizeNearestNeighborGrad = "ResizeNearestNeighborGrad"; -var ResizeBilinear = "ResizeBilinear"; -var ResizeBilinearGrad = "ResizeBilinearGrad"; -var Relu6 = "Relu6"; -var Reverse = "Reverse"; -var Round = "Round"; -var Rsqrt = "Rsqrt"; -var ScatterNd = "ScatterNd"; -var Select = "Select"; -var Selu = "Selu"; -var Slice = "Slice"; -var Sin = "Sin"; -var Sinh = "Sinh"; -var Sign = "Sign"; -var Sigmoid = "Sigmoid"; -var Softplus = "Softplus"; -var Sqrt = "Sqrt"; -var Sum = "Sum"; -var SpaceToBatchND = "SpaceToBatchND"; -var SplitV = "SplitV"; -var Softmax = "Softmax"; -var SparseFillEmptyRows = "SparseFillEmptyRows"; -var SparseReshape = "SparseReshape"; -var SparseSegmentMean = "SparseSegmentMean"; -var SparseSegmentSum = "SparseSegmentSum"; -var SparseToDense = "SparseToDense"; -var SquaredDifference = "SquaredDifference"; -var Square = "Square"; -var StridedSlice = "StridedSlice"; -var StringNGrams = "StringNGrams"; -var StringSplit = "StringSplit"; -var StringToHashBucketFast = "StringToHashBucketFast"; -var Sub = "Sub"; -var Tan = "Tan"; -var Tanh = "Tanh"; -var Tile = "Tile"; -var TopK = "TopK"; -var Transform = "Transform"; -var Transpose = "Transpose"; -var Unique = "Unique"; -var Unpack = "Unpack"; -var UnsortedSegmentSum = "UnsortedSegmentSum"; -var ZerosLike = "ZerosLike"; -var Step = "Step"; -var FromPixels = "FromPixels"; -var RotateWithOffset = "RotateWithOffset"; -var _FusedMatMul = "_FusedMatMul"; -var FusedConv2D = "FusedConv2D"; -var FusedDepthwiseConv2D = "FusedDepthwiseConv2D"; -var kernelRegistry = getGlobal("kernelRegistry", () => new Map()); -var gradRegistry = getGlobal("gradRegistry", () => new Map()); -function getKernel(kernelName, backendName) { - const key = makeKey(kernelName, backendName); - return kernelRegistry.get(key); -} -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 [backend3] = key.split("_"); - if (backend3 === backendName) { - result.push(config3); - } - } - return result; -} -function registerKernel(config3) { - const { kernelName, backendName } = config3; - const key = makeKey(kernelName, backendName); - if (kernelRegistry.has(key)) { - warn(`The kernel '${kernelName}' for backend '${backendName}' is already registered`); - } - kernelRegistry.set(key, config3); -} -function registerGradient(config3) { - const { kernelName } = config3; - if (gradRegistry.has(kernelName)) { - if (env().getBool("DEBUG")) { - 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: () => fetch3, - fingerPrint64: () => fingerPrint64, - flatten: () => flatten, - getArrayFromDType: () => getArrayFromDType, - getTypedArrayFromDType: () => getTypedArrayFromDType, - hasEncodingLoss: () => hasEncodingLoss, - hexToLong: () => hexToLong, - indexToLoc: () => indexToLoc, - inferDtype: () => inferDtype, - inferFromImplicitShape: () => inferFromImplicitShape, - isBoolean: () => isBoolean, - isFunction: () => isFunction, - isInt: () => isInt, - isNumber: () => isNumber, - isPromise: () => isPromise, - isScalarShape: () => isScalarShape, - isString: () => isString, - isTypedArray: () => isTypedArray, - isValidDtype: () => isValidDtype, - locToIndex: () => locToIndex, - makeOnesTypedArray: () => makeOnesTypedArray, - makeZerosNestedTypedArray: () => makeZerosNestedTypedArray, - makeZerosTypedArray: () => makeZerosTypedArray, - nearestDivisor: () => nearestDivisor, - nearestLargerEven: () => nearestLargerEven, - now: () => now2, - parseAxisParam: () => parseAxisParam, - randUniform: () => randUniform, - repeatedTry: () => repeatedTry, - rightPad: () => rightPad, - shuffle: () => shuffle, - shuffleCombo: () => shuffleCombo, - sizeFromShape: () => sizeFromShape, - sizeToSquarishShape: () => sizeToSquarishShape, - squeezeShape: () => squeezeShape, - sum: () => sum, - swap: () => swap, - tanh: () => tanh, - toNestedArray: () => toNestedArray, - toTypedArray: () => toTypedArray -}); -var LongExports = __toModule(require_long()); -var Long = LongExports.default || LongExports; -function hexToLong(hex) { - return Long.fromString(hex, true, 16); -} -var k0 = hexToLong("c3a5c85c97cb3127"); -var k1 = hexToLong("b492b66fbe98f273"); -var k2 = hexToLong("9ae16a3b2f90404f"); -function shiftMix(val) { - return val.xor(val.shru(47)); -} -function fetch2(s, offset, numBytes) { - const bytes = s.slice(offset, offset + numBytes); - return Long.fromBytes(Array.from(bytes), true, true); -} -function fetch64(s, offset) { - return fetch2(s, offset, 8); -} -function fetch32(s, offset) { - return fetch2(s, offset, 4); -} -function rotate64(val, shift) { - return shift === 0 ? val : val.shru(shift).or(val.shl(64 - shift)); -} -function hashLen16(u, v, mul2 = hexToLong("9ddfea08eb382d69")) { - let a = u.xor(v).mul(mul2); - a = a.xor(a.shru(47)); - let b = v.xor(a).mul(mul2); - b = b.xor(b.shru(47)); - b = b.mul(mul2); - return b; -} -function weakHashLen32WithSeeds(w, x, y, z, a, b) { - a = a.add(w); - b = rotate64(b.add(a).add(z), 21); - const c = a; - a = a.add(x); - a = a.add(y); - b = b.add(rotate64(a, 44)); - return [a.add(z), b.add(c)]; -} -function weakHashLen32WithSeedsStr(s, offset, a, b) { - return weakHashLen32WithSeeds(fetch64(s, offset), fetch64(s, offset + 8), fetch64(s, offset + 16), fetch64(s, offset + 24), a, b); -} -function hashLen0to16(s, len = s.length) { - if (len >= 8) { - const mul2 = k2.add(len * 2); - const a = fetch64(s, 0).add(k2); - const b = fetch64(s, len - 8); - const c = rotate64(b, 37).mul(mul2).add(a); - const d = rotate64(a, 25).add(b).mul(mul2); - return hashLen16(c, d, mul2); - } - if (len >= 4) { - const mul2 = k2.add(len * 2); - const a = fetch32(s, 0); - return hashLen16(a.shl(3).add(len), fetch32(s, len - 4), mul2); - } - if (len > 0) { - const a = s[0]; - const b = s[len >> 1]; - const c = s[len - 1]; - const y = a + (b << 8); - const z = len + (c << 2); - return shiftMix(k2.mul(y).xor(k0.mul(z))).mul(k2); - } - return k2; -} -function hashLen17to32(s, len = s.length) { - const mul2 = k2.add(len * 2); - const a = fetch64(s, 0).mul(k1); - const b = fetch64(s, 8); - const c = fetch64(s, len - 8).mul(mul2); - const d = fetch64(s, len - 16).mul(k2); - return hashLen16(rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d), a.add(rotate64(b.add(k2), 18)).add(c), mul2); -} -function hashLen33to64(s, len = s.length) { - const mul2 = k2.add(len * 2); - const a = fetch64(s, 0).mul(k2); - const b = fetch64(s, 8); - const c = fetch64(s, len - 8).mul(mul2); - const d = fetch64(s, len - 16).mul(k2); - const y = rotate64(a.add(b), 43).add(rotate64(c, 30)).add(d); - const z = hashLen16(y, a.add(rotate64(b.add(k2), 18)).add(c), mul2); - const e = fetch64(s, 16).mul(mul2); - const f = fetch64(s, 24); - const g = y.add(fetch64(s, len - 32)).mul(mul2); - const h = z.add(fetch64(s, len - 24)).mul(mul2); - return hashLen16(rotate64(e.add(f), 43).add(rotate64(g, 30)).add(h), e.add(rotate64(f.add(a), 18)).add(g), mul2); -} -function fingerPrint64(s, len = s.length) { - const seed = Long.fromNumber(81, true); - if (len <= 32) { - if (len <= 16) { - return hashLen0to16(s, len); - } else { - return hashLen17to32(s, len); - } - } else if (len <= 64) { - return hashLen33to64(s, len); - } - let x = seed; - let y = seed.mul(k1).add(113); - let z = shiftMix(y.mul(k2).add(113)).mul(k2); - let v = [Long.UZERO, Long.UZERO]; - let w = [Long.UZERO, Long.UZERO]; - x = x.mul(k2).add(fetch64(s, 0)); - let offset = 0; - const end = (len - 1 >> 6) * 64; - const last64 = end + (len - 1 & 63) - 63; - do { - x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(k1); - y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(k1); - x = x.xor(w[1]); - y = y.add(v[0]).add(fetch64(s, offset + 40)); - z = rotate64(z.add(w[0]), 33).mul(k1); - v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(k1), x.add(w[0])); - w = weakHashLen32WithSeedsStr(s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16))); - [z, x] = [x, z]; - offset += 64; - } while (offset !== end); - const mul2 = k1.add(z.and(255).shl(1)); - offset = last64; - w[0] = w[0].add(len - 1 & 63); - v[0] = v[0].add(w[0]); - w[0] = w[0].add(v[0]); - x = rotate64(x.add(y).add(v[0]).add(fetch64(s, offset + 8)), 37).mul(mul2); - y = rotate64(y.add(v[1]).add(fetch64(s, offset + 48)), 42).mul(mul2); - x = x.xor(w[1].mul(9)); - y = y.add(v[0].mul(9).add(fetch64(s, offset + 40))); - z = rotate64(z.add(w[0]), 33).mul(mul2); - v = weakHashLen32WithSeedsStr(s, offset, v[1].mul(mul2), x.add(w[0])); - w = weakHashLen32WithSeedsStr(s, offset + 32, z.add(w[1]), y.add(fetch64(s, offset + 16))); - [z, x] = [x, z]; - return hashLen16(hashLen16(v[0], w[0], mul2).add(shiftMix(y).mul(k0)).add(z), hashLen16(v[1], w[1], mul2).add(x), mul2); -} -function 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 fetch3(path, requestInits) { - return env().platform.fetch(path, requestInits); -} -function encodeString(s, encoding = "utf-8") { - encoding = encoding || "utf-8"; - return env().platform.encode(s, encoding); -} -function decodeString(bytes, encoding = "utf-8") { - encoding = encoding || "utf-8"; - return env().platform.decode(bytes, encoding); -} -var Profiler = class { - constructor(backendTimer, logger) { - this.backendTimer = backendTimer; - this.logger = logger; - if (logger == null) { - this.logger = new Logger(); - } - } - profileKernel(kernelName, inputs, f) { - let outputs; - const holdResultWrapperFn = () => { - outputs = f(); - }; - let timer; - const start = now2(); - if (this.backendTimer.timerAvailable()) { - timer = this.backendTimer.time(holdResultWrapperFn); - } else { - holdResultWrapperFn(); - for (const output of outputs) { - output.dataSync(); - } - timer = Promise.resolve({ kernelMs: now2() - start }); - } - if (env().getBool("CHECK_COMPUTATION_FOR_ERRORS")) { - for (let i = 0; i < outputs.length; i++) { - const output = outputs[i]; - output.data().then((tensorVals) => { - checkComputationForErrors(tensorVals, output.dtype, kernelName); - }); - } - } - 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 size2 = 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${size2} %c${inputShapesDescription} %c${extraInfo}`, "font-weight:bold", "color:red", "color:blue", "color: orange", "color: green", "color: steelblue"); - } -}; -function getFilteredNodesXToY(tape, xs, y) { - const tensorsFromX = {}; - const nodesFromX = {}; - for (let i = 0; i < xs.length; i++) { - tensorsFromX[xs[i].id] = true; - } - for (let i = 0; i < tape.length; i++) { - const node2 = tape[i]; - const nodeInputs = node2.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]) { - node2.outputs.forEach((output) => tensorsFromX[output.id] = true); - anyInputFromX = true; - nodesFromX[node2.id] = true; - break; - } - } - if (anyInputFromX) { - break; - } - } - } - const tensorsLeadToY = {}; - tensorsLeadToY[y.id] = true; - const nodesToY = {}; - for (let i = tape.length - 1; i >= 0; i--) { - const node2 = tape[i]; - const nodeInputs = node2.inputs; - for (let j = 0; j < node2.outputs.length; j++) { - if (tensorsLeadToY[node2.outputs[j].id]) { - for (const inputName in nodeInputs) { - tensorsLeadToY[nodeInputs[inputName].id] = true; - nodesToY[node2.id] = true; - } - break; - } - } - } - const filteredTape = []; - for (let i = 0; i < tape.length; i++) { - const node2 = tape[i]; - if (nodesFromX[node2.id] && nodesToY[node2.id]) { - const prunedInputs = {}; - for (const inputName in node2.inputs) { - const nodeInput = node2.inputs[inputName]; - if (tensorsFromX[nodeInput.id]) { - prunedInputs[inputName] = nodeInput; - } - } - const prunedNode = Object.assign({}, node2); - prunedNode.inputs = prunedInputs; - prunedNode.outputs = node2.outputs; - filteredTape.push(prunedNode); - } - } - return filteredTape; -} -function backpropagateGradients(tensorAccumulatedGradientMap, filteredTape, tidy2, add6) { - for (let i = filteredTape.length - 1; i >= 0; i--) { - const node2 = filteredTape[i]; - const dys = []; - node2.outputs.forEach((o) => { - const gradTensor = tensorAccumulatedGradientMap[o.id]; - if (gradTensor != null) { - dys.push(gradTensor); - } else { - dys.push(null); - } - }); - if (node2.gradient == null) { - throw new Error(`Cannot compute gradient: gradient function not found for ${node2.kernelName}.`); - } - const inputGradients = node2.gradient(dys); - for (const inputName in node2.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 ${node2.kernelName}. The gradient of input ${inputName} must have 'float32' dtype, but has '${dx.dtype}'`); - } - const x = node2.inputs[inputName]; - if (!arraysEqual(dx.shape, x.shape)) { - throw new Error(`Error in gradient for op ${node2.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] = add6(curGradient, dx); - curGradient.dispose(); - } - } - } -} -var FORMAT_LIMIT_NUM_VALS = 20; -var FORMAT_NUM_FIRST_LAST_VALS = 3; -var FORMAT_NUM_SIG_DIGITS = 7; -function tensorToString(vals, shape, dtype, verbose) { - const strides = computeStrides(shape); - const padPerCol = computeMaxSizePerColumn(vals, shape, dtype, strides); - const rank = shape.length; - const valsLines = subTensorToString(vals, shape, dtype, strides, padPerCol); - const lines2 = ["Tensor"]; - if (verbose) { - lines2.push(` dtype: ${dtype}`); - lines2.push(` rank: ${rank}`); - lines2.push(` shape: [${shape}]`); - lines2.push(` values:`); - } - lines2.push(valsLines.map((l) => " " + l).join("\n")); - return lines2.join("\n"); -} -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 size2 = 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 (size2 > 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((size2 - FORMAT_NUM_FIRST_LAST_VALS) * storagePerElement, size2 * 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[size2 - 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 (size2 > 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 = size2 - FORMAT_NUM_FIRST_LAST_VALS; i < size2; i++) { - const start = i * stride; - const end = start + stride; - lines2.push(...subTensorToString(vals.slice(start, end), subshape, dtype, substrides, padPerCol, i === size2 - 1)); - } - } else { - for (let i = 0; i < size2; i++) { - const start = i * stride; - const end = start + stride; - lines2.push(...subTensorToString(vals.slice(start, end), subshape, dtype, substrides, padPerCol, i === size2 - 1)); - } - } - const sep = rank === 2 ? "," : ""; - lines2[0] = "[" + lines2[0] + sep; - for (let i = 1; i < lines2.length - 1; i++) { - lines2[i] = " " + lines2[i] + sep; - } - let newLineSep = ",\n"; - for (let i = 2; i < rank; i++) { - newLineSep += "\n"; - } - lines2[lines2.length - 1] = " " + lines2[lines2.length - 1] + "]" + (isLast ? "" : newLineSep); - return lines2; -} -function createComplexTuples(vals) { - const complexTuples = []; - for (let i = 0; i < vals.length; i += 2) { - complexTuples.push([vals[i], vals[i + 1]]); - } - return complexTuples; -} -var TensorBuffer = class { - constructor(shape, dtype, values) { - this.dtype = dtype; - this.shape = shape.slice(); - this.size = sizeFromShape(shape); - if (values != null) { - const n = values.length; - assert(n === this.size, () => `Length of values '${n}' does not match the size inferred by the shape '${this.size}'.`); - } - if (dtype === "complex64") { - throw new Error(`complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).`); - } - this.values = values || getArrayFromDType(dtype, this.size); - this.strides = computeStrides(shape); - } - set(value, ...locs) { - if (locs.length === 0) { - locs = [0]; - } - assert(locs.length === this.rank, () => `The number of provided coordinates (${locs.length}) must match the rank (${this.rank})`); - const index = this.locToIndex(locs); - this.values[index] = value; - } - get(...locs) { - if (locs.length === 0) { - locs = [0]; - } - let i = 0; - for (const loc of locs) { - if (loc < 0 || loc >= this.shape[i]) { - const msg = `Requested out of range element at ${locs}. Buffer shape=${this.shape}`; - throw new Error(msg); - } - i++; - } - let index = locs[locs.length - 1]; - for (let i2 = 0; i2 < locs.length - 1; ++i2) { - index += this.strides[i2] * locs[i2]; - } - return this.values[index]; - } - locToIndex(locs) { - if (this.rank === 0) { - 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 Tensor4 = 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, this.dtype === "complex64"); - } - arraySync() { - return toNestedArray(this.shape, this.dataSync(), this.dtype === "complex64"); - } - async data() { - this.throwIfDisposed(); - const data = trackerFn().read(this.dataId); - if (this.dtype === "string") { - const bytes = await data; - try { - return bytes.map((b) => decodeString(b)); - } catch (e) { - throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes()."); - } - } - return data; - } - dataSync() { - this.throwIfDisposed(); - const data = trackerFn().readSync(this.dataId); - if (this.dtype === "string") { - try { - return data.map((b) => decodeString(b)); - } catch (e) { - throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes()."); - } - } - return data; - } - async bytes() { - this.throwIfDisposed(); - const data = await trackerFn().read(this.dataId); - if (this.dtype === "string") { - return data; - } else { - return new Uint8Array(data.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(Tensor4, Symbol.hasInstance, { - value: (instance) => { - return !!instance && instance.data != null && instance.dataSync != null && instance.throwIfDisposed != null; - } -}); -function getGlobalTensorClass() { - return getGlobal("Tensor", () => { - return Tensor4; - }); -} -getGlobalTensorClass(); -var Variable = class extends Tensor4 { - 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: (instance) => { - return instance instanceof Tensor4 && instance.assign != null && instance.assign instanceof Function; - } -}); -var tensor_util_exports = {}; -__export2(tensor_util_exports, { - assertTypesMatch: () => assertTypesMatch, - getTensorsInContainer: () => getTensorsInContainer, - isTensorInList: () => isTensorInList, - makeTypesMatch: () => makeTypesMatch -}); -var Rank2; -(function(Rank41) { - Rank41["R0"] = "R0"; - Rank41["R1"] = "R1"; - Rank41["R2"] = "R2"; - Rank41["R3"] = "R3"; - Rank41["R4"] = "R4"; - Rank41["R5"] = "R5"; - Rank41["R6"] = "R6"; -})(Rank2 || (Rank2 = {})); -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"); -} -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 Tensor4) { - 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"; -} -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(ENV6) { - this.ENV = ENV6; - 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) { - 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 backend3 = registryFactoryEntry.factory(); - if (backend3 && !(backend3 instanceof KernelBackend) && typeof backend3.then === "function") { - const promiseId = ++this.pendingBackendInitId; - const success = backend3.then((backendInstance) => { - if (promiseId < this.pendingBackendInitId) { - return false; - } - this.registry[backendName] = backendInstance; - this.pendingBackendInit = null; - return true; - }).catch((err) => { - if (promiseId < this.pendingBackendInitId) { - return false; - } - this.pendingBackendInit = null; - warn(`Initialization of backend ${backendName} failed`); - warn(err.stack || err.message); - return false; - }); - this.pendingBackendInit = success; - return { success, asyncInit: true }; - } else { - this.registry[backendName] = backend3; - return { success: true, asyncInit: false }; - } - } catch (err) { - warn(`Initialization of backend ${backendName} failed`); - 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(backend3, dataId) { - const info = this.state.tensorInfo.get(dataId); - const srcBackend = info.backend; - const values = this.readSync(dataId); - const refCount = srcBackend.refCount(dataId); - srcBackend.disposeData(dataId, true); - info.backend = backend3; - backend3.move(dataId, values, info.shape, info.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) { - if (this.backendName == null) { - this.backend; - } - const hasKernel = getKernel(kernelName, this.backendName) != null; - if (!hasKernel) { - throw new Error(`Kernel '${kernelName}' not registered for backend '${this.backendName}'`); - } - return this.runKernelFunc({ kernelName, inputs, attrs }); - } - shouldCheckForMemLeaks() { - return this.ENV.getBool("IS_TEST"); - } - checkKernelForMemLeak(kernelName, numDataIdsBefore, outInfos) { - const numDataIdsAfter = this.backend.numDataIds(); - let numOutputDataIds = 0; - outInfos.forEach((info) => { - numOutputDataIds += info.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, backend3) { - if (values == null) { - throw new Error("Values passed to engine.makeTensor() are null"); - } - dtype = dtype || "float32"; - backend3 = backend3 || this.backend; - let backendVals = values; - if (dtype === "string" && isString(values[0])) { - backendVals = values.map((d) => encodeString(d)); - } - const dataId = backend3.write(backendVals, shape, dtype); - const t = new Tensor4(shape, dtype, dataId, this.nextTensorId()); - this.trackTensor(t, backend3); - if (dtype === "string") { - const info = this.state.tensorInfo.get(dataId); - const newBytes = bytesFromStringArray(backendVals); - this.state.numBytes += newBytes - info.bytes; - info.bytes = newBytes; - } - return t; - } - makeTensorFromDataId(dataId, shape, dtype, backend3) { - dtype = dtype || "float32"; - const t = new Tensor4(shape, dtype, dataId, this.nextTensorId()); - this.trackTensor(t, backend3); - 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, backend3) { - 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: backend3 || this.backend, - dtype: a.dtype, - shape: a.shape, - bytes - }); - } - if (!(a instanceof Variable)) { - this.track(a); - } - } - incRef(a, backend3) { - this.trackTensor(a, backend3); - this.backend.incRef(a.dataId); - } - removeDataId(dataId, backend3) { - if (this.state.tensorInfo.has(dataId) && this.state.tensorInfo.get(dataId).backend === backend3) { - this.state.tensorInfo.delete(dataId); - this.state.numDataBuffers--; - } - } - disposeTensor(a) { - if (!this.state.tensorInfo.has(a.dataId)) { - return; - } - const info = this.state.tensorInfo.get(a.dataId); - this.state.numTensors--; - if (a.dtype === "string") { - this.state.numStringTensors--; - this.state.numBytes -= info.bytes; - } - if (a.dtype !== "complex64" && a.dtype !== "string") { - const bytes = a.size * bytesPerElement(a.dtype); - this.state.numBytes -= bytes; - } - if (info.backend.disposeData(a.dataId)) { - this.removeDataId(a.dataId, info.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 info = this.backend.memory(); - info.numTensors = this.state.numTensors; - info.numDataBuffers = this.state.numDataBuffers; - info.numBytes = this.state.numBytes; - if (this.state.numStringTensors > 0) { - info.unreliable = true; - if (info.reasons == null) { - info.reasons = []; - } - info.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)"); - } - return info; - } - 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 Tensor4, () => "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((node2) => { - for (const tensor2 of node2.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 Tensor4), () => "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 Tensor4, () => "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 Tensor4), () => "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 info = this.state.tensorInfo.get(dataId); - return info.backend.readSync(dataId); - } - read(dataId) { - const info = this.state.tensorInfo.get(dataId); - return info.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; - } -}; -var Engine = _Engine; -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, - mockIsMobile: () => mockIsMobile -}); -function _isNavigatorDefined() { - return typeof navigator !== "undefined" && navigator != null; -} -var isMobileMockValue; -function mockIsMobile(value) { - isMobileMockValue = value; -} -function isMobile(nav) { - if (isMobileMockValue !== void 0) { - return isMobileMockValue; - } - if (nav || _isNavigatorDefined()) { - if (!nav) { - nav = navigator; - } - if (nav.product === "ReactNative") { - return true; - } - const a = nav.userAgent || nav.vendor || (typeof window !== "undefined" ? window.opera : ""); - if (!a) { - const navAny = nav; - return navAny.userAgentData && navAny.userAgentData.mobile; - } - return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4)); - } - return false; -} -function isBrowser() { - return typeof window !== "undefined" && window.document != null || typeof WorkerGlobalScope !== "undefined"; -} -var ENV2 = env(); -ENV2.registerFlag("DEBUG", () => false, (debugValue) => { - if (debugValue) { - console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance."); - } -}); -ENV2.registerFlag("IS_BROWSER", () => isBrowser()); -ENV2.registerFlag("IS_NODE", () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined"); -ENV2.registerFlag("IS_CHROME", () => typeof navigator !== "undefined" && navigator != null && navigator.userAgent != null && /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor)); -ENV2.registerFlag("PROD", () => false); -ENV2.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY", () => ENV2.getBool("DEBUG")); -ENV2.registerFlag("DEPRECATION_WARNINGS_ENABLED", () => true); -ENV2.registerFlag("IS_TEST", () => false); -ENV2.registerFlag("CHECK_COMPUTATION_FOR_ERRORS", () => true); -ENV2.registerFlag("WRAP_TO_IMAGEBITMAP", () => false); -function inferShape(val, dtype) { - let firstElem = val; - if (isTypedArray(val)) { - return dtype === "string" ? [] : [val.length]; - } - if (!Array.isArray(val)) { - 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 Tensor4) { - 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)); -} -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; -} -function complex_(real5, imag5) { - const $real = convertToTensor(real5, "real", "complex"); - const $imag = convertToTensor(imag5, "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_ }); -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); -} -function tensor(values, shape, dtype) { - const inferredShape = inferShape(values, dtype); - return makeTensor(values, shape, inferredShape, dtype); -} -var DTYPE_VALUE_SIZE_MAP = { - "float32": 4, - "float16": 2, - "int32": 4, - "uint16": 2, - "uint8": 1, - "bool": 1, - "complex64": 8 -}; -var NUM_BYTES_STRING_LENGTH = 4; -async function encodeWeights(tensors, group) { - const specs = []; - const dataPromises = []; - const names = Array.isArray(tensors) ? tensors.map((tensor2) => tensor2.name) : Object.keys(tensors); - for (let i = 0; i < names.length; ++i) { - const name = names[i]; - const t = Array.isArray(tensors) ? tensors[i].tensor : tensors[name]; - if (t.dtype !== "float32" && t.dtype !== "int32" && t.dtype !== "bool" && t.dtype !== "string" && t.dtype !== "complex64") { - throw new Error(`Unsupported dtype in weight '${name}': ${t.dtype}`); - } - const spec = { name, shape: t.shape, dtype: t.dtype }; - if (t.dtype === "string") { - const utf8bytes = new Promise(async (resolve) => { - const vals = await t.bytes(); - const totalNumBytes = vals.reduce((p2, c) => p2 + c.length, 0) + NUM_BYTES_STRING_LENGTH * vals.length; - const bytes = new Uint8Array(totalNumBytes); - let offset = 0; - for (let i2 = 0; i2 < vals.length; i2++) { - const val = vals[i2]; - const bytesOfLength = new Uint8Array(new Uint32Array([val.length]).buffer); - bytes.set(bytesOfLength, offset); - offset += NUM_BYTES_STRING_LENGTH; - bytes.set(val, offset); - offset += val.length; - } - 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 size2 = 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 + size2 * 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 += size2 * quantizationSizeFactor; - } else if (dtype === "string") { - const size22 = sizeFromShape(spec.shape); - values = []; - for (let i = 0; i < size22; 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 + size2 * 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 real5 = new Float32Array(values.length / 2); - const image32 = new Float32Array(values.length / 2); - for (let i = 0; i < real5.length; i++) { - real5[i] = values[i * 2]; - image32[i] = values[i * 2 + 1]; - } - const realTensor = tensor(real5, shape, "float32"); - const imageTensor = tensor(image32, shape, "float32"); - out[name] = complex(realTensor, imageTensor); - realTensor.dispose(); - imageTensor.dispose(); - } else { - throw new Error(`Unsupported dtype in weight '${name}': ${dtype}`); - } - offset += size2 * 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(str) { - if (useNodeBuffer) { - return Buffer.byteLength(str); - } - return new Blob([str]).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(str) { - if (useNodeBuffer) { - const buf = Buffer.from(str, "base64"); - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - } - const s = atob(str); - const buffer2 = new Uint8Array(s.length); - for (let i = 0; i < s.length; ++i) { - buffer2.set([s.charCodeAt(i)], i); - } - return buffer2.buffer; -} -function concatenateArrayBuffers(buffers) { - if (buffers.length === 1) { - return buffers[0]; - } - let totalByteLength = 0; - buffers.forEach((buffer2) => { - totalByteLength += buffer2.byteLength; - }); - const temp = new Uint8Array(totalByteLength); - let offset = 0; - buffers.forEach((buffer2) => { - temp.set(new Uint8Array(buffer2), offset); - offset += buffer2.byteLength; - }); - return temp.buffer; -} -function basename(path) { - const SEPARATOR = "/"; - path = path.trim(); - while (path.endsWith(SEPARATOR)) { - path = path.slice(0, path.length - 1); - } - const items = path.split(SEPARATOR); - return items[items.length - 1]; -} -function getModelJSONForModelArtifacts(artifacts, manifest) { - const result = { - modelTopology: artifacts.modelTopology, - format: artifacts.format, - generatedBy: artifacts.generatedBy, - convertedBy: artifacts.convertedBy, - weightsManifest: manifest - }; - if (artifacts.signature != null) { - result.signature = artifacts.signature; - } - if (artifacts.userDefinedMetadata != null) { - result.userDefinedMetadata = artifacts.userDefinedMetadata; - } - if (artifacts.modelInitializer != null) { - result.modelInitializer = artifacts.modelInitializer; - } - if (artifacts.trainingConfig != null) { - result.trainingConfig = artifacts.trainingConfig; - } - return result; -} -async function getModelArtifactsForJSON(modelJSON, loadWeights2) { - const modelArtifacts = { - modelTopology: modelJSON.modelTopology, - format: modelJSON.format, - generatedBy: modelJSON.generatedBy, - convertedBy: modelJSON.convertedBy - }; - if (modelJSON.trainingConfig != null) { - modelArtifacts.trainingConfig = modelJSON.trainingConfig; - } - if (modelJSON.weightsManifest != null) { - const [weightSpecs, weightData] = await loadWeights2(modelJSON.weightsManifest); - modelArtifacts.weightSpecs = weightSpecs; - modelArtifacts.weightData = weightData; - } - if (modelJSON.signature != null) { - modelArtifacts.signature = modelJSON.signature; - } - if (modelJSON.userDefinedMetadata != null) { - modelArtifacts.userDefinedMetadata = modelJSON.userDefinedMetadata; - } - if (modelJSON.modelInitializer != null) { - modelArtifacts.modelInitializer = modelJSON.modelInitializer; - } - return modelArtifacts; -} -function getModelArtifactsInfoForJSON(modelArtifacts) { - if (modelArtifacts.modelTopology instanceof ArrayBuffer) { - 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); - }; -} -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); -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); - }); - } -}; -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 removeItems(keys) { - for (const key of Object.values(keys)) { - window.localStorage.removeItem(key); - } -} -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 metadata = { - format: modelArtifacts.format, - generatedBy: modelArtifacts.generatedBy, - convertedBy: modelArtifacts.convertedBy, - signature: modelArtifacts.signature != null ? modelArtifacts.signature : void 0, - userDefinedMetadata: modelArtifacts.userDefinedMetadata != null ? modelArtifacts.userDefinedMetadata : void 0, - modelInitializer: modelArtifacts.modelInitializer != null ? modelArtifacts.modelInitializer : void 0, - trainingConfig: modelArtifacts.trainingConfig != null ? modelArtifacts.trainingConfig : void 0 - }; - this.LS.setItem(this.keys.modelMetadata, JSON.stringify(metadata)); - return { modelArtifactsInfo }; - } catch (err) { - removeItems(this.keys); - throw new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${modelArtifactsInfo.modelTopologyBytes}, weightSpecsBytes=${modelArtifactsInfo.weightSpecsBytes}, weightDataBytes=${modelArtifactsInfo.weightDataBytes}.`); - } - } - } - async load() { - const info = JSON.parse(this.LS.getItem(this.keys.info)); - if (info == null) { - throw new Error(`In local storage, there is no model with name '${this.modelPath}'`); - } - if (info.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; - } - if (metadata.trainingConfig != null) { - out.trainingConfig = metadata.trainingConfig; - } - } - 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 info = JSON.parse(this.LS.getItem(keys.info)); - removeItems(keys); - return info; - } -}; -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); -} -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) { - } -} -var getNodeFetch = { - importFetch: () => require_node_fetch() -}; -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()); -} -function buffer(shape, dtype = "float32", values) { - dtype = dtype || "float32"; - assertNonNegativeIntegerDimensions(shape); - return new TensorBuffer(shape, dtype, values); -} -function cast_(x, dtype) { - const $x = convertToTensor(x, "x", "cast"); - if (!isValidDtype(dtype)) { - throw new Error(`Failed to cast to unknown dtype ${dtype}`); - } - if (dtype === "string" && $x.dtype !== "string" || dtype !== "string" && $x.dtype === "string") { - 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_ }); -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_ }); -function print2(x, verbose = false) { - console.log(x.toString(verbose)); -} -getOrMakeEngine(); -var opHandler2 = { - buffer, - cast, - clone, - print: print2 -}; -setOpHandler(opHandler2); -var io_exports = {}; -__export2(io_exports, { - browserFiles: () => browserFiles, - browserHTTPRequest: () => browserHTTPRequest, - concatenateArrayBuffers: () => concatenateArrayBuffers, - copyModel: () => copyModel, - decodeWeights: () => decodeWeights, - encodeWeights: () => encodeWeights, - fromMemory: () => fromMemory, - getLoadHandlers: () => getLoadHandlers, - getModelArtifactsForJSON: () => getModelArtifactsForJSON, - getModelArtifactsInfoForJSON: () => getModelArtifactsInfoForJSON, - getSaveHandlers: () => getSaveHandlers, - http: () => http, - isHTTPScheme: () => isHTTPScheme, - listModels: () => listModels, - loadWeights: () => loadWeights, - moveModel: () => moveModel, - registerLoadRouter: () => registerLoadRouter, - registerSaveRouter: () => registerSaveRouter, - removeModel: () => removeModel, - weightsLoaderFactory: () => weightsLoaderFactory, - withSaveHandler: () => withSaveHandler -}); -var DEFAULT_FILE_NAME_PREFIX = "model"; -var DEFAULT_JSON_EXTENSION_NAME = ".json"; -var DEFAULT_WEIGHT_DATA_EXTENSION_NAME = ".weights.bin"; -function defer(f) { - return new Promise((resolve) => setTimeout(resolve)).then(f); -} -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.modelJsonFileName = 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 modelJSON = getModelJSONForModelArtifacts(modelArtifacts, weightsManifest); - const modelJsonURL = window.URL.createObjectURL(new Blob([JSON.stringify(modelJSON)], { type: "application/json" })); - const jsonAnchor = this.modelJsonAnchor == null ? document.createElement("a") : this.modelJsonAnchor; - jsonAnchor.download = this.modelJsonFileName; - jsonAnchor.href = modelJsonURL; - await defer(() => jsonAnchor.dispatchEvent(new MouseEvent("click"))); - if (modelArtifacts.weightData != null) { - const weightDataAnchor = this.weightDataAnchor == null ? document.createElement("a") : this.weightDataAnchor; - weightDataAnchor.download = this.weightDataFileName; - weightDataAnchor.href = weightsURL; - await defer(() => weightDataAnchor.dispatchEvent(new MouseEvent("click"))); - } - return { modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts) }; - } - } -}; -var BrowserDownloads = _BrowserDownloads; -BrowserDownloads.URL_SCHEME = "downloads://"; -var BrowserFiles = class { - constructor(files) { - if (files == null || files.length < 1) { - throw new Error(`When calling browserFiles, at least 1 file is required, but received ${files}`); - } - this.jsonFile = files[0]; - this.weightsFiles = files.slice(1); - } - async load() { - return new Promise((resolve, reject) => { - const jsonReader = new FileReader(); - jsonReader.onload = (event) => { - const modelJSON = JSON.parse(event.target.result); - const modelTopology = modelJSON.modelTopology; - if (modelTopology == null) { - reject(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`)); - return; - } - const weightsManifest = modelJSON.weightsManifest; - if (weightsManifest == null) { - reject(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`)); - return; - } - if (this.weightsFiles.length === 0) { - resolve({ modelTopology }); - return; - } - const modelArtifactsPromise = getModelArtifactsForJSON(modelJSON, (weightsManifest2) => this.loadWeights(weightsManifest2)); - resolve(modelArtifactsPromise); - }; - jsonReader.onerror = (error) => reject(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`); - jsonReader.readAsText(this.jsonFile); - }); - } - loadWeights(weightsManifest) { - const weightSpecs = []; - const paths = []; - for (const entry of weightsManifest) { - weightSpecs.push(...entry.weights); - paths.push(...entry.paths); - } - const pathToFile = this.checkManifestAndWeightFiles(weightsManifest); - const promises = paths.map((path) => this.loadWeightsFile(path, pathToFile[path])); - return Promise.all(promises).then((buffers) => [weightSpecs, concatenateArrayBuffers(buffers)]); - } - loadWeightsFile(path, file) { - return new Promise((resolve, reject) => { - const weightFileReader = new FileReader(); - weightFileReader.onload = (event) => { - const weightData = event.target.result; - resolve(weightData); - }; - weightFileReader.onerror = (error) => reject(`Failed to weights data from file of path '${path}'.`); - weightFileReader.readAsArrayBuffer(file); - }); - } - checkManifestAndWeightFiles(manifest) { - const basenames = []; - const fileNames = this.weightsFiles.map((file) => basename(file.name)); - const pathToFile = {}; - for (const group of manifest) { - group.paths.forEach((path) => { - const pathBasename = basename(path); - if (basenames.indexOf(pathBasename) !== -1) { - throw new Error(`Duplicate file basename found in weights manifest: '${pathBasename}'`); - } - basenames.push(pathBasename); - if (fileNames.indexOf(pathBasename) === -1) { - throw new Error(`Weight file with basename '${pathBasename}' is not provided.`); - } else { - pathToFile[path] = this.weightsFiles[fileNames.indexOf(pathBasename)]; - } - }); - } - if (basenames.length !== this.weightsFiles.length) { - throw new Error(`Mismatch in the number of files in weights manifest (${basenames.length}) and the number of weight files provided (${this.weightsFiles.length}).`); - } - return pathToFile; - } -}; -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); -} -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)); -} -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; - }; -} -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 = getModelJSONForModelArtifacts(modelArtifacts, weightsManifest); - init2.body.append("model.json", new Blob([JSON.stringify(modelTopologyAndWeightManifest)], { type: JSON_TYPE }), "model.json"); - if (modelArtifacts.weightData != null) { - init2.body.append("model.weights.bin", new Blob([modelArtifacts.weightData], { type: OCTET_STREAM_MIME_TYPE }), "model.weights.bin"); - } - const response = await this.fetch(this.path, init2); - if (response.ok) { - return { - modelArtifactsInfo: getModelArtifactsInfoForJSON(modelArtifacts), - responses: [response] - }; - } else { - throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${response.status}.`); - } - } - async load() { - const modelConfigRequest = await this.fetch(this.path, this.requestInit); - if (!modelConfigRequest.ok) { - throw new Error(`Request to ${this.path} failed with status code ${modelConfigRequest.status}. Please verify this URL points to the model JSON of the model to load.`); - } - let modelJSON; - try { - modelJSON = await modelConfigRequest.json(); - } catch (e) { - let message = `Failed to parse model JSON of response from ${this.path}.`; - if (this.path.endsWith(".pb")) { - message += " Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository."; - } else { - message += " Please make sure the server is serving valid JSON for this request."; - } - throw new Error(message); - } - const modelTopology = modelJSON.modelTopology; - const weightsManifest = modelJSON.weightsManifest; - if (modelTopology == null && weightsManifest == null) { - throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`); - } - return getModelArtifactsForJSON(modelJSON, (weightsManifest2) => this.loadWeights(weightsManifest2)); - } - 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); -} -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); -} -var math_exports = {}; -__export2(math_exports, { - confusionMatrix: () => confusionMatrix -}); -function matMul_(a, b, transposeA = false, transposeB = false) { - let $a = convertToTensor(a, "a", "matMul"); - let $b = convertToTensor(b, "b", "matMul"); - [$a, $b] = makeTypesMatch($a, $b); - const inputs = { a: $a, b: $b }; - const attrs = { transposeA, transposeB }; - return ENGINE.runKernel(BatchMatMul, inputs, attrs); -} -var matMul = op({ matMul_ }); -function oneHot_(indices, depth, onValue = 1, offValue = 0) { - if (depth < 2) { - throw new Error(`Error in oneHot: depth must be >=2, but it is ${depth}`); - } - const $indices = convertToTensor(indices, "indices", "oneHot", "int32"); - const inputs = { indices: $indices }; - const attrs = { depth, onValue, offValue }; - return ENGINE.runKernel(OneHot, inputs, attrs); -} -var oneHot = op({ oneHot_ }); -function transpose_(x, perm) { - const $x = convertToTensor(x, "x", "transpose"); - if (perm == null) { - perm = $x.shape.map((s, i) => i).reverse(); - } - assert($x.rank === perm.length, () => `Error in transpose: rank of input ${$x.rank} must match length of perm ${perm}.`); - perm.forEach((axis) => { - assert(axis >= 0 && axis < $x.rank, () => `All entries in 'perm' must be between 0 and ${$x.rank - 1} but got ${perm}`); - }); - if ($x.rank <= 1) { - return $x.clone(); - } - const inputs = { x: $x }; - const attrs = { perm }; - return ENGINE.runKernel(Transpose, inputs, attrs); -} -var transpose = op({ transpose_ }); -function confusionMatrix_(labels2, predictions, numClasses) { - const $labels = convertToTensor(labels2, "labels", "confusionMatrix"); - const $predictions = convertToTensor(predictions, "predictions", "confusionMatrix"); - assert(numClasses == null || numClasses > 0 && Number.isInteger(numClasses), () => `If provided, numClasses must be a positive integer, but got ${numClasses}`); - assert($labels.rank === 1, () => `Expected the rank of labels to be 1, but got ${$labels.rank}`); - assert($predictions.rank === 1, () => `Expected the rank of predictions to be 1, but got ${$predictions.rank}`); - assert($labels.shape[0] === $predictions.shape[0], () => `Mismatch in the number of examples: ${$labels.shape[0]} vs. ${$predictions.shape[0]}. Labels and predictions should have the same number of elements.`); - assert(numClasses > 0 && Number.isInteger(numClasses), () => `numClasses is required to be a positive integer, but got ${numClasses}`); - const oneHotLabels = oneHot(cast($labels, "int32"), numClasses); - const oneHotPredictions = oneHot(cast($predictions, "int32"), numClasses); - const oneHotLabelsT = transpose(oneHotLabels); - const product = matMul(oneHotLabelsT, oneHotPredictions); - return cast(product, "int32"); -} -var confusionMatrix = op({ confusionMatrix_ }); -var browser_exports = {}; -__export2(browser_exports, { - fromPixels: () => fromPixels, - fromPixelsAsync: () => fromPixelsAsync, - toPixels: () => toPixels -}); -function tensor3d(values, shape, dtype) { - assertNonNull(values); - if (shape != null && shape.length !== 3) { - 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); -} -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